@flowscape-ui/core-sdk 1.0.5 → 1.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import H from'konva';var Ot=Object.defineProperty;var It=(S,i,e)=>i in S?Ot(S,i,{enumerable:true,configurable:true,writable:true,value:e}):S[i]=e;var a=(S,i,e)=>It(S,typeof i!="symbol"?i+"":i,e);var Ke=class{constructor(){a(this,"_listeners");this._listeners=new Map;}get listeners(){return this._listeners}on(i,e){this._listeners.has(i)||this._listeners.set(i,[]),this._listeners.get(i).push(e);}off(i,e){let t=this._listeners.get(i);t&&this._listeners.set(i,t.filter(o=>o!==e));}once(i,e){let t=((...o)=>{this.off(i,t),e(...o);});this.on(i,t);}emit(i,...e){let t=this._listeners.get(i);t&&[...t].forEach(o=>{o(...e);});}};var Re=class{constructor(i){a(this,"_stage");a(this,"_eventBus");a(this,"_target");a(this,"_scale");a(this,"_minScale");a(this,"_maxScale");a(this,"_zoomStep");a(this,"_panStep");a(this,"_wheelScheduled",false);a(this,"_pendingWheelEvent",null);this._stage=i.stage,this._eventBus=i.eventBus,this._target=i.target??i.stage,this._scale=i.initialScale??1,this._minScale=i.minScale??.1,this._maxScale=i.maxScale??5,this._zoomStep=i.zoomStep??1.05,this._panStep=i.panStep??40,this._initWheelZoom();}_initWheelZoom(){this._stage.on("wheel",i=>{if(i.evt.preventDefault(),this._pendingWheelEvent=i.evt,this._wheelScheduled)return;this._wheelScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._wheelScheduled=false,this._pendingWheelEvent&&(this._handleWheel(this._pendingWheelEvent),this._pendingWheelEvent=null);});});}_handleWheel(i){let e=this._target.scaleX()||1,t=this._stage.getPointerPosition();if(!t)return;let o=this._zoomStep,r=(i.deltaY>0?-1:1)>0?e*o:e/o;r=Math.max(this._minScale,Math.min(this._maxScale,r));let s={x:(t.x-this._target.x())/e,y:(t.y-this._target.y())/e};this._target.scale({x:r,y:r});let l={x:t.x-s.x*r,y:t.y-s.y*r};this._target.position(l),this._stage.batchDraw(),this._scale=r,this._eventBus.emit("camera:zoom",{scale:this._scale,position:l});}get zoomStep(){return this._zoomStep}get panStep(){return this._panStep}setZoom(i){this._scale=Math.max(this._minScale,Math.min(this._maxScale,i)),this._target.scale({x:this._scale,y:this._scale}),this._stage.batchDraw(),this._eventBus.emit("camera:setZoom",{scale:this._scale});}zoomIn(i){i===void 0?this.setZoom(this._scale*this._zoomStep):this.setZoom(this._scale+i);}zoomOut(i){i===void 0?this.setZoom(this._scale/this._zoomStep):this.setZoom(this._scale-i);}reset(){this.setZoom(1),this._target.position({x:0,y:0}),this._stage.batchDraw(),this._eventBus.emit("camera:reset");}setDraggable(i){this._stage.draggable(i);}setZoomStep(i){i&&i>0&&(this._zoomStep=i,this._eventBus.emit("camera:zoomStep",{zoomStep:i}));}setPanStep(i){typeof i=="number"&&isFinite(i)&&(this._panStep=i,this._eventBus.emit("camera:panStep",{panStep:i}));}};var Me=class{constructor(i){a(this,"_node");a(this,"_addons",new Set);this._node=i;}add(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)||(this._addons.add(t),t.attach(this._node));return this._node}remove(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)&&(this._addons.delete(t),t.detach(this._node));return this._node}list(){return Array.from(this._addons)}has(i){return this._addons.has(i)}clear(){this._addons.forEach(i=>{i.detach(this._node);}),this._addons.clear();}};var B=class{constructor(i,e={}){a(this,"konvaNode");a(this,"id");a(this,"addons");this.konvaNode=i,this.id=e.id??`node_${String(Date.now())}_${String(Math.random())}`,this.addons=new Me(this),e.x&&this.konvaNode.x(e.x),e.y&&this.konvaNode.y(e.y),e.width&&this.konvaNode.width(e.width),e.height&&this.konvaNode.height(e.height);}getKonvaNode(){return this.konvaNode}setPosition({x:i,y:e}){return this.konvaNode.position({x:i,y:e}),this}getPosition(){return this.konvaNode.position()}remove(){this.addons.clear(),this.konvaNode.destroy();}};var Fe=class extends B{constructor(i={}){let e=new H.Arc({});e.x(i.x??0),e.y(i.y??0),e.innerRadius(i.innerRadius??0),e.outerRadius(i.outerRadius??0),e.angle(i.angle??0),e.rotation(i.rotation??0),i.clockwise!==void 0&&e.clockwise(i.clockwise),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getInnerRadius(){return this.konvaNode.innerRadius()}getOuterRadius(){return this.konvaNode.outerRadius()}getAngle(){return this.konvaNode.angle()}isClockwise(){return this.konvaNode.clockwise()}setInnerRadius(i){return this.konvaNode.innerRadius(i),this}setOuterRadius(i){return this.konvaNode.outerRadius(i),this}setAngle(i){return this.konvaNode.angle(i),this}setRotationDeg(i){return this.konvaNode.rotation(i),this}setClockwise(i){return this.konvaNode.clockwise(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var We=class extends B{constructor(i={}){let e=new H.Arrow({});e.x(i.x??0),e.y(i.y??0),e.points(i.points??[]),i.tension&&e.tension(i.tension),i.pointerLength&&e.pointerLength(i.pointerLength),i.pointerWidth&&e.pointerWidth(i.pointerWidth),i.pointerAtBeginning&&e.pointerAtBeginning(i.pointerAtBeginning),i.pointerAtEnding&&e.pointerAtEnding(i.pointerAtEnding),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getPoints(){return this.konvaNode.points()}getTension(){return this.konvaNode.tension()}getPointerLength(){return this.konvaNode.pointerLength()}getPointerWidth(){return this.konvaNode.pointerWidth()}getPointerAtBeginning(){return this.konvaNode.pointerAtBeginning()}getPointerAtEnding(){return this.konvaNode.pointerAtEnding()}setPoints(i){return this.konvaNode.points(i),this}setTension(i){return this.konvaNode.tension(i),this}setPointerLength(i){return this.konvaNode.pointerLength(i),this}setPointerWidth(i){return this.konvaNode.pointerWidth(i),this}setPointerAtBeginning(i){return this.konvaNode.pointerAtBeginning(i),this}setPointerAtEnding(i){return this.konvaNode.pointerAtEnding(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var Ve=class extends B{constructor(i={}){let e=new H.Circle({});e.x(i.x??0),e.y(i.y??0),e.radius(i.radius??0),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),e.draggable(true),super(e,i);}getRadius(){return this.konvaNode.radius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setRadius(i){return this.konvaNode.radius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var Xe=class extends B{constructor(i={}){let e=new H.Ellipse({});e.x(i.x??0),e.y(i.y??0),e.radiusX(i.radiusX??0),e.radiusY(i.radiusY??0),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getRadiusX(){return this.konvaNode.radiusX()}getRadiusY(){return this.konvaNode.radiusY()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setRadiusX(i){return this.konvaNode.radiusX(i),this}setRadiusY(i){return this.konvaNode.radiusY(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var Vt={text:"",textColor:"#bdbdbd",font:"12px sans-serif",backgroundColor:"#1f1f1f",borderColor:"transparent",baseSpinnerColor:"#6b6b6b",accentSpinnerColor:"#2b83ff",lineWidth:2,fallbackWidth:150,fallbackHeight:150},ae=class{constructor(i,e){a(this,"_node");a(this,"_options");a(this,"_rafId",null);a(this,"_startTime",0);a(this,"_lastDrawTime",0);a(this,"_canvas",null);a(this,"_ctx",null);a(this,"_logicalWidth",0);a(this,"_logicalHeight",0);a(this,"_pixelRatio",1);a(this,"_maxPixelRatio",3);a(this,"_maxCanvasPixels",15e5);a(this,"_targetFps",30);a(this,"_tick",()=>{let i=this._canvas,e=this._ctx;if(!i||!e)return;let t=globalThis.performance.now(),o=1e3/this._targetFps;if(this._lastDrawTime!==0&&t-this._lastDrawTime<o){this._rafId=globalThis.requestAnimationFrame(this._tick);return}this._lastDrawTime=t;let r=(t-this._startTime)/1e3,s=this._getPixelRatio();s!==this._pixelRatio&&this._logicalWidth>0&&this._logicalHeight>0&&(i.width=Math.max(1,Math.round(this._logicalWidth*s)),i.height=Math.max(1,Math.round(this._logicalHeight*s)),e.setTransform(s,0,0,s,0,0),this._pixelRatio=s),this._draw(r),this._node.getLayer()?.batchDraw(),this._rafId=globalThis.requestAnimationFrame(this._tick);});this._node=i,this._options={...Vt,...e??{}};}setOptions(i){this._options={...this._options,...i},this._draw(0),this._node.getLayer()?.batchDraw();}start(){if(this.stop(),typeof document>"u")return;let i=globalThis.document.createElement("canvas"),e=this._node.size(),t=Math.max(1,Math.round(e.width||this._options.fallbackWidth)),o=Math.max(1,Math.round(e.height||this._options.fallbackHeight)),n=this._getPixelRatio();i.width=Math.max(1,Math.round(t*n)),i.height=Math.max(1,Math.round(o*n));let r=i.getContext("2d");r&&(r.setTransform(n,0,0,n,0,0),this._canvas=i,this._ctx=r,this._logicalWidth=t,this._logicalHeight=o,this._pixelRatio=n,this._node.image(i),this._startTime=globalThis.performance.now(),this._lastDrawTime=0,this._tick());}stop(){this._rafId!==null&&(globalThis.cancelAnimationFrame(this._rafId),this._rafId=null),this._canvas=null,this._ctx=null,this._logicalWidth=0,this._logicalHeight=0,this._pixelRatio=1,this._startTime=0,this._lastDrawTime=0;}_getPixelRatio(){let i=globalThis.devicePixelRatio||1,e=this._node.getAbsoluteScale(),t=Math.max(1e-6,Math.max(e.x,e.y)),o=Math.max(1,i*t);o=Math.min(this._maxPixelRatio,o);let n=this._logicalWidth||Math.max(1,Math.round(this._node.width()||this._options.fallbackWidth)),r=this._logicalHeight||Math.max(1,Math.round(this._node.height()||this._options.fallbackHeight));if(n*r*o*o>this._maxCanvasPixels){let l=Math.sqrt(this._maxCanvasPixels/(n*r));o=Math.max(1,Math.min(o,l));}return o}_draw(i){let e=this._ctx,t=this._canvas;if(!e||!t)return;let{backgroundColor:o,borderColor:n,baseSpinnerColor:r,accentSpinnerColor:s,text:l,textColor:h,font:p,lineWidth:d}=this._options,c=this._logicalWidth||Math.max(1,Math.round(t.width/this._pixelRatio)),u=this._logicalHeight||Math.max(1,Math.round(t.height/this._pixelRatio));e.clearRect(0,0,c,u),e.fillStyle=o,e.fillRect(0,0,c,u),e.strokeStyle=n,e.lineWidth=d,e.strokeRect(1,1,c-2,u-2);let f=c/2,g=u/2,_=Math.max(10,Math.min(c,u)*.12);e.beginPath(),e.strokeStyle=r,e.lineWidth=Math.max(2,_*.25),e.arc(f,g,_,0,Math.PI*2),e.stroke(),e.beginPath(),e.strokeStyle=s,e.lineWidth=Math.max(2,_*.25),e.lineCap="round";let m=i*Math.PI*2;e.arc(f,g,_,m,m+Math.PI*.9),e.stroke(),e.fillStyle=h,e.font=p,e.textAlign="center",e.textBaseline="top",e.fillText(l,f,Math.min(u-14,g+_+8));}};var Ue=class extends B{constructor(e={}){let t=new H.Image({});t.setAttr("flowscapeNodeType","gif"),t.x(e.x??0),t.y(e.y??0),t.width(e.width??150),t.height(e.height??150),t.cornerRadius(e.cornerRadius??0),t.setAttr("placeholder",e.placeholder??{}),e.src&&t.setAttr("src",e.src);super(t,e);a(this,"_canvas",null);a(this,"_placeholder");a(this,"_isLoaded",false);a(this,"_isPlaying",false);a(this,"_giflerLoaded",false);a(this,"_frameIndex",0);this._placeholder=new ae(this.konvaNode,e.placeholder),this._ensureGiflerLibrary(),e.src&&this.setSrc(e.src,e);}async setSrc(e,t={}){if(this._cleanup(),typeof document>"u")throw new Error("GifNode requires a browser environment with document object");await this._ensureGiflerLibrary(),this._placeholder.start();let o=globalThis.document.createElement("canvas");return this._canvas=o,this.konvaNode.setAttr("src",e),new Promise((n,r)=>{if(!globalThis.window.gifler){let s=new Error("Gifler library is not loaded");t.onError&&t.onError(s),r(s);return}try{globalThis.window.gifler(e).frames(o,(s,l)=>{if(o.width=l.width,o.height=l.height,s.drawImage(l.buffer,0,0),this._isLoaded||(this._placeholder.stop(),this.konvaNode.image(o),this._isLoaded=!0,this._isPlaying=t.autoplay??!0,t.onLoad&&t.onLoad(this),n(this)),this._isPlaying){this._frameIndex++,t.onFrame&&t.onFrame(this,this._frameIndex);let h=this.konvaNode.getLayer();h&&h.batchDraw();}});}catch(s){this._placeholder.stop();let l=new Error(`Failed to load GIF: ${e}. ${s.message}`);this._isLoaded=false,t.onError&&t.onError(l),r(l);}})}play(){return this._isPlaying=true,this}pause(){return this._isPlaying=false,this}isPlaying(){return this._isPlaying}isLoaded(){return this._isLoaded}getFrameIndex(){return this._frameIndex}getCanvas(){return this._canvas}getSize(){return this.konvaNode.size()}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}async _ensureGiflerLibrary(){if(this._giflerLoaded||globalThis.window.gifler){this._giflerLoaded=true;return}if(typeof document>"u")throw new Error("GifNode requires a browser environment");let e=globalThis.document.querySelector('script[src*="gifler"]');return e?new Promise((t,o)=>{if(globalThis.window.gifler){this._giflerLoaded=true,t();return}e.addEventListener("load",()=>{this._giflerLoaded=true,t();}),e.addEventListener("error",()=>{o(new Error("Failed to load gifler library"));});}):new Promise((t,o)=>{let n=globalThis.document.createElement("script");n.src="https://unpkg.com/gifler@0.1.0/gifler.min.js",n.onload=()=>{this._giflerLoaded=true,t();},n.onerror=()=>{o(new Error("Failed to load gifler library"));},globalThis.document.head.appendChild(n);})}_cleanup(){this._placeholder.stop(),this._isPlaying=false,this._isLoaded=false,this._frameIndex=0,this._canvas=null;}remove(){this._cleanup(),super.remove();}};var ue=class extends B{constructor(i={}){let e=new H.Group({});e.x(i.x??0),e.y(i.y??0),e.draggable(i.draggable??true),i.listening!==void 0&&e.listening(i.listening),i.clip&&e.clip(i.clip),super(e,i);}addChild(i){let e=i.getKonvaNode?i.getKonvaNode():i;return this.konvaNode.add(e),this.konvaNode.getLayer()?.batchDraw(),this}removeChild(i){return (i.getKonvaNode?i.getKonvaNode():i).remove(),this.konvaNode.getLayer()?.batchDraw(),this}removeAllChildren(){return this.konvaNode.removeChildren(),this.konvaNode.getLayer()?.batchDraw(),this}getChildren(){return this.konvaNode.getChildren()}findByName(i){return this.konvaNode.find(`.${i}`)}setDraggable(i){return this.konvaNode.draggable(i),this}isDraggable(){return this.konvaNode.draggable()}setListening(i){return this.konvaNode.listening(i),this}isListening(){return this.konvaNode.listening()}setClip(i){return this.konvaNode.clip(i),this.konvaNode.getLayer()?.batchDraw(),this}};var Ye=class extends B{constructor(e={}){let t=new H.Image({});t.x(e.x??0),t.y(e.y??0),t.width(e.width??150),t.height(e.height??150),t.image(e.image??null),t.cornerRadius(e.cornerRadius??0),t.setAttr("placeholder",e.placeholder??{});super(t,e);a(this,"_placeholder");this._placeholder=new ae(this.konvaNode,e.placeholder),!e.image&&e.src&&(this.konvaNode.setAttr("src",e.src),this.setSrc(e.src));}getSize(){return this.konvaNode.size()}async setSrc(e,t="anonymous"){this.konvaNode.setAttr("src",e),this._placeholder.start();let o=await this._loadHTMLImage(e,t);return this._placeholder.stop(),this.konvaNode.image(o),this.konvaNode.getLayer()?.batchDraw(),this}setImage(e){return this.konvaNode.image(e),this.konvaNode.getLayer()?.batchDraw(),this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this}getCornerRadius(){return this.konvaNode.cornerRadius()}_loadHTMLImage(e,t="anonymous"){return new Promise((o,n)=>{let r=globalThis.Image??null;if(!r){n(new Error("Image constructor is not available in current environment"));return}let s=new r,l=t;s.crossOrigin=l,s.onload=()=>{o(s);},s.onerror=()=>{n(new Error(`Failed to load image: ${e}`));},s.src=e;})}remove(){this._placeholder.stop(),super.remove();}};var Ze=class extends B{constructor(i={}){let e=new H.RegularPolygon({});e.x(i.x??0),e.y(i.y??0),e.sides(i.sides??3),e.radius(i.radius??60),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getSides(){return this.konvaNode.sides()}getRadius(){return this.konvaNode.radius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setSides(i){return this.konvaNode.sides(i),this}setRadius(i){return this.konvaNode.radius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var je=class extends B{constructor(i={}){let e=new H.Ring({});e.x(i.x??0),e.y(i.y??0),e.innerRadius(i.innerRadius??20),e.outerRadius(i.outerRadius??40),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getInnerRadius(){return this.konvaNode.innerRadius()}getOuterRadius(){return this.konvaNode.outerRadius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setInnerRadius(i){return this.konvaNode.innerRadius(i),this}setOuterRadius(i){return this.konvaNode.outerRadius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var qe=class extends B{constructor(i){let e=new H.Rect({x:i.x??0,y:i.y??0,width:i.width??100,height:i.height??100,fill:i.fill??"lightgray",stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,cornerRadius:i.cornerRadius??0,draggable:true});super(e,i);}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}setCornerRadius(i){return this.konvaNode.cornerRadius(i),this}setSize({width:i,height:e}){return this.konvaNode.size({width:i,height:e}),this}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}getCornerRadius(){return this.konvaNode.cornerRadius()}};var $e=class extends B{constructor(i={}){let e=new H.Star({});e.x(i.x??0),e.y(i.y??0),e.numPoints(i.numPoints??5),e.innerRadius(i.innerRadius??20),e.outerRadius(i.outerRadius??40),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getNumPoints(){return this.konvaNode.numPoints()}getInnerRadius(){return this.konvaNode.innerRadius()}getOuterRadius(){return this.konvaNode.outerRadius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setNumPoints(i){return this.konvaNode.numPoints(i),this}setInnerRadius(i){return this.konvaNode.innerRadius(i),this}setOuterRadius(i){return this.konvaNode.outerRadius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var Je=class extends B{constructor(e={}){let t=new H.Image({});t.setAttr("flowscapeNodeType","svg"),t.x(e.x??0),t.y(e.y??0),t.width(e.width??150),t.height(e.height??150),t.cornerRadius(e.cornerRadius??0),t.setAttr("placeholder",e.placeholder??{});super(t,e);a(this,"_isLoading",false);a(this,"_isLoaded",false);a(this,"_placeholder");this._placeholder=new ae(this.konvaNode,e.placeholder),e.src&&this.setSrc(e.src,e.onLoad,e.onError);}isLoading(){return this._isLoading}isLoaded(){return this._isLoaded}getSize(){return this.konvaNode.size()}async setSrc(e,t,o){this.konvaNode.setAttr("src",e),this._isLoading=true,this._isLoaded=false,this._placeholder.start();try{await new Promise((n,r)=>{H.Image.fromURL(e,s=>{this._placeholder.stop(),this.konvaNode.image(s.image());let l=this.konvaNode.getLayer();l&&l.batchDraw(),this._isLoading=!1,this._isLoaded=!0,t&&t(this),n();},s=>{this._placeholder.stop(),this._isLoading=!1,this._isLoaded=!1;let l=s instanceof Error?s.message:typeof s=="string"?s:"Unknown error",h=new Error(`Failed to load SVG: ${e}. ${l}`);o&&o(h),r(h);});});}catch(n){throw this._placeholder.stop(),this._isLoading=false,this._isLoaded=false,n}return this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}remove(){this._placeholder.stop(),super.remove();}};var ke=class extends B{constructor(e={}){let t=new H.Text({x:e.x??0,y:e.y??0,...e.width?{width:e.width}:{},...e.height?{height:e.height}:{},text:e.text??"Text",fontSize:e.fontSize??16,fontFamily:e.fontFamily??"Inter, Arial, sans-serif",fontStyle:e.fontStyle??"normal",fill:e.fill??"#ffffff",align:e.align??"left",verticalAlign:e.verticalAlign??"top",padding:e.padding??0,lineHeight:e.lineHeight??1});super(t,e);a(this,"_editable");a(this,"_isEditing",false);a(this,"_textarea",null);a(this,"_onTextChangeCallbacks",[]);a(this,"_onEditStartCallbacks",[]);a(this,"_onEditEndCallbacks",[]);a(this,"_pendingGroupEditDblClick",false);a(this,"_groupEditClickResetAttached",false);a(this,"_oldText","");a(this,"_keyHandler",null);a(this,"_clickHandler",null);a(this,"_syncTextareaRafId",null);a(this,"_inputHandler",null);a(this,"_prevWrap",null);this._editable=e.editable??true,this._editable&&this._setupEditHandler(),this._setupTransformHandler();}getText(){return this.konvaNode.text()}setText(e){return this.konvaNode.text(e),this}setFontSize(e){return this.konvaNode.fontSize(e),this}setFontFamily(e){return this.konvaNode.fontFamily(e),this}setFill(e){return this.konvaNode.fill(e),this}setAlign(e){return this.konvaNode.align(e),this}setPadding(e){return this.konvaNode.padding(e),this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this}setLineHeight(e){return this.konvaNode.lineHeight(e),this}setVerticalAlign(e){return this.konvaNode.verticalAlign(e),this}isEditable(){return this._editable}setEditable(e){return this._editable===e?this:(this._editable=e,e?this._setupEditHandler():(this.konvaNode.off("dblclick.textEdit dbltap.textEdit"),this._isEditing&&this.cancelEdit()),this)}isEditing(){return this._isEditing}startEdit(){this._isEditing||this._openTextarea();}finishEdit(){!this._isEditing||!this._textarea||this._saveAndClose(false);}cancelEdit(){!this._isEditing||!this._textarea||this._saveAndClose(true);}onTextChange(e){return this._onTextChangeCallbacks.push(e),this}offTextChange(e){let t=this._onTextChangeCallbacks.indexOf(e);return t!==-1&&this._onTextChangeCallbacks.splice(t,1),this}onEditStart(e){return this._onEditStartCallbacks.push(e),this}offEditStart(e){let t=this._onEditStartCallbacks.indexOf(e);return t!==-1&&this._onEditStartCallbacks.splice(t,1),this}onEditEnd(e){return this._onEditEndCallbacks.push(e),this}offEditEnd(e){let t=this._onEditEndCallbacks.indexOf(e);return t!==-1&&this._onEditEndCallbacks.splice(t,1),this}_setupEditHandler(){this.konvaNode.on("dblclick.textEdit dbltap.textEdit",()=>{let e=this.konvaNode.getParent(),t=e?e.getParent():null;if(!(e instanceof H.Group&&t instanceof H.Group)){this._openTextarea();return}if(!this._groupEditClickResetAttached){let n=this.konvaNode.getStage();n&&(this._groupEditClickResetAttached=true,n.on("mousedown.textEditGroupReset",r=>{r.target!==this.konvaNode&&(this._pendingGroupEditDblClick=false);}));}if(!this._isEditing){if(!this._pendingGroupEditDblClick){this._pendingGroupEditDblClick=true;return}this._pendingGroupEditDblClick=false,this._openTextarea();}});}_setupTransformHandler(){this.konvaNode.on("transform.textResize",()=>{let e=this.konvaNode.scaleX(),t=this.konvaNode.scaleY(),o=Math.max(1,this.konvaNode.width()*e);this.konvaNode.width(o);let n=this.konvaNode.height(),r=Math.max(1,n*t);this.konvaNode.height(r),this.konvaNode.scaleX(1),this.konvaNode.scaleY(1),this._ensureHeightFitsWrappedText();}),this.konvaNode.on("transformend.textResize",()=>{this._ensureHeightFitsWrappedText(),this.konvaNode.getLayer()?.batchDraw();});}_getWrappedLineCount(e){let t=this.konvaNode.text();if(!t)return 1;let o=this.konvaNode.wrap(),n=t.split(`
2
- `);if(o==="none")return Math.max(1,n.length);let r=Math.max(0,e),s=0;for(let l of n){if(l.length===0){s+=1;continue}if(o==="char"){let d="";for(let c of l){let u=d+c;if(this.konvaNode.measureSize(u).width<=r||d.length===0){d=u;continue}s+=1,d=c;}d.length>0&&(s+=1);continue}let h=l.split(/\s+/g),p="";for(let d of h){if(!d)continue;let c=p?p+" "+d:d;if(this.konvaNode.measureSize(c).width<=r||p.length===0){p=c;continue}s+=1,p=d;}p.length>0&&(s+=1);}return Math.max(1,s)}_ensureHeightFitsWrappedText(){let e=this.konvaNode.padding()*2,t=this.konvaNode.width()-e;if(this.konvaNode.wrap()==="none")return;let o=this._getWrappedLineCount(t),n=this.konvaNode.fontSize()*this.konvaNode.lineHeight(),r=Math.ceil(o*n+e);Number.isFinite(r)&&r>this.konvaNode.height()&&this.konvaNode.height(r);}_ensureWidthFitsText(){let e=this.konvaNode.padding()*2,o=this.konvaNode.text().split(`
3
- `),n=0;for(let l of o){let h=this.konvaNode.measureSize(l);h.width>n&&(n=h.width);}let s=Math.ceil(n+e+2);Number.isFinite(s)&&s>this.konvaNode.width()&&this.konvaNode.width(s);}_syncNodeSizeFromTextarea(){if(!this._isEditing||!this._textarea)return;let e=this._textarea,t=this.konvaNode.getAbsoluteScale(),o=t.x||t.y||1,n=this.konvaNode.padding()*2,r=e.scrollWidth,s=e.scrollHeight,l=Math.max(1,r/o+n),h=Math.max(1,s/o+n);Number.isFinite(l)&&l!==this.konvaNode.width()&&this.konvaNode.width(l),Number.isFinite(h)&&h!==this.konvaNode.height()&&this.konvaNode.height(h);}_syncTextareaPosition(){if(!this._isEditing||!this._textarea)return;let e=this.konvaNode.getStage();if(!e)return;this._syncNodeSizeFromTextarea();let t=this.konvaNode.absolutePosition(),o=e.container().getBoundingClientRect(),n=this.konvaNode.getAbsoluteScale();this._textarea.style.top=String(o.top+t.y)+"px",this._textarea.style.left=String(o.left+t.x)+"px",this._textarea.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*n.x)+"px",this._textarea.style.fontSize=String(this.konvaNode.fontSize()*n.x)+"px",this._syncTextareaRafId=globalThis.requestAnimationFrame(()=>{this._syncTextareaPosition();});}_openTextarea(){if(this._isEditing)return;let e=this.konvaNode.getStage();if(!e)return;this._isEditing=true,this._oldText=this.konvaNode.text(),this._prevWrap=this.konvaNode.wrap(),this.konvaNode.wrap("none"),this.konvaNode.opacity(0),this.konvaNode.listening(false),e.batchDraw();let t=this.konvaNode.absolutePosition(),o=e.container().getBoundingClientRect(),n=this.konvaNode.getAbsoluteScale(),r=globalThis.document.createElement("textarea");globalThis.document.body.appendChild(r),this._textarea=r,r.value=this.konvaNode.text(),r.style.position="absolute",r.style.top=String(o.top+t.y)+"px",r.style.left=String(o.left+t.x)+"px",r.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*n.x)+"px",r.style.fontSize=String(this.konvaNode.fontSize()*n.x)+"px",r.style.border="none",r.style.padding="0",r.style.margin="0",r.style.overflow="hidden",r.wrap="off",r.style.whiteSpace="pre",r.style.background="none",r.style.outline="none",r.style.resize="none",r.style.lineHeight=String(this.konvaNode.lineHeight()),r.style.fontFamily=this.konvaNode.fontFamily(),r.style.transformOrigin="left top",r.style.textAlign=this.konvaNode.align();let s=this.konvaNode.fill();r.style.color=typeof s=="string"?s:"#000000";let l=this.konvaNode.fontStyle();r.style.fontStyle=l.includes("italic")?"italic":"normal",r.style.fontWeight=l.includes("bold")?"bold":"normal";let h=this.konvaNode.rotation();h&&(r.style.transform="rotateZ("+String(h)+"deg)"),r.style.height="auto",r.focus(),r.select();let p=()=>{if(!this._textarea)return;this._textarea.style.height="auto",this._textarea.style.height=String(this._textarea.scrollHeight)+"px",this._syncNodeSizeFromTextarea();let d=this.konvaNode.getAbsoluteScale(),c=d.x||d.y||1;this._textarea.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*c)+"px",this.konvaNode.getLayer()?.batchDraw();};this._inputHandler=()=>{globalThis.requestAnimationFrame(()=>{p();});},r.addEventListener("input",this._inputHandler),p(),this._syncTextareaRafId=globalThis.requestAnimationFrame(()=>{this._syncTextareaPosition();});for(let d of this._onEditStartCallbacks)d();this._keyHandler=d=>{if(d.key==="Enter"&&(d.ctrlKey||d.metaKey)){d.preventDefault(),this._saveAndClose(false);return}if(d.key==="Escape"){d.preventDefault(),this._saveAndClose(true);return}globalThis.requestAnimationFrame(()=>{p();});},this._clickHandler=d=>{d.target!==r&&this._saveAndClose(false);},r.addEventListener("keydown",this._keyHandler),globalThis.setTimeout(()=>{this._clickHandler&&(globalThis.addEventListener("click",this._clickHandler),globalThis.addEventListener("touchstart",this._clickHandler));});}_saveAndClose(e){if(!this._textarea)return;let t=e?this._oldText:this._textarea.value;this.konvaNode.text(t),e||this._syncNodeSizeFromTextarea(),this._syncTextareaRafId!==null&&(globalThis.cancelAnimationFrame(this._syncTextareaRafId),this._syncTextareaRafId=null),this._keyHandler&&this._textarea.removeEventListener("keydown",this._keyHandler),this._inputHandler&&this._textarea.removeEventListener("input",this._inputHandler),this._clickHandler&&(globalThis.removeEventListener("click",this._clickHandler),globalThis.removeEventListener("touchstart",this._clickHandler)),this._textarea.remove(),this._textarea=null,this._keyHandler=null,this._clickHandler=null,this._inputHandler=null,this._prevWrap&&(this.konvaNode.wrap(this._prevWrap),this._prevWrap=null),this._ensureWidthFitsText(),this._ensureHeightFitsWrappedText(),this.konvaNode.opacity(1),this.konvaNode.listening(true),this.konvaNode.getStage()?.batchDraw(),this._isEditing=false,this._pendingGroupEditDblClick=false;for(let o of this._onTextChangeCallbacks)o({oldText:this._oldText,newText:t,cancelled:e});for(let o of this._onEditEndCallbacks)o();}};var Qe=class extends B{constructor(e={}){let t=new H.Image({});t.setAttr("flowscapeNodeType","video"),t.x(e.x??0),t.y(e.y??0),t.width(e.width??320),t.height(e.height??240),t.cornerRadius(e.cornerRadius??0),t.setAttr("src",e.src??""),t.setAttr("loop",e.loop??true),t.setAttr("muted",e.muted??false),t.setAttr("autoplay",e.autoplay??false),t.setAttr("currentTime",e.currentTime??0),t.setAttr("volume",e.volume??1),t.setAttr("playbackRate",e.playbackRate??1),t.setAttr("placeholder",e.placeholder??{});super(t,e);a(this,"_videoElement",null);a(this,"_animation",null);a(this,"_placeholder");a(this,"_isPlaying",false);a(this,"_isLoaded",false);this._placeholder=new ae(this.konvaNode,{fallbackWidth:320,fallbackHeight:240,...e.placeholder??{}}),e.src&&this.setSrc(e.src,e);}async setSrc(e,t={}){if(this._cleanup(),typeof document>"u")throw new Error("VideoNode requires a browser environment with document object");let o=this.konvaNode.getAttrs(),n=t.loop??o.loop??false,r=t.muted??o.muted??false,s=t.autoplay??o.autoplay,l=t.currentTime??o.currentTime??0,h=t.volume??o.volume??1,p=t.playbackRate??o.playbackRate??1;this._placeholder.start();let d=globalThis.document.createElement("video");return d.preload="auto",d.src=e,d.loop=n,d.muted=r,d.currentTime=l,d.volume=h,d.playbackRate=p,d.load(),this._videoElement=d,this.konvaNode.setAttr("src",e),this.konvaNode.setAttr("loop",n),this.konvaNode.setAttr("muted",r),this.konvaNode.setAttr("currentTime",l),this.konvaNode.setAttr("autoplay",s),this._ensureAnimation(),new Promise((c,u)=>{let f=false,g=()=>{f||(f=true,this._isLoaded=true,this._placeholder.stop(),this.konvaNode.image(d),this.konvaNode.getLayer()?.batchDraw(),s&&this.play(),c(this));};d.addEventListener("loadedmetadata",()=>{t.onLoadedMetadata&&t.onLoadedMetadata(this,d);}),d.addEventListener("loadeddata",()=>{g();}),d.addEventListener("canplay",()=>{g();}),d.addEventListener("error",()=>{if(f)return;f=true,this._placeholder.stop();let _=new Error(`Failed to load video: ${e}`);this._isLoaded=false,t.onError&&t.onError(_),u(_);}),t.onPlay&&d.addEventListener("play",()=>{t.onPlay&&t.onPlay(this);}),t.onPause&&d.addEventListener("pause",()=>{t.onPause&&t.onPause(this);}),t.onEnded&&d.addEventListener("ended",()=>{t.onEnded&&t.onEnded(this);});})}async play(){if(!this._videoElement)throw new Error("Video element is not initialized");this._ensureAnimation();try{await this._videoElement.play(),this._isPlaying=!0,this._animation?.start();}catch(e){let t=e;t.name==="NotAllowedError"||t.message.includes("user didn't interact")?globalThis.console.warn("Video autoplay blocked by browser policy. User interaction required.",t.message):globalThis.console.error("Failed to play video:",t.message);}return this}pause(){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.pause(),this._isPlaying=false,this._animation?.stop(),this}stop(){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=false,this._animation?.stop(),this}setCurrentTime(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.currentTime=e,this.konvaNode.setAttr("currentTime",e),this}getCurrentTime(){return this._videoElement?this._videoElement.currentTime:0}getDuration(){return this._videoElement?this._videoElement.duration:0}setVolume(e){if(!this._videoElement)throw new Error("Video element is not initialized");let t=Math.max(0,Math.min(1,e));return this._videoElement.volume=t,this.konvaNode.setAttr("volume",t),this}getVolume(){return this._videoElement?this._videoElement.volume:0}setMuted(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.muted=e,this.konvaNode.setAttr("muted",e),this}isMuted(){return this._videoElement?this._videoElement.muted:false}setLoop(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.loop=e,this.konvaNode.setAttr("loop",e),this}isLoop(){return this._videoElement?this._videoElement.loop:false}setPlaybackRate(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.playbackRate=e,this.konvaNode.setAttr("playbackRate",e),this}getPlaybackRate(){return this._videoElement?this._videoElement.playbackRate:1}isPlaying(){return this._isPlaying}isLoaded(){return this._isLoaded}getVideoElement(){return this._videoElement}getSize(){return this.konvaNode.size()}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}_ensureAnimation(){if(this._animation)return;let e=this.konvaNode.getLayer();e&&(this._animation=new H.Animation(()=>{},e));}_cleanup(){this._placeholder.stop(),this._animation&&(this._animation.stop(),this._animation=null),this._videoElement&&(this._videoElement.pause(),this._videoElement.src="",this._videoElement.load(),this._videoElement=null),this._isPlaying=false,this._isLoaded=false;}remove(){this._cleanup(),super.remove();}};var Ae=class{constructor(i,e){a(this,"_layer");a(this,"_world");a(this,"_nodes",new Map);a(this,"_stage");a(this,"_eventBus");a(this,"_batchDrawScheduled",false);a(this,"_listCache",null);a(this,"_listCacheInvalidated",true);this._layer=new H.Layer,this._world=new H.Group,this._layer.add(this._world),this._stage=i,this._stage.add(this._layer),this._eventBus=e;}get layer(){return this._layer}get world(){return this._world}get stage(){return this._stage}get eventBus(){return this._eventBus}addShape(i){let e=new qe(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addText(i){let e=new ke(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addImage(i){let e=new Ye(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addCircle(i){let e=new Ve(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addEllipse(i){let e=new Xe(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addArc(i){let e=new Fe(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addStar(i){let e=new $e(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addArrow(i){let e=new We(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addRing(i){let e=new je(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addRegularPolygon(i){let e=new Ze(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addGroup(i){let e=new ue(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addSvg(i){let e=new Je(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addVideo(i){let e=new Qe(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addGif(i){let e=new Ue(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}remove(i){this._eventBus.emit("node:removed",i),i.remove(),this._nodes.delete(i.id),this._listCacheInvalidated=true,this._scheduleBatchDraw();}findById(i){return this._nodes.get(i)}list(){return (this._listCacheInvalidated||!this._listCache)&&(this._listCache=Array.from(this._nodes.values()),this._listCacheInvalidated=false),this._listCache}_scheduleBatchDraw(){if(this._batchDrawScheduled)return;this._batchDrawScheduled=true;let i=globalThis.requestAnimationFrame;i(()=>{this._batchDrawScheduled=false,this._layer.batchDraw();});}};var ge=class{constructor(i=16){a(this,"_lastTime",0);a(this,"_throttle");this._throttle=i;}shouldExecute(){let i=Date.now();return i-this._lastTime<this._throttle?false:(this._lastTime=i,true)}reset(){this._lastTime=0;}setThrottle(i){this._throttle=i;}getThrottle(){return this._throttle}};var et=class{constructor(i={}){a(this,"_enabled");a(this,"_levels");a(this,"_currentScale",1);a(this,"_appliedNodes",new Map);this._enabled=i.enabled??true,this._levels=i.levels??[{minScale:0,maxScale:.1,simplify:true,disableStroke:true,disableShadow:true,disablePerfectDraw:true},{minScale:.1,maxScale:.3,simplify:true,disableShadow:true,disablePerfectDraw:true},{minScale:.3,maxScale:1/0,simplify:false}];}_getLODLevel(i){return this._enabled?this._levels.find(t=>i>=t.minScale&&i<t.maxScale)??null:null}applyLOD(i,e){if(!this._enabled)return;this._currentScale=e;let t=this._getLODLevel(e);if(!t?.simplify){this._restoreNode(i);return}let o=i.getKonvaNode(),n=this._appliedNodes.get(i.id);n!==t&&(n||(o._originalLOD={stroke:o.stroke?.(),strokeEnabled:o.strokeEnabled(),shadow:o.shadowEnabled(),perfectDraw:o.perfectDrawEnabled?.()}),t.disableStroke&&o.strokeEnabled(false),t.disableShadow&&o.shadowEnabled(false),t.disablePerfectDraw&&o.perfectDrawEnabled&&o.perfectDrawEnabled(false),this._appliedNodes.set(i.id,t));}_restoreNode(i){let e=i.getKonvaNode(),t=e._originalLOD;t&&(e.strokeEnabled(t.strokeEnabled),e.shadowEnabled(t.shadow),t.perfectDraw!==void 0&&e.perfectDrawEnabled&&e.perfectDrawEnabled(t.perfectDraw),this._appliedNodes.delete(i.id),delete e._originalLOD);}applyToAll(i,e){if(this._enabled)for(let t of i)this.applyLOD(t,e);}restoreAll(i){for(let e of i)this._restoreNode(e);this._appliedNodes.clear();}enable(){this._enabled=true;}disable(i){this._enabled=false,this.restoreAll(i);}get enabled(){return this._enabled}get currentScale(){return this._currentScale}getStats(){return {enabled:this._enabled,currentScale:this._currentScale,appliedNodes:this._appliedNodes.size,currentLevel:this._getLODLevel(this._currentScale)}}setLevels(i){this._levels=i;}};var tt=class{constructor(i,e,t,o={}){this._stage=i;this._world=e;this._nodeManager=t;a(this,"_enabled");a(this,"_bufferZone");a(this,"_throttle");a(this,"_viewport",{x:0,y:0,width:0,height:0});a(this,"_visibleNodes",new Set);a(this,"_hiddenNodes",new Set);a(this,"_tempMultiNodeIds",new Set);a(this,"_updateScheduled",false);a(this,"_lod",null);this._enabled=o.enabled??true,this._bufferZone=o.bufferZone??200,this._throttle=new ge(o.throttleMs??16),o.lod&&(this._lod=new et(o.lod)),this._updateViewport(),this._setupListeners(),this._enabled&&this.updateVisibility();}_updateViewport(){let i=this._world.scaleX(),e=this._world.position();this._viewport={x:-e.x/i-this._bufferZone,y:-e.y/i-this._bufferZone,width:this._stage.width()/i+this._bufferZone*2,height:this._stage.height()/i+this._bufferZone*2};}_getNodeBBox(i){let t=i.getKonvaNode().getClientRect({relativeTo:this._world});return {x:t.x,y:t.y,width:t.width,height:t.height}}_isNodeVisible(i){let e=i.getKonvaNode();if(this._tempMultiNodeIds.has(i.id))return true;let t=e.getParent();if(t&&t instanceof H.Group&&t!==this._world)return true;let o=this._getNodeBBox(i);return !(o.x+o.width<this._viewport.x||o.x>this._viewport.x+this._viewport.width||o.y+o.height<this._viewport.y||o.y>this._viewport.y+this._viewport.height)}updateVisibility(){if(!this._enabled||!this._throttle.shouldExecute())return;let i=this._nodeManager.list(),e=new Set,t=0;for(let o of i){let n=this._isNodeVisible(o),r=o.getKonvaNode();n?(e.add(o.id),this._hiddenNodes.has(o.id)&&(r.visible(true),r.listening(true),this._hiddenNodes.delete(o.id),t++)):this._hiddenNodes.has(o.id)||(r.visible(false),r.listening(false),this._hiddenNodes.add(o.id),t++);}if(this._visibleNodes=e,this._lod?.enabled&&t>0){let o=this._world.scaleX();for(let n of i)e.has(n.id)&&this._lod.applyLOD(n,o);}t>0&&this._nodeManager.layer.batchDraw();}_setupListeners(){this._world.on("xChange yChange scaleXChange scaleYChange",()=>{this._scheduleUpdate();}),typeof globalThis.window<"u"&&globalThis.window.addEventListener("resize",()=>{this._updateViewport(),this._scheduleUpdate();}),this._nodeManager.eventBus.on("node:removed",i=>{this._visibleNodes.delete(i.id),this._hiddenNodes.delete(i.id),this._tempMultiNodeIds.delete(i.id);}),this._nodeManager.eventBus.on("selection:multi:created",i=>{this._tempMultiNodeIds.clear();for(let e of i)this._tempMultiNodeIds.add(e.id);}),this._nodeManager.eventBus.on("selection:multi:destroyed",()=>{this._tempMultiNodeIds.clear();});}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=true,globalThis.requestAnimationFrame(()=>{this._updateViewport(),this.updateVisibility(),this._updateScheduled=false;}));}enable(){this._enabled||(this._enabled=true,this.updateVisibility());}disable(){if(this._enabled){this._enabled=false;for(let i of this._hiddenNodes){let e=this._nodeManager.findById(i);if(e){let t=e.getKonvaNode();t.visible(true),t.listening(true);}}this._hiddenNodes.clear(),this._visibleNodes.clear(),this._nodeManager.layer.batchDraw();}}getStats(){let i=this._nodeManager.list().length,e=this._visibleNodes.size,t=this._hiddenNodes.size;return {total:i,visible:e,hidden:t,cullingRate:i>0?t/i*100:0}}setBufferZone(i){this._bufferZone=i,this._updateViewport(),this._scheduleUpdate();}setThrottle(i){this._throttle=new ge(i);}get enabled(){return this._enabled}get viewport(){return {...this._viewport}}forceUpdate(){this._throttle.reset(),this._updateViewport(),this.updateVisibility();}get lod(){return this._lod}destroy(){if(this.disable(),this._visibleNodes.clear(),this._hiddenNodes.clear(),this._lod){let i=this._nodeManager.list();this._lod.restoreAll(i);}}};var ot=class{constructor(i){a(this,"_plugin");a(this,"_addons",new Set);a(this,"_core");this._plugin=i;}_attachAll(i){this._core=i,this._addons.forEach(e=>{e.attach(this._plugin,i);});}_detachAll(i){this._addons.forEach(e=>{e.detach(this._plugin,i);}),this._core=void 0;}add(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)||(this._addons.add(t),this._core&&t.attach(this._plugin,this._core));return this._plugin}remove(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)&&(this._addons.delete(t),this._core&&t.detach(this._plugin,this._core));return this._plugin}list(){return Array.from(this._addons)}has(i){return this._addons.has(i)}clear(){if(this._core){let i=this._core;this._addons.forEach(e=>{e.detach(this._plugin,i);});}this._addons.clear();}};var D=class{constructor(){a(this,"addons");this.addons=new ot(this);}attach(i){this.onAttach(i),this.addons._attachAll(i);}detach(i){this.addons._detachAll(i),this.onDetach(i);}};var Le=class{constructor(i,e=[]){a(this,"_core");a(this,"_items",[]);this._core=i,e.length&&this.addPlugins(e);}addPlugins(i){let e=[];for(let t of i)this._items.includes(t)||(this._items.push(t),t.attach(this._core),e.push(t),this._core.eventBus.emit("plugin:added",t.constructor.name));return e}removePlugins(i){let e=[];for(let t of i){let o=this._items.indexOf(t);o!==-1&&(t.detach(this._core),this._items.splice(o,1),e.push(t),this._core.eventBus.emit("plugin:removed",t.constructor.name));}return e}removeAllPlugins(){let i=[...this._items];for(let e of i)e.detach(this._core);this._items=[];for(let e of i)this._core.eventBus.emit("plugin:removed",e.constructor.name);return i}list(){return [...this._items]}get(i){return this._items.find(e=>e.constructor.name===i)}};var dt=class{constructor(i){a(this,"_stage");a(this,"_eventBus");a(this,"_initialWidth");a(this,"_initialHeight");a(this,"_autoResize");a(this,"_backgroundColor");a(this,"_draggable");a(this,"_minScale");a(this,"_maxScale");a(this,"_gridLayer");a(this,"_resizeObserver",null);a(this,"container");a(this,"nodes");a(this,"camera");a(this,"virtualization");a(this,"plugins");a(this,"_handleResize",()=>{if(!this._autoResize)return;let i=this.container.offsetWidth,e=this.container.offsetHeight;(i!==this._stage.width()||e!==this._stage.height())&&this.setSize({width:i,height:e});});this.container=i.container,this._initialWidth=i.width??800,this._initialHeight=i.height??800,this._autoResize=i.autoResize??true,this._backgroundColor=i.backgroundColor??"#1e1e1e",this._draggable=i.draggable??true,this._minScale=i.minScale??.1,this._maxScale=i.maxScale??500,this._stage=new H.Stage({container:this.container,width:this._autoResize?this.container.offsetWidth:this._initialWidth,height:this._autoResize?this.container.offsetHeight:this._initialHeight,draggable:false}),this._autoResize||(this.container.style.width=`${String(this._initialWidth)}px`,this.container.style.height=`${String(this._initialHeight)}px`),this.container.style.background=this._backgroundColor,this._eventBus=new Ke,this._gridLayer=new H.Layer({listening:false}),this._stage.add(this._gridLayer),this.nodes=new Ae(this._stage,this._eventBus),this.camera=new Re({stage:this._stage,target:this.nodes.world,eventBus:this._eventBus,initialScale:1,draggable:false,minScale:this._minScale,maxScale:this._maxScale}),this.virtualization=new tt(this._stage,this.nodes.world,this.nodes,i.virtualization),this.plugins=new Le(this),i.plugins?.length&&this.plugins.addPlugins(i.plugins),this._autoResize&&this._setupAutoResize();}_setupAutoResize(){typeof ResizeObserver<"u"?(this._resizeObserver=new ResizeObserver(()=>{this._handleResize();}),this._resizeObserver.observe(this.container)):globalThis.addEventListener("resize",this._handleResize);}destroy(){this._resizeObserver?(this._resizeObserver.disconnect(),this._resizeObserver=null):globalThis.removeEventListener("resize",this._handleResize),this._stage.destroy();}get eventBus(){return this._eventBus}get stage(){return this._stage}get gridLayer(){return this._gridLayer}get draggable(){return this._draggable}get autoResize(){return this._autoResize}get backgroundColor(){return this._backgroundColor}get initialWidth(){return this._initialWidth}get initialHeight(){return this._initialHeight}get minScale(){return this._minScale}get maxScale(){return this._maxScale}setSize({width:i,height:e}){this._stage.size({width:i,height:e}),this._stage.fire("resize"),this._eventBus.emit("stage:resized",{width:i,height:e});}setBackgroundColor(i){this.container.style.background=i;}setDraggable(i){this._stage.draggable(i),this._draggable=i;}setAutoResize(i){this._autoResize!==i&&(this._autoResize=i,i?(this._setupAutoResize(),this._handleResize()):this._resizeObserver?(this._resizeObserver.disconnect(),this._resizeObserver=null):globalThis.removeEventListener("resize",this._handleResize));}};var Be=class{constructor(){a(this,"_actions",[]);a(this,"_currentIndex",-1);}push(i){this._currentIndex<this._actions.length-1&&this.pop(this._currentIndex+1),this._actions.push(i),this._currentIndex=this._actions.length-1,this._debug("push",i);}pop(i){if(i<0||i>this._actions.length)return;let e=this._actions.splice(i);this._currentIndex=Math.min(this._currentIndex,this._actions.length-1),this._debug("pop",{fromIndex:i,removedCount:e.length});}select(i){if(i<-1||i>=this._actions.length)return;let e=this._currentIndex;this._currentIndex=i,this._debug("select",{oldIndex:e,newIndex:i});}getCurrentIndex(){return this._currentIndex}get length(){return this._actions.length}getActions(){return [...this._actions]}canUndo(){return this._currentIndex>=0}canRedo(){return this._currentIndex<this._actions.length-1}undo(){if(!this.canUndo())return this._debug("undo","cannot undo - at beginning"),null;let i=this._actions[this._currentIndex];return this._currentIndex--,this._debug("undo",{action:i,newIndex:this._currentIndex}),i??null}redo(){if(!this.canRedo())return this._debug("redo","cannot redo - at end"),null;this._currentIndex++;let i=this._actions[this._currentIndex];return this._debug("redo",{action:i,newIndex:this._currentIndex}),i??null}clear(){this._actions=[],this._currentIndex=-1,this._debug("clear","history cleared");}getAction(i){return i<0||i>=this._actions.length?null:this._actions[i]??null}_debug(i,e){}};var te=class{attach(i,e){this.onAttach(i,e);}detach(i,e){this.onDetach(i,e);}};var De=class extends te{constructor(e={}){super();a(this,"_core",null);a(this,"_rootEl",null);a(this,"_controlsEl",null);a(this,"_playBtn",null);a(this,"_muteBtn",null);a(this,"_speedBtn",null);a(this,"_timeLabel",null);a(this,"_seekInput",null);a(this,"_volInput",null);a(this,"_selectedVideoNode",null);a(this,"_selectedVideoEl",null);a(this,"_hiddenForDrag",false);a(this,"_hiddenForSize",false);a(this,"_hiddenForTransform",false);a(this,"_hiddenForZoom",false);a(this,"_hiddenForWorldScale",false);a(this,"_hiddenForNotReady",false);a(this,"_uiMode","full");a(this,"_zoomUnhideTimeoutId",null);a(this,"_onKonvaDragStart",null);a(this,"_onKonvaDragEnd",null);a(this,"_onKonvaTransformStart",null);a(this,"_onKonvaTransformEnd",null);a(this,"_onLayerTransformStart",null);a(this,"_onLayerTransformEnd",null);a(this,"_onLayerDragStart",null);a(this,"_onLayerDragEnd",null);a(this,"_rafId",null);a(this,"_options");a(this,"_onNodeSelected",null);a(this,"_onNodeDeselected",null);a(this,"_onSelectionCleared",null);a(this,"_onNodeTransformed",null);a(this,"_onStageResized",null);a(this,"_onCameraChanged",null);a(this,"_onWorldChanged",null);a(this,"_onTimeUpdate",null);a(this,"_onLoadedMetadata",null);a(this,"_onCanPlay",null);a(this,"_onPlayPauseSync",null);this._options={zIndex:e.zIndex??20,marginPx:e.marginPx??8,controlsHeightPx:e.controlsHeightPx??42,speeds:e.speeds??[.5,.75,1,1.25,1.5,2],minWidthPx:e.minWidthPx??220,minHeightPx:e.minHeightPx??120,maxWorldScaleToShow:e.maxWorldScaleToShow??8,hideDuringCameraZoomMs:e.hideDuringCameraZoomMs??120,uiBackgroundColor:e.uiBackgroundColor??"rgba(31,31,31,0.92)",uiBorderColor:e.uiBorderColor??"rgba(255,255,255,0.08)",uiTextColor:e.uiTextColor??"#ffffff",uiMutedTextColor:e.uiMutedTextColor??"rgba(255,255,255,0.6)",uiAccentColor:e.uiAccentColor??"#2b83ff",uiTrackColor:e.uiTrackColor??"rgba(255,255,255,0.22)",uiTrackFilledColor:e.uiTrackFilledColor??"#2b83ff"};}onAttach(e,t){if(this._core=t,typeof document>"u")return;this._ensureDom(t),this._onNodeSelected=n=>{this._tryShowForNode(n);},this._onNodeDeselected=n=>{n&&this._selectedVideoNode&&n===this._selectedVideoNode&&this._hide();},this._onSelectionCleared=()=>{this._hide();},this._onNodeTransformed=n=>{this._selectedVideoNode&&n===this._selectedVideoNode&&this._scheduleSync();},t.eventBus.on("node:selected",this._onNodeSelected),t.eventBus.on("node:deselected",this._onNodeDeselected),t.eventBus.on("selection:cleared",this._onSelectionCleared),t.eventBus.on("node:transformed",this._onNodeTransformed),this._onStageResized=()=>{this._hideTemporarilyForZoom(),this._scheduleSync();},t.eventBus.on("stage:resized",this._onStageResized),this._onCameraChanged=()=>{this._hideTemporarilyForZoom(),this._scheduleSync();},t.eventBus.on("camera:zoom",this._onCameraChanged),t.eventBus.on("camera:setZoom",this._onCameraChanged),t.eventBus.on("camera:reset",this._onCameraChanged),t.eventBus.on("camera:pan",this._onCameraChanged);let o=t.nodes.world;this._onWorldChanged=()=>{this._scheduleSync();},o.on("xChange.videoOverlay yChange.videoOverlay scaleXChange.videoOverlay scaleYChange.videoOverlay",this._onWorldChanged),this._bindLayerInteractionEvents(t),this._hide();}onDetach(e,t){this._hide(),this._zoomUnhideTimeoutId!=null&&(globalThis.clearTimeout(this._zoomUnhideTimeoutId),this._zoomUnhideTimeoutId=null),this._onNodeSelected&&t.eventBus.off("node:selected",this._onNodeSelected),this._onNodeDeselected&&t.eventBus.off("node:deselected",this._onNodeDeselected),this._onSelectionCleared&&t.eventBus.off("selection:cleared",this._onSelectionCleared),this._onNodeTransformed&&t.eventBus.off("node:transformed",this._onNodeTransformed),this._onStageResized&&t.eventBus.off("stage:resized",this._onStageResized),this._onCameraChanged&&(t.eventBus.off("camera:zoom",this._onCameraChanged),t.eventBus.off("camera:setZoom",this._onCameraChanged),t.eventBus.off("camera:reset",this._onCameraChanged),t.eventBus.off("camera:pan",this._onCameraChanged)),this._onWorldChanged&&t.nodes.world.off(".videoOverlay"),this._unbindLayerInteractionEvents(t),this._rafId!=null&&(globalThis.cancelAnimationFrame(this._rafId),this._rafId=null),this._rootEl&&this._rootEl.remove(),this._rootEl=null,this._controlsEl=null,this._playBtn=null,this._muteBtn=null,this._speedBtn=null,this._timeLabel=null,this._seekInput=null,this._volInput=null,this._hiddenForDrag=false,this._hiddenForSize=false,this._hiddenForTransform=false,this._hiddenForZoom=false,this._hiddenForWorldScale=false,this._hiddenForNotReady=false,this._onKonvaDragStart=null,this._onKonvaDragEnd=null,this._onKonvaTransformStart=null,this._onKonvaTransformEnd=null,this._onLayerTransformStart=null,this._onLayerTransformEnd=null,this._onLayerDragStart=null,this._onLayerDragEnd=null,this._core=null,this._onNodeSelected=null,this._onNodeDeselected=null,this._onSelectionCleared=null,this._onNodeTransformed=null,this._onStageResized=null,this._onCameraChanged=null,this._onWorldChanged=null;}_ensureDom(e){if(this._rootEl)return;let t=globalThis.document.createElement("div");t.style.position="absolute",t.style.left="0px",t.style.top="0px",t.style.width="0px",t.style.height="0px",t.style.display="none",t.style.zIndex=String(this._options.zIndex),t.style.pointerEvents="none",t.style.boxSizing="border-box",t.style.borderRadius="8px",t.style.overflow="visible";let o=globalThis.document.createElement("div");o.style.position="absolute",o.style.left="0px",o.style.top="0px",o.style.height=String(this._options.controlsHeightPx)+"px",o.style.display="flex",o.style.alignItems="center",o.style.gap="10px",o.style.padding="8px 10px",o.style.borderRadius="10px",o.style.pointerEvents="auto",o.style.boxSizing="border-box",o.style.background=this._options.uiBackgroundColor,o.style.border="1px solid "+this._options.uiBorderColor,o.style.backdropFilter="blur(8px)",o.style.transformOrigin="0 0";let n=f=>{let g=f.target;g instanceof HTMLInputElement&&g.type==="range"||f.stopPropagation();};o.addEventListener("pointerdown",n),o.addEventListener("mousedown",n),o.addEventListener("touchstart",n),o.addEventListener("wheel",f=>{f.ctrlKey&&f.preventDefault();},{passive:false});let r=f=>{let g=globalThis.document.createElement("button");return g.type="button",g.textContent=f,g.style.height="28px",g.style.minWidth="34px",g.style.padding="0 10px",g.style.borderRadius="8px",g.style.border="1px solid "+this._options.uiBorderColor,g.style.background="rgba(0,0,0,0.12)",g.style.color=this._options.uiTextColor,g.style.cursor="pointer",g.style.fontSize="12px",g.style.fontFamily="Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",g.style.lineHeight="28px",g.style.whiteSpace="nowrap",g},s=r("Play");s.style.minWidth="56px";let l=r("Mute");l.style.minWidth="56px";let h=globalThis.document.createElement("span");h.textContent="0:00 / 0:00",h.style.color=this._options.uiTextColor,h.style.opacity="0.9",h.style.fontSize="12px",h.style.fontFamily="Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",h.style.whiteSpace="nowrap";let p=r("1x"),d=globalThis.document.createElement("input");d.type="range",d.min="0",d.max="0",d.step="0.01",d.value="0",d.style.flex="1",d.style.height="6px",d.style.cursor="pointer",d.style.accentColor=this._options.uiAccentColor;let c=globalThis.document.createElement("input");c.type="range",c.min="0",c.max="1",c.step="0.01",c.value="1",c.style.width="90px",c.style.height="6px",c.style.cursor="pointer",c.style.accentColor=this._options.uiAccentColor,o.appendChild(s),o.appendChild(d),o.appendChild(h),o.appendChild(l),o.appendChild(c),o.appendChild(p),t.appendChild(o);let u=e.stage.container();u.style.position=u.style.position||"relative",u.appendChild(t),this._rootEl=t,this._controlsEl=o,this._playBtn=s,this._muteBtn=l,this._speedBtn=p,this._timeLabel=h,this._seekInput=d,this._volInput=c,this._updateRangeFill(d,0),this._updateRangeFill(c,1),s.addEventListener("click",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;!f||!g||(g.paused?f.play():f.pause(),this._syncControls());}),d.addEventListener("input",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g||!Number.isFinite(g.duration)||g.duration<=0)return;let _=Number(d.value);if(!Number.isFinite(_))return;let m=Math.max(0,Math.min(g.duration,_));f.setCurrentTime(m),this._updateRangeFill(d,g.duration>0?m/g.duration:0),this._syncControls();}),l.addEventListener("click",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g)return;let _=!g.muted;f.setMuted(_),!_&&g.volume<=0&&f.setVolume(.8),this._syncControls();}),c.addEventListener("input",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g)return;let _=Math.max(0,Math.min(1,Number(c.value)));f.setVolume(_),_>0&&g.muted&&f.setMuted(false),this._updateRangeFill(c,_),this._syncControls();}),p.addEventListener("click",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g)return;let _=this._options.speeds;if(!Array.isArray(_)||_.length===0)return;let m=g.playbackRate,b=_.findIndex(w=>Math.abs(w-m)<.001);b<0&&(b=0);let v=_[(b+1)%_.length];typeof v=="number"&&Number.isFinite(v)&&v>0&&f.setPlaybackRate(v),this._syncControls();});}_updateRangeFill(e,t){let o=Math.max(0,Math.min(1,t)),n=Math.round(o*100),r=this._options.uiTrackFilledColor,s=this._options.uiTrackColor;e.style.background="linear-gradient(to right, "+r+" 0%, "+r+" "+String(n)+"%, "+s+" "+String(n)+"%, "+s+" 100%)",e.style.borderRadius="999px",e.style.border="none",e.style.outline="none";}_tryShowForNode(e){if(!this._core)return;if(!e||typeof e.getKonvaNode!="function"){this._hide();return}let t=e.getKonvaNode();if((t&&typeof t.getAttr=="function"?t.getAttr("flowscapeNodeType"):void 0)!=="video"){this._hide();return}this._show(e);}_show(e){this._rootEl&&(this._selectedVideoNode=e,this._selectedVideoEl=e.getVideoElement(),this._bindKonvaDragEvents(),this._bindKonvaTransformEvents(),this._bindVideoEvents(),this._hiddenForZoom=false,this._hiddenForTransform=false,this._hiddenForNotReady=!this._isVideoReady(),this._rootEl.style.display=this._hiddenForNotReady?"none":"block",this._hiddenForSize=false,this._scheduleSync(),this._syncControls());}_hide(){this._rootEl&&(this._rootEl.style.display="none"),this._hiddenForDrag=false,this._hiddenForSize=false,this._hiddenForTransform=false,this._hiddenForZoom=false,this._hiddenForWorldScale=false,this._hiddenForNotReady=false,this._unbindKonvaDragEvents(),this._unbindKonvaTransformEvents(),this._unbindVideoEvents(),this._selectedVideoNode=null,this._selectedVideoEl=null;}_bindLayerInteractionEvents(e){let t=e.nodes.layer;typeof t.on!="function"||typeof t.off!="function"||(this._unbindLayerInteractionEvents(e),this._onLayerTransformStart=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onLayerTransformEnd=()=>{if(this._rootEl&&this._selectedVideoNode){if(this._hiddenForTransform=false,this._hiddenForDrag||this._hiddenForZoom||this._hiddenForSize||this._hiddenForNotReady){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}},this._onLayerDragStart=o=>{if(!this._rootEl||!this._selectedVideoNode)return;let n=o.target,r=typeof n?.name=="function"?n.name():void 0;typeof r=="string"&&r.startsWith("rotate-")&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onLayerDragEnd=()=>{if(this._rootEl&&this._selectedVideoNode){if(this._hiddenForTransform=false,this._hiddenForDrag||this._hiddenForZoom||this._hiddenForSize||this._hiddenForNotReady){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}},t.on("transformstart.videoOverlayLayer",this._onLayerTransformStart),t.on("transformend.videoOverlayLayer",this._onLayerTransformEnd),t.on("dragstart.videoOverlayLayer",this._onLayerDragStart),t.on("dragend.videoOverlayLayer",this._onLayerDragEnd));}_unbindLayerInteractionEvents(e){let t=e.nodes.layer;typeof t.off=="function"&&(t.off(".videoOverlayLayer"),this._onLayerTransformStart=null,this._onLayerTransformEnd=null,this._onLayerDragStart=null,this._onLayerDragEnd=null);}_bindKonvaDragEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.on!="function"||typeof e.off!="function"||(this._unbindKonvaDragEvents(),this._onKonvaDragStart=()=>{this._rootEl&&(this._hiddenForDrag=true,this._rootEl.style.display="none");},this._onKonvaDragEnd=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForDrag=false,this._rootEl.style.display="block",this._scheduleSync());},e.on("dragstart.videoOverlay",this._onKonvaDragStart),e.on("dragend.videoOverlay",this._onKonvaDragEnd));}_unbindKonvaDragEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.off=="function"&&(e.off(".videoOverlay"),this._onKonvaDragStart=null,this._onKonvaDragEnd=null);}_bindKonvaTransformEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.on!="function"||typeof e.off!="function"||(this._unbindKonvaTransformEvents(),this._onKonvaTransformStart=()=>{this._rootEl&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onKonvaTransformEnd=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForTransform=false,this._rootEl.style.display="block",this._scheduleSync());},e.on("transformstart.videoOverlayTransform",this._onKonvaTransformStart),e.on("transformend.videoOverlayTransform",this._onKonvaTransformEnd));}_unbindKonvaTransformEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.off=="function"&&(e.off(".videoOverlayTransform"),this._onKonvaTransformStart=null,this._onKonvaTransformEnd=null);}_hideTemporarilyForZoom(){this._rootEl&&this._selectedVideoNode&&(this._hiddenForZoom=true,this._rootEl.style.display="none",this._zoomUnhideTimeoutId!=null&&globalThis.clearTimeout(this._zoomUnhideTimeoutId),this._zoomUnhideTimeoutId=globalThis.setTimeout(()=>{this._zoomUnhideTimeoutId=null,this._rootEl&&this._selectedVideoNode&&(this._hiddenForZoom=false,!(this._hiddenForDrag||this._hiddenForTransform||this._hiddenForSize)&&(this._rootEl.style.display="block",this._scheduleSync()));},this._options.hideDuringCameraZoomMs));}_bindVideoEvents(){let e=this._selectedVideoEl;e&&(this._onTimeUpdate=()=>{this._syncControls();},this._onLoadedMetadata=()=>{this._syncControls(),this._maybeShowWhenReady();},this._onCanPlay=()=>{this._syncControls(),this._maybeShowWhenReady();},this._onPlayPauseSync=()=>{this._syncControls();},e.addEventListener("timeupdate",this._onTimeUpdate),e.addEventListener("loadedmetadata",this._onLoadedMetadata),e.addEventListener("canplay",this._onCanPlay),e.addEventListener("play",this._onPlayPauseSync),e.addEventListener("pause",this._onPlayPauseSync));}_unbindVideoEvents(){let e=this._selectedVideoEl;if(!e){this._onTimeUpdate=null,this._onLoadedMetadata=null,this._onPlayPauseSync=null;return}this._onTimeUpdate&&e.removeEventListener("timeupdate",this._onTimeUpdate),this._onLoadedMetadata&&e.removeEventListener("loadedmetadata",this._onLoadedMetadata),this._onCanPlay&&e.removeEventListener("canplay",this._onCanPlay),this._onPlayPauseSync&&(e.removeEventListener("play",this._onPlayPauseSync),e.removeEventListener("pause",this._onPlayPauseSync)),this._onTimeUpdate=null,this._onLoadedMetadata=null,this._onCanPlay=null,this._onPlayPauseSync=null;}_isVideoReady(){let e=this._selectedVideoEl;return !e||!Number.isFinite(e.duration)||e.duration<=0?false:e.readyState>=1}_maybeShowWhenReady(){if(!this._rootEl||!this._selectedVideoNode)return;if(!this._isVideoReady()){this._hiddenForNotReady=true,this._rootEl.style.display="none";return}if(this._hiddenForNotReady){if(this._hiddenForNotReady=false,this._hiddenForDrag||this._hiddenForTransform||this._hiddenForZoom||this._hiddenForSize){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}}_scheduleSync(){this._rafId==null&&(this._rafId=globalThis.requestAnimationFrame(()=>{this._rafId=null,this._syncPosition();}));}_syncPosition(){if(!this._core||!this._rootEl||!this._selectedVideoNode||this._hiddenForDrag||this._hiddenForTransform||this._hiddenForZoom)return;if(!this._isVideoReady()){this._hiddenForNotReady=true,this._rootEl.style.display="none";return}this._hiddenForNotReady&&(this._hiddenForNotReady=false,this._rootEl.style.display="block");let e=this._core.nodes.world.scaleX(),t=this._options.maxWorldScaleToShow;if(t!=null&&e>=t){this._hiddenForWorldScale=true,this._rootEl.style.display="none";return}this._hiddenForWorldScale&&(this._hiddenForWorldScale=false,this._rootEl.style.display="block");let o=this._selectedVideoNode.getKonvaNode(),n=o.getClientRect?o.getClientRect({skipShadow:true,skipStroke:false}):null;if(!n)return;if(n.width<140||n.height<64){this._hiddenForSize=true,this._rootEl.style.display="none";return}let l=e,h=n.width<260||n.height<110||l<.55?"mini":n.width<340||n.height<135||l<.75?"compact":"full";this._applyUiMode(h),this._hiddenForSize&&(this._hiddenForSize=false,this._rootEl.style.display="block");let p=this._core.stage.container(),d=p.clientWidth,c=p.clientHeight;if(this._rootEl.style.left="0px",this._rootEl.style.top="0px",this._rootEl.style.width=String(d)+"px",this._rootEl.style.height=String(c)+"px",this._controlsEl){let _=n.width/360,m=this._uiMode==="full"?.75:this._uiMode==="compact"?.68:.6,b=Math.max(m,Math.min(1,_));this._controlsEl.style.transform="scale("+String(b)+")";let w=Math.max(64,Math.min(240,n.height))/240,y=Math.max(10,Math.min(28,28*w)),N=Math.max(4,Math.min(10,10*w)),x=this._controlsEl.getBoundingClientRect(),k=x.width,C=x.height,P=n.y+n.height+y+N,R=n.y-y-N-C,L=Math.max(0,c-C-this._options.marginPx),A=P;P>L&&R>=0&&(A=R),A=Math.max(this._options.marginPx,Math.min(L,A));let E=n.x+n.width/2,O=Math.max(0,d-k-this._options.marginPx),j=E-k/2;j=Math.max(this._options.marginPx,Math.min(O,j)),this._controlsEl.style.left=String(j)+"px",this._controlsEl.style.top=String(A)+"px",this._controlsEl.style.right="",this._controlsEl.style.bottom="";}let u=typeof o.cornerRadius=="function"?o.cornerRadius():0,f=0;if(Array.isArray(u)){let _=u[0];f=typeof _=="number"&&Number.isFinite(_)?_:0;}else f=typeof u=="number"&&Number.isFinite(u)?u:0;this._rootEl.style.borderRadius=String(Math.max(0,f))+"px";}_syncControls(){let e=this._selectedVideoEl;if(e){if(this._playBtn&&(this._playBtn.textContent=e.paused?"Play":"Pause"),this._muteBtn){let t=e.muted||e.volume<=0;this._muteBtn.textContent=t?"Muted":"Mute",this._muteBtn.style.color=t?this._options.uiMutedTextColor:this._options.uiTextColor;}if(this._seekInput){let t=Number.isFinite(e.duration)&&e.duration>0?e.duration:0,o=t>0?Math.max(0,Math.min(1,e.currentTime/t)):0;this._seekInput.max=String(t),this._seekInput.value=String(t>0?Math.max(0,Math.min(t,e.currentTime)):0),this._updateRangeFill(this._seekInput,o),this._timeLabel&&(this._timeLabel.textContent=this._formatTime(e.currentTime)+" / "+this._formatTime(t));}if(this._volInput&&(this._volInput.value=String(Math.max(0,Math.min(1,e.volume))),this._updateRangeFill(this._volInput,Math.max(0,Math.min(1,e.volume)))),this._speedBtn){let t=e.playbackRate;this._speedBtn.textContent=String(Math.round(t*100)/100)+"x";}}}_formatTime(e){let t=Number.isFinite(e)&&e>0?e:0,o=Math.floor(t),n=Math.floor(o/60),r=o%60,s=r<10?"0"+String(r):String(r);return String(n)+":"+s}_applyUiMode(e){this._controlsEl&&this._uiMode!==e&&(this._uiMode=e,this._timeLabel&&(this._timeLabel.style.display=e==="full"?"inline":"none"),this._volInput&&(this._volInput.style.display=e==="full"||e==="compact"?"block":"none"),this._speedBtn&&(this._speedBtn.style.display=e==="full"?"inline-flex":"none"),this._controlsEl.style.gap=e==="full"?"10px":"8px",this._controlsEl.style.padding=e==="full"?"8px 10px":"6px 8px",this._seekInput&&(this._seekInput.style.minWidth=e==="mini"?"80px":"120px"));}};var me=class{constructor(){a(this,"_scheduled",false);}schedule(i){this._scheduled||(this._scheduled=true,globalThis.requestAnimationFrame(()=>{this._scheduled=false,i();}));}isScheduled(){return this._scheduled}cancel(){this._scheduled=false;}};var nt=class{constructor(i){a(this,"deps");this.deps=i;}ensure(i){this.deps.ensureTempMulti(i);}destroy(){this.deps.destroyTempMulti();}commitToPermanentGroup(){this.deps.commitTempMultiToGroup();}isActive(){return this.deps.isActive()}forceUpdateOverlays(){this.deps.forceUpdate();}onWorldChanged(){this.deps.onWorldChanged?this.deps.onWorldChanged():this.deps.forceUpdate();}isInsideTempByTarget(i){return this.deps.isInsideTempByTarget?this.deps.isInsideTempByTarget(i):false}};function Se(S){if(S instanceof H.Group){let i=S.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false});return {x:i.x,y:i.y,width:i.width,height:i.height}}if(S instanceof H.Shape&&typeof S.getSelfRect=="function"){let i=S.getSelfRect();return {x:i.x,y:i.y,width:i.width,height:i.height}}return {x:0,y:0,width:S.width(),height:S.height()}}function Te(S,i){let{x:e,y:t,width:o,height:n}=i;switch(S){case "top-left":return {x:e+o,y:t+n};case "top-right":return {x:e,y:t+n};case "bottom-right":return {x:e,y:t};case "bottom-left":return {x:e+o,y:t};case "middle-left":return {x:e+o,y:t+n/2};case "middle-right":return {x:e,y:t+n/2};case "top-center":return {x:e+o/2,y:t+n};case "bottom-center":return {x:e+o/2,y:t};default:return null}}function pe(S,i,e,t=6){if(!S||!i||!e)return;let n=e instanceof H.Group&&typeof e.name=="function"&&e.name().includes("temp-multi-overlay")?e.findOne(".temp-multi-overlay-rect"):null,r=n?n.getClientRect({skipShadow:true,skipStroke:true}):e.getClientRect({skipShadow:true,skipStroke:false}),s=n?n.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}):e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),l=e.getAbsoluteScale(),h=Math.abs(l.x)||1,p=Math.abs(l.y)||1,d=s.width*h,c=s.height*p,u=(()=>{let v=e.getAbsoluteTransform().decompose();return typeof v.rotation=="number"?v.rotation:0})(),f=Math.abs((u%180+180)%180)>.5,g=i.findOne(".top-center"),_=i.findOne(".middle-right"),m=i.findOne(".bottom-center"),b=i.findOne(".middle-left");if(g){let v=f?d:r.width,w=t;g.setAttrs({opacity:0,width:v,height:w,offsetX:v/2,offsetY:0});}if(m){let v=f?d:r.width,w=t;m.setAttrs({opacity:0,width:v,height:w,offsetX:v/2,offsetY:w});}if(b){let v=t,w=f?c:r.height;b.setAttrs({opacity:0,width:v,height:w,offsetX:0,offsetY:w/2});}if(_){let v=t,w=f?c:r.height;_.setAttrs({opacity:0,width:v,height:w,offsetX:v,offsetY:w/2});}}function he(S){return new H.Circle({name:S,radius:4,width:25,height:25,fill:"#ffffff",stroke:"#2b83ff",strokeWidth:1.5,opacity:0,hitStrokeWidth:16,draggable:true,dragOnTop:true,listening:true,cursor:"pointer"})}var it=class{constructor(i){a(this,"core");a(this,"getKonvaNode");a(this,"getTransformer");a(this,"onUpdate");a(this,"setRotateCursor");a(this,"clearRotateCursor");a(this,"onRotateStart");a(this,"onRotateMove");a(this,"onRotateEnd");a(this,"group",null);a(this,"handles",{tl:null,tr:null,br:null,bl:null});a(this,"dragState",null);a(this,"centerAbsStart",null);a(this,"cursorSvgCache",null);this.core=i.core,this.getKonvaNode=i.getNode,this.getTransformer=i.getTransformer,i.onUpdate&&(this.onUpdate=i.onUpdate),i.setRotateCursor&&(this.setRotateCursor=i.setRotateCursor),i.clearRotateCursor&&(this.clearRotateCursor=i.clearRotateCursor),i.onRotateStart&&(this.onRotateStart=i.onRotateStart),i.onRotateMove&&(this.onRotateMove=i.onRotateMove),i.onRotateEnd&&(this.onRotateEnd=i.onRotateEnd);}attach(){if(!this.getKonvaNode())return;let e=this.core.nodes.layer;this.detach();let t=new H.Group({name:"rotate-handles-group",listening:true});e.add(t),this.group=t;let o=he("rotate-tl"),n=he("rotate-tr"),r=he("rotate-br"),s=he("rotate-bl");t.add(o),t.add(n),t.add(r),t.add(s),this.handles={tl:o,tr:n,br:r,bl:s};let l=h=>{h.on("mouseenter.rotate",()=>{let p=this.getKonvaNode();if(!p){this.core.stage.container().style.cursor="pointer";return}let d=this.getNodeCenterAbs(p),c=h.getAbsolutePosition(),u=c.x-d.x,f=c.y-d.y,m=Math.atan2(f,u)*180/Math.PI+45;this.setRotateCursor?this.setRotateCursor(m):this.applyRotatedCursor(m);}),h.on("mouseleave.rotate",()=>{this.clearRotateCursor?this.clearRotateCursor():this.core.stage.container().style.cursor="default";}),h.on("dragstart.rotate",()=>{let p=this.getKonvaNode();if(!p)return;let d=p.getAbsoluteTransform().decompose();this.centerAbsStart=this.getNodeCenterAbs(p);let c=this.core.stage.getPointerPosition()??h.getAbsolutePosition(),u=Math.atan2(c.y-this.centerAbsStart.y,c.x-this.centerAbsStart.x)*180/Math.PI;this.dragState={base:d.rotation||0,start:u};let f=u+90;this.setRotateCursor?this.setRotateCursor(f):this.applyRotatedCursor(f),this.getTransformer()?.moveToTop(),this.placeBelowTransformer(),this.onRotateStart&&this.onRotateStart(),p.fire("rotate:start");}),h.on("dragmove.rotate",p=>{let d=this.getKonvaNode();if(!d||!this.dragState)return;let c=this.centerAbsStart??this.getNodeCenterAbs(d),u=this.core.stage.getPointerPosition()??h.getAbsolutePosition(),f=Math.atan2(u.y-c.y,u.x-c.x)*180/Math.PI,g=this.dragState.base+(f-this.dragState.start),_=f+45;this.setRotateCursor?this.setRotateCursor(_):this.applyRotatedCursor(_);let m=this.getTransformer();if(p.evt.shiftKey&&m){let v=x=>{let k=x%360;return k<0&&(k+=360),k},w=(x,k)=>v(x-k+180)-180,y=Array.isArray(m.rotationSnaps())?m.rotationSnaps().map(x=>v(x)):void 0,N=typeof m.rotationSnapTolerance=="function"?m.rotationSnapTolerance():5;if(y?.length){let x=v(g),k=g,C=1/0;for(let P of y){let R=Math.abs(w(x,P));R<C&&R<=N&&(k=P,C=R);}C!==1/0&&(g=k);}}if(d.rotation(g),this.centerAbsStart){let v=this.getNodeCenterAbs(d),w=this.centerAbsStart.x-v.x,y=this.centerAbsStart.y-v.y,N=d.getParent();if(N){let x=N.getAbsoluteTransform().copy().invert(),k=x.point({x:v.x,y:v.y}),C=x.point({x:v.x+w,y:v.y+y}),P=d.x()+(C.x-k.x),R=d.y()+(C.y-k.y);d.position({x:P,y:R});}}let b=this.getTransformer();b?.forceUpdate(),b&&pe(this.core,b,d),this.updatePosition(),this.placeBelowTransformer(),this.core.nodes.layer.batchDraw(),this.onUpdate&&this.onUpdate(),this.onRotateMove&&this.onRotateMove(),d.fire("rotate:move");}),h.on("dragend.rotate",()=>{this.dragState=null,this.centerAbsStart=null,this.core.stage.draggable(false),this.updatePosition(),this.placeBelowTransformer();let p=this.core.stage.container();p.style.cursor="grab",this.onUpdate&&this.onUpdate();let d=this.getKonvaNode();this.onRotateEnd&&this.onRotateEnd(),d&&d.fire("rotate:end");});};l(o),l(n),l(r),l(s),this.updatePosition(),this.placeBelowTransformer();}applyRotatedCursor(i){let e=this.core.stage.container(),t=(i%360+360)%360;if(this.cursorSvgCache&&this.cursorSvgCache.angle===t){e.style.cursor=this.cursorSvgCache.url;return}let o=`
1
+ import G from'konva';var dn=Object.defineProperty;var cn=(y,i,e)=>i in y?dn(y,i,{enumerable:true,configurable:true,writable:true,value:e}):y[i]=e;var a=(y,i,e)=>cn(y,typeof i!="symbol"?i+"":i,e);var Be=class{constructor(){a(this,"_listeners");this._listeners=new Map;}get listeners(){return this._listeners}on(i,e){this._listeners.has(i)||this._listeners.set(i,[]),this._listeners.get(i).push(e);}off(i,e){let t=this._listeners.get(i);t&&this._listeners.set(i,t.filter(n=>n!==e));}once(i,e){let t=((...n)=>{this.off(i,t),e(...n);});this.on(i,t);}emit(i,...e){let t=this._listeners.get(i);t&&[...t].forEach(n=>{n(...e);});}};var Ae=class{constructor(i){a(this,"_stage");a(this,"_eventBus");a(this,"_target");a(this,"_scale");a(this,"_minScale");a(this,"_maxScale");a(this,"_zoomStep");a(this,"_panStep");a(this,"_wheelScheduled",false);a(this,"_pendingWheelEvent",null);this._stage=i.stage,this._eventBus=i.eventBus,this._target=i.target??i.stage,this._scale=i.initialScale??1,this._minScale=i.minScale??.1,this._maxScale=i.maxScale??5,this._zoomStep=i.zoomStep??1.05,this._panStep=i.panStep??40,this._initWheelZoom();}_initWheelZoom(){this._stage.on("wheel",i=>{if(i.evt.preventDefault(),this._pendingWheelEvent=i.evt,this._wheelScheduled)return;this._wheelScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._wheelScheduled=false,this._pendingWheelEvent&&(this._handleWheel(this._pendingWheelEvent),this._pendingWheelEvent=null);});});}_handleWheel(i){let e=this._target.scaleX()||1,t=this._stage.getPointerPosition();if(!t)return;let n=this._zoomStep,s=(i.deltaY>0?-1:1)>0?e*n:e/n;s=Math.max(this._minScale,Math.min(this._maxScale,s));let r={x:(t.x-this._target.x())/e,y:(t.y-this._target.y())/e};this._target.scale({x:s,y:s});let l={x:t.x-r.x*s,y:t.y-r.y*s};this._target.position(l),this._stage.batchDraw(),this._scale=s,this._eventBus.emit("camera:zoom",{scale:this._scale,position:l});}get zoomStep(){return this._zoomStep}get panStep(){return this._panStep}setZoom(i){this._scale=Math.max(this._minScale,Math.min(this._maxScale,i)),this._target.scale({x:this._scale,y:this._scale}),this._stage.batchDraw(),this._eventBus.emit("camera:setZoom",{scale:this._scale});}zoomIn(i){i===void 0?this.setZoom(this._scale*this._zoomStep):this.setZoom(this._scale+i);}zoomOut(i){i===void 0?this.setZoom(this._scale/this._zoomStep):this.setZoom(this._scale-i);}reset(){this.setZoom(1),this._target.position({x:0,y:0}),this._stage.batchDraw(),this._eventBus.emit("camera:reset");}setDraggable(i){this._stage.draggable(i);}setZoomStep(i){i&&i>0&&(this._zoomStep=i,this._eventBus.emit("camera:zoomStep",{zoomStep:i}));}setPanStep(i){typeof i=="number"&&isFinite(i)&&(this._panStep=i,this._eventBus.emit("camera:panStep",{panStep:i}));}};var Le=class{constructor(i){a(this,"_node");a(this,"_addons",new Set);this._node=i;}add(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)||(this._addons.add(t),t.attach(this._node));return this._node}remove(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)&&(this._addons.delete(t),t.detach(this._node));return this._node}list(){return Array.from(this._addons)}has(i){return this._addons.has(i)}clear(){this._addons.forEach(i=>{i.detach(this._node);}),this._addons.clear();}};var D=class{constructor(i,e={}){a(this,"konvaNode");a(this,"id");a(this,"addons");this.konvaNode=i,this.id=e.id??`node_${String(Date.now())}_${String(Math.random())}`,this.addons=new Le(this),e.x&&this.konvaNode.x(e.x),e.y&&this.konvaNode.y(e.y),e.width&&this.konvaNode.width(e.width),e.height&&this.konvaNode.height(e.height),e.rotation!==void 0&&this.konvaNode.rotation(e.rotation);}getKonvaNode(){return this.konvaNode}setPosition({x:i,y:e}){return this.konvaNode.position({x:i,y:e}),this}getPosition(){return this.konvaNode.position()}remove(){this.addons.clear(),this.konvaNode.destroy();}};var Ze=class extends D{constructor(i={}){let e=new G.Arc({});e.x(i.x??0),e.y(i.y??0),e.innerRadius(i.innerRadius??0),e.outerRadius(i.outerRadius??0),e.angle(i.angle??0),e.rotation(i.rotation??0),i.clockwise!==void 0&&e.clockwise(i.clockwise),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getInnerRadius(){return this.konvaNode.innerRadius()}getOuterRadius(){return this.konvaNode.outerRadius()}getAngle(){return this.konvaNode.angle()}isClockwise(){return this.konvaNode.clockwise()}setInnerRadius(i){return this.konvaNode.innerRadius(i),this}setOuterRadius(i){return this.konvaNode.outerRadius(i),this}setAngle(i){return this.konvaNode.angle(i),this}setRotationDeg(i){return this.konvaNode.rotation(i),this}setClockwise(i){return this.konvaNode.clockwise(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var qe=class extends D{constructor(i={}){let e=new G.Arrow({});e.x(i.x??0),e.y(i.y??0),e.points(i.points??[]),i.tension&&e.tension(i.tension),i.pointerLength&&e.pointerLength(i.pointerLength),i.pointerWidth&&e.pointerWidth(i.pointerWidth),i.pointerAtBeginning&&e.pointerAtBeginning(i.pointerAtBeginning),i.pointerAtEnding&&e.pointerAtEnding(i.pointerAtEnding),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getPoints(){return this.konvaNode.points()}getTension(){return this.konvaNode.tension()}getPointerLength(){return this.konvaNode.pointerLength()}getPointerWidth(){return this.konvaNode.pointerWidth()}getPointerAtBeginning(){return this.konvaNode.pointerAtBeginning()}getPointerAtEnding(){return this.konvaNode.pointerAtEnding()}setPoints(i){return this.konvaNode.points(i),this}setTension(i){return this.konvaNode.tension(i),this}setPointerLength(i){return this.konvaNode.pointerLength(i),this}setPointerWidth(i){return this.konvaNode.pointerWidth(i),this}setPointerAtBeginning(i){return this.konvaNode.pointerAtBeginning(i),this}setPointerAtEnding(i){return this.konvaNode.pointerAtEnding(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var $e=class extends D{constructor(i={}){let e=new G.Circle({});e.x(i.x??0),e.y(i.y??0),e.radius(i.radius??0),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),e.draggable(true),super(e,i);}getRadius(){return this.konvaNode.radius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setRadius(i){return this.konvaNode.radius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var Je=class extends D{constructor(i={}){let e=new G.Ellipse({});e.x(i.x??0),e.y(i.y??0),e.radiusX(i.radiusX??0),e.radiusY(i.radiusY??0),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getRadiusX(){return this.konvaNode.radiusX()}getRadiusY(){return this.konvaNode.radiusY()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setRadiusX(i){return this.konvaNode.radiusX(i),this}setRadiusY(i){return this.konvaNode.radiusY(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var M=class extends D{constructor(e){let t={draggable:e.draggable??true};e.name!==void 0&&(t.name=e.name);let n=new G.Group(t);super(n,e);a(this,"_rect");a(this,"_contentGroup");a(this,"_container");let o=e.width,s=e.height,r=e.background??"#ffffff",l=new G.Group({clip:{x:0,y:0,width:o,height:s}}),h={x:0,y:0,width:o,height:s,fill:r},c=new G.Rect(h),d=new G.Group;l.add(c),l.add(d),this.konvaNode.add(l),this._rect=c,this._contentGroup=d,this._container=l;let u=this.konvaNode;u._frameOrigGetClientRect||(u._frameOrigGetClientRect=u.getClientRect.bind(u),u.getClientRect=p=>c.getClientRect(p));}getRect(){return this._rect}getContentGroup(){return this._contentGroup}resize(e,t){this._rect.width(e),this._rect.height(t),this._container.clip({x:0,y:0,width:e,height:t});}};var gn={text:"",textColor:"#bdbdbd",font:"12px sans-serif",backgroundColor:"#1f1f1f",borderColor:"transparent",baseSpinnerColor:"#6b6b6b",accentSpinnerColor:"#2b83ff",lineWidth:2,fallbackWidth:150,fallbackHeight:150},ce=class{constructor(i,e){a(this,"_node");a(this,"_options");a(this,"_rafId",null);a(this,"_startTime",0);a(this,"_lastDrawTime",0);a(this,"_canvas",null);a(this,"_ctx",null);a(this,"_logicalWidth",0);a(this,"_logicalHeight",0);a(this,"_pixelRatio",1);a(this,"_maxPixelRatio",3);a(this,"_maxCanvasPixels",15e5);a(this,"_targetFps",30);a(this,"_tick",()=>{let i=this._canvas,e=this._ctx;if(!i||!e)return;let t=globalThis.performance.now(),n=1e3/this._targetFps;if(this._lastDrawTime!==0&&t-this._lastDrawTime<n){this._rafId=globalThis.requestAnimationFrame(this._tick);return}this._lastDrawTime=t;let s=(t-this._startTime)/1e3,r=this._getPixelRatio();r!==this._pixelRatio&&this._logicalWidth>0&&this._logicalHeight>0&&(i.width=Math.max(1,Math.round(this._logicalWidth*r)),i.height=Math.max(1,Math.round(this._logicalHeight*r)),e.setTransform(r,0,0,r,0,0),this._pixelRatio=r),this._draw(s),this._node.getLayer()?.batchDraw(),this._rafId=globalThis.requestAnimationFrame(this._tick);});this._node=i,this._options={...gn,...e??{}};}setOptions(i){this._options={...this._options,...i},this._draw(0),this._node.getLayer()?.batchDraw();}start(){if(this.stop(),typeof document>"u")return;let i=globalThis.document.createElement("canvas"),e=this._node.size(),t=Math.max(1,Math.round(e.width||this._options.fallbackWidth)),n=Math.max(1,Math.round(e.height||this._options.fallbackHeight)),o=this._getPixelRatio();i.width=Math.max(1,Math.round(t*o)),i.height=Math.max(1,Math.round(n*o));let s=i.getContext("2d");s&&(s.setTransform(o,0,0,o,0,0),this._canvas=i,this._ctx=s,this._logicalWidth=t,this._logicalHeight=n,this._pixelRatio=o,this._node.image(i),this._startTime=globalThis.performance.now(),this._lastDrawTime=0,this._tick());}stop(){this._rafId!==null&&(globalThis.cancelAnimationFrame(this._rafId),this._rafId=null),this._canvas=null,this._ctx=null,this._logicalWidth=0,this._logicalHeight=0,this._pixelRatio=1,this._startTime=0,this._lastDrawTime=0;}_getPixelRatio(){let i=globalThis.devicePixelRatio||1,e=this._node.getAbsoluteScale(),t=Math.max(1e-6,Math.max(e.x,e.y)),n=Math.max(1,i*t);n=Math.min(this._maxPixelRatio,n);let o=this._logicalWidth||Math.max(1,Math.round(this._node.width()||this._options.fallbackWidth)),s=this._logicalHeight||Math.max(1,Math.round(this._node.height()||this._options.fallbackHeight));if(o*s*n*n>this._maxCanvasPixels){let l=Math.sqrt(this._maxCanvasPixels/(o*s));n=Math.max(1,Math.min(n,l));}return n}_draw(i){let e=this._ctx,t=this._canvas;if(!e||!t)return;let{backgroundColor:n,borderColor:o,baseSpinnerColor:s,accentSpinnerColor:r,text:l,textColor:h,font:c,lineWidth:d}=this._options,u=this._logicalWidth||Math.max(1,Math.round(t.width/this._pixelRatio)),p=this._logicalHeight||Math.max(1,Math.round(t.height/this._pixelRatio));e.clearRect(0,0,u,p),e.fillStyle=n,e.fillRect(0,0,u,p),e.strokeStyle=o,e.lineWidth=d,e.strokeRect(1,1,u-2,p-2);let f=u/2,g=p/2,m=Math.max(10,Math.min(u,p)*.12);e.beginPath(),e.strokeStyle=s,e.lineWidth=Math.max(2,m*.25),e.arc(f,g,m,0,Math.PI*2),e.stroke(),e.beginPath(),e.strokeStyle=r,e.lineWidth=Math.max(2,m*.25),e.lineCap="round";let _=i*Math.PI*2;e.arc(f,g,m,_,_+Math.PI*.9),e.stroke(),e.fillStyle=h,e.font=c,e.textAlign="center",e.textBaseline="top",e.fillText(l,f,Math.min(p-14,g+m+8));}};var et=class extends D{constructor(e={}){let t=new G.Image({});t.setAttr("flowscapeNodeType","gif"),t.x(e.x??0),t.y(e.y??0),t.width(e.width??150),t.height(e.height??150),t.cornerRadius(e.cornerRadius??0),t.setAttr("placeholder",e.placeholder??{}),e.src&&t.setAttr("src",e.src);super(t,e);a(this,"_canvas",null);a(this,"_placeholder");a(this,"_isLoaded",false);a(this,"_isPlaying",false);a(this,"_giflerLoaded",false);a(this,"_frameIndex",0);this._placeholder=new ce(this.konvaNode,e.placeholder),this._ensureGiflerLibrary(),e.src&&this.setSrc(e.src,e);}async setSrc(e,t={}){if(this._cleanup(),typeof document>"u")throw new Error("GifNode requires a browser environment with document object");await this._ensureGiflerLibrary(),this._placeholder.start();let n=globalThis.document.createElement("canvas");return this._canvas=n,this.konvaNode.setAttr("src",e),new Promise((o,s)=>{if(!globalThis.window.gifler){let r=new Error("Gifler library is not loaded");t.onError&&t.onError(r),s(r);return}try{globalThis.window.gifler(e).frames(n,(r,l)=>{if(n.width=l.width,n.height=l.height,r.drawImage(l.buffer,0,0),this._isLoaded||(this._placeholder.stop(),this.konvaNode.image(n),this._isLoaded=!0,this._isPlaying=t.autoplay??!0,t.onLoad&&t.onLoad(this),o(this)),this._isPlaying){this._frameIndex++,t.onFrame&&t.onFrame(this,this._frameIndex);let h=this.konvaNode.getLayer();h&&h.batchDraw();}});}catch(r){this._placeholder.stop();let l=new Error(`Failed to load GIF: ${e}. ${r.message}`);this._isLoaded=false,t.onError&&t.onError(l),s(l);}})}play(){return this._isPlaying=true,this}pause(){return this._isPlaying=false,this}isPlaying(){return this._isPlaying}isLoaded(){return this._isLoaded}getFrameIndex(){return this._frameIndex}getCanvas(){return this._canvas}getSize(){return this.konvaNode.size()}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}async _ensureGiflerLibrary(){if(this._giflerLoaded||globalThis.window.gifler){this._giflerLoaded=true;return}if(typeof document>"u")throw new Error("GifNode requires a browser environment");let e=globalThis.document.querySelector('script[src*="gifler"]');return e?new Promise((t,n)=>{if(globalThis.window.gifler){this._giflerLoaded=true,t();return}e.addEventListener("load",()=>{this._giflerLoaded=true,t();}),e.addEventListener("error",()=>{n(new Error("Failed to load gifler library"));});}):new Promise((t,n)=>{let o=globalThis.document.createElement("script");o.src="https://unpkg.com/gifler@0.1.0/gifler.min.js",o.onload=()=>{this._giflerLoaded=true,t();},o.onerror=()=>{n(new Error("Failed to load gifler library"));},globalThis.document.head.appendChild(o);})}_cleanup(){this._placeholder.stop(),this._isPlaying=false,this._isLoaded=false,this._frameIndex=0,this._canvas=null;}remove(){this._cleanup(),super.remove();}};var ge=class extends D{constructor(i={}){let e=new G.Group({});e.x(i.x??0),e.y(i.y??0),e.draggable(i.draggable??true),i.listening!==void 0&&e.listening(i.listening),i.clip&&e.clip(i.clip),super(e,i);}addChild(i){let e=i.getKonvaNode?i.getKonvaNode():i;return this.konvaNode.add(e),this.konvaNode.getLayer()?.batchDraw(),this}removeChild(i){return (i.getKonvaNode?i.getKonvaNode():i).remove(),this.konvaNode.getLayer()?.batchDraw(),this}removeAllChildren(){return this.konvaNode.removeChildren(),this.konvaNode.getLayer()?.batchDraw(),this}getChildren(){return this.konvaNode.getChildren()}findByName(i){return this.konvaNode.find(`.${i}`)}setDraggable(i){return this.konvaNode.draggable(i),this}isDraggable(){return this.konvaNode.draggable()}setListening(i){return this.konvaNode.listening(i),this}isListening(){return this.konvaNode.listening()}setClip(i){return this.konvaNode.clip(i),this.konvaNode.getLayer()?.batchDraw(),this}};var tt=class extends D{constructor(e={}){let t=new G.Image({});t.x(e.x??0),t.y(e.y??0),t.width(e.width??150),t.height(e.height??150),t.image(e.image??null),t.cornerRadius(e.cornerRadius??0),t.setAttr("placeholder",e.placeholder??{});super(t,e);a(this,"_placeholder");this._placeholder=new ce(this.konvaNode,e.placeholder),!e.image&&e.src&&(this.konvaNode.setAttr("src",e.src),this.setSrc(e.src));}getSize(){return this.konvaNode.size()}async setSrc(e,t="anonymous"){this.konvaNode.setAttr("src",e),this._placeholder.start();let n=await this._loadHTMLImage(e,t);return this._placeholder.stop(),this.konvaNode.image(n),this.konvaNode.getLayer()?.batchDraw(),this}setImage(e){return this.konvaNode.image(e),this.konvaNode.getLayer()?.batchDraw(),this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this}getCornerRadius(){return this.konvaNode.cornerRadius()}_loadHTMLImage(e,t="anonymous"){return new Promise((n,o)=>{let s=globalThis.Image??null;if(!s){o(new Error("Image constructor is not available in current environment"));return}let r=new s,l=t;r.crossOrigin=l,r.onload=()=>{n(r);},r.onerror=()=>{o(new Error(`Failed to load image: ${e}`));},r.src=e;})}remove(){this._placeholder.stop(),super.remove();}};var nt=class extends D{constructor(i={}){let e=new G.RegularPolygon({});e.x(i.x??0),e.y(i.y??0),e.sides(i.sides??3),e.radius(i.radius??60),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getSides(){return this.konvaNode.sides()}getRadius(){return this.konvaNode.radius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setSides(i){return this.konvaNode.sides(i),this}setRadius(i){return this.konvaNode.radius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var ot=class extends D{constructor(i={}){let e=new G.Ring({});e.x(i.x??0),e.y(i.y??0),e.innerRadius(i.innerRadius??20),e.outerRadius(i.outerRadius??40),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getInnerRadius(){return this.konvaNode.innerRadius()}getOuterRadius(){return this.konvaNode.outerRadius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setInnerRadius(i){return this.konvaNode.innerRadius(i),this}setOuterRadius(i){return this.konvaNode.outerRadius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var it=class extends D{constructor(i){let e=new G.Rect({x:i.x??0,y:i.y??0,width:i.width??100,height:i.height??100,fill:i.fill??"lightgray",stroke:i.stroke??"black",strokeWidth:i.strokeWidth??1,cornerRadius:i.cornerRadius??0,draggable:true});super(e,i);}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}setCornerRadius(i){return this.konvaNode.cornerRadius(i),this}setSize({width:i,height:e}){return this.konvaNode.size({width:i,height:e}),this}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}getCornerRadius(){return this.konvaNode.cornerRadius()}};var st=class extends D{constructor(i={}){let e=new G.Star({});e.x(i.x??0),e.y(i.y??0),e.numPoints(i.numPoints??5),e.innerRadius(i.innerRadius??20),e.outerRadius(i.outerRadius??40),e.fill(i.fill??"black"),e.stroke(i.stroke??"black"),e.strokeWidth(i.strokeWidth??0),super(e,i);}getNumPoints(){return this.konvaNode.numPoints()}getInnerRadius(){return this.konvaNode.innerRadius()}getOuterRadius(){return this.konvaNode.outerRadius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setNumPoints(i){return this.konvaNode.numPoints(i),this}setInnerRadius(i){return this.konvaNode.innerRadius(i),this}setOuterRadius(i){return this.konvaNode.outerRadius(i),this}setFill(i){return this.konvaNode.fill(i),this}setStroke(i){return this.konvaNode.stroke(i),this}setStrokeWidth(i){return this.konvaNode.strokeWidth(i),this}};var rt=class extends D{constructor(e={}){let t=new G.Image({});t.setAttr("flowscapeNodeType","svg"),t.x(e.x??0),t.y(e.y??0),t.width(e.width??150),t.height(e.height??150),t.cornerRadius(e.cornerRadius??0),t.setAttr("placeholder",e.placeholder??{});super(t,e);a(this,"_isLoading",false);a(this,"_isLoaded",false);a(this,"_placeholder");this._placeholder=new ce(this.konvaNode,e.placeholder),e.src&&this.setSrc(e.src,e.onLoad,e.onError);}isLoading(){return this._isLoading}isLoaded(){return this._isLoaded}getSize(){return this.konvaNode.size()}async setSrc(e,t,n){this.konvaNode.setAttr("src",e),this._isLoading=true,this._isLoaded=false,this._placeholder.start();try{await new Promise((o,s)=>{G.Image.fromURL(e,r=>{this._placeholder.stop(),this.konvaNode.image(r.image());let l=this.konvaNode.getLayer();l&&l.batchDraw(),this._isLoading=!1,this._isLoaded=!0,t&&t(this),o();},r=>{this._placeholder.stop(),this._isLoading=!1,this._isLoaded=!1;let l=r instanceof Error?r.message:typeof r=="string"?r:"Unknown error",h=new Error(`Failed to load SVG: ${e}. ${l}`);n&&n(h),s(h);});});}catch(o){throw this._placeholder.stop(),this._isLoading=false,this._isLoaded=false,o}return this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}remove(){this._placeholder.stop(),super.remove();}};var Te=class extends D{constructor(e={}){let t=new G.Text({x:e.x??0,y:e.y??0,...e.width?{width:e.width}:{},...e.height?{height:e.height}:{},text:e.text??"Text",fontSize:e.fontSize??16,fontFamily:e.fontFamily??"Inter, Arial, sans-serif",fontStyle:e.fontStyle??"normal",fill:e.fill??"#ffffff",align:e.align??"left",verticalAlign:e.verticalAlign??"top",padding:e.padding??0,lineHeight:e.lineHeight??1});super(t,e);a(this,"_editable");a(this,"_isEditing",false);a(this,"_textarea",null);a(this,"_onTextChangeCallbacks",[]);a(this,"_onEditStartCallbacks",[]);a(this,"_onEditEndCallbacks",[]);a(this,"_pendingGroupEditDblClick",false);a(this,"_groupEditClickResetAttached",false);a(this,"_oldText","");a(this,"_keyHandler",null);a(this,"_clickHandler",null);a(this,"_syncTextareaRafId",null);a(this,"_inputHandler",null);a(this,"_prevWrap",null);this._editable=e.editable??true,this._editable&&this._setupEditHandler(),this._setupTransformHandler();}getText(){return this.konvaNode.text()}setText(e){return this.konvaNode.text(e),this}setFontSize(e){return this.konvaNode.fontSize(e),this}setFontFamily(e){return this.konvaNode.fontFamily(e),this}setFill(e){return this.konvaNode.fill(e),this}setAlign(e){return this.konvaNode.align(e),this}setPadding(e){return this.konvaNode.padding(e),this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this}setLineHeight(e){return this.konvaNode.lineHeight(e),this}setVerticalAlign(e){return this.konvaNode.verticalAlign(e),this}isEditable(){return this._editable}setEditable(e){return this._editable===e?this:(this._editable=e,e?this._setupEditHandler():(this.konvaNode.off("dblclick.textEdit dbltap.textEdit"),this._isEditing&&this.cancelEdit()),this)}isEditing(){return this._isEditing}startEdit(){this._isEditing||this._openTextarea();}finishEdit(){!this._isEditing||!this._textarea||this._saveAndClose(false);}cancelEdit(){!this._isEditing||!this._textarea||this._saveAndClose(true);}onTextChange(e){return this._onTextChangeCallbacks.push(e),this}offTextChange(e){let t=this._onTextChangeCallbacks.indexOf(e);return t!==-1&&this._onTextChangeCallbacks.splice(t,1),this}onEditStart(e){return this._onEditStartCallbacks.push(e),this}offEditStart(e){let t=this._onEditStartCallbacks.indexOf(e);return t!==-1&&this._onEditStartCallbacks.splice(t,1),this}onEditEnd(e){return this._onEditEndCallbacks.push(e),this}offEditEnd(e){let t=this._onEditEndCallbacks.indexOf(e);return t!==-1&&this._onEditEndCallbacks.splice(t,1),this}_setupEditHandler(){this.konvaNode.on("dblclick.textEdit dbltap.textEdit",()=>{let e=this.konvaNode.getParent(),t=e?e.getParent():null;if(!(e instanceof G.Group&&t instanceof G.Group)){this._openTextarea();return}if(!this._groupEditClickResetAttached){let o=this.konvaNode.getStage();o&&(this._groupEditClickResetAttached=true,o.on("mousedown.textEditGroupReset",s=>{s.target!==this.konvaNode&&(this._pendingGroupEditDblClick=false);}));}if(!this._isEditing){if(!this._pendingGroupEditDblClick){this._pendingGroupEditDblClick=true;return}this._pendingGroupEditDblClick=false,this._openTextarea();}});}_setupTransformHandler(){this.konvaNode.on("transform.textResize",()=>{let e=this.konvaNode.scaleX(),t=this.konvaNode.scaleY(),n=Math.max(1,this.konvaNode.width()*e);this.konvaNode.width(n);let o=this.konvaNode.height(),s=Math.max(1,o*t);this.konvaNode.height(s),this.konvaNode.scaleX(1),this.konvaNode.scaleY(1),this._ensureHeightFitsWrappedText();}),this.konvaNode.on("transformend.textResize",()=>{this._ensureHeightFitsWrappedText(),this.konvaNode.getLayer()?.batchDraw();});}_getWrappedLineCount(e){let t=this.konvaNode.text();if(!t)return 1;let n=this.konvaNode.wrap(),o=t.split(`
2
+ `);if(n==="none")return Math.max(1,o.length);let s=Math.max(0,e),r=0;for(let l of o){if(l.length===0){r+=1;continue}if(n==="char"){let d="";for(let u of l){let p=d+u;if(this.konvaNode.measureSize(p).width<=s||d.length===0){d=p;continue}r+=1,d=u;}d.length>0&&(r+=1);continue}let h=l.split(/\s+/g),c="";for(let d of h){if(!d)continue;let u=c?c+" "+d:d;if(this.konvaNode.measureSize(u).width<=s||c.length===0){c=u;continue}r+=1,c=d;}c.length>0&&(r+=1);}return Math.max(1,r)}_ensureHeightFitsWrappedText(){let e=this.konvaNode.padding()*2,t=this.konvaNode.width()-e;if(this.konvaNode.wrap()==="none")return;let n=this._getWrappedLineCount(t),o=this.konvaNode.fontSize()*this.konvaNode.lineHeight(),s=Math.ceil(n*o+e);Number.isFinite(s)&&s>this.konvaNode.height()&&this.konvaNode.height(s);}_ensureWidthFitsText(){let e=this.konvaNode.padding()*2,n=this.konvaNode.text().split(`
3
+ `),o=0;for(let l of n){let h=this.konvaNode.measureSize(l);h.width>o&&(o=h.width);}let r=Math.ceil(o+e+2);Number.isFinite(r)&&r>this.konvaNode.width()&&this.konvaNode.width(r);}_syncNodeSizeFromTextarea(){if(!this._isEditing||!this._textarea)return;let e=this._textarea,t=this.konvaNode.getAbsoluteScale(),n=t.x||t.y||1,o=this.konvaNode.padding()*2,s=e.scrollWidth,r=e.scrollHeight,l=Math.max(1,s/n+o),h=Math.max(1,r/n+o);Number.isFinite(l)&&l!==this.konvaNode.width()&&this.konvaNode.width(l),Number.isFinite(h)&&h!==this.konvaNode.height()&&this.konvaNode.height(h);}_syncTextareaPosition(){if(!this._isEditing||!this._textarea)return;let e=this.konvaNode.getStage();if(!e)return;this._syncNodeSizeFromTextarea();let t=this.konvaNode.absolutePosition(),n=e.container().getBoundingClientRect(),o=this.konvaNode.getAbsoluteScale();this._textarea.style.top=String(n.top+t.y)+"px",this._textarea.style.left=String(n.left+t.x)+"px",this._textarea.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*o.x)+"px",this._textarea.style.fontSize=String(this.konvaNode.fontSize()*o.x)+"px",this._syncTextareaRafId=globalThis.requestAnimationFrame(()=>{this._syncTextareaPosition();});}_openTextarea(){if(this._isEditing)return;let e=this.konvaNode.getStage();if(!e)return;this._isEditing=true,this._oldText=this.konvaNode.text(),this._prevWrap=this.konvaNode.wrap(),this.konvaNode.wrap("none"),this.konvaNode.opacity(0),this.konvaNode.listening(false),e.batchDraw();let t=this.konvaNode.absolutePosition(),n=e.container().getBoundingClientRect(),o=this.konvaNode.getAbsoluteScale(),s=globalThis.document.createElement("textarea");globalThis.document.body.appendChild(s),this._textarea=s,s.value=this.konvaNode.text(),s.style.position="absolute",s.style.top=String(n.top+t.y)+"px",s.style.left=String(n.left+t.x)+"px",s.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*o.x)+"px",s.style.fontSize=String(this.konvaNode.fontSize()*o.x)+"px",s.style.border="none",s.style.padding="0",s.style.margin="0",s.style.overflow="hidden",s.wrap="off",s.style.whiteSpace="pre",s.style.background="none",s.style.outline="none",s.style.resize="none",s.style.lineHeight=String(this.konvaNode.lineHeight()),s.style.fontFamily=this.konvaNode.fontFamily(),s.style.transformOrigin="left top",s.style.textAlign=this.konvaNode.align();let r=this.konvaNode.fill();s.style.color=typeof r=="string"?r:"#000000";let l=this.konvaNode.fontStyle();s.style.fontStyle=l.includes("italic")?"italic":"normal",s.style.fontWeight=l.includes("bold")?"bold":"normal";let h=this.konvaNode.rotation();h&&(s.style.transform="rotateZ("+String(h)+"deg)"),s.style.height="auto",s.focus(),s.select();let c=()=>{if(!this._textarea)return;this._textarea.style.height="auto",this._textarea.style.height=String(this._textarea.scrollHeight)+"px",this._syncNodeSizeFromTextarea();let d=this.konvaNode.getAbsoluteScale(),u=d.x||d.y||1;this._textarea.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*u)+"px",this.konvaNode.getLayer()?.batchDraw();};this._inputHandler=()=>{globalThis.requestAnimationFrame(()=>{c();});},s.addEventListener("input",this._inputHandler),c(),this._syncTextareaRafId=globalThis.requestAnimationFrame(()=>{this._syncTextareaPosition();});for(let d of this._onEditStartCallbacks)d();this._keyHandler=d=>{if(d.key==="Enter"&&(d.ctrlKey||d.metaKey)){d.preventDefault(),this._saveAndClose(false);return}if(d.key==="Escape"){d.preventDefault(),this._saveAndClose(true);return}globalThis.requestAnimationFrame(()=>{c();});},this._clickHandler=d=>{d.target!==s&&this._saveAndClose(false);},s.addEventListener("keydown",this._keyHandler),globalThis.setTimeout(()=>{this._clickHandler&&(globalThis.addEventListener("click",this._clickHandler),globalThis.addEventListener("touchstart",this._clickHandler));});}_saveAndClose(e){if(!this._textarea)return;let t=e?this._oldText:this._textarea.value;this.konvaNode.text(t),e||this._syncNodeSizeFromTextarea(),this._syncTextareaRafId!==null&&(globalThis.cancelAnimationFrame(this._syncTextareaRafId),this._syncTextareaRafId=null),this._keyHandler&&this._textarea.removeEventListener("keydown",this._keyHandler),this._inputHandler&&this._textarea.removeEventListener("input",this._inputHandler),this._clickHandler&&(globalThis.removeEventListener("click",this._clickHandler),globalThis.removeEventListener("touchstart",this._clickHandler)),this._textarea.remove(),this._textarea=null,this._keyHandler=null,this._clickHandler=null,this._inputHandler=null,this._prevWrap&&(this.konvaNode.wrap(this._prevWrap),this._prevWrap=null),this._ensureWidthFitsText(),this._ensureHeightFitsWrappedText(),this.konvaNode.opacity(1),this.konvaNode.listening(true),this.konvaNode.getStage()?.batchDraw(),this._isEditing=false,this._pendingGroupEditDblClick=false;for(let n of this._onTextChangeCallbacks)n({oldText:this._oldText,newText:t,cancelled:e});for(let n of this._onEditEndCallbacks)n();}};var at=class extends D{constructor(e={}){let t=new G.Image({});t.setAttr("flowscapeNodeType","video"),t.x(e.x??0),t.y(e.y??0),t.width(e.width??320),t.height(e.height??240),t.cornerRadius(e.cornerRadius??0),t.setAttr("src",e.src??""),t.setAttr("loop",e.loop??true),t.setAttr("muted",e.muted??false),t.setAttr("autoplay",e.autoplay??false),t.setAttr("currentTime",e.currentTime??0),t.setAttr("volume",e.volume??1),t.setAttr("playbackRate",e.playbackRate??1),t.setAttr("placeholder",e.placeholder??{});super(t,e);a(this,"_videoElement",null);a(this,"_animation",null);a(this,"_placeholder");a(this,"_isPlaying",false);a(this,"_isLoaded",false);this._placeholder=new ce(this.konvaNode,{fallbackWidth:320,fallbackHeight:240,...e.placeholder??{}}),e.src&&this.setSrc(e.src,e);}async setSrc(e,t={}){if(this._cleanup(),typeof document>"u")throw new Error("VideoNode requires a browser environment with document object");let n=this.konvaNode.getAttrs(),o=t.loop??n.loop??false,s=t.muted??n.muted??false,r=t.autoplay??n.autoplay,l=t.currentTime??n.currentTime??0,h=t.volume??n.volume??1,c=t.playbackRate??n.playbackRate??1;this._placeholder.start();let d=globalThis.document.createElement("video");return d.preload="auto",d.src=e,d.loop=o,d.muted=s,d.currentTime=l,d.volume=h,d.playbackRate=c,d.load(),this._videoElement=d,this.konvaNode.setAttr("src",e),this.konvaNode.setAttr("loop",o),this.konvaNode.setAttr("muted",s),this.konvaNode.setAttr("currentTime",l),this.konvaNode.setAttr("autoplay",r),this._ensureAnimation(),new Promise((u,p)=>{let f=false,g=()=>{f||(f=true,this._isLoaded=true,this._placeholder.stop(),this.konvaNode.image(d),this.konvaNode.getLayer()?.batchDraw(),r&&this.play(),u(this));};d.addEventListener("loadedmetadata",()=>{t.onLoadedMetadata&&t.onLoadedMetadata(this,d);}),d.addEventListener("loadeddata",()=>{g();}),d.addEventListener("canplay",()=>{g();}),d.addEventListener("error",()=>{if(f)return;f=true,this._placeholder.stop();let m=new Error(`Failed to load video: ${e}`);this._isLoaded=false,t.onError&&t.onError(m),p(m);}),t.onPlay&&d.addEventListener("play",()=>{t.onPlay&&t.onPlay(this);}),t.onPause&&d.addEventListener("pause",()=>{t.onPause&&t.onPause(this);}),t.onEnded&&d.addEventListener("ended",()=>{t.onEnded&&t.onEnded(this);});})}async play(){if(!this._videoElement)throw new Error("Video element is not initialized");this._ensureAnimation();try{await this._videoElement.play(),this._isPlaying=!0,this._animation?.start();}catch(e){let t=e;t.name==="NotAllowedError"||t.message.includes("user didn't interact")?globalThis.console.warn("Video autoplay blocked by browser policy. User interaction required.",t.message):globalThis.console.error("Failed to play video:",t.message);}return this}pause(){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.pause(),this._isPlaying=false,this._animation?.stop(),this}stop(){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=false,this._animation?.stop(),this}setCurrentTime(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.currentTime=e,this.konvaNode.setAttr("currentTime",e),this}getCurrentTime(){return this._videoElement?this._videoElement.currentTime:0}getDuration(){return this._videoElement?this._videoElement.duration:0}setVolume(e){if(!this._videoElement)throw new Error("Video element is not initialized");let t=Math.max(0,Math.min(1,e));return this._videoElement.volume=t,this.konvaNode.setAttr("volume",t),this}getVolume(){return this._videoElement?this._videoElement.volume:0}setMuted(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.muted=e,this.konvaNode.setAttr("muted",e),this}isMuted(){return this._videoElement?this._videoElement.muted:false}setLoop(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.loop=e,this.konvaNode.setAttr("loop",e),this}isLoop(){return this._videoElement?this._videoElement.loop:false}setPlaybackRate(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.playbackRate=e,this.konvaNode.setAttr("playbackRate",e),this}getPlaybackRate(){return this._videoElement?this._videoElement.playbackRate:1}isPlaying(){return this._isPlaying}isLoaded(){return this._isLoaded}getVideoElement(){return this._videoElement}getSize(){return this.konvaNode.size()}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}_ensureAnimation(){if(this._animation)return;let e=this.konvaNode.getLayer();e&&(this._animation=new G.Animation(()=>{},e));}_cleanup(){this._placeholder.stop(),this._animation&&(this._animation.stop(),this._animation=null),this._videoElement&&(this._videoElement.pause(),this._videoElement.src="",this._videoElement.load(),this._videoElement=null),this._isPlaying=false,this._isLoaded=false;}remove(){this._cleanup(),super.remove();}};var De=class{constructor(i,e){a(this,"_layer");a(this,"_world");a(this,"_nodes",new Map);a(this,"_stage");a(this,"_eventBus");a(this,"_frameLabels",new Map);a(this,"_selectedFrame",null);a(this,"_batchDrawScheduled",false);a(this,"_listCache",null);a(this,"_listCacheInvalidated",true);a(this,"_hadFrameInLastMultiSelection",false);this._layer=new G.Layer,this._world=new G.Group,this._layer.add(this._world),this._stage=i,this._stage.add(this._layer),this._eventBus=e,this._eventBus.on("node:created",n=>{this._attachFrameAutogroupHandlers(n);}),this._eventBus.on("node:removed",n=>{if(n instanceof M){let o=this._frameLabels.get(n);o&&(o.destroy(),this._frameLabels.delete(n));}}),this._eventBus.on("node:transformed",n=>{n instanceof M&&this._updateFrameLabelsPosition();});let t=()=>{this._updateFrameLabelsPosition();};this._eventBus.on("camera:zoom",t),this._eventBus.on("camera:setZoom",t),this._eventBus.on("camera:reset",t),this._eventBus.on("camera:pan",t),this._eventBus.on("node:selected",n=>{for(let[,o]of this._frameLabels.entries()){let s=o._baseFill;o.fill(s);}if(n instanceof M){this._selectedFrame=n;let o=this._frameLabels.get(n);if(o){let s=o._hoverFill;o.fill(s);}this._enforceFrameDraggableInvariant(n);}else this._selectedFrame=null;this._layer.batchDraw();}),this._eventBus.on("node:deselected",n=>{n instanceof M&&this._enforceFrameDraggableInvariant(n);}),this._eventBus.on("selection:multi:created",n=>{for(let[,o]of this._frameLabels.entries()){let s=o._baseFill;o.fill(s);}this._selectedFrame=null,this._hadFrameInLastMultiSelection=false;for(let o of n)if(o instanceof M){let s=this._frameLabels.get(o);if(s){let r=s._hoverFill;s.fill(r);}this._selectedFrame||(this._selectedFrame=o),this._hadFrameInLastMultiSelection=true;}this._layer.batchDraw();}),this._eventBus.on("selection:multi:destroyed",()=>{if(this._hadFrameInLastMultiSelection){for(let[,n]of this._frameLabels.entries()){let o=n._baseFill;n.fill(o);}this._hadFrameInLastMultiSelection=false,this._layer.batchDraw();}}),this._eventBus.on("selection:cleared",()=>{this._selectedFrame=null;for(let[,n]of this._frameLabels.entries()){let o=n._baseFill;n.fill(o);}this._layer.batchDraw();for(let n of this._nodes.values())n instanceof M&&this._enforceFrameDraggableInvariant(n);});}get layer(){return this._layer}get world(){return this._world}get stage(){return this._stage}get eventBus(){return this._eventBus}addShape(i){let e=new it(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addText(i){let e=new Te(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addImage(i){let e=new tt(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addCircle(i){let e=new $e(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addEllipse(i){let e=new Je(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addArc(i){let e=new Ze(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addStar(i){let e=new st(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addArrow(i){let e=new qe(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addRing(i){let e=new ot(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addRegularPolygon(i){let e=new nt(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addGroup(i){let e=new ge(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addSvg(i){let e=new rt(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addVideo(i){let e=new at(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addGif(i){let e=new et(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addFrame(i){let e=new M(i);this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw();let t=i.label??i.name??"Frame",n=i.labelColor??"#ffffff",o=i.labelHoverColor??"#2683ff",s=new G.Text({text:t,fontSize:12,fill:n,listening:true});s._baseFill=n,s._hoverFill=o,this._layer.add(s),this._frameLabels.set(e,s);let r=s.fill();s.on("mouseenter.frame-label-ui",()=>{s.fill(o),this._layer.batchDraw();}),s.on("mouseleave.frame-label-ui",()=>{this._selectedFrame!==e&&(s.fill(r),this._layer.batchDraw());}),s.on("click.frame-label-ui tap.frame-label-ui",h=>{let c=h.evt,d=c.shiftKey,u=c.ctrlKey||c.metaKey;this._eventBus.emit("frame:label-clicked",e,{shiftKey:d,ctrlKey:u});}),s.on("mousedown.frame-label-drag",h=>{if(h.evt.button!==0)return;let c=this._stage,d=e.getKonvaNode(),u=3,p=h.evt.clientX,f=h.evt.clientY,g=c.draggable(),m=false,_=v=>{let w=Math.abs(v.evt.clientX-p),x=Math.abs(v.evt.clientY-f);!m&&(w>u||x>u)&&(m=true,d.on("dragstart.frame-label-drag-once",()=>{c.draggable(false),this._eventBus.emit("frame:label-dragstart",e);}),d.on("dragend.frame-label-drag-once",()=>{c.draggable(g),d.off(".frame-label-drag-once"),this._eventBus.emit("frame:label-clicked",e),this._eventBus.emit("frame:label-dragend",e);}),typeof d.startDrag=="function"&&d.startDrag(),h.cancelBubble=true);},b=()=>{c.off("mousemove.frame-label-drag-temp",_),c.off("mouseup.frame-label-drag-temp",b);};c.on("mousemove.frame-label-drag-temp",_),c.on("mouseup.frame-label-drag-temp",b);}),s.on("dblclick.frame-label-ui dbltap.frame-label-ui",h=>{h.cancelBubble=true;let c=this._stage.container(),d=s.text(),u=globalThis.document.createElement("input");u.type="text",u.value=d,u.maxLength=40,u.style.position="absolute",u.style.boxSizing="border-box";let p=s.getClientRect({skipShadow:true,skipStroke:true});u.style.left=String(p.x)+"px",u.style.top=String(p.y)+"px",u.style.width=String(p.width||80)+"px",u.style.height=String(p.height||16)+"px",u.style.backgroundColor="transparent",u.style.color=n,u.style.border="none",u.style.outline="none";let f=String(s.fontSize())+"px",g=s.fontFamily()||"sans-serif";u.style.fontSize=f,u.style.fontFamily=g;let m=s.visible();s.visible(false),this._layer.batchDraw();let _=globalThis.document.createElement("span");_.style.position="absolute",_.style.visibility="hidden",_.style.whiteSpace="pre",_.style.fontSize=f,_.style.fontFamily=g,c.appendChild(_);let b=()=>{let T=u.value||" ";_.textContent=T;let K=_.getBoundingClientRect(),L=16;u.style.width=String(K.width+L)+"px";};c.appendChild(u),u.focus(),u.select(),b();let v=false,w=()=>{v||(v=true,u.removeEventListener("keydown",k),u.removeEventListener("blur",C),u.removeEventListener("input",S),u.parentNode===c&&c.removeChild(u),_.parentNode===c&&c.removeChild(_),s.visible(m),this._layer.batchDraw());},x=()=>{if(v)return;let T=u.value.trim();T.length>=1&&T.length<=40&&T!==d&&(s.text(T),this._eventBus.emit("frame:label-changed",e,T),this._layer.batchDraw()),w();},N=()=>{v||w();},k=T=>{T.key==="Escape"?(T.preventDefault(),N()):T.key==="Enter"&&(T.preventDefault(),x());},S=()=>{b();},C=()=>{x();};u.addEventListener("keydown",k),u.addEventListener("blur",C),u.addEventListener("input",S);});let l=e.getKonvaNode();return l.on("dragmove.frame-label",()=>{this._updateFrameLabelsPosition();}),l.on("transform.frame-label",()=>{this._updateFrameLabelsPosition();}),l.on("xChange.frame-label yChange.frame-label widthChange.frame-label heightChange.frame-label scaleXChange.frame-label scaleYChange.frame-label rotationChange.frame-label",()=>{this._updateFrameLabelsPosition();}),this._updateFrameLabelsPosition(),e}remove(i){this._eventBus.emit("node:removed",i),i.remove(),this._nodes.delete(i.id),this._listCacheInvalidated=true,this._scheduleBatchDraw();}findById(i){return this._nodes.get(i)}list(){return (this._listCacheInvalidated||!this._listCache)&&(this._listCache=Array.from(this._nodes.values()),this._listCacheInvalidated=false),this._listCache}_scheduleBatchDraw(){if(this._batchDrawScheduled)return;this._batchDrawScheduled=true;let i=globalThis.requestAnimationFrame;i(()=>{this._batchDrawScheduled=false,this._layer.batchDraw();});}_listFrames(){let i=[];for(let e of this._nodes.values())e instanceof M&&i.push(e);return i}_attachFrameAutogroupHandlers(i){if(i instanceof M)return;let e=i.getKonvaNode();e.on("dragmove.frame-autogroup",()=>{let t=this._stage.getPointerPosition();if(!t)return;let n=e.getParent(),o=this._world,s=null;e:for(let l of this._listFrames()){let h=n,c=l.getContentGroup();for(;h&&h!==o;){if(h===c){s=l;break e}h=h.getParent();}}let r=null;for(let l of this._listFrames()){let c=l.getRect().getClientRect({skipShadow:true,skipStroke:true});if(t.x>=c.x&&t.x<=c.x+c.width&&t.y>=c.y&&t.y<=c.y+c.height){r=l;break}}if(s){if(!r||r!==s){let l=e.getAbsolutePosition();this._world.add(e),e.setAbsolutePosition(l),this._layer.batchDraw();let d=s.getContentGroup().getChildren().length>0,u=s.getKonvaNode();typeof u.draggable=="function"&&u.draggable(!d),this._eventBus.emit("frame:children-changed",s,d);}return}if(r&&n!==r.getContentGroup()){let l=e.getAbsolutePosition(),h=r.getContentGroup();h.add(e),e.setAbsolutePosition(l),this._layer.batchDraw();let c=h.getChildren().length>0,d=r.getKonvaNode();typeof d.draggable=="function"&&d.draggable(!c),this._eventBus.emit("frame:children-changed",r,c);}});}_updateFrameLabelsPosition(){for(let[i,e]of this._frameLabels.entries()){let n=i.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false}),o=16,s=n.x,r=n.y-o;e.absolutePosition({x:s,y:r}),e.offsetX(0),e.offsetY(0);}this._layer.batchDraw();}_enforceFrameDraggableInvariant(i){let t=i.getContentGroup().getChildren().length>0,n=i.getKonvaNode();typeof n.draggable=="function"&&n.draggable(!t);}};var ve=class{constructor(i=16){a(this,"_lastTime",0);a(this,"_throttle");this._throttle=i;}shouldExecute(){let i=Date.now();return i-this._lastTime<this._throttle?false:(this._lastTime=i,true)}reset(){this._lastTime=0;}setThrottle(i){this._throttle=i;}getThrottle(){return this._throttle}};var lt=class{constructor(i={}){a(this,"_enabled");a(this,"_levels");a(this,"_currentScale",1);a(this,"_appliedNodes",new Map);this._enabled=i.enabled??true,this._levels=i.levels??[{minScale:0,maxScale:.1,simplify:true,disableStroke:true,disableShadow:true,disablePerfectDraw:true},{minScale:.1,maxScale:.3,simplify:true,disableShadow:true,disablePerfectDraw:true},{minScale:.3,maxScale:1/0,simplify:false}];}_getLODLevel(i){return this._enabled?this._levels.find(t=>i>=t.minScale&&i<t.maxScale)??null:null}applyLOD(i,e){if(!this._enabled)return;this._currentScale=e;let t=this._getLODLevel(e);if(!t?.simplify){this._restoreNode(i);return}let n=i.getKonvaNode(),o=this._appliedNodes.get(i.id);o!==t&&(o||(n._originalLOD={stroke:n.stroke?.(),strokeEnabled:n.strokeEnabled(),shadow:n.shadowEnabled(),perfectDraw:n.perfectDrawEnabled?.()}),t.disableStroke&&n.strokeEnabled(false),t.disableShadow&&n.shadowEnabled(false),t.disablePerfectDraw&&n.perfectDrawEnabled&&n.perfectDrawEnabled(false),this._appliedNodes.set(i.id,t));}_restoreNode(i){let e=i.getKonvaNode(),t=e._originalLOD;t&&(e.strokeEnabled(t.strokeEnabled),e.shadowEnabled(t.shadow),t.perfectDraw!==void 0&&e.perfectDrawEnabled&&e.perfectDrawEnabled(t.perfectDraw),this._appliedNodes.delete(i.id),delete e._originalLOD);}applyToAll(i,e){if(this._enabled)for(let t of i)this.applyLOD(t,e);}restoreAll(i){for(let e of i)this._restoreNode(e);this._appliedNodes.clear();}enable(){this._enabled=true;}disable(i){this._enabled=false,this.restoreAll(i);}get enabled(){return this._enabled}get currentScale(){return this._currentScale}getStats(){return {enabled:this._enabled,currentScale:this._currentScale,appliedNodes:this._appliedNodes.size,currentLevel:this._getLODLevel(this._currentScale)}}setLevels(i){this._levels=i;}};var dt=class{constructor(i,e,t,n={}){this._stage=i;this._world=e;this._nodeManager=t;a(this,"_enabled");a(this,"_bufferZone");a(this,"_throttle");a(this,"_viewport",{x:0,y:0,width:0,height:0});a(this,"_visibleNodes",new Set);a(this,"_hiddenNodes",new Set);a(this,"_tempMultiNodeIds",new Set);a(this,"_updateScheduled",false);a(this,"_lod",null);this._enabled=n.enabled??true,this._bufferZone=n.bufferZone??200,this._throttle=new ve(n.throttleMs??16),n.lod&&(this._lod=new lt(n.lod)),this._updateViewport(),this._setupListeners(),this._enabled&&this.updateVisibility();}_updateViewport(){let i=this._world.scaleX(),e=this._world.position();this._viewport={x:-e.x/i-this._bufferZone,y:-e.y/i-this._bufferZone,width:this._stage.width()/i+this._bufferZone*2,height:this._stage.height()/i+this._bufferZone*2};}_getNodeBBox(i){let t=i.getKonvaNode().getClientRect({relativeTo:this._world});return {x:t.x,y:t.y,width:t.width,height:t.height}}_isNodeVisible(i){let e=i.getKonvaNode();if(this._tempMultiNodeIds.has(i.id))return true;let t=e.getParent();if(t&&t instanceof G.Group&&t!==this._world)return true;let n=this._getNodeBBox(i);return !(n.x+n.width<this._viewport.x||n.x>this._viewport.x+this._viewport.width||n.y+n.height<this._viewport.y||n.y>this._viewport.y+this._viewport.height)}updateVisibility(){if(!this._enabled||!this._throttle.shouldExecute())return;let i=this._nodeManager.list(),e=new Set,t=0;for(let n of i){let o=this._isNodeVisible(n),s=n.getKonvaNode();o?(e.add(n.id),this._hiddenNodes.has(n.id)&&(s.visible(true),s.listening(true),this._hiddenNodes.delete(n.id),t++)):this._hiddenNodes.has(n.id)||(s.visible(false),s.listening(false),this._hiddenNodes.add(n.id),t++);}if(this._visibleNodes=e,this._lod?.enabled&&t>0){let n=this._world.scaleX();for(let o of i)e.has(o.id)&&this._lod.applyLOD(o,n);}t>0&&this._nodeManager.layer.batchDraw();}_setupListeners(){this._world.on("xChange yChange scaleXChange scaleYChange",()=>{this._scheduleUpdate();}),typeof globalThis.window<"u"&&globalThis.window.addEventListener("resize",()=>{this._updateViewport(),this._scheduleUpdate();}),this._nodeManager.eventBus.on("node:removed",i=>{this._visibleNodes.delete(i.id),this._hiddenNodes.delete(i.id),this._tempMultiNodeIds.delete(i.id);}),this._nodeManager.eventBus.on("selection:multi:created",i=>{this._tempMultiNodeIds.clear();for(let e of i)this._tempMultiNodeIds.add(e.id);}),this._nodeManager.eventBus.on("selection:multi:destroyed",()=>{this._tempMultiNodeIds.clear();});}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=true,globalThis.requestAnimationFrame(()=>{this._updateViewport(),this.updateVisibility(),this._updateScheduled=false;}));}enable(){this._enabled||(this._enabled=true,this.updateVisibility());}disable(){if(this._enabled){this._enabled=false;for(let i of this._hiddenNodes){let e=this._nodeManager.findById(i);if(e){let t=e.getKonvaNode();t.visible(true),t.listening(true);}}this._hiddenNodes.clear(),this._visibleNodes.clear(),this._nodeManager.layer.batchDraw();}}getStats(){let i=this._nodeManager.list().length,e=this._visibleNodes.size,t=this._hiddenNodes.size;return {total:i,visible:e,hidden:t,cullingRate:i>0?t/i*100:0}}setBufferZone(i){this._bufferZone=i,this._updateViewport(),this._scheduleUpdate();}setThrottle(i){this._throttle=new ve(i);}get enabled(){return this._enabled}get viewport(){return {...this._viewport}}forceUpdate(){this._throttle.reset(),this._updateViewport(),this.updateVisibility();}get lod(){return this._lod}destroy(){if(this.disable(),this._visibleNodes.clear(),this._hiddenNodes.clear(),this._lod){let i=this._nodeManager.list();this._lod.restoreAll(i);}}};var ct=class{constructor(i){a(this,"_plugin");a(this,"_addons",new Set);a(this,"_core");this._plugin=i;}_attachAll(i){this._core=i,this._addons.forEach(e=>{e.attach(this._plugin,i);});}_detachAll(i){this._addons.forEach(e=>{e.detach(this._plugin,i);}),this._core=void 0;}add(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)||(this._addons.add(t),this._core&&t.attach(this._plugin,this._core));return this._plugin}remove(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)&&(this._addons.delete(t),this._core&&t.detach(this._plugin,this._core));return this._plugin}list(){return Array.from(this._addons)}has(i){return this._addons.has(i)}clear(){if(this._core){let i=this._core;this._addons.forEach(e=>{e.detach(this._plugin,i);});}this._addons.clear();}};var O=class{constructor(){a(this,"addons");this.addons=new ct(this);}attach(i){this.onAttach(i),this.addons._attachAll(i);}detach(i){this.addons._detachAll(i),this.onDetach(i);}};var Oe=class{constructor(i,e=[]){a(this,"_core");a(this,"_items",[]);this._core=i,e.length&&this.addPlugins(e);}addPlugins(i){let e=[];for(let t of i)this._items.includes(t)||(this._items.push(t),t.attach(this._core),e.push(t),this._core.eventBus.emit("plugin:added",t.constructor.name));return e}removePlugins(i){let e=[];for(let t of i){let n=this._items.indexOf(t);n!==-1&&(t.detach(this._core),this._items.splice(n,1),e.push(t),this._core.eventBus.emit("plugin:removed",t.constructor.name));}return e}removeAllPlugins(){let i=[...this._items];for(let e of i)e.detach(this._core);this._items=[];for(let e of i)this._core.eventBus.emit("plugin:removed",e.constructor.name);return i}list(){return [...this._items]}get(i){return this._items.find(e=>e.constructor.name===i)}};var xt=class{constructor(i){a(this,"_stage");a(this,"_eventBus");a(this,"_initialWidth");a(this,"_initialHeight");a(this,"_autoResize");a(this,"_backgroundColor");a(this,"_draggable");a(this,"_minScale");a(this,"_maxScale");a(this,"_gridLayer");a(this,"_resizeObserver",null);a(this,"container");a(this,"nodes");a(this,"camera");a(this,"virtualization");a(this,"plugins");a(this,"_handleResize",()=>{if(!this._autoResize)return;let i=this.container.offsetWidth,e=this.container.offsetHeight;(i!==this._stage.width()||e!==this._stage.height())&&this.setSize({width:i,height:e});});this.container=i.container,this.container.style.visibility="hidden",this._initialWidth=i.width??800,this._initialHeight=i.height??800,this._autoResize=i.autoResize??true,this._backgroundColor=i.backgroundColor??"#1e1e1e",this._draggable=i.draggable??true,this._minScale=i.minScale??.1,this._maxScale=i.maxScale??500,this._stage=new G.Stage({container:this.container,width:this._autoResize?this.container.offsetWidth:this._initialWidth,height:this._autoResize?this.container.offsetHeight:this._initialHeight,draggable:false}),this._autoResize||(this.container.style.width=`${String(this._initialWidth)}px`,this.container.style.height=`${String(this._initialHeight)}px`),this.container.style.background=this._backgroundColor,this._eventBus=new Be,this._gridLayer=new G.Layer({listening:false}),this._stage.add(this._gridLayer),this.nodes=new De(this._stage,this._eventBus),this.camera=new Ae({stage:this._stage,target:this.nodes.world,eventBus:this._eventBus,initialScale:1,draggable:false,minScale:this._minScale,maxScale:this._maxScale}),this.virtualization=new dt(this._stage,this.nodes.world,this.nodes,i.virtualization),this.plugins=new Oe(this),i.plugins?.length&&this.plugins.addPlugins(i.plugins),this._autoResize&&this._setupAutoResize();}_setupAutoResize(){typeof ResizeObserver<"u"?(this._resizeObserver=new ResizeObserver(()=>{this._handleResize();}),this._resizeObserver.observe(this.container)):globalThis.addEventListener("resize",this._handleResize);}destroy(){this._resizeObserver?(this._resizeObserver.disconnect(),this._resizeObserver=null):globalThis.removeEventListener("resize",this._handleResize),this._stage.destroy();}get eventBus(){return this._eventBus}get stage(){return this._stage}get gridLayer(){return this._gridLayer}get draggable(){return this._draggable}get autoResize(){return this._autoResize}get backgroundColor(){return this._backgroundColor}get initialWidth(){return this._initialWidth}get initialHeight(){return this._initialHeight}get minScale(){return this._minScale}get maxScale(){return this._maxScale}setSize({width:i,height:e}){this._stage.size({width:i,height:e}),this._stage.fire("resize"),this._eventBus.emit("stage:resized",{width:i,height:e});}setBackgroundColor(i){this.container.style.background=i;}setDraggable(i){this._stage.draggable(i),this._draggable=i;}setAutoResize(i){this._autoResize!==i&&(this._autoResize=i,i?(this._setupAutoResize(),this._handleResize()):this._resizeObserver?(this._resizeObserver.disconnect(),this._resizeObserver=null):globalThis.removeEventListener("resize",this._handleResize));}showContainer(){this.container.style.visibility="visible";}};var Ie=class{constructor(){a(this,"_actions",[]);a(this,"_currentIndex",-1);}push(i){this._currentIndex<this._actions.length-1&&this.pop(this._currentIndex+1),this._actions.push(i),this._currentIndex=this._actions.length-1,this._debug("push",i);}pop(i){if(i<0||i>this._actions.length)return;let e=this._actions.splice(i);this._currentIndex=Math.min(this._currentIndex,this._actions.length-1),this._debug("pop",{fromIndex:i,removedCount:e.length});}select(i){if(i<-1||i>=this._actions.length)return;let e=this._currentIndex;this._currentIndex=i,this._debug("select",{oldIndex:e,newIndex:i});}getCurrentIndex(){return this._currentIndex}get length(){return this._actions.length}getActions(){return [...this._actions]}canUndo(){return this._currentIndex>=0}canRedo(){return this._currentIndex<this._actions.length-1}undo(){if(!this.canUndo())return this._debug("undo","cannot undo - at beginning"),null;let i=this._actions[this._currentIndex];return this._currentIndex--,this._debug("undo",{action:i,newIndex:this._currentIndex}),i??null}redo(){if(!this.canRedo())return this._debug("redo","cannot redo - at end"),null;this._currentIndex++;let i=this._actions[this._currentIndex];return this._debug("redo",{action:i,newIndex:this._currentIndex}),i??null}clear(){this._actions=[],this._currentIndex=-1,this._debug("clear","history cleared");}getAction(i){return i<0||i>=this._actions.length?null:this._actions[i]??null}_debug(i,e){}};var oe=class{attach(i,e){this.onAttach(i,e);}detach(i,e){this.onDetach(i,e);}};var Ge=class extends oe{constructor(e={}){super();a(this,"_core",null);a(this,"_rootEl",null);a(this,"_controlsEl",null);a(this,"_playBtn",null);a(this,"_muteBtn",null);a(this,"_speedBtn",null);a(this,"_timeLabel",null);a(this,"_seekInput",null);a(this,"_volInput",null);a(this,"_selectedVideoNode",null);a(this,"_selectedVideoEl",null);a(this,"_hiddenForDrag",false);a(this,"_hiddenForSize",false);a(this,"_hiddenForTransform",false);a(this,"_hiddenForZoom",false);a(this,"_hiddenForWorldScale",false);a(this,"_hiddenForNotReady",false);a(this,"_uiMode","full");a(this,"_zoomUnhideTimeoutId",null);a(this,"_onKonvaDragStart",null);a(this,"_onKonvaDragEnd",null);a(this,"_onKonvaTransformStart",null);a(this,"_onKonvaTransformEnd",null);a(this,"_onLayerTransformStart",null);a(this,"_onLayerTransformEnd",null);a(this,"_onLayerDragStart",null);a(this,"_onLayerDragEnd",null);a(this,"_rafId",null);a(this,"_options");a(this,"_onNodeSelected",null);a(this,"_onNodeDeselected",null);a(this,"_onSelectionCleared",null);a(this,"_onNodeTransformed",null);a(this,"_onStageResized",null);a(this,"_onCameraChanged",null);a(this,"_onWorldChanged",null);a(this,"_onTimeUpdate",null);a(this,"_onLoadedMetadata",null);a(this,"_onCanPlay",null);a(this,"_onPlayPauseSync",null);this._options={zIndex:e.zIndex??20,marginPx:e.marginPx??8,controlsHeightPx:e.controlsHeightPx??42,speeds:e.speeds??[.5,.75,1,1.25,1.5,2],minWidthPx:e.minWidthPx??220,minHeightPx:e.minHeightPx??120,maxWorldScaleToShow:e.maxWorldScaleToShow??8,hideDuringCameraZoomMs:e.hideDuringCameraZoomMs??120,uiBackgroundColor:e.uiBackgroundColor??"rgba(31,31,31,0.92)",uiBorderColor:e.uiBorderColor??"rgba(255,255,255,0.08)",uiTextColor:e.uiTextColor??"#ffffff",uiMutedTextColor:e.uiMutedTextColor??"rgba(255,255,255,0.6)",uiAccentColor:e.uiAccentColor??"#2b83ff",uiTrackColor:e.uiTrackColor??"rgba(255,255,255,0.22)",uiTrackFilledColor:e.uiTrackFilledColor??"#2b83ff"};}onAttach(e,t){if(this._core=t,typeof document>"u")return;this._ensureDom(t),this._onNodeSelected=o=>{this._tryShowForNode(o);},this._onNodeDeselected=o=>{o&&this._selectedVideoNode&&o===this._selectedVideoNode&&this._hide();},this._onSelectionCleared=()=>{this._hide();},this._onNodeTransformed=o=>{this._selectedVideoNode&&o===this._selectedVideoNode&&this._scheduleSync();},t.eventBus.on("node:selected",this._onNodeSelected),t.eventBus.on("node:deselected",this._onNodeDeselected),t.eventBus.on("selection:cleared",this._onSelectionCleared),t.eventBus.on("node:transformed",this._onNodeTransformed),this._onStageResized=()=>{this._hideTemporarilyForZoom(),this._scheduleSync();},t.eventBus.on("stage:resized",this._onStageResized),this._onCameraChanged=()=>{this._hideTemporarilyForZoom(),this._scheduleSync();},t.eventBus.on("camera:zoom",this._onCameraChanged),t.eventBus.on("camera:setZoom",this._onCameraChanged),t.eventBus.on("camera:reset",this._onCameraChanged),t.eventBus.on("camera:pan",this._onCameraChanged);let n=t.nodes.world;this._onWorldChanged=()=>{this._scheduleSync();},n.on("xChange.videoOverlay yChange.videoOverlay scaleXChange.videoOverlay scaleYChange.videoOverlay",this._onWorldChanged),this._bindLayerInteractionEvents(t),this._hide();}onDetach(e,t){this._hide(),this._zoomUnhideTimeoutId!=null&&(globalThis.clearTimeout(this._zoomUnhideTimeoutId),this._zoomUnhideTimeoutId=null),this._onNodeSelected&&t.eventBus.off("node:selected",this._onNodeSelected),this._onNodeDeselected&&t.eventBus.off("node:deselected",this._onNodeDeselected),this._onSelectionCleared&&t.eventBus.off("selection:cleared",this._onSelectionCleared),this._onNodeTransformed&&t.eventBus.off("node:transformed",this._onNodeTransformed),this._onStageResized&&t.eventBus.off("stage:resized",this._onStageResized),this._onCameraChanged&&(t.eventBus.off("camera:zoom",this._onCameraChanged),t.eventBus.off("camera:setZoom",this._onCameraChanged),t.eventBus.off("camera:reset",this._onCameraChanged),t.eventBus.off("camera:pan",this._onCameraChanged)),this._onWorldChanged&&t.nodes.world.off(".videoOverlay"),this._unbindLayerInteractionEvents(t),this._rafId!=null&&(globalThis.cancelAnimationFrame(this._rafId),this._rafId=null),this._rootEl&&this._rootEl.remove(),this._rootEl=null,this._controlsEl=null,this._playBtn=null,this._muteBtn=null,this._speedBtn=null,this._timeLabel=null,this._seekInput=null,this._volInput=null,this._hiddenForDrag=false,this._hiddenForSize=false,this._hiddenForTransform=false,this._hiddenForZoom=false,this._hiddenForWorldScale=false,this._hiddenForNotReady=false,this._onKonvaDragStart=null,this._onKonvaDragEnd=null,this._onKonvaTransformStart=null,this._onKonvaTransformEnd=null,this._onLayerTransformStart=null,this._onLayerTransformEnd=null,this._onLayerDragStart=null,this._onLayerDragEnd=null,this._core=null,this._onNodeSelected=null,this._onNodeDeselected=null,this._onSelectionCleared=null,this._onNodeTransformed=null,this._onStageResized=null,this._onCameraChanged=null,this._onWorldChanged=null;}_ensureDom(e){if(this._rootEl)return;let t=globalThis.document.createElement("div");t.style.position="absolute",t.style.left="0px",t.style.top="0px",t.style.width="0px",t.style.height="0px",t.style.display="none",t.style.zIndex=String(this._options.zIndex),t.style.pointerEvents="none",t.style.boxSizing="border-box",t.style.borderRadius="8px",t.style.overflow="visible";let n=globalThis.document.createElement("div");n.style.position="absolute",n.style.left="0px",n.style.top="0px",n.style.height=String(this._options.controlsHeightPx)+"px",n.style.display="flex",n.style.alignItems="center",n.style.gap="10px",n.style.padding="8px 10px",n.style.borderRadius="10px",n.style.pointerEvents="auto",n.style.boxSizing="border-box",n.style.background=this._options.uiBackgroundColor,n.style.border="1px solid "+this._options.uiBorderColor,n.style.backdropFilter="blur(8px)",n.style.transformOrigin="0 0";let o=f=>{let g=f.target;g instanceof HTMLInputElement&&g.type==="range"||f.stopPropagation();};n.addEventListener("pointerdown",o),n.addEventListener("mousedown",o),n.addEventListener("touchstart",o),n.addEventListener("wheel",f=>{f.ctrlKey&&f.preventDefault();},{passive:false});let s=f=>{let g=globalThis.document.createElement("button");return g.type="button",g.textContent=f,g.style.height="28px",g.style.minWidth="34px",g.style.padding="0 10px",g.style.borderRadius="8px",g.style.border="1px solid "+this._options.uiBorderColor,g.style.background="rgba(0,0,0,0.12)",g.style.color=this._options.uiTextColor,g.style.cursor="pointer",g.style.fontSize="12px",g.style.fontFamily="Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",g.style.lineHeight="28px",g.style.whiteSpace="nowrap",g},r=s("Play");r.style.minWidth="56px";let l=s("Mute");l.style.minWidth="56px";let h=globalThis.document.createElement("span");h.textContent="0:00 / 0:00",h.style.color=this._options.uiTextColor,h.style.opacity="0.9",h.style.fontSize="12px",h.style.fontFamily="Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",h.style.whiteSpace="nowrap";let c=s("1x"),d=globalThis.document.createElement("input");d.type="range",d.min="0",d.max="0",d.step="0.01",d.value="0",d.style.flex="1",d.style.height="6px",d.style.cursor="pointer",d.style.accentColor=this._options.uiAccentColor;let u=globalThis.document.createElement("input");u.type="range",u.min="0",u.max="1",u.step="0.01",u.value="1",u.style.width="90px",u.style.height="6px",u.style.cursor="pointer",u.style.accentColor=this._options.uiAccentColor,n.appendChild(r),n.appendChild(d),n.appendChild(h),n.appendChild(l),n.appendChild(u),n.appendChild(c),t.appendChild(n);let p=e.stage.container();p.style.position=p.style.position||"relative",p.appendChild(t),this._rootEl=t,this._controlsEl=n,this._playBtn=r,this._muteBtn=l,this._speedBtn=c,this._timeLabel=h,this._seekInput=d,this._volInput=u,this._updateRangeFill(d,0),this._updateRangeFill(u,1),r.addEventListener("click",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;!f||!g||(g.paused?f.play():f.pause(),this._syncControls());}),d.addEventListener("input",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g||!Number.isFinite(g.duration)||g.duration<=0)return;let m=Number(d.value);if(!Number.isFinite(m))return;let _=Math.max(0,Math.min(g.duration,m));f.setCurrentTime(_),this._updateRangeFill(d,g.duration>0?_/g.duration:0),this._syncControls();}),l.addEventListener("click",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g)return;let m=!g.muted;f.setMuted(m),!m&&g.volume<=0&&f.setVolume(.8),this._syncControls();}),u.addEventListener("input",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g)return;let m=Math.max(0,Math.min(1,Number(u.value)));f.setVolume(m),m>0&&g.muted&&f.setMuted(false),this._updateRangeFill(u,m),this._syncControls();}),c.addEventListener("click",()=>{let f=this._selectedVideoNode,g=this._selectedVideoEl;if(!f||!g)return;let m=this._options.speeds;if(!Array.isArray(m)||m.length===0)return;let _=g.playbackRate,b=m.findIndex(w=>Math.abs(w-_)<.001);b<0&&(b=0);let v=m[(b+1)%m.length];typeof v=="number"&&Number.isFinite(v)&&v>0&&f.setPlaybackRate(v),this._syncControls();});}_updateRangeFill(e,t){let n=Math.max(0,Math.min(1,t)),o=Math.round(n*100),s=this._options.uiTrackFilledColor,r=this._options.uiTrackColor;e.style.background="linear-gradient(to right, "+s+" 0%, "+s+" "+String(o)+"%, "+r+" "+String(o)+"%, "+r+" 100%)",e.style.borderRadius="999px",e.style.border="none",e.style.outline="none";}_tryShowForNode(e){if(!this._core)return;if(!e||typeof e.getKonvaNode!="function"){this._hide();return}let t=e.getKonvaNode();if((t&&typeof t.getAttr=="function"?t.getAttr("flowscapeNodeType"):void 0)!=="video"){this._hide();return}this._show(e);}_show(e){this._rootEl&&(this._selectedVideoNode=e,this._selectedVideoEl=e.getVideoElement(),this._bindKonvaDragEvents(),this._bindKonvaTransformEvents(),this._bindVideoEvents(),this._hiddenForZoom=false,this._hiddenForTransform=false,this._hiddenForNotReady=!this._isVideoReady(),this._rootEl.style.display=this._hiddenForNotReady?"none":"block",this._hiddenForSize=false,this._scheduleSync(),this._syncControls());}_hide(){this._rootEl&&(this._rootEl.style.display="none"),this._hiddenForDrag=false,this._hiddenForSize=false,this._hiddenForTransform=false,this._hiddenForZoom=false,this._hiddenForWorldScale=false,this._hiddenForNotReady=false,this._unbindKonvaDragEvents(),this._unbindKonvaTransformEvents(),this._unbindVideoEvents(),this._selectedVideoNode=null,this._selectedVideoEl=null;}_bindLayerInteractionEvents(e){let t=e.nodes.layer;typeof t.on!="function"||typeof t.off!="function"||(this._unbindLayerInteractionEvents(e),this._onLayerTransformStart=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onLayerTransformEnd=()=>{if(this._rootEl&&this._selectedVideoNode){if(this._hiddenForTransform=false,this._hiddenForDrag||this._hiddenForZoom||this._hiddenForSize||this._hiddenForNotReady){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}},this._onLayerDragStart=n=>{if(!this._rootEl||!this._selectedVideoNode)return;let o=n.target,s=typeof o?.name=="function"?o.name():void 0;typeof s=="string"&&s.startsWith("rotate-")&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onLayerDragEnd=()=>{if(this._rootEl&&this._selectedVideoNode){if(this._hiddenForTransform=false,this._hiddenForDrag||this._hiddenForZoom||this._hiddenForSize||this._hiddenForNotReady){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}},t.on("transformstart.videoOverlayLayer",this._onLayerTransformStart),t.on("transformend.videoOverlayLayer",this._onLayerTransformEnd),t.on("dragstart.videoOverlayLayer",this._onLayerDragStart),t.on("dragend.videoOverlayLayer",this._onLayerDragEnd));}_unbindLayerInteractionEvents(e){let t=e.nodes.layer;typeof t.off=="function"&&(t.off(".videoOverlayLayer"),this._onLayerTransformStart=null,this._onLayerTransformEnd=null,this._onLayerDragStart=null,this._onLayerDragEnd=null);}_bindKonvaDragEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.on!="function"||typeof e.off!="function"||(this._unbindKonvaDragEvents(),this._onKonvaDragStart=()=>{this._rootEl&&(this._hiddenForDrag=true,this._rootEl.style.display="none");},this._onKonvaDragEnd=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForDrag=false,this._rootEl.style.display="block",this._scheduleSync());},e.on("dragstart.videoOverlay",this._onKonvaDragStart),e.on("dragend.videoOverlay",this._onKonvaDragEnd));}_unbindKonvaDragEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.off=="function"&&(e.off(".videoOverlay"),this._onKonvaDragStart=null,this._onKonvaDragEnd=null);}_bindKonvaTransformEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.on!="function"||typeof e.off!="function"||(this._unbindKonvaTransformEvents(),this._onKonvaTransformStart=()=>{this._rootEl&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onKonvaTransformEnd=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForTransform=false,this._rootEl.style.display="block",this._scheduleSync());},e.on("transformstart.videoOverlayTransform",this._onKonvaTransformStart),e.on("transformend.videoOverlayTransform",this._onKonvaTransformEnd));}_unbindKonvaTransformEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.off=="function"&&(e.off(".videoOverlayTransform"),this._onKonvaTransformStart=null,this._onKonvaTransformEnd=null);}_hideTemporarilyForZoom(){this._rootEl&&this._selectedVideoNode&&(this._hiddenForZoom=true,this._rootEl.style.display="none",this._zoomUnhideTimeoutId!=null&&globalThis.clearTimeout(this._zoomUnhideTimeoutId),this._zoomUnhideTimeoutId=globalThis.setTimeout(()=>{this._zoomUnhideTimeoutId=null,this._rootEl&&this._selectedVideoNode&&(this._hiddenForZoom=false,!(this._hiddenForDrag||this._hiddenForTransform||this._hiddenForSize)&&(this._rootEl.style.display="block",this._scheduleSync()));},this._options.hideDuringCameraZoomMs));}_bindVideoEvents(){let e=this._selectedVideoEl;e&&(this._onTimeUpdate=()=>{this._syncControls();},this._onLoadedMetadata=()=>{this._syncControls(),this._maybeShowWhenReady();},this._onCanPlay=()=>{this._syncControls(),this._maybeShowWhenReady();},this._onPlayPauseSync=()=>{this._syncControls();},e.addEventListener("timeupdate",this._onTimeUpdate),e.addEventListener("loadedmetadata",this._onLoadedMetadata),e.addEventListener("canplay",this._onCanPlay),e.addEventListener("play",this._onPlayPauseSync),e.addEventListener("pause",this._onPlayPauseSync));}_unbindVideoEvents(){let e=this._selectedVideoEl;if(!e){this._onTimeUpdate=null,this._onLoadedMetadata=null,this._onPlayPauseSync=null;return}this._onTimeUpdate&&e.removeEventListener("timeupdate",this._onTimeUpdate),this._onLoadedMetadata&&e.removeEventListener("loadedmetadata",this._onLoadedMetadata),this._onCanPlay&&e.removeEventListener("canplay",this._onCanPlay),this._onPlayPauseSync&&(e.removeEventListener("play",this._onPlayPauseSync),e.removeEventListener("pause",this._onPlayPauseSync)),this._onTimeUpdate=null,this._onLoadedMetadata=null,this._onCanPlay=null,this._onPlayPauseSync=null;}_isVideoReady(){let e=this._selectedVideoEl;return !e||!Number.isFinite(e.duration)||e.duration<=0?false:e.readyState>=1}_maybeShowWhenReady(){if(!this._rootEl||!this._selectedVideoNode)return;if(!this._isVideoReady()){this._hiddenForNotReady=true,this._rootEl.style.display="none";return}if(this._hiddenForNotReady){if(this._hiddenForNotReady=false,this._hiddenForDrag||this._hiddenForTransform||this._hiddenForZoom||this._hiddenForSize){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}}_scheduleSync(){this._rafId==null&&(this._rafId=globalThis.requestAnimationFrame(()=>{this._rafId=null,this._syncPosition();}));}_syncPosition(){if(!this._core||!this._rootEl||!this._selectedVideoNode||this._hiddenForDrag||this._hiddenForTransform||this._hiddenForZoom)return;if(!this._isVideoReady()){this._hiddenForNotReady=true,this._rootEl.style.display="none";return}this._hiddenForNotReady&&(this._hiddenForNotReady=false,this._rootEl.style.display="block");let e=this._core.nodes.world.scaleX(),t=this._options.maxWorldScaleToShow;if(t!=null&&e>=t){this._hiddenForWorldScale=true,this._rootEl.style.display="none";return}this._hiddenForWorldScale&&(this._hiddenForWorldScale=false,this._rootEl.style.display="block");let n=this._selectedVideoNode.getKonvaNode(),o=n.getClientRect?n.getClientRect({skipShadow:true,skipStroke:false}):null;if(!o)return;if(o.width<140||o.height<64){this._hiddenForSize=true,this._rootEl.style.display="none";return}let l=e,h=o.width<260||o.height<110||l<.55?"mini":o.width<340||o.height<135||l<.75?"compact":"full";this._applyUiMode(h),this._hiddenForSize&&(this._hiddenForSize=false,this._rootEl.style.display="block");let c=this._core.stage.container(),d=c.clientWidth,u=c.clientHeight;if(this._rootEl.style.left="0px",this._rootEl.style.top="0px",this._rootEl.style.width=String(d)+"px",this._rootEl.style.height=String(u)+"px",this._controlsEl){let m=o.width/360,_=this._uiMode==="full"?.75:this._uiMode==="compact"?.68:.6,b=Math.max(_,Math.min(1,m));this._controlsEl.style.transform="scale("+String(b)+")";let w=Math.max(64,Math.min(240,o.height))/240,x=Math.max(10,Math.min(28,28*w)),N=Math.max(4,Math.min(10,10*w)),k=this._controlsEl.getBoundingClientRect(),S=k.width,C=k.height,T=o.y+o.height+x+N,K=o.y-x-N-C,L=Math.max(0,u-C-this._options.marginPx),B=T;T>L&&K>=0&&(B=K),B=Math.max(this._options.marginPx,Math.min(L,B));let P=o.x+o.width/2,I=Math.max(0,d-S-this._options.marginPx),X=P-S/2;X=Math.max(this._options.marginPx,Math.min(I,X)),this._controlsEl.style.left=String(X)+"px",this._controlsEl.style.top=String(B)+"px",this._controlsEl.style.right="",this._controlsEl.style.bottom="";}let p=typeof n.cornerRadius=="function"?n.cornerRadius():0,f=0;if(Array.isArray(p)){let m=p[0];f=typeof m=="number"&&Number.isFinite(m)?m:0;}else f=typeof p=="number"&&Number.isFinite(p)?p:0;this._rootEl.style.borderRadius=String(Math.max(0,f))+"px";}_syncControls(){let e=this._selectedVideoEl;if(e){if(this._playBtn&&(this._playBtn.textContent=e.paused?"Play":"Pause"),this._muteBtn){let t=e.muted||e.volume<=0;this._muteBtn.textContent=t?"Muted":"Mute",this._muteBtn.style.color=t?this._options.uiMutedTextColor:this._options.uiTextColor;}if(this._seekInput){let t=Number.isFinite(e.duration)&&e.duration>0?e.duration:0,n=t>0?Math.max(0,Math.min(1,e.currentTime/t)):0;this._seekInput.max=String(t),this._seekInput.value=String(t>0?Math.max(0,Math.min(t,e.currentTime)):0),this._updateRangeFill(this._seekInput,n),this._timeLabel&&(this._timeLabel.textContent=this._formatTime(e.currentTime)+" / "+this._formatTime(t));}if(this._volInput&&(this._volInput.value=String(Math.max(0,Math.min(1,e.volume))),this._updateRangeFill(this._volInput,Math.max(0,Math.min(1,e.volume)))),this._speedBtn){let t=e.playbackRate;this._speedBtn.textContent=String(Math.round(t*100)/100)+"x";}}}_formatTime(e){let t=Number.isFinite(e)&&e>0?e:0,n=Math.floor(t),o=Math.floor(n/60),s=n%60,r=s<10?"0"+String(s):String(s);return String(o)+":"+r}_applyUiMode(e){this._controlsEl&&this._uiMode!==e&&(this._uiMode=e,this._timeLabel&&(this._timeLabel.style.display=e==="full"?"inline":"none"),this._volInput&&(this._volInput.style.display=e==="full"||e==="compact"?"block":"none"),this._speedBtn&&(this._speedBtn.style.display=e==="full"?"inline-flex":"none"),this._controlsEl.style.gap=e==="full"?"10px":"8px",this._controlsEl.style.padding=e==="full"?"8px 10px":"6px 8px",this._seekInput&&(this._seekInput.style.minWidth=e==="mini"?"80px":"120px"));}};var ye=class{constructor(){a(this,"_scheduled",false);}schedule(i){this._scheduled||(this._scheduled=true,globalThis.requestAnimationFrame(()=>{this._scheduled=false,i();}));}isScheduled(){return this._scheduled}cancel(){this._scheduled=false;}};var ht=class{constructor(i){a(this,"deps");this.deps=i;}ensure(i){this.deps.ensureTempMulti(i);}destroy(){this.deps.destroyTempMulti();}commitToPermanentGroup(){this.deps.commitTempMultiToGroup();}isActive(){return this.deps.isActive()}forceUpdateOverlays(){this.deps.forceUpdate();}onWorldChanged(){this.deps.onWorldChanged?this.deps.onWorldChanged():this.deps.forceUpdate();}isInsideTempByTarget(i){return this.deps.isInsideTempByTarget?this.deps.isInsideTempByTarget(i):false}};function Ee(y){if(y instanceof G.Group){let i=y.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false});return {x:i.x,y:i.y,width:i.width,height:i.height}}if(y instanceof G.Shape&&typeof y.getSelfRect=="function"){let i=y.getSelfRect();return {x:i.x,y:i.y,width:i.width,height:i.height}}return {x:0,y:0,width:y.width(),height:y.height()}}function Pe(y,i){let{x:e,y:t,width:n,height:o}=i;switch(y){case "top-left":return {x:e+n,y:t+o};case "top-right":return {x:e,y:t+o};case "bottom-right":return {x:e,y:t};case "bottom-left":return {x:e+n,y:t};case "middle-left":return {x:e+n,y:t+o/2};case "middle-right":return {x:e,y:t+o/2};case "top-center":return {x:e+n/2,y:t+o};case "bottom-center":return {x:e+n/2,y:t};default:return null}}function me(y,i,e,t=6){if(!y||!i||!e)return;let o=e instanceof G.Group&&typeof e.name=="function"&&e.name().includes("temp-multi-overlay")?e.findOne(".temp-multi-overlay-rect"):null,s=o?o.getClientRect({skipShadow:true,skipStroke:true}):e.getClientRect({skipShadow:true,skipStroke:false}),r=o?o.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}):e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),l=e.getAbsoluteScale(),h=Math.abs(l.x)||1,c=Math.abs(l.y)||1,d=r.width*h,u=r.height*c,p=(()=>{let v=e.getAbsoluteTransform().decompose();return typeof v.rotation=="number"?v.rotation:0})(),f=Math.abs((p%180+180)%180)>.5,g=i.findOne(".top-center"),m=i.findOne(".middle-right"),_=i.findOne(".bottom-center"),b=i.findOne(".middle-left");if(g){let v=f?d:s.width,w=t;g.setAttrs({opacity:0,width:v,height:w,offsetX:v/2,offsetY:0});}if(_){let v=f?d:s.width,w=t;_.setAttrs({opacity:0,width:v,height:w,offsetX:v/2,offsetY:w});}if(b){let v=t,w=f?u:s.height;b.setAttrs({opacity:0,width:v,height:w,offsetX:0,offsetY:w/2});}if(m){let v=t,w=f?u:s.height;m.setAttrs({opacity:0,width:v,height:w,offsetX:v,offsetY:w/2});}}function pe(y){return new G.Circle({name:y,radius:4,width:25,height:25,fill:"#ffffff",stroke:"#2b83ff",strokeWidth:1.5,opacity:0,hitStrokeWidth:16,draggable:true,dragOnTop:true,listening:true,cursor:"pointer"})}var ut=class{constructor(i){a(this,"core");a(this,"getKonvaNode");a(this,"getTransformer");a(this,"onUpdate");a(this,"setRotateCursor");a(this,"clearRotateCursor");a(this,"onRotateStart");a(this,"onRotateMove");a(this,"onRotateEnd");a(this,"group",null);a(this,"handles",{tl:null,tr:null,br:null,bl:null});a(this,"dragState",null);a(this,"centerAbsStart",null);a(this,"cursorSvgCache",null);this.core=i.core,this.getKonvaNode=i.getNode,this.getTransformer=i.getTransformer,i.onUpdate&&(this.onUpdate=i.onUpdate),i.setRotateCursor&&(this.setRotateCursor=i.setRotateCursor),i.clearRotateCursor&&(this.clearRotateCursor=i.clearRotateCursor),i.onRotateStart&&(this.onRotateStart=i.onRotateStart),i.onRotateMove&&(this.onRotateMove=i.onRotateMove),i.onRotateEnd&&(this.onRotateEnd=i.onRotateEnd);}attach(){if(!this.getKonvaNode())return;let e=this.core.nodes.layer;this.detach();let t=new G.Group({name:"rotate-handles-group",listening:true});e.add(t),this.group=t;let n=pe("rotate-tl"),o=pe("rotate-tr"),s=pe("rotate-br"),r=pe("rotate-bl");t.add(n),t.add(o),t.add(s),t.add(r),this.handles={tl:n,tr:o,br:s,bl:r};let l=h=>{h.on("mouseenter.rotate",()=>{let c=this.getKonvaNode();if(!c){this.core.stage.container().style.cursor="pointer";return}let d=this.getNodeCenterAbs(c),u=h.getAbsolutePosition(),p=u.x-d.x,f=u.y-d.y,_=Math.atan2(f,p)*180/Math.PI+45;this.setRotateCursor?this.setRotateCursor(_):this.applyRotatedCursor(_);}),h.on("mouseleave.rotate",()=>{this.clearRotateCursor?this.clearRotateCursor():this.core.stage.container().style.cursor="default";}),h.on("dragstart.rotate",()=>{let c=this.getKonvaNode();if(!c)return;let d=c.getAbsoluteTransform().decompose();this.centerAbsStart=this.getNodeCenterAbs(c);let u=this.core.stage.getPointerPosition()??h.getAbsolutePosition(),p=Math.atan2(u.y-this.centerAbsStart.y,u.x-this.centerAbsStart.x)*180/Math.PI;this.dragState={base:d.rotation||0,start:p};let f=p+90;this.setRotateCursor?this.setRotateCursor(f):this.applyRotatedCursor(f),this.getTransformer()?.moveToTop(),this.placeBelowTransformer(),this.onRotateStart&&this.onRotateStart(),c.fire("rotate:start");}),h.on("dragmove.rotate",c=>{let d=this.getKonvaNode();if(!d||!this.dragState)return;let u=this.centerAbsStart??this.getNodeCenterAbs(d),p=this.core.stage.getPointerPosition()??h.getAbsolutePosition(),f=Math.atan2(p.y-u.y,p.x-u.x)*180/Math.PI,g=this.dragState.base+(f-this.dragState.start),m=f+45;this.setRotateCursor?this.setRotateCursor(m):this.applyRotatedCursor(m);let _=this.getTransformer();if(c.evt.shiftKey&&_){let v=k=>{let S=k%360;return S<0&&(S+=360),S},w=(k,S)=>v(k-S+180)-180,x=Array.isArray(_.rotationSnaps())?_.rotationSnaps().map(k=>v(k)):void 0,N=typeof _.rotationSnapTolerance=="function"?_.rotationSnapTolerance():5;if(x?.length){let k=v(g),S=g,C=1/0;for(let T of x){let K=Math.abs(w(k,T));K<C&&K<=N&&(S=T,C=K);}C!==1/0&&(g=S);}}if(d.rotation(g),this.centerAbsStart){let v=this.getNodeCenterAbs(d),w=this.centerAbsStart.x-v.x,x=this.centerAbsStart.y-v.y,N=d.getParent();if(N){let k=N.getAbsoluteTransform().copy().invert(),S=k.point({x:v.x,y:v.y}),C=k.point({x:v.x+w,y:v.y+x}),T=d.x()+(C.x-S.x),K=d.y()+(C.y-S.y);d.position({x:T,y:K});}}let b=this.getTransformer();b?.forceUpdate(),b&&me(this.core,b,d),this.updatePosition(),this.placeBelowTransformer(),this.core.nodes.layer.batchDraw(),this.onUpdate&&this.onUpdate(),this.onRotateMove&&this.onRotateMove(),d.fire("rotate:move");}),h.on("dragend.rotate",()=>{this.dragState=null,this.centerAbsStart=null,this.core.stage.draggable(false),this.updatePosition(),this.placeBelowTransformer();let c=this.core.stage.container();c.style.cursor="grab",this.onUpdate&&this.onUpdate();let d=this.getKonvaNode();this.onRotateEnd&&this.onRotateEnd(),d&&d.fire("rotate:end");});};l(n),l(o),l(s),l(r),this.updatePosition(),this.placeBelowTransformer();}applyRotatedCursor(i){let e=this.core.stage.container(),t=(i%360+360)%360;if(this.cursorSvgCache?.angle===t){e.style.cursor=this.cursorSvgCache.url;return}let n=`
4
4
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
5
5
  <g transform="rotate(${t.toString()} 12 12)">
6
6
  <g clip-path="url(#clip0_36_31)">
@@ -54,7 +54,7 @@ import H from'konva';var Ot=Object.defineProperty;var It=(S,i,e)=>i in S?Ot(S,i,
54
54
  </defs>
55
55
  </g>
56
56
  </svg>
57
- `.trim(),r=`url("data:image/svg+xml,${encodeURIComponent(o)}") 12 12, grab`;e.style.cursor=r,this.cursorSvgCache={angle:t,url:r};}detach(){this.group&&(this.group.destroy(),this.group=null),this.handles={tl:null,tr:null,br:null,bl:null},this.dragState=null,this.centerAbsStart=null;}moveToTop(){this.placeBelowTransformer();}updatePosition(){let i=this.getKonvaNode();if(!i||!this.group)return;let e=i.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),t=e.width,o=e.height;if(t<=0||o<=0)return;let n=i.getAbsoluteTransform().copy(),r=N=>n.point(N),s=12,l=r({x:e.x+t/2,y:e.y+o/2}),h=r({x:e.x,y:e.y}),p=r({x:e.x+t,y:e.y}),d=r({x:e.x+t,y:e.y+o}),c=r({x:e.x,y:e.y+o}),u=N=>{let x=N.x-l.x,k=N.y-l.y,C=Math.hypot(x,k)||1;return {x:x/C,y:k/C}},f=u(h),g=u(p),_=u(d),m=u(c),b={x:h.x+f.x*s,y:h.y+f.y*s},v={x:p.x+g.x*s,y:p.y+g.y*s},w={x:d.x+_.x*s,y:d.y+_.y*s},y={x:c.x+m.x*s,y:c.y+m.y*s};this.handles.tl&&this.handles.tl.absolutePosition(b),this.handles.tr&&this.handles.tr.absolutePosition(v),this.handles.br&&this.handles.br.absolutePosition(w),this.handles.bl&&this.handles.bl.absolutePosition(y),this.placeBelowTransformer();}placeBelowTransformer(){if(!this.group)return;let i=this.getTransformer(),e=this.core.nodes.layer;if(i&&i.getLayer()===e){let t=i.zIndex(),o=this.group.zIndex();if(o>=t){let n=o-t+1;for(let r=0;r<n&&this.group.zIndex()>0;r++)this.group.moveDown();}}else this.group.moveToBottom();}getNodeCenterAbs(i){let e=i.getAbsoluteTransform().copy(),t=i.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),o=t.x+t.width/2,n=t.y+t.height/2;return e.point({x:o,y:n})}};var He=class{constructor(i){a(this,"core");a(this,"tr",null);a(this,"sizeLabel",null);a(this,"rotateGroup",null);a(this,"rotateCtrl",null);a(this,"keepRatioPredicate",null);a(this,"boundNode",null);a(this,"hitRect",null);a(this,"transformOppositeCorner",null);a(this,"trWasVisibleBeforeDrag",false);a(this,"labelWasVisibleBeforeDrag",false);a(this,"rotateWasVisibleBeforeDrag",false);a(this,"rotateCtrlWasAttachedBeforeDrag",false);this.core=i;}attach(i,e){this.detach(),this.boundNode=i,this.keepRatioPredicate=e?.keepRatioCornerOnlyShift??null;let t=this.core.nodes.layer,o=new H.Transformer({rotateEnabled:false,keepRatio:false,rotationSnapTolerance:15,rotationSnaps:[0,15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240,255,270,285,300,315,330,345,360],enabledAnchors:["top-left","top-center","top-right","middle-left","middle-right","bottom-left","bottom-center","bottom-right"],borderEnabled:true,borderStroke:"#2b83ff",borderStrokeWidth:1.5,name:"overlay-transformer"});t.add(o),o.nodes([i]),o.forceUpdate(),o.boundBoxFunc((s,l)=>{let p=Math.max(1,Math.abs(l.width)),d=Math.max(1,Math.abs(l.height));return {...l,width:p,height:d}}),this.tr=o,pe(this.core,o,i),globalThis.queueMicrotask(()=>{!this.tr||!this.boundNode||(this.tr.forceUpdate(),pe(this.core,this.tr,this.boundNode),this.core.nodes.layer.batchDraw());});let n=()=>{let s=typeof o.getActiveAnchor=="function"?o.getActiveAnchor():"",l=s==="top-left"||s==="top-right"||s==="bottom-left"||s==="bottom-right",h=this.keepRatioPredicate?this.keepRatioPredicate():false;o.keepRatio(l&&h);};o.on("transformstart.overlayKeepRatio",()=>{n();let l=(typeof o.getActiveAnchor=="function"?o.getActiveAnchor():"")??"",h=Se(i),p=Te(l,h);if(!p){this.transformOppositeCorner=null;return}let d=i.getAbsoluteTransform();this.transformOppositeCorner=d.point({x:p.x,y:p.y});}),o.on("transform.overlayKeepRatio",n);let r=()=>{if(this.boundNode){if(this.transformOppositeCorner){let l=(typeof o.getActiveAnchor=="function"?o.getActiveAnchor():"")??"",h=this.boundNode.getAbsoluteTransform(),p=Se(this.boundNode),d=Te(l,p);if(!d)return;let c=h.point({x:d.x,y:d.y}),u=this.transformOppositeCorner.x-c.x,f=this.transformOppositeCorner.y-c.y,g=this.boundNode.getParent();if(g&&(Math.abs(u)>.01||Math.abs(f)>.01)){let _=g.getAbsoluteTransform().copy().invert(),m=this.boundNode.getAbsolutePosition(),b={x:m.x+u,y:m.y+f},v=_.point(b);this.boundNode.position(v);}}this.tr?.forceUpdate(),pe(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),t.batchDraw();}};o.on("transform.overlayFrameTransform",r),o.on("transformend.overlayFrameTransform",()=>{this.transformOppositeCorner=null,r();}),this.ensureSizeLabel(),this.updateSizeLabel(),this.updateHitRect(),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null),this.rotateCtrl=new it({core:this.core,getNode:()=>this.boundNode,getTransformer:()=>this.tr,onUpdate:()=>{this.forceUpdate(),this.core.nodes.layer.batchDraw();}}),this.rotateCtrl.attach(),this.rotateCtrl.updatePosition(),this.tr.moveToTop(),t.batchDraw();}shiftTransformReferencePoint(i,e){this.transformOppositeCorner&&(this.transformOppositeCorner={x:this.transformOppositeCorner.x+i,y:this.transformOppositeCorner.y+e});}detach(){this.tr&&(this.tr.off(".overlayKeepRatio"),this.tr.off(".overlayFrameTransform"),this.tr.destroy(),this.tr=null),this.transformOppositeCorner=null,this.sizeLabel&&(this.sizeLabel.destroy(),this.sizeLabel=null),this.hitRect&&(this.hitRect.destroy(),this.hitRect=null),this.rotateGroup&&(this.rotateGroup.destroy(),this.rotateGroup=null),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null);}forceUpdate(){this.boundNode&&(this.tr?.forceUpdate(),pe(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),this.updateSizeLabel(),this.updateHitRect());}onWorldChanged(){this.forceUpdate();}hideOverlaysForDrag(){this.tr?(this.trWasVisibleBeforeDrag=this.tr.visible(),this.tr.visible(false)):this.trWasVisibleBeforeDrag=false,this.sizeLabel?(this.labelWasVisibleBeforeDrag=this.sizeLabel.visible(),this.sizeLabel.visible(false)):this.labelWasVisibleBeforeDrag=false,this.rotateGroup?(this.rotateWasVisibleBeforeDrag=this.rotateGroup.visible(),this.rotateGroup.visible(false)):this.rotateWasVisibleBeforeDrag=false,this.rotateCtrl?(this.rotateCtrlWasAttachedBeforeDrag=true,this.rotateCtrl.detach()):this.rotateCtrlWasAttachedBeforeDrag=false;}restoreOverlaysAfterDrag(){this.tr&&this.trWasVisibleBeforeDrag&&this.tr.visible(true),this.sizeLabel&&this.labelWasVisibleBeforeDrag&&this.sizeLabel.visible(true),this.rotateGroup&&this.rotateWasVisibleBeforeDrag&&this.rotateGroup.visible(true),this.rotateCtrl&&this.rotateCtrlWasAttachedBeforeDrag&&(this.rotateCtrl.attach(),this.rotateCtrl.updatePosition(),this.tr?.moveToTop()),this.trWasVisibleBeforeDrag=false,this.labelWasVisibleBeforeDrag=false,this.rotateWasVisibleBeforeDrag=false,this.rotateCtrlWasAttachedBeforeDrag=false,this.forceUpdate();}ensureSizeLabel(){let i=this.core.nodes.layer;this.sizeLabel&&this.sizeLabel.destroy();let e=new H.Label({listening:false,opacity:.95}),t=new H.Tag({fill:"#2b83ff",cornerRadius:4,lineJoin:"round"}),o=new H.Text({text:"",fontFamily:"Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",fontSize:12,fill:"#ffffff",padding:6,align:"center"});e.add(t),e.add(o),i.add(e),this.sizeLabel=e;}updateSizeLabel(){if(!this.boundNode||!this.sizeLabel)return;let i=this.core.nodes.world,e=this.boundNode.getClientRect({skipShadow:true,skipStroke:true}),t=e.width/Math.max(1e-6,i.scaleX()),o=e.height/Math.max(1e-6,i.scaleY()),n=Math.max(0,Math.round(t)),r=Math.max(0,Math.round(o));this.sizeLabel.getText().text(String(n)+" \xD7 "+String(r));let l=8,h=e.x+e.width/2,p=e.y+e.height+l,c=this.sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this.sizeLabel.setAttrs({x:h-c/2,y:p}),this.sizeLabel.moveToTop();}updateHitRect(){if(!this.boundNode)return;let i=this.core.nodes.layer,e=this.boundNode.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),t={x:e.x,y:e.y},o=e.width,n=e.height;if(!this.hitRect){let r=new H.Rect({name:"overlay-hit",x:t.x,y:t.y,width:o,height:n,fill:"rgba(0,0,0,0.001)",listening:true,perfectDrawEnabled:false});r.on("mousedown.overlayHit",s=>{if(s.evt.button!==0)return;s.cancelBubble=true;let l=this.boundNode;typeof l.startDrag=="function"&&l.startDrag();}),this.boundNode instanceof H.Container?(this.boundNode.add(r),r.moveToBottom(),this.hitRect=r,i.batchDraw()):r.destroy();return}this.hitRect.position(t),this.hitRect.size({width:o,height:n}),this.hitRect.moveToBottom();}};var ve=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_selected",null);a(this,"_prevDraggable",null);a(this,"_transformer",null);a(this,"_transformerWasVisibleBeforeDrag",false);a(this,"_cornerHandlesWereVisibleBeforeDrag",false);a(this,"_sizeLabelWasVisibleBeforeDrag",false);a(this,"_rotateHandlesWereVisibleBeforeDrag",false);a(this,"_cornerHandlesGroup",null);a(this,"_cornerHandles",{tl:null,tr:null,br:null,bl:null});a(this,"_cornerHandlesSuppressed",false);a(this,"_transformOppositeCorner",null);a(this,"_isTransforming",false);a(this,"_sizeLabel",null);a(this,"_radiusLabel",null);a(this,"_rotateHandlesGroup",null);a(this,"_rotateHandles",{tl:null,tr:null,br:null,bl:null});a(this,"_rotateDragState",null);a(this,"_rotateCenterAbsStart",null);a(this,"_prevStageDraggableBeforeRotate",null);a(this,"_worldSyncRafId",null);a(this,"_onCameraZoomEvent",null);a(this,"_hoverTr",null);a(this,"_isPointerDown",false);a(this,"_autoPanRafId",null);a(this,"_autoPanActive",false);a(this,"_autoPanEdgePx");a(this,"_autoPanMaxSpeedPx");a(this,"_draggingNode",null);a(this,"_tempMultiTransformingGroup",null);a(this,"_ratioKeyPressed",false);a(this,"_onGlobalKeyDown",null);a(this,"_onGlobalKeyUp",null);a(this,"_tempMultiSet",new Set);a(this,"_tempMultiNodes",[]);a(this,"_tempMultiInitialTransforms",new Map);a(this,"_tempMultiGroup",null);a(this,"_tempOverlay",null);a(this,"_multiCtrl",null);a(this,"_parentGroupDuringChildEdit",null);a(this,"_parentGroupPrevDraggable",null);a(this,"_dragMoveScheduled",false);a(this,"_batchDrawScheduled",false);a(this,"_hoverThrottle",new ge(16));a(this,"_uiUpdateDebounce",new me);a(this,"_onMouseDown",e=>{if(!this._core||e.evt.button!==0)return;let t=this._core.stage,o=this._core.nodes.layer;if(e.target===t||e.target.getLayer()!==o){let v=false;if(this._selected){let w=t.getPointerPosition();if(w){let y=this._selected.getKonvaNode(),N=y.getClientRect({skipShadow:true,skipStroke:false});if(w.x>=N.x&&w.x<=N.x+N.width&&w.y>=N.y&&w.y<=N.y+N.height&&(v=true,typeof y.startDrag=="function")){let k=y,C=3,P=e.evt.clientX,R=e.evt.clientY,L=typeof k.draggable=="function"?k.draggable():false,A=t.draggable(),E=false,O=X=>{let re=Math.abs(X.evt.clientX-P),F=Math.abs(X.evt.clientY-R);!E&&(re>C||F>C)&&(E=true,typeof k.draggable=="function"&&!L&&k.draggable(true),y.on("dragstart.selection-once-bbox",()=>{t.draggable(false);}),y.on("dragend.selection-once-bbox",()=>{t.draggable(A),typeof k.draggable=="function"&&k.draggable(this._options.dragEnabled?true:L),this._selected&&(this._refreshTransformer(),this._core?.nodes.layer.batchDraw()),y.off(".selection-once-bbox");}),y.startDrag(),e.cancelBubble=true);},j=()=>{!E&&this._options.deselectOnEmptyClick&&this._clearSelection(),t.off("mousemove.selection-once-bbox"),t.off("mouseup.selection-once-bbox");};t.on("mousemove.selection-once-bbox",O),t.on("mouseup.selection-once-bbox",j);}}}v||this._options.deselectOnEmptyClick&&this._clearSelection();return}let n=e.target;if(!this._options.selectablePredicate(n))return;let r=this._findBaseNodeByTarget(n);if(!r)return;let s=r,l=this._selected;if(l){let v=l.getKonvaNode();((y,N)=>{let x=N;for(;x;){if(x===y)return true;x=x.getParent();}return false})(v,n)&&(s=l);}let h=s.getKonvaNode();h instanceof H.Group&&this._disableGroupChildrenDragging(h);let p=3,d=e.evt.clientX,c=e.evt.clientY,u=false,f=v=>{if(u)return;let w=Math.abs(v.evt.clientX-d),y=Math.abs(v.evt.clientY-c);(w>p||y>p)&&(u=true,typeof h.startDrag=="function"&&h.startDrag(),this._core?.stage.off("mousemove.selection-once"),this._core?.stage.off("mouseup.selection-once"));},g=()=>{this._core?.stage.off("mousemove.selection-once"),this._core?.stage.off("mouseup.selection-once");};if(this._core.stage.on("mousemove.selection-once",f),this._core.stage.on("mouseup.selection-once",g),typeof h.isDragging=="function"&&h.isDragging())return;let _=typeof h.draggable=="function",m=_?h.draggable():false,b=t.draggable();_&&h.draggable(true),h.on("dragstart.selection-once",()=>{t.draggable(false);}),h.on("dragend.selection-once",()=>{t.draggable(b),_&&(this._options.dragEnabled?h.draggable(true):h.draggable(m)),this._select(s);});});a(this,"_onHoverMoveThrottled",e=>{this._hoverThrottle.shouldExecute()&&this._onHoverMove(e);});a(this,"_onHoverMove",e=>{if(!this._core)return;let t=this._core.stage,o=this._core.nodes.layer,n=e.target;if((()=>{if(!!!this._tempMultiGroup){let v=n;for(;v;){if(v instanceof H.Group&&typeof v.name=="function"){let w=v.name();if(typeof w=="string"&&(w.includes("temp-multi-group")||w.includes("area-temp-group")))return true}v=v.getParent();}return false}let b=n;for(;b;){if(b===this._tempMultiGroup)return true;b=b.getParent();}return false})()){this._destroyHoverTr();return}let s=typeof e.evt.buttons=="number"?e.evt.buttons:0;if(this._isPointerDown||s&1){this._destroyHoverTr();return}if(n===t||n.getLayer()!==o){this._destroyHoverTr();return}let l=this._core.nodes.list().map(m=>m.getKonvaNode()),h=new Set(l),p=m=>{let b=m;for(;b;){if(h.has(b))return b;b=b.getParent();}return null},c=(m=>{let b=m,v=null;for(;b;)h.has(b)&&b instanceof H.Group&&(v=b),b=b.getParent();return v})(n),u=p(n),f=e.evt.ctrlKey,g=f?u??c:c??u;if(!f&&this._selected&&u&&!(this._selected.getKonvaNode()instanceof H.Group)){let m=this._selected.getKonvaNode();c&&((v,w,y)=>{if(!y)return false;let N=(x,k)=>{let C=k;for(;C;){if(C===x)return true;C=C.getParent();}return false};return N(y,v)&&N(y,w)})(m,u,c)&&m!==u&&(g=u);}if(!g){this._destroyHoverTr();return}if(!this._options.selectablePredicate(g)){this._destroyHoverTr();return}if(this._selected){let m=this._selected.getKonvaNode();if(f?g===m:g===m||((w,y)=>{let N=y;for(;N;){if(N===w)return true;N=N.getParent();}return false})(m,g)){this._destroyHoverTr();return}}let _=this._ensureHoverTr();_.nodes([g]),_.visible(true),_.moveToTop(),o.batchDraw();});a(this,"_onHoverDown",()=>{this._isPointerDown=true,this._destroyHoverTr();});a(this,"_onHoverUp",()=>{this._isPointerDown=false;});a(this,"_onHoverLeave",e=>{this._destroyHoverTr();});a(this,"_onNodeRemoved",e=>{this._selected&&this._selected===e&&this._clearSelection();});let{dragEnabled:t=true,enableTransformer:o=true,deselectOnEmptyClick:n=true,selectablePredicate:r}=e;if(this._options={dragEnabled:t,enableTransformer:o,deselectOnEmptyClick:n,selectablePredicate:r??(()=>true),autoPanEnabled:e.autoPanEnabled??true,autoPanEdgePx:e.autoPanEdgePx??40,autoPanMaxSpeedPx:e.autoPanMaxSpeedPx??24,enableVideoOverlay:e.enableVideoOverlay??false},e.enableVideoOverlay){let s=typeof e.enableVideoOverlay=="object"?e.enableVideoOverlay:{};this.addons.add(new De(s));}this._autoPanEdgePx=this._options.autoPanEdgePx,this._autoPanMaxSpeedPx=this._options.autoPanMaxSpeedPx;}getMultiGroupController(){if(!this._core)throw new Error("Core is not attached");return this._multiCtrl??(this._multiCtrl=new nt({ensureTempMulti:e=>{this._ensureTempMulti(e);},destroyTempMulti:()=>{this._destroyTempMulti();},commitTempMultiToGroup:()=>{this._commitTempMultiToGroup();},isActive:()=>!!this._tempMultiGroup||this._tempMultiSet.size>0,forceUpdate:()=>{this._tempOverlay?.forceUpdate();},onWorldChanged:()=>{this._tempOverlay?.onWorldChanged();},isInsideTempByTarget:e=>this._tempMultiGroup?e===this._tempMultiGroup?true:e.isAncestorOf(this._tempMultiGroup)||this._tempMultiGroup.isAncestorOf(e):false})),this._multiCtrl}_startAutoPanLoop(){if(!this._core||this._autoPanRafId!=null)return;this._autoPanActive=true;let e=this._core.nodes.world,t=this._core.stage,o=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let n=t.getPointerPosition();if(n){let r=t.width(),s=t.height(),l=this._autoPanEdgePx,h=0,p=0,d=Math.max(0,l-n.x),c=Math.max(0,n.x-(r-l)),u=Math.max(0,l-n.y),f=Math.max(0,n.y-(s-l)),g=_=>Math.min(1,_/l);if(h=this._autoPanMaxSpeedPx*(g(c)-g(d)),p=this._autoPanMaxSpeedPx*(g(f)-g(u)),h!==0||p!==0){if(e.x(e.x()-h),e.y(e.y()-p),this._isTransforming&&this._transformOppositeCorner&&(this._transformOppositeCorner={x:this._transformOppositeCorner.x-h,y:this._transformOppositeCorner.y-p}),this._tempMultiTransformingGroup&&this._tempOverlay&&this._tempOverlay.shiftTransformReferencePoint(-h,-p),this._draggingNode&&typeof this._draggingNode.setAbsolutePosition=="function"){let _=this._draggingNode.getAbsolutePosition();this._draggingNode.setAbsolutePosition({x:_.x+h,y:_.y+p}),this._transformer?.forceUpdate();}if(this._isTransforming){let _=t.getPointerPosition();if(_){let m=t.container(),b=m.getBoundingClientRect();try{m.dispatchEvent(new MouseEvent("mousemove",{bubbles:!0,cancelable:!0,clientX:b.left+_.x,clientY:b.top+_.y}));}catch{}}}if(this._tempMultiTransformingGroup){let _=t.getPointerPosition();if(_){let m=t.container(),b=m.getBoundingClientRect();try{m.dispatchEvent(new MouseEvent("mousemove",{bubbles:!0,cancelable:!0,clientX:b.left+_.x,clientY:b.top+_.y}));}catch{}}}this._core.nodes.layer.batchDraw();}}this._autoPanRafId=globalThis.requestAnimationFrame(o);};this._autoPanRafId=globalThis.requestAnimationFrame(o);}_stopAutoPanLoop(){this._autoPanActive=false,this._autoPanRafId!=null&&(globalThis.cancelAnimationFrame(this._autoPanRafId),this._autoPanRafId=null);}_scheduleBatchDraw(){if(this._batchDrawScheduled)return;this._batchDrawScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._batchDrawScheduled=false,this._core?.stage.batchDraw();});}setOptions(e){this._options={...this._options,...e},this._core&&this._refreshTransformer(),typeof e.autoPanEdgePx=="number"&&(this._autoPanEdgePx=e.autoPanEdgePx),typeof e.autoPanMaxSpeedPx=="number"&&(this._autoPanMaxSpeedPx=e.autoPanMaxSpeedPx),e.autoPanEnabled===false&&this._stopAutoPanLoop();}onAttach(e){this._core=e;let t=e.stage;t.on("mousedown.selection",this._onMouseDown),t.on("click.selection",s=>{if(!this._core)return;let l=this._core.stage,h=this._core.nodes.layer;if(s.evt.button!==0)return;if(s.target===l||s.target.getLayer()!==h){if(!!l.getAttr("_skipSelectionEmptyClickOnce")){l.setAttr("_skipSelectionEmptyClickOnce",false),s.cancelBubble=true;return}this._options.deselectOnEmptyClick&&(this._destroyTempMulti(),this._clearSelection());return}let p=s.target;if(!this._options.selectablePredicate(p))return;if(s.evt.shiftKey||s.evt.ctrlKey||s.evt.metaKey){let c=this._findBaseNodeByTarget(p);if(!c)return;let f=c.getKonvaNode().getParent();if(f&&f instanceof H.Group&&f!==this._core.nodes.world)return;if(this._tempMultiSet.size===0&&this._selected&&this._selected!==c&&(this._tempMultiSet.add(this._selected),this._transformer&&(this._transformer.destroy(),this._transformer=null),this._destroyCornerRadiusHandles(),this._destroyRotateHandles(),this._destroySizeLabel(),this._selected=null),Array.from(this._tempMultiSet).includes(c)?this._tempMultiSet.delete(c):this._tempMultiSet.add(c),this._tempMultiSet.size===0){this._destroyTempMulti(),this._clearSelection();return}if(this._tempMultiSet.size===1){let _=this._tempMultiSet.values().next(),m=_.done?void 0:_.value;m&&(this._destroyTempMulti(),this._select(m),this._scheduleBatchDraw());return}this._ensureTempMulti(Array.from(this._tempMultiSet)),this._scheduleBatchDraw();return}let d=this._findBaseNodeByTarget(p);d&&(this._destroyTempMulti(),this._select(d),this._scheduleBatchDraw());}),t.on("dblclick.selection",s=>{if(!this._core)return;let l=this._core.nodes.layer;if(s.target===t||s.target.getLayer()!==l||s.evt.button!==0||!this._selected)return;let h=this._selected.getKonvaNode();if(h instanceof H.Group&&typeof h.isAncestorOf=="function"&&h.isAncestorOf(s.target)){s.cancelBubble=true;let p=null;for(let d of this._core.nodes.list()){let c=d.getKonvaNode();if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(c)&&c!==h&&typeof c.isAncestorOf=="function"&&c.isAncestorOf(s.target)){let u=true;for(let f of this._core.nodes.list()){if(f===d)continue;let g=f.getKonvaNode();if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(g)&&typeof c.isAncestorOf=="function"&&c.isAncestorOf(g)&&typeof g.isAncestorOf=="function"&&g.isAncestorOf(s.target)){u=false;break}}if(u){p=d;break}}}if(p??(p=this._core.nodes.list().find(d=>d.getKonvaNode()===s.target)??null),p){this._select(p);let d=p.getKonvaNode();typeof d.draggable=="function"&&d.draggable(true),h instanceof H.Group&&(this._parentGroupDuringChildEdit=h,this._parentGroupPrevDraggable=typeof h.draggable=="function"?h.draggable():null,typeof h.draggable=="function"&&h.draggable(false)),this._core.stage.batchDraw();}}}),e.eventBus.on("node:removed",this._onNodeRemoved),t.on("mousemove.hover",this._onHoverMoveThrottled),t.on("mouseleave.hover",this._onHoverLeave),t.on("mousedown.hover",this._onHoverDown),t.on("mouseup.hover",this._onHoverUp),t.on("touchstart.hover",this._onHoverDown),t.on("touchend.hover",this._onHoverUp),this._core.nodes.layer.on("dragstart.hover",()=>{this._destroyHoverTr();}),this._core.nodes.layer.on("dragmove.hover",()=>{this._destroyHoverTr();});let o=this._core.nodes.layer;o.on("dragstart.selectionAutoPan",s=>{if(!this._options.autoPanEnabled)return;let l=s.target,h=l.getParent(),p=u=>u&&typeof u.name=="function"&&u.name()||"",d=p(l),c=p(h);d.startsWith("rotate-")||c==="rotate-handles-group"||this._options.selectablePredicate(l)&&(this._draggingNode=l,this._startAutoPanLoop());}),o.on("dragend.selectionAutoPan",()=>{this._draggingNode=null,this._stopAutoPanLoop();});let n=this._core.nodes.world,r=()=>{this._core&&this._worldSyncRafId==null&&(this._worldSyncRafId=globalThis.requestAnimationFrame(()=>{this._worldSyncRafId=null,this._core&&((this._transformer||this._cornerHandlesGroup||this._rotateHandlesGroup||this._sizeLabel||this._tempMultiGroup)&&(this._transformer?.forceUpdate(),this._hoverTr?.forceUpdate(),this._restyleSideAnchors(),this._updateCornerRadiusHandlesPosition(),this._updateRotateHandlesPosition(),this._updateSizeLabel(),this._updateCornerRadiusHandlesVisibility(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw()),this._destroyHoverTr());}));};n.on("xChange.selectionCamera yChange.selectionCamera scaleXChange.selectionCamera scaleYChange.selectionCamera",r),this._onCameraZoomEvent=()=>{r();},e.eventBus.on("camera:zoom",this._onCameraZoomEvent),e.eventBus.on("camera:setZoom",this._onCameraZoomEvent),e.eventBus.on("camera:reset",this._onCameraZoomEvent),this._onGlobalKeyDown=s=>{s.key==="Shift"&&(this._ratioKeyPressed=true);let l=s.ctrlKey||s.metaKey;l&&!s.shiftKey&&s.code==="KeyG"&&(s.preventDefault(),this._commitTempMultiToGroup()),l&&s.shiftKey&&s.code==="KeyG"&&(s.preventDefault(),this._tryUngroupSelectedGroup());},this._onGlobalKeyUp=s=>{s.key==="Shift"&&(this._ratioKeyPressed=false);},globalThis.addEventListener("keydown",this._onGlobalKeyDown),globalThis.addEventListener("keyup",this._onGlobalKeyUp);}onDetach(e){this._destroyTempMulti(),this._clearSelection(),e.stage.off(".selection"),e.stage.off(".hover"),this._core?.nodes.layer.off(".hover"),this._core?.nodes.world.off(".selectionCamera"),this._core?.nodes.layer.off(".selectionAutoPan"),this._worldSyncRafId!=null&&(globalThis.cancelAnimationFrame(this._worldSyncRafId),this._worldSyncRafId=null),this._onCameraZoomEvent&&(e.eventBus.off("camera:zoom",this._onCameraZoomEvent),e.eventBus.off("camera:setZoom",this._onCameraZoomEvent),e.eventBus.off("camera:reset",this._onCameraZoomEvent),this._onCameraZoomEvent=null),e.eventBus.off("node:removed",this._onNodeRemoved),this._destroyHoverTr(),this._onGlobalKeyDown&&globalThis.removeEventListener("keydown",this._onGlobalKeyDown),this._onGlobalKeyUp&&globalThis.removeEventListener("keyup",this._onGlobalKeyUp),this._onGlobalKeyDown=null,this._onGlobalKeyUp=null;}_select(e){if(!this._core)return;let t=this._core;this._clearSelection();let o=e.getKonvaNode();this._prevDraggable=o.draggable(),this._options.dragEnabled&&typeof o.draggable=="function"&&o.draggable(true),o instanceof H.Group&&this._disableGroupChildrenDragging(o),this._selected=e,this._refreshTransformer(),t.eventBus.emit("node:selected",e),o.on("dragstart.selection",()=>{this._draggingNode=o,this._transformer&&(this._transformerWasVisibleBeforeDrag=this._transformer.visible(),this._transformer.visible(false)),this._cornerHandlesGroup&&(this._cornerHandlesWereVisibleBeforeDrag=this._cornerHandlesGroup.visible(),this._cornerHandlesGroup.visible(false)),this._rotateHandlesGroup&&(this._rotateHandlesWereVisibleBeforeDrag=this._rotateHandlesGroup.visible(),this._rotateHandlesGroup.visible(false)),this._sizeLabel&&(this._sizeLabelWasVisibleBeforeDrag=this._sizeLabel.visible(),this._sizeLabel.visible(false)),this._core?.stage.batchDraw(),this._startAutoPanLoop();}),o.on("dragmove.selection",()=>{if(this._dragMoveScheduled)return;this._dragMoveScheduled=true;let n=globalThis.requestAnimationFrame;n(()=>{this._dragMoveScheduled=false,this._scheduleBatchDraw();});}),o.on("dragend.selection",()=>{let n={};typeof o.x=="function"&&(n.x=o.x()),typeof o.y=="function"&&(n.y=o.y()),typeof o.width=="function"&&(n.width=o.width()),typeof o.height=="function"&&(n.height=o.height()),typeof o.rotation=="function"&&(n.rotation=o.rotation()),typeof o.scaleX=="function"&&(n.scaleX=o.scaleX()),typeof o.scaleY=="function"&&(n.scaleY=o.scaleY()),t.eventBus.emit("node:transformed",e,n);}),o.on("transformend.selection",()=>{let n={};typeof o.x=="function"&&(n.x=o.x()),typeof o.y=="function"&&(n.y=o.y()),typeof o.width=="function"&&(n.width=o.width()),typeof o.height=="function"&&(n.height=o.height()),typeof o.rotation=="function"&&(n.rotation=o.rotation()),typeof o.scaleX=="function"&&(n.scaleX=o.scaleX()),typeof o.scaleY=="function"&&(n.scaleY=o.scaleY()),this._core?.eventBus.emit("node:transformed",e,n);}),o.on("dragend.selection",()=>{this._draggingNode=null,this._transformer&&(this._transformerWasVisibleBeforeDrag&&this._transformer.visible(true),this._transformerWasVisibleBeforeDrag=false),this._cornerHandlesGroup&&(this._cornerHandlesWereVisibleBeforeDrag&&this._cornerHandlesGroup.visible(true),this._cornerHandlesWereVisibleBeforeDrag=false),this._rotateHandlesGroup&&(this._rotateHandlesWereVisibleBeforeDrag&&this._rotateHandlesGroup.visible(true),this._rotateHandlesWereVisibleBeforeDrag=false),this._sizeLabel&&(this._sizeLabelWasVisibleBeforeDrag&&this._sizeLabel.visible(true),this._sizeLabelWasVisibleBeforeDrag=false),this._stopAutoPanLoop(),this._select(e),this._core?.stage.batchDraw();}),o.on("mousedown.selection",n=>{let r=n.evt.button;(r===1||r===2)&&typeof o.draggable=="function"&&o.draggable(false);});}_clearSelection(){if(!this._selected)return;let e=this._selected,t=this._selected.getKonvaNode();if(typeof t.draggable=="function"&&this._prevDraggable!==null&&t.draggable(this._prevDraggable),this._prevDraggable=null,this._parentGroupDuringChildEdit){let o=this._parentGroupDuringChildEdit;typeof o.draggable=="function"&&this._parentGroupPrevDraggable!==null&&o.draggable(this._parentGroupPrevDraggable),this._parentGroupDuringChildEdit=null,this._parentGroupPrevDraggable=null;}t.off(".selection"),t.off(".selection-once"),this._destroyCornerRadiusHandles(),this._destroyRotateHandles(),this._destroySizeLabel(),this._transformer&&(this._transformer.destroy(),this._transformer=null),this._selected=null,this._core&&(this._core.eventBus.emit("node:deselected",e),this._core.eventBus.emit("selection:cleared")),this._core?.stage.batchDraw();}_applyOverlayTransformToNodes(e,t){if(!this._core)return;let n=this._core.nodes.world.getAbsoluteTransform().copy(),s=n.copy().invert().multiply(e.getAbsoluteTransform().copy()),l=t.copy();l.invert();let h=s.multiply(l);for(let p of this._tempMultiNodes){let d=this._tempMultiInitialTransforms.get(p);if(!d)continue;let c=h.copy().multiply(d),u=n.copy().multiply(c),f=p.getParent();if(!f)continue;let g=f.getAbsoluteTransform().copy();g.invert();let m=g.multiply(u).decompose();typeof p.position=="function"&&p.position({x:m.x,y:m.y}),typeof p.rotation=="function"&&p.rotation(m.rotation),typeof p.scale=="function"&&p.scale({x:m.scaleX,y:m.scaleY});}}_updateTempMultiOverlayBBox(){if(!this._core||!this._tempMultiGroup)return;let e=this._computeUnionBBox(Array.from(this._tempMultiSet));if(!e)return;this._tempMultiGroup.position({x:e.x,y:e.y});let t=this._tempMultiGroup.findOne(".temp-multi-overlay-rect");t&&t.size({width:e.width,height:e.height});}_computeUnionBBox(e){if(e.length===0||!this._core)return null;let t=this._core.nodes.world,o=1/0,n=1/0,r=-1/0,s=-1/0;for(let l of e){let p=l.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false}),d=t.getAbsoluteTransform().copy().invert(),c=[d.point({x:p.x,y:p.y}),d.point({x:p.x+p.width,y:p.y}),d.point({x:p.x+p.width,y:p.y+p.height}),d.point({x:p.x,y:p.y+p.height})];for(let u of c)o=Math.min(o,u.x),n=Math.min(n,u.y),r=Math.max(r,u.x),s=Math.max(s,u.y);}return !isFinite(o)||!isFinite(n)||!isFinite(r)||!isFinite(s)?null:{x:o,y:n,width:r-o,height:s-n}}_ensureTempMulti(e){if(!this._core)return;let t=this._core.nodes.world,o=this._core.nodes.layer;this._tempMultiSet.clear();for(let c of e)this._tempMultiSet.add(c);let n=e.map(c=>c.getKonvaNode());if(this._tempMultiGroup&&this._tempMultiNodes.length>0){if(this._tempMultiNodes.length===n.length&&n.every(u=>this._tempMultiNodes.includes(u)))return;this._destroyTempMultiOverlayOnly(),this._tempMultiSet.clear();for(let u of e)this._tempMultiSet.add(u);}let r=this._computeUnionBBox(e);if(!r)return;this._tempMultiNodes=n;let s=new H.Group({name:"temp-multi-overlay",x:r.x,y:r.y});t.add(s),this._tempMultiGroup=s;let l=new H.Rect({x:0,y:0,width:r.width,height:r.height,fill:"rgba(0,0,0,0.001)",listening:false,name:"temp-multi-overlay-rect"});s.add(l),this._tempOverlay??(this._tempOverlay=new He(this._core)),this._tempOverlay.attach(s,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed}),this._tempOverlay.forceUpdate();let h=this._core.stage,p=h.draggable();s.draggable(true);let d=null;s.on("dragstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let c=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let u of this._tempMultiNodes)if(c){let f=c.copy().multiply(u.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(u,f);}else this._tempMultiInitialTransforms.set(u,u.getAbsoluteTransform().copy());d=c?c.copy().multiply(s.getAbsoluteTransform().copy()):s.getAbsoluteTransform().copy(),h.draggable(false),this._draggingNode=s,this._tempMultiTransformingGroup=s,this._startAutoPanLoop(),this._tempOverlay?.hideOverlaysForDrag();}),s.on("dragmove.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(s,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),s.on("rotate:start.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let c=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let u of this._tempMultiNodes)if(c){let f=c.copy().multiply(u.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(u,f);}else this._tempMultiInitialTransforms.set(u,u.getAbsoluteTransform().copy());d=c?c.copy().multiply(s.getAbsoluteTransform().copy()):s.getAbsoluteTransform().copy();}),s.on("rotate:move.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(s,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),s.on("rotate:end.tempMulti",()=>{s.fire("transformend.tempMulti");}),s.on("dragend.tempMulti",()=>{if(h.draggable(p),this._draggingNode=null,this._stopAutoPanLoop(),this._tempMultiTransformingGroup=null,this._tempOverlay?.restoreOverlaysAfterDrag(),s.scale({x:1,y:1}),s.rotation(0),s.skew({x:0,y:0}),this._core){let u=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiSet){let _=f.getKonvaNode().getAbsoluteTransform().copy(),b=u.copy().multiply(_).decompose();this._core.eventBus.emit("node:transformed",f,{x:b.x,y:b.y,rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY});}}this._updateTempMultiOverlayBBox(),this._tempMultiInitialTransforms.clear(),this._tempMultiTransformingGroup=null,this._stopAutoPanLoop(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),s.on("transformstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let c=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let u of this._tempMultiNodes)if(c){let f=c.copy().multiply(u.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(u,f);}else this._tempMultiInitialTransforms.set(u,u.getAbsoluteTransform().copy());d=c?c.copy().multiply(s.getAbsoluteTransform().copy()):s.getAbsoluteTransform().copy(),this._tempMultiTransformingGroup=s,this._startAutoPanLoop();}),s.on("transform.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(s,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),s.on("transformend.tempMulti",()=>{if(this._core){let f=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let g of this._tempMultiSet){let m=g.getKonvaNode().getAbsoluteTransform().copy(),v=f.copy().multiply(m).decompose();this._core.eventBus.emit("node:transformed",g,{x:v.x,y:v.y,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY});}}let c=this._tempOverlay;c?.detach(),globalThis.requestAnimationFrame(()=>{if(!this._core||!this._tempMultiGroup||this._tempMultiGroup!==s)return;s.scale({x:1,y:1}),s.rotation(0),s.skew({x:0,y:0}),this._updateTempMultiOverlayBBox();let u=c??this._tempOverlay??(this._tempOverlay=new He(this._core));u.attach(s,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed}),u.forceUpdate(),this._scheduleBatchDraw();}),d=null,this._tempMultiInitialTransforms.clear(),this._tempMultiTransformingGroup=null,this._stopAutoPanLoop(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),o.batchDraw(),this._core.eventBus.emit("selection:multi:created",e);}_destroyTempMultiOverlayOnly(){this._core&&this._tempMultiGroup&&(this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null,this._tempMultiNodes=[],this._tempMultiInitialTransforms.clear(),this._core.nodes.layer.batchDraw(),this._core.eventBus.emit("selection:multi:destroyed"));}_destroyTempMulti(){this._core&&(!this._tempMultiGroup&&this._tempMultiSet.size===0||(this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup&&(this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null),this._tempMultiNodes=[],this._tempMultiInitialTransforms.clear(),this._tempMultiSet.clear(),this._core.nodes.layer.batchDraw(),this._core.eventBus.emit("selection:multi:destroyed")));}_commitTempMultiToGroup(){if(!this._core||!this._tempMultiGroup||this._tempMultiSet.size<2)return;let e=this._core.nodes,t=this._computeUnionBBox(Array.from(this._tempMultiSet));if(!t)return;let o=e.addGroup({x:t.x,y:t.y,draggable:true}),n=o.getKonvaNode(),r=[],s=[...this._tempMultiNodes].sort((c,u)=>c.zIndex()-u.zIndex()),l=Math.max(...s.map(c=>c.zIndex()));for(let c of s){let u=c.getAbsolutePosition();n.add(c),c.setAbsolutePosition(u),typeof c.draggable=="function"&&c.draggable(false);let f=this._core.nodes.list().find(g=>g.getKonvaNode()===c);f&&r.push(f);}let h=this._core.nodes.world,p=n.zIndex(),d=l;if(p<d){let c=d-p;for(let u=0;u<c&&n.zIndex()<h.children.length-1;u++)n.moveUp();}this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null,this._tempMultiNodes=[],this._tempMultiSet.clear(),typeof n.draggable=="function"&&n.draggable(true),this._core.eventBus.emit("group:created",o,r),this._select(o),this._core.stage.batchDraw();}_tryUngroupSelectedGroup(){if(!this._core||!this._selected)return;let e=this._selected.getKonvaNode();if(!(e instanceof H.Group))return;let t=[...e.getChildren()],o=this._core.nodes.world,n=[];for(let s of t){let l=s.getAbsoluteTransform().copy();o.add(s);let h=o.getAbsoluteTransform().copy();h.invert();let d=h.multiply(l).decompose();typeof s.position=="function"?s.position({x:d.x,y:d.y}):s.setAbsolutePosition({x:d.x,y:d.y}),typeof s.rotation=="function"&&s.rotation(d.rotation),typeof s.scale=="function"&&s.scale({x:d.scaleX,y:d.scaleY}),typeof s.draggable=="function"&&s.draggable(true);for(let c of this._core.nodes.list())if(c.getKonvaNode()===s){n.push(c);break}}let r=this._selected;this._selected=null,this._transformer?.destroy(),this._transformer=null,this._destroySizeLabel(),this._core.eventBus.emit("group:ungrouped",r,n),this._core.nodes.remove(r),this._core.stage.batchDraw();}_ensureHoverTr(){if(!this._core)throw new Error("Core is not attached");if(this._hoverTr?.getParent())return this._hoverTr;let e=new H.Transformer({rotateEnabled:false,enabledAnchors:[],rotationSnaps:[0,15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240,255,270,285,300,315,330,345,360],borderEnabled:true,borderStroke:"#2b83ff",borderStrokeWidth:1.5,listening:false,name:"hover-transformer"});return this._core.nodes.layer.add(e),this._hoverTr=e,e}_destroyHoverTr(){this._hoverTr&&(this._hoverTr.destroy(),this._hoverTr=null);}_refreshTransformer(){if(!this._core||(this._transformer&&(this._transformer.destroy(),this._transformer=null),!this._options.enableTransformer||!this._selected))return;let e=this._core.nodes.layer,t=new H.Transformer({rotateEnabled:false,rotationSnapTolerance:15,flipEnabled:false,keepRatio:false,rotationSnaps:[0,15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240,255,270,285,300,315,330,345,360],enabledAnchors:["top-left","top-center","top-right","middle-right","bottom-right","bottom-center","bottom-left","middle-left"]});e.add(t),t.nodes([this._selected.getKonvaNode()]),t.boundBoxFunc((s,l)=>{let p=l.width,d=l.height,c=l.x,u=l.y;return (p<0||p<1)&&(p=1),(d<0||d<1)&&(d=1),{...l,x:c,y:u,width:p,height:d}}),this._transformer=t,this._restyleSideAnchors(),this._setupCornerRadiusHandles(false),this._setupRotateHandles(),this._setupSizeLabel();let o=()=>{let s=typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"",l=s==="top-left"||s==="top-right"||s==="bottom-left"||s==="bottom-right";t.keepRatio(l&&this._ratioKeyPressed);};t.on("transformstart.keepratio",()=>{o(),this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel(),this._isTransforming=true,this._startAutoPanLoop();let s=this._selected?.getKonvaNode(),h=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"";if(!s){this._transformOppositeCorner=null,this._isTransforming=false;return}let p=Se(s),d=Te(h,p);if(!d){this._transformOppositeCorner=null,this._isTransforming=false;return}let c=s.getAbsoluteTransform();this._transformOppositeCorner=c.point({x:d.x,y:d.y});}),t.on("transform.keepratio",o),t.on("transform.corner-sync",()=>{let s=this._selected?.getKonvaNode();if(s&&(this._bakeRectScale(s),this._transformOppositeCorner)){let h=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"",p=s.getAbsoluteTransform(),d=Se(s),c=Te(h,d);if(!c)return;let u=p.point({x:c.x,y:c.y}),f=this._transformOppositeCorner.x-u.x,g=this._transformOppositeCorner.y-u.y,_=s.getParent();if(_&&(Math.abs(f)>.01||Math.abs(g)>.01)){let m=_.getAbsoluteTransform().copy().invert(),b=s.getAbsolutePosition(),v={x:b.x+f,y:b.y+g},w=m.point(v);s.position(w);}}this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();}),t.on("transformend.corner-sync",()=>{this._cornerHandlesSuppressed=false,this._transformOppositeCorner=null,this._isTransforming=false,this._restyleSideAnchors(),this._stopAutoPanLoop(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();});let n=this._selected.getKonvaNode();n.off(".overlay-sync");let r=()=>{this._restyleSideAnchors(),this._scheduleUIUpdate(),this._scheduleBatchDraw();};n.on("widthChange.overlay-sync heightChange.overlay-sync scaleXChange.overlay-sync scaleYChange.overlay-sync rotationChange.overlay-sync xChange.overlay-sync yChange.overlay-sync",r),this._scheduleBatchDraw();}_restyleSideAnchors(){if(!this._core||!this._selected||!this._transformer)return;let e=this._selected.getKonvaNode();pe(this._core,this._transformer,e);}_setupRotateHandles(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroyRotateHandles();let t=new H.Group({name:"rotate-handles-group",listening:true});e.add(t),this._rotateHandlesGroup=t;let o=he("rotate-tl"),n=he("rotate-tr"),r=he("rotate-br"),s=he("rotate-bl");t.add(o),t.add(n),t.add(r),t.add(s),this._rotateHandles={tl:o,tr:n,br:r,bl:s};let l=d=>{d.on("dragstart.rotate",()=>{if(!this._selected)return;let c=this._selected.getKonvaNode(),u=c.getAbsoluteTransform().decompose(),f=this._getNodeCenterAbs(c);this._rotateCenterAbsStart=f;let g=this._core?.stage.getPointerPosition()??d.getAbsolutePosition(),_=Math.atan2(g.y-f.y,g.x-f.x)*180/Math.PI;this._rotateDragState={base:u.rotation||0,start:_},this._core&&(this._prevStageDraggableBeforeRotate=this._core.stage.draggable()),typeof c.draggable=="function"&&c.draggable(false),this._core?.stage.draggable(false);let m=_+90;this._applyRotatedCursor(m);}),d.on("dragmove.rotate",c=>{if(!this._core||!this._selected||!this._rotateDragState)return;let u=this._selected.getKonvaNode(),f=this._rotateCenterAbsStart??this._getNodeCenterAbs(u),g=this._core.stage.getPointerPosition()??d.getAbsolutePosition(),_=Math.atan2(g.y-f.y,g.x-f.x)*180/Math.PI,m=this._rotateDragState.base+(_-this._rotateDragState.start),b=_+45;this._applyRotatedCursor(b);let v=y=>{let N=y%360;return N<0&&(N+=360),N},w=(y,N)=>v(y-N+180)-180;if(c.evt.shiftKey){let y=this._transformer,N,x=5;if(y){let k=y.rotationSnaps();Array.isArray(k)&&(N=k.map(P=>v(P)));let C=y.rotationSnapTolerance();typeof C=="number"&&(x=C);}if(N?.length){let k=v(m),C=m,P=1/0;for(let R of N){let L=Math.abs(w(k,R));L<P&&L<=x&&(C=R,P=L);}P!==1/0&&(m=C);}}if(u.rotation(m),this._rotateCenterAbsStart){let y=this._getNodeCenterAbs(u),N=this._rotateCenterAbsStart.x-y.x,x=this._rotateCenterAbsStart.y-y.y,k=u.getParent();if(k){let C=k.getAbsoluteTransform().copy().invert(),P=C.point({x:y.x,y:y.y}),R=C.point({x:y.x+N,y:y.y+x}),L=u.x()+(R.x-P.x),A=u.y()+(R.y-P.y);typeof u.position=="function"&&u.position({x:L,y:A});}}this._transformer?.forceUpdate(),this._restyleSideAnchors(),this._core.nodes.layer.batchDraw(),this._scheduleUIUpdate();}),d.on("dragend.rotate",()=>{if(this._rotateDragState=null,this._rotateCenterAbsStart=null,this._selected){let c=this._selected.getKonvaNode();this._options.dragEnabled&&typeof c.draggable=="function"&&c.draggable(true);let u={x:c.x(),y:c.y(),rotation:c.rotation()};this._core?.eventBus.emit("node:transformed",this._selected,u);}this._core&&this._prevStageDraggableBeforeRotate!==null&&(this._core.stage.draggable(this._prevStageDraggableBeforeRotate),this._prevStageDraggableBeforeRotate=null),this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw(),this._core&&(this._core.stage.container().style.cursor="grab");});};l(o),l(n),l(r),l(s);let h=d=>{this._core&&(this._core.stage.container().style.cursor=d);},p=d=>{d.on("mouseenter.rotate-cursor",()=>{if(!this._core||!this._selected)return;let c=this._selected.getKonvaNode(),u=this._getNodeCenterAbs(c),f=d.getAbsolutePosition(),g=f.x-u.x,_=f.y-u.y,v=Math.atan2(_,g)*180/Math.PI+45;this._setRotateCursor(v);}),d.on("mouseleave.rotate-cursor",()=>{h("default");});};this._rotateHandles.tl&&p(this._rotateHandles.tl),this._rotateHandles.tr&&p(this._rotateHandles.tr),this._rotateHandles.br&&p(this._rotateHandles.br),this._rotateHandles.bl&&p(this._rotateHandles.bl),this._updateRotateHandlesPosition();}_destroyRotateHandles(){this._rotateHandlesGroup&&(this._rotateHandlesGroup.destroy(),this._rotateHandlesGroup=null),this._rotateHandles={tl:null,tr:null,br:null,bl:null},this._rotateDragState=null;}_getNodeCenterAbs(e){let t=e.getAbsoluteTransform().copy(),o=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false});return t.point({x:o.x+o.width/2,y:o.y+o.height/2})}_setRotateCursor(e){this._core&&this._applyRotatedCursor(e);}_applyRotatedCursor(e){if(!this._core)return;let t=`
57
+ `.trim(),s=`url("data:image/svg+xml,${encodeURIComponent(n)}") 12 12, grab`;e.style.cursor=s,this.cursorSvgCache={angle:t,url:s};}detach(){this.group&&(this.group.destroy(),this.group=null),this.handles={tl:null,tr:null,br:null,bl:null},this.dragState=null,this.centerAbsStart=null;}moveToTop(){this.placeBelowTransformer();}updatePosition(){let i=this.getKonvaNode();if(!i||!this.group)return;let e=i.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),t=e.width,n=e.height;if(t<=0||n<=0)return;let o=i.getAbsoluteTransform().copy(),s=N=>o.point(N),r=12,l=s({x:e.x+t/2,y:e.y+n/2}),h=s({x:e.x,y:e.y}),c=s({x:e.x+t,y:e.y}),d=s({x:e.x+t,y:e.y+n}),u=s({x:e.x,y:e.y+n}),p=N=>{let k=N.x-l.x,S=N.y-l.y,C=Math.hypot(k,S)||1;return {x:k/C,y:S/C}},f=p(h),g=p(c),m=p(d),_=p(u),b={x:h.x+f.x*r,y:h.y+f.y*r},v={x:c.x+g.x*r,y:c.y+g.y*r},w={x:d.x+m.x*r,y:d.y+m.y*r},x={x:u.x+_.x*r,y:u.y+_.y*r};this.handles.tl&&this.handles.tl.absolutePosition(b),this.handles.tr&&this.handles.tr.absolutePosition(v),this.handles.br&&this.handles.br.absolutePosition(w),this.handles.bl&&this.handles.bl.absolutePosition(x),this.placeBelowTransformer();}placeBelowTransformer(){if(!this.group)return;let i=this.getTransformer(),e=this.core.nodes.layer;if(i?.getLayer()===e){let t=i.zIndex(),n=this.group.zIndex();if(n>=t){let o=n-t+1;for(let s=0;s<o&&this.group.zIndex()>0;s++)this.group.moveDown();}}else this.group.moveToBottom();}getNodeCenterAbs(i){let e=i.getAbsoluteTransform().copy(),t=i.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),n=t.x+t.width/2,o=t.y+t.height/2;return e.point({x:n,y:o})}};var He=class{constructor(i){a(this,"core");a(this,"tr",null);a(this,"sizeLabel",null);a(this,"rotateGroup",null);a(this,"rotateCtrl",null);a(this,"keepRatioPredicate",null);a(this,"boundNode",null);a(this,"hitRect",null);a(this,"transformOppositeCorner",null);a(this,"trWasVisibleBeforeDrag",false);a(this,"labelWasVisibleBeforeDrag",false);a(this,"rotateWasVisibleBeforeDrag",false);a(this,"rotateCtrlWasAttachedBeforeDrag",false);this.core=i;}attach(i,e){this.detach(),this.boundNode=i,this.keepRatioPredicate=e?.keepRatioCornerOnlyShift??null;let t=this.core.nodes.layer,n=new G.Transformer({rotateEnabled:false,keepRatio:false,rotationSnapTolerance:15,rotationSnaps:[0,15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240,255,270,285,300,315,330,345,360],enabledAnchors:["top-left","top-center","top-right","middle-left","middle-right","bottom-left","bottom-center","bottom-right"],borderEnabled:true,borderStroke:"#2b83ff",borderStrokeWidth:1.5,name:"overlay-transformer"});t.add(n),n.nodes([i]),n.forceUpdate(),n.boundBoxFunc((r,l)=>{let c=Math.max(1,Math.abs(l.width)),d=Math.max(1,Math.abs(l.height));return {...l,width:c,height:d}}),this.tr=n,me(this.core,n,i),globalThis.queueMicrotask(()=>{!this.tr||!this.boundNode||(this.tr.forceUpdate(),me(this.core,this.tr,this.boundNode),this.core.nodes.layer.batchDraw());});let o=()=>{let r=typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"",l=r==="top-left"||r==="top-right"||r==="bottom-left"||r==="bottom-right",h=this.keepRatioPredicate?this.keepRatioPredicate():false;n.keepRatio(l&&h);};n.on("transformstart.overlayKeepRatio",()=>{o();let l=(typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"")??"",h=Ee(i),c=Pe(l,h);if(!c){this.transformOppositeCorner=null;return}let d=i.getAbsoluteTransform();this.transformOppositeCorner=d.point({x:c.x,y:c.y});}),n.on("transform.overlayKeepRatio",o);let s=()=>{if(this.boundNode){if(this.transformOppositeCorner){let l=(typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"")??"",h=this.boundNode.getAbsoluteTransform(),c=Ee(this.boundNode),d=Pe(l,c);if(!d)return;let u=h.point({x:d.x,y:d.y}),p=this.transformOppositeCorner.x-u.x,f=this.transformOppositeCorner.y-u.y,g=this.boundNode.getParent();if(g&&(Math.abs(p)>.01||Math.abs(f)>.01)){let m=g.getAbsoluteTransform().copy().invert(),_=this.boundNode.getAbsolutePosition(),b={x:_.x+p,y:_.y+f},v=m.point(b);this.boundNode.position(v);}}this.tr?.forceUpdate(),me(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),t.batchDraw();}};n.on("transform.overlayFrameTransform",s),n.on("transformend.overlayFrameTransform",()=>{this.transformOppositeCorner=null,s();}),this.ensureSizeLabel(),this.updateSizeLabel(),this.updateHitRect(),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null),this.rotateCtrl=new ut({core:this.core,getNode:()=>this.boundNode,getTransformer:()=>this.tr,onUpdate:()=>{this.forceUpdate(),this.core.nodes.layer.batchDraw();}}),this.rotateCtrl.attach(),this.rotateCtrl.updatePosition(),this.tr.moveToTop(),t.batchDraw();}shiftTransformReferencePoint(i,e){this.transformOppositeCorner&&(this.transformOppositeCorner={x:this.transformOppositeCorner.x+i,y:this.transformOppositeCorner.y+e});}detach(){this.tr&&(this.tr.off(".overlayKeepRatio"),this.tr.off(".overlayFrameTransform"),this.tr.destroy(),this.tr=null),this.transformOppositeCorner=null,this.sizeLabel&&(this.sizeLabel.destroy(),this.sizeLabel=null),this.hitRect&&(this.hitRect.destroy(),this.hitRect=null),this.rotateGroup&&(this.rotateGroup.destroy(),this.rotateGroup=null),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null);}forceUpdate(){this.boundNode&&(this.tr?.forceUpdate(),me(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),this.updateSizeLabel(),this.updateHitRect());}onWorldChanged(){this.forceUpdate();}hideOverlaysForDrag(){this.tr?(this.trWasVisibleBeforeDrag=this.tr.visible(),this.tr.visible(false)):this.trWasVisibleBeforeDrag=false,this.sizeLabel?(this.labelWasVisibleBeforeDrag=this.sizeLabel.visible(),this.sizeLabel.visible(false)):this.labelWasVisibleBeforeDrag=false,this.rotateGroup?(this.rotateWasVisibleBeforeDrag=this.rotateGroup.visible(),this.rotateGroup.visible(false)):this.rotateWasVisibleBeforeDrag=false,this.rotateCtrl?(this.rotateCtrlWasAttachedBeforeDrag=true,this.rotateCtrl.detach()):this.rotateCtrlWasAttachedBeforeDrag=false;}restoreOverlaysAfterDrag(){this.tr&&this.trWasVisibleBeforeDrag&&this.tr.visible(true),this.sizeLabel&&this.labelWasVisibleBeforeDrag&&this.sizeLabel.visible(true),this.rotateGroup&&this.rotateWasVisibleBeforeDrag&&this.rotateGroup.visible(true),this.rotateCtrl&&this.rotateCtrlWasAttachedBeforeDrag&&(this.rotateCtrl.attach(),this.rotateCtrl.updatePosition(),this.tr?.moveToTop()),this.trWasVisibleBeforeDrag=false,this.labelWasVisibleBeforeDrag=false,this.rotateWasVisibleBeforeDrag=false,this.rotateCtrlWasAttachedBeforeDrag=false,this.forceUpdate();}ensureSizeLabel(){let i=this.core.nodes.layer;this.sizeLabel&&this.sizeLabel.destroy();let e=new G.Label({listening:false,opacity:.95}),t=new G.Tag({fill:"#2b83ff",cornerRadius:4,lineJoin:"round"}),n=new G.Text({text:"",fontFamily:"Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",fontSize:12,fill:"#ffffff",padding:6,align:"center"});e.add(t),e.add(n),i.add(e),this.sizeLabel=e;}updateSizeLabel(){if(!this.boundNode||!this.sizeLabel)return;let i=this.core.nodes.world,e=this.boundNode.getClientRect({skipShadow:true,skipStroke:true}),t=e.width/Math.max(1e-6,i.scaleX()),n=e.height/Math.max(1e-6,i.scaleY()),o=Math.max(0,Math.round(t)),s=Math.max(0,Math.round(n));this.sizeLabel.getText().text(String(o)+" \xD7 "+String(s));let l=8,h=e.x+e.width/2,c=e.y+e.height+l,u=this.sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this.sizeLabel.setAttrs({x:h-u/2,y:c}),this.sizeLabel.moveToTop();}updateHitRect(){if(!this.boundNode)return;let i=this.core.nodes.layer,e=this.boundNode.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),t={x:e.x,y:e.y},n=e.width,o=e.height;if(!this.hitRect){let s=new G.Rect({name:"overlay-hit",x:t.x,y:t.y,width:n,height:o,fill:"rgba(0,0,0,0.001)",listening:true,perfectDrawEnabled:false});s.on("mousedown.overlayHit",r=>{if(r.evt.button!==0)return;r.cancelBubble=true;let l=this.boundNode;typeof l.startDrag=="function"&&l.startDrag();}),this.boundNode instanceof G.Container?(this.boundNode.add(s),s.moveToBottom(),this.hitRect=s,i.batchDraw()):s.destroy();return}this.hitRect.position(t),this.hitRect.size({width:n,height:o}),this.hitRect.moveToBottom();}};var we=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_selected",null);a(this,"_prevDraggable",null);a(this,"_transformer",null);a(this,"_transformerWasVisibleBeforeDrag",false);a(this,"_cornerHandlesWereVisibleBeforeDrag",false);a(this,"_sizeLabelWasVisibleBeforeDrag",false);a(this,"_rotateHandlesWereVisibleBeforeDrag",false);a(this,"_cornerHandlesGroup",null);a(this,"_cornerHandles",{tl:null,tr:null,br:null,bl:null});a(this,"_cornerHandlesSuppressed",false);a(this,"_transformOppositeCorner",null);a(this,"_isTransforming",false);a(this,"_sizeLabel",null);a(this,"_radiusLabel",null);a(this,"_rotateHandlesGroup",null);a(this,"_rotateHandles",{tl:null,tr:null,br:null,bl:null});a(this,"_rotateDragState",null);a(this,"_rotateCenterAbsStart",null);a(this,"_prevStageDraggableBeforeRotate",null);a(this,"_worldSyncRafId",null);a(this,"_onCameraZoomEvent",null);a(this,"_onFrameChildrenChangedBound",null);a(this,"_onFrameLabelClickedBound",null);a(this,"_onFrameLabelDragStartBound",null);a(this,"_onFrameLabelDragEndBound",null);a(this,"_hoverTr",null);a(this,"_isPointerDown",false);a(this,"_autoPanRafId",null);a(this,"_autoPanActive",false);a(this,"_autoPanEdgePx");a(this,"_autoPanMaxSpeedPx");a(this,"_draggingNode",null);a(this,"_tempMultiTransformingGroup",null);a(this,"_ratioKeyPressed",false);a(this,"_onGlobalKeyDown",null);a(this,"_onGlobalKeyUp",null);a(this,"_tempMultiSet",new Set);a(this,"_tempMultiNodes",[]);a(this,"_tempMultiInitialTransforms",new Map);a(this,"_tempMultiGroup",null);a(this,"_tempOverlay",null);a(this,"_multiCtrl",null);a(this,"_parentGroupDuringChildEdit",null);a(this,"_parentGroupPrevDraggable",null);a(this,"_dragMoveScheduled",false);a(this,"_batchDrawScheduled",false);a(this,"_hoverThrottle",new ve(16));a(this,"_uiUpdateDebounce",new ye);a(this,"_onMouseDown",e=>{if(!this._core||e.evt.button!==0)return;let t=this._core.stage,n=this._core.nodes.layer;if(e.target===t||e.target.getLayer()!==n){let w=false;if(this._selected){let x=t.getPointerPosition();if(x){let N=this._selected.getKonvaNode(),k=N.getClientRect({skipShadow:true,skipStroke:false});if(x.x>=k.x&&x.x<=k.x+k.width&&x.y>=k.y&&x.y<=k.y+k.height&&(w=true,typeof N.startDrag=="function")){let C=N,T=3,K=e.evt.clientX,L=e.evt.clientY,B=typeof C.draggable=="function"?C.draggable():false,P=t.draggable(),I=false,X=J=>{let W=Math.abs(J.evt.clientX-K),$=Math.abs(J.evt.clientY-L);!I&&(W>T||$>T)&&(I=true,this._selected instanceof M||typeof C.draggable=="function"&&!B&&C.draggable(true),N.on("dragstart.selection-once-bbox",()=>{t.draggable(false);}),N.on("dragend.selection-once-bbox",()=>{t.draggable(P),this._selected instanceof M||typeof C.draggable=="function"&&C.draggable(this._options.dragEnabled?true:B),this._selected&&(this._refreshTransformer(),this._core?.nodes.layer.batchDraw()),N.off(".selection-once-bbox");}),N.startDrag(),e.cancelBubble=true);},U=()=>{!I&&this._options.deselectOnEmptyClick&&this._clearSelection(),t.off("mousemove.selection-once-bbox"),t.off("mouseup.selection-once-bbox");};t.on("mousemove.selection-once-bbox",X),t.on("mouseup.selection-once-bbox",U);}}}w||this._options.deselectOnEmptyClick&&this._clearSelection();return}let o=e.target;if(!this._options.selectablePredicate(o)){if(this._selected){let w=t.getPointerPosition();if(w){let x=this._selected.getKonvaNode(),N=x.getClientRect({skipShadow:true,skipStroke:false});if(w.x>=N.x&&w.x<=N.x+N.width&&w.y>=N.y&&w.y<=N.y+N.height&&typeof x.startDrag=="function"){let S=x,C=3,T=e.evt.clientX,K=e.evt.clientY,L=typeof S.draggable=="function"?S.draggable():false,B=t.draggable(),P=false,I=U=>{let J=Math.abs(U.evt.clientX-T),W=Math.abs(U.evt.clientY-K);!P&&(J>C||W>C)&&(P=true,this._selected instanceof M||typeof S.draggable=="function"&&!L&&S.draggable(true),x.on("dragstart.selection-once-bbox2",()=>{t.draggable(false);}),x.on("dragend.selection-once-bbox2",()=>{t.draggable(B),this._selected instanceof M||typeof S.draggable=="function"&&S.draggable(this._options.dragEnabled?true:L),this._selected&&(this._refreshTransformer(),this._core?.nodes.layer.batchDraw()),x.off(".selection-once-bbox2");}),x.startDrag(),e.cancelBubble=true);},X=()=>{!P&&this._options.deselectOnEmptyClick&&this._clearSelection(),t.off("mousemove.selection-once-bbox2"),t.off("mouseup.selection-once-bbox2");};t.on("mousemove.selection-once-bbox2",I),t.on("mouseup.selection-once-bbox2",X);}}}return}let s=this._findBaseNodeByTarget(o);if(!s)return;let r=s,l=this._selected;if(l){let w=l.getKonvaNode();((N,k)=>{let S=k;for(;S;){if(S===N)return true;S=S.getParent();}return false})(w,o)&&(r=l);}let h=r.getKonvaNode();h instanceof G.Group&&this._disableGroupChildrenDragging(h);let c=3,d=e.evt.clientX,u=e.evt.clientY,p=false,f=w=>{if(p)return;let x=Math.abs(w.evt.clientX-d),N=Math.abs(w.evt.clientY-u);(x>c||N>c)&&(p=true,typeof h.startDrag=="function"&&h.startDrag(),this._core?.stage.off("mousemove.selection-once"),this._core?.stage.off("mouseup.selection-once"));},g=()=>{this._core?.stage.off("mousemove.selection-once"),this._core?.stage.off("mouseup.selection-once");};if(this._core.stage.on("mousemove.selection-once",f),this._core.stage.on("mouseup.selection-once",g),typeof h.isDragging=="function"&&h.isDragging())return;let m=r instanceof M,_=typeof h.draggable=="function"&&!m,b=_?h.draggable():false,v=t.draggable();_&&h.draggable(true),h.on("dragstart.selection-once",()=>{t.draggable(false);}),h.on("dragend.selection-once",()=>{t.draggable(v),_&&(this._options.dragEnabled?h.draggable(true):h.draggable(b)),this._select(r);});});a(this,"_onHoverMoveThrottled",e=>{this._hoverThrottle.shouldExecute()&&this._onHoverMove(e);});a(this,"_onHoverMove",e=>{if(!this._core)return;let t=this._core.stage,n=this._core.nodes.layer,o=e.target;if((()=>{if(!!!this._tempMultiGroup){let v=o;for(;v;){if(v instanceof G.Group&&typeof v.name=="function"){let w=v.name();if(typeof w=="string"&&(w.includes("temp-multi-group")||w.includes("area-temp-group")))return true}v=v.getParent();}return false}let b=o;for(;b;){if(b===this._tempMultiGroup)return true;b=b.getParent();}return false})()){this._destroyHoverTr();return}let r=typeof e.evt.buttons=="number"?e.evt.buttons:0;if(this._isPointerDown||r&1){this._destroyHoverTr();return}if(o===t||o.getLayer()!==n){this._destroyHoverTr();return}let l=this._core.nodes.list().map(_=>_.getKonvaNode()),h=new Set(l),c=_=>{let b=_;for(;b;){if(h.has(b))return b;b=b.getParent();}return null},u=(_=>{let b=_,v=null;for(;b;)h.has(b)&&b instanceof G.Group&&(v=b),b=b.getParent();return v})(o),p=c(o),f=e.evt.ctrlKey,g=f?p??u:u??p;{let _=this._core.nodes.list().filter(v=>v instanceof M),b=false;for(let v of _){let w=v.getContentGroup();if(o===w||typeof w.isAncestorOf=="function"&&w.isAncestorOf(o)){b=true;break}}if(b){let v=this._core.nodes.list().filter(C=>!(C instanceof M)).map(C=>C.getKonvaNode()),w=new Set(v),x=C=>{let T=C;for(;T;){if(w.has(T))return T;T=T.getParent();}return null},k=(C=>{let T=C,K=null;for(;T;)w.has(T)&&T instanceof G.Group&&(K=T),T=T.getParent();return K})(o),S=x(o);g=f?S??k:k??S;}}if(!f&&this._selected&&p&&!(this._selected.getKonvaNode()instanceof G.Group)){let _=this._selected.getKonvaNode();u&&((v,w,x)=>{if(!x)return false;let N=(k,S)=>{let C=S;for(;C;){if(C===k)return true;C=C.getParent();}return false};return N(x,v)&&N(x,w)})(_,p,u)&&_!==p&&(g=p);}if(!g){this._destroyHoverTr();return}if(!this._options.selectablePredicate(g)){this._destroyHoverTr();return}if(this._selected){let _=this._selected.getKonvaNode();if(f?g===_:g===_||((w,x)=>{let N=x;for(;N;){if(N===w)return true;N=N.getParent();}return false})(_,g)){this._destroyHoverTr();return}}let m=this._ensureHoverTr();m.nodes([g]),m.visible(true),m.moveToTop(),n.batchDraw();});a(this,"_onHoverDown",()=>{this._isPointerDown=true,this._destroyHoverTr();});a(this,"_onHoverUp",()=>{this._isPointerDown=false;});a(this,"_onHoverLeave",e=>{this._destroyHoverTr();});a(this,"_onNodeRemoved",e=>{this._selected&&this._selected===e&&this._clearSelection();});let{dragEnabled:t=true,enableTransformer:n=true,deselectOnEmptyClick:o=true,selectablePredicate:s}=e,r=s??(()=>true);if(this._options={dragEnabled:t,enableTransformer:n,deselectOnEmptyClick:o,selectablePredicate:l=>r(l)?this._isSelectableByFrameRules(l):false,autoPanEnabled:e.autoPanEnabled??true,autoPanEdgePx:e.autoPanEdgePx??40,autoPanMaxSpeedPx:e.autoPanMaxSpeedPx??24,enableVideoOverlay:e.enableVideoOverlay??false},e.enableVideoOverlay){let l=typeof e.enableVideoOverlay=="object"?e.enableVideoOverlay:{};this.addons.add(new Ge(l));}this._autoPanEdgePx=this._options.autoPanEdgePx,this._autoPanMaxSpeedPx=this._options.autoPanMaxSpeedPx;}getSelected(){return this._selected}getMultiGroupController(){if(!this._core)throw new Error("Core is not attached");return this._multiCtrl??(this._multiCtrl=new ht({ensureTempMulti:e=>{this._ensureTempMulti(e);},destroyTempMulti:()=>{this._destroyTempMulti();},commitTempMultiToGroup:()=>{this._commitTempMultiToGroup();},isActive:()=>!!this._tempMultiGroup||this._tempMultiSet.size>0,forceUpdate:()=>{this._tempOverlay?.forceUpdate();},onWorldChanged:()=>{this._tempOverlay?.onWorldChanged();},isInsideTempByTarget:e=>this._tempMultiGroup?e===this._tempMultiGroup?true:e.isAncestorOf(this._tempMultiGroup)||this._tempMultiGroup.isAncestorOf(e):false})),this._multiCtrl}_startAutoPanLoop(){if(!this._core||this._autoPanRafId!=null)return;this._autoPanActive=true;let e=this._core.nodes.world,t=this._core.stage,n=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let o=t.getPointerPosition();if(o){let s=t.width(),r=t.height(),l=this._autoPanEdgePx,h=0,c=0,d=Math.max(0,l-o.x),u=Math.max(0,o.x-(s-l)),p=Math.max(0,l-o.y),f=Math.max(0,o.y-(r-l)),g=m=>Math.min(1,m/l);if(h=this._autoPanMaxSpeedPx*(g(u)-g(d)),c=this._autoPanMaxSpeedPx*(g(f)-g(p)),h!==0||c!==0){e.x(e.x()-h),e.y(e.y()-c);let m=e.position();if(this._core.eventBus.emit("camera:pan",{dx:-h,dy:-c,position:{x:m.x,y:m.y}}),this._isTransforming&&this._transformOppositeCorner&&(this._transformOppositeCorner={x:this._transformOppositeCorner.x-h,y:this._transformOppositeCorner.y-c}),this._tempMultiTransformingGroup&&this._tempOverlay&&this._tempOverlay.shiftTransformReferencePoint(-h,-c),this._draggingNode&&typeof this._draggingNode.setAbsolutePosition=="function"){let _=this._draggingNode.getAbsolutePosition();this._draggingNode.setAbsolutePosition({x:_.x+h,y:_.y+c}),this._transformer?.forceUpdate();}if(this._isTransforming){let _=t.getPointerPosition();if(_){let b=t.container(),v=b.getBoundingClientRect();try{b.dispatchEvent(new MouseEvent("mousemove",{bubbles:!0,cancelable:!0,clientX:v.left+_.x,clientY:v.top+_.y}));}catch{}}}if(this._tempMultiTransformingGroup){let _=t.getPointerPosition();if(_){let b=t.container(),v=b.getBoundingClientRect();try{b.dispatchEvent(new MouseEvent("mousemove",{bubbles:!0,cancelable:!0,clientX:v.left+_.x,clientY:v.top+_.y}));}catch{}}}this._core.nodes.layer.batchDraw();}}this._autoPanRafId=globalThis.requestAnimationFrame(n);};this._autoPanRafId=globalThis.requestAnimationFrame(n);}_stopAutoPanLoop(){this._autoPanActive=false,this._autoPanRafId!=null&&(globalThis.cancelAnimationFrame(this._autoPanRafId),this._autoPanRafId=null);}_scheduleBatchDraw(){if(this._batchDrawScheduled)return;this._batchDrawScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._batchDrawScheduled=false,this._core?.stage.batchDraw();});}setOptions(e){this._options={...this._options,...e},this._core&&this._refreshTransformer(),typeof e.autoPanEdgePx=="number"&&(this._autoPanEdgePx=e.autoPanEdgePx),typeof e.autoPanMaxSpeedPx=="number"&&(this._autoPanMaxSpeedPx=e.autoPanMaxSpeedPx),e.autoPanEnabled===false&&this._stopAutoPanLoop();}selectSingleFromArea(e){this._destroyTempMulti(),this._select(e),this._scheduleBatchDraw();}clearSelectionFromAreaLasso(){this._destroyTempMulti(),this._clearSelection();}onAttach(e){this._core=e;let t=e.stage;t.on("mousedown.selection",this._onMouseDown),t.on("click.selection",r=>{if(!this._core)return;let l=this._core.stage,h=this._core.nodes.layer;if(!!l.getAttr("_skipSelectionEmptyClickOnce")){l.setAttr("_skipSelectionEmptyClickOnce",false),r.cancelBubble=true;return}if(r.evt.button!==0)return;if(r.target===l||r.target.getLayer()!==h){this._options.deselectOnEmptyClick&&(this._destroyTempMulti(),this._clearSelection());return}let d=r.target;if(!this._options.selectablePredicate(d)){this._options.deselectOnEmptyClick&&(this._destroyTempMulti(),this._clearSelection());return}if(r.evt.shiftKey||r.evt.ctrlKey||r.evt.metaKey){let p=this._findBaseNodeByTarget(d);if(!p)return;let g=p.getKonvaNode().getParent();if(g&&g instanceof G.Group){let m=this._core.nodes.world;if(g!==m&&!this._core.nodes.list().filter(v=>v instanceof M).some(v=>v.getContentGroup()===g))return}if(this._tempMultiSet.size===0&&this._selected&&this._selected!==p&&(this._tempMultiSet.add(this._selected),this._transformer&&(this._transformer.destroy(),this._transformer=null),this._destroyCornerRadiusHandles(),this._destroyRotateHandles(),this._destroySizeLabel(),this._selected=null),Array.from(this._tempMultiSet).includes(p)?this._tempMultiSet.delete(p):this._tempMultiSet.add(p),this._tempMultiSet.size===0){this._destroyTempMulti(),this._clearSelection();return}if(this._tempMultiSet.size===1){let _=this._tempMultiSet.values().next(),b=_.done?void 0:_.value;b&&(this._destroyTempMulti(),this._select(b),this._scheduleBatchDraw());return}this._ensureTempMulti(Array.from(this._tempMultiSet)),this._scheduleBatchDraw();return}let u=this._findBaseNodeByTarget(d);u&&(this._destroyTempMulti(),this._select(u),this._scheduleBatchDraw());}),t.on("dblclick.selection",r=>{if(!this._core)return;let l=this._core.nodes.layer;if(r.target===t||r.target.getLayer()!==l||r.evt.button!==0||!this._selected)return;let h=this._selected.getKonvaNode();if(h instanceof G.Group&&typeof h.isAncestorOf=="function"&&h.isAncestorOf(r.target)){r.cancelBubble=true;let c=null;for(let d of this._core.nodes.list()){let u=d.getKonvaNode();if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(u)&&u!==h&&typeof u.isAncestorOf=="function"&&u.isAncestorOf(r.target)){let p=true;for(let f of this._core.nodes.list()){if(f===d)continue;let g=f.getKonvaNode();if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(g)&&typeof u.isAncestorOf=="function"&&u.isAncestorOf(g)&&typeof g.isAncestorOf=="function"&&g.isAncestorOf(r.target)){p=false;break}}if(p){c=d;break}}}if(c??(c=this._core.nodes.list().find(d=>d.getKonvaNode()===r.target)??null),c){this._select(c);let d=c.getKonvaNode();c instanceof M||typeof d.draggable=="function"&&d.draggable(true),h instanceof G.Group&&(this._parentGroupDuringChildEdit=h,this._parentGroupPrevDraggable=typeof h.draggable=="function"?h.draggable():null,typeof h.draggable=="function"&&h.draggable(false)),this._core.stage.batchDraw();}}}),e.eventBus.on("node:removed",this._onNodeRemoved),t.on("mousemove.hover",this._onHoverMoveThrottled),t.on("mouseleave.hover",this._onHoverLeave),t.on("mousedown.hover",this._onHoverDown),t.on("mouseup.hover",this._onHoverUp),t.on("touchstart.hover",this._onHoverDown),t.on("touchend.hover",this._onHoverUp),this._core.nodes.layer.on("dragstart.hover",()=>{this._destroyHoverTr();}),this._core.nodes.layer.on("dragmove.hover",()=>{this._destroyHoverTr();});let n=this._core.nodes.layer;n.on("dragstart.selectionAutoPan",r=>{if(!this._options.autoPanEnabled)return;let l=r.target,h=l.getParent(),c=f=>f&&typeof f.name=="function"&&f.name()||"",d=c(l),u=c(h);if(d.startsWith("rotate-")||u==="rotate-handles-group")return;let p=l;if(this._selected instanceof M){let f=t.getPointerPosition();if(f){let g=this._selected.getKonvaNode(),m=g.getClientRect({skipShadow:true,skipStroke:false});f.x>=m.x&&f.x<=m.x+m.width&&f.y>=m.y&&f.y<=m.y+m.height&&(p=g);}}this._draggingNode=p,this._startAutoPanLoop();}),n.on("dragend.selectionAutoPan",()=>{this._draggingNode=null,this._stopAutoPanLoop();});let o=this._core.nodes.world,s=()=>{this._core&&this._worldSyncRafId==null&&(this._worldSyncRafId=globalThis.requestAnimationFrame(()=>{this._worldSyncRafId=null,this._core&&((this._transformer||this._cornerHandlesGroup||this._rotateHandlesGroup||this._sizeLabel||this._tempMultiGroup)&&(this._transformer?.forceUpdate(),this._hoverTr?.forceUpdate(),this._restyleSideAnchors(),this._updateCornerRadiusHandlesPosition(),this._updateRotateHandlesPosition(),this._updateSizeLabel(),this._updateCornerRadiusHandlesVisibility(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw()),this._destroyHoverTr());}));};o.on("xChange.selectionCamera yChange.selectionCamera scaleXChange.selectionCamera scaleYChange.selectionCamera",s),this._onCameraZoomEvent=()=>{s();},e.eventBus.on("camera:zoom",this._onCameraZoomEvent),e.eventBus.on("camera:setZoom",this._onCameraZoomEvent),e.eventBus.on("camera:reset",this._onCameraZoomEvent),this._onFrameChildrenChangedBound=(r,l)=>{let h=r,c=!!l;if(!this._selected||this._selected!==h)return;let d=this._selected.getKonvaNode();typeof d.draggable=="function"&&(this._prevDraggable=d.draggable()),c&&this._clearSelection();},e.eventBus.on("frame:children-changed",this._onFrameChildrenChangedBound),this._onFrameLabelClickedBound=r=>{let l=r;this._destroyTempMulti(),this._select(l),this._scheduleBatchDraw();},e.eventBus.on("frame:label-clicked",this._onFrameLabelClickedBound),this._onFrameLabelDragStartBound=()=>{this._core&&(this._transformer&&this._transformer.visible(false),this._cornerHandlesGroup&&this._cornerHandlesGroup.visible(false),this._rotateHandlesGroup&&this._rotateHandlesGroup.visible(false),this._sizeLabel&&this._sizeLabel.visible(false),this._hoverTr&&this._hoverTr.visible(false),this._tempOverlay?.hideOverlaysForDrag(),this._core.stage.batchDraw());},this._onFrameLabelDragEndBound=()=>{this._core&&(this._selected&&this._refreshTransformer(),this._tempOverlay?.restoreOverlaysAfterDrag(),this._core.stage.batchDraw());},e.eventBus.on("frame:label-dragstart",this._onFrameLabelDragStartBound),e.eventBus.on("frame:label-dragend",this._onFrameLabelDragEndBound),this._onGlobalKeyDown=r=>{r.key==="Shift"&&(this._ratioKeyPressed=true);let l=r.ctrlKey||r.metaKey;l&&!r.shiftKey&&r.code==="KeyG"&&(r.preventDefault(),this._commitTempMultiToGroup()),l&&r.shiftKey&&r.code==="KeyG"&&(r.preventDefault(),this._tryUngroupSelectedGroup());},this._onGlobalKeyUp=r=>{r.key==="Shift"&&(this._ratioKeyPressed=false);},globalThis.addEventListener("keydown",this._onGlobalKeyDown),globalThis.addEventListener("keyup",this._onGlobalKeyUp);}onDetach(e){this._destroyTempMulti(),this._clearSelection(),e.stage.off(".selection"),e.stage.off(".hover"),this._core?.nodes.layer.off(".hover"),this._core?.nodes.world.off(".selectionCamera"),this._core?.nodes.layer.off(".selectionAutoPan"),this._worldSyncRafId!=null&&(globalThis.cancelAnimationFrame(this._worldSyncRafId),this._worldSyncRafId=null),this._onCameraZoomEvent&&(e.eventBus.off("camera:zoom",this._onCameraZoomEvent),e.eventBus.off("camera:setZoom",this._onCameraZoomEvent),e.eventBus.off("camera:reset",this._onCameraZoomEvent),this._onCameraZoomEvent=null),this._onFrameChildrenChangedBound&&(e.eventBus.off("frame:children-changed",this._onFrameChildrenChangedBound),this._onFrameChildrenChangedBound=null),this._onFrameLabelClickedBound&&(e.eventBus.off("frame:label-clicked",this._onFrameLabelClickedBound),this._onFrameLabelClickedBound=null),this._onFrameLabelDragStartBound&&(e.eventBus.off("frame:label-dragstart",this._onFrameLabelDragStartBound),this._onFrameLabelDragStartBound=null),this._onFrameLabelDragEndBound&&(e.eventBus.off("frame:label-dragend",this._onFrameLabelDragEndBound),this._onFrameLabelDragEndBound=null),e.eventBus.off("node:removed",this._onNodeRemoved),this._destroyHoverTr(),this._onGlobalKeyDown&&globalThis.removeEventListener("keydown",this._onGlobalKeyDown),this._onGlobalKeyUp&&globalThis.removeEventListener("keyup",this._onGlobalKeyUp),this._onGlobalKeyDown=null,this._onGlobalKeyUp=null;}_select(e){if(!this._core)return;let t=this._core;this._clearSelection();let n=e.getKonvaNode();this._prevDraggable=n.draggable(),this._options.dragEnabled&&typeof n.draggable=="function"&&n.draggable(true),n instanceof G.Group&&this._disableGroupChildrenDragging(n),this._selected=e,this._refreshTransformer(),t.eventBus.emit("node:selected",e),n.on("dragstart.selection",()=>{this._draggingNode=n,this._transformer&&(this._transformerWasVisibleBeforeDrag=this._transformer.visible(),this._transformer.visible(false)),this._cornerHandlesGroup&&(this._cornerHandlesWereVisibleBeforeDrag=this._cornerHandlesGroup.visible(),this._cornerHandlesGroup.visible(false)),this._rotateHandlesGroup&&(this._rotateHandlesWereVisibleBeforeDrag=this._rotateHandlesGroup.visible(),this._rotateHandlesGroup.visible(false)),this._sizeLabel&&(this._sizeLabelWasVisibleBeforeDrag=this._sizeLabel.visible(),this._sizeLabel.visible(false)),this._core?.stage.batchDraw(),this._startAutoPanLoop();}),n.on("dragmove.selection",()=>{if(this._dragMoveScheduled)return;this._dragMoveScheduled=true;let o=globalThis.requestAnimationFrame;o(()=>{this._dragMoveScheduled=false,this._scheduleBatchDraw();});}),n.on("dragend.selection",()=>{let o={};typeof n.x=="function"&&(o.x=n.x()),typeof n.y=="function"&&(o.y=n.y()),typeof n.width=="function"&&(o.width=n.width()),typeof n.height=="function"&&(o.height=n.height()),typeof n.rotation=="function"&&(o.rotation=n.rotation()),typeof n.scaleX=="function"&&(o.scaleX=n.scaleX()),typeof n.scaleY=="function"&&(o.scaleY=n.scaleY()),t.eventBus.emit("node:transformed",e,o);}),n.on("transformend.selection",()=>{let o={};typeof n.x=="function"&&(o.x=n.x()),typeof n.y=="function"&&(o.y=n.y()),typeof n.width=="function"&&(o.width=n.width()),typeof n.height=="function"&&(o.height=n.height()),typeof n.rotation=="function"&&(o.rotation=n.rotation()),typeof n.scaleX=="function"&&(o.scaleX=n.scaleX()),typeof n.scaleY=="function"&&(o.scaleY=n.scaleY()),this._core?.eventBus.emit("node:transformed",e,o);}),n.on("dragend.selection",()=>{this._draggingNode=null,this._transformer&&(this._transformerWasVisibleBeforeDrag&&this._transformer.visible(true),this._transformerWasVisibleBeforeDrag=false),this._cornerHandlesGroup&&(this._cornerHandlesWereVisibleBeforeDrag&&this._cornerHandlesGroup.visible(true),this._cornerHandlesWereVisibleBeforeDrag=false),this._rotateHandlesGroup&&(this._rotateHandlesWereVisibleBeforeDrag&&this._rotateHandlesGroup.visible(true),this._rotateHandlesWereVisibleBeforeDrag=false),this._sizeLabel&&(this._sizeLabelWasVisibleBeforeDrag&&this._sizeLabel.visible(true),this._sizeLabelWasVisibleBeforeDrag=false),this._stopAutoPanLoop(),this._select(e),this._core?.stage.batchDraw();}),n.on("mousedown.selection",o=>{let s=o.evt.button;(s===1||s===2)&&typeof n.draggable=="function"&&n.draggable(false);});}_clearSelection(){if(!this._selected)return;let e=this._selected,t=this._selected.getKonvaNode();if(typeof t.draggable=="function"&&this._prevDraggable!==null&&t.draggable(this._prevDraggable),this._prevDraggable=null,this._parentGroupDuringChildEdit){let n=this._parentGroupDuringChildEdit;typeof n.draggable=="function"&&this._parentGroupPrevDraggable!==null&&n.draggable(this._parentGroupPrevDraggable),this._parentGroupDuringChildEdit=null,this._parentGroupPrevDraggable=null;}t.off(".selection"),t.off(".selection-once"),this._destroyCornerRadiusHandles(),this._destroyRotateHandles(),this._destroySizeLabel(),this._transformer&&(this._transformer.destroy(),this._transformer=null),this._selected=null,this._core&&(this._core.eventBus.emit("node:deselected",e),this._core.eventBus.emit("selection:cleared")),this._core?.stage.batchDraw();}_applyOverlayTransformToNodes(e,t){if(!this._core)return;let o=this._core.nodes.world.getAbsoluteTransform().copy(),r=o.copy().invert().multiply(e.getAbsoluteTransform().copy()),l=t.copy();l.invert();let h=r.multiply(l);for(let c of this._tempMultiNodes){let d=this._tempMultiInitialTransforms.get(c);if(!d)continue;let u=h.copy().multiply(d),p=o.copy().multiply(u),f=c.getParent();if(!f)continue;let g=f.getAbsoluteTransform().copy();g.invert();let _=g.multiply(p).decompose();typeof c.position=="function"&&c.position({x:_.x,y:_.y}),typeof c.rotation=="function"&&c.rotation(_.rotation),typeof c.scale=="function"&&c.scale({x:_.scaleX,y:_.scaleY});}}_updateTempMultiOverlayBBox(){if(!this._core||!this._tempMultiGroup)return;let e=this._computeUnionBBox(Array.from(this._tempMultiSet));if(!e)return;this._tempMultiGroup.position({x:e.x,y:e.y});let t=this._tempMultiGroup.findOne(".temp-multi-overlay-rect");t&&t.size({width:e.width,height:e.height});}_computeUnionBBox(e){if(e.length===0||!this._core)return null;let t=this._core.nodes.world,n=1/0,o=1/0,s=-1/0,r=-1/0;for(let l of e){let c=l.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false}),d=t.getAbsoluteTransform().copy().invert(),u=[d.point({x:c.x,y:c.y}),d.point({x:c.x+c.width,y:c.y}),d.point({x:c.x+c.width,y:c.y+c.height}),d.point({x:c.x,y:c.y+c.height})];for(let p of u)n=Math.min(n,p.x),o=Math.min(o,p.y),s=Math.max(s,p.x),r=Math.max(r,p.y);}return !isFinite(n)||!isFinite(o)||!isFinite(s)||!isFinite(r)?null:{x:n,y:o,width:s-n,height:r-o}}_ensureTempMulti(e){if(!this._core)return;let t=this._core.nodes.world,n=this._core.nodes.layer;this._tempMultiSet.clear();for(let u of e)this._tempMultiSet.add(u);let o=e.map(u=>u.getKonvaNode());if(this._tempMultiGroup&&this._tempMultiNodes.length>0){if(this._tempMultiNodes.length===o.length&&o.every(p=>this._tempMultiNodes.includes(p)))return;this._destroyTempMultiOverlayOnly(),this._tempMultiSet.clear();for(let p of e)this._tempMultiSet.add(p);}let s=this._computeUnionBBox(e);if(!s)return;this._tempMultiNodes=o;let r=new G.Group({name:"temp-multi-overlay",x:s.x,y:s.y});t.add(r),this._tempMultiGroup=r;let l=new G.Rect({x:0,y:0,width:s.width,height:s.height,fill:"rgba(0,0,0,0.001)",listening:false,name:"temp-multi-overlay-rect"});r.add(l),this._tempOverlay??(this._tempOverlay=new He(this._core)),this._tempOverlay.attach(r,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed}),this._tempOverlay.forceUpdate();let h=this._core.stage,c=h.draggable();r.draggable(true);let d=null;r.on("dragstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let u=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let p of this._tempMultiNodes)if(u){let f=u.copy().multiply(p.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(p,f);}else this._tempMultiInitialTransforms.set(p,p.getAbsoluteTransform().copy());d=u?u.copy().multiply(r.getAbsoluteTransform().copy()):r.getAbsoluteTransform().copy(),h.draggable(false),this._draggingNode=r,this._tempMultiTransformingGroup=r,this._startAutoPanLoop(),this._tempOverlay?.hideOverlaysForDrag();}),r.on("dragmove.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(r,d),this._autogroupTempMultiInFrames(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("rotate:start.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let u=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let p of this._tempMultiNodes)if(u){let f=u.copy().multiply(p.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(p,f);}else this._tempMultiInitialTransforms.set(p,p.getAbsoluteTransform().copy());d=u?u.copy().multiply(r.getAbsoluteTransform().copy()):r.getAbsoluteTransform().copy();}),r.on("rotate:move.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(r,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("rotate:end.tempMulti",()=>{r.fire("transformend.tempMulti");}),r.on("dragend.tempMulti",()=>{if(h.draggable(c),this._draggingNode=null,this._stopAutoPanLoop(),this._tempMultiTransformingGroup=null,this._tempOverlay?.restoreOverlaysAfterDrag(),r.scale({x:1,y:1}),r.rotation(0),r.skew({x:0,y:0}),this._core){let p=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiSet){let m=f.getKonvaNode().getAbsoluteTransform().copy(),b=p.copy().multiply(m).decompose();this._core.eventBus.emit("node:transformed",f,{x:b.x,y:b.y,rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY});}this._autogroupTempMultiInFrames();}this._updateTempMultiOverlayBBox(),this._tempMultiInitialTransforms.clear(),this._tempMultiTransformingGroup=null,this._stopAutoPanLoop(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),r.on("transformstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let u=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let p of this._tempMultiNodes)if(u){let f=u.copy().multiply(p.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(p,f);}else this._tempMultiInitialTransforms.set(p,p.getAbsoluteTransform().copy());d=u?u.copy().multiply(r.getAbsoluteTransform().copy()):r.getAbsoluteTransform().copy(),this._tempMultiTransformingGroup=r,this._startAutoPanLoop();}),r.on("transform.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(r,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("transformend.tempMulti",()=>{if(this._core){let f=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let g of this._tempMultiSet){let _=g.getKonvaNode().getAbsoluteTransform().copy(),v=f.copy().multiply(_).decompose();this._core.eventBus.emit("node:transformed",g,{x:v.x,y:v.y,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY});}}let u=this._tempOverlay;u?.detach(),globalThis.requestAnimationFrame(()=>{if(!this._core||!this._tempMultiGroup||this._tempMultiGroup!==r)return;r.scale({x:1,y:1}),r.rotation(0),r.skew({x:0,y:0}),this._updateTempMultiOverlayBBox();let p=u??this._tempOverlay??(this._tempOverlay=new He(this._core));p.attach(r,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed}),p.forceUpdate(),this._scheduleBatchDraw();}),d=null,this._tempMultiInitialTransforms.clear(),this._tempMultiTransformingGroup=null,this._stopAutoPanLoop(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),n.batchDraw(),this._core.eventBus.emit("selection:multi:created",e);}_destroyTempMultiOverlayOnly(){this._core&&this._tempMultiGroup&&(this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null,this._tempMultiNodes=[],this._tempMultiInitialTransforms.clear(),this._core.nodes.layer.batchDraw(),this._core.eventBus.emit("selection:multi:destroyed"));}_destroyTempMulti(){this._core&&(!this._tempMultiGroup&&this._tempMultiSet.size===0||(this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup&&(this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null),this._tempMultiNodes=[],this._tempMultiInitialTransforms.clear(),this._tempMultiSet.clear(),this._core.nodes.layer.batchDraw(),this._core.eventBus.emit("selection:multi:destroyed")));}_autogroupTempMultiInFrames(){if(!this._core||this._tempMultiSet.size===0)return;let e=this._core.nodes,t=e.world,n=this._core.stage,o=e.list().filter(s=>s instanceof M);if(o.length!==0)for(let s of this._tempMultiSet){if(s instanceof M)continue;let r=s.getKonvaNode(),l=r.getParent();if(!l)continue;let h=null;e:for(let u of o){let p=l,f=u.getContentGroup();for(;p&&p!==t;){if(p===f){h=u;break e}p=p.getParent();}}let c=null,d=n.getPointerPosition();if(d){for(let u of o){let f=u.getRect().getClientRect({skipShadow:true,skipStroke:true});if(d.x>=f.x&&d.x<=f.x+f.width&&d.y>=f.y&&d.y<=f.y+f.height){c=u;break}}if(h){if(!c||c!==h){let u=r.getAbsolutePosition();t.add(r),r.setAbsolutePosition(u);let f=h.getContentGroup().getChildren().length>0,g=h.getKonvaNode();typeof g.draggable=="function"&&g.draggable(!f);}continue}if(c&&l!==c.getContentGroup()){let u=r.getAbsolutePosition(),p=c.getContentGroup();p.add(r),r.setAbsolutePosition(u);let f=p.getChildren().length>0,g=c.getKonvaNode();typeof g.draggable=="function"&&g.draggable(!f);}}}}_commitTempMultiToGroup(){if(!this._core||!this._tempMultiGroup||this._tempMultiSet.size<2)return;let e=Array.from(this._tempMultiSet),t=e.some(_=>_ instanceof M),n=e.some(_=>!(_ instanceof M));if(t){n?globalThis.console.warn("[SelectionPlugin] Grouping FrameNode with other nodes is not allowed. Operation is ignored."):globalThis.console.warn("[SelectionPlugin] Grouping FrameNode instances into a permanent group is not allowed. Operation is ignored.");return}let o=this._core.nodes,s=o.world,r=this._computeUnionBBox(e);if(!r)return;let l=o.list().filter(_=>_ instanceof M),h=null;e:for(let _ of e){let b=_.getKonvaNode(),v=null,w=b.getParent();for(;w&&w!==s;){for(let x of l){let N=x.getContentGroup();if(w===N){v=x;break}}if(v)break;w=w.getParent();}if(!v){h=null;break e}if(!h)h=v;else if(h!==v){h=null;break e}}let c=o.addGroup({x:r.x,y:r.y,draggable:true}),d=c.getKonvaNode();if(h){let _=d.getAbsolutePosition();h.getContentGroup().add(d),d.setAbsolutePosition(_);}let u=[],p=[...this._tempMultiNodes].sort((_,b)=>_.zIndex()-b.zIndex()),f=Math.max(...p.map(_=>_.zIndex()));for(let _ of p){let b=_.getAbsolutePosition();d.add(_),_.setAbsolutePosition(b),typeof _.draggable=="function"&&_.draggable(false);let v=this._core.nodes.list().find(w=>w.getKonvaNode()===_);v&&u.push(v);}let g=d.zIndex(),m=f;if(g<m){let _=m-g;for(let b=0;b<_&&d.zIndex()<s.children.length-1;b++)d.moveUp();}this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null,this._tempMultiNodes=[],this._tempMultiSet.clear(),typeof d.draggable=="function"&&d.draggable(true),this._core.eventBus.emit("group:created",c,u),this._select(c),this._core.stage.batchDraw();}_tryUngroupSelectedGroup(){if(!this._core||!this._selected)return;let e=this._selected.getKonvaNode();if(!(e instanceof G.Group))return;let t=[...e.getChildren()],n=this._core.nodes.world,s=this._core.nodes.list().filter(c=>c instanceof M),r=null;if(s.length>0)e:for(let c of s){let d=c.getContentGroup(),u=e.getParent();for(;u&&u!==n;){if(u===d){r=c;break e}u=u.getParent();}}let l=[];for(let c of t){let d=c.getAbsoluteTransform().copy(),u=r?r.getContentGroup():n;u.add(c);let p=u.getAbsoluteTransform().copy();p.invert();let g=p.multiply(d).decompose();typeof c.position=="function"?c.position({x:g.x,y:g.y}):c.setAbsolutePosition({x:g.x,y:g.y}),typeof c.rotation=="function"&&c.rotation(g.rotation),typeof c.scale=="function"&&c.scale({x:g.scaleX,y:g.scaleY});let m=false;for(let _ of this._core.nodes.list())if(_.getKonvaNode()===c){_ instanceof M&&(m=true),l.push(_);break}!m&&typeof c.draggable=="function"&&c.draggable(true);}let h=this._selected;this._selected=null,this._transformer?.destroy(),this._transformer=null,this._destroySizeLabel(),this._core.eventBus.emit("group:ungrouped",h,l),this._core.nodes.remove(h),this._core.stage.batchDraw();}_ensureHoverTr(){if(!this._core)throw new Error("Core is not attached");if(this._hoverTr?.getParent())return this._hoverTr;let e=new G.Transformer({rotateEnabled:false,enabledAnchors:[],rotationSnaps:[0,15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240,255,270,285,300,315,330,345,360],borderEnabled:true,borderStroke:"#2b83ff",borderStrokeWidth:1.5,listening:false,name:"hover-transformer"});return this._core.nodes.layer.add(e),this._hoverTr=e,e}_destroyHoverTr(){this._hoverTr&&(this._hoverTr.destroy(),this._hoverTr=null);}_isSelectableByFrameRules(e){let t=this._findBaseNodeByTarget(e);return t&&t instanceof M?!(t.getContentGroup().getChildren().length>0):true}_refreshTransformer(){if(!this._core||(this._transformer&&(this._transformer.destroy(),this._transformer=null),!this._options.enableTransformer||!this._selected))return;let e=this._core.nodes.layer,t=new G.Transformer({rotateEnabled:false,rotationSnapTolerance:15,flipEnabled:false,keepRatio:false,rotationSnaps:[0,15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240,255,270,285,300,315,330,345,360],enabledAnchors:["top-left","top-center","top-right","middle-right","bottom-right","bottom-center","bottom-left","middle-left"]});e.add(t),t.nodes([this._selected.getKonvaNode()]),t.boundBoxFunc((r,l)=>{let c=l.width,d=l.height,u=l.x,p=l.y;return (c<0||c<1)&&(c=1),(d<0||d<1)&&(d=1),{...l,x:u,y:p,width:c,height:d}}),this._transformer=t,this._restyleSideAnchors(),this._setupCornerRadiusHandles(false),this._setupRotateHandles(),this._setupSizeLabel();let n=()=>{let r=typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"",l=r==="top-left"||r==="top-right"||r==="bottom-left"||r==="bottom-right";t.keepRatio(l&&this._ratioKeyPressed);};t.on("transformstart.keepratio",()=>{n(),this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel(),this._isTransforming=true,this._startAutoPanLoop();let r=this._selected?.getKonvaNode(),h=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"";if(!r){this._transformOppositeCorner=null,this._isTransforming=false;return}let c=Ee(r),d=Pe(h,c);if(!d){this._transformOppositeCorner=null,this._isTransforming=false;return}let u=r.getAbsoluteTransform();this._transformOppositeCorner=u.point({x:d.x,y:d.y});}),t.on("transform.keepratio",n),t.on("transform.corner-sync",()=>{let r=this._selected,l=r?.getKonvaNode();if(l){if(r instanceof M){let h=r,c=Math.abs(l.scaleX?.()??1),d=Math.abs(l.scaleY?.()??1),u=h.getRect(),p=u.width(),f=u.height(),g=p*c,m=f*d;h.resize(g,m),typeof l.scaleX=="function"&&l.scaleX(1),typeof l.scaleY=="function"&&l.scaleY(1);}else this._bakeRectScale(l);if(this._transformOppositeCorner){let c=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"",d=l.getAbsoluteTransform(),u=Ee(l),p=Pe(c,u);if(!p)return;let f=d.point({x:p.x,y:p.y}),g=this._transformOppositeCorner.x-f.x,m=this._transformOppositeCorner.y-f.y,_=l.getParent();if(_&&(Math.abs(g)>.01||Math.abs(m)>.01)){let b=_.getAbsoluteTransform().copy().invert(),v=l.getAbsolutePosition(),w={x:v.x+g,y:v.y+m},x=b.point(w);l.position(x);}}}this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();}),t.on("transformend.corner-sync",()=>{this._cornerHandlesSuppressed=false,this._transformOppositeCorner=null,this._isTransforming=false,this._restyleSideAnchors(),this._stopAutoPanLoop(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();});let o=this._selected.getKonvaNode();o.off(".overlay-sync");let s=()=>{this._restyleSideAnchors(),this._scheduleUIUpdate(),this._scheduleBatchDraw();};o.on("widthChange.overlay-sync heightChange.overlay-sync scaleXChange.overlay-sync scaleYChange.overlay-sync rotationChange.overlay-sync xChange.overlay-sync yChange.overlay-sync",s),globalThis.queueMicrotask(()=>{this._core&&this._selected&&this._transformer===t&&(this._transformer.forceUpdate(),this._restyleSideAnchors(),this._scheduleBatchDraw());}),this._scheduleBatchDraw();}_restyleSideAnchors(){if(!this._core||!this._selected||!this._transformer)return;let e=this._selected.getKonvaNode();me(this._core,this._transformer,e);}_setupRotateHandles(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroyRotateHandles();let t=new G.Group({name:"rotate-handles-group",listening:true});e.add(t),this._rotateHandlesGroup=t;let n=pe("rotate-tl"),o=pe("rotate-tr"),s=pe("rotate-br"),r=pe("rotate-bl");t.add(n),t.add(o),t.add(s),t.add(r),this._rotateHandles={tl:n,tr:o,br:s,bl:r};let l=d=>{d.on("dragstart.rotate",()=>{if(!this._selected)return;let u=this._selected.getKonvaNode(),p=u.getAbsoluteTransform().decompose(),f=this._getNodeCenterAbs(u);this._rotateCenterAbsStart=f;let g=this._core?.stage.getPointerPosition()??d.getAbsolutePosition(),m=Math.atan2(g.y-f.y,g.x-f.x)*180/Math.PI;this._rotateDragState={base:p.rotation||0,start:m},this._core&&(this._prevStageDraggableBeforeRotate=this._core.stage.draggable()),typeof u.draggable=="function"&&u.draggable(false),this._core?.stage.draggable(false);let _=m+90;this._applyRotatedCursor(_);}),d.on("dragmove.rotate",u=>{if(!this._core||!this._selected||!this._rotateDragState)return;let p=this._selected.getKonvaNode(),f=this._rotateCenterAbsStart??this._getNodeCenterAbs(p),g=this._core.stage.getPointerPosition()??d.getAbsolutePosition(),m=Math.atan2(g.y-f.y,g.x-f.x)*180/Math.PI,_=this._rotateDragState.base+(m-this._rotateDragState.start),b=m+45;this._applyRotatedCursor(b);let v=x=>{let N=x%360;return N<0&&(N+=360),N},w=(x,N)=>v(x-N+180)-180;if(u.evt.shiftKey){let x=this._transformer,N,k=5;if(x){let S=x.rotationSnaps();Array.isArray(S)&&(N=S.map(T=>v(T)));let C=x.rotationSnapTolerance();typeof C=="number"&&(k=C);}if(N?.length){let S=v(_),C=_,T=1/0;for(let K of N){let L=Math.abs(w(S,K));L<T&&L<=k&&(C=K,T=L);}T!==1/0&&(_=C);}}if(p.rotation(_),this._rotateCenterAbsStart){let x=this._getNodeCenterAbs(p),N=this._rotateCenterAbsStart.x-x.x,k=this._rotateCenterAbsStart.y-x.y,S=p.getParent();if(S){let C=S.getAbsoluteTransform().copy().invert(),T=C.point({x:x.x,y:x.y}),K=C.point({x:x.x+N,y:x.y+k}),L=p.x()+(K.x-T.x),B=p.y()+(K.y-T.y);typeof p.position=="function"&&p.position({x:L,y:B});}}this._transformer?.forceUpdate(),this._restyleSideAnchors(),this._core.nodes.layer.batchDraw(),this._scheduleUIUpdate();}),d.on("dragend.rotate",()=>{if(this._rotateDragState=null,this._rotateCenterAbsStart=null,this._selected){let u=this._selected,p=u.getKonvaNode();!(u instanceof M)&&this._options.dragEnabled&&typeof p.draggable=="function"&&p.draggable(true);let f={x:p.x(),y:p.y(),rotation:p.rotation()};this._core?.eventBus.emit("node:transformed",this._selected,f);}this._core&&this._prevStageDraggableBeforeRotate!==null&&(this._core.stage.draggable(this._prevStageDraggableBeforeRotate),this._prevStageDraggableBeforeRotate=null),this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw(),this._core&&(this._core.stage.container().style.cursor="grab");});};l(n),l(o),l(s),l(r);let h=d=>{this._core&&(this._core.stage.container().style.cursor=d);},c=d=>{d.on("mouseenter.rotate-cursor",()=>{if(!this._core||!this._selected)return;let u=this._selected.getKonvaNode(),p=this._getNodeCenterAbs(u),f=d.getAbsolutePosition(),g=f.x-p.x,m=f.y-p.y,v=Math.atan2(m,g)*180/Math.PI+45;this._setRotateCursor(v);}),d.on("mouseleave.rotate-cursor",()=>{h("default");});};this._rotateHandles.tl&&c(this._rotateHandles.tl),this._rotateHandles.tr&&c(this._rotateHandles.tr),this._rotateHandles.br&&c(this._rotateHandles.br),this._rotateHandles.bl&&c(this._rotateHandles.bl),this._updateRotateHandlesPosition();}_destroyRotateHandles(){this._rotateHandlesGroup&&(this._rotateHandlesGroup.destroy(),this._rotateHandlesGroup=null),this._rotateHandles={tl:null,tr:null,br:null,bl:null},this._rotateDragState=null;}_getNodeCenterAbs(e){let t=e.getAbsoluteTransform().copy(),n=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false});return t.point({x:n.x+n.width/2,y:n.y+n.height/2})}_setRotateCursor(e){this._core&&this._applyRotatedCursor(e);}_applyRotatedCursor(e){if(!this._core)return;let t=`
58
58
  <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
59
59
  <g transform="rotate(${e.toString()} 12 12)">
60
60
  <g clip-path="url(#clip0_36_31)">
@@ -108,4 +108,4 @@ import H from'konva';var Ot=Object.defineProperty;var It=(S,i,e)=>i in S?Ot(S,i,
108
108
  </defs>
109
109
  </g>
110
110
  </svg>
111
- `.trim(),n=`data:image/svg+xml,${encodeURIComponent(t)}`,r=this._core.stage.container();r.style.cursor=`url("${n}") 12 12, grab`;}_updateRotateHandlesPosition(){if(!this._core||!this._selected||!this._rotateHandlesGroup)return;let e=this._selected.getKonvaNode(),t=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),o=t.width,n=t.height;if(o<=0||n<=0)return;let r=e.getAbsoluteTransform().copy(),s=k=>r.point(k),l=12,h=s({x:t.x+o/2,y:t.y+n/2}),p=s({x:t.x,y:t.y}),d=s({x:t.x+o,y:t.y}),c=s({x:t.x+o,y:t.y+n}),u=s({x:t.x,y:t.y+n}),f=k=>{let C=k.x-h.x,P=k.y-h.y,R=Math.hypot(C,P)||1;return {x:C/R,y:P/R}},g=f(p),_=f(d),m=f(c),b=f(u),v={x:p.x+g.x*l,y:p.y+g.y*l},w={x:d.x+_.x*l,y:d.y+_.y*l},y={x:c.x+m.x*l,y:c.y+m.y*l},N={x:u.x+b.x*l,y:u.y+b.y*l};this._rotateHandles.tl&&this._rotateHandles.tl.absolutePosition(v),this._rotateHandles.tr&&this._rotateHandles.tr.absolutePosition(w),this._rotateHandles.br&&this._rotateHandles.br.absolutePosition(y),this._rotateHandles.bl&&this._rotateHandles.bl.absolutePosition(N);let x=this._rotateHandlesGroup.getParent();if(x){let k=x.getAbsoluteTransform().decompose(),C=1/(Math.abs(k.scaleX)||1),P=1/(Math.abs(k.scaleY)||1);this._rotateHandles.tl&&this._rotateHandles.tl.scale({x:C,y:P}),this._rotateHandles.tr&&this._rotateHandles.tr.scale({x:C,y:P}),this._rotateHandles.br&&this._rotateHandles.br.scale({x:C,y:P}),this._rotateHandles.bl&&this._rotateHandles.bl.scale({x:C,y:P});}}_setupSizeLabel(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroySizeLabel();let t=new H.Label({listening:false,opacity:.95}),o=new H.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),n=new H.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:4,fill:"#ffffff"});t.add(o),t.add(n),e.add(t),this._sizeLabel=t,this._updateSizeLabel();}_scheduleUIUpdate(){this._uiUpdateDebounce.schedule(()=>{this._updateSizeLabel(),this._updateRotateHandlesPosition(),this._updateCornerRadiusHandlesPosition();});}_updateSizeLabel(){if(!this._core||!this._selected||!this._sizeLabel)return;let e=this._selected.getKonvaNode(),t=e.getClientRect({skipShadow:true,skipStroke:false}),o=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),n=e.getAbsoluteTransform().decompose(),r=this._core.nodes.world.getAbsoluteTransform().decompose(),s=Math.abs(n.scaleX)||1,l=Math.abs(n.scaleY)||1,h=Math.abs(r.scaleX)||1,p=Math.abs(r.scaleY)||1,d=o.width*(s/h),c=o.height*(l/p),u=Math.max(0,Math.round(d)),f=Math.max(0,Math.round(c));this._sizeLabel.getText().text(String(u)+" \xD7 "+String(f));let _=8,m=t.x+t.width/2,b=t.y+t.height+_,w=this._sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this._sizeLabel.absolutePosition({x:m,y:b}),this._sizeLabel.offsetX(w/2),this._sizeLabel.offsetY(0);let y=this._sizeLabel.getParent();if(y){let N=y.getAbsoluteTransform().decompose(),x=1/(Math.abs(N.scaleX)||1),k=1/(Math.abs(N.scaleY)||1);this._sizeLabel.scale({x,y:k});}this._sizeLabel.moveToTop(),this._transformer&&this._transformer.moveToTop(),this._cornerHandlesGroup&&this._cornerHandlesGroup.moveToTop();}_destroySizeLabel(){this._sizeLabel&&(this._sizeLabel.destroy(),this._sizeLabel=null);}_isCornerRadiusSupported(e){return e instanceof H.Rect||e instanceof H.Image}_getCornerRadiusArray(e){let t=e.cornerRadius();if(Array.isArray(t)){let[n=0,r=0,s=0,l=0]=t;return [n||0,r||0,s||0,l||0]}let o=typeof t=="number"?t:0;return [o,o,o,o]}_setCornerRadiusArray(e,t){let[o,n,r,s]=t;o===n&&n===r&&r===s?e.cornerRadius(o):e.cornerRadius(t);}_setupCornerRadiusHandles(e=false){if(!this._core||!this._selected)return;let t=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(t))return;let o=this._core.nodes.layer,n=this._core.stage;this._destroyCornerRadiusHandles();let r=new H.Group({name:"corner-radius-handles-group",listening:true});o.add(r),r.moveToTop(),r.visible(false),this._cornerHandlesGroup=r,t.off(".cornerRadiusHover"),t.on("mouseenter.cornerRadiusHover",()=>{!this._core||!this._cornerHandlesGroup||this._core.nodes.world.scaleX()<.3||this._cornerHandlesGroup.visible(true);}),t.on("mouseleave.cornerRadiusHover",()=>{if(!this._cornerHandlesGroup)return;let T=n.getPointerPosition();if(!T){this._cornerHandlesGroup.visible(false);return}let K=o.getIntersection(T);K&&this._cornerHandlesGroup.isAncestorOf(K)||this._cornerHandlesGroup.visible(false);}),r.on("mouseenter.cornerRadiusHover",()=>{!this._core||!this._cornerHandlesGroup||this._core.nodes.world.scaleX()<.3||this._cornerHandlesGroup.visible(true);}),r.on("mouseleave.cornerRadiusHover",()=>{this._cornerHandlesGroup&&this._cornerHandlesGroup.visible(false);});let s=n.getPointerPosition();if(s&&this._core.nodes.world.scaleX()>=.3){let M=o.getIntersection(s);M&&(M===t||t.isAncestorOf(M))&&this._cornerHandlesGroup.visible(true);}let l=()=>{let T=t.width(),K=t.height(),M=t.getAbsoluteScale(),G=1/(Math.abs(M.x)||1),U=1/(Math.abs(M.y)||1),Y=12*G,z=12*U,Q=Math.max(0,T/2-Y),ne=Math.max(0,K/2-z),ee=Math.min(Q,ne);return {tl:{corner:{x:Y,y:z},sign:{x:1,y:1},side:ee},tr:{corner:{x:T-Y,y:z},sign:{x:-1,y:1},side:ee},br:{corner:{x:T-Y,y:K-z},sign:{x:-1,y:-1},side:ee},bl:{corner:{x:Y,y:K-z},sign:{x:1,y:-1},side:ee}}},h=(T,K)=>{let M=t.getAbsoluteTransform().copy(),G=V=>M.copy().invert().point(V),U=V=>M.point(V),z=l()[K],Q=G(T),ne=Q.x-z.corner.x,ee=Q.y-z.corner.y,I=(z.sign.x*ne+z.sign.y*ee)/2;I=Math.max(0,Math.min(z.side,I));let W={x:z.corner.x+z.sign.x*I,y:z.corner.y+z.sign.y*I};return {snappedAbs:U(W),r:I,meta:z}},p=T=>new H.Line({name:T,points:[],stroke:e?"#4a90e2":"",strokeWidth:e?1:0,dash:e?[4,4]:[],closed:true,listening:false}),d=p("corner-square-tl"),c=p("corner-square-tr"),u=p("corner-square-br"),f=p("corner-square-bl");r.add(d,c,u,f);let g=T=>{let K=new H.Circle({name:T,radius:4,fill:"#ffffff",stroke:"#4a90e2",strokeWidth:1.5,draggable:true,dragOnTop:true,hitStrokeWidth:16});return K.on("mouseenter.corner-radius",()=>{this._core&&(this._core.stage.container().style.cursor="default");}),K},_=g("corner-radius-tl"),m=g("corner-radius-tr"),b=g("corner-radius-br"),v=g("corner-radius-bl");r.add(_,m,b,v),this._cornerHandles={tl:_,tr:m,br:b,bl:v};let w={tl:0,tr:1,br:2,bl:3},y=false,N=null,x=false,k=()=>{let T=t.getAbsoluteTransform().copy(),K=t.width(),M=t.height();return T.point({x:K/2,y:M/2})},C=()=>{let T={};return this._cornerHandles.tl&&(T.tl=this._cornerHandles.tl.getAbsolutePosition()),this._cornerHandles.tr&&(T.tr=this._cornerHandles.tr.getAbsolutePosition()),this._cornerHandles.br&&(T.br=this._cornerHandles.br.getAbsolutePosition()),this._cornerHandles.bl&&(T.bl=this._cornerHandles.bl.getAbsolutePosition()),T},P=(T,K=8)=>{let M=k();return Math.hypot(T.x-M.x,T.y-M.y)<=K},R=(T,K=6)=>{let M=k();return Math.min(Math.abs(T.x-M.x),Math.abs(T.y-M.y))<=K},L=(T,K=8)=>{let M=C(),G=0;return ["tl","tr","br","bl"].forEach(U=>{let Y=M[U];Y&&Math.hypot(Y.x-T.x,Y.y-T.y)<=K&&G++;}),G>=2},A=T=>{if(!y||N)return;let K=k(),M=T.x-K.x,G=T.y-K.y,U=Math.hypot(M,G);if(U<.1)return;M/=U,G/=U;let Y=t.getAbsoluteTransform().copy(),z=l(),Q=["tl","tr","br","bl"].reduce((I,W)=>{let se=z[W],V=Y.point(se.corner),ie=V.x-K.x,Z=V.y-K.y,J=Math.hypot(ie,Z)||1;return I[W]={x:ie/J,y:Z/J},I},{}),ne="tl",ee=-1/0;["tl","tr","br","bl"].forEach(I=>{let W=Q[I],se=M*W.x+G*W.y;se>ee&&(ee=se,ne=I);}),N=ne;},E=T=>K=>{A(K);let M=N??T,{snappedAbs:G,r:U,meta:Y}=h(K,M),z=t.width(),Q=t.height(),ne=Math.max(0,Math.min(z,Q)/2),ee=Y.side>0?U/Y.side:0,I=Math.round(ee*ne);I=Math.max(0,Math.min(I,ne));let W=this._getCornerRadiusArray(t),se=w[M];return x?W[se]=I:(W[0]=I,W[1]=I,W[2]=I,W[3]=I),this._setCornerRadiusArray(t,W),this._showRadiusLabelForCorner(se),O(),this._core?.nodes.layer.batchDraw(),G};_.dragBoundFunc(E("tl")),m.dragBoundFunc(E("tr")),b.dragBoundFunc(E("br")),v.dragBoundFunc(E("bl"));let O=()=>{let{tl:T,tr:K,br:M,bl:G}=this._cornerHandles;if(!T||!K||!M||!G)return;if(this._cornerHandlesSuppressed){this._cornerHandlesGroup?.visible(false),this._radiusLabel?.visible(false);return}if(this._core&&this._cornerHandlesGroup&&this._radiusLabel){if(this._core.nodes.world.scaleX()<.3){this._cornerHandlesGroup.visible(false),this._radiusLabel.visible(false);return}this._cornerHandlesGroup.visible(true);}let U=t.getAbsoluteTransform().copy(),Y=o.getAbsoluteTransform().copy().invert(),z=V=>U.point(V),Q=V=>Y.point(U.point(V)),ne=l(),ee=this._getCornerRadiusArray(t),I=(V,ie,Z)=>{let J=ne[V],xe=t.width(),Ie=t.height(),Ne=Math.max(0,Math.min(xe,Ie)/2),Ge=Math.max(0,Math.min(Ne,ee[ie]||0)),ze=Ne>0?Ge/Ne:0,Pt=Math.max(0,Math.min(J.side,ze*J.side)),Ht={x:J.corner.x+J.sign.x*Pt,y:J.corner.y+J.sign.y*Pt};Z.absolutePosition(z(Ht));},W=(V,ie)=>{let Z=ne[V],J=Z.corner,xe={x:Z.corner.x+Z.sign.x*Z.side,y:Z.corner.y+Z.sign.y*Z.side},Ie=Q({x:J.x,y:J.y}),Ne=Q({x:xe.x,y:J.y}),Ge=Q({x:xe.x,y:xe.y}),ze=Q({x:J.x,y:xe.y});ie.points([Ie.x,Ie.y,Ne.x,Ne.y,Ge.x,Ge.y,ze.x,ze.y]);};W("tl",d),W("tr",c),W("br",u),W("bl",f),I("tl",0,T),I("tr",1,K),I("br",2,M),I("bl",3,G);let se=this._cornerHandlesGroup?.getParent();if(se){let V=se.getAbsoluteTransform().decompose(),ie=1/(Math.abs(V.scaleX)||1),Z=1/(Math.abs(V.scaleY)||1);T.scale({x:ie,y:Z}),K.scale({x:ie,y:Z}),M.scale({x:ie,y:Z}),G.scale({x:ie,y:Z});}this._cornerHandlesGroup?.moveToTop();};this._updateCornerRadiusHandlesPosition=O;let j=(T,K)=>{x=!!K?.evt?.altKey;let M=T.getAbsolutePosition();if(y=P(M,8)||R(M,6)||L(M,8),N=null,y){let G=this._core?.stage.getPointerPosition()??M;A(G);}},X=(T,K)=>M=>{x=M.evt.altKey;},re=()=>{if(y=false,N=null,x=false,this._selected&&this._core){let T=this._selected.getKonvaNode(),K={x:T.x(),y:T.y()};typeof T.width=="function"&&(K.width=T.width()),typeof T.height=="function"&&(K.height=T.height()),this._core.eventBus.emit("node:transformed",this._selected,K);}};_.on("dragstart.corner-radius",T=>{j(_,T);}),m.on("dragstart.corner-radius",T=>{j(m,T);}),b.on("dragstart.corner-radius",T=>{j(b,T);}),v.on("dragstart.corner-radius",T=>{j(v,T);}),_.on("dragmove.corner-radius",X()),m.on("dragmove.corner-radius",X()),b.on("dragmove.corner-radius",X()),v.on("dragmove.corner-radius",X()),_.on("dragend.corner-radius",re),m.on("dragend.corner-radius",re),b.on("dragend.corner-radius",re),v.on("dragend.corner-radius",re);let F=T=>()=>{this._showRadiusLabelForCorner(T);},q=()=>{this._hideRadiusLabel();},oe=T=>()=>{this._showRadiusLabelForCorner(T);};_.on("mouseenter.corner-radius",F(0)),m.on("mouseenter.corner-radius",F(1)),b.on("mouseenter.corner-radius",F(2)),v.on("mouseenter.corner-radius",F(3)),_.on("mouseleave.corner-radius",q),m.on("mouseleave.corner-radius",q),b.on("mouseleave.corner-radius",q),v.on("mouseleave.corner-radius",q),_.on("dragstart.corner-radius",F(0)),m.on("dragstart.corner-radius",F(1)),b.on("dragstart.corner-radius",F(2)),v.on("dragstart.corner-radius",F(3)),_.on("dragmove.corner-radius",oe(0)),m.on("dragmove.corner-radius",oe(1)),b.on("dragmove.corner-radius",oe(2)),v.on("dragmove.corner-radius",oe(3)),_.on("dragend.corner-radius",q),m.on("dragend.corner-radius",q),b.on("dragend.corner-radius",q),v.on("dragend.corner-radius",q);let de=()=>{if(!this._selected)return;this._selected.getKonvaNode().draggable(false),this._restyleSideAnchors();},ce=()=>{if(!this._selected)return;let T=this._selected.getKonvaNode();this._options.dragEnabled&&T.draggable(true),this._restyleSideAnchors();};_.on("mousedown.corner-radius touchstart.corner-radius",de),m.on("mousedown.corner-radius touchstart.corner-radius",de),b.on("mousedown.corner-radius touchstart.corner-radius",de),v.on("mousedown.corner-radius touchstart.corner-radius",de),_.on("mouseup.corner-radius touchend.corner-radius",ce),m.on("mouseup.corner-radius touchend.corner-radius",ce),b.on("mouseup.corner-radius touchend.corner-radius",ce),v.on("mouseup.corner-radius touchend.corner-radius",ce);let $=".corner-squares",ye=false,we=()=>{ye||(ye=true,H.Util.requestAnimFrame(()=>{ye=false,O(),this._core?.nodes.layer.batchDraw();}));};n.on(["wheel","resize","xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(T=>T+$).join(" "),we),o.on(["xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(T=>T+$).join(" "),we),t.on(["dragmove","transform","xChange","yChange","widthChange","heightChange","rotationChange","scaleXChange","scaleYChange","positionChange","scaleChange"].map(T=>T+$).join(" "),we),this._transformer&&(this._transformer.on("transformstart"+$,()=>{this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel(),this._core?.nodes.layer.batchDraw();}),this._transformer.on("transform"+$,()=>{O(),this._core?.nodes.layer.batchDraw();}),this._transformer.on("transformend"+$,()=>{this._cornerHandlesSuppressed=false,we();})),r.on("destroy"+$,()=>{n.off($),o.off($),t.off($),this._transformer?.off($);}),O(),o.batchDraw();}_destroyCornerRadiusHandles(){this._cornerHandlesGroup&&(this._cornerHandlesGroup.destroy(),this._cornerHandlesGroup=null),this._cornerHandles={tl:null,tr:null,br:null,bl:null},this._core&&(this._core.stage.container().style.cursor="default"),this._destroyRadiusLabel(),this._selected&&this._selected.getKonvaNode().off(".overlay-sync");}_bakeRectScale(e){if(!(e instanceof H.Rect))return;let t=e.scaleX(),o=e.scaleY();if(t===1&&o===1)return;let n=e.getAbsolutePosition(),r=e.width(),s=e.height(),l=Math.abs(t)*r,h=Math.abs(o)*s;e.width(l),e.height(h),e.scaleX(1),e.scaleY(1),e.setAbsolutePosition(n);}_updateCornerRadiusHandlesPosition(){if(!this._core||!this._selected||!this._cornerHandlesGroup)return;let e=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(e))return;let t=e,o=t.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),n=o.width,r=o.height;if(n<=0||r<=0)return;let s=t.getAbsoluteTransform().copy(),l=x=>s.point(x),h=t.getAbsoluteScale(),p=1/(Math.abs(h.x)||1),d=1/(Math.abs(h.y)||1),c=12*p,u=12*d,f=this._getCornerRadiusArray(t),g=Math.min(n,r)/2||1,_=x=>{let k=Math.hypot(x.x,x.y)||1;return {x:x.x/k,y:x.y/k}},m=[_({x:n/2-c,y:r/2-u}),_({x:-(n/2-c),y:r/2-u}),_({x:-(n/2-c),y:-(r/2-u)}),_({x:n/2-c,y:-(r/2-u)})],b=l({x:o.x+c+m[0].x*Math.min(g,f[0]),y:o.y+u+m[0].y*Math.min(g,f[0])}),v=l({x:o.x+n-c+m[1].x*Math.min(g,f[1]),y:o.y+u+m[1].y*Math.min(g,f[1])}),w=l({x:o.x+n-c+m[2].x*Math.min(g,f[2]),y:o.y+r-u+m[2].y*Math.min(g,f[2])}),y=l({x:o.x+c+m[3].x*Math.min(g,f[3]),y:o.y+r-u+m[3].y*Math.min(g,f[3])});this._cornerHandles.tl&&this._cornerHandles.tl.absolutePosition(b),this._cornerHandles.tr&&this._cornerHandles.tr.absolutePosition(v),this._cornerHandles.br&&this._cornerHandles.br.absolutePosition(w),this._cornerHandles.bl&&this._cornerHandles.bl.absolutePosition(y);let N=this._cornerHandlesGroup.getParent();if(N){let x=N.getAbsoluteTransform().decompose(),k=1/(Math.abs(x.scaleX)||1),C=1/(Math.abs(x.scaleY)||1);this._cornerHandles.tl&&this._cornerHandles.tl.scale({x:k,y:C}),this._cornerHandles.tr&&this._cornerHandles.tr.scale({x:k,y:C}),this._cornerHandles.br&&this._cornerHandles.br.scale({x:k,y:C}),this._cornerHandles.bl&&this._cornerHandles.bl.scale({x:k,y:C});}this._cornerHandlesGroup.moveToTop();}_updateCornerRadiusHandlesVisibility(){if(!this._core||!this._selected||!this._cornerHandlesGroup)return;let t=this._core.nodes.world.scaleX(),o=this._core.stage,n=this._core.nodes.layer,r=this._selected.getKonvaNode(),s=o.getPointerPosition();if(!s){t<.3&&this._cornerHandlesGroup.visible(false);return}if(t<.3){this._cornerHandlesGroup.visible(false);return}let l=n.getIntersection(s);if(l){let h=l===r||r.isAncestorOf(l),p=this._cornerHandlesGroup.isAncestorOf(l);h||p?this._cornerHandlesGroup.visible(true):this._cornerHandlesGroup.visible(false);}else this._cornerHandlesGroup.visible(false);}_ensureRadiusLabel(){if(!this._core)return null;if(this._radiusLabel)return this._radiusLabel;let e=this._core.nodes.layer,t=new H.Label({listening:false,opacity:.95}),o=new H.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),n=new H.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:4,fill:"#ffffff"});return t.add(o),t.add(n),t.visible(false),e.add(t),this._radiusLabel=t,t}_updateRadiusLabelAt(e,t){let o=this._ensureRadiusLabel();if(!o)return;o.getText().text(t);let s=o.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width,l={x:8,y:8};o.absolutePosition({x:e.x-l.x,y:e.y+l.y}),o.offsetX(s),o.offsetY(0);let h=o.getParent();if(h){let p=h.getAbsoluteTransform().decompose(),d=1/(Math.abs(p.scaleX)||1),c=1/(Math.abs(p.scaleY)||1);o.scale({x:d,y:c});}o.visible(true),o.moveToTop(),this._transformer&&this._transformer.moveToTop();}_showRadiusLabelForCorner(e){if(!this._core||!this._selected)return;let t=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(t))return;let o=t,n=this._getCornerRadiusArray(o),r=Math.round(n[e]),s=e===0?this._cornerHandles.tl:e===1?this._cornerHandles.tr:e===2?this._cornerHandles.br:this._cornerHandles.bl;if(!s)return;let l=s.getAbsolutePosition();this._updateRadiusLabelAt(l,"Radius "+String(r));}_hideRadiusLabel(){this._radiusLabel&&this._radiusLabel.visible(false);}_destroyRadiusLabel(){this._radiusLabel&&(this._radiusLabel.destroy(),this._radiusLabel=null);}_findBaseNodeByTarget(e){if(!this._core)return null;if(this._selected){let o=this._selected.getKonvaNode();if(o===e)return this._selected;if(typeof o.isAncestorOf=="function"&&o.isAncestorOf(e))return this._selected}let t=null;for(let o of this._core.nodes.list()){let n=o.getKonvaNode();if(typeof n.isAncestorOf=="function"&&n.isAncestorOf(e)){let r=true;for(let s of this._core.nodes.list()){if(s===o)continue;let l=s.getKonvaNode();if(typeof l.isAncestorOf=="function"&&l.isAncestorOf(n)){r=false;break}}r&&(t=o);}}if(t)return t;for(let o of this._core.nodes.list())if(o.getKonvaNode()===e)return o;return null}_disableGroupChildrenDragging(e){let t=e.getChildren();for(let o of t){let n=o;typeof n.draggable=="function"&&n.draggable(false);}}};var ut=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_layer",null);a(this,"_rect",null);a(this,"_start",null);a(this,"_transformer",null);a(this,"_selecting",false);a(this,"_skipNextClick",false);a(this,"_lastPickedBaseNodes",[]);a(this,"_autoPanRafId",null);a(this,"_autoPanActive",false);a(this,"_autoPanEdgePx",50);a(this,"_autoPanMaxSpeedPx",20);a(this,"_options");this._options={rectStroke:e.rectStroke??"#2b83ff",rectFill:e.rectFill??"#2b83ff",rectStrokeWidth:e.rectStrokeWidth??1,rectOpacity:e.rectOpacity??.15,enableKeyboardShortcuts:e.enableKeyboardShortcuts??true};}onAttach(e){this._core=e;let t=new H.Layer({name:"area-selection-layer",listening:false});e.stage.add(t),this._layer=t,this._rect=new H.Rect({x:0,y:0,width:0,height:0,visible:false,stroke:this._options.rectStroke,strokeWidth:this._options.rectStrokeWidth,fill:this._options.rectFill,opacity:this._options.rectOpacity,listening:false}),t.add(this._rect);let o=e.stage;o.on("mousedown.area",n=>{if(n.evt.button!==0||n.target!==o&&n.target.getLayer()===e.nodes.layer)return;let r=o.getPointerPosition();if(!r||!this._rect)return;let s=o.findOne(".ruler-layer");if(s&&n.target.getLayer()===s)return;let l=o.findOne(".guides-layer");if(l&&n.target.getLayer()===l)return;let h=30;r.y<=h||r.x<=h||(this._selecting=true,this._start={x:r.x,y:r.y},this._rect.visible(true),this._rect.position({x:r.x,y:r.y}),this._rect.size({width:0,height:0}),this._layer?.batchDraw(),this._lastPickedBaseNodes=[],this._startAutoPanLoop());}),o.on("mousemove.area",()=>{if(!this._selecting||!this._rect||!this._start)return;let n=o.getPointerPosition();if(!n)return;let r=Math.min(this._start.x,n.x),s=Math.min(this._start.y,n.y),l=Math.abs(n.x-this._start.x),h=Math.abs(n.y-this._start.y);this._rect.position({x:r,y:s}),this._rect.size({width:l,height:h}),this._layer?.batchDraw();let p={x:r,y:s,width:l,height:h},d=this._core?.nodes.list()??[],c=new Set;for(let g of d){if(g instanceof ue)continue;let _=g.getKonvaNode();if(_.getLayer()!==this._core?.nodes.layer)continue;let b=_.getClientRect({skipShadow:true,skipStroke:false});if(this._rectsIntersect(p,b)){let v=this._findOwningGroupBaseNode(_);c.add(v??g);}}let u=Array.from(c),f=this._getSelectionPlugin();if(u.length>0&&(this._lastPickedBaseNodes=u),f){let g=f.getMultiGroupController();u.length>0&&g.ensure(u),this._core?.stage.batchDraw();}}),o.on("mouseup.area",n=>{if(!this._selecting)return;let r=false;if(this._rect?.visible()){let s=this._rect.size();r=s.width>2||s.height>2;}this._finalizeArea(),this._stopAutoPanLoop(),r&&(this._skipNextClick=true,this._core?.stage.setAttr("_skipSelectionEmptyClickOnce",true),n.cancelBubble=true);}),o.on("click.area",n=>{if(!this._core)return;if(this._skipNextClick){this._skipNextClick=false,n.cancelBubble=true;return}if(n.evt.shiftKey)return;let s=this._getSelectionPlugin()?.getMultiGroupController(),l=!!s?.isActive();if(!l&&!this._isPermanentGroupSelected())return;let h=n.target,p=this._currentGroupNode();p?this._isAncestor(p,h)||this._clearSelection():l&&s&&(s.isInsideTempByTarget(h)||(s.destroy(),this._core.stage.batchDraw()));});}onDetach(e){e.stage.off(".area"),this._stopAutoPanLoop(),this._clearSelection(),this._layer&&this._layer.destroy(),this._layer=null,this._rect=null;}_startAutoPanLoop(){if(!this._core||this._autoPanRafId!=null)return;this._autoPanActive=true;let e=this._core.nodes.world,t=this._core.stage,o=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let n=t.getPointerPosition();if(n){let r=t.width(),s=t.height(),l=this._autoPanEdgePx,h=0,p=0,d=Math.max(0,l-n.x),c=Math.max(0,n.x-(r-l)),u=Math.max(0,l-n.y),f=Math.max(0,n.y-(s-l)),g=_=>Math.min(1,_/l);if(h=this._autoPanMaxSpeedPx*(g(c)-g(d)),p=this._autoPanMaxSpeedPx*(g(f)-g(u)),h!==0||p!==0){if(e.x(e.x()-h),e.y(e.y()-p),this._start&&(this._start.x-=h,this._start.y-=p),this._rect&&this._start){let _=t.getPointerPosition();if(_){let m=Math.min(this._start.x,_.x),b=Math.min(this._start.y,_.y),v=Math.abs(_.x-this._start.x),w=Math.abs(_.y-this._start.y);this._rect.position({x:m,y:b}),this._rect.size({width:v,height:w});}}this._layer?.batchDraw(),this._core.nodes.layer.batchDraw();}}this._autoPanRafId=globalThis.requestAnimationFrame(o);};this._autoPanRafId=globalThis.requestAnimationFrame(o);}_stopAutoPanLoop(){this._autoPanActive=false,this._autoPanRafId!=null&&(globalThis.cancelAnimationFrame(this._autoPanRafId),this._autoPanRafId=null);}_finalizeArea(){if(!this._core||!this._rect||!this._start)return;this._selecting=false;let e=this._rect.getClientRect({skipStroke:true});this._rect.visible(false),this._layer?.batchDraw();let t=[];if(this._lastPickedBaseNodes.length>0)t=[...this._lastPickedBaseNodes];else {let n=this._core.nodes.list(),r=[];for(let h of n){let p=h.getKonvaNode();if(p.getLayer()!==this._core.nodes.layer)continue;let c=p.getClientRect({skipShadow:true,skipStroke:false});this._rectsIntersect(e,c)&&r.push(p);}let s=this._core.nodes.list(),l=new Set;for(let h of r){let p=s.find(c=>c.getKonvaNode()===h)??null,d=this._findOwningGroupBaseNode(h);d?l.add(d):p&&!(p instanceof ue)&&l.add(p);}t=Array.from(l);}let o=this._getSelectionPlugin();o&&(t.length>0?(o.getMultiGroupController().ensure(t),this._core.stage.batchDraw()):o.getMultiGroupController().destroy()),this._lastPickedBaseNodes=[];}_clearSelection(){this._isPermanentGroupSelected()&&(this._transformer&&this._transformer.destroy(),this._transformer=null,this._core?.stage.batchDraw());let t=this._getSelectionPlugin()?.getMultiGroupController();t&&t.destroy();}_getSelectionPlugin(){return this._core?this._core.plugins.list().find(t=>t instanceof ve)??null:null}_rectsIntersect(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}_findOwningGroupBaseNode(e){if(!this._core)return null;let o=this._core.nodes.list().filter(s=>s instanceof ue),n=e,r=null;for(;n;){let s=o.find(l=>l.getKonvaNode()===n)??null;s&&(r=s),n=n.getParent();}return r}_isAncestor(e,t){let o=t;for(;o;){if(o===e)return true;o=o.getParent();}return false}_isPermanentGroupSelected(){if(!this._transformer)return false;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return !t||!this._core?false:this._core.nodes.list().some(o=>o instanceof ue&&o.getKonvaNode()===t)}_currentGroupNode(){if(!this._transformer)return null;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return t&&t instanceof H.Group?t:null}};var pt=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_attached",false);a(this,"_panning",false);a(this,"_last",null);a(this,"_prevCursor",null);a(this,"_prevStageDraggable");a(this,"_onWheelDOM",e=>{if(!this._core||e.ctrlKey)return;e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation?.();let{deltaX:o,deltaY:n,shiftKey:r}=e;if(this._isTouchpadWheel(e)){if(r){let l=-(Math.abs(o)>=Math.abs(n)?o:n);this._pan(l,0);}else {let s=-o,l=-n;this._pan(s,l);}return}if(r){let s=n<0?-Math.abs(n):Math.abs(n);this._pan(s,0);}else {let s=-n;this._pan(0,s);}});a(this,"_onMouseDownKonva",e=>{if(!this._core||!this._options.enablePanning)return;let t=e.evt.button;if(!(this._options.allowMiddleButtonPan&&t===1||this._options.allowRightButtonPan&&t===2))return;this._panning=true;let n=this._core.stage.getPointerPosition();n&&(this._last={x:n.x,y:n.y});let r=this._core.stage.container();this._prevCursor=r.style.cursor||null,r.style.cursor="grabbing",e.evt.preventDefault();});a(this,"_onMouseMoveKonva",e=>{if(!this._core||!this._options.enablePanning||!this._panning||!this._last)return;let t=this._core.stage.getPointerPosition();if(!t)return;let o=t.x-this._last.x,n=t.y-this._last.y;this._pan(o,n),this._last={x:t.x,y:t.y};});a(this,"_onMouseUpKonva",e=>{if(!this._options.enablePanning||(this._panning=false,this._last=null,!this._core))return;let t=this._core.stage.container();this._prevCursor!==null?(t.style.cursor=this._prevCursor,this._prevCursor=null):t.style.removeProperty("cursor");});a(this,"_onMouseLeaveKonva",e=>{if(!this._options.enablePanning||(this._panning=false,this._last=null,!this._core))return;let t=this._core.stage.container();this._prevCursor!==null?(t.style.cursor=this._prevCursor,this._prevCursor=null):t.style.removeProperty("cursor");});a(this,"_onContextMenuDOM",e=>{this._options.disableContextMenu&&e.preventDefault();});a(this,"_handleKeyDown",e=>{if(this._options.ignoreEditableTargets&&this._isEditableTarget(e.target)||!this._core)return;let t=e.code==="Equal"||e.code==="NumpadAdd",o=e.code==="Minus"||e.code==="NumpadSubtract";if(t||o){e.preventDefault(),t?this._core.camera.zoomIn():this._core.camera.zoomOut();return}if(this._options.enableArrows){let n=this._core.camera.panStep;switch(e.key){case "ArrowLeft":e.preventDefault(),this._pan(n,0);return;case "ArrowRight":e.preventDefault(),this._pan(-n,0);return;case "ArrowUp":e.preventDefault(),this._pan(0,n);return;case "ArrowDown":e.preventDefault(),this._pan(0,-n);return}}});let{target:t=globalThis,zoomStep:o=1.1,panStep:n=40,ignoreEditableTargets:r=true,enableArrows:s=true,enablePanning:l=true,allowMiddleButtonPan:h=true,allowRightButtonPan:p=true,disableContextMenu:d=true}=e;this._options={target:t,zoomStep:o,panStep:n,ignoreEditableTargets:r,enableArrows:s,enablePanning:l,allowMiddleButtonPan:h,allowRightButtonPan:p,disableContextMenu:d};}setOptions(e){let t=this._options.disableContextMenu;if(this._options={...this._options,...e},this._attached&&this._core&&(typeof e.zoomStep=="number"&&this._core.camera.setZoomStep(this._options.zoomStep),typeof e.panStep=="number"&&this._core.camera.setPanStep(this._options.panStep),typeof e.disableContextMenu=="boolean"&&e.disableContextMenu!==t)){let o=this._core.stage.container();this._options.disableContextMenu?o.addEventListener("contextmenu",this._onContextMenuDOM):o.removeEventListener("contextmenu",this._onContextMenuDOM);}}onAttach(e){this._core=e;let t=this._core.stage;typeof this._options.zoomStep=="number"&&this._core.camera.setZoomStep(this._options.zoomStep),typeof this._options.panStep=="number"&&this._core.camera.setPanStep(this._options.panStep),this._prevStageDraggable=t.draggable(),t.draggable(false),this._options.target.addEventListener("keydown",this._handleKeyDown),this._options.enablePanning&&(t.on("mousedown.cameraHotkeys",this._onMouseDownKonva),t.on("mousemove.cameraHotkeys",this._onMouseMoveKonva),t.on("mouseup.cameraHotkeys",this._onMouseUpKonva),t.on("mouseleave.cameraHotkeys",this._onMouseLeaveKonva),this._options.disableContextMenu&&t.container().addEventListener("contextmenu",this._onContextMenuDOM)),t.container().addEventListener("wheel",this._onWheelDOM,{passive:false,capture:true}),t.on("wheel.cameraHotkeysGuard",n=>{n.evt.ctrlKey||(n.evt.preventDefault(),n.cancelBubble=true);}),this._attached=true;}onDetach(e){if(!this._attached)return;this._options.target.removeEventListener("keydown",this._handleKeyDown);let o=e.stage;o.off(".cameraHotkeys"),o.off(".cameraHotkeysGuard"),o.container().removeEventListener("wheel",this._onWheelDOM),this._options.enablePanning&&o.container().removeEventListener("contextmenu",this._onContextMenuDOM),this._prevStageDraggable!==void 0&&o.draggable(this._prevStageDraggable),this._attached=false,this._last=null,this._prevCursor=null;}_isEditableTarget(e){let t=e;if(!t)return false;let o=t.tagName;return t.isContentEditable||o==="INPUT"||o==="TEXTAREA"||o==="SELECT"}_isTouchpadWheel(e){return e.deltaMode===0&&(Math.abs(e.deltaX)>0||Math.abs(e.deltaY)<50)}_pan(e,t){if(!this._core)return;let o=this._core.nodes.world,n=o.x()+e,r=o.y()+t;o.position({x:n,y:r}),this._core.eventBus.emit("camera:pan",{dx:e,dy:t,position:{x:n,y:r}}),this._core.stage.batchDraw();}};var le=class{attach(i){this.onAttach(i);}detach(i){this.onDetach(i);}};var ft=class extends te{constructor(){super(...arguments);a(this,"_container",null);a(this,"_onDragOver",null);a(this,"_onDrop",null);}onAttach(e,t){let o=t.stage.container();this._container=o,this._onDragOver=n=>{n.preventDefault();},this._onDrop=n=>{e.handleDrop(n);},o.addEventListener("dragover",this._onDragOver),o.addEventListener("drop",this._onDrop);}onDetach(e,t){this._container&&this._onDragOver&&this._container.removeEventListener("dragover",this._onDragOver),this._container&&this._onDrop&&this._container.removeEventListener("drop",this._onDrop),this._container=null,this._onDragOver=null,this._onDrop=null;}},rt=class extends le{constructor(e){super();a(this,"_objectUrl");a(this,"_revoked",false);this._objectUrl=e;}onAttach(e){}onDetach(){this._revoked||(URL.revokeObjectURL(this._objectUrl),this._revoked=true);}},gt=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_dragDropAddon",null);a(this,"_onPaste",e=>{this._handlePaste(e);});let{target:t=globalThis,ignoreEditableTargets:o=true}=e;this._options={target:t,ignoreEditableTargets:o,maxImageSize:e.maxImageSize??Number.POSITIVE_INFINITY,enableDragDrop:e.enableDragDrop??true},this._options.enableDragDrop&&(this._dragDropAddon=new ft,this.addons.add(this._dragDropAddon));}onAttach(e){this._core=e,this._options.target.addEventListener("paste",this._onPaste);}onDetach(e){this._options.target.removeEventListener("paste",this._onPaste),this._core=void 0;}async _handlePaste(e){if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let t=e.clipboardData;if(!t)return;let o=this._getPastePosition();await this._handleDataTransfer(t,o,e);}async handleDrop(e){if(!this._core)return;let t=e.dataTransfer;if(!t)return;e.preventDefault(),e.stopImmediatePropagation(),this._core.stage.setPointersPositions(e);let o=this._core.stage.getPointerPosition();if(!o)return;let s=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(o);await this._handleDataTransfer(t,{x:s.x,y:s.y},e);}async _handleDataTransfer(e,t,o){if(!this._core)return;let n=Array.from(e.items);for(let d=n.length-1;d>=0;d--){let c=n[d];if(c){if(c.kind==="file"){let u=c.getAsFile();if(u?.type==="image/svg+xml"||u?.name.toLowerCase().endsWith(".svg")){o?.preventDefault(),await this._pasteSvgFile(u,t);return}if(u&&(u.type.startsWith("video/")||this._looksLikeVideoFile(u))){o?.preventDefault(),await this._pasteVideoFile(u,t);return}if(u&&(u.type.startsWith("image/")||u.type==="")){o?.preventDefault(),await this._pasteImageFile(u,t);return}}if(c.kind==="string"&&(c.type==="text/plain"||c.type==="text/html")){let u=await this._getAsString(c),f=this._extractSvgMarkup(u);if(f){o?.preventDefault(),this._pasteSvgText(f,t);return}let g=c.type==="text/html"?this._htmlToText(u):u;if(g.trim().length>0){o?.preventDefault(),this._core.nodes.addText({x:t.x,y:t.y,text:g});return}}}}let r=Array.from(e.files??[]);for(let d=r.length-1;d>=0;d--){let c=r[d];if(c){if(c.type==="image/svg+xml"||c.name.toLowerCase().endsWith(".svg")){o?.preventDefault(),await this._pasteSvgFile(c,t);return}if(c.type.startsWith("video/")||this._looksLikeVideoFile(c)){o?.preventDefault(),await this._pasteVideoFile(c,t);return}if(c.type.startsWith("image/")||c.type===""){o?.preventDefault(),await this._pasteImageFile(c,t);return}}}let s=e.getData("text/plain")||"",l=e.getData("text/html")||"",h=this._extractSvgMarkup(l)??this._extractSvgMarkup(s);if(h){o?.preventDefault(),this._pasteSvgText(h,t);return}let p=this._htmlToText(l||s);if(p.trim().length>0){o?.preventDefault(),this._core.nodes.addText({x:t.x,y:t.y,text:p});return}}_pasteSvgText(e,t){if(!this._core)return;let o=this._svgTextToSrc(e),n=this._extractSvgSize(e),r=this._fitIntoMaxSize(n,this._options.maxImageSize);this._core.nodes.addSvg({x:t.x,y:t.y,src:o,width:r.width,height:r.height});}async _pasteSvgFile(e,t){let o=await this._readFileAsText(e);this._pasteSvgText(o,t);}async _pasteImageFile(e,t){if(!this._core)return;let o=URL.createObjectURL(e);try{let n=await this._loadImageSize(o),r=this._fitIntoMaxSize(n,this._options.maxImageSize);this._core.nodes.addImage({x:t.x,y:t.y,src:o,width:r.width,height:r.height}).addons.add(new rt(o));}catch(n){throw URL.revokeObjectURL(o),n}}async _pasteVideoFile(e,t){if(!this._core)return;let o=URL.createObjectURL(e);try{let n=this._core.nodes.addVideo({x:t.x,y:t.y,width:320,height:240,autoplay:!0,loop:!0,muted:!1,volume:1});await n.setSrc(o,{autoplay:!0,loop:!0,muted:!1,volume:1});let r=n.getVideoElement(),s=r?{width:r.videoWidth||0,height:r.videoHeight||0}:{width:0,height:0},l=this._fitIntoMaxSize(s,this._options.maxImageSize);n.setSize({width:l.width,height:l.height}),n.addons.add(new rt(o));}catch(n){throw URL.revokeObjectURL(o),n}}_fitIntoMaxSize(e,t){if(!isFinite(e.width)||!isFinite(e.height)||e.width<=0||e.height<=0)return {width:150,height:150};if(!isFinite(t)||t<=0)return e;let o=Math.max(e.width,e.height);if(o<=t)return e;let n=t/o;return {width:Math.max(1,Math.round(e.width*n)),height:Math.max(1,Math.round(e.height*n))}}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_getPastePosition(){if(!this._core)return {x:0,y:0};let t=this._core.stage.getPointerPosition();if(t&&this._isPointerOnScreen(t)){let r=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(t);return {x:r.x,y:r.y}}return this._getScreenCenter()}_isPointerOnScreen(e){if(!this._core)return false;let t=this._core.stage,o=t.width(),n=t.height();return e.x>=0&&e.x<=o&&e.y>=0&&e.y<=n}_getScreenCenter(){if(!this._core)return {x:0,y:0};let e=this._core.stage,t=this._core.nodes.world,o=e.width()/2,n=e.height()/2,s=t.getAbsoluteTransform().copy().invert().point({x:o,y:n});return {x:s.x,y:s.y}}_getAsString(e){return new Promise(t=>{e.getAsString(o=>{t(o);});})}_looksLikeVideoFile(e){let t=typeof e.name=="string"?e.name.toLowerCase():"";return t?t.endsWith(".mp4")||t.endsWith(".webm")||t.endsWith(".mov")||t.endsWith(".m4v")||t.endsWith(".mkv")||t.endsWith(".avi"):false}_htmlToText(e){let t=globalThis.DOMParser??null;return t?new t().parseFromString(e,"text/html").body.textContent||"":e}_readFileAsText(e){return new Promise((t,o)=>{let n=new FileReader;n.onload=()=>{let r=n.result;if(typeof r=="string"){t(r);return}o(new Error("Failed to read clipboard SVG"));},n.onerror=()=>{o(new Error("Failed to read clipboard SVG"));},n.readAsText(e);})}_extractSvgMarkup(e){let t=e.trim(),o=t.toLowerCase(),n=o.indexOf("<svg");if(n===-1)return null;let r=o.lastIndexOf("</svg>");return r===-1?null:t.slice(n,r+6)}_svgTextToSrc(e){return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`}_parseSvgNumber(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}_extractSvgSize(e){let t=/\bwidth\s*=\s*["']([^"']+)["']/i,o=/\bheight\s*=\s*["']([^"']+)["']/i,n=t.exec(e),r=o.exec(e),s=n?.[1]?this._parseSvgNumber(n[1]):0,l=r?.[1]?this._parseSvgNumber(r[1]):0;if(s>0&&l>0)return {width:s,height:l};let p=/\bviewBox\s*=\s*["']([^"']+)["']/i.exec(e);if(p?.[1]){let d=p[1].trim().split(/[\s,]+/),c=d.length>=4?d[2]:void 0,u=d.length>=4?d[3]:void 0,f=c?this._parseSvgNumber(c):0,g=u?this._parseSvgNumber(u):0;if(f>0&&g>0)return {width:f,height:g}}return {width:150,height:150}}_loadImageSize(e){return new Promise((t,o)=>{let n=globalThis.Image??null;if(!n){o(new Error("Image constructor is not available in current environment"));return}let r=new n;r.onload=()=>{t({width:r.naturalWidth||r.width,height:r.naturalHeight||r.height});},r.onerror=()=>{o(new Error("Failed to load clipboard image"));},r.src=e;})}};var _t=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_layer",null);a(this,"_shape",null);a(this,"_stepX");a(this,"_stepY");a(this,"_color");a(this,"_lineWidth");a(this,"_visible");a(this,"_minScaleToShow");a(this,"_enableSnap");a(this,"_dragMoveHandler",null);a(this,"_nodesAddHandler",null);a(this,"_nodesRemoveHandler",null);a(this,"_redrawScheduled",false);a(this,"_transformersCache",[]);a(this,"_cacheInvalidated",true);this._stepX=Math.max(1,e.stepX??1),this._stepY=Math.max(1,e.stepY??1),this._color=e.color??"#2b313a",this._lineWidth=e.lineWidth??1,this._visible=e.visible??true,this._minScaleToShow=e.minScaleToShow??8,this._enableSnap=e.enableSnap??true;}onAttach(e){this._core=e;let t=e.nodes.layer,o=(d,c)=>{if(!this._visible||!this._core)return;let u=this._core.stage,f=this._core.nodes.world,g=f.scaleX();if(this._minScaleToShow!=null&&g<this._minScaleToShow)return;let _=u.width(),m=u.height(),b=f.scaleX(),v=f.scaleY(),w=Math.max(1,this._stepX)*Math.max(1e-6,b),y=Math.max(1,this._stepY)*Math.max(1e-6,v),N=(f.x()%w+w)%w,x=(f.y()%y+y)%y;d.beginPath(),d.lineWidth=this._lineWidth,d.strokeStyle=this._color;for(let k=N;k<=_;k+=w)d.moveTo(k,0),d.lineTo(k,m);for(let k=x;k<=m;k+=y)d.moveTo(0,k),d.lineTo(_,k);d.stroke();},n=new H.Shape({listening:false,sceneFunc:o});t.add(n),this._layer=t,this._shape=n;let r=e.stage,s=e.nodes.world;r.on("resize.grid",()=>{this._scheduleRedraw();}),s.on("xChange.grid yChange.grid scaleXChange.grid scaleYChange.grid",()=>{this._scheduleRedraw();}),(()=>{this._cacheInvalidated&&(this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false);for(let d of this._transformersCache)d.moveToTop();this._shape?.moveToTop();for(let d of this._transformersCache)d.moveToTop();})(),this._dragMoveHandler=d=>{if(!this._core||!this._enableSnap)return;let c=this._core.stage,u=this._core.nodes.world,f=d.target;if(f===c||f instanceof H.Layer)return;let g=this._core.nodes.layer,_=f,m=false;for(;_;){if(_===g){m=true;break}_=_.getParent();}if(!m)return;let b=f;if(typeof b.draggable=="function"&&!b.draggable())return;let v=f.getAbsolutePosition(),w=u.scaleX()||1,y=u.scaleY()||1;if(this._minScaleToShow!=null?w>=this._minScaleToShow:false){let x=(v.x-u.x())/w,k=(v.y-u.y())/y,C=Math.max(1,this._stepX),P=Math.max(1,this._stepY),R=Math.round(x/C)*C,L=Math.round(k/P)*P,A=R*w+u.x(),E=L*y+u.y();(Math.abs(A-v.x)>.001||Math.abs(E-v.y)>.001)&&f.absolutePosition({x:A,y:E});}else {let x=(v.x-u.x())/w,k=(v.y-u.y())/y,C=Math.max(1,this._stepX),P=Math.max(1,this._stepY),R=Math.round(x/C)*C,L=Math.round(k/P)*P,A=R*w+u.x(),E=L*y+u.y();(Math.abs(A-v.x)>.001||Math.abs(E-v.y)>.001)&&f.absolutePosition({x:A,y:E});}},r.on("dragmove.grid",this._dragMoveHandler);let h=d=>{let c=d;if((typeof c.getClassName=="function"?c.getClassName():"")!=="Transformer")return;let f=d,g=(_,m)=>{let b=m;if(!this._enableSnap||!this._core||!(typeof c.nodes=="function"?c.nodes():[])[0])return b;let y=typeof c.getActiveAnchor=="function"?c.getActiveAnchor():"";if(y==="rotater")return b;let N=Math.max(1,this._stepX),x=Math.max(1,this._stepY),k=typeof y=="string"?y:"",C=this._core.nodes.world.getAbsoluteTransform(),P=C.copy();P.invert();let R=b.x,L=b.x+b.width,A=b.y,E=b.y+b.height,O=P.point({x:R,y:A}).x,j=P.point({x:L,y:A}).x,X=P.point({x:R,y:A}).y,re=P.point({x:R,y:E}).y,F=O,q=j,oe=X,de=re,ce=(G,U)=>Math.round((G+1e-9)/U)*U;k.includes("left")&&(F=ce(O,N)),k.includes("right")&&(q=ce(j,N)),k.includes("top")&&(oe=ce(X,x)),k.includes("bottom")&&(de=ce(re,x)),q-F<N&&(k.includes("left")?F=q-N:q=F+N),de-oe<x&&(k.includes("top")?oe=de-x:de=oe+x);let $=C.point({x:F,y:oe}).x,ye=C.point({x:F,y:oe}).y,we=C.point({x:q,y:oe}).x,T=C.point({x:F,y:de}).y,K=G=>Math.round(G*1e3)/1e3;return {x:K($),y:K(ye),width:K(we-$),height:K(T-ye),rotation:b.rotation}};globalThis.queueMicrotask(()=>{f.boundBoxFunc(g);});},p=d=>{h(d);let c=d,u=typeof c.getChildren=="function"?c.getChildren():[];for(let f of u)p(f);};p(e.nodes.layer),this._nodesAddHandler=d=>{let c=d.child??d.target;p(c);let u=c;if((typeof u.getClassName=="function"?u.getClassName():"")==="Transformer"){this._cacheInvalidated=true,c.moveToTop(),this._shape?.moveToTop(),this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false;for(let g of this._transformersCache)g.moveToTop();}},this._nodesRemoveHandler=d=>{let c=d.child??d.target,u=_=>{let m=_;(typeof m.getClassName=="function"?m.getClassName():"")==="Transformer"&&_.boundBoxFunc?.(void 0);let v=typeof m.getChildren=="function"?m.getChildren():[];for(let w of v)u(w);};u(c);let f=c;(typeof f.getClassName=="function"?f.getClassName():"")==="Transformer"&&(this._cacheInvalidated=true),this._shape?.moveToTop(),this._cacheInvalidated&&(this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false);for(let _ of this._transformersCache)_.moveToTop();},e.nodes.layer.on("add.grid",this._nodesAddHandler),e.nodes.layer.on("remove.grid",this._nodesRemoveHandler),e.nodes.layer.on("cornerRadiusChange.grid",d=>{let c=d.target;if((typeof c.getClassName=="function"?c.getClassName():"")!=="Rect")return;let f=c.cornerRadius;if(typeof f!="function")return;let g=f.call(c),_=w=>{c.cornerRadius(w);},m=this._core?.stage,b=m?.scaleX()??1,v=this._minScaleToShow!=null?b>=this._minScaleToShow:false;if(Array.isArray(g)){let w=g.map(y=>{if(v){let N=m?.scaleX()??1,x=m?.scaleY()??1,k=y*(.5*(N+x));return Math.max(0,Math.round(k))/Math.max(1e-6,.5*(N+x))}else return Math.max(0,Math.round(y))});_(w);}else if(typeof g=="number")if(v){let w=m?.scaleX()??1,y=m?.scaleY()??1,N=g*(.5*(w+y)),x=Math.max(0,Math.round(N));_(x/Math.max(1e-6,.5*(w+y)));}else _(Math.max(0,Math.round(g)));});}_scheduleRedraw(){if(this._redrawScheduled)return;this._redrawScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._redrawScheduled=false,this._layer?.batchDraw();});}onDetach(e){e.stage.off(".grid"),e.nodes.layer.off(".grid"),this._shape&&this._shape.destroy(),this._shape=null,this._layer=null,this._dragMoveHandler=null,this._nodesAddHandler=null,this._nodesRemoveHandler=null,e.stage.batchDraw();}setVisible(e){this._visible=e,this._core&&this._core.stage.batchDraw();}get stepX(){return this._stepX}get stepY(){return this._stepY}get minScaleToShow(){return this._minScaleToShow}setStep(e,t){this._stepX=Math.max(1,e),this._stepY=Math.max(1,t),this._core&&this._core.stage.batchDraw();}setMinScaleToShow(e){this._minScaleToShow=e,this._core&&this._core.stage.batchDraw();}setSnap(e){this._enableSnap=e;}};var mt=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_history");a(this,"_options");a(this,"_isUndoRedoInProgress",false);a(this,"_dragStartStateCache",new Map);a(this,"_isBatchMode",false);a(this,"_batchBuffer",[]);a(this,"_batchCommitTimer",null);a(this,"_onKeyDown",e=>{if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let t=e.ctrlKey||e.metaKey,o=e.shiftKey;if(t&&!o&&e.code==="KeyZ"){e.preventDefault(),this._performUndo();return}if(t&&o&&e.code==="KeyZ"){e.preventDefault(),this._performRedo();return}});a(this,"_onDragStart",e=>{if(this._isUndoRedoInProgress)return;let t=e.target;this._debug("dragstart raw target",{targetName:t.name(),targetClassName:t.getClassName(),targetId:t.id()});let o=t.name();if(typeof o=="string"&&o.includes("temp-multi-group")){this._isBatchMode=true,this._batchBuffer=[];let s=t.getChildren();for(let l of s){let h=this._findBaseNodeByKonva(l);if(h){let p=this._captureTransformState(h);this._dragStartStateCache.set(h.id,p),this._debug("dragstart (temp-multi child)",{nodeId:h.id});}}return}let n=this._findBaseNodeByKonva(t);if(n){let r=this._captureTransformState(n);this._dragStartStateCache.set(n.id,r),this._debug("dragstart",{nodeId:n.id,state:r});}else this._debug("dragstart - baseNode not found for target");});a(this,"_onDragEnd",e=>{});a(this,"_onTransformStart",e=>{if(this._isUndoRedoInProgress)return;let t=e.target;this._debug("transformstart raw target",{targetName:t.name(),targetClassName:t.getClassName(),targetId:t.id()});let o=t.name();if(typeof o=="string"&&o.includes("temp-multi-group")){this._isBatchMode=true,this._batchBuffer=[];let s=t.getChildren();for(let l of s){let h=this._findBaseNodeByKonva(l);if(h){let p=this._captureTransformState(h);this._dragStartStateCache.set(h.id,p),this._debug("transformstart (temp-multi child)",{nodeId:h.id});}}return}let n=this._findBaseNodeByKonva(t);if(n){let r=this._captureTransformState(n);this._dragStartStateCache.set(n.id,r),this._debug("transformstart",{nodeId:n.id,state:r});}else this._debug("transformstart - baseNode not found for target");});a(this,"_onTransformEnd",e=>{});a(this,"_onNodeCreated",e=>{if(this._isUndoRedoInProgress){this._debug("node:created skipped (undo/redo in progress)",e.id);return}let t=this._serializeNode(e),o={type:"create",nodeId:e.id,before:null,after:t,timestamp:Date.now()};this._history.push(o),this._dragStartStateCache.set(e.id,this._captureTransformState(e)),this._trimHistoryIfNeeded();});a(this,"_onNodeRemoved",e=>{if(this._isUndoRedoInProgress)return;let t=this._serializeNode(e),o={type:"remove",nodeId:e.id,before:t,after:null,timestamp:Date.now()};this._isBatchMode?this._batchBuffer.push(o):(this._history.push(o),this._trimHistoryIfNeeded()),this._dragStartStateCache.delete(e.id);});a(this,"_onNodeTransformed",(e,t)=>{if(this._isUndoRedoInProgress){this._debug("node:transformed skipped (undo/redo in progress)",e.id);return}let o=this._dragStartStateCache.get(e.id),n=this._buildAfterState(e,t);if(!o){this._debug("transform - no before state, saving current",e.id),this._dragStartStateCache.set(e.id,n);return}if(this._statesEqual(o,n)){this._debug("transform skipped - no changes",e.id);return}let r={type:"transform",nodeId:e.id,before:o,after:n,timestamp:Date.now()};this._debug("transform recorded",{nodeId:e.id,before:o,after:n,batchMode:this._isBatchMode}),this._isBatchMode?(this._batchBuffer.push(r),this._scheduleBatchCommit()):(this._history.push(r),this._trimHistoryIfNeeded()),this._dragStartStateCache.set(e.id,n);});a(this,"_onZIndexChanged",(e,t,o)=>{if(this._isUndoRedoInProgress)return;let n={type:"zIndex",nodeId:e.id,before:{zIndex:t},after:{zIndex:o},timestamp:Date.now()};this._history.push(n),this._trimHistoryIfNeeded();});a(this,"_onGroupCreated",(e,t)=>{if(this._isUndoRedoInProgress)return;let o=t.map(s=>this._serializeNode(s)),n=t.map(s=>s.id),r={type:"group",nodeId:e.id,before:{childIds:n,childStates:o},after:this._serializeNode(e),timestamp:Date.now()};this._history.push(r),this._trimHistoryIfNeeded();});a(this,"_onGroupUngrouped",(e,t)=>{if(this._isUndoRedoInProgress)return;let o=this._serializeNode(e),n=t.map(s=>this._serializeNode(s)),r={type:"ungroup",nodeId:e.id,before:o,after:{childStates:n},timestamp:Date.now()};this._history.push(r),this._trimHistoryIfNeeded();});this._history=new Be;let{target:t=globalThis,ignoreEditableTargets:o=true,maxHistoryLength:n=100}=e;this._options={target:t,ignoreEditableTargets:o,maxHistoryLength:n};}getHistoryManager(){return this._history}startBatch(){this._batchCommitTimer!==null&&(globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=null),this._isBatchMode=true,this._batchBuffer=[],this._debug("batch started");}commitBatch(){this._batchCommitTimer!==null&&(globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=null),this._finishBatch();}isBatchMode(){return this._isBatchMode}onAttach(e){this._core=e,this._options.target.addEventListener("keydown",this._onKeyDown),e.eventBus.on("node:created",this._onNodeCreated),e.eventBus.on("node:removed",this._onNodeRemoved),e.eventBus.on("node:transformed",this._onNodeTransformed),e.eventBus.on("node:zIndexChanged",this._onZIndexChanged),e.eventBus.on("group:created",this._onGroupCreated),e.eventBus.on("group:ungrouped",this._onGroupUngrouped);let t=e.nodes.world,o=e.nodes.layer;t.on("dragstart.history",this._onDragStart),t.on("dragend.history",this._onDragEnd),o.on("transformstart.history",this._onTransformStart),o.on("transformend.history",this._onTransformEnd),this._debug("attached");}onDetach(e){this._options.target.removeEventListener("keydown",this._onKeyDown),e.eventBus.off("node:created",this._onNodeCreated),e.eventBus.off("node:removed",this._onNodeRemoved),e.eventBus.off("node:transformed",this._onNodeTransformed),e.eventBus.off("node:zIndexChanged",this._onZIndexChanged),e.eventBus.off("group:created",this._onGroupCreated),e.eventBus.off("group:ungrouped",this._onGroupUngrouped),e.nodes.world.off(".history"),e.nodes.layer.off(".history"),this._core=void 0,this._dragStartStateCache.clear(),this._debug("detached");}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_finishBatch(){if(!this._isBatchMode||this._batchBuffer.length===0){this._isBatchMode=false,this._batchBuffer=[];return}let e={type:"batch",nodeId:"",before:null,after:null,timestamp:Date.now(),children:[...this._batchBuffer]};this._debug("batch recorded",{childCount:this._batchBuffer.length}),this._history.push(e),this._trimHistoryIfNeeded(),this._isBatchMode=false,this._batchBuffer=[];}_performUndo(){if(!this._core)return;let e=this._history.undo();if(!e){this._debug("undo","nothing to undo");return}this._isUndoRedoInProgress=true;try{this._applyActionState(e,"before"),this._debug("undo applied",e);}finally{this._isUndoRedoInProgress=false;}this._core.stage.batchDraw();}_performRedo(){if(!this._core)return;let e=this._history.redo();if(!e){this._debug("redo","nothing to redo");return}this._isUndoRedoInProgress=true;try{this._applyActionState(e,"after"),this._debug("redo applied",e);}finally{this._isUndoRedoInProgress=false;}this._core.stage.batchDraw();}_applyActionState(e,t){if(!this._core)return;let o=t==="before"?e.before:e.after;switch(e.type){case "create":if(t==="before"){let n=this._core.nodes.findById(e.nodeId);n&&this._core.nodes.remove(n);}else o&&this._recreateNode(o);break;case "remove":if(t==="before")o&&this._recreateNode(o);else {let n=this._core.nodes.findById(e.nodeId);n&&this._core.nodes.remove(n);}break;case "transform":if(o&&typeof o=="object"){let n=this._core.nodes.findById(e.nodeId);this._debug("transform apply",{nodeId:e.nodeId,nodeFound:!!n,state:o}),n&&this._applyTransformState(n,o);}break;case "zIndex":if(o&&typeof o=="object"&&"zIndex"in o){let n=this._core.nodes.findById(e.nodeId);n&&n.getKonvaNode().zIndex(o.zIndex);}break;case "group":this._applyGroupAction(e,t);break;case "ungroup":this._applyUngroupAction(e,t);break;case "batch":if(e.children){let n=t==="before"?[...e.children].reverse():e.children;for(let r of n)this._applyActionState(r,t);}break;default:this._debug("unknown action type",e.type);}}_applyTransformState(e,t){let o=e.getKonvaNode();this._debug("applyTransformState",{nodeId:e.id,current:{x:o.x(),y:o.y(),rotation:o.rotation(),scaleX:o.scaleX(),scaleY:o.scaleY()},target:t}),typeof t.x=="number"&&o.x(t.x),typeof t.y=="number"&&o.y(t.y),typeof t.width=="number"&&typeof o.width=="function"&&o.width(t.width),typeof t.height=="number"&&typeof o.height=="function"&&o.height(t.height),typeof t.rotation=="number"&&o.rotation(t.rotation),typeof t.scaleX=="number"&&o.scaleX(t.scaleX),typeof t.scaleY=="number"&&o.scaleY(t.scaleY);let n=o;typeof t.cornerRadius=="number"&&typeof n.cornerRadius=="function"&&n.cornerRadius(t.cornerRadius),this._dragStartStateCache.set(e.id,this._captureTransformState(e));}_applyGroupAction(e,t){if(this._core){if(t==="before"){let o=this._core.nodes.findById(e.nodeId);if(o&&e.before){let n=e.before;this._core.nodes.remove(o);for(let r of n.childStates)this._recreateNode(r);}}else if(e.after){let o=e.after;this._recreateNode(o);}}}_applyUngroupAction(e,t){if(this._core)if(t==="before"){if(e.before){let o=e.before;this._recreateNode(o);}}else {let o=this._core.nodes.findById(e.nodeId);if(o&&e.after){let n=e.after;this._core.nodes.remove(o);for(let r of n.childStates)this._recreateNode(r);}}}_recreateNode(e){if(!this._core)return null;let{nodeType:t,attrs:o}=e,{id:n,zIndex:r,...s}=o;try{let l=null;switch(t){case "shape":l=this._core.nodes.addShape(s);break;case "text":l=this._core.nodes.addText(s);break;case "circle":l=this._core.nodes.addCircle(s);break;case "ellipse":l=this._core.nodes.addEllipse(s);break;case "arc":l=this._core.nodes.addArc(s);break;case "star":l=this._core.nodes.addStar(s);break;case "arrow":l=this._core.nodes.addArrow(s);break;case "ring":l=this._core.nodes.addRing(s);break;case "regularPolygon":case "regularpolygon":l=this._core.nodes.addRegularPolygon(s);break;case "image":l=this._core.nodes.addImage(s);break;case "svg":l=this._core.nodes.addSvg(s);break;case "group":{if(l=this._core.nodes.addGroup(s),e.children&&e.children.length>0){let h=l.getKonvaNode();for(let p of e.children){let d=this._recreateNode(p);d&&d.getKonvaNode().moveTo(h);}}break}default:return this._debug("recreateNode",`unknown type: ${t}`),null}if(e.parentId){let h=this._core.nodes.findById(e.parentId);if(h){let p=h.getKonvaNode();l.getKonvaNode().moveTo(p),this._debug("recreateNode - moved to parent",{nodeId:l.id,parentId:e.parentId});}}return this._debug("recreateNode",{nodeType:t,nodeId:l.id,parentId:e.parentId}),l}catch(l){return this._debug("recreateNode error",l),null}}_scheduleBatchCommit(){this._batchCommitTimer!==null&&globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=globalThis.setTimeout(()=>{this._batchCommitTimer=null,this._finishBatch();},50);}_serializeNode(e){let t=e.getKonvaNode(),o=t.getAttrs(),n=this._getNodeType(t),r={nodeType:n,nodeId:e.id,attrs:{...o}},s=t.getParent();if(s&&this._core){let l=this._findBaseNodeByKonva(s);if(l&&l.id!==e.id){let h=this._core.nodes.world;s!==h&&(r.parentId=l.id);}}if(n==="group"){let h=t.getChildren();r.children=[];for(let p of h){let d=this._findBaseNodeByKonva(p);d&&r.children.push(this._serializeNode(d));}}return r}_captureTransformState(e){let t=e.getKonvaNode(),o=t.getAbsoluteTransform().decompose(),n={absX:o.x,absY:o.y,absRotation:o.rotation,absScaleX:o.scaleX,absScaleY:o.scaleY,x:t.x(),y:t.y(),rotation:t.rotation(),scaleX:t.scaleX(),scaleY:t.scaleY()};typeof t.width=="function"&&(n.width=t.width()),typeof t.height=="function"&&(n.height=t.height());let r=t;return typeof r.cornerRadius=="function"&&(n.cornerRadius=r.cornerRadius()),n}_buildAfterState(e,t){let o=e.getKonvaNode(),n=t.x??o.x(),r=t.y??o.y(),s=t.rotation??o.rotation(),l=t.scaleX??o.scaleX(),h=t.scaleY??o.scaleY(),p={absX:n,absY:r,absRotation:s,absScaleX:l,absScaleY:h,x:n,y:r,rotation:s,scaleX:l,scaleY:h};typeof o.width=="function"&&(p.width=t.width??o.width()),typeof o.height=="function"&&(p.height=t.height??o.height());let d=o;return typeof d.cornerRadius=="function"&&(p.cornerRadius=d.cornerRadius()),p}_getNodeType(e){let t=e.getClassName();return t==="Image"?e.getAttrs().flowscapeNodeType==="svg"?"svg":"image":{Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Group:"group",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon"}[t]??t.toLowerCase()}_findBaseNodeByKonva(e){if(!this._core)return null;for(let o of this._core.nodes.list())if(o.getKonvaNode()===e)return o;let t=e.getParent();for(;t;){for(let o of this._core.nodes.list())if(o.getKonvaNode()===t)return o;t=t.getParent();}return null}_statesEqual(e,t){let n=["absX","absY","absRotation","absScaleX","absScaleY"];for(let s of n){let l=e[s],h=t[s];if(typeof l=="number"&&typeof h=="number"){if(Math.abs(l-h)>.001)return false}else if(l!==h)return false}let r=["width","height","cornerRadius"];for(let s of r)if(e[s]!==t[s])return false;return true}_trimHistoryIfNeeded(){if(!(this._options.maxHistoryLength<=0))for(;this._history.length>this._options.maxHistoryLength;){this._history.pop(0);break}}_debug(e,t){}};var bt=class extends D{constructor(e){super();a(this,"_core");a(this,"_layer");a(this,"_image");a(this,"_src");a(this,"_width");a(this,"_height");a(this,"_opacity");this._src=e.src,this._width=e.width,this._height=e.height,this._opacity=e.opacity??1;}onAttach(e){this._core=e,this._layer=new H.Layer({name:"logo-layer",listening:false}),this._core.stage.add(this._layer),this._image=new H.Image({image:void 0,width:this._width,height:this._height,name:"logo-background",listening:false,opacity:this._opacity}),this._layer.add(this._image),this.setSource(this._src);let t=this._core.stage;t.on("resize.logo",()=>{this._layout();}),t.on("xChange.logo yChange.logo scaleXChange.logo scaleYChange.logo",()=>{this._layout();}),this._layout(),this._core.stage.batchDraw();}onDetach(e){e.stage.off(".logo"),this._image&&this._image.destroy(),this._layer&&this._layer.destroy();}setOpacity(e){this._opacity=e,this._image&&this._core&&(this._image.opacity(e),this._core.stage.batchDraw());}setSize({width:e,height:t}){this._width=e,this._height=t,this._layout(),this._core&&this._core.stage.batchDraw();}setSource(e){this._src=e,this._loadImageFromString(e);}_setImage(e){this._image&&(this._image.image(e),this._layout(),this._core&&this._core.stage.batchDraw());}_loadImageFromString(e){H.Image.fromURL(e,t=>{let o=t.image();o&&this._setImage(o);});}_layout(){if(!this._core||!this._image)return;let e=this._core.stage,t=e.width(),o=e.height(),n=e.scaleX(),r=e.position(),s={x:Math.floor(t/2),y:Math.floor(o/2)};this._image.scale({x:1/n,y:1/n});let l=this._width,h=this._height;this._image.size({width:l,height:h}),this._image.offset({x:l/2,y:h/2});let p=(s.x-r.x)/n,d=(s.y-r.y)/n;this._image.position({x:p,y:d}),this._image.opacity(this._opacity),this._layer&&this._layer.moveToBottom();}};var st="flowscape:nodes:",yt=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_clipboard",null);a(this,"_selectionPlugin");a(this,"_onPaste",e=>{if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let o=e.clipboardData?.getData("text/plain")??"";if(!o.startsWith(st))return;let n=o.slice(st.length),r=null;try{r=JSON.parse(n);}catch{r=null;}if(!(!r||!Array.isArray(r.nodes)||r.nodes.length===0)&&r.nodes.length>0){e.preventDefault(),e.stopImmediatePropagation(),this._clipboard=r,this._handlePaste();return}});a(this,"_onKeyDown",e=>{if(!this._core)return;if(!this._selectionPlugin){let n=this._core.plugins.list().find(r=>r instanceof ve);n&&(this._selectionPlugin=n);}if(!this._selectionPlugin||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let t=e.ctrlKey||e.metaKey,o=e.shiftKey;if(!t&&!o&&e.code==="Enter"){let n=this._getSelectedNodes();if(n.length===1&&n[0]instanceof ke){e.preventDefault(),n[0].startEdit();return}}if(t&&e.code==="KeyC"){e.preventDefault(),this._handleCopy();return}if(t&&e.code==="KeyX"){e.preventDefault(),this._handleCut();return}if(!(t&&e.code==="KeyV")){if(e.code==="Delete"||e.code==="Backspace"){e.preventDefault(),this._handleDelete();return}if(t&&o&&e.code==="BracketRight"){e.preventDefault(),this._handleMoveToTop();return}if(t&&o&&e.code==="BracketLeft"){e.preventDefault(),this._handleMoveToBottom();return}if(t&&(e.code==="BracketRight"||o&&e.code==="Equal")){e.preventDefault(),this._handleMoveUp();return}if(t&&(e.code==="BracketLeft"||o&&e.code==="Minus")){e.preventDefault(),this._handleMoveDown();return}}});let{target:t=globalThis,ignoreEditableTargets:o=true}=e;this._options={target:t,ignoreEditableTargets:o};}onAttach(e){this._core=e,this._options.target.addEventListener("keydown",this._onKeyDown),this._options.target.addEventListener("paste",this._onPaste);}onDetach(e){this._options.target.removeEventListener("keydown",this._onKeyDown),this._options.target.removeEventListener("paste",this._onPaste),this._core=void 0,this._selectionPlugin=void 0,this._clipboard=null;}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_handleCopy(){let e=this._getSelectedNodes();if(e.length===0)return;let t=e.map(n=>this._serializeNode(n)),o=this._computeSelectionWorldCenter(e);this._clipboard={nodes:t,center:o};try{globalThis.navigator.clipboard.writeText(`${st}${JSON.stringify(this._clipboard)}`);}catch{}this._core&&this._core.eventBus.emit("clipboard:copy",e);}_handleCut(){let e=this._getSelectedNodes();if(e.length===0)return;let t=e.map(n=>this._serializeNode(n)),o=this._computeSelectionWorldCenter(e);this._clipboard={nodes:t,center:o};try{globalThis.navigator.clipboard.writeText(`${st}${JSON.stringify(this._clipboard)}`);}catch{}this._deleteNodes(e),this._core&&this._core.eventBus.emit("clipboard:cut",e);}_handlePaste(){if(!this._core||!this._clipboard||this._clipboard.nodes.length===0)return;let e=this._getPastePosition(),t=this._getClipboardCenter(),o=[];for(let n of this._clipboard.nodes){let r=n.position.x-t.x,s=n.position.y-t.y,l=this._deserializeNode(n,{x:e.x+r,y:e.y+s});l&&o.push(l);}o.length>0&&this._core.eventBus.emit("clipboard:paste",o),this._core.nodes.layer.batchDraw();}_handleDelete(){let e=this._getSelectedNodes();e.length!==0&&this._deleteNodes(e);}_getSelectedNodes(){if(!this._selectionPlugin)return [];let e=this._selectionPlugin._tempMultiGroup;if(e&&typeof e.getChildren=="function"&&this._core){let n=e.getChildren(),r=this._core.nodes.list(),s=new Set;for(let l of n){let h=r.find(p=>p.getKonvaNode()===l);h&&s.add(h);}if(s.size>0)return Array.from(s)}let t=this._selectionPlugin._tempMultiSet;if(t&&t.size>0)return Array.from(t);let o=this._selectionPlugin._selected;return o?[o]:[]}_deleteNodes(e){if(!this._core)return;if(this._selectionPlugin){let o=this._selectionPlugin;typeof o._destroyTempMulti=="function"&&o._destroyTempMulti(),typeof o._clearSelection=="function"&&o._clearSelection();}let t=this._core.plugins.get("HistoryPlugin");e.length>1&&t&&t.startBatch();for(let o of e)this._core.nodes.remove(o);e.length>1&&t&&t.commitBatch();}_serializeNode(e){let t=e.getKonvaNode(),o=t.getAttrs(),n=this._getNodeTypeFromKonva(t),r={x:0,y:0};if(this._core){let u=t.getAbsolutePosition(),g=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(u);r={x:g.x,y:g.y};}let{id:s,image:l,video:h,...p}=o,d={type:n,config:p,position:r};if(n==="group"){let u=t.getChildren(),f=[];for(let g of u){let _=this._serializeKonvaNode(g);_&&f.push(_);}f.length>0&&(d.children=f);}return d}_serializeKonvaNode(e){if(!this._core)return null;let t=e.getAttrs(),o=e.getClassName(),n=o.toLowerCase();if(n==="rect"&&(n="shape"),o==="Image"){let c=e.getAttrs().flowscapeNodeType;c==="svg"?n="svg":c==="gif"?n="gif":c==="video"?n="video":n="image";}let{id:r,image:s,video:l,...h}=t,p={type:n,config:h,position:{x:e.x(),y:e.y()}};if(e instanceof H.Group){let d=e.getChildren(),c=[];for(let u of d){let f=this._serializeKonvaNode(u);f&&c.push(f);}c.length>0&&(p.children=c);}return p}_getNodeTypeFromKonva(e){let t=e.getClassName();if(t==="Image"){let r=e.getAttrs().flowscapeNodeType;return r==="svg"?"svg":r==="gif"?"gif":r==="video"?"video":"image"}return {Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Group:"group",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon",Label:"label"}[t]??t.toLowerCase()}_deserializeNode(e,t){if(!this._core)return null;let{zIndex:o,...n}=e.config,r=n.placeholder,{placeholder:s,...l}=n,h={...l,...r?{placeholder:r}:{},x:t.x,y:t.y};try{let p=null;switch(e.type){case "shape":p=this._core.nodes.addShape(h);break;case "text":p=this._core.nodes.addText(h);break;case "circle":p=this._core.nodes.addCircle(h);break;case "ellipse":p=this._core.nodes.addEllipse(h);break;case "arc":p=this._core.nodes.addArc(h);break;case "star":p=this._core.nodes.addStar(h);break;case "arrow":p=this._core.nodes.addArrow(h);break;case "ring":p=this._core.nodes.addRing(h);break;case "regularPolygon":case "regularpolygon":p=this._core.nodes.addRegularPolygon(h);break;case "image":p=this._core.nodes.addImage(h);break;case "svg":p=this._core.nodes.addSvg(h);break;case "gif":p=this._core.nodes.addGif(h);break;case "video":p=this._core.nodes.addVideo(h);break;case "label":return globalThis.console.warn("LabelNode is not supported for copy/paste yet"),null;case "group":{p=this._core.nodes.addGroup(h);let c=p.getKonvaNode();if(e.config.scaleX!==void 0&&c.scaleX(e.config.scaleX),e.config.scaleY!==void 0&&c.scaleY(e.config.scaleY),e.config.rotation!==void 0&&c.rotation(e.config.rotation),e.config.skewX!==void 0&&c.skewX(e.config.skewX),e.config.skewY!==void 0&&c.skewY(e.config.skewY),e.config.offsetX!==void 0&&c.offsetX(e.config.offsetX),e.config.offsetY!==void 0&&c.offsetY(e.config.offsetY),e.children&&e.children.length>0)for(let u of e.children){let f=this._deserializeNode(u,{x:u.position.x,y:u.position.y});if(f){let g=f.getKonvaNode();typeof g.draggable=="function"&&g.draggable(!1),g.moveTo(c);}}break}default:return globalThis.console.warn(`Unknown node type: ${e.type}`),null}let d=p.getKonvaNode();return e.config.scaleX!==void 0&&d.scaleX(e.config.scaleX),e.config.scaleY!==void 0&&d.scaleY(e.config.scaleY),e.config.rotation!==void 0&&d.rotation(e.config.rotation),e.config.skewX!==void 0&&d.skewX(e.config.skewX),e.config.skewY!==void 0&&d.skewY(e.config.skewY),e.config.offsetX!==void 0&&d.offsetX(e.config.offsetX),e.config.offsetY!==void 0&&d.offsetY(e.config.offsetY),p}catch(p){return globalThis.console.error("Failed to deserialize node:",p),null}}_getPastePosition(){if(!this._core)return {x:0,y:0};let t=this._core.stage.getPointerPosition();if(t&&this._isPointerOnScreen(t)){let r=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(t);return {x:r.x,y:r.y}}return this._getScreenCenter()}_isPointerOnScreen(e){if(!this._core)return false;let t=this._core.stage,o=t.width(),n=t.height();return e.x>=0&&e.x<=o&&e.y>=0&&e.y<=n}_getScreenCenter(){if(!this._core)return {x:0,y:0};let e=this._core.stage,t=this._core.nodes.world,o=e.width()/2,n=e.height()/2,s=t.getAbsoluteTransform().copy().invert().point({x:o,y:n});return {x:s.x,y:s.y}}_getClipboardCenter(){if(!this._clipboard||this._clipboard.nodes.length===0)return {x:0,y:0};if(this._clipboard.center)return this._clipboard.center;let e=0,t=0;for(let o of this._clipboard.nodes)e+=o.position.x,t+=o.position.y;return {x:e/this._clipboard.nodes.length,y:t/this._clipboard.nodes.length}}_computeSelectionWorldCenter(e){if(!this._core||e.length===0)return {x:0,y:0};let t=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,n=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let c of e){let f=c.getKonvaNode().getClientRect({skipShadow:true,skipStroke:true});t=Math.min(t,f.x),o=Math.min(o,f.y),n=Math.max(n,f.x+f.width),r=Math.max(r,f.y+f.height);}if(!isFinite(t)||!isFinite(o)||!isFinite(n)||!isFinite(r))return {x:0,y:0};let s=(t+n)/2,l=(o+r)/2,d=this._core.nodes.world.getAbsoluteTransform().copy().invert().point({x:s,y:l});return {x:d.x,y:d.y}}_handleMoveUp(){let e=this._getSelectedNodes();if(e.length!==0){for(let t of e){let o=t.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let n=o.zIndex();o.moveUp();let r=o.zIndex();this._syncGroupZIndex(o),this._core&&n!==r&&this._core.eventBus.emit("node:zIndexChanged",t,n,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}}_handleMoveDown(){let e=this._getSelectedNodes();if(e.length!==0){for(let t=e.length-1;t>=0;t--){let o=e[t];if(!o)continue;let n=o.getKonvaNode();if(this._isNodeInsidePermanentGroup(n))continue;let r=n.zIndex();n.moveDown();let s=n.zIndex();this._syncGroupZIndex(n),this._core&&r!==s&&this._core.eventBus.emit("node:zIndexChanged",o,r,s);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}}_handleMoveToTop(){let e=this._getSelectedNodes();if(e.length===0)return;let t=[...e].sort((o,n)=>{let r=o.getKonvaNode(),s=n.getKonvaNode();return r.zIndex()-s.zIndex()});for(let o of t){let n=o.getKonvaNode();if(this._isNodeInsidePermanentGroup(n))continue;let r=n.zIndex();n.moveToTop();let s=n.zIndex();this._syncGroupZIndex(n),this._core&&r!==s&&this._core.eventBus.emit("node:zIndexChanged",o,r,s);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_handleMoveToBottom(){let e=this._getSelectedNodes();if(e.length===0)return;let t=[...e].sort((o,n)=>{let r=o.getKonvaNode();return n.getKonvaNode().zIndex()-r.zIndex()});for(let o of t){let n=o.getKonvaNode();if(this._isNodeInsidePermanentGroup(n))continue;let r=n.zIndex();n.moveToBottom();let s=n.zIndex();this._syncGroupZIndex(n),this._core&&r!==s&&this._core.eventBus.emit("node:zIndexChanged",o,r,s);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_isNodeInsidePermanentGroup(e){if(e instanceof H.Group)return false;let t=e.getParent();return !(!t||!(t instanceof H.Group)||t===this._core?.nodes.world)}_syncGroupZIndex(e){let t=e.getParent();t&&(e instanceof H.Group||t instanceof H.Group&&t.name());}};var _e=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_guidesLayer",null);a(this,"_guides",[]);a(this,"_activeGuide",null);a(this,"_draggingGuide",null);a(this,"_rulerLayerCache",null);a(this,"_updateScheduled",false);a(this,"_dragMoveScheduled",false);a(this,"_batchDrawScheduled",false);let{guideColor:t="#8e3e2c",activeColor:o="#2b83ff",rulerThicknessPx:n=30,snapToGrid:r=true,gridStep:s=1}=e;this._options={guideColor:t,activeColor:o,rulerThicknessPx:n,snapToGrid:r,gridStep:s};}onAttach(e){if(this._core=e,!e.stage.findOne(".ruler-layer"))throw new Error("RulerGuidesPlugin requires RulerPlugin to be added to the CoreEngine first. Please add RulerPlugin before RulerGuidesPlugin.");this._guidesLayer=new H.Layer({name:"guides-layer"}),e.stage.add(this._guidesLayer),this._guidesLayer.moveToTop();let o=e.stage,n=this._options.rulerThicknessPx;o.on("mousedown.ruler-guides",()=>{let s=o.getPointerPosition();if(!s)return;let l=o.getIntersection(s);l&&(l.name()==="guide-h"||l.name()==="guide-v")||(s.y<=n&&s.x>=n?this._startCreateGuide("h"):s.x<=n&&s.y>=n?this._startCreateGuide("v"):this._setActiveGuide(null));}),o.on("mousemove.ruler-guides",()=>{let s=o.getPointerPosition();if(!s)return;let l=o.getIntersection(s);if(l){let h=l.name();if(h==="guide-h"||h==="guide-v"||h.includes("_anchor")||h.includes("rotater")||l.draggable())return}s.y<=n&&s.x>=n?o.container().style.cursor="ns-resize":s.x<=n&&s.y>=n?o.container().style.cursor="ew-resize":this._draggingGuide||(o.container().style.cursor="default");}),this._rulerLayerCache=e.stage.findOne(".ruler-layer"),e.nodes.world.on("xChange.ruler-guides yChange.ruler-guides scaleXChange.ruler-guides scaleYChange.ruler-guides",()=>{this._scheduleUpdate();}),o.on("resize.ruler-guides",()=>{this._scheduleUpdate();}),e.stage.batchDraw();}onDetach(e){e.stage.off(".ruler-guides"),e.nodes.world.off(".ruler-guides"),this._guidesLayer&&(this._guidesLayer.destroy(),this._guidesLayer=null),this._guides=[],this._activeGuide=null,this._draggingGuide=null;}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=true,globalThis.requestAnimationFrame(()=>{this._updateScheduled=false,this._updateGuidesPositions();}));}_updateGuidesPositions(){if(!this._core||this._guides.length===0)return;let e=this._core.nodes.world,t=e.scaleX(),o=e.x(),n=e.y(),r=this._core.stage.width(),s=this._core.stage.height(),l=[0,0,r,0],h=[0,0,0,s];for(let p of this._guides){let d=p.worldCoord;if(p.name()==="guide-h"){let u=n+d*t;p.position({x:0,y:u}),p.points(l);}else {let u=o+d*t;p.position({x:u,y:0}),p.points(h);}}this._guidesLayer?.batchDraw();}_snapToGrid(e){if(!this._options.snapToGrid)return Math.round(e);let t=this._options.gridStep;return Math.round(e/t)*t}_scheduleBatchDraw(){this._batchDrawScheduled||(this._batchDrawScheduled=true,globalThis.requestAnimationFrame(()=>{this._batchDrawScheduled=false,this._core?.stage.batchDraw();}));}_startCreateGuide(e){if(!this._core||!this._guidesLayer)return;let t=this._core.stage,o=this._core.nodes.world,n=o.scaleX(),r=t.getPointerPosition();if(!r)return;let s=e==="h"?(r.y-o.y())/n:(r.x-o.x())/n,l=this._snapToGrid(s),h=new H.Line({name:e==="h"?"guide-h":"guide-v",stroke:this._options.guideColor,strokeWidth:1,opacity:1,draggable:true,hitStrokeWidth:8,dragBoundFunc:u=>{if(!this._core)return u;let f=this._core.nodes.world,g=f.scaleX();if(e==="h"){let _=(u.y-f.y())/g,m=this._snapToGrid(_);return {x:0,y:f.y()+m*g}}else {let _=(u.x-f.x())/g,m=this._snapToGrid(_);return {x:f.x()+m*g,y:0}}}});h.worldCoord=l,h.on("mouseenter",()=>{this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize"),this._scheduleBatchDraw();}),h.on("mouseleave",()=>{this._core&&!this._draggingGuide&&(this._core.stage.container().style.cursor="default"),this._scheduleBatchDraw();}),h.on("click",()=>{this._setActiveGuide(h);}),h.on("dragstart",()=>{let u=h;this._draggingGuide={type:e,line:u},this._setActiveGuide(u),this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize");}),h.on("dragmove",()=>{!this._core||this._dragMoveScheduled||(this._dragMoveScheduled=true,globalThis.requestAnimationFrame(()=>{if(this._dragMoveScheduled=false,!this._core)return;let u=this._core.nodes.world,f=u.scaleX(),g=h.getAbsolutePosition(),_=e==="h"?(g.y-u.y())/f:(g.x-u.x())/f,m=this._snapToGrid(_);h.worldCoord=m,this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize",this._rulerLayerCache&&this._rulerLayerCache.batchDraw();}));}),h.on("dragend",()=>{this._draggingGuide=null,this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize");});let p=h;this._guidesLayer.add(p),this._guides.push(p),this._setActiveGuide(p),e==="h"?(h.position({x:0,y:o.y()+l*n}),h.points([0,0,t.width(),0])):(h.position({x:o.x()+l*n,y:0}),h.points([0,0,0,t.height()])),this._draggingGuide={type:e,line:p};let d=()=>{if(!this._draggingGuide||!this._core)return;let u=this._core.stage.getPointerPosition();if(!u)return;let f=this._core.nodes.world,g=f.scaleX(),_=e==="h"?(u.y-f.y())/g:(u.x-f.x())/g,m=this._snapToGrid(_);h.worldCoord=m,e==="h"?(h.position({x:0,y:f.y()+m*g}),h.points([0,0,this._core.stage.width(),0])):(h.position({x:f.x()+m*g,y:0}),h.points([0,0,0,this._core.stage.height()])),this._scheduleBatchDraw();},c=()=>{this._draggingGuide=null,this._core&&(this._core.stage.off("mousemove.guide-create"),this._core.stage.off("mouseup.guide-create"));};t.on("mousemove.guide-create",d),t.on("mouseup.guide-create",c),this._scheduleBatchDraw();}_setActiveGuide(e){this._activeGuide&&this._activeGuide!==e&&(this._activeGuide.stroke(this._options.guideColor),this._activeGuide.strokeWidth(1)),this._activeGuide=e,e&&(e.stroke(this._options.activeColor),e.strokeWidth(2)),this._rulerLayerCache&&this._rulerLayerCache.batchDraw(),this._core?.stage.fire("guidesChanged.ruler"),this._scheduleBatchDraw();}getActiveGuide(){return this._activeGuide}getActiveGuideInfo(){if(!this._activeGuide)return null;let e=this._activeGuide.worldCoord;return {type:this._activeGuide.name()==="guide-h"?"h":"v",coord:e}}removeActiveGuide(){this._activeGuide&&(this._activeGuide.destroy(),this._guides=this._guides.filter(e=>e!==this._activeGuide),this._activeGuide=null,this._scheduleBatchDraw());}getGuides(){return [...this._guides]}clearGuides(){this._guides.forEach(e=>e.destroy()),this._guides=[],this._activeGuide=null,this._scheduleBatchDraw();}};var Ee=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_highlightLayer",null);a(this,"_hGroup",null);a(this,"_vGroup",null);a(this,"_hHighlights",[]);a(this,"_vHighlights",[]);a(this,"_updateDebounce",new me);a(this,"_transformersCache",[]);a(this,"_cacheInvalidated",true);let{highlightColor:t="#2b83ff",highlightOpacity:o=.3,rulerThicknessPx:n=30}=e;this._options={highlightColor:t,highlightOpacity:o,rulerThicknessPx:n};}onAttach(e){this._core=e;let t=e.stage.findOne(".ruler-layer");if(!t){globalThis.console.warn("RulerHighlightPlugin: RulerPlugin not found. Please add RulerPlugin before RulerHighlightPlugin. Plugin will not work without RulerPlugin.");return}this._highlightLayer=t;let o=t.find("Group");if(o.length>=2)this._hGroup=o[0],this._vGroup=o[1];else {globalThis.console.warn("RulerHighlightPlugin: Could not find ruler groups");return}e.nodes.world.on("xChange.ruler-highlight yChange.ruler-highlight scaleXChange.ruler-highlight scaleYChange.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("resize.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("transform.ruler-highlight transformend.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("click.ruler-highlight",()=>{this._invalidateCache(),this._scheduleUpdate();}),e.stage.on("dragmove.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("mouseup.ruler-highlight",()=>{this._invalidateCache(),this._scheduleUpdate();}),this._updateHighlights();}onDetach(e){try{e.stage.off(".ruler-highlight"),e.nodes.world.off(".ruler-highlight");}catch{}this._hHighlights.forEach(t=>{try{t.destroy();}catch{}}),this._vHighlights.forEach(t=>{try{t.destroy();}catch{}}),this._hHighlights=[],this._vHighlights=[],this._highlightLayer=null,this._hGroup=null,this._vGroup=null;}_scheduleUpdate(){this._updateDebounce.schedule(()=>{this._updateHighlights();});}_invalidateCache(){this._cacheInvalidated=true;}_updateHighlights(){if(!this._core||!this._highlightLayer)return;for(let g of this._hHighlights)g.destroy();this._hHighlights=[];for(let g of this._vHighlights)g.destroy();this._vHighlights=[];let e=this._getSelectedKonvaNodes();if(e.length===0){this._highlightLayer.batchDraw();return}let t=this._core.stage,o=this._core.nodes.world,n=t.width(),r=t.height(),s=this._options.rulerThicknessPx,l=o.scaleX(),h=o.x(),p=o.y(),d=[],c=[];for(let g of e){let _=g.getClientRect({relativeTo:o}),m=h+_.x*l,b=h+(_.x+_.width)*l,v=p+_.y*l,w=p+(_.y+_.height)*l;if(m<n&&b>s){let y=Math.max(s,m),N=Math.min(n,b);y<N&&d.push({start:y,end:N});}if(v<r&&w>s){let y=Math.max(s,v),N=Math.min(r,w);y<N&&c.push({start:y,end:N});}}let u=this._mergeSegments(d),f=this._mergeSegments(c);if(this._hGroup)for(let g of u){let _=new H.Rect({x:g.start,y:0,width:g.end-g.start,height:s,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-h"});this._hGroup.add(_),_.setZIndex(1),this._hHighlights.push(_);}if(this._vGroup)for(let g of f){let _=new H.Rect({x:0,y:g.start,width:s,height:g.end-g.start,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-v"});this._vGroup.add(_),_.setZIndex(1),this._vHighlights.push(_);}this._highlightLayer.batchDraw();}_collectNodes(e,t){let o=e.getClassName(),n=e.name(),s=["overlay-hit","ruler-","guide-","_anchor","back","rotater"].some(l=>n.includes(l));if(!(o==="Transformer"||o==="Layer"||s))if(o==="Group"){let h=e.getChildren();if(h.length===0)return;for(let p of h)this._collectNodes(p,t);}else t.includes(e)||t.push(e);}_mergeSegments(e){if(e.length===0)return [];let t=e.slice().sort((s,l)=>s.start-l.start),o=t[0];if(!o)return [];let n=[],r={start:o.start,end:o.end};for(let s=1;s<t.length;s++){let l=t[s];l&&(l.start<=r.end+1?r.end=Math.max(r.end,l.end):(n.push(r),r={start:l.start,end:l.end}));}return n.push(r),n}_getSelectedKonvaNodes(){if(!this._core)return [];let e=[];try{this._cacheInvalidated&&(this._transformersCache=this._core.stage.find("Transformer"),this._cacheInvalidated=!1);for(let o of this._transformersCache){let n=o.nodes();for(let r of n)e.includes(r)||e.push(r);}}catch{}let t=[];for(let o of e)this._collectNodes(o,t);return t}update(){this._updateHighlights();}};var Pe=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_visible",true);a(this,"_handleKeyDown",e=>{if(e.shiftKey&&(e.key==="r"||e.key==="R"||e.key==="\u043A"||e.key==="\u041A")){e.preventDefault(),this.toggle();return}(e.code==="Delete"||e.code==="Backspace")&&this.deleteActiveGuide()&&e.preventDefault();});let{enabled:t=true}=e;this._options={enabled:t};}onAttach(e){this._options.enabled&&(this._core=e,this._bindKeyboardEvents());}onDetach(e){this._unbindKeyboardEvents();}_bindKeyboardEvents(){globalThis.addEventListener("keydown",this._handleKeyDown);}_unbindKeyboardEvents(){globalThis.removeEventListener("keydown",this._handleKeyDown);}toggle(){this._visible?this.hide():this.show();}show(){if(!this._core)return;this._visible=true;let e=this._core.stage.findOne(".ruler-layer");e&&!e.isVisible()&&e.show();let t=this._core.stage.findOne(".guides-layer");t&&!t.isVisible()&&t.show(),this._core.stage.batchDraw();}hide(){if(!this._core)return;this._visible=false;let e=this._core.stage.findOne(".ruler-layer");e?.isVisible()&&e.hide();let t=this._core.stage.findOne(".guides-layer");t?.isVisible()&&t.hide(),this._core.stage.batchDraw();}isVisible(){return this._visible}deleteActiveGuide(){if(!this._core)return false;let e=this._core.plugins.list().find(t=>t instanceof _e);return e&&"getActiveGuide"in e&&"removeActiveGuide"in e&&e.getActiveGuide.call(e)?(e.removeActiveGuide.call(e),true):false}};var wt=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_layer",null);a(this,"_hGroup");a(this,"_vGroup");a(this,"_hBg");a(this,"_vBg");a(this,"_hTicksShape");a(this,"_vTicksShape");a(this,"_hBorder");a(this,"_vBorder");a(this,"_redrawScheduled",false);a(this,"_lastRedrawTime",0);a(this,"_redrawThrottleMs",16);a(this,"_panThrottleMs",32);a(this,"_cachedActiveGuide",null);a(this,"_cacheInvalidated",true);a(this,"_stepsCache",new Map);let{thicknessPx:t=30,fontFamily:o="Inter, Calibri, Arial, sans-serif",fontSizePx:n=10,color:r="#8c8c8c",bgColor:s="#2c2c2c",borderColor:l="#1f1f1f",enabled:h=true}=e;this._options={thicknessPx:t,fontFamily:o,fontSizePx:n,color:r,bgColor:s,borderColor:l,enabled:h};}_calculateNiceStep(e){if(!isFinite(e)||e<=0)return 1;let t=Math.pow(10,Math.floor(Math.log10(e))),o=e/t,n;return o<=1?n=1:o<=2?n=2:o<=5?n=5:n=10,n*t}_formatNumber(e){return Math.round(e).toString()}_getStepsConfig(e){let t=this._stepsCache.get(e);if(t)return t;let o=this._options.thicknessPx,r=50/e,s=this._calculateNiceStep(r);s<1&&(s=1);let l=s*e,h,p,d,c;l>=60?(h=s*10,p=s*5,d=s,c=s):l>=40?(h=s*10,p=s*5,d=s*5,c=s):(h=s*10,p=s*5,d=s*10,c=s);let u={step:s,stepPx:l,majorStep:h,mediumStep:p,labelStep:d,drawStep:c,drawStepEpsilon:c*.01,majorTickLength:o*.6,mediumTickLength:o*.4,minorTickLength:o*.25,fontString:`${String(this._options.fontSizePx)}px ${this._options.fontFamily}`};if(this._stepsCache.size>10){let f=this._stepsCache.keys().next().value;f!==void 0&&this._stepsCache.delete(f);}return this._stepsCache.set(e,u),u}onAttach(e){this._core=e,this._layer=new H.Layer({name:"ruler-layer",listening:true}),this._options.enabled&&e.stage.add(this._layer),this._hGroup=new H.Group({listening:true}),this._vGroup=new H.Group({listening:true}),this._layer.add(this._hGroup),this._layer.add(this._vGroup),this._hBg=new H.Rect({fill:this._options.bgColor,listening:true,name:"ruler-h-bg"}),this._vBg=new H.Rect({fill:this._options.bgColor,listening:true,name:"ruler-v-bg"}),this._hGroup.add(this._hBg),this._vGroup.add(this._vBg),this._hBorder=new H.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._vBorder=new H.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._hGroup.add(this._hBorder),this._vGroup.add(this._vBorder),this._hTicksShape=new H.Shape({listening:false,sceneFunc:n=>{let r=this._getActiveGuideInfo();this._drawHorizontalRuler(n,r);}}),this._hGroup.add(this._hTicksShape),this._vTicksShape=new H.Shape({listening:false,sceneFunc:n=>{let r=this._getActiveGuideInfo();this._drawVerticalRuler(n,r);}}),this._vGroup.add(this._vTicksShape);let t=e.stage,o=e.nodes.world;t.on("resize.ruler",()=>{this._scheduleRedraw();}),o.on("xChange.ruler yChange.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw(true);}),o.on("scaleXChange.ruler scaleYChange.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw(false);}),t.on("guidesChanged.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw();}),this._redraw(),e.stage.batchDraw();}onDetach(e){e.stage.off(".ruler"),e.nodes.world.off(".ruler"),this._layer&&(this._layer.destroy(),this._layer=null);}_getActiveGuideInfo(){if(!this._core)return null;if(!this._cacheInvalidated)return this._cachedActiveGuide;let e=this._core.stage.findOne(".guides-layer");if(!e)return this._cachedActiveGuide=null,this._cacheInvalidated=false,null;let t=e.find("Line");for(let o of t){let n=o;if(n.strokeWidth()===2){let r=n.worldCoord,s=n.name()==="guide-h"?"h":"v";return this._cachedActiveGuide={type:s,coord:r},this._cacheInvalidated=false,this._cachedActiveGuide}}return this._cachedActiveGuide=null,this._cacheInvalidated=false,null}_invalidateGuideCache(){this._cacheInvalidated=true;}_drawRuler(e,t,o){if(!this._core)return;let n=this._core.stage,r=this._core.nodes.world,s=r.scaleX()||1e-9,l=this._options.thicknessPx,h=t==="h",p=h?n.width():n.height(),d=h?r.x():r.y(),c=o?.type===(h?"v":"h")?o.coord:null,u=this._getStepsConfig(s),{majorStep:f,mediumStep:g,labelStep:_,drawStep:m,drawStepEpsilon:b,majorTickLength:v,mediumTickLength:w,minorTickLength:y,fontString:N}=u;e.save();let x=-d/s,k=Math.floor(x/m)*m,C=[],P=[],R=[],L=[],A=null;for(let E=k;;E+=m){let O=d+E*s;if(O>p)break;if(O<0)continue;if(c!==null&&Math.abs(E-c)<b){A=O,L.push({pos:O,text:this._formatNumber(E)});continue}let X=Math.abs(E%f)<b,re=!X&&Math.abs(E%g)<b;X?C.push(O):re?P.push(O):R.push(O),Math.abs(E%_)<b&&L.push({pos:O,text:this._formatNumber(E)});}if(R.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.4,e.lineWidth=1,e.beginPath();for(let E of R)h?(e.moveTo(E,l),e.lineTo(E,l-y)):(e.moveTo(l,E),e.lineTo(l-y,E));e.stroke();}if(P.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.6,e.lineWidth=1,e.beginPath();for(let E of P)h?(e.moveTo(E,l),e.lineTo(E,l-w)):(e.moveTo(l,E),e.lineTo(l-w,E));e.stroke();}if(C.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.9,e.lineWidth=1,e.beginPath();for(let E of C)h?(e.moveTo(E,l),e.lineTo(E,l-v)):(e.moveTo(l,E),e.lineTo(l-v,E));e.stroke();}if(A!==null&&(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(A,l),e.lineTo(A,l-v)):(e.moveTo(l,A),e.lineTo(l-v,A)),e.stroke()),L.length>0){e.font=N,e.textBaseline="top",e.textAlign="left";for(let E of L){let O=E.pos===A;if(e.globalAlpha=O?1:.9,e.fillStyle=O?"#ff8c00":this._options.color,h)e.fillText(E.text,E.pos+4,4);else {let X=E.pos+4;e.setTransform(0,-1,1,0,4,X),e.fillText(E.text,0,0),e.setTransform(1,0,0,1,0,0);}}}if(c!==null){let E=d+c*s;if(E>=0&&E<=p&&!(Math.abs(c%m)<b))if(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(E,l),e.lineTo(E,l-v)):(e.moveTo(l,E),e.lineTo(l-v,E)),e.stroke(),e.fillStyle="#ff8c00",e.font=N,e.textBaseline="top",e.textAlign="left",h)e.fillText(this._formatNumber(c),E+4,4);else {let X=E+4;e.setTransform(0,-1,1,0,4,X),e.fillText(this._formatNumber(c),0,0),e.setTransform(1,0,0,1,0,0);}}e.restore();}_drawHorizontalRuler(e,t){this._drawRuler(e,"h",t);}_drawVerticalRuler(e,t){this._drawRuler(e,"v",t);}_redraw(){if(!this._core||!this._layer)return;let e=this._core.stage,t=e.width(),o=e.height(),n=this._options.thicknessPx;this._hBg&&this._hBg.size({width:t,height:n}),this._vBg&&this._vBg.size({width:n,height:o}),this._hBorder&&this._hBorder.points([0,n,t,n]),this._vBorder&&this._vBorder.points([n,0,n,o]),this._layer.batchDraw();}_scheduleRedraw(e=false){if(!this._core||!this._layer)return;let o=globalThis.performance.now()-this._lastRedrawTime;if(this._redrawScheduled)return;this._redrawScheduled=true;let n=e?this._panThrottleMs:this._redrawThrottleMs;if(o>=n)globalThis.requestAnimationFrame(()=>{this._redrawScheduled=false,this._lastRedrawTime=globalThis.performance.now(),this._redraw();});else {let r=n-o;globalThis.setTimeout(()=>{globalThis.requestAnimationFrame(()=>{this._redrawScheduled=false,this._lastRedrawTime=globalThis.performance.now(),this._redraw();});},r);}}show(){this._core&&this._layer&&(this._core.stage.add(this._layer),this._layer.moveToTop(),this._redraw(),this._core.stage.batchDraw());}hide(){this._layer?.getStage()&&(this._layer.remove(),this._core?.stage.batchDraw());}toggle(){this._layer?.getStage()?this.hide():this.show();}isVisible(){return !!this._layer?.getStage()}};var xt=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_layer",null);a(this,"_maxGuideDistancePx",1200);a(this,"_dragMoveHandler",null);a(this,"_dragEndHandler",null);a(this,"_nodesAddHandler",null);a(this,"_nodesRemoveHandler",null);let{guidelineColor:t="#8e3e2c",guidelineWidth:o=1,guidelineDash:n=[0,0],thresholdPx:r=8}=e;this._options={guidelineColor:t,guidelineWidth:o,guidelineDash:n,thresholdPx:r};}_applyGapSnappingForDrag(e,t,o){if(!this._core)return;let n=this._options.thresholdPx,r=e.getClientRect({skipShadow:true,skipStroke:false}),s=o.x-t.x,l=o.y-t.y,h={x:r.x+s,y:r.y+l,width:r.width,height:r.height},p=this._collectOtherNodeBoxes(e),d=n+1,c=0,u=n+1,f=0;for(let g of p){let _=g.box;if(!(h.y>_.y+_.height||h.y+h.height<_.y)){let v=h.x,w=h.x+h.width,y=_.x,N=_.x+_.width;if(y>=w){let x=y-w;x>0&&x<d&&(d=x,c=x);}if(N<=v){let x=v-N;x>0&&x<d&&(d=x,c=-x);}}if(!(h.x>_.x+_.width||h.x+h.width<_.x)){let v=h.y,w=h.y+h.height,y=_.y,N=_.y+_.height;if(y>=w){let x=y-w;x>0&&x<u&&(u=x,f=x);}if(N<=v){let x=v-N;x>0&&x<u&&(u=x,f=-x);}}}d<=n&&(o.x+=c),u<=n&&(o.y+=f);}onAttach(e){this._core=e;let t=new H.Layer({name:"snap-guides-layer"});e.stage.add(t),t.moveToTop(),this._layer=t,this._dragMoveHandler=n=>{this._onDragMove(n);},this._dragEndHandler=()=>{this._clearGuides();},e.stage.on("dragmove.snap-guides",this._dragMoveHandler),e.stage.on("dragend.snap-guides",this._dragEndHandler);let o=e.nodes.layer;this._nodesAddHandler=n=>{let s=n.child??n.target;this._walkAttachTransformers(s);},this._nodesRemoveHandler=n=>{let s=n.child??n.target;this._walkDetachTransformers(s);},o.on("add.snap-guides",this._nodesAddHandler),o.on("remove.snap-guides",this._nodesRemoveHandler),this._attachExistingTransformers();}onDetach(e){e.stage.off(".snap-guides"),e.nodes.layer.off(".snap-guides");let t=e.nodes.layer.find("Transformer");for(let o of t)o.off(".snap-guides-resize");this._layer&&(this._layer.destroy(),this._layer=null),this._dragMoveHandler=null,this._dragEndHandler=null,this._nodesAddHandler=null,this._nodesRemoveHandler=null,this._core=void 0;}_onDragMove(e){if(!this._core||!this._layer)return;if(this._isVisualLinesShouldCleared(e.target)){this._clearGuides();return}let t=this._core.stage,o=this._core.nodes.layer,n=e.target;if(n===t||n instanceof H.Layer)return;let r=n,s=false;for(;r;){if(r===o){s=true;break}r=r.getParent();}if(!s)return;let l=n;if(typeof l.draggable=="function"&&!l.draggable())return;this._clearGuides();let h=this._getLineGuideStops(n),p=this._getObjectSnappingEdges(n),d=this._getGuides(h,p);if(!d.length)return;let c=n.absolutePosition(),u={...c};for(let f of d)f.orientation==="V"?u.x=f.lineGuide+f.offset:u.y=f.lineGuide+f.offset;this._applyGapSnappingForDrag(n,c,u),n.absolutePosition(u),this._drawDragGuides(n);}_clearGuides(){if(!this._layer)return;let e=this._layer.find(".snap-guid-line");for(let t of e)t.destroy();this._layer.batchDraw();}_drawDragGuides(e){if(!this._core||!this._layer)return;let t=e.getClientRect({skipShadow:true,skipStroke:false}),o=this._buildDragRays(t),n=this._collectOtherNodeBoxes(e);if(!n.length)return;let r=16;for(let s of o){let l=[];for(let u of n){let f=this._intersectRayWithBox(s.origin,s.dir,u.box);f&&l.push({...f,box:u.box});}if(!l.length)continue;l.sort((u,f)=>u.tEnter-f.tEnter);let h=l.slice(0,r);if(!h.length)continue;let p=0;for(let u of h)u.tExit>p&&(p=u.tExit);if(p<=0)continue;let d;s.dir==="right"?d=[0,0,p,0]:s.dir==="left"?d=[0,0,-p,0]:s.dir==="down"?d=[0,0,0,p]:d=[0,0,0,-p];let c=new H.Line({points:d,stroke:this._options.guidelineColor,strokeWidth:this._options.guidelineWidth,name:"snap-guid-line",dash:this._options.guidelineDash,listening:false});this._layer.add(c),c.absolutePosition({x:s.origin.x,y:s.origin.y});for(let u of h){let f=u.tEnter,g=u.tExit,_=this._pointOnRay(s.origin,s.dir,f),m=this._pointOnRay(s.origin,s.dir,g),b=u.box,v=0,w=0;if(s.dir==="right"){let y=t.x+t.width,N=b.x,x=b.x+b.width;v=N-y,w=x-y;}else if(s.dir==="left"){let y=t.x,N=b.x,x=b.x+b.width;v=y-x,w=y-N;}else if(s.dir==="down"){let y=t.y+t.height,N=b.y,x=b.y+b.height;v=N-y,w=x-y;}else {let y=t.y,N=b.y,x=b.y+b.height;v=y-x,w=y-N;}v=Math.max(0,v),w=Math.max(0,w),this._drawRayMarkerWithLabel(_.x,_.y,v,s.dir),this._drawRayMarkerWithLabel(m.x,m.y,w,s.dir);}}this._layer.batchDraw();}_pointOnRay(e,t,o){return t==="right"?{x:e.x+o,y:e.y}:t==="left"?{x:e.x-o,y:e.y}:t==="down"?{x:e.x,y:e.y+o}:{x:e.x,y:e.y-o}}_drawRayMarkerWithLabel(e,t,o,n){if(!this._layer)return;let r=4,s=new H.Line({points:[-r,-r,r,r],stroke:this._options.guidelineColor,strokeWidth:1,name:"snap-guid-line",listening:false});this._layer.add(s),s.absolutePosition({x:e,y:t});let l=new H.Line({points:[-r,r,r,-r],stroke:this._options.guidelineColor,strokeWidth:1,name:"snap-guid-line",listening:false});this._layer.add(l),l.absolutePosition({x:e,y:t});}_buildDragRays(e){let t=[],o=e.x+e.width/2,n=e.y+e.height/2;t.push({origin:{x:o,y:n},dir:"up"},{origin:{x:o,y:n},dir:"down"},{origin:{x:o,y:n},dir:"left"},{origin:{x:o,y:n},dir:"right"}),t.push({origin:{x:o,y:e.y},dir:"up"},{origin:{x:o,y:e.y+e.height},dir:"down"},{origin:{x:e.x,y:n},dir:"left"},{origin:{x:e.x+e.width,y:n},dir:"right"});let r={x:e.x,y:e.y},s={x:e.x+e.width,y:e.y},l={x:e.x+e.width,y:e.y+e.height},h={x:e.x,y:e.y+e.height};return t.push({origin:r,dir:"up"},{origin:r,dir:"left"},{origin:s,dir:"up"},{origin:s,dir:"right"},{origin:l,dir:"down"},{origin:l,dir:"right"},{origin:h,dir:"down"},{origin:h,dir:"left"}),t}_collectOtherNodeBoxes(e){let t=[];if(!this._core)return t;let o=this._core.nodes.list(),n=e.getClientRect({skipShadow:true,skipStroke:false}),r=n.x+n.width/2,s=n.y+n.height/2,l=this._core.nodes.world;for(let h of o){let p=h.getKonvaNode();if(p===e)continue;let d=p,c=e;if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(e)||typeof c.isAncestorOf=="function"&&c.isAncestorOf(p))continue;let u=p.getParent(),f=e.getParent();if(u&&f&&u===f&&u!==l&&u instanceof H.Group)continue;let g=p.getClientRect({skipShadow:true,skipStroke:false}),_=g.x+g.width/2,m=g.y+g.height/2,b=_-r,v=m-s;Math.sqrt(b*b+v*v)>this._maxGuideDistancePx||t.push({node:p,box:{x:g.x,y:g.y,width:g.width,height:g.height}});}return t}_intersectRayWithBox(e,t,o){let n=e.x,r=e.y,s=o.x,l=o.y,h=o.x+o.width,p=o.y+o.height;if(t==="right"||t==="left"){if(r<l||r>p)return null;if(t==="right"){if(h<=n)return null;let d=Math.max(s,n),c=h,u=d-n,f=c-n;return f<=0||f<=u?null:{tEnter:u,tExit:f}}else {if(s>=n)return null;let d=Math.min(h,n),c=s,u=n-d,f=n-c;return f<=0||f<=u?null:{tEnter:u,tExit:f}}}if(n<s||n>h)return null;if(t==="down"){if(p<=r)return null;let d=Math.max(l,r),c=p,u=d-r,f=c-r;return f<=0||f<=u?null:{tEnter:u,tExit:f}}else {if(l>=r)return null;let d=Math.min(p,r),c=l,u=r-d,f=r-c;return f<=0||f<=u?null:{tEnter:u,tExit:f}}}_getLineGuideStops(e){if(!this._core)return {vertical:[],horizontal:[]};let t=this._core.stage,o=[0,t.width()/2,t.width()],n=[0,t.height()/2,t.height()],r=this._core.nodes.list();for(let s of r){let l=s.getKonvaNode();if(l===e)continue;let h=l,p=e;if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(e)||typeof p.isAncestorOf=="function"&&p.isAncestorOf(l))continue;let d=l.getClientRect({skipShadow:true,skipStroke:false});o.push(d.x,d.x+d.width,d.x+d.width/2),n.push(d.y,d.y+d.height,d.y+d.height/2);}return {vertical:o,horizontal:n}}_getObjectSnappingEdges(e){let t=e.getClientRect({skipShadow:true,skipStroke:false}),o=e.absolutePosition();return {vertical:[{guide:Math.round(t.x),offset:Math.round(o.x-t.x),snap:"start"},{guide:Math.round(t.x+t.width/2),offset:Math.round(o.x-t.x-t.width/2),snap:"center"},{guide:Math.round(t.x+t.width),offset:Math.round(o.x-t.x-t.width),snap:"end"}],horizontal:[{guide:Math.round(t.y),offset:Math.round(o.y-t.y),snap:"start"},{guide:Math.round(t.y+t.height/2),offset:Math.round(o.y-t.y-t.height/2),snap:"center"},{guide:Math.round(t.y+t.height),offset:Math.round(o.y-t.y-t.height),snap:"end"}]}}_getGuides(e,t){let o=[],n=[],r=this._options.thresholdPx;for(let l of e.vertical)for(let h of t.vertical){let p=Math.abs(l-h.guide);p<r&&o.push({lineGuide:l,diff:p,snap:h.snap,offset:h.offset});}for(let l of e.horizontal)for(let h of t.horizontal){let p=Math.abs(l-h.guide);p<r&&n.push({lineGuide:l,diff:p,snap:h.snap,offset:h.offset});}let s=[];if(o.length>0){let[l]=[...o].sort((h,p)=>h.diff-p.diff);l&&s.push({lineGuide:l.lineGuide,offset:l.offset,orientation:"V",snap:l.snap});}if(n.length>0){let[l]=[...n].sort((h,p)=>h.diff-p.diff);l&&s.push({lineGuide:l.lineGuide,offset:l.offset,orientation:"H",snap:l.snap});}return s}_attachExistingTransformers(){if(!this._core)return;let e=this._core.nodes.layer;this._walkAttachTransformers(e);}_walkAttachTransformers(e){this._attachTransformer(e);let t=e,o=typeof t.getChildren=="function"?t.getChildren():[];for(let n of o)this._walkAttachTransformers(n);}_attachTransformer(e){let t=e;if((typeof t.getClassName=="function"?t.getClassName():"")!=="Transformer")return;let n=e;n.off(".snap-guides-resize"),n.on("transform.snap-guides-resize",()=>{this._handleTransformerTransform(n);}),n.on("transformend.snap-guides-resize",()=>{this._clearGuides();});}_walkDetachTransformers(e){let t=e;(typeof t.getClassName=="function"?t.getClassName():"")==="Transformer"&&e.off(".snap-guides-resize");let n=typeof t.getChildren=="function"?t.getChildren():[];for(let r of n)this._walkDetachTransformers(r);}_handleTransformerTransform(e){if(!this._core||!this._layer)return;if((typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"")==="rotater"||this._isVisualLinesShouldCleared(e)){this._clearGuides();return}let n=(typeof e.nodes=="function"?e.nodes():[])[0];if(!n)return;let r=n,s=typeof r.getLayer=="function"?r.getLayer():null;if(!s||s!==this._core.nodes.layer)return;this._clearGuides();let l=this._getLineGuideStops(n),h=this._getObjectSnappingEdges(n),p=this._getGuides(l,h);if(!p.length)return;let d=n.absolutePosition();for(let c of p)c.orientation==="V"?d.x=c.lineGuide+c.offset:d.y=c.lineGuide+c.offset;n.absolutePosition(d),this._drawResizeGuides(e,n,p);}_drawResizeGuides(e,t,o){if(!this._core||!this._layer)return;let n=typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"";if(!n)return;let r=t.getClientRect({skipShadow:true,skipStroke:false}),s=o.some(u=>u.orientation==="V"),l=o.some(u=>u.orientation==="H"),p=this._buildResizeRays(n,r).filter(u=>!((u.dir==="left"||u.dir==="right")&&!l||(u.dir==="up"||u.dir==="down")&&!s));if(!p.length)return;let d=this._collectOtherNodeBoxes(t);if(!d.length)return;let c=16;for(let u of p){let f=[];for(let v of d){let w=this._intersectRayWithBox(u.origin,u.dir,v.box);w&&f.push({...w,box:v.box});}if(!f.length)continue;f.sort((v,w)=>v.tEnter-w.tEnter);let g=f.slice(0,c);if(!g.length)continue;let _=0;for(let v of g)v.tExit>_&&(_=v.tExit);if(_<=0)continue;let m;u.dir==="right"?m=[0,0,_,0]:u.dir==="left"?m=[0,0,-_,0]:u.dir==="down"?m=[0,0,0,_]:m=[0,0,0,-_];let b=new H.Line({points:m,stroke:this._options.guidelineColor,strokeWidth:this._options.guidelineWidth,name:"snap-guid-line",dash:this._options.guidelineDash,listening:false});this._layer.add(b),b.absolutePosition({x:u.origin.x,y:u.origin.y});for(let v of g){let w=v.tEnter,y=v.tExit,N=this._pointOnRay(u.origin,u.dir,w),x=this._pointOnRay(u.origin,u.dir,y),k=v.box,C=0,P=0;if(u.dir==="right"){let R=r.x+r.width,L=k.x,A=k.x+k.width;C=L-R,P=A-R;}else if(u.dir==="left"){let R=r.x,L=k.x,A=k.x+k.width;C=R-A,P=R-L;}else if(u.dir==="down"){let R=r.y+r.height,L=k.y,A=k.y+k.height;C=L-R,P=A-R;}else {let R=r.y,L=k.y,A=k.y+k.height;C=R-A,P=R-L;}C=Math.max(0,C),P=Math.max(0,P),this._drawRayMarkerWithLabel(N.x,N.y,C,u.dir),this._drawRayMarkerWithLabel(x.x,x.y,P,u.dir);}}this._layer.batchDraw();}_buildResizeRays(e,t){let o={x:t.x,y:t.y},n={x:t.x+t.width,y:t.y},r={x:t.x+t.width,y:t.y+t.height},s={x:t.x,y:t.y+t.height},l=[];switch(e){case "top-left":l.push({origin:o,dir:"up"},{origin:o,dir:"left"});break;case "top-right":l.push({origin:n,dir:"up"},{origin:n,dir:"right"});break;case "bottom-right":l.push({origin:r,dir:"down"},{origin:r,dir:"right"});break;case "bottom-left":l.push({origin:s,dir:"down"},{origin:s,dir:"left"});break;case "middle-left":l.push({origin:o,dir:"up"},{origin:o,dir:"left"});break;case "middle-right":l.push({origin:n,dir:"up"},{origin:n,dir:"right"});break;case "top-center":l.push({origin:o,dir:"up"},{origin:o,dir:"left"});break;case "bottom-center":l.push({origin:s,dir:"down"},{origin:s,dir:"left"});break;}return l}_isVisualLinesShouldCleared(e){let t=e;for(;t;){let o=t,n=typeof o.name=="function"?o.name():"";if(n.startsWith("rotate-")||n==="rotate-handles-group"||n.startsWith("corner-radius-")||n==="corner-radius-handles-group")return true;t=t.getParent();}return false}};var Nt=class extends le{constructor(e={}){super();a(this,"mode");a(this,"intensity");a(this,"pixelRatio");a(this,"nodes",new WeakMap);this.mode=e.mode??"sepia";let t=e.intensity??.4;this.intensity=Math.max(0,Math.min(1,t)),this.pixelRatio=e.pixelRatio??3;}onAttach(e){if(this.nodes.has(e))return;let t=e.getKonvaNode(),o=t.filters(),n=Array.isArray(o)?o:[],r=t,s=typeof r.red=="function"?r.red():0,l=typeof r.green=="function"?r.green():0,h=typeof r.blue=="function"?r.blue():0,p=typeof r.alpha=="function"?r.alpha():1,d=typeof r.hue=="function"?r.hue():0,c=typeof r.saturation=="function"?r.saturation():0,u=typeof r.luminance=="function"?r.luminance():0,f={prevFilters:[...n],prevRed:s,prevGreen:l,prevBlue:h,prevAlpha:p,prevHue:d,prevSaturation:c,prevLuminance:u,mouseEnterHandler:()=>{},mouseLeaveHandler:()=>{},hadHover:false};f.mouseEnterHandler=()=>{if(f.hadHover=true,t.cache({pixelRatio:this.pixelRatio}),this.mode==="sepia"){let g=t.filters(),_=Array.isArray(g)?g:[];_.includes(H.Filters.Sepia)||t.filters([..._,H.Filters.Sepia]);}else {let g=t.filters(),_=Array.isArray(g)?g:[];_.includes(H.Filters.HSL)||t.filters([..._,H.Filters.HSL]);let m=this.intensity,b=18,v=.2,w=b*m,y=v*m;switch(this.mode){case "warm":{typeof r.hue=="function"&&r.hue(f.prevHue+w),typeof r.saturation=="function"&&r.saturation(f.prevSaturation+y);break}case "cool":{typeof r.hue=="function"&&r.hue(f.prevHue-w),typeof r.saturation=="function"&&r.saturation(f.prevSaturation+y);break}}}t.getLayer()?.batchDraw();},f.mouseLeaveHandler=()=>{f.hadHover&&(t.filters(f.prevFilters),(this.mode==="warm"||this.mode==="cool")&&(typeof r.red=="function"&&r.red(f.prevRed),typeof r.green=="function"&&r.green(f.prevGreen),typeof r.blue=="function"&&r.blue(f.prevBlue),typeof r.alpha=="function"&&r.alpha(f.prevAlpha),typeof r.hue=="function"&&r.hue(f.prevHue),typeof r.saturation=="function"&&r.saturation(f.prevSaturation),typeof r.luminance=="function"&&r.luminance(f.prevLuminance)),t.getLayer()?.batchDraw(),t.clearCache());},t.on("mouseenter.imageHoverFilterAddon",f.mouseEnterHandler),t.on("mouseleave.imageHoverFilterAddon",f.mouseLeaveHandler),this.nodes.set(e,f);}onDetach(e){let t=this.nodes.get(e);if(!t)return;let o=e.getKonvaNode();o.off("mouseenter.imageHoverFilterAddon",t.mouseEnterHandler),o.off("mouseleave.imageHoverFilterAddon",t.mouseLeaveHandler),o.filters(t.prevFilters);let n=o;(this.mode==="warm"||this.mode==="cool")&&(typeof n.red=="function"&&n.red(t.prevRed),typeof n.green=="function"&&n.green(t.prevGreen),typeof n.blue=="function"&&n.blue(t.prevBlue),typeof n.alpha=="function"&&n.alpha(t.prevAlpha)),o.getLayer()?.batchDraw(),o.clearCache(),this.nodes.delete(e);}};var kt=class extends te{constructor(e={}){super();a(this,"_options");a(this,"_instance",null);a(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let o=t.plugins.list().find(r=>r instanceof _e);if(o){this._instance=o,this._owned=false;return}let n=new _e(this._options);t.plugins.addPlugins([n]),this._instance=n,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var St=class extends te{constructor(e={}){super();a(this,"_options");a(this,"_instance",null);a(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let o=t.plugins.list().find(r=>r instanceof Ee);if(o){this._instance=o,this._owned=false;return}let n=new Ee(this._options);t.plugins.addPlugins([n]),this._instance=n,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Tt=class extends te{constructor(e={}){super();a(this,"_options");a(this,"_instance",null);a(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let o=t.plugins.list().find(r=>r instanceof Pe);if(o){this._instance=o,this._owned=false;return}let n=new Pe(this._options);t.plugins.addPlugins([n]),this._instance=n,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Ct=class extends le{constructor(e={}){super();a(this,"stroke");a(this,"strokeWidth");a(this,"fill");a(this,"mode");a(this,"nodes",new WeakMap);this.stroke=e.stroke??"#1976d2",this.strokeWidth=e.strokeWidth??2,this.fill=e.fill??"rgba(255, 255, 0, 0.25)",this.mode=e.mode??"stroke";}onAttach(e){if(this.nodes.has(e))return;let t=e.getKonvaNode(),o={mouseEnterHandler:()=>{},mouseLeaveHandler:()=>{},prevStroke:e.getStroke(),prevStrokeWidth:e.getStrokeWidth(),prevStrokeEnabled:t.strokeEnabled(),prevFill:t.fill(),prevFillEnabled:t.fillEnabled(),hadHover:false};o.mouseEnterHandler=()=>{o.prevStroke=e.getStroke(),o.prevStrokeWidth=e.getStrokeWidth(),o.prevStrokeEnabled=t.strokeEnabled(),o.prevFill=t.fill(),o.prevFillEnabled=t.fillEnabled(),o.hadHover=true,(this.mode==="stroke"||this.mode==="both")&&(t.strokeEnabled(true),t.stroke(this.stroke),t.strokeWidth(this.strokeWidth)),(this.mode==="fill"||this.mode==="both")&&(t.fillEnabled(true),t.fill(this.fill)),t.getLayer()?.batchDraw();},o.mouseLeaveHandler=()=>{o.hadHover&&(t.strokeEnabled(o.prevStrokeEnabled),typeof o.prevStroke=="string"&&t.stroke(o.prevStroke),t.strokeWidth(o.prevStrokeWidth),t.fillEnabled(o.prevFillEnabled),typeof o.prevFill=="string"&&t.fill(o.prevFill),t.getLayer()?.batchDraw());},t.on("mouseenter.shapeHoverHighlightAddon",o.mouseEnterHandler),t.on("mouseleave.shapeHoverHighlightAddon",o.mouseLeaveHandler),this.nodes.set(e,o);}onDetach(e){let t=this.nodes.get(e);if(!t)return;let o=e.getKonvaNode();o.off("mouseenter.shapeHoverHighlightAddon",t.mouseEnterHandler),o.off("mouseleave.shapeHoverHighlightAddon",t.mouseLeaveHandler),t.hadHover&&(o.strokeEnabled(t.prevStrokeEnabled),typeof t.prevStroke=="string"&&o.stroke(t.prevStroke),o.strokeWidth(t.prevStrokeWidth),o.fillEnabled(t.prevFillEnabled),typeof t.prevFill=="string"&&o.fill(t.prevFill),o.getLayer()?.batchDraw()),this.nodes.delete(e);}};var Et=class extends le{constructor(){super(...arguments);a(this,"nodes",new WeakMap);}onAttach(e){if(this.nodes.has(e))return;let t=o=>{if(o.cancelled)return;let n=this.normalize(o.newText);n!==o.newText&&(e.setText(n),e.getKonvaNode().getLayer()?.batchDraw());};e.onTextChange(t),this.nodes.set(e,{handler:t});}onDetach(e){let t=this.nodes.get(e);t&&(e.offTextChange(t.handler),this.nodes.delete(e));}normalize(e){return e?e.replace(/[ \t]+/g," ").trim():""}};export{ut as AreaSelectionPlugin,pt as CameraHotkeysPlugin,Re as CameraManager,gt as ContentFromClipboardPlugin,dt as CoreEngine,me as DebounceHelper,Ke as EventBus,_t as GridPlugin,Be as HistoryManager,mt as HistoryPlugin,Nt as ImageHoverFilterAddon,bt as LogoPlugin,ae as MediaPlaceholder,le as NodeAddon,Me as NodeAddons,yt as NodeHotkeysPlugin,Ae as NodeManager,te as PluginAddon,Le as Plugins,kt as RulerGuidesAddon,_e as RulerGuidesPlugin,St as RulerHighlightAddon,Ee as RulerHighlightPlugin,Tt as RulerManagerAddon,Pe as RulerManagerPlugin,wt as RulerPlugin,ve as SelectionPlugin,Ct as ShapeHoverHighlightAddon,Et as TextAutoTrimAddon,ge as ThrottleHelper,De as VideoOverlayAddon,xt as VisualGuidesPlugin};
111
+ `.trim(),o=`data:image/svg+xml,${encodeURIComponent(t)}`,s=this._core.stage.container();s.style.cursor=`url("${o}") 12 12, grab`;}_updateRotateHandlesPosition(){if(!this._core||!this._selected||!this._rotateHandlesGroup)return;let e=this._selected.getKonvaNode(),t=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),n=t.width,o=t.height;if(n<=0||o<=0)return;let s=e.getAbsoluteTransform().copy(),r=S=>s.point(S),l=12,h=r({x:t.x+n/2,y:t.y+o/2}),c=r({x:t.x,y:t.y}),d=r({x:t.x+n,y:t.y}),u=r({x:t.x+n,y:t.y+o}),p=r({x:t.x,y:t.y+o}),f=S=>{let C=S.x-h.x,T=S.y-h.y,K=Math.hypot(C,T)||1;return {x:C/K,y:T/K}},g=f(c),m=f(d),_=f(u),b=f(p),v={x:c.x+g.x*l,y:c.y+g.y*l},w={x:d.x+m.x*l,y:d.y+m.y*l},x={x:u.x+_.x*l,y:u.y+_.y*l},N={x:p.x+b.x*l,y:p.y+b.y*l};this._rotateHandles.tl&&this._rotateHandles.tl.absolutePosition(v),this._rotateHandles.tr&&this._rotateHandles.tr.absolutePosition(w),this._rotateHandles.br&&this._rotateHandles.br.absolutePosition(x),this._rotateHandles.bl&&this._rotateHandles.bl.absolutePosition(N);let k=this._rotateHandlesGroup.getParent();if(k){let S=k.getAbsoluteTransform().decompose(),C=1/(Math.abs(S.scaleX)||1),T=1/(Math.abs(S.scaleY)||1);this._rotateHandles.tl&&this._rotateHandles.tl.scale({x:C,y:T}),this._rotateHandles.tr&&this._rotateHandles.tr.scale({x:C,y:T}),this._rotateHandles.br&&this._rotateHandles.br.scale({x:C,y:T}),this._rotateHandles.bl&&this._rotateHandles.bl.scale({x:C,y:T});}}_setupSizeLabel(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroySizeLabel();let t=new G.Label({listening:false,opacity:.95}),n=new G.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000"}),o=new G.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:6,fill:"#ffffff"});t.add(n),t.add(o),e.add(t),this._sizeLabel=t,this._updateSizeLabel();}_scheduleUIUpdate(){this._uiUpdateDebounce.schedule(()=>{this._updateSizeLabel(),this._updateRotateHandlesPosition(),this._updateCornerRadiusHandlesPosition();});}_updateSizeLabel(){if(!this._core||!this._selected||!this._sizeLabel)return;let e=this._selected.getKonvaNode(),t=e.getClientRect({skipShadow:true,skipStroke:false}),n=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),o=e.getAbsoluteTransform().decompose(),s=this._core.nodes.world.getAbsoluteTransform().decompose(),r=Math.abs(o.scaleX)||1,l=Math.abs(o.scaleY)||1,h=Math.abs(s.scaleX)||1,c=Math.abs(s.scaleY)||1,d=n.width*(r/h),u=n.height*(l/c),p=Math.max(0,Math.round(d)),f=Math.max(0,Math.round(u));this._sizeLabel.getText().text(String(p)+" \xD7 "+String(f));let m=8,_=t.x+t.width/2,b=t.y+t.height+m,w=this._sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this._sizeLabel.absolutePosition({x:_,y:b}),this._sizeLabel.offsetX(w/2),this._sizeLabel.offsetY(0);let x=this._sizeLabel.getParent();if(x){let N=x.getAbsoluteTransform().decompose(),k=1/(Math.abs(N.scaleX)||1),S=1/(Math.abs(N.scaleY)||1);this._sizeLabel.scale({x:k,y:S});}this._sizeLabel.moveToTop(),this._transformer&&this._transformer.moveToTop(),this._cornerHandlesGroup&&this._cornerHandlesGroup.moveToTop();}_destroySizeLabel(){this._sizeLabel&&(this._sizeLabel.destroy(),this._sizeLabel=null);}_isCornerRadiusSupported(e){return e instanceof G.Rect||e instanceof G.Image}_getCornerRadiusArray(e){let t=e.cornerRadius();if(Array.isArray(t)){let[o=0,s=0,r=0,l=0]=t;return [o||0,s||0,r||0,l||0]}let n=typeof t=="number"?t:0;return [n,n,n,n]}_setCornerRadiusArray(e,t){let[n,o,s,r]=t;n===o&&o===s&&s===r?e.cornerRadius(n):e.cornerRadius(t);}_setupCornerRadiusHandles(e=false){if(!this._core||!this._selected)return;let t=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(t))return;let n=this._core.nodes.layer,o=this._core.stage;this._destroyCornerRadiusHandles();let s=new G.Group({name:"corner-radius-handles-group",listening:true});n.add(s),s.moveToTop(),s.visible(false),this._cornerHandlesGroup=s,t.off(".cornerRadiusHover"),t.on("mouseenter.cornerRadiusHover",()=>{!this._core||!this._cornerHandlesGroup||this._core.nodes.world.scaleX()<.3||this._cornerHandlesGroup.visible(true);}),t.on("mouseleave.cornerRadiusHover",()=>{if(!this._cornerHandlesGroup)return;let E=o.getPointerPosition();if(!E){this._cornerHandlesGroup.visible(false);return}let R=n.getIntersection(E);R&&this._cornerHandlesGroup.isAncestorOf(R)||this._cornerHandlesGroup.visible(false);}),s.on("mouseenter.cornerRadiusHover",()=>{!this._core||!this._cornerHandlesGroup||this._core.nodes.world.scaleX()<.3||this._cornerHandlesGroup.visible(true);}),s.on("mouseleave.cornerRadiusHover",()=>{this._cornerHandlesGroup&&this._cornerHandlesGroup.visible(false);});let r=o.getPointerPosition();if(r&&this._core.nodes.world.scaleX()>=.3){let A=n.getIntersection(r);A&&(A===t||t.isAncestorOf(A))&&this._cornerHandlesGroup.visible(true);}let l=()=>{let E=t.width(),R=t.height(),A=t.getAbsoluteScale(),F=1/(Math.abs(A.x)||1),j=1/(Math.abs(A.y)||1),Z=12*F,z=12*j,te=Math.max(0,E/2-Z),se=Math.max(0,R/2-z),ne=Math.min(te,se);return {tl:{corner:{x:Z,y:z},sign:{x:1,y:1},side:ne},tr:{corner:{x:E-Z,y:z},sign:{x:-1,y:1},side:ne},br:{corner:{x:E-Z,y:R-z},sign:{x:-1,y:-1},side:ne},bl:{corner:{x:Z,y:R-z},sign:{x:1,y:-1},side:ne}}},h=(E,R)=>{let A=t.getAbsoluteTransform().copy(),F=Y=>A.copy().invert().point(Y),j=Y=>A.point(Y),z=l()[R],te=F(E),se=te.x-z.corner.x,ne=te.y-z.corner.y,H=(z.sign.x*se+z.sign.y*ne)/2;H=Math.max(0,Math.min(z.side,H));let V={x:z.corner.x+z.sign.x*H,y:z.corner.y+z.sign.y*H};return {snappedAbs:j(V),r:H,meta:z}},c=E=>new G.Line({name:E,points:[],stroke:e?"#4a90e2":"",strokeWidth:e?1:0,dash:e?[4,4]:[],closed:true,listening:false}),d=c("corner-square-tl"),u=c("corner-square-tr"),p=c("corner-square-br"),f=c("corner-square-bl");s.add(d,u,p,f);let g=E=>{let R=new G.Circle({name:E,radius:4,fill:"#ffffff",stroke:"#4a90e2",strokeWidth:1.5,draggable:true,dragOnTop:true,hitStrokeWidth:16});return R.on("mouseenter.corner-radius",()=>{this._core&&(this._core.stage.container().style.cursor="default");}),R},m=g("corner-radius-tl"),_=g("corner-radius-tr"),b=g("corner-radius-br"),v=g("corner-radius-bl");s.add(m,_,b,v),this._cornerHandles={tl:m,tr:_,br:b,bl:v};let w={tl:0,tr:1,br:2,bl:3},x=false,N=null,k=false,S=()=>{let E=t.getAbsoluteTransform().copy(),R=t.width(),A=t.height();return E.point({x:R/2,y:A/2})},C=()=>{let E={};return this._cornerHandles.tl&&(E.tl=this._cornerHandles.tl.getAbsolutePosition()),this._cornerHandles.tr&&(E.tr=this._cornerHandles.tr.getAbsolutePosition()),this._cornerHandles.br&&(E.br=this._cornerHandles.br.getAbsolutePosition()),this._cornerHandles.bl&&(E.bl=this._cornerHandles.bl.getAbsolutePosition()),E},T=(E,R=8)=>{let A=S();return Math.hypot(E.x-A.x,E.y-A.y)<=R},K=(E,R=6)=>{let A=S();return Math.min(Math.abs(E.x-A.x),Math.abs(E.y-A.y))<=R},L=(E,R=8)=>{let A=C(),F=0;return ["tl","tr","br","bl"].forEach(j=>{let Z=A[j];Z&&Math.hypot(Z.x-E.x,Z.y-E.y)<=R&&F++;}),F>=2},B=E=>{if(!x||N)return;let R=S(),A=E.x-R.x,F=E.y-R.y,j=Math.hypot(A,F);if(j<.1)return;A/=j,F/=j;let Z=t.getAbsoluteTransform().copy(),z=l(),te=["tl","tr","br","bl"].reduce((H,V)=>{let de=z[V],Y=Z.point(de.corner),re=Y.x-R.x,q=Y.y-R.y,ee=Math.hypot(re,q)||1;return H[V]={x:re/ee,y:q/ee},H},{}),se="tl",ne=-1/0;["tl","tr","br","bl"].forEach(H=>{let V=te[H],de=A*V.x+F*V.y;de>ne&&(ne=de,se=H);}),N=se;},P=E=>R=>{B(R);let A=N??E,{snappedAbs:F,r:j,meta:Z}=h(R,A),z=t.width(),te=t.height(),se=Math.max(0,Math.min(z,te)/2),ne=Z.side>0?j/Z.side:0,H=Math.round(ne*se);H=Math.max(0,Math.min(H,se));let V=this._getCornerRadiusArray(t),de=w[A];return k?V[de]=H:(V[0]=H,V[1]=H,V[2]=H,V[3]=H),this._setCornerRadiusArray(t,V),this._showRadiusLabelForCorner(de),I(),this._core?.nodes.layer.batchDraw(),F};m.dragBoundFunc(P("tl")),_.dragBoundFunc(P("tr")),b.dragBoundFunc(P("br")),v.dragBoundFunc(P("bl"));let I=()=>{let{tl:E,tr:R,br:A,bl:F}=this._cornerHandles;if(!E||!R||!A||!F)return;if(this._cornerHandlesSuppressed){this._cornerHandlesGroup?.visible(false),this._radiusLabel?.visible(false);return}if(this._core&&this._cornerHandlesGroup&&this._radiusLabel){if(this._core.nodes.world.scaleX()<.3){this._cornerHandlesGroup.visible(false),this._radiusLabel.visible(false);return}this._cornerHandlesGroup.visible(true);}let j=t.getAbsoluteTransform().copy(),Z=n.getAbsoluteTransform().copy().invert(),z=Y=>j.point(Y),te=Y=>Z.point(j.point(Y)),se=l(),ne=this._getCornerRadiusArray(t),H=(Y,re,q)=>{let ee=se[Y],Se=t.width(),Xe=t.height(),Ce=Math.max(0,Math.min(Se,Xe)/2),Ye=Math.max(0,Math.min(Ce,ne[re]||0)),je=Ce>0?Ye/Ce:0,Yt=Math.max(0,Math.min(ee.side,je*ee.side)),ln={x:ee.corner.x+ee.sign.x*Yt,y:ee.corner.y+ee.sign.y*Yt};q.absolutePosition(z(ln));},V=(Y,re)=>{let q=se[Y],ee=q.corner,Se={x:q.corner.x+q.sign.x*q.side,y:q.corner.y+q.sign.y*q.side},Xe=te({x:ee.x,y:ee.y}),Ce=te({x:Se.x,y:ee.y}),Ye=te({x:Se.x,y:Se.y}),je=te({x:ee.x,y:Se.y});re.points([Xe.x,Xe.y,Ce.x,Ce.y,Ye.x,Ye.y,je.x,je.y]);};V("tl",d),V("tr",u),V("br",p),V("bl",f),H("tl",0,E),H("tr",1,R),H("br",2,A),H("bl",3,F);let de=this._cornerHandlesGroup?.getParent();if(de){let Y=de.getAbsoluteTransform().decompose(),re=1/(Math.abs(Y.scaleX)||1),q=1/(Math.abs(Y.scaleY)||1);E.scale({x:re,y:q}),R.scale({x:re,y:q}),A.scale({x:re,y:q}),F.scale({x:re,y:q});}this._cornerHandlesGroup?.moveToTop();};this._updateCornerRadiusHandlesPosition=I;let X=(E,R)=>{k=!!R?.evt?.altKey;let A=E.getAbsolutePosition();if(x=T(A,8)||K(A,6)||L(A,8),N=null,x){let F=this._core?.stage.getPointerPosition()??A;B(F);}},U=(E,R)=>A=>{k=A.evt.altKey;},J=()=>{if(x=false,N=null,k=false,this._selected&&this._core){let E=this._selected.getKonvaNode(),R={x:E.x(),y:E.y()};typeof E.width=="function"&&(R.width=E.width()),typeof E.height=="function"&&(R.height=E.height()),this._core.eventBus.emit("node:transformed",this._selected,R);}};m.on("dragstart.corner-radius",E=>{X(m,E);}),_.on("dragstart.corner-radius",E=>{X(_,E);}),b.on("dragstart.corner-radius",E=>{X(b,E);}),v.on("dragstart.corner-radius",E=>{X(v,E);}),m.on("dragmove.corner-radius",U()),_.on("dragmove.corner-radius",U()),b.on("dragmove.corner-radius",U()),v.on("dragmove.corner-radius",U()),m.on("dragend.corner-radius",J),_.on("dragend.corner-radius",J),b.on("dragend.corner-radius",J),v.on("dragend.corner-radius",J);let W=E=>()=>{this._showRadiusLabelForCorner(E);},$=()=>{this._hideRadiusLabel();},ie=E=>()=>{this._showRadiusLabelForCorner(E);};m.on("mouseenter.corner-radius",W(0)),_.on("mouseenter.corner-radius",W(1)),b.on("mouseenter.corner-radius",W(2)),v.on("mouseenter.corner-radius",W(3)),m.on("mouseleave.corner-radius",$),_.on("mouseleave.corner-radius",$),b.on("mouseleave.corner-radius",$),v.on("mouseleave.corner-radius",$),m.on("dragstart.corner-radius",W(0)),_.on("dragstart.corner-radius",W(1)),b.on("dragstart.corner-radius",W(2)),v.on("dragstart.corner-radius",W(3)),m.on("dragmove.corner-radius",ie(0)),_.on("dragmove.corner-radius",ie(1)),b.on("dragmove.corner-radius",ie(2)),v.on("dragmove.corner-radius",ie(3)),m.on("dragend.corner-radius",$),_.on("dragend.corner-radius",$),b.on("dragend.corner-radius",$),v.on("dragend.corner-radius",$);let ue=()=>{if(!this._selected)return;this._selected.getKonvaNode().draggable(false),this._restyleSideAnchors();},fe=()=>{if(!this._selected)return;let E=this._selected,R=E.getKonvaNode();this._options.dragEnabled&&!(E instanceof M)&&typeof R.draggable=="function"&&R.draggable(true),this._restyleSideAnchors();};m.on("mousedown.corner-radius touchstart.corner-radius",ue),_.on("mousedown.corner-radius touchstart.corner-radius",ue),b.on("mousedown.corner-radius touchstart.corner-radius",ue),v.on("mousedown.corner-radius touchstart.corner-radius",ue),m.on("mouseup.corner-radius touchend.corner-radius",fe),_.on("mouseup.corner-radius touchend.corner-radius",fe),b.on("mouseup.corner-radius touchend.corner-radius",fe),v.on("mouseup.corner-radius touchend.corner-radius",fe);let Q=".corner-squares",Ne=false,ke=()=>{Ne||(Ne=true,G.Util.requestAnimFrame(()=>{Ne=false,I(),this._core?.nodes.layer.batchDraw();}));};o.on(["wheel","resize","xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(E=>E+Q).join(" "),ke),n.on(["xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(E=>E+Q).join(" "),ke),t.on(["dragmove","transform","xChange","yChange","widthChange","heightChange","rotationChange","scaleXChange","scaleYChange","positionChange","scaleChange"].map(E=>E+Q).join(" "),ke),this._transformer&&(this._transformer.on("transformstart"+Q,()=>{this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel(),this._core?.nodes.layer.batchDraw();}),this._transformer.on("transform"+Q,()=>{I(),this._core?.nodes.layer.batchDraw();}),this._transformer.on("transformend"+Q,()=>{this._cornerHandlesSuppressed=false,ke();})),s.on("destroy"+Q,()=>{o.off(Q),n.off(Q),t.off(Q),this._transformer?.off(Q);}),I(),n.batchDraw();}_destroyCornerRadiusHandles(){this._cornerHandlesGroup&&(this._cornerHandlesGroup.destroy(),this._cornerHandlesGroup=null),this._cornerHandles={tl:null,tr:null,br:null,bl:null},this._core&&(this._core.stage.container().style.cursor="default"),this._destroyRadiusLabel(),this._selected&&this._selected.getKonvaNode().off(".overlay-sync");}_bakeRectScale(e){if(!(e instanceof G.Rect))return;let t=e.scaleX(),n=e.scaleY();if(t===1&&n===1)return;let o=e.getAbsolutePosition(),s=e.width(),r=e.height(),l=Math.abs(t)*s,h=Math.abs(n)*r;e.width(l),e.height(h),e.scaleX(1),e.scaleY(1),e.setAbsolutePosition(o);}_updateCornerRadiusHandlesPosition(){if(!this._core||!this._selected||!this._cornerHandlesGroup)return;let e=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(e))return;let t=e,n=t.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),o=n.width,s=n.height;if(o<=0||s<=0)return;let r=t.getAbsoluteTransform().copy(),l=k=>r.point(k),h=t.getAbsoluteScale(),c=1/(Math.abs(h.x)||1),d=1/(Math.abs(h.y)||1),u=12*c,p=12*d,f=this._getCornerRadiusArray(t),g=Math.min(o,s)/2||1,m=k=>{let S=Math.hypot(k.x,k.y)||1;return {x:k.x/S,y:k.y/S}},_=[m({x:o/2-u,y:s/2-p}),m({x:-(o/2-u),y:s/2-p}),m({x:-(o/2-u),y:-(s/2-p)}),m({x:o/2-u,y:-(s/2-p)})],b=l({x:n.x+u+_[0].x*Math.min(g,f[0]),y:n.y+p+_[0].y*Math.min(g,f[0])}),v=l({x:n.x+o-u+_[1].x*Math.min(g,f[1]),y:n.y+p+_[1].y*Math.min(g,f[1])}),w=l({x:n.x+o-u+_[2].x*Math.min(g,f[2]),y:n.y+s-p+_[2].y*Math.min(g,f[2])}),x=l({x:n.x+u+_[3].x*Math.min(g,f[3]),y:n.y+s-p+_[3].y*Math.min(g,f[3])});this._cornerHandles.tl&&this._cornerHandles.tl.absolutePosition(b),this._cornerHandles.tr&&this._cornerHandles.tr.absolutePosition(v),this._cornerHandles.br&&this._cornerHandles.br.absolutePosition(w),this._cornerHandles.bl&&this._cornerHandles.bl.absolutePosition(x);let N=this._cornerHandlesGroup.getParent();if(N){let k=N.getAbsoluteTransform().decompose(),S=1/(Math.abs(k.scaleX)||1),C=1/(Math.abs(k.scaleY)||1);this._cornerHandles.tl&&this._cornerHandles.tl.scale({x:S,y:C}),this._cornerHandles.tr&&this._cornerHandles.tr.scale({x:S,y:C}),this._cornerHandles.br&&this._cornerHandles.br.scale({x:S,y:C}),this._cornerHandles.bl&&this._cornerHandles.bl.scale({x:S,y:C});}this._cornerHandlesGroup.moveToTop();}_updateCornerRadiusHandlesVisibility(){if(!this._core||!this._selected||!this._cornerHandlesGroup)return;let t=this._core.nodes.world.scaleX(),n=this._core.stage,o=this._core.nodes.layer,s=this._selected.getKonvaNode(),r=n.getPointerPosition();if(!r){t<.3&&this._cornerHandlesGroup.visible(false);return}if(t<.3){this._cornerHandlesGroup.visible(false);return}let l=o.getIntersection(r);if(l){let h=l===s||s.isAncestorOf(l),c=this._cornerHandlesGroup.isAncestorOf(l);h||c?this._cornerHandlesGroup.visible(true):this._cornerHandlesGroup.visible(false);}else this._cornerHandlesGroup.visible(false);}_ensureRadiusLabel(){if(!this._core)return null;if(this._radiusLabel)return this._radiusLabel;let e=this._core.nodes.layer,t=new G.Label({listening:false,opacity:.95}),n=new G.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),o=new G.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:4,fill:"#ffffff"});return t.add(n),t.add(o),t.visible(false),e.add(t),this._radiusLabel=t,t}_updateRadiusLabelAt(e,t){let n=this._ensureRadiusLabel();if(!n)return;n.getText().text(t);let r=n.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width,l={x:8,y:8};n.absolutePosition({x:e.x-l.x,y:e.y+l.y}),n.offsetX(r),n.offsetY(0);let h=n.getParent();if(h){let c=h.getAbsoluteTransform().decompose(),d=1/(Math.abs(c.scaleX)||1),u=1/(Math.abs(c.scaleY)||1);n.scale({x:d,y:u});}n.visible(true),n.moveToTop(),this._transformer&&this._transformer.moveToTop();}_showRadiusLabelForCorner(e){if(!this._core||!this._selected)return;let t=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(t))return;let n=t,o=this._getCornerRadiusArray(n),s=Math.round(o[e]),r=e===0?this._cornerHandles.tl:e===1?this._cornerHandles.tr:e===2?this._cornerHandles.br:this._cornerHandles.bl;if(!r)return;let l=r.getAbsolutePosition();this._updateRadiusLabelAt(l,"Radius "+String(s));}_hideRadiusLabel(){this._radiusLabel&&this._radiusLabel.visible(false);}_destroyRadiusLabel(){this._radiusLabel&&(this._radiusLabel.destroy(),this._radiusLabel=null);}_findBaseNodeByTarget(e){if(!this._core)return null;if(this._selected){let r=this._selected.getKonvaNode();if(r===e)return this._selected;if(typeof r.isAncestorOf=="function"&&r.isAncestorOf(e))return this._selected}let t=this._core.nodes.list(),n=t.filter(r=>r instanceof M),o=false;for(let r of n){let l=r.getContentGroup();if(e===l||typeof l.isAncestorOf=="function"&&l.isAncestorOf(e)){o=true;break}}if(o){let r=t.filter(h=>!(h instanceof M)),l=null;for(let h of r){let c=h.getKonvaNode();if(typeof c.isAncestorOf!="function"||!c.isAncestorOf(e))continue;let d=true;for(let u of r){if(u===h)continue;let p=u.getKonvaNode();if(typeof p.isAncestorOf=="function"&&p.isAncestorOf(c)){d=false;break}}if(d){l=h;break}}if(l)return l;for(let h of r)if(h.getKonvaNode()===e)return h}let s=null;for(let r of this._core.nodes.list()){let l=r.getKonvaNode();if(typeof l.isAncestorOf=="function"&&l.isAncestorOf(e)){let h=true;for(let c of this._core.nodes.list()){if(c===r)continue;let d=c.getKonvaNode();if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(l)){h=false;break}}h&&(s=r);}}if(s)return s;for(let r of this._core.nodes.list())if(r.getKonvaNode()===e)return r;return null}_disableGroupChildrenDragging(e){let t=e.getChildren();for(let n of t){let o=n;typeof o.draggable=="function"&&o.draggable(false);}}};var St=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_layer",null);a(this,"_rect",null);a(this,"_start",null);a(this,"_transformer",null);a(this,"_selecting",false);a(this,"_skipNextClick",false);a(this,"_lastPickedBaseNodes",[]);a(this,"_autoPanRafId",null);a(this,"_autoPanActive",false);a(this,"_autoPanEdgePx",50);a(this,"_autoPanMaxSpeedPx",20);a(this,"_options");this._options={rectStroke:e.rectStroke??"#2b83ff",rectFill:e.rectFill??"#2b83ff",rectStrokeWidth:e.rectStrokeWidth??1,rectOpacity:e.rectOpacity??.15,enableKeyboardShortcuts:e.enableKeyboardShortcuts??true};}onAttach(e){this._core=e;let t=new G.Layer({name:"area-selection-layer",listening:false});e.stage.add(t),this._layer=t,this._rect=new G.Rect({x:0,y:0,width:0,height:0,visible:false,stroke:this._options.rectStroke,strokeWidth:this._options.rectStrokeWidth,fill:this._options.rectFill,opacity:this._options.rectOpacity,listening:false}),t.add(this._rect);let n=e.stage;n.on("mousedown.area",o=>{if(o.evt.button!==0)return;let s=o.target,r=e.nodes.layer;if(s!==n&&s.getLayer()===r){let f=this._core?.nodes.list()??[],g=false;for(let v of f){if(!(v instanceof M))continue;let w=v.getKonvaNode(),x=v.getContentGroup(),N=s,k=false;for(;N;){if(N===w){k=true;break}N=N.getParent();}if(!k||s===x||x.isAncestorOf(s))continue;let C=x.getChildren().length>0,T=w,K=typeof T.draggable=="function"?T.draggable():true;if(C&&!K){g=true;break}}if(!g)return;let m=this._getSelectionPlugin(),_=m?.getSelected(),b=n.getPointerPosition();if(_&&b){let w=_.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false});if(b.x>=w.x&&b.x<=w.x+w.width&&b.y>=w.y&&b.y<=w.y+w.height)return}m&&m.clearSelectionFromAreaLasso();}let l=n.getPointerPosition();if(!l||!this._rect)return;let c=this._getSelectionPlugin()?.getSelected();if(c){let g=c.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false});if(l.x>=g.x&&l.x<=g.x+g.width&&l.y>=g.y&&l.y<=g.y+g.height)return}let d=n.findOne(".ruler-layer");if(d&&o.target.getLayer()===d)return;let u=n.findOne(".guides-layer");if(u&&o.target.getLayer()===u)return;let p=30;l.y<=p||l.x<=p||(this._selecting=true,this._start={x:l.x,y:l.y},this._rect.visible(true),this._rect.position({x:l.x,y:l.y}),this._rect.size({width:0,height:0}),this._layer?.batchDraw(),this._lastPickedBaseNodes=[],this._startAutoPanLoop());}),n.on("mousemove.area",()=>{if(!this._selecting||!this._rect||!this._start)return;let o=n.getPointerPosition();if(!o)return;let s=Math.min(this._start.x,o.x),r=Math.min(this._start.y,o.y),l=Math.abs(o.x-this._start.x),h=Math.abs(o.y-this._start.y);this._rect.position({x:s,y:r}),this._rect.size({width:l,height:h}),this._layer?.batchDraw();let c={x:s,y:r,width:l,height:h},d=this._core?.nodes.list()??[],u=new Set,p=new Set;for(let m of d){if(m instanceof ge)continue;let _=m.getKonvaNode();if(_.getLayer()!==this._core?.nodes.layer)continue;if(m instanceof M){let N=m.getRect().getClientRect({skipShadow:true,skipStroke:true});m.getContentGroup().getChildren().length>0?this._rectContains(c,N)&&(u.add(m),p.add(m)):this._rectsIntersect(c,N)&&u.add(m);continue}let v=false;for(let x of p){let N=x.getContentGroup();if(_===N||N.isAncestorOf(_)){v=true;break}}if(v)continue;let w=_.getClientRect({skipShadow:true,skipStroke:false});if(this._rectsIntersect(c,w)){let x=this._findOwningGroupBaseNode(_);u.add(x??m);}}let f=Array.from(u),g=this._getSelectionPlugin();if(f.length>0&&(this._lastPickedBaseNodes=f),g){let m=g.getMultiGroupController();f.length>0&&m.ensure(f),this._core?.stage.batchDraw();}}),n.on("mouseup.area",o=>{if(!this._selecting)return;let s=false;if(this._rect?.visible()){let r=this._rect.size();s=r.width>2||r.height>2;}this._finalizeArea(),this._stopAutoPanLoop(),s&&(this._skipNextClick=true,this._core?.stage.setAttr("_skipSelectionEmptyClickOnce",true),o.cancelBubble=true);}),n.on("click.area",o=>{if(!this._core)return;if(this._skipNextClick){this._skipNextClick=false,o.cancelBubble=true;return}if(o.evt.shiftKey)return;let r=this._getSelectionPlugin()?.getMultiGroupController(),l=!!r?.isActive();if(!l&&!this._isPermanentGroupSelected())return;let h=o.target,c=this._currentGroupNode();c?this._isAncestor(c,h)||this._clearSelection():l&&r&&(r.isInsideTempByTarget(h)||(r.destroy(),this._core.stage.batchDraw()));});}onDetach(e){e.stage.off(".area"),this._stopAutoPanLoop(),this._clearSelection(),this._layer&&this._layer.destroy(),this._layer=null,this._rect=null;}_rectContains(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}_startAutoPanLoop(){if(!this._core||this._autoPanRafId!=null)return;this._autoPanActive=true;let e=this._core.nodes.world,t=this._core.stage,n=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let o=t.getPointerPosition();if(o){let s=t.width(),r=t.height(),l=this._autoPanEdgePx,h=0,c=0,d=Math.max(0,l-o.x),u=Math.max(0,o.x-(s-l)),p=Math.max(0,l-o.y),f=Math.max(0,o.y-(r-l)),g=m=>Math.min(1,m/l);if(h=this._autoPanMaxSpeedPx*(g(u)-g(d)),c=this._autoPanMaxSpeedPx*(g(f)-g(p)),h!==0||c!==0){e.x(e.x()-h),e.y(e.y()-c);let m=e.position();if(this._core.eventBus.emit("camera:pan",{dx:-h,dy:-c,position:{x:m.x,y:m.y}}),this._start&&(this._start.x-=h,this._start.y-=c),this._rect&&this._start){let _=t.getPointerPosition();if(_){let b=Math.min(this._start.x,_.x),v=Math.min(this._start.y,_.y),w=Math.abs(_.x-this._start.x),x=Math.abs(_.y-this._start.y);this._rect.position({x:b,y:v}),this._rect.size({width:w,height:x});}}this._layer?.batchDraw(),this._core.nodes.layer.batchDraw();}}this._autoPanRafId=globalThis.requestAnimationFrame(n);};this._autoPanRafId=globalThis.requestAnimationFrame(n);}_stopAutoPanLoop(){this._autoPanActive=false,this._autoPanRafId!=null&&(globalThis.cancelAnimationFrame(this._autoPanRafId),this._autoPanRafId=null);}_finalizeArea(){if(!this._core||!this._rect||!this._start)return;this._selecting=false;let e=this._rect.getClientRect({skipStroke:true});this._rect.visible(false),this._layer?.batchDraw();let t=[];if(this._lastPickedBaseNodes.length>0)t=[...this._lastPickedBaseNodes];else {let o=this._core.nodes.list(),s=[];for(let h of o){let c=h.getKonvaNode();if(c.getLayer()!==this._core.nodes.layer)continue;if(h instanceof M){let f=h.getRect().getClientRect({skipShadow:true,skipStroke:true});if(h.getContentGroup().getChildren().length>0)this._rectContains(e,f)&&s.push(c);else {let _=c.getClientRect({skipShadow:true,skipStroke:false});this._rectsIntersect(e,_)&&s.push(c);}continue}let u=c.getClientRect({skipShadow:true,skipStroke:false});this._rectsIntersect(e,u)&&s.push(c);}let r=this._core.nodes.list(),l=new Set;for(let h of s){let c=r.find(u=>u.getKonvaNode()===h)??null,d=this._findOwningGroupBaseNode(h);d?l.add(d):c&&!(c instanceof ge)&&l.add(c);}t=Array.from(l);}let n=this._getSelectionPlugin();if(n)if(t.length===1){let o=t[0];o&&n.selectSingleFromArea(o);}else t.length>1?(n.getMultiGroupController().ensure(t),this._core.stage.batchDraw()):n.getMultiGroupController().destroy();this._lastPickedBaseNodes=[];}_clearSelection(){this._isPermanentGroupSelected()&&(this._transformer&&this._transformer.destroy(),this._transformer=null,this._core?.stage.batchDraw());let t=this._getSelectionPlugin()?.getMultiGroupController();t&&t.destroy();}_getSelectionPlugin(){return this._core?this._core.plugins.list().find(t=>t instanceof we)??null:null}_rectsIntersect(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}_findOwningGroupBaseNode(e){if(!this._core)return null;let n=this._core.nodes.list().filter(r=>r instanceof ge),o=e,s=null;for(;o;){let r=n.find(l=>l.getKonvaNode()===o)??null;r&&(s=r),o=o.getParent();}return s}_isAncestor(e,t){let n=t;for(;n;){if(n===e)return true;n=n.getParent();}return false}_isPermanentGroupSelected(){if(!this._transformer)return false;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return !t||!this._core?false:this._core.nodes.list().some(n=>n instanceof ge&&n.getKonvaNode()===t)}_currentGroupNode(){if(!this._transformer)return null;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return t&&t instanceof G.Group?t:null}};var Ct=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_attached",false);a(this,"_panning",false);a(this,"_last",null);a(this,"_prevCursor",null);a(this,"_prevStageDraggable");a(this,"_onWheelDOM",e=>{if(!this._core||e.ctrlKey)return;e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation?.();let{deltaX:n,deltaY:o,shiftKey:s}=e;if(this._isTouchpadWheel(e)){if(s){let l=-(Math.abs(n)>=Math.abs(o)?n:o);this._pan(l,0);}else {let r=-n,l=-o;this._pan(r,l);}return}if(s){let r=o<0?-Math.abs(o):Math.abs(o);this._pan(r,0);}else {let r=-o;this._pan(0,r);}});a(this,"_onMouseDownKonva",e=>{if(!this._core||!this._options.enablePanning)return;let t=e.evt.button;if(!(this._options.allowMiddleButtonPan&&t===1||this._options.allowRightButtonPan&&t===2))return;this._panning=true;let o=this._core.stage.getPointerPosition();o&&(this._last={x:o.x,y:o.y});let s=this._core.stage.container();this._prevCursor=s.style.cursor||null,s.style.cursor="grabbing",e.evt.preventDefault();});a(this,"_onMouseMoveKonva",e=>{if(!this._core||!this._options.enablePanning||!this._panning||!this._last)return;let t=this._core.stage.getPointerPosition();if(!t)return;let n=t.x-this._last.x,o=t.y-this._last.y;this._pan(n,o),this._last={x:t.x,y:t.y};});a(this,"_onMouseUpKonva",e=>{if(!this._options.enablePanning||(this._panning=false,this._last=null,!this._core))return;let t=this._core.stage.container();this._prevCursor!==null?(t.style.cursor=this._prevCursor,this._prevCursor=null):t.style.removeProperty("cursor");});a(this,"_onMouseLeaveKonva",e=>{if(!this._options.enablePanning||(this._panning=false,this._last=null,!this._core))return;let t=this._core.stage.container();this._prevCursor!==null?(t.style.cursor=this._prevCursor,this._prevCursor=null):t.style.removeProperty("cursor");});a(this,"_onContextMenuDOM",e=>{this._options.disableContextMenu&&e.preventDefault();});a(this,"_handleKeyDown",e=>{if(this._options.ignoreEditableTargets&&this._isEditableTarget(e.target)||!this._core)return;let t=e.code==="Equal"||e.code==="NumpadAdd",n=e.code==="Minus"||e.code==="NumpadSubtract";if(t||n){e.preventDefault(),t?this._core.camera.zoomIn():this._core.camera.zoomOut();return}if(this._options.enableArrows){let o=this._core.camera.panStep;switch(e.key){case "ArrowLeft":e.preventDefault(),this._pan(o,0);return;case "ArrowRight":e.preventDefault(),this._pan(-o,0);return;case "ArrowUp":e.preventDefault(),this._pan(0,o);return;case "ArrowDown":e.preventDefault(),this._pan(0,-o);return}}});let{target:t=globalThis,zoomStep:n=1.1,panStep:o=40,ignoreEditableTargets:s=true,enableArrows:r=true,enablePanning:l=true,allowMiddleButtonPan:h=true,allowRightButtonPan:c=true,disableContextMenu:d=true}=e;this._options={target:t,zoomStep:n,panStep:o,ignoreEditableTargets:s,enableArrows:r,enablePanning:l,allowMiddleButtonPan:h,allowRightButtonPan:c,disableContextMenu:d};}setOptions(e){let t=this._options.disableContextMenu;if(this._options={...this._options,...e},this._attached&&this._core&&(typeof e.zoomStep=="number"&&this._core.camera.setZoomStep(this._options.zoomStep),typeof e.panStep=="number"&&this._core.camera.setPanStep(this._options.panStep),typeof e.disableContextMenu=="boolean"&&e.disableContextMenu!==t)){let n=this._core.stage.container();this._options.disableContextMenu?n.addEventListener("contextmenu",this._onContextMenuDOM):n.removeEventListener("contextmenu",this._onContextMenuDOM);}}onAttach(e){this._core=e;let t=this._core.stage;typeof this._options.zoomStep=="number"&&this._core.camera.setZoomStep(this._options.zoomStep),typeof this._options.panStep=="number"&&this._core.camera.setPanStep(this._options.panStep),this._prevStageDraggable=t.draggable(),t.draggable(false),this._options.target.addEventListener("keydown",this._handleKeyDown),this._options.enablePanning&&(t.on("mousedown.cameraHotkeys",this._onMouseDownKonva),t.on("mousemove.cameraHotkeys",this._onMouseMoveKonva),t.on("mouseup.cameraHotkeys",this._onMouseUpKonva),t.on("mouseleave.cameraHotkeys",this._onMouseLeaveKonva),this._options.disableContextMenu&&t.container().addEventListener("contextmenu",this._onContextMenuDOM)),t.container().addEventListener("wheel",this._onWheelDOM,{passive:false,capture:true}),t.on("wheel.cameraHotkeysGuard",o=>{o.evt.ctrlKey||(o.evt.preventDefault(),o.cancelBubble=true);}),this._attached=true;}onDetach(e){if(!this._attached)return;this._options.target.removeEventListener("keydown",this._handleKeyDown);let n=e.stage;n.off(".cameraHotkeys"),n.off(".cameraHotkeysGuard"),n.container().removeEventListener("wheel",this._onWheelDOM),this._options.enablePanning&&n.container().removeEventListener("contextmenu",this._onContextMenuDOM),this._prevStageDraggable!==void 0&&n.draggable(this._prevStageDraggable),this._attached=false,this._last=null,this._prevCursor=null;}_isEditableTarget(e){let t=e;if(!t)return false;let n=t.tagName;return t.isContentEditable||n==="INPUT"||n==="TEXTAREA"||n==="SELECT"}_isTouchpadWheel(e){return e.deltaMode===0&&(Math.abs(e.deltaX)>0||Math.abs(e.deltaY)<50)}_pan(e,t){if(!this._core)return;let n=this._core.nodes.world,o=n.x()+e,s=n.y()+t;n.position({x:o,y:s}),this._core.eventBus.emit("camera:pan",{dx:e,dy:t,position:{x:o,y:s}}),this._core.stage.batchDraw();}};var he=class{attach(i){this.onAttach(i);}detach(i){this.onDetach(i);}};var Tt=class extends oe{constructor(){super(...arguments);a(this,"_container",null);a(this,"_onDragOver",null);a(this,"_onDrop",null);}onAttach(e,t){let n=t.stage.container();this._container=n,this._onDragOver=o=>{o.preventDefault();},this._onDrop=o=>{e.handleDrop(o);},n.addEventListener("dragover",this._onDragOver),n.addEventListener("drop",this._onDrop);}onDetach(e,t){this._container&&this._onDragOver&&this._container.removeEventListener("dragover",this._onDragOver),this._container&&this._onDrop&&this._container.removeEventListener("drop",this._onDrop),this._container=null,this._onDragOver=null,this._onDrop=null;}},pt=class extends he{constructor(e){super();a(this,"_objectUrl");a(this,"_revoked",false);this._objectUrl=e;}onAttach(e){}onDetach(){this._revoked||(URL.revokeObjectURL(this._objectUrl),this._revoked=true);}},Et=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_dragDropAddon",null);a(this,"_onPaste",e=>{this._handlePaste(e);});let{target:t=globalThis,ignoreEditableTargets:n=true}=e;this._options={target:t,ignoreEditableTargets:n,maxImageSize:e.maxImageSize??Number.POSITIVE_INFINITY,enableDragDrop:e.enableDragDrop??true},this._options.enableDragDrop&&(this._dragDropAddon=new Tt,this.addons.add(this._dragDropAddon));}onAttach(e){this._core=e,this._options.target.addEventListener("paste",this._onPaste);}onDetach(e){this._options.target.removeEventListener("paste",this._onPaste),this._core=void 0;}async _handlePaste(e){if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let t=e.clipboardData;if(!t)return;let n=this._getPastePosition();await this._handleDataTransfer(t,n,e);}async handleDrop(e){if(!this._core)return;let t=e.dataTransfer;if(!t)return;e.preventDefault(),e.stopImmediatePropagation(),this._core.stage.setPointersPositions(e);let n=this._core.stage.getPointerPosition();if(!n)return;let r=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(n);await this._handleDataTransfer(t,{x:r.x,y:r.y},e);}async _handleDataTransfer(e,t,n){if(!this._core)return;let o=Array.from(e.items);for(let d=o.length-1;d>=0;d--){let u=o[d];if(u){if(u.kind==="file"){let p=u.getAsFile();if(p?.type==="image/svg+xml"||p?.name.toLowerCase().endsWith(".svg")){n?.preventDefault(),await this._pasteSvgFile(p,t);return}if(p&&(p.type.startsWith("video/")||this._looksLikeVideoFile(p))){n?.preventDefault(),await this._pasteVideoFile(p,t);return}if(p&&(p.type.startsWith("image/")||p.type==="")){n?.preventDefault(),await this._pasteImageFile(p,t);return}}if(u.kind==="string"&&(u.type==="text/plain"||u.type==="text/html")){let p=await this._getAsString(u),f=this._extractSvgMarkup(p);if(f){n?.preventDefault(),this._pasteSvgText(f,t);return}let g=u.type==="text/html"?this._htmlToText(p):p;if(g.trim().length>0){n?.preventDefault(),this._core.nodes.addText({x:t.x,y:t.y,text:g});return}}}}let s=Array.from(e.files??[]);for(let d=s.length-1;d>=0;d--){let u=s[d];if(u){if(u.type==="image/svg+xml"||u.name.toLowerCase().endsWith(".svg")){n?.preventDefault(),await this._pasteSvgFile(u,t);return}if(u.type.startsWith("video/")||this._looksLikeVideoFile(u)){n?.preventDefault(),await this._pasteVideoFile(u,t);return}if(u.type.startsWith("image/")||u.type===""){n?.preventDefault(),await this._pasteImageFile(u,t);return}}}let r=e.getData("text/plain")||"",l=e.getData("text/html")||"",h=this._extractSvgMarkup(l)??this._extractSvgMarkup(r);if(h){n?.preventDefault(),this._pasteSvgText(h,t);return}let c=this._htmlToText(l||r);if(c.trim().length>0){n?.preventDefault(),this._core.nodes.addText({x:t.x,y:t.y,text:c});return}}_pasteSvgText(e,t){if(!this._core)return;let n=this._svgTextToSrc(e),o=this._extractSvgSize(e),s=this._fitIntoMaxSize(o,this._options.maxImageSize);this._core.nodes.addSvg({x:t.x,y:t.y,src:n,width:s.width,height:s.height});}async _pasteSvgFile(e,t){let n=await this._readFileAsText(e);this._pasteSvgText(n,t);}async _pasteImageFile(e,t){if(!this._core)return;let n=URL.createObjectURL(e);try{let o=await this._loadImageSize(n),s=this._fitIntoMaxSize(o,this._options.maxImageSize);this._core.nodes.addImage({x:t.x,y:t.y,src:n,width:s.width,height:s.height}).addons.add(new pt(n));}catch(o){throw URL.revokeObjectURL(n),o}}async _pasteVideoFile(e,t){if(!this._core)return;let n=URL.createObjectURL(e);try{let o=this._core.nodes.addVideo({x:t.x,y:t.y,width:320,height:240,autoplay:!0,loop:!0,muted:!1,volume:1});await o.setSrc(n,{autoplay:!0,loop:!0,muted:!1,volume:1});let s=o.getVideoElement(),r=s?{width:s.videoWidth||0,height:s.videoHeight||0}:{width:0,height:0},l=this._fitIntoMaxSize(r,this._options.maxImageSize);o.setSize({width:l.width,height:l.height}),o.addons.add(new pt(n));}catch(o){throw URL.revokeObjectURL(n),o}}_fitIntoMaxSize(e,t){if(!isFinite(e.width)||!isFinite(e.height)||e.width<=0||e.height<=0)return {width:150,height:150};if(!isFinite(t)||t<=0)return e;let n=Math.max(e.width,e.height);if(n<=t)return e;let o=t/n;return {width:Math.max(1,Math.round(e.width*o)),height:Math.max(1,Math.round(e.height*o))}}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_getPastePosition(){if(!this._core)return {x:0,y:0};let t=this._core.stage.getPointerPosition();if(t&&this._isPointerOnScreen(t)){let s=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(t);return {x:s.x,y:s.y}}return this._getScreenCenter()}_isPointerOnScreen(e){if(!this._core)return false;let t=this._core.stage,n=t.width(),o=t.height();return e.x>=0&&e.x<=n&&e.y>=0&&e.y<=o}_getScreenCenter(){if(!this._core)return {x:0,y:0};let e=this._core.stage,t=this._core.nodes.world,n=e.width()/2,o=e.height()/2,r=t.getAbsoluteTransform().copy().invert().point({x:n,y:o});return {x:r.x,y:r.y}}_getAsString(e){return new Promise(t=>{e.getAsString(n=>{t(n);});})}_looksLikeVideoFile(e){let t=typeof e.name=="string"?e.name.toLowerCase():"";return t?t.endsWith(".mp4")||t.endsWith(".webm")||t.endsWith(".mov")||t.endsWith(".m4v")||t.endsWith(".mkv")||t.endsWith(".avi"):false}_htmlToText(e){let t=globalThis.DOMParser??null;return t?new t().parseFromString(e,"text/html").body.textContent||"":e}_readFileAsText(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;if(typeof s=="string"){t(s);return}n(new Error("Failed to read clipboard SVG"));},o.onerror=()=>{n(new Error("Failed to read clipboard SVG"));},o.readAsText(e);})}_extractSvgMarkup(e){let t=e.trim(),n=t.toLowerCase(),o=n.indexOf("<svg");if(o===-1)return null;let s=n.lastIndexOf("</svg>");return s===-1?null:t.slice(o,s+6)}_svgTextToSrc(e){return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`}_parseSvgNumber(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}_extractSvgSize(e){let t=/\bwidth\s*=\s*["']([^"']+)["']/i,n=/\bheight\s*=\s*["']([^"']+)["']/i,o=t.exec(e),s=n.exec(e),r=o?.[1]?this._parseSvgNumber(o[1]):0,l=s?.[1]?this._parseSvgNumber(s[1]):0;if(r>0&&l>0)return {width:r,height:l};let c=/\bviewBox\s*=\s*["']([^"']+)["']/i.exec(e);if(c?.[1]){let d=c[1].trim().split(/[\s,]+/),u=d.length>=4?d[2]:void 0,p=d.length>=4?d[3]:void 0,f=u?this._parseSvgNumber(u):0,g=p?this._parseSvgNumber(p):0;if(f>0&&g>0)return {width:f,height:g}}return {width:150,height:150}}_loadImageSize(e){return new Promise((t,n)=>{let o=globalThis.Image??null;if(!o){n(new Error("Image constructor is not available in current environment"));return}let s=new o;s.onload=()=>{t({width:s.naturalWidth||s.width,height:s.naturalHeight||s.height});},s.onerror=()=>{n(new Error("Failed to load clipboard image"));},s.src=e;})}};var Pt=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_layer",null);a(this,"_shape",null);a(this,"_stepX");a(this,"_stepY");a(this,"_color");a(this,"_lineWidth");a(this,"_visible");a(this,"_minScaleToShow");a(this,"_enableSnap");a(this,"_dragMoveHandler",null);a(this,"_nodesAddHandler",null);a(this,"_nodesRemoveHandler",null);a(this,"_redrawScheduled",false);a(this,"_transformersCache",[]);a(this,"_cacheInvalidated",true);this._stepX=Math.max(1,e.stepX??1),this._stepY=Math.max(1,e.stepY??1),this._color=e.color??"#2b313a",this._lineWidth=e.lineWidth??1,this._visible=e.visible??true,this._minScaleToShow=e.minScaleToShow??8,this._enableSnap=e.enableSnap??true;}onAttach(e){this._core=e;let t=e.nodes.layer,n=(d,u)=>{if(!this._visible||!this._core)return;let p=this._core.stage,f=this._core.nodes.world,g=f.scaleX();if(this._minScaleToShow!=null&&g<this._minScaleToShow)return;let m=p.width(),_=p.height(),b=f.scaleX(),v=f.scaleY(),w=Math.max(1,this._stepX)*Math.max(1e-6,b),x=Math.max(1,this._stepY)*Math.max(1e-6,v),N=(f.x()%w+w)%w,k=(f.y()%x+x)%x;d.beginPath(),d.lineWidth=this._lineWidth,d.strokeStyle=this._color;for(let S=N;S<=m;S+=w)d.moveTo(S,0),d.lineTo(S,_);for(let S=k;S<=_;S+=x)d.moveTo(0,S),d.lineTo(m,S);d.stroke();},o=new G.Shape({listening:false,sceneFunc:n});t.add(o),this._layer=t,this._shape=o;let s=e.stage,r=e.nodes.world;s.on("resize.grid",()=>{this._scheduleRedraw();}),r.on("xChange.grid yChange.grid scaleXChange.grid scaleYChange.grid",()=>{this._scheduleRedraw();}),(()=>{this._cacheInvalidated&&(this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false);for(let d of this._transformersCache)d.moveToTop();this._shape?.moveToTop();for(let d of this._transformersCache)d.moveToTop();})(),this._dragMoveHandler=d=>{if(!this._core||!this._enableSnap)return;let u=this._core.stage,p=this._core.nodes.world,f=d.target;if(f===u||f instanceof G.Layer)return;let g=this._core.nodes.layer,m=f,_=false;for(;m;){if(m===g){_=true;break}m=m.getParent();}if(!_)return;let b=f;if(typeof b.draggable=="function"&&!b.draggable())return;let v=f.getAbsolutePosition(),w=p.scaleX()||1,x=p.scaleY()||1;if(this._minScaleToShow!=null?w>=this._minScaleToShow:false){let k=(v.x-p.x())/w,S=(v.y-p.y())/x,C=Math.max(1,this._stepX),T=Math.max(1,this._stepY),K=Math.round(k/C)*C,L=Math.round(S/T)*T,B=K*w+p.x(),P=L*x+p.y();(Math.abs(B-v.x)>.001||Math.abs(P-v.y)>.001)&&f.absolutePosition({x:B,y:P});}else {let k=(v.x-p.x())/w,S=(v.y-p.y())/x,C=Math.max(1,this._stepX),T=Math.max(1,this._stepY),K=Math.round(k/C)*C,L=Math.round(S/T)*T,B=K*w+p.x(),P=L*x+p.y();(Math.abs(B-v.x)>.001||Math.abs(P-v.y)>.001)&&f.absolutePosition({x:B,y:P});}},s.on("dragmove.grid",this._dragMoveHandler);let h=d=>{let u=d;if((typeof u.getClassName=="function"?u.getClassName():"")!=="Transformer")return;let f=d,g=(m,_)=>{let b=_;if(!this._enableSnap||!this._core||!(typeof u.nodes=="function"?u.nodes():[])[0])return b;let x=typeof u.getActiveAnchor=="function"?u.getActiveAnchor():"";if(x==="rotater")return b;let N=Math.max(1,this._stepX),k=Math.max(1,this._stepY),S=typeof x=="string"?x:"",C=this._core.nodes.world.getAbsoluteTransform(),T=C.copy();T.invert();let K=b.x,L=b.x+b.width,B=b.y,P=b.y+b.height,I=T.point({x:K,y:B}).x,X=T.point({x:L,y:B}).x,U=T.point({x:K,y:B}).y,J=T.point({x:K,y:P}).y,W=I,$=X,ie=U,ue=J,fe=(F,j)=>Math.round((F+1e-9)/j)*j;S.includes("left")&&(W=fe(I,N)),S.includes("right")&&($=fe(X,N)),S.includes("top")&&(ie=fe(U,k)),S.includes("bottom")&&(ue=fe(J,k)),$-W<N&&(S.includes("left")?W=$-N:$=W+N),ue-ie<k&&(S.includes("top")?ie=ue-k:ue=ie+k);let Q=C.point({x:W,y:ie}).x,Ne=C.point({x:W,y:ie}).y,ke=C.point({x:$,y:ie}).x,E=C.point({x:W,y:ue}).y,R=F=>Math.round(F*1e3)/1e3;return {x:R(Q),y:R(Ne),width:R(ke-Q),height:R(E-Ne),rotation:b.rotation}};globalThis.queueMicrotask(()=>{f.boundBoxFunc(g);});},c=d=>{h(d);let u=d,p=typeof u.getChildren=="function"?u.getChildren():[];for(let f of p)c(f);};c(e.nodes.layer),this._nodesAddHandler=d=>{let u=d.child??d.target;c(u);let p=u;if((typeof p.getClassName=="function"?p.getClassName():"")==="Transformer"){this._cacheInvalidated=true,u.moveToTop(),this._shape?.moveToTop(),this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false;for(let g of this._transformersCache)g.moveToTop();}},this._nodesRemoveHandler=d=>{let u=d.child??d.target,p=m=>{let _=m;(typeof _.getClassName=="function"?_.getClassName():"")==="Transformer"&&m.boundBoxFunc?.(void 0);let v=typeof _.getChildren=="function"?_.getChildren():[];for(let w of v)p(w);};p(u);let f=u;(typeof f.getClassName=="function"?f.getClassName():"")==="Transformer"&&(this._cacheInvalidated=true),this._shape?.moveToTop(),this._cacheInvalidated&&(this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false);for(let m of this._transformersCache)m.moveToTop();},e.nodes.layer.on("add.grid",this._nodesAddHandler),e.nodes.layer.on("remove.grid",this._nodesRemoveHandler),e.nodes.layer.on("cornerRadiusChange.grid",d=>{let u=d.target;if((typeof u.getClassName=="function"?u.getClassName():"")!=="Rect")return;let f=u.cornerRadius;if(typeof f!="function")return;let g=f.call(u),m=w=>{u.cornerRadius(w);},_=this._core?.stage,b=_?.scaleX()??1,v=this._minScaleToShow!=null?b>=this._minScaleToShow:false;if(Array.isArray(g)){let w=g.map(x=>{if(v){let N=_?.scaleX()??1,k=_?.scaleY()??1,S=x*(.5*(N+k));return Math.max(0,Math.round(S))/Math.max(1e-6,.5*(N+k))}else return Math.max(0,Math.round(x))});m(w);}else if(typeof g=="number")if(v){let w=_?.scaleX()??1,x=_?.scaleY()??1,N=g*(.5*(w+x)),k=Math.max(0,Math.round(N));m(k/Math.max(1e-6,.5*(w+x)));}else m(Math.max(0,Math.round(g)));});}_scheduleRedraw(){if(this._redrawScheduled)return;this._redrawScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._redrawScheduled=false,this._layer?.batchDraw();});}onDetach(e){e.stage.off(".grid"),e.nodes.layer.off(".grid"),this._shape&&this._shape.destroy(),this._shape=null,this._layer=null,this._dragMoveHandler=null,this._nodesAddHandler=null,this._nodesRemoveHandler=null,e.stage.batchDraw();}setVisible(e){this._visible=e,this._core&&this._core.stage.batchDraw();}get stepX(){return this._stepX}get stepY(){return this._stepY}get minScaleToShow(){return this._minScaleToShow}setStep(e,t){this._stepX=Math.max(1,e),this._stepY=Math.max(1,t),this._core&&this._core.stage.batchDraw();}setMinScaleToShow(e){this._minScaleToShow=e,this._core&&this._core.stage.batchDraw();}setSnap(e){this._enableSnap=e;}};var Kt=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_history");a(this,"_options");a(this,"_isUndoRedoInProgress",false);a(this,"_dragStartStateCache",new Map);a(this,"_isBatchMode",false);a(this,"_batchBuffer",[]);a(this,"_batchCommitTimer",null);a(this,"_onKeyDown",e=>{if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let t=e.ctrlKey||e.metaKey,n=e.shiftKey;if(t&&!n&&e.code==="KeyZ"){e.preventDefault(),this._performUndo();return}if(t&&n&&e.code==="KeyZ"){e.preventDefault(),this._performRedo();return}});a(this,"_onDragStart",e=>{if(this._isUndoRedoInProgress)return;let t=e.target;this._debug("dragstart raw target",{targetName:t.name(),targetClassName:t.getClassName(),targetId:t.id()});let n=t.name();if(typeof n=="string"&&n.includes("temp-multi-group")){this._isBatchMode=true,this._batchBuffer=[];let r=t.getChildren();for(let l of r){let h=this._findBaseNodeByKonva(l);if(h){let c=this._captureTransformState(h);this._dragStartStateCache.set(h.id,c),this._debug("dragstart (temp-multi child)",{nodeId:h.id});}}return}let o=this._findBaseNodeByKonva(t);if(o){let s=this._captureTransformState(o);this._dragStartStateCache.set(o.id,s),this._debug("dragstart",{nodeId:o.id,state:s});}else this._debug("dragstart - baseNode not found for target");});a(this,"_onDragEnd",e=>{});a(this,"_onTransformStart",e=>{if(this._isUndoRedoInProgress)return;let t=e.target;this._debug("transformstart raw target",{targetName:t.name(),targetClassName:t.getClassName(),targetId:t.id()});let n=t.name();if(typeof n=="string"&&n.includes("temp-multi-group")){this._isBatchMode=true,this._batchBuffer=[];let r=t.getChildren();for(let l of r){let h=this._findBaseNodeByKonva(l);if(h){let c=this._captureTransformState(h);this._dragStartStateCache.set(h.id,c),this._debug("transformstart (temp-multi child)",{nodeId:h.id});}}return}let o=this._findBaseNodeByKonva(t);if(o){let s=this._captureTransformState(o);this._dragStartStateCache.set(o.id,s),this._debug("transformstart",{nodeId:o.id,state:s});}else this._debug("transformstart - baseNode not found for target");});a(this,"_onTransformEnd",e=>{});a(this,"_onNodeCreated",e=>{if(this._isUndoRedoInProgress){this._debug("node:created skipped (undo/redo in progress)",e.id);return}let t=this._serializeNode(e),n={type:"create",nodeId:e.id,before:null,after:t,timestamp:Date.now()};this._history.push(n),this._dragStartStateCache.set(e.id,this._captureTransformState(e)),this._trimHistoryIfNeeded();});a(this,"_onNodeRemoved",e=>{if(this._isUndoRedoInProgress)return;let t=this._serializeNode(e),n={type:"remove",nodeId:e.id,before:t,after:null,timestamp:Date.now()};this._isBatchMode?this._batchBuffer.push(n):(this._history.push(n),this._trimHistoryIfNeeded()),this._dragStartStateCache.delete(e.id);});a(this,"_onNodeTransformed",(e,t)=>{if(this._isUndoRedoInProgress){this._debug("node:transformed skipped (undo/redo in progress)",e.id);return}let n=this._dragStartStateCache.get(e.id),o=this._buildAfterState(e,t);if(!n){this._debug("transform - no before state, saving current",e.id),this._dragStartStateCache.set(e.id,o);return}if(this._statesEqual(n,o)){this._debug("transform skipped - no changes",e.id);return}let s={type:"transform",nodeId:e.id,before:n,after:o,timestamp:Date.now()};this._debug("transform recorded",{nodeId:e.id,before:n,after:o,batchMode:this._isBatchMode}),this._isBatchMode?(this._batchBuffer.push(s),this._scheduleBatchCommit()):(this._history.push(s),this._trimHistoryIfNeeded()),this._dragStartStateCache.set(e.id,o);});a(this,"_onZIndexChanged",(e,t,n)=>{if(this._isUndoRedoInProgress)return;let o={type:"zIndex",nodeId:e.id,before:{zIndex:t},after:{zIndex:n},timestamp:Date.now()};this._history.push(o),this._trimHistoryIfNeeded();});a(this,"_onGroupCreated",(e,t)=>{if(this._isUndoRedoInProgress)return;let n=t.map(r=>this._serializeNode(r)),o=t.map(r=>r.id),s={type:"group",nodeId:e.id,before:{childIds:o,childStates:n},after:this._serializeNode(e),timestamp:Date.now()};this._history.push(s),this._trimHistoryIfNeeded();});a(this,"_onGroupUngrouped",(e,t)=>{if(this._isUndoRedoInProgress)return;let n=this._serializeNode(e),o=t.map(r=>this._serializeNode(r)),s={type:"ungroup",nodeId:e.id,before:n,after:{childStates:o},timestamp:Date.now()};this._history.push(s),this._trimHistoryIfNeeded();});this._history=new Ie;let{target:t=globalThis,ignoreEditableTargets:n=true,maxHistoryLength:o=100}=e;this._options={target:t,ignoreEditableTargets:n,maxHistoryLength:o};}getHistoryManager(){return this._history}startBatch(){this._batchCommitTimer!==null&&(globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=null),this._isBatchMode=true,this._batchBuffer=[],this._debug("batch started");}commitBatch(){this._batchCommitTimer!==null&&(globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=null),this._finishBatch();}isBatchMode(){return this._isBatchMode}onAttach(e){this._core=e,this._options.target.addEventListener("keydown",this._onKeyDown),e.eventBus.on("node:created",this._onNodeCreated),e.eventBus.on("node:removed",this._onNodeRemoved),e.eventBus.on("node:transformed",this._onNodeTransformed),e.eventBus.on("node:zIndexChanged",this._onZIndexChanged),e.eventBus.on("group:created",this._onGroupCreated),e.eventBus.on("group:ungrouped",this._onGroupUngrouped);let t=e.nodes.world,n=e.nodes.layer;t.on("dragstart.history",this._onDragStart),t.on("dragend.history",this._onDragEnd),n.on("transformstart.history",this._onTransformStart),n.on("transformend.history",this._onTransformEnd),this._debug("attached");}onDetach(e){this._options.target.removeEventListener("keydown",this._onKeyDown),e.eventBus.off("node:created",this._onNodeCreated),e.eventBus.off("node:removed",this._onNodeRemoved),e.eventBus.off("node:transformed",this._onNodeTransformed),e.eventBus.off("node:zIndexChanged",this._onZIndexChanged),e.eventBus.off("group:created",this._onGroupCreated),e.eventBus.off("group:ungrouped",this._onGroupUngrouped),e.nodes.world.off(".history"),e.nodes.layer.off(".history"),this._core=void 0,this._dragStartStateCache.clear(),this._debug("detached");}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_finishBatch(){if(!this._isBatchMode||this._batchBuffer.length===0){this._isBatchMode=false,this._batchBuffer=[];return}let e={type:"batch",nodeId:"",before:null,after:null,timestamp:Date.now(),children:[...this._batchBuffer]};this._debug("batch recorded",{childCount:this._batchBuffer.length}),this._history.push(e),this._trimHistoryIfNeeded(),this._isBatchMode=false,this._batchBuffer=[];}_performUndo(){if(!this._core)return;let e=this._history.undo();if(!e){this._debug("undo","nothing to undo");return}this._isUndoRedoInProgress=true;try{this._applyActionState(e,"before"),this._debug("undo applied",e);}finally{this._isUndoRedoInProgress=false;}this._core.stage.batchDraw();}_performRedo(){if(!this._core)return;let e=this._history.redo();if(!e){this._debug("redo","nothing to redo");return}this._isUndoRedoInProgress=true;try{this._applyActionState(e,"after"),this._debug("redo applied",e);}finally{this._isUndoRedoInProgress=false;}this._core.stage.batchDraw();}_applyActionState(e,t){if(!this._core)return;let n=t==="before"?e.before:e.after;switch(e.type){case "create":if(t==="before"){let o=this._core.nodes.findById(e.nodeId);o&&this._core.nodes.remove(o);}else n&&this._recreateNode(n);break;case "remove":if(t==="before")n&&this._recreateNode(n);else {let o=this._core.nodes.findById(e.nodeId);o&&this._core.nodes.remove(o);}break;case "transform":if(n&&typeof n=="object"){let o=this._core.nodes.findById(e.nodeId);this._debug("transform apply",{nodeId:e.nodeId,nodeFound:!!o,state:n}),o&&this._applyTransformState(o,n);}break;case "zIndex":if(n&&typeof n=="object"&&"zIndex"in n){let o=this._core.nodes.findById(e.nodeId);o&&o.getKonvaNode().zIndex(n.zIndex);}break;case "group":this._applyGroupAction(e,t);break;case "ungroup":this._applyUngroupAction(e,t);break;case "batch":if(e.children){let o=t==="before"?[...e.children].reverse():e.children;for(let s of o)this._applyActionState(s,t);}break;default:this._debug("unknown action type",e.type);}}_applyTransformState(e,t){let n=e.getKonvaNode();this._debug("applyTransformState",{nodeId:e.id,current:{x:n.x(),y:n.y(),rotation:n.rotation(),scaleX:n.scaleX(),scaleY:n.scaleY()},target:t}),typeof t.x=="number"&&n.x(t.x),typeof t.y=="number"&&n.y(t.y),typeof t.width=="number"&&typeof n.width=="function"&&n.width(t.width),typeof t.height=="number"&&typeof n.height=="function"&&n.height(t.height),typeof t.rotation=="number"&&n.rotation(t.rotation),typeof t.scaleX=="number"&&n.scaleX(t.scaleX),typeof t.scaleY=="number"&&n.scaleY(t.scaleY);let o=n;typeof t.cornerRadius=="number"&&typeof o.cornerRadius=="function"&&o.cornerRadius(t.cornerRadius),this._dragStartStateCache.set(e.id,this._captureTransformState(e));}_applyGroupAction(e,t){if(this._core){if(t==="before"){let n=this._core.nodes.findById(e.nodeId);if(n&&e.before){let o=e.before;this._core.nodes.remove(n);for(let s of o.childStates)this._recreateNode(s);}}else if(e.after){let n=e.after;this._recreateNode(n);}}}_applyUngroupAction(e,t){if(this._core)if(t==="before"){if(e.before){let n=e.before;this._recreateNode(n);}}else {let n=this._core.nodes.findById(e.nodeId);if(n&&e.after){let o=e.after;this._core.nodes.remove(n);for(let s of o.childStates)this._recreateNode(s);}}}_recreateNode(e){if(!this._core)return null;let{nodeType:t,attrs:n}=e,{id:o,zIndex:s,...r}=n;try{let l=null;switch(t){case "shape":l=this._core.nodes.addShape(r);break;case "text":l=this._core.nodes.addText(r);break;case "circle":l=this._core.nodes.addCircle(r);break;case "ellipse":l=this._core.nodes.addEllipse(r);break;case "arc":l=this._core.nodes.addArc(r);break;case "star":l=this._core.nodes.addStar(r);break;case "arrow":l=this._core.nodes.addArrow(r);break;case "ring":l=this._core.nodes.addRing(r);break;case "regularPolygon":case "regularpolygon":l=this._core.nodes.addRegularPolygon(r);break;case "image":l=this._core.nodes.addImage(r);break;case "svg":l=this._core.nodes.addSvg(r);break;case "group":{if(l=this._core.nodes.addGroup(r),e.children&&e.children.length>0){let h=l.getKonvaNode();for(let c of e.children){let d=this._recreateNode(c);d&&d.getKonvaNode().moveTo(h);}}break}default:return this._debug("recreateNode",`unknown type: ${t}`),null}if(e.parentId){let h=this._core.nodes.findById(e.parentId);if(h){let c=h.getKonvaNode();l.getKonvaNode().moveTo(c),this._debug("recreateNode - moved to parent",{nodeId:l.id,parentId:e.parentId});}}return this._debug("recreateNode",{nodeType:t,nodeId:l.id,parentId:e.parentId}),l}catch(l){return this._debug("recreateNode error",l),null}}_scheduleBatchCommit(){this._batchCommitTimer!==null&&globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=globalThis.setTimeout(()=>{this._batchCommitTimer=null,this._finishBatch();},50);}_serializeNode(e){let t=e.getKonvaNode(),n=t.getAttrs(),o=this._getNodeType(t),s={nodeType:o,nodeId:e.id,attrs:{...n}},r=t.getParent();if(r&&this._core){let l=this._findBaseNodeByKonva(r);if(l&&l.id!==e.id){let h=this._core.nodes.world;r!==h&&(s.parentId=l.id);}}if(o==="group"){let h=t.getChildren();s.children=[];for(let c of h){let d=this._findBaseNodeByKonva(c);d&&d.id!==e.id&&s.children.push(this._serializeNode(d));}}return s}_captureTransformState(e){let t=e.getKonvaNode(),n=t.getAbsoluteTransform().decompose(),o={absX:n.x,absY:n.y,absRotation:n.rotation,absScaleX:n.scaleX,absScaleY:n.scaleY,x:t.x(),y:t.y(),rotation:t.rotation(),scaleX:t.scaleX(),scaleY:t.scaleY()};typeof t.width=="function"&&(o.width=t.width()),typeof t.height=="function"&&(o.height=t.height());let s=t;return typeof s.cornerRadius=="function"&&(o.cornerRadius=s.cornerRadius()),o}_buildAfterState(e,t){let n=e.getKonvaNode(),o=t.x??n.x(),s=t.y??n.y(),r=t.rotation??n.rotation(),l=t.scaleX??n.scaleX(),h=t.scaleY??n.scaleY(),c={absX:o,absY:s,absRotation:r,absScaleX:l,absScaleY:h,x:o,y:s,rotation:r,scaleX:l,scaleY:h};typeof n.width=="function"&&(c.width=t.width??n.width()),typeof n.height=="function"&&(c.height=t.height??n.height());let d=n;return typeof d.cornerRadius=="function"&&(c.cornerRadius=d.cornerRadius()),c}_getNodeType(e){let t=e.getClassName();return t==="Image"?e.getAttrs().flowscapeNodeType==="svg"?"svg":"image":{Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Group:"group",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon"}[t]??t.toLowerCase()}_findBaseNodeByKonva(e){if(!this._core)return null;for(let n of this._core.nodes.list())if(n.getKonvaNode()===e)return n;let t=e.getParent();for(;t;){for(let n of this._core.nodes.list())if(n.getKonvaNode()===t)return n;t=t.getParent();}return null}_statesEqual(e,t){let o=["absX","absY","absRotation","absScaleX","absScaleY"];for(let r of o){let l=e[r],h=t[r];if(typeof l=="number"&&typeof h=="number"){if(Math.abs(l-h)>.001)return false}else if(l!==h)return false}let s=["width","height","cornerRadius"];for(let r of s)if(e[r]!==t[r])return false;return true}_trimHistoryIfNeeded(){if(!(this._options.maxHistoryLength<=0))for(;this._history.length>this._options.maxHistoryLength;){this._history.pop(0);break}}_debug(e,t){}};var Mt=class extends O{constructor(e){super();a(this,"_core");a(this,"_layer");a(this,"_image");a(this,"_src");a(this,"_width");a(this,"_height");a(this,"_opacity");this._src=e.src,this._width=e.width,this._height=e.height,this._opacity=e.opacity??1;}onAttach(e){this._core=e,this._layer=new G.Layer({name:"logo-layer",listening:false}),this._core.stage.add(this._layer),this._image=new G.Image({image:void 0,width:this._width,height:this._height,name:"logo-background",listening:false,opacity:this._opacity}),this._layer.add(this._image),this.setSource(this._src);let t=this._core.stage;t.on("resize.logo",()=>{this._layout();}),t.on("xChange.logo yChange.logo scaleXChange.logo scaleYChange.logo",()=>{this._layout();}),this._layout(),this._core.stage.batchDraw();}onDetach(e){e.stage.off(".logo"),this._image&&this._image.destroy(),this._layer&&this._layer.destroy();}setOpacity(e){this._opacity=e,this._image&&this._core&&(this._image.opacity(e),this._core.stage.batchDraw());}setSize({width:e,height:t}){this._width=e,this._height=t,this._layout(),this._core&&this._core.stage.batchDraw();}setSource(e){this._src=e,this._loadImageFromString(e);}_setImage(e){this._image&&(this._image.image(e),this._layout(),this._core&&this._core.stage.batchDraw());}_loadImageFromString(e){G.Image.fromURL(e,t=>{let n=t.image();n&&this._setImage(n);});}_layout(){if(!this._core||!this._image)return;let e=this._core.stage,t=e.width(),n=e.height(),o=e.scaleX(),s=e.position(),r={x:Math.floor(t/2),y:Math.floor(n/2)};this._image.scale({x:1/o,y:1/o});let l=this._width,h=this._height;this._image.size({width:l,height:h}),this._image.offset({x:l/2,y:h/2});let c=(r.x-s.x)/o,d=(r.y-s.y)/o;this._image.position({x:c,y:d}),this._image.opacity(this._opacity),this._layer&&this._layer.moveToBottom();}};var ft="flowscape:nodes:",Bt=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_clipboard",null);a(this,"_selectionPlugin");a(this,"_onPaste",e=>{if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let n=e.clipboardData?.getData("text/plain")??"";if(!n.startsWith(ft))return;let o=n.slice(ft.length),s=null;try{s=JSON.parse(o);}catch{s=null;}if(!(!s||!Array.isArray(s.nodes)||s.nodes.length===0)&&s.nodes.length>0){e.preventDefault(),e.stopImmediatePropagation(),this._clipboard=s,this._handlePaste();return}});a(this,"_onKeyDown",e=>{if(!this._core)return;if(!this._selectionPlugin){let o=this._core.plugins.list().find(s=>s instanceof we);o&&(this._selectionPlugin=o);}if(!this._selectionPlugin||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let t=e.ctrlKey||e.metaKey,n=e.shiftKey;if(!t&&!n&&e.code==="Enter"){let o=this._getSelectedNodes();if(o.length===1&&o[0]instanceof Te){e.preventDefault(),o[0].startEdit();return}}if(t&&e.code==="KeyC"){e.preventDefault(),this._handleCopy();return}if(t&&e.code==="KeyX"){e.preventDefault(),this._handleCut();return}if(!(t&&e.code==="KeyV")){if(e.code==="Delete"||e.code==="Backspace"){e.preventDefault(),this._handleDelete();return}if(t&&n&&e.code==="BracketRight"){e.preventDefault(),this._handleMoveToTop();return}if(t&&n&&e.code==="BracketLeft"){e.preventDefault(),this._handleMoveToBottom();return}if(t&&(e.code==="BracketRight"||n&&e.code==="Equal")){e.preventDefault(),this._handleMoveUp();return}if(t&&(e.code==="BracketLeft"||n&&e.code==="Minus")){e.preventDefault(),this._handleMoveDown();return}}});let{target:t=globalThis,ignoreEditableTargets:n=true}=e;this._options={target:t,ignoreEditableTargets:n};}onAttach(e){this._core=e,this._options.target.addEventListener("keydown",this._onKeyDown),this._options.target.addEventListener("paste",this._onPaste);}onDetach(e){this._options.target.removeEventListener("keydown",this._onKeyDown),this._options.target.removeEventListener("paste",this._onPaste),this._core=void 0,this._selectionPlugin=void 0,this._clipboard=null;}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_handleCopy(){let e=this._getSelectedNodes();if(e.length===0)return;let t=e.map(o=>this._serializeNode(o)),n=this._computeSelectionWorldCenter(e);this._clipboard={nodes:t,center:n};try{globalThis.navigator.clipboard.writeText(`${ft}${JSON.stringify(this._clipboard)}`);}catch{}this._core&&this._core.eventBus.emit("clipboard:copy",e);}_handleCut(){let e=this._getSelectedNodes();if(e.length===0)return;let t=e.map(o=>this._serializeNode(o)),n=this._computeSelectionWorldCenter(e);this._clipboard={nodes:t,center:n};try{globalThis.navigator.clipboard.writeText(`${ft}${JSON.stringify(this._clipboard)}`);}catch{}this._deleteNodes(e),this._core&&this._core.eventBus.emit("clipboard:cut",e);}_handlePaste(){if(!this._core||!this._clipboard||this._clipboard.nodes.length===0)return;let e=this._getPastePosition(),t=this._getClipboardCenter(),n=[];for(let o of this._clipboard.nodes){let s=o.position.x-t.x,r=o.position.y-t.y,l=this._deserializeNode(o,{x:e.x+s,y:e.y+r});l&&n.push(l);}n.length>0&&this._core.eventBus.emit("clipboard:paste",n),this._core.nodes.layer.batchDraw();}_handleDelete(){let e=this._getSelectedNodes();e.length!==0&&this._deleteNodes(e);}_getSelectedNodes(){if(!this._selectionPlugin)return [];let e=this._selectionPlugin._tempMultiGroup;if(e&&typeof e.getChildren=="function"&&this._core){let o=e.getChildren(),s=this._core.nodes.list(),r=new Set;for(let l of o){let h=s.find(c=>c.getKonvaNode()===l);h&&r.add(h);}if(r.size>0)return Array.from(r)}let t=this._selectionPlugin._tempMultiSet;if(t&&t.size>0)return Array.from(t);let n=this._selectionPlugin._selected;return n?[n]:[]}_deleteNodes(e){if(!this._core)return;if(this._selectionPlugin){let n=this._selectionPlugin;typeof n._destroyTempMulti=="function"&&n._destroyTempMulti(),typeof n._clearSelection=="function"&&n._clearSelection();}let t=this._core.plugins.get("HistoryPlugin");e.length>1&&t&&t.startBatch();for(let n of e)this._core.nodes.remove(n);e.length>1&&t&&t.commitBatch();}_serializeNode(e){let t=e.getKonvaNode(),n=t.getAttrs(),o=this._getNodeTypeFromKonva(t),s={x:0,y:0};if(this._core){let p=t.getAbsolutePosition(),g=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(p);s={x:g.x,y:g.y};}let{id:r,image:l,video:h,...c}=n,d={type:o,config:c,position:s};if(o==="group"){let p=t.getChildren(),f=[];for(let g of p){let m=this._serializeKonvaNode(g);m&&f.push(m);}f.length>0&&(d.children=f);}return d}_serializeKonvaNode(e){if(!this._core)return null;let t=e.getAttrs(),n=e.getClassName(),o=n.toLowerCase();if(o==="rect"&&(o="shape"),n==="Image"){let u=e.getAttrs().flowscapeNodeType;u==="svg"?o="svg":u==="gif"?o="gif":u==="video"?o="video":o="image";}let{id:s,image:r,video:l,...h}=t,c={type:o,config:h,position:{x:e.x(),y:e.y()}};if(e instanceof G.Group){let d=e.getChildren(),u=[];for(let p of d){let f=this._serializeKonvaNode(p);f&&u.push(f);}u.length>0&&(c.children=u);}return c}_getNodeTypeFromKonva(e){let t=e.getClassName();if(t==="Image"){let s=e.getAttrs().flowscapeNodeType;return s==="svg"?"svg":s==="gif"?"gif":s==="video"?"video":"image"}return {Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Group:"group",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon",Label:"label"}[t]??t.toLowerCase()}_deserializeNode(e,t){if(!this._core)return null;let{zIndex:n,...o}=e.config,s=o.placeholder,{placeholder:r,...l}=o,h={...l,...s?{placeholder:s}:{},x:t.x,y:t.y};try{let c=null;switch(e.type){case "shape":c=this._core.nodes.addShape(h);break;case "text":c=this._core.nodes.addText(h);break;case "circle":c=this._core.nodes.addCircle(h);break;case "ellipse":c=this._core.nodes.addEllipse(h);break;case "arc":c=this._core.nodes.addArc(h);break;case "star":c=this._core.nodes.addStar(h);break;case "arrow":c=this._core.nodes.addArrow(h);break;case "ring":c=this._core.nodes.addRing(h);break;case "regularPolygon":case "regularpolygon":c=this._core.nodes.addRegularPolygon(h);break;case "image":c=this._core.nodes.addImage(h);break;case "svg":c=this._core.nodes.addSvg(h);break;case "gif":c=this._core.nodes.addGif(h);break;case "video":c=this._core.nodes.addVideo(h);break;case "label":return globalThis.console.warn("LabelNode is not supported for copy/paste yet"),null;case "group":{c=this._core.nodes.addGroup(h);let u=c.getKonvaNode();if(e.config.scaleX!==void 0&&u.scaleX(e.config.scaleX),e.config.scaleY!==void 0&&u.scaleY(e.config.scaleY),e.config.rotation!==void 0&&u.rotation(e.config.rotation),e.config.skewX!==void 0&&u.skewX(e.config.skewX),e.config.skewY!==void 0&&u.skewY(e.config.skewY),e.config.offsetX!==void 0&&u.offsetX(e.config.offsetX),e.config.offsetY!==void 0&&u.offsetY(e.config.offsetY),e.children&&e.children.length>0)for(let p of e.children){let f=this._deserializeNode(p,{x:p.position.x,y:p.position.y});if(f){let g=f.getKonvaNode();typeof g.draggable=="function"&&g.draggable(!1),g.moveTo(u);}}break}default:return globalThis.console.warn(`Unknown node type: ${e.type}`),null}let d=c.getKonvaNode();return e.config.scaleX!==void 0&&d.scaleX(e.config.scaleX),e.config.scaleY!==void 0&&d.scaleY(e.config.scaleY),e.config.rotation!==void 0&&d.rotation(e.config.rotation),e.config.skewX!==void 0&&d.skewX(e.config.skewX),e.config.skewY!==void 0&&d.skewY(e.config.skewY),e.config.offsetX!==void 0&&d.offsetX(e.config.offsetX),e.config.offsetY!==void 0&&d.offsetY(e.config.offsetY),c}catch(c){return globalThis.console.error("Failed to deserialize node:",c),null}}_getPastePosition(){if(!this._core)return {x:0,y:0};let t=this._core.stage.getPointerPosition();if(t&&this._isPointerOnScreen(t)){let s=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(t);return {x:s.x,y:s.y}}return this._getScreenCenter()}_isPointerOnScreen(e){if(!this._core)return false;let t=this._core.stage,n=t.width(),o=t.height();return e.x>=0&&e.x<=n&&e.y>=0&&e.y<=o}_getScreenCenter(){if(!this._core)return {x:0,y:0};let e=this._core.stage,t=this._core.nodes.world,n=e.width()/2,o=e.height()/2,r=t.getAbsoluteTransform().copy().invert().point({x:n,y:o});return {x:r.x,y:r.y}}_getClipboardCenter(){if(!this._clipboard||this._clipboard.nodes.length===0)return {x:0,y:0};if(this._clipboard.center)return this._clipboard.center;let e=0,t=0;for(let n of this._clipboard.nodes)e+=n.position.x,t+=n.position.y;return {x:e/this._clipboard.nodes.length,y:t/this._clipboard.nodes.length}}_computeSelectionWorldCenter(e){if(!this._core||e.length===0)return {x:0,y:0};let t=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let u of e){let f=u.getKonvaNode().getClientRect({skipShadow:true,skipStroke:true});t=Math.min(t,f.x),n=Math.min(n,f.y),o=Math.max(o,f.x+f.width),s=Math.max(s,f.y+f.height);}if(!isFinite(t)||!isFinite(n)||!isFinite(o)||!isFinite(s))return {x:0,y:0};let r=(t+o)/2,l=(n+s)/2,d=this._core.nodes.world.getAbsoluteTransform().copy().invert().point({x:r,y:l});return {x:d.x,y:d.y}}_handleMoveUp(){let e=this._getSelectedNodes();if(e.length!==0){for(let t of e){let n=t.getKonvaNode();if(this._isNodeInsidePermanentGroup(n))continue;let o=n.zIndex();n.moveUp();let s=n.zIndex();this._syncGroupZIndex(n),this._core&&o!==s&&this._core.eventBus.emit("node:zIndexChanged",t,o,s);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}}_handleMoveDown(){let e=this._getSelectedNodes();if(e.length!==0){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n)continue;let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let s=o.zIndex();o.moveDown();let r=o.zIndex();this._syncGroupZIndex(o),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",n,s,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}}_handleMoveToTop(){let e=this._getSelectedNodes();if(e.length===0)return;let t=[...e].sort((n,o)=>{let s=n.getKonvaNode(),r=o.getKonvaNode();return s.zIndex()-r.zIndex()});for(let n of t){let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let s=o.zIndex();o.moveToTop();let r=o.zIndex();this._syncGroupZIndex(o),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",n,s,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_handleMoveToBottom(){let e=this._getSelectedNodes();if(e.length===0)return;let t=[...e].sort((n,o)=>{let s=n.getKonvaNode();return o.getKonvaNode().zIndex()-s.zIndex()});for(let n of t){let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let s=o.zIndex();o.moveToBottom();let r=o.zIndex();this._syncGroupZIndex(o),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",n,s,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_isNodeInsidePermanentGroup(e){if(e instanceof G.Group)return false;let t=e.getParent();return !(!t||!(t instanceof G.Group)||t===this._core?.nodes.world)}_syncGroupZIndex(e){let t=e.getParent();t&&(e instanceof G.Group||t instanceof G.Group&&t.name());}};var Cn=["image","video","gif","svg"];function Qt(y){let i=y.getKonvaNode(),e=i.getClassName(),t=i.getAttr("flowscapeNodeType");return t||({Text:"text",Image:"image",Rect:"shape",Circle:"circle",Ellipse:"ellipse",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon",Group:"group"}[e]??"shape")}function At(y){return Cn.includes(y)}function ze(y){return typeof y.getContentGroup=="function"}function We(y){return y.getKonvaNode().getClassName()==="Group"&&!ze(y)}function en(){return `blob_${String(Date.now())}_${Math.random().toString(36).substring(2,11)}`}function Tn(y){return y.startsWith("blob:")||y.startsWith("data:")}async function En(y){if(!Tn(y))return null;try{let i=await globalThis.fetch(y);return i.ok?await i.blob():null}catch{return null}}function Pn(y){return new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{let o=t.result.split(",")[1];o?i(o):e(new Error("Failed to extract base64"));},t.onerror=()=>{e(new Error("Failed to convert blob to base64"));},t.readAsDataURL(y);})}function Kn(y,i){let e=globalThis.atob(y),t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new Blob([new Uint8Array(t)],{type:i})}function gt(y,i,e){let t=y.getKonvaNode(),n=Qt(y),o=t.getAttrs(),s={};for(let[h,c]of Object.entries(o))typeof c=="function"||c instanceof HTMLElement||c instanceof HTMLImageElement||c instanceof HTMLVideoElement||c instanceof HTMLCanvasElement||h==="image"||h==="container"||(s[h]=c);if(At(n)){let h=t.scaleX(),c=t.scaleY();(h!==1||c!==1)&&(s.width=t.width()*h,s.height=t.height()*c,s.scaleX=1,s.scaleY=1);}let r={id:y.id,type:n,attrs:s,zIndex:t.zIndex()};if(At(n)){let h=o.src;if(h){let c=i.get(h);c||(c=en(),i.set(h,c)),r.blobId=c;}}let l=e.get(y.id);return l&&(r.parentFrameId=l),r}function tn(y,i,e,t){let n=y.getKonvaNode(),o=n.getAttrs(),s={};for(let[u,p]of Object.entries(o))typeof p=="function"||p instanceof HTMLElement||u==="container"||(s[u]=p);let r=y.getRect();s.width=r.width(),s.height=r.height(),s.background=r.fill();let l={id:y.id,type:"frame",attrs:s,zIndex:n.zIndex()},h=y.getContentGroup(),c=[],d=new Map;for(let u of h.getChildren()){let p=false;for(let[,f]of i)if(f.getKonvaNode()===u){t.set(f.id,y.id),We(f)?c.push(mt(f,i,e,t,d)):c.push(gt(f,e,t)),p=true;break}if(!p&&u.getClassName()==="Group"){let f=nn(u,i,e,t);f&&c.push(f);}}return c.length>0&&(l.children=c),l}function nn(y,i,e,t){let n=y.getAttrs(),o={};for(let[c,d]of Object.entries(n))typeof d=="function"||d instanceof HTMLElement||c==="container"||(o[c]=d);let s=n.id??`group_${String(Date.now())}_${Math.random().toString(36).substring(2,11)}`,r={id:s,type:"group",attrs:o,zIndex:y.zIndex()},l=[],h=new Map;for(let c of y.getChildren()){let d=false;for(let[,u]of i)if(u.getKonvaNode()===c){h.set(u.id,s),We(u)?l.push(mt(u,i,e,t,h)):l.push(gt(u,e,t)),d=true;break}if(!d&&c.getClassName()==="Group"){let u=nn(c,i,e,t);u&&l.push(u);}}return l.length>0&&(r.children=l),r}function mt(y,i,e,t,n){let o=y.getKonvaNode(),s=o.getAttrs(),r={};for(let[c,d]of Object.entries(s))typeof d=="function"||d instanceof HTMLElement||c==="container"||(r[c]=d);let l={id:y.id,type:"group",attrs:r,zIndex:o.zIndex()},h=[];for(let c of o.getChildren())for(let[,d]of i)if(d.getKonvaNode()===c){n.set(d.id,y.id),We(d)?h.push(mt(d,i,e,t,n)):ze(d)?h.push(tn(d,i,e,t)):h.push(gt(d,e,t));break}return h.length>0&&(l.children=h),l}function Jt(y,i,e){let{type:t,attrs:n,blobId:o}=i,s=n.src;o&&e.has(o)&&(s=e.get(o));let r={...n,id:i.id};s&&(r.src=s);try{switch(t){case "text":return y.nodes.addText(r);case "image":return y.nodes.addImage(r);case "video":return y.nodes.addVideo(r);case "gif":return y.nodes.addGif(r);case "svg":return y.nodes.addSvg(r);case "circle":return y.nodes.addCircle(r);case "ellipse":return y.nodes.addEllipse(r);case "arc":return y.nodes.addArc(r);case "star":return y.nodes.addStar(r);case "arrow":return y.nodes.addArrow(r);case "ring":return y.nodes.addRing(r);case "regularPolygon":return y.nodes.addRegularPolygon(r);case "group":return y.nodes.addGroup(r);case "frame":return y.nodes.addFrame(r);default:return y.nodes.addShape(r)}}catch(l){return globalThis.console.error(`Failed to create node of type ${t}:`,l),null}}function _t(y,i={}){let e=y.nodes.list(),t=i.blobUrlToId?new Map(i.blobUrlToId):new Map,n=new Map,o=new Map,s=[],r=new Map;for(let d of e)r.set(d.id,d);for(let d of e)if(ze(d)){let u=d,p=u.getContentGroup();for(let f of p.getChildren())for(let[g,m]of r)if(m.getKonvaNode()===f){n.set(g,u.id);break}}for(let d of e)if(We(d)){let u=d.getKonvaNode();for(let p of u.getChildren())for(let[f,g]of r)if(g.getKonvaNode()===p){o.set(f,d.id);break}}for(let d of e)n.has(d.id)||o.has(d.id)||(ze(d)?s.push(tn(d,r,t,n)):We(d)?s.push(mt(d,r,t,n,o)):s.push(gt(d,t,n)));let l=y.nodes.world,h={x:l.x(),y:l.y(),scale:l.scaleX()},c=Array.from(t.values());return {version:1,timestamp:Date.now(),nodes:s,camera:h,blobIds:c}}async function on(y){let i=y.nodes.list(),e=new Map,t=new Map;for(let n of i){let o=Qt(n);if(!At(o))continue;let r=n.getKonvaNode().getAttr("src");if(!r||t.has(r))continue;let l=await En(r);if(l){let h=en();t.set(r,h),e.set(h,{id:h,blob:l,originalUrl:r});}}return e}function vt(y,i,e={}){let{blobUrls:t=new Map,clearExisting:n=true}=e;if(n){let c=y.nodes.list();for(let d of [...c])y.nodes.remove(d);}let o=new Map,s=new Map;for(let c of i.nodes){let d=Jt(y,c,t);if(d){o.set(c.id,d),s.set(c.id,c.zIndex);let u=d.getKonvaNode(),p=c.attrs;p.scaleX!==void 0&&u.scaleX(p.scaleX),p.scaleY!==void 0&&u.scaleY(p.scaleY),p.rotation!==void 0&&u.rotation(p.rotation),p.skewX!==void 0&&u.skewX(p.skewX),p.skewY!==void 0&&u.skewY(p.skewY),p.offsetX!==void 0&&u.offsetX(p.offsetX),p.offsetY!==void 0&&u.offsetY(p.offsetY);}}let r=(c,d)=>{if(!c.children)return;let u=[...c.children].sort((p,f)=>p.zIndex-f.zIndex);for(let p of u){let f=Jt(y,p,t);if(f){let g=f.getKonvaNode(),m=p.attrs;m.scaleX!==void 0&&g.scaleX(m.scaleX),m.scaleY!==void 0&&g.scaleY(m.scaleY),m.rotation!==void 0&&g.rotation(m.rotation),m.skewX!==void 0&&g.skewX(m.skewX),m.skewY!==void 0&&g.skewY(m.skewY),m.offsetX!==void 0&&g.offsetX(m.offsetX),m.offsetY!==void 0&&g.offsetY(m.offsetY);let _=p.attrs.x??0,b=p.attrs.y??0;g.remove(),d.add(g),g.x(_),g.y(b),o.set(p.id,f),p.type==="group"&&p.children&&r(p,g);}}};for(let c of i.nodes)if(c.type==="frame"&&c.children){let d=o.get(c.id);if(d&&ze(d)){let p=d.getContentGroup();r(c,p);}}for(let c of i.nodes)if(c.type==="group"&&c.children){let d=o.get(c.id);if(d){let u=d.getKonvaNode();r(c,u);}}let l=[...i.nodes].filter(c=>!c.parentFrameId&&c.type!=="frame").sort((c,d)=>c.zIndex-d.zIndex);for(let c of l){let d=o.get(c.id);d&&d.getKonvaNode().moveToTop();}let h=[...i.nodes].filter(c=>c.type==="frame").sort((c,d)=>c.zIndex-d.zIndex);for(let c of h){let d=o.get(c.id);d&&d.getKonvaNode().moveToTop();}y.camera.setZoom(i.camera.scale),y.nodes.world.position({x:i.camera.x,y:i.camera.y}),y.nodes.layer.batchDraw();}async function Lt(y){let i=_t(y),e=await on(y),t={};for(let[n,o]of e){let s=await Pn(o.blob);t[n]={data:s,mimeType:o.blob.type,originalUrl:o.originalUrl};}return JSON.stringify({...i,embeddedBlobs:t},null,2)}function Dt(y,i,e={}){let t=JSON.parse(i),n=new Map;if(t.embeddedBlobs)for(let[o,s]of Object.entries(t.embeddedBlobs)){let r=Kn(s.data,s.mimeType),l=URL.createObjectURL(r);n.set(o,l);}vt(y,t,{...e,blobUrls:n});}function Ot(y,i){let e=new Map;for(let t of y.blobIds){let n=i.get(t);n&&e.set(t,URL.createObjectURL(n));}return e}function Ue(y){for(let i of y.values())URL.revokeObjectURL(i);y.clear();}var Rn="flowscape-persistence";var ae="canvas",le="blobs",sn=()=>{if(typeof globalThis.indexedDB<"u")return globalThis.indexedDB;throw new Error("IndexedDB is not available in this environment")},Ve=class{constructor(i=Rn){this._dbName=i;a(this,"_db",null);a(this,"_dbPromise",null);}async init(){if(!this._db){if(this._dbPromise){await this._dbPromise;return}this._dbPromise=this._openDatabase(),this._db=await this._dbPromise;}}_openDatabase(){return new Promise((i,e)=>{let t;try{t=sn();}catch(o){e(o instanceof Error?o:new Error(String(o)));return}let n=t.open(this._dbName,1);n.onerror=()=>{e(new Error(`Failed to open IndexedDB: ${n.error?.message??"Unknown error"}`));},n.onsuccess=()=>{i(n.result);},n.onupgradeneeded=o=>{let s=o.target.result;s.objectStoreNames.contains(ae)||s.createObjectStore(ae,{keyPath:"id"}),s.objectStoreNames.contains(le)||s.createObjectStore(le,{keyPath:"id"});};})}_getDb(){if(!this._db)throw new Error("PersistenceStorage not initialized. Call init() first.");return this._db}async saveCanvasState(i,e){let t=this._getDb();return new Promise((n,o)=>{let r=t.transaction([ae],"readwrite").objectStore(ae),l={id:i,state:e,updatedAt:Date.now()},h=r.put(l);h.onerror=()=>{o(new Error(`Failed to save canvas state: ${h.error?.message??"Unknown error"}`));},h.onsuccess=()=>{n();};})}async loadCanvasState(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([ae],"readonly").objectStore(ae).get(i);r.onerror=()=>{n(new Error(`Failed to load canvas state: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t(r.result);};})}async deleteCanvasState(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([ae],"readwrite").objectStore(ae).delete(i);r.onerror=()=>{n(new Error(`Failed to delete canvas state: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t();};})}async listCanvasStates(){let i=this._getDb();return new Promise((e,t)=>{let s=i.transaction([ae],"readonly").objectStore(ae).getAll();s.onerror=()=>{t(new Error(`Failed to list canvas states: ${s.error?.message??"Unknown error"}`));},s.onsuccess=()=>{e(s.result);};})}async saveBlob(i,e,t){let n=this._getDb();return new Promise((o,s)=>{let l=n.transaction([le],"readwrite").objectStore(le),h={id:i,blob:e,mimeType:e.type,originalUrl:t},c=l.put(h);c.onerror=()=>{s(new Error(`Failed to save blob: ${c.error?.message??"Unknown error"}`));},c.onsuccess=()=>{o();};})}async loadBlob(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([le],"readonly").objectStore(le).get(i);r.onerror=()=>{n(new Error(`Failed to load blob: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t(r.result);};})}async deleteBlob(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([le],"readwrite").objectStore(le).delete(i);r.onerror=()=>{n(new Error(`Failed to delete blob: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t();};})}async loadBlobs(i){let e=new Map;for(let t of i){let n=await this.loadBlob(t);n&&e.set(t,n);}return e}async saveBlobs(i){for(let[e,t]of i)await this.saveBlob(e,t.blob,t.originalUrl);}async listBlobIds(){let i=this._getDb();return new Promise((e,t)=>{let s=i.transaction([le],"readonly").objectStore(le).getAllKeys();s.onerror=()=>{t(new Error(`Failed to list blob IDs: ${s.error?.message??"Unknown error"}`));},s.onsuccess=()=>{e(s.result);};})}async cleanupUnusedBlobs(i){let e=await this.listBlobIds(),t=0;for(let n of e)i.has(n)||(await this.deleteBlob(n),t++);return t}async clearAll(){let i=this._getDb();return new Promise((e,t)=>{let n=i.transaction([ae,le],"readwrite");n.onerror=()=>{t(new Error(`Failed to clear storage: ${n.error?.message??"Unknown error"}`));},n.oncomplete=()=>{e();},n.objectStore(ae).clear(),n.objectStore(le).clear();})}close(){this._db&&(this._db.close(),this._db=null,this._dbPromise=null);}async deleteDatabase(){return this.close(),new Promise((i,e)=>{let t=sn().deleteDatabase(this._dbName);t.onerror=()=>{e(new Error(`Failed to delete database: ${t.error?.message??"Unknown error"}`));},t.onsuccess=()=>{i();};})}};var It=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_storage");a(this,"_canvasId");a(this,"_debounceMs");a(this,"_autoRestore");a(this,"_debug");a(this,"_saveTimer",null);a(this,"_isRestoring",false);a(this,"_blobUrls",new Map);a(this,"_initialized",false);a(this,"_blobUrlToId",new Map);a(this,"_onNodeCreated",e=>{if(this._isRestoring)return;this._captureBlobFromNode(e);let t=e.getKonvaNode();t.className==="Text"&&t.on("textChange.persistence",this._onTextChange),this._scheduleSave();});a(this,"_onNodeChange",e=>{this._isRestoring||this._scheduleSave();});a(this,"_onClipboardPaste",e=>{if(!this._isRestoring){for(let t of e)this._captureBlobFromNode(t);this._scheduleSave();}});a(this,"_onNodeTransformed",(e,t)=>{this._isRestoring||this._scheduleSave();});a(this,"_onCameraChange",()=>{this._isRestoring||this._scheduleSave();});a(this,"_onKonvaDragEnd",()=>{this._isRestoring||this._scheduleSave();});a(this,"_onKonvaTransformEnd",()=>{this._isRestoring||this._scheduleSave();});a(this,"_onTextChange",()=>{this._isRestoring||(this._log("Text changed, scheduling save"),this._scheduleSave());});this._canvasId=e.canvasId??"default",this._debounceMs=e.debounceMs??300,this._autoRestore=e.autoRestore??true,this._debug=e.debug??false,this._storage=new Ve(e.dbName);}onAttach(e){this._core=e,this._initialize();}onDetach(e){this._unsubscribeFromEvents(e),this._cancelPendingSave(),Ue(this._blobUrls),this._storage.close(),this._core=void 0,this._initialized=false;}async _initialize(){if(this._core)try{if(await this._storage.init(),this._log("Storage initialized"),this._autoRestore)try{await this.restore();}catch(e){e instanceof Error&&this._core.eventBus.emit("persistence:restore:error",{error:e.message});}finally{this._core.showContainer();}this._subscribeToEvents(this._core),this._initialized=!0,this._log("Plugin initialized");}catch(e){globalThis.console.error("[PersistencePlugin] Failed to initialize:",e);}}_subscribeToEvents(e){let t=e.eventBus;t.on("node:created",this._onNodeCreated),t.on("node:removed",this._onNodeChange),t.on("node:transformed",this._onNodeTransformed),t.on("node:zIndexChanged",this._onNodeChange),t.on("group:created",this._onNodeChange),t.on("group:ungrouped",this._onNodeChange),t.on("clipboard:paste",this._onClipboardPaste),t.on("camera:zoom",this._onCameraChange),t.on("camera:setZoom",this._onCameraChange),t.on("camera:pan",this._onCameraChange),t.on("camera:reset",this._onCameraChange),e.nodes.world.on("dragend.persistence",this._onKonvaDragEnd),e.nodes.layer.on("transformend.persistence",this._onKonvaTransformEnd),this._log("Subscribed to events");}_unsubscribeFromEvents(e){let t=e.eventBus;t.off("node:created",this._onNodeCreated),t.off("node:removed",this._onNodeChange),t.off("node:transformed",this._onNodeTransformed),t.off("node:zIndexChanged",this._onNodeChange),t.off("group:created",this._onNodeChange),t.off("group:ungrouped",this._onNodeChange),t.off("clipboard:paste",this._onClipboardPaste),t.off("camera:zoom",this._onCameraChange),t.off("camera:setZoom",this._onCameraChange),t.off("camera:pan",this._onCameraChange),t.off("camera:reset",this._onCameraChange),e.nodes.world.off(".persistence"),e.nodes.layer.off(".persistence"),this._log("Unsubscribed from events");}async _captureBlobFromNode(e){let n=e.getKonvaNode().getAttr("src");if(n?.startsWith("blob:")&&!this._blobUrlToId.has(n))try{let o=await globalThis.fetch(n);if(!o.ok)return;let s=await o.blob(),r=`blob_${String(Date.now())}_${Math.random().toString(36).substring(2,11)}`;await this._storage.saveBlob(r,s,n),this._blobUrlToId.set(n,r),this._log(`Captured blob: ${n} -> ${r}`);}catch(o){this._log(`Failed to capture blob from ${n}: ${String(o)}`);}}_subscribeToTextNodes(){if(!this._core)return;let e=this._core.nodes.list();for(let t of e){let n=t.getKonvaNode();n.className==="Text"&&(n.off("textChange.persistence"),n.on("textChange.persistence",this._onTextChange));}}_scheduleSave(){this._cancelPendingSave(),this._saveTimer=globalThis.setTimeout(()=>{this.save();},this._debounceMs);}_cancelPendingSave(){this._saveTimer&&(globalThis.clearTimeout(this._saveTimer),this._saveTimer=null);}async save(){if(!(!this._core||!this._initialized))try{await this._captureAllBlobUrls();let e=_t(this._core,{blobUrlToId:this._blobUrlToId});await this._storage.saveCanvasState(this._canvasId,JSON.stringify(e));let t=new Set(e.blobIds);await this._storage.cleanupUnusedBlobs(t),this._log("Saved canvas state");}catch(e){globalThis.console.error("[PersistencePlugin] Failed to save:",e);}}async restore(){if(!this._core)return false;try{let e=await this._storage.loadCanvasState(this._canvasId);if(!e)return this._log("No saved state found"),!1;let t=JSON.parse(e.state),n=new Map;for(let o of t.blobIds){let s=await this._storage.loadBlob(o);s&&n.set(o,s.blob);}Ue(this._blobUrls),this._blobUrls=Ot(t,n),this._blobUrlToId.clear();for(let[o,s]of this._blobUrls)this._blobUrlToId.set(s,o);this._isRestoring=!0;try{vt(this._core,t,{blobUrls:this._blobUrls,clearExisting:!0});}finally{this._isRestoring=!1;}return this._subscribeToTextNodes(),this._core.eventBus.emit("camera:pan",{dx:0,dy:0,position:{x:t.camera.x,y:t.camera.y}}),this._log("Restored canvas state"),!0}catch(e){return globalThis.console.error("[PersistencePlugin] Failed to restore:",e),false}}async clear(){try{await this._storage.deleteCanvasState(this._canvasId),await this._storage.clearAll(),Ue(this._blobUrls),this._log("Cleared saved state");}catch(e){globalThis.console.error("[PersistencePlugin] Failed to clear:",e);}}async exportToJSON(){if(!this._core)throw new Error("Plugin not attached to CoreEngine");return Lt(this._core)}importFromJSON(e){if(!this._core)throw new Error("Plugin not attached to CoreEngine");this._isRestoring=true,Dt(this._core,e,{clearExisting:true}),this._isRestoring=false,this._subscribeToTextNodes();let t=JSON.parse(e);this._core.eventBus.emit("camera:pan",{dx:0,dy:0,position:{x:t.camera?.x??0,y:t.camera?.y??0}}),this.save();}async downloadJSON(e="canvas.json"){let t=await this.exportToJSON(),n=new Blob([t],{type:"application/json"}),o=URL.createObjectURL(n),s=globalThis.document.createElement("a");s.href=o,s.download=e,s.click(),URL.revokeObjectURL(o);}uploadJSON(){return new Promise((e,t)=>{let n=globalThis.document.createElement("input");n.type="file",n.accept=".json,application/json",n.onchange=()=>{let o=n.files?.[0];if(!o){e();return}let s=new FileReader;s.onload=()=>{try{let r=s.result;this.importFromJSON(r),e();}catch(r){t(r instanceof Error?r:new Error(String(r)));}},s.onerror=()=>{t(new Error("Failed to read file"));},s.readAsText(o);},n.click();})}async hasSavedState(){return await this._storage.loadCanvasState(this._canvasId)!==null}getStorage(){return this._storage}getCanvasId(){return this._canvasId}async setCanvasId(e){this._canvasId=e,this._autoRestore&&this._initialized&&await this.restore();}_log(e){this._debug&&globalThis.console.log(`[PersistencePlugin] ${e}`);}async _captureAllBlobUrls(){if(!this._core)return;let e=this._core.nodes.list();for(let t of e)await this._captureBlobFromNode(t);}};var be=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_guidesLayer",null);a(this,"_guides",[]);a(this,"_activeGuide",null);a(this,"_draggingGuide",null);a(this,"_rulerLayerCache",null);a(this,"_updateScheduled",false);a(this,"_dragMoveScheduled",false);a(this,"_batchDrawScheduled",false);let{guideColor:t="#8e3e2c",activeColor:n="#2b83ff",rulerThicknessPx:o=30,snapToGrid:s=true,gridStep:r=1}=e;this._options={guideColor:t,activeColor:n,rulerThicknessPx:o,snapToGrid:s,gridStep:r};}onAttach(e){if(this._core=e,!e.stage.findOne(".ruler-layer"))throw new Error("RulerGuidesPlugin requires RulerPlugin to be added to the CoreEngine first. Please add RulerPlugin before RulerGuidesPlugin.");this._guidesLayer=new G.Layer({name:"guides-layer"}),e.stage.add(this._guidesLayer),this._guidesLayer.moveToTop();let n=e.stage,o=this._options.rulerThicknessPx;n.on("mousedown.ruler-guides",()=>{let r=n.getPointerPosition();if(!r)return;let l=n.getIntersection(r);l&&(l.name()==="guide-h"||l.name()==="guide-v")||(r.y<=o&&r.x>=o?this._startCreateGuide("h"):r.x<=o&&r.y>=o?this._startCreateGuide("v"):this._setActiveGuide(null));}),n.on("mousemove.ruler-guides",()=>{let r=n.getPointerPosition();if(!r)return;let l=n.getIntersection(r);if(l){let h=l.name();if(h==="guide-h"||h==="guide-v"||h.includes("_anchor")||h.includes("rotater")||l.draggable())return}r.y<=o&&r.x>=o?n.container().style.cursor="ns-resize":r.x<=o&&r.y>=o?n.container().style.cursor="ew-resize":this._draggingGuide||(n.container().style.cursor="default");}),this._rulerLayerCache=e.stage.findOne(".ruler-layer"),e.nodes.world.on("xChange.ruler-guides yChange.ruler-guides scaleXChange.ruler-guides scaleYChange.ruler-guides",()=>{this._scheduleUpdate();}),n.on("resize.ruler-guides",()=>{this._scheduleUpdate();}),e.stage.batchDraw();}onDetach(e){e.stage.off(".ruler-guides"),e.nodes.world.off(".ruler-guides"),this._guidesLayer&&(this._guidesLayer.destroy(),this._guidesLayer=null),this._guides=[],this._activeGuide=null,this._draggingGuide=null;}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=true,globalThis.requestAnimationFrame(()=>{this._updateScheduled=false,this._updateGuidesPositions();}));}_updateGuidesPositions(){if(!this._core||this._guides.length===0)return;let e=this._core.nodes.world,t=e.scaleX(),n=e.x(),o=e.y(),s=this._core.stage.width(),r=this._core.stage.height(),l=[0,0,s,0],h=[0,0,0,r];for(let c of this._guides){let d=c.worldCoord;if(c.name()==="guide-h"){let p=o+d*t;c.position({x:0,y:p}),c.points(l);}else {let p=n+d*t;c.position({x:p,y:0}),c.points(h);}}this._guidesLayer?.batchDraw();}_snapToGrid(e){if(!this._options.snapToGrid)return Math.round(e);let t=this._options.gridStep;return Math.round(e/t)*t}_scheduleBatchDraw(){this._batchDrawScheduled||(this._batchDrawScheduled=true,globalThis.requestAnimationFrame(()=>{this._batchDrawScheduled=false,this._core?.stage.batchDraw();}));}_startCreateGuide(e){if(!this._core||!this._guidesLayer)return;let t=this._core.stage,n=this._core.nodes.world,o=n.scaleX(),s=t.getPointerPosition();if(!s)return;let r=e==="h"?(s.y-n.y())/o:(s.x-n.x())/o,l=this._snapToGrid(r),h=new G.Line({name:e==="h"?"guide-h":"guide-v",stroke:this._options.guideColor,strokeWidth:1,opacity:1,draggable:true,hitStrokeWidth:8,dragBoundFunc:p=>{if(!this._core)return p;let f=this._core.nodes.world,g=f.scaleX();if(e==="h"){let m=(p.y-f.y())/g,_=this._snapToGrid(m);return {x:0,y:f.y()+_*g}}else {let m=(p.x-f.x())/g,_=this._snapToGrid(m);return {x:f.x()+_*g,y:0}}}});h.worldCoord=l,h.on("mouseenter",()=>{this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize"),this._scheduleBatchDraw();}),h.on("mouseleave",()=>{this._core&&!this._draggingGuide&&(this._core.stage.container().style.cursor="default"),this._scheduleBatchDraw();}),h.on("click",()=>{this._setActiveGuide(h);}),h.on("dragstart",()=>{let p=h;this._draggingGuide={type:e,line:p},this._setActiveGuide(p),this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize");}),h.on("dragmove",()=>{!this._core||this._dragMoveScheduled||(this._dragMoveScheduled=true,globalThis.requestAnimationFrame(()=>{if(this._dragMoveScheduled=false,!this._core)return;let p=this._core.nodes.world,f=p.scaleX(),g=h.getAbsolutePosition(),m=e==="h"?(g.y-p.y())/f:(g.x-p.x())/f,_=this._snapToGrid(m);h.worldCoord=_,this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize",this._rulerLayerCache&&this._rulerLayerCache.batchDraw();}));}),h.on("dragend",()=>{this._draggingGuide=null,this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize");});let c=h;this._guidesLayer.add(c),this._guides.push(c),this._setActiveGuide(c),e==="h"?(h.position({x:0,y:n.y()+l*o}),h.points([0,0,t.width(),0])):(h.position({x:n.x()+l*o,y:0}),h.points([0,0,0,t.height()])),this._draggingGuide={type:e,line:c};let d=()=>{if(!this._draggingGuide||!this._core)return;let p=this._core.stage.getPointerPosition();if(!p)return;let f=this._core.nodes.world,g=f.scaleX(),m=e==="h"?(p.y-f.y())/g:(p.x-f.x())/g,_=this._snapToGrid(m);h.worldCoord=_,e==="h"?(h.position({x:0,y:f.y()+_*g}),h.points([0,0,this._core.stage.width(),0])):(h.position({x:f.x()+_*g,y:0}),h.points([0,0,0,this._core.stage.height()])),this._scheduleBatchDraw();},u=()=>{this._draggingGuide=null,this._core&&(this._core.stage.off("mousemove.guide-create"),this._core.stage.off("mouseup.guide-create"));};t.on("mousemove.guide-create",d),t.on("mouseup.guide-create",u),this._scheduleBatchDraw();}_setActiveGuide(e){this._activeGuide&&this._activeGuide!==e&&(this._activeGuide.stroke(this._options.guideColor),this._activeGuide.strokeWidth(1)),this._activeGuide=e,e&&(e.stroke(this._options.activeColor),e.strokeWidth(2)),this._rulerLayerCache&&this._rulerLayerCache.batchDraw(),this._core?.stage.fire("guidesChanged.ruler"),this._scheduleBatchDraw();}getActiveGuide(){return this._activeGuide}getActiveGuideInfo(){if(!this._activeGuide)return null;let e=this._activeGuide.worldCoord;return {type:this._activeGuide.name()==="guide-h"?"h":"v",coord:e}}removeActiveGuide(){this._activeGuide&&(this._activeGuide.destroy(),this._guides=this._guides.filter(e=>e!==this._activeGuide),this._activeGuide=null,this._scheduleBatchDraw());}getGuides(){return [...this._guides]}clearGuides(){this._guides.forEach(e=>e.destroy()),this._guides=[],this._activeGuide=null,this._scheduleBatchDraw();}};var Re=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_highlightLayer",null);a(this,"_hGroup",null);a(this,"_vGroup",null);a(this,"_hHighlights",[]);a(this,"_vHighlights",[]);a(this,"_updateDebounce",new ye);a(this,"_transformersCache",[]);a(this,"_cacheInvalidated",true);let{highlightColor:t="#2b83ff",highlightOpacity:n=.3,rulerThicknessPx:o=30}=e;this._options={highlightColor:t,highlightOpacity:n,rulerThicknessPx:o};}onAttach(e){this._core=e;let t=e.stage.findOne(".ruler-layer");if(!t){globalThis.console.warn("RulerHighlightPlugin: RulerPlugin not found. Please add RulerPlugin before RulerHighlightPlugin. Plugin will not work without RulerPlugin.");return}this._highlightLayer=t;let n=t.find("Group");if(n.length>=2)this._hGroup=n[0],this._vGroup=n[1];else {globalThis.console.warn("RulerHighlightPlugin: Could not find ruler groups");return}e.nodes.world.on("xChange.ruler-highlight yChange.ruler-highlight scaleXChange.ruler-highlight scaleYChange.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("resize.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("transform.ruler-highlight transformend.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("click.ruler-highlight",()=>{this._invalidateCache(),this._scheduleUpdate();}),e.stage.on("dragmove.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("mouseup.ruler-highlight",()=>{this._invalidateCache(),this._scheduleUpdate();}),this._updateHighlights();}onDetach(e){try{e.stage.off(".ruler-highlight"),e.nodes.world.off(".ruler-highlight");}catch{}this._hHighlights.forEach(t=>{try{t.destroy();}catch{}}),this._vHighlights.forEach(t=>{try{t.destroy();}catch{}}),this._hHighlights=[],this._vHighlights=[],this._highlightLayer=null,this._hGroup=null,this._vGroup=null;}_scheduleUpdate(){this._updateDebounce.schedule(()=>{this._updateHighlights();});}_invalidateCache(){this._cacheInvalidated=true;}_updateHighlights(){if(!this._core||!this._highlightLayer)return;for(let g of this._hHighlights)g.destroy();this._hHighlights=[];for(let g of this._vHighlights)g.destroy();this._vHighlights=[];let e=this._getSelectedKonvaNodes();if(e.length===0){this._highlightLayer.batchDraw();return}let t=this._core.stage,n=this._core.nodes.world,o=t.width(),s=t.height(),r=this._options.rulerThicknessPx,l=n.scaleX(),h=n.x(),c=n.y(),d=[],u=[];for(let g of e){let m=g.getClientRect({relativeTo:n}),_=h+m.x*l,b=h+(m.x+m.width)*l,v=c+m.y*l,w=c+(m.y+m.height)*l;if(_<o&&b>r){let x=Math.max(r,_),N=Math.min(o,b);x<N&&d.push({start:x,end:N});}if(v<s&&w>r){let x=Math.max(r,v),N=Math.min(s,w);x<N&&u.push({start:x,end:N});}}let p=this._mergeSegments(d),f=this._mergeSegments(u);if(this._hGroup)for(let g of p){let m=new G.Rect({x:g.start,y:0,width:g.end-g.start,height:r,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-h"});this._hGroup.add(m),m.setZIndex(1),this._hHighlights.push(m);}if(this._vGroup)for(let g of f){let m=new G.Rect({x:0,y:g.start,width:r,height:g.end-g.start,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-v"});this._vGroup.add(m),m.setZIndex(1),this._vHighlights.push(m);}this._highlightLayer.batchDraw();}_collectNodes(e,t){let n=e.getClassName(),o=e.name(),r=["overlay-hit","ruler-","guide-","_anchor","back","rotater"].some(l=>o.includes(l));if(!(n==="Transformer"||n==="Layer"||r))if(n==="Group"){let h=e.getChildren();if(h.length===0)return;for(let c of h)this._collectNodes(c,t);}else t.includes(e)||t.push(e);}_mergeSegments(e){if(e.length===0)return [];let t=e.slice().sort((r,l)=>r.start-l.start),n=t[0];if(!n)return [];let o=[],s={start:n.start,end:n.end};for(let r=1;r<t.length;r++){let l=t[r];l&&(l.start<=s.end+1?s.end=Math.max(s.end,l.end):(o.push(s),s={start:l.start,end:l.end}));}return o.push(s),o}_getSelectedKonvaNodes(){if(!this._core)return [];let e=[];try{this._cacheInvalidated&&(this._transformersCache=this._core.stage.find("Transformer"),this._cacheInvalidated=!1);for(let n of this._transformersCache){let o=n.nodes();for(let s of o)e.includes(s)||e.push(s);}}catch{}let t=[];for(let n of e)this._collectNodes(n,t);return t}update(){this._updateHighlights();}};var Me=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_visible",true);a(this,"_handleKeyDown",e=>{if(e.shiftKey&&(e.key==="r"||e.key==="R"||e.key==="\u043A"||e.key==="\u041A")){e.preventDefault(),this.toggle();return}(e.code==="Delete"||e.code==="Backspace")&&this.deleteActiveGuide()&&e.preventDefault();});let{enabled:t=true}=e;this._options={enabled:t};}onAttach(e){this._options.enabled&&(this._core=e,this._bindKeyboardEvents());}onDetach(e){this._unbindKeyboardEvents();}_bindKeyboardEvents(){globalThis.addEventListener("keydown",this._handleKeyDown);}_unbindKeyboardEvents(){globalThis.removeEventListener("keydown",this._handleKeyDown);}toggle(){this._visible?this.hide():this.show();}show(){if(!this._core)return;this._visible=true;let e=this._core.stage.findOne(".ruler-layer");e&&!e.isVisible()&&e.show();let t=this._core.stage.findOne(".guides-layer");t&&!t.isVisible()&&t.show(),this._core.stage.batchDraw();}hide(){if(!this._core)return;this._visible=false;let e=this._core.stage.findOne(".ruler-layer");e?.isVisible()&&e.hide();let t=this._core.stage.findOne(".guides-layer");t?.isVisible()&&t.hide(),this._core.stage.batchDraw();}isVisible(){return this._visible}deleteActiveGuide(){if(!this._core)return false;let e=this._core.plugins.list().find(t=>t instanceof be);return e&&"getActiveGuide"in e&&"removeActiveGuide"in e&&e.getActiveGuide.call(e)?(e.removeActiveGuide.call(e),true):false}};var Gt=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_layer",null);a(this,"_hGroup");a(this,"_vGroup");a(this,"_hBg");a(this,"_vBg");a(this,"_hTicksShape");a(this,"_vTicksShape");a(this,"_hBorder");a(this,"_vBorder");a(this,"_redrawScheduled",false);a(this,"_lastRedrawTime",0);a(this,"_redrawThrottleMs",16);a(this,"_panThrottleMs",32);a(this,"_cachedActiveGuide",null);a(this,"_cacheInvalidated",true);a(this,"_stepsCache",new Map);let{thicknessPx:t=30,fontFamily:n="Inter, Calibri, Arial, sans-serif",fontSizePx:o=10,color:s="#8c8c8c",bgColor:r="#2c2c2c",borderColor:l="#1f1f1f",enabled:h=true}=e;this._options={thicknessPx:t,fontFamily:n,fontSizePx:o,color:s,bgColor:r,borderColor:l,enabled:h};}_calculateNiceStep(e){if(!isFinite(e)||e<=0)return 1;let t=Math.pow(10,Math.floor(Math.log10(e))),n=e/t,o;return n<=1?o=1:n<=2?o=2:n<=5?o=5:o=10,o*t}_formatNumber(e){return Math.round(e).toString()}_getStepsConfig(e){let t=this._stepsCache.get(e);if(t)return t;let n=this._options.thicknessPx,s=50/e,r=this._calculateNiceStep(s);r<1&&(r=1);let l=r*e,h,c,d,u;l>=60?(h=r*10,c=r*5,d=r,u=r):l>=40?(h=r*10,c=r*5,d=r*5,u=r):(h=r*10,c=r*5,d=r*10,u=r);let p={step:r,stepPx:l,majorStep:h,mediumStep:c,labelStep:d,drawStep:u,drawStepEpsilon:u*.01,majorTickLength:n*.6,mediumTickLength:n*.4,minorTickLength:n*.25,fontString:`${String(this._options.fontSizePx)}px ${this._options.fontFamily}`};if(this._stepsCache.size>10){let f=this._stepsCache.keys().next().value;f!==void 0&&this._stepsCache.delete(f);}return this._stepsCache.set(e,p),p}onAttach(e){this._core=e,this._layer=new G.Layer({name:"ruler-layer",listening:true}),this._options.enabled&&e.stage.add(this._layer),this._hGroup=new G.Group({listening:true}),this._vGroup=new G.Group({listening:true}),this._layer.add(this._hGroup),this._layer.add(this._vGroup),this._hBg=new G.Rect({fill:this._options.bgColor,listening:true,name:"ruler-h-bg"}),this._vBg=new G.Rect({fill:this._options.bgColor,listening:true,name:"ruler-v-bg"}),this._hGroup.add(this._hBg),this._vGroup.add(this._vBg),this._hBorder=new G.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._vBorder=new G.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._hGroup.add(this._hBorder),this._vGroup.add(this._vBorder),this._hTicksShape=new G.Shape({listening:false,sceneFunc:o=>{let s=this._getActiveGuideInfo();this._drawHorizontalRuler(o,s);}}),this._hGroup.add(this._hTicksShape),this._vTicksShape=new G.Shape({listening:false,sceneFunc:o=>{let s=this._getActiveGuideInfo();this._drawVerticalRuler(o,s);}}),this._vGroup.add(this._vTicksShape);let t=e.stage,n=e.nodes.world;t.on("resize.ruler",()=>{this._scheduleRedraw();}),n.on("xChange.ruler yChange.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw(true);}),n.on("scaleXChange.ruler scaleYChange.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw(false);}),t.on("guidesChanged.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw();}),this._redraw(),e.stage.batchDraw();}onDetach(e){e.stage.off(".ruler"),e.nodes.world.off(".ruler"),this._layer&&(this._layer.destroy(),this._layer=null);}_getActiveGuideInfo(){if(!this._core)return null;if(!this._cacheInvalidated)return this._cachedActiveGuide;let e=this._core.stage.findOne(".guides-layer");if(!e)return this._cachedActiveGuide=null,this._cacheInvalidated=false,null;let t=e.find("Line");for(let n of t){let o=n;if(o.strokeWidth()===2){let s=o.worldCoord,r=o.name()==="guide-h"?"h":"v";return this._cachedActiveGuide={type:r,coord:s},this._cacheInvalidated=false,this._cachedActiveGuide}}return this._cachedActiveGuide=null,this._cacheInvalidated=false,null}_invalidateGuideCache(){this._cacheInvalidated=true;}_drawRuler(e,t,n){if(!this._core)return;let o=this._core.stage,s=this._core.nodes.world,r=s.scaleX()||1e-9,l=this._options.thicknessPx,h=t==="h",c=h?o.width():o.height(),d=h?s.x():s.y(),u=n?.type===(h?"v":"h")?n.coord:null,p=this._getStepsConfig(r),{majorStep:f,mediumStep:g,labelStep:m,drawStep:_,drawStepEpsilon:b,majorTickLength:v,mediumTickLength:w,minorTickLength:x,fontString:N}=p;e.save();let k=-d/r,S=Math.floor(k/_)*_,C=[],T=[],K=[],L=[],B=null;for(let P=S;;P+=_){let I=d+P*r;if(I>c)break;if(I<0)continue;if(u!==null&&Math.abs(P-u)<b){B=I,L.push({pos:I,text:this._formatNumber(P)});continue}let U=Math.abs(P%f)<b,J=!U&&Math.abs(P%g)<b;U?C.push(I):J?T.push(I):K.push(I),Math.abs(P%m)<b&&L.push({pos:I,text:this._formatNumber(P)});}if(K.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.4,e.lineWidth=1,e.beginPath();for(let P of K)h?(e.moveTo(P,l),e.lineTo(P,l-x)):(e.moveTo(l,P),e.lineTo(l-x,P));e.stroke();}if(T.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.6,e.lineWidth=1,e.beginPath();for(let P of T)h?(e.moveTo(P,l),e.lineTo(P,l-w)):(e.moveTo(l,P),e.lineTo(l-w,P));e.stroke();}if(C.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.9,e.lineWidth=1,e.beginPath();for(let P of C)h?(e.moveTo(P,l),e.lineTo(P,l-v)):(e.moveTo(l,P),e.lineTo(l-v,P));e.stroke();}if(B!==null&&(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(B,l),e.lineTo(B,l-v)):(e.moveTo(l,B),e.lineTo(l-v,B)),e.stroke()),L.length>0){e.font=N,e.textBaseline="top",e.textAlign="left";for(let P of L){let I=P.pos===B;if(e.globalAlpha=I?1:.9,e.fillStyle=I?"#ff8c00":this._options.color,h)e.fillText(P.text,P.pos+4,4);else {let U=P.pos+4;e.setTransform(0,-1,1,0,4,U),e.fillText(P.text,0,0),e.setTransform(1,0,0,1,0,0);}}}if(u!==null){let P=d+u*r;if(P>=0&&P<=c&&!(Math.abs(u%_)<b))if(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(P,l),e.lineTo(P,l-v)):(e.moveTo(l,P),e.lineTo(l-v,P)),e.stroke(),e.fillStyle="#ff8c00",e.font=N,e.textBaseline="top",e.textAlign="left",h)e.fillText(this._formatNumber(u),P+4,4);else {let U=P+4;e.setTransform(0,-1,1,0,4,U),e.fillText(this._formatNumber(u),0,0),e.setTransform(1,0,0,1,0,0);}}e.restore();}_drawHorizontalRuler(e,t){this._drawRuler(e,"h",t);}_drawVerticalRuler(e,t){this._drawRuler(e,"v",t);}_redraw(){if(!this._core||!this._layer)return;let e=this._core.stage,t=e.width(),n=e.height(),o=this._options.thicknessPx;this._hBg&&this._hBg.size({width:t,height:o}),this._vBg&&this._vBg.size({width:o,height:n}),this._hBorder&&this._hBorder.points([0,o,t,o]),this._vBorder&&this._vBorder.points([o,0,o,n]),this._layer.batchDraw();}_scheduleRedraw(e=false){if(!this._core||!this._layer)return;let n=globalThis.performance.now()-this._lastRedrawTime;if(this._redrawScheduled)return;this._redrawScheduled=true;let o=e?this._panThrottleMs:this._redrawThrottleMs;if(n>=o)globalThis.requestAnimationFrame(()=>{this._redrawScheduled=false,this._lastRedrawTime=globalThis.performance.now(),this._redraw();});else {let s=o-n;globalThis.setTimeout(()=>{globalThis.requestAnimationFrame(()=>{this._redrawScheduled=false,this._lastRedrawTime=globalThis.performance.now(),this._redraw();});},s);}}show(){this._core&&this._layer&&(this._core.stage.add(this._layer),this._layer.moveToTop(),this._redraw(),this._core.stage.batchDraw());}hide(){this._layer?.getStage()&&(this._layer.remove(),this._core?.stage.batchDraw());}toggle(){this._layer?.getStage()?this.hide():this.show();}isVisible(){return !!this._layer?.getStage()}};var Ht=class extends O{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_layer",null);a(this,"_maxGuideDistancePx",1200);a(this,"_dragMoveHandler",null);a(this,"_dragEndHandler",null);a(this,"_nodesAddHandler",null);a(this,"_nodesRemoveHandler",null);let{guidelineColor:t="#8e3e2c",guidelineWidth:n=1,guidelineDash:o=[0,0],thresholdPx:s=8}=e;this._options={guidelineColor:t,guidelineWidth:n,guidelineDash:o,thresholdPx:s};}_applyGapSnappingForDrag(e,t,n){if(!this._core)return;let o=this._options.thresholdPx,s=e.getClientRect({skipShadow:true,skipStroke:false}),r=n.x-t.x,l=n.y-t.y,h={x:s.x+r,y:s.y+l,width:s.width,height:s.height},c=this._collectOtherNodeBoxes(e),d=o+1,u=0,p=o+1,f=0;for(let g of c){let m=g.box;if(!(h.y>m.y+m.height||h.y+h.height<m.y)){let v=h.x,w=h.x+h.width,x=m.x,N=m.x+m.width;if(x>=w){let k=x-w;k>0&&k<d&&(d=k,u=k);}if(N<=v){let k=v-N;k>0&&k<d&&(d=k,u=-k);}}if(!(h.x>m.x+m.width||h.x+h.width<m.x)){let v=h.y,w=h.y+h.height,x=m.y,N=m.y+m.height;if(x>=w){let k=x-w;k>0&&k<p&&(p=k,f=k);}if(N<=v){let k=v-N;k>0&&k<p&&(p=k,f=-k);}}}d<=o&&(n.x+=u),p<=o&&(n.y+=f);}onAttach(e){this._core=e;let t=new G.Layer({name:"snap-guides-layer"});e.stage.add(t),t.moveToTop(),this._layer=t,this._dragMoveHandler=o=>{this._onDragMove(o);},this._dragEndHandler=()=>{this._clearGuides();},e.stage.on("dragmove.snap-guides",this._dragMoveHandler),e.stage.on("dragend.snap-guides",this._dragEndHandler);let n=e.nodes.layer;this._nodesAddHandler=o=>{let r=o.child??o.target;this._walkAttachTransformers(r);},this._nodesRemoveHandler=o=>{let r=o.child??o.target;this._walkDetachTransformers(r);},n.on("add.snap-guides",this._nodesAddHandler),n.on("remove.snap-guides",this._nodesRemoveHandler),this._attachExistingTransformers();}onDetach(e){e.stage.off(".snap-guides"),e.nodes.layer.off(".snap-guides");let t=e.nodes.layer.find("Transformer");for(let n of t)n.off(".snap-guides-resize");this._layer&&(this._layer.destroy(),this._layer=null),this._dragMoveHandler=null,this._dragEndHandler=null,this._nodesAddHandler=null,this._nodesRemoveHandler=null,this._core=void 0;}_onDragMove(e){if(!this._core||!this._layer)return;if(this._isVisualLinesShouldCleared(e.target)){this._clearGuides();return}let t=this._core.stage,n=this._core.nodes.layer,o=e.target;if(o===t||o instanceof G.Layer)return;let s=o,r=false;for(;s;){if(s===n){r=true;break}s=s.getParent();}if(!r)return;let l=o;if(typeof l.draggable=="function"&&!l.draggable())return;this._clearGuides();let h=this._getLineGuideStops(o),c=this._getObjectSnappingEdges(o),d=this._getGuides(h,c);if(!d.length)return;let u=o.absolutePosition(),p={...u};for(let f of d)f.orientation==="V"?p.x=f.lineGuide+f.offset:p.y=f.lineGuide+f.offset;this._applyGapSnappingForDrag(o,u,p),o.absolutePosition(p),this._drawDragGuides(o);}_clearGuides(){if(!this._layer)return;let e=this._layer.find(".snap-guid-line");for(let t of e)t.destroy();this._layer.batchDraw();}_drawDragGuides(e){if(!this._core||!this._layer)return;let t=e.getClientRect({skipShadow:true,skipStroke:false}),n=this._buildDragRays(t),o=this._collectOtherNodeBoxes(e);if(!o.length)return;let s=16;for(let r of n){let l=[];for(let p of o){let f=this._intersectRayWithBox(r.origin,r.dir,p.box);f&&l.push({...f,box:p.box});}if(!l.length)continue;l.sort((p,f)=>p.tEnter-f.tEnter);let h=l.slice(0,s);if(!h.length)continue;let c=0;for(let p of h)p.tExit>c&&(c=p.tExit);if(c<=0)continue;let d;r.dir==="right"?d=[0,0,c,0]:r.dir==="left"?d=[0,0,-c,0]:r.dir==="down"?d=[0,0,0,c]:d=[0,0,0,-c];let u=new G.Line({points:d,stroke:this._options.guidelineColor,strokeWidth:this._options.guidelineWidth,name:"snap-guid-line",dash:this._options.guidelineDash,listening:false});this._layer.add(u),u.absolutePosition({x:r.origin.x,y:r.origin.y});for(let p of h){let f=p.tEnter,g=p.tExit,m=this._pointOnRay(r.origin,r.dir,f),_=this._pointOnRay(r.origin,r.dir,g),b=p.box,v=0,w=0;if(r.dir==="right"){let x=t.x+t.width,N=b.x,k=b.x+b.width;v=N-x,w=k-x;}else if(r.dir==="left"){let x=t.x,N=b.x,k=b.x+b.width;v=x-k,w=x-N;}else if(r.dir==="down"){let x=t.y+t.height,N=b.y,k=b.y+b.height;v=N-x,w=k-x;}else {let x=t.y,N=b.y,k=b.y+b.height;v=x-k,w=x-N;}v=Math.max(0,v),w=Math.max(0,w),this._drawRayMarkerWithLabel(m.x,m.y,v,r.dir),this._drawRayMarkerWithLabel(_.x,_.y,w,r.dir);}}this._layer.batchDraw();}_pointOnRay(e,t,n){return t==="right"?{x:e.x+n,y:e.y}:t==="left"?{x:e.x-n,y:e.y}:t==="down"?{x:e.x,y:e.y+n}:{x:e.x,y:e.y-n}}_drawRayMarkerWithLabel(e,t,n,o){if(!this._layer)return;let s=4,r=new G.Line({points:[-s,-s,s,s],stroke:this._options.guidelineColor,strokeWidth:1,name:"snap-guid-line",listening:false});this._layer.add(r),r.absolutePosition({x:e,y:t});let l=new G.Line({points:[-s,s,s,-s],stroke:this._options.guidelineColor,strokeWidth:1,name:"snap-guid-line",listening:false});this._layer.add(l),l.absolutePosition({x:e,y:t});}_buildDragRays(e){let t=[],n=e.x+e.width/2,o=e.y+e.height/2;t.push({origin:{x:n,y:o},dir:"up"},{origin:{x:n,y:o},dir:"down"},{origin:{x:n,y:o},dir:"left"},{origin:{x:n,y:o},dir:"right"}),t.push({origin:{x:n,y:e.y},dir:"up"},{origin:{x:n,y:e.y+e.height},dir:"down"},{origin:{x:e.x,y:o},dir:"left"},{origin:{x:e.x+e.width,y:o},dir:"right"});let s={x:e.x,y:e.y},r={x:e.x+e.width,y:e.y},l={x:e.x+e.width,y:e.y+e.height},h={x:e.x,y:e.y+e.height};return t.push({origin:s,dir:"up"},{origin:s,dir:"left"},{origin:r,dir:"up"},{origin:r,dir:"right"},{origin:l,dir:"down"},{origin:l,dir:"right"},{origin:h,dir:"down"},{origin:h,dir:"left"}),t}_collectOtherNodeBoxes(e){let t=[];if(!this._core)return t;let n=this._core.nodes.list(),o=e.getClientRect({skipShadow:true,skipStroke:false}),s=o.x+o.width/2,r=o.y+o.height/2,l=this._core.nodes.world;for(let h of n){let c=h.getKonvaNode();if(c===e)continue;let d=c,u=e;if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(e)||typeof u.isAncestorOf=="function"&&u.isAncestorOf(c))continue;let p=c.getParent(),f=e.getParent();if(p&&f&&p===f&&p!==l&&p instanceof G.Group)continue;let g=c.getClientRect({skipShadow:true,skipStroke:false}),m=g.x+g.width/2,_=g.y+g.height/2,b=m-s,v=_-r;Math.sqrt(b*b+v*v)>this._maxGuideDistancePx||t.push({node:c,box:{x:g.x,y:g.y,width:g.width,height:g.height}});}return t}_intersectRayWithBox(e,t,n){let o=e.x,s=e.y,r=n.x,l=n.y,h=n.x+n.width,c=n.y+n.height;if(t==="right"||t==="left"){if(s<l||s>c)return null;if(t==="right"){if(h<=o)return null;let d=Math.max(r,o),u=h,p=d-o,f=u-o;return f<=0||f<=p?null:{tEnter:p,tExit:f}}else {if(r>=o)return null;let d=Math.min(h,o),u=r,p=o-d,f=o-u;return f<=0||f<=p?null:{tEnter:p,tExit:f}}}if(o<r||o>h)return null;if(t==="down"){if(c<=s)return null;let d=Math.max(l,s),u=c,p=d-s,f=u-s;return f<=0||f<=p?null:{tEnter:p,tExit:f}}else {if(l>=s)return null;let d=Math.min(c,s),u=l,p=s-d,f=s-u;return f<=0||f<=p?null:{tEnter:p,tExit:f}}}_getLineGuideStops(e){if(!this._core)return {vertical:[],horizontal:[]};let t=this._core.stage,n=[0,t.width()/2,t.width()],o=[0,t.height()/2,t.height()],s=this._core.nodes.list();for(let r of s){let l=r.getKonvaNode();if(l===e)continue;let h=l,c=e;if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(e)||typeof c.isAncestorOf=="function"&&c.isAncestorOf(l))continue;let d=l.getClientRect({skipShadow:true,skipStroke:false});n.push(d.x,d.x+d.width,d.x+d.width/2),o.push(d.y,d.y+d.height,d.y+d.height/2);}return {vertical:n,horizontal:o}}_getObjectSnappingEdges(e){let t=e.getClientRect({skipShadow:true,skipStroke:false}),n=e.absolutePosition();return {vertical:[{guide:Math.round(t.x),offset:Math.round(n.x-t.x),snap:"start"},{guide:Math.round(t.x+t.width/2),offset:Math.round(n.x-t.x-t.width/2),snap:"center"},{guide:Math.round(t.x+t.width),offset:Math.round(n.x-t.x-t.width),snap:"end"}],horizontal:[{guide:Math.round(t.y),offset:Math.round(n.y-t.y),snap:"start"},{guide:Math.round(t.y+t.height/2),offset:Math.round(n.y-t.y-t.height/2),snap:"center"},{guide:Math.round(t.y+t.height),offset:Math.round(n.y-t.y-t.height),snap:"end"}]}}_getGuides(e,t){let n=[],o=[],s=this._options.thresholdPx;for(let l of e.vertical)for(let h of t.vertical){let c=Math.abs(l-h.guide);c<s&&n.push({lineGuide:l,diff:c,snap:h.snap,offset:h.offset});}for(let l of e.horizontal)for(let h of t.horizontal){let c=Math.abs(l-h.guide);c<s&&o.push({lineGuide:l,diff:c,snap:h.snap,offset:h.offset});}let r=[];if(n.length>0){let[l]=[...n].sort((h,c)=>h.diff-c.diff);l&&r.push({lineGuide:l.lineGuide,offset:l.offset,orientation:"V",snap:l.snap});}if(o.length>0){let[l]=[...o].sort((h,c)=>h.diff-c.diff);l&&r.push({lineGuide:l.lineGuide,offset:l.offset,orientation:"H",snap:l.snap});}return r}_attachExistingTransformers(){if(!this._core)return;let e=this._core.nodes.layer;this._walkAttachTransformers(e);}_walkAttachTransformers(e){this._attachTransformer(e);let t=e,n=typeof t.getChildren=="function"?t.getChildren():[];for(let o of n)this._walkAttachTransformers(o);}_attachTransformer(e){let t=e;if((typeof t.getClassName=="function"?t.getClassName():"")!=="Transformer")return;let o=e;o.off(".snap-guides-resize"),o.on("transform.snap-guides-resize",()=>{this._handleTransformerTransform(o);}),o.on("transformend.snap-guides-resize",()=>{this._clearGuides();});}_walkDetachTransformers(e){let t=e;(typeof t.getClassName=="function"?t.getClassName():"")==="Transformer"&&e.off(".snap-guides-resize");let o=typeof t.getChildren=="function"?t.getChildren():[];for(let s of o)this._walkDetachTransformers(s);}_handleTransformerTransform(e){if(!this._core||!this._layer)return;if((typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"")==="rotater"||this._isVisualLinesShouldCleared(e)){this._clearGuides();return}let o=(typeof e.nodes=="function"?e.nodes():[])[0];if(!o)return;let s=o,r=typeof s.getLayer=="function"?s.getLayer():null;if(!r||r!==this._core.nodes.layer)return;this._clearGuides();let l=this._getLineGuideStops(o),h=this._getObjectSnappingEdges(o),c=this._getGuides(l,h);if(!c.length)return;let d=o.absolutePosition();for(let u of c)u.orientation==="V"?d.x=u.lineGuide+u.offset:d.y=u.lineGuide+u.offset;o.absolutePosition(d),this._drawResizeGuides(e,o,c);}_drawResizeGuides(e,t,n){if(!this._core||!this._layer)return;let o=typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"";if(!o)return;let s=t.getClientRect({skipShadow:true,skipStroke:false}),r=n.some(p=>p.orientation==="V"),l=n.some(p=>p.orientation==="H"),c=this._buildResizeRays(o,s).filter(p=>!((p.dir==="left"||p.dir==="right")&&!l||(p.dir==="up"||p.dir==="down")&&!r));if(!c.length)return;let d=this._collectOtherNodeBoxes(t);if(!d.length)return;let u=16;for(let p of c){let f=[];for(let v of d){let w=this._intersectRayWithBox(p.origin,p.dir,v.box);w&&f.push({...w,box:v.box});}if(!f.length)continue;f.sort((v,w)=>v.tEnter-w.tEnter);let g=f.slice(0,u);if(!g.length)continue;let m=0;for(let v of g)v.tExit>m&&(m=v.tExit);if(m<=0)continue;let _;p.dir==="right"?_=[0,0,m,0]:p.dir==="left"?_=[0,0,-m,0]:p.dir==="down"?_=[0,0,0,m]:_=[0,0,0,-m];let b=new G.Line({points:_,stroke:this._options.guidelineColor,strokeWidth:this._options.guidelineWidth,name:"snap-guid-line",dash:this._options.guidelineDash,listening:false});this._layer.add(b),b.absolutePosition({x:p.origin.x,y:p.origin.y});for(let v of g){let w=v.tEnter,x=v.tExit,N=this._pointOnRay(p.origin,p.dir,w),k=this._pointOnRay(p.origin,p.dir,x),S=v.box,C=0,T=0;if(p.dir==="right"){let K=s.x+s.width,L=S.x,B=S.x+S.width;C=L-K,T=B-K;}else if(p.dir==="left"){let K=s.x,L=S.x,B=S.x+S.width;C=K-B,T=K-L;}else if(p.dir==="down"){let K=s.y+s.height,L=S.y,B=S.y+S.height;C=L-K,T=B-K;}else {let K=s.y,L=S.y,B=S.y+S.height;C=K-B,T=K-L;}C=Math.max(0,C),T=Math.max(0,T),this._drawRayMarkerWithLabel(N.x,N.y,C,p.dir),this._drawRayMarkerWithLabel(k.x,k.y,T,p.dir);}}this._layer.batchDraw();}_buildResizeRays(e,t){let n={x:t.x,y:t.y},o={x:t.x+t.width,y:t.y},s={x:t.x+t.width,y:t.y+t.height},r={x:t.x,y:t.y+t.height},l=[];switch(e){case "top-left":l.push({origin:n,dir:"up"},{origin:n,dir:"left"});break;case "top-right":l.push({origin:o,dir:"up"},{origin:o,dir:"right"});break;case "bottom-right":l.push({origin:s,dir:"down"},{origin:s,dir:"right"});break;case "bottom-left":l.push({origin:r,dir:"down"},{origin:r,dir:"left"});break;case "middle-left":l.push({origin:n,dir:"up"},{origin:n,dir:"left"});break;case "middle-right":l.push({origin:o,dir:"up"},{origin:o,dir:"right"});break;case "top-center":l.push({origin:n,dir:"up"},{origin:n,dir:"left"});break;case "bottom-center":l.push({origin:r,dir:"down"},{origin:r,dir:"left"});break;}return l}_isVisualLinesShouldCleared(e){let t=e;for(;t;){let n=t,o=typeof n.name=="function"?n.name():"";if(o.startsWith("rotate-")||o==="rotate-handles-group"||o.startsWith("corner-radius-")||o==="corner-radius-handles-group")return true;t=t.getParent();}return false}};var Ft=class extends he{constructor(e={}){super();a(this,"mode");a(this,"intensity");a(this,"pixelRatio");a(this,"nodes",new WeakMap);this.mode=e.mode??"sepia";let t=e.intensity??.4;this.intensity=Math.max(0,Math.min(1,t)),this.pixelRatio=e.pixelRatio??3;}onAttach(e){if(this.nodes.has(e))return;let t=e.getKonvaNode(),n=t.filters(),o=Array.isArray(n)?n:[],s=t,r=typeof s.red=="function"?s.red():0,l=typeof s.green=="function"?s.green():0,h=typeof s.blue=="function"?s.blue():0,c=typeof s.alpha=="function"?s.alpha():1,d=typeof s.hue=="function"?s.hue():0,u=typeof s.saturation=="function"?s.saturation():0,p=typeof s.luminance=="function"?s.luminance():0,f={prevFilters:[...o],prevRed:r,prevGreen:l,prevBlue:h,prevAlpha:c,prevHue:d,prevSaturation:u,prevLuminance:p,mouseEnterHandler:()=>{},mouseLeaveHandler:()=>{},hadHover:false};f.mouseEnterHandler=()=>{if(f.hadHover=true,t.cache({pixelRatio:this.pixelRatio}),this.mode==="sepia"){let g=t.filters(),m=Array.isArray(g)?g:[];m.includes(G.Filters.Sepia)||t.filters([...m,G.Filters.Sepia]);}else {let g=t.filters(),m=Array.isArray(g)?g:[];m.includes(G.Filters.HSL)||t.filters([...m,G.Filters.HSL]);let _=this.intensity,b=18,v=.2,w=b*_,x=v*_;switch(this.mode){case "warm":{typeof s.hue=="function"&&s.hue(f.prevHue+w),typeof s.saturation=="function"&&s.saturation(f.prevSaturation+x);break}case "cool":{typeof s.hue=="function"&&s.hue(f.prevHue-w),typeof s.saturation=="function"&&s.saturation(f.prevSaturation+x);break}}}t.getLayer()?.batchDraw();},f.mouseLeaveHandler=()=>{f.hadHover&&(t.filters(f.prevFilters),(this.mode==="warm"||this.mode==="cool")&&(typeof s.red=="function"&&s.red(f.prevRed),typeof s.green=="function"&&s.green(f.prevGreen),typeof s.blue=="function"&&s.blue(f.prevBlue),typeof s.alpha=="function"&&s.alpha(f.prevAlpha),typeof s.hue=="function"&&s.hue(f.prevHue),typeof s.saturation=="function"&&s.saturation(f.prevSaturation),typeof s.luminance=="function"&&s.luminance(f.prevLuminance)),t.getLayer()?.batchDraw(),t.clearCache());},t.on("mouseenter.imageHoverFilterAddon",f.mouseEnterHandler),t.on("mouseleave.imageHoverFilterAddon",f.mouseLeaveHandler),this.nodes.set(e,f);}onDetach(e){let t=this.nodes.get(e);if(!t)return;let n=e.getKonvaNode();n.off("mouseenter.imageHoverFilterAddon",t.mouseEnterHandler),n.off("mouseleave.imageHoverFilterAddon",t.mouseLeaveHandler),n.filters(t.prevFilters);let o=n;(this.mode==="warm"||this.mode==="cool")&&(typeof o.red=="function"&&o.red(t.prevRed),typeof o.green=="function"&&o.green(t.prevGreen),typeof o.blue=="function"&&o.blue(t.prevBlue),typeof o.alpha=="function"&&o.alpha(t.prevAlpha)),n.getLayer()?.batchDraw(),n.clearCache(),this.nodes.delete(e);}};var zt=class extends oe{constructor(e={}){super();a(this,"_options");a(this,"_instance",null);a(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let n=t.plugins.list().find(s=>s instanceof be);if(n){this._instance=n,this._owned=false;return}let o=new be(this._options);t.plugins.addPlugins([o]),this._instance=o,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Wt=class extends oe{constructor(e={}){super();a(this,"_options");a(this,"_instance",null);a(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let n=t.plugins.list().find(s=>s instanceof Re);if(n){this._instance=n,this._owned=false;return}let o=new Re(this._options);t.plugins.addPlugins([o]),this._instance=o,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Ut=class extends oe{constructor(e={}){super();a(this,"_options");a(this,"_instance",null);a(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let n=t.plugins.list().find(s=>s instanceof Me);if(n){this._instance=n,this._owned=false;return}let o=new Me(this._options);t.plugins.addPlugins([o]),this._instance=o,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Vt=class extends he{constructor(e={}){super();a(this,"stroke");a(this,"strokeWidth");a(this,"fill");a(this,"mode");a(this,"nodes",new WeakMap);this.stroke=e.stroke??"#1976d2",this.strokeWidth=e.strokeWidth??2,this.fill=e.fill??"rgba(255, 255, 0, 0.25)",this.mode=e.mode??"stroke";}onAttach(e){if(this.nodes.has(e))return;let t=e.getKonvaNode(),n={mouseEnterHandler:()=>{},mouseLeaveHandler:()=>{},prevStroke:e.getStroke(),prevStrokeWidth:e.getStrokeWidth(),prevStrokeEnabled:t.strokeEnabled(),prevFill:t.fill(),prevFillEnabled:t.fillEnabled(),hadHover:false};n.mouseEnterHandler=()=>{n.prevStroke=e.getStroke(),n.prevStrokeWidth=e.getStrokeWidth(),n.prevStrokeEnabled=t.strokeEnabled(),n.prevFill=t.fill(),n.prevFillEnabled=t.fillEnabled(),n.hadHover=true,(this.mode==="stroke"||this.mode==="both")&&(t.strokeEnabled(true),t.stroke(this.stroke),t.strokeWidth(this.strokeWidth)),(this.mode==="fill"||this.mode==="both")&&(t.fillEnabled(true),t.fill(this.fill)),t.getLayer()?.batchDraw();},n.mouseLeaveHandler=()=>{n.hadHover&&(t.strokeEnabled(n.prevStrokeEnabled),typeof n.prevStroke=="string"&&t.stroke(n.prevStroke),t.strokeWidth(n.prevStrokeWidth),t.fillEnabled(n.prevFillEnabled),typeof n.prevFill=="string"&&t.fill(n.prevFill),t.getLayer()?.batchDraw());},t.on("mouseenter.shapeHoverHighlightAddon",n.mouseEnterHandler),t.on("mouseleave.shapeHoverHighlightAddon",n.mouseLeaveHandler),this.nodes.set(e,n);}onDetach(e){let t=this.nodes.get(e);if(!t)return;let n=e.getKonvaNode();n.off("mouseenter.shapeHoverHighlightAddon",t.mouseEnterHandler),n.off("mouseleave.shapeHoverHighlightAddon",t.mouseLeaveHandler),t.hadHover&&(n.strokeEnabled(t.prevStrokeEnabled),typeof t.prevStroke=="string"&&n.stroke(t.prevStroke),n.strokeWidth(t.prevStrokeWidth),n.fillEnabled(t.prevFillEnabled),typeof t.prevFill=="string"&&n.fill(t.prevFill),n.getLayer()?.batchDraw()),this.nodes.delete(e);}};var Xt=class extends he{constructor(){super(...arguments);a(this,"nodes",new WeakMap);}onAttach(e){if(this.nodes.has(e))return;let t=n=>{if(n.cancelled)return;let o=this.normalize(n.newText);o!==n.newText&&(e.setText(o),e.getKonvaNode().getLayer()?.batchDraw());};e.onTextChange(t),this.nodes.set(e,{handler:t});}onDetach(e){let t=this.nodes.get(e);t&&(e.offTextChange(t.handler),this.nodes.delete(e));}normalize(e){return e?e.replace(/[ \t]+/g," ").trim():""}};var Mn={desktopFrame:{width:1920,height:1080,template:"Figma desktop",label:"Desktop"}};export{St as AreaSelectionPlugin,Ct as CameraHotkeysPlugin,Ae as CameraManager,Et as ContentFromClipboardPlugin,xt as CoreEngine,ye as DebounceHelper,Be as EventBus,M as FrameNode,Pt as GridPlugin,Ie as HistoryManager,Kt as HistoryPlugin,Ft as ImageHoverFilterAddon,Mt as LogoPlugin,ce as MediaPlaceholder,he as NodeAddon,Le as NodeAddons,Bt as NodeHotkeysPlugin,De as NodeManager,It as PersistencePlugin,Ve as PersistenceStorage,oe as PluginAddon,Oe as Plugins,zt as RulerGuidesAddon,be as RulerGuidesPlugin,Wt as RulerHighlightAddon,Re as RulerHighlightPlugin,Ut as RulerManagerAddon,Me as RulerManagerPlugin,Gt as RulerPlugin,we as SelectionPlugin,Vt as ShapeHoverHighlightAddon,Xt as TextAutoTrimAddon,ve as ThrottleHelper,Ge as VideoOverlayAddon,Ht as VisualGuidesPlugin,Ot as createBlobUrlMap,vt as deserializeCanvas,Lt as exportCanvasToJSON,on as extractBlobs,Mn as frameTemplates,Dt as importCanvasFromJSON,Ue as revokeBlobUrls,_t as serializeCanvas};