@flowscape-ui/core-sdk 1.0.3 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1 +1,57 @@
1
- 'use strict';var M=require('konva');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var M__default=/*#__PURE__*/_interopDefault(M);var Ct=Object.defineProperty;var Tt=(C,n,e)=>n in C?Ct(C,n,{enumerable:true,configurable:true,writable:true,value:e}):C[n]=e;var a=(C,n,e)=>Tt(C,typeof n!="symbol"?n+"":n,e);var Ae=class{constructor(){a(this,"_listeners");this._listeners=new Map;}get listeners(){return this._listeners}on(n,e){this._listeners.has(n)||this._listeners.set(n,[]),this._listeners.get(n).push(e);}off(n,e){let t=this._listeners.get(n);t&&this._listeners.set(n,t.filter(o=>o!==e));}once(n,e){let t=((...o)=>{this.off(n,t),e(...o);});this.on(n,t);}emit(n,...e){let t=this._listeners.get(n);t&&[...t].forEach(o=>{o(...e);});}};var Ee=class{constructor(n){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=n.stage,this._eventBus=n.eventBus,this._target=n.target??n.stage,this._scale=n.initialScale??1,this._minScale=n.minScale??.1,this._maxScale=n.maxScale??5,this._zoomStep=n.zoomStep??1.05,this._panStep=n.panStep??40,this._initWheelZoom();}_initWheelZoom(){this._stage.on("wheel",n=>{if(n.evt.preventDefault(),this._pendingWheelEvent=n.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(n){let e=this._target.scaleX()||1,t=this._stage.getPointerPosition();if(!t)return;let o=this._zoomStep,s=(n.deltaY>0?-1:1)>0?e*o:e/o;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(n){this._scale=Math.max(this._minScale,Math.min(this._maxScale,n)),this._target.scale({x:this._scale,y:this._scale}),this._stage.batchDraw(),this._eventBus.emit("camera:setZoom",{scale:this._scale});}zoomIn(n){n===void 0?this.setZoom(this._scale*this._zoomStep):this.setZoom(this._scale+n);}zoomOut(n){n===void 0?this.setZoom(this._scale/this._zoomStep):this.setZoom(this._scale-n);}reset(){this.setZoom(1),this._target.position({x:0,y:0}),this._stage.batchDraw(),this._eventBus.emit("camera:reset");}setDraggable(n){this._stage.draggable(n);}setZoomStep(n){n&&n>0&&(this._zoomStep=n,this._eventBus.emit("camera:zoomStep",{zoomStep:n}));}setPanStep(n){typeof n=="number"&&isFinite(n)&&(this._panStep=n,this._eventBus.emit("camera:panStep",{panStep:n}));}};var Pe=class{constructor(n){a(this,"_node");a(this,"_addons",new Set);this._node=n;}add(n){let e=Array.isArray(n)?n:[n];for(let t of e)this._addons.has(t)||(this._addons.add(t),t.attach(this._node));return this._node}remove(n){let e=Array.isArray(n)?n:[n];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(n){return this._addons.has(n)}clear(){this._addons.forEach(n=>{n.detach(this._node);}),this._addons.clear();}};var O=class{constructor(n,e={}){a(this,"konvaNode");a(this,"id");a(this,"addons");this.konvaNode=n,this.id=e.id??`node_${String(Date.now())}_${String(Math.random())}`,this.addons=new Pe(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:n,y:e}){return this.konvaNode.position({x:n,y:e}),this}getPosition(){return this.konvaNode.position()}remove(){this.addons.clear(),this.konvaNode.destroy();}};var Oe=class extends O{constructor(n={}){let e=new M__default.default.Arc({});e.x(n.x??0),e.y(n.y??0),e.innerRadius(n.innerRadius??0),e.outerRadius(n.outerRadius??0),e.angle(n.angle??0),e.rotation(n.rotation??0),n.clockwise!==void 0&&e.clockwise(n.clockwise),e.fill(n.fill??"black"),e.stroke(n.stroke??"black"),e.strokeWidth(n.strokeWidth??0),super(e,n);}getInnerRadius(){return this.konvaNode.innerRadius()}getOuterRadius(){return this.konvaNode.outerRadius()}getAngle(){return this.konvaNode.angle()}isClockwise(){return this.konvaNode.clockwise()}setInnerRadius(n){return this.konvaNode.innerRadius(n),this}setOuterRadius(n){return this.konvaNode.outerRadius(n),this}setAngle(n){return this.konvaNode.angle(n),this}setRotationDeg(n){return this.konvaNode.rotation(n),this}setClockwise(n){return this.konvaNode.clockwise(n),this}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}};var Ie=class extends O{constructor(n={}){let e=new M__default.default.Arrow({});e.x(n.x??0),e.y(n.y??0),e.points(n.points??[]),n.tension&&e.tension(n.tension),n.pointerLength&&e.pointerLength(n.pointerLength),n.pointerWidth&&e.pointerWidth(n.pointerWidth),n.pointerAtBeginning&&e.pointerAtBeginning(n.pointerAtBeginning),n.pointerAtEnding&&e.pointerAtEnding(n.pointerAtEnding),e.fill(n.fill??"black"),e.stroke(n.stroke??"black"),e.strokeWidth(n.strokeWidth??0),super(e,n);}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(n){return this.konvaNode.points(n),this}setTension(n){return this.konvaNode.tension(n),this}setPointerLength(n){return this.konvaNode.pointerLength(n),this}setPointerWidth(n){return this.konvaNode.pointerWidth(n),this}setPointerAtBeginning(n){return this.konvaNode.pointerAtBeginning(n),this}setPointerAtEnding(n){return this.konvaNode.pointerAtEnding(n),this}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}};var ze=class extends O{constructor(n={}){let e=new M__default.default.Circle({});e.x(n.x??0),e.y(n.y??0),e.radius(n.radius??0),e.fill(n.fill??"black"),e.stroke(n.stroke??"black"),e.strokeWidth(n.strokeWidth??0),e.draggable(true),super(e,n);}getRadius(){return this.konvaNode.radius()}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}setRadius(n){return this.konvaNode.radius(n),this}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}};var We=class extends O{constructor(n={}){let e=new M__default.default.Ellipse({});e.x(n.x??0),e.y(n.y??0),e.radiusX(n.radiusX??0),e.radiusY(n.radiusY??0),e.fill(n.fill??"black"),e.stroke(n.stroke??"black"),e.strokeWidth(n.strokeWidth??0),super(e,n);}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(n){return this.konvaNode.radiusX(n),this}setRadiusY(n){return this.konvaNode.radiusY(n),this}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}};var de=class extends O{constructor(n={}){let e=new M__default.default.Group({});e.x(n.x??0),e.y(n.y??0),e.draggable(n.draggable??true),n.listening!==void 0&&e.listening(n.listening),n.clip&&e.clip(n.clip),super(e,n);}addChild(n){let e=n.getKonvaNode?n.getKonvaNode():n;return this.konvaNode.add(e),this.konvaNode.getLayer()?.batchDraw(),this}removeChild(n){return (n.getKonvaNode?n.getKonvaNode():n).remove(),this.konvaNode.getLayer()?.batchDraw(),this}removeAllChildren(){return this.konvaNode.removeChildren(),this.konvaNode.getLayer()?.batchDraw(),this}getChildren(){return this.konvaNode.getChildren()}findByName(n){return this.konvaNode.find(`.${n}`)}setDraggable(n){return this.konvaNode.draggable(n),this}isDraggable(){return this.konvaNode.draggable()}setListening(n){return this.konvaNode.listening(n),this}isListening(){return this.konvaNode.listening()}setClip(n){return this.konvaNode.clip(n),this.konvaNode.getLayer()?.batchDraw(),this}};var Xe=class extends O{constructor(n={}){let e=new M__default.default.Image({});e.x(n.x??0),e.y(n.y??0),e.width(n.width??150),e.height(n.height??150),e.image(n.image??null),super(e,n),!n.image&&n.src&&this.setSrc(n.src);}getSize(){return this.konvaNode.size()}async setSrc(n,e="anonymous"){let t=await this._loadHTMLImage(n,e);return this.konvaNode.image(t),this.konvaNode.getLayer()?.batchDraw(),this}setImage(n){return this.konvaNode.image(n),this.konvaNode.getLayer()?.batchDraw(),this}setSize({width:n,height:e}){return this.konvaNode.size({width:n,height:e}),this}setCornerRadius(n){return this.konvaNode.cornerRadius(n),this}getCornerRadius(){return this.konvaNode.cornerRadius()}_loadHTMLImage(n,e="anonymous"){return new Promise((t,o)=>{let i=globalThis.Image??null;if(!i){o(new Error("Image constructor is not available in current environment"));return}let s=new i,r=e;s.crossOrigin=r,s.onload=()=>{t(s);},s.onerror=()=>{o(new Error(`Failed to load image: ${n}`));},s.src=n;})}};var Ye=class extends O{constructor(n={}){let e=new M__default.default.RegularPolygon({});e.x(n.x??0),e.y(n.y??0),e.sides(n.sides??3),e.radius(n.radius??60),e.fill(n.fill??"black"),e.stroke(n.stroke??"black"),e.strokeWidth(n.strokeWidth??0),super(e,n);}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(n){return this.konvaNode.sides(n),this}setRadius(n){return this.konvaNode.radius(n),this}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}};var Fe=class extends O{constructor(n={}){let e=new M__default.default.Ring({});e.x(n.x??0),e.y(n.y??0),e.innerRadius(n.innerRadius??20),e.outerRadius(n.outerRadius??40),e.fill(n.fill??"black"),e.stroke(n.stroke??"black"),e.strokeWidth(n.strokeWidth??0),super(e,n);}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(n){return this.konvaNode.innerRadius(n),this}setOuterRadius(n){return this.konvaNode.outerRadius(n),this}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}};var Ue=class extends O{constructor(n){let e=new M__default.default.Rect({x:n.x??0,y:n.y??0,width:n.width??100,height:n.height??100,fill:n.fill??"lightgray",stroke:n.stroke??"black",strokeWidth:n.strokeWidth??1,cornerRadius:n.cornerRadius??0,draggable:true});super(e,n);}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}setCornerRadius(n){return this.konvaNode.cornerRadius(n),this}setSize({width:n,height:e}){return this.konvaNode.size({width:n,height:e}),this}getFill(){return this.konvaNode.fill()}getStroke(){return this.konvaNode.stroke()}getStrokeWidth(){return this.konvaNode.strokeWidth()}getCornerRadius(){return this.konvaNode.cornerRadius()}};var Ve=class extends O{constructor(n={}){let e=new M__default.default.Star({});e.x(n.x??0),e.y(n.y??0),e.numPoints(n.numPoints??5),e.innerRadius(n.innerRadius??20),e.outerRadius(n.outerRadius??40),e.fill(n.fill??"black"),e.stroke(n.stroke??"black"),e.strokeWidth(n.strokeWidth??0),super(e,n);}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(n){return this.konvaNode.numPoints(n),this}setInnerRadius(n){return this.konvaNode.innerRadius(n),this}setOuterRadius(n){return this.konvaNode.outerRadius(n),this}setFill(n){return this.konvaNode.fill(n),this}setStroke(n){return this.konvaNode.stroke(n),this}setStrokeWidth(n){return this.konvaNode.strokeWidth(n),this}};var xe=class extends O{constructor(e={}){let t=new M__default.default.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);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 M__default.default.Group&&t instanceof M__default.default.Group)){this._openTextarea();return}if(!this._groupEditClickResetAttached){let i=this.konvaNode.getStage();i&&(this._groupEditClickResetAttached=true,i.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(),o=Math.max(1,this.konvaNode.width()*e);this.konvaNode.width(o);let i=this.konvaNode.height(),s=Math.max(1,i*t);this.konvaNode.height(s),this.konvaNode.scaleX(1),this.konvaNode.scaleY(1);});}_syncTextareaPosition(){if(!this._isEditing||!this._textarea)return;let e=this.konvaNode.getStage();if(!e)return;let t=this.konvaNode.absolutePosition(),o=e.container().getBoundingClientRect(),i=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)*i.x)+"px",this._textarea.style.fontSize=String(this.konvaNode.fontSize()*i.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.konvaNode.hide(),e.batchDraw();let t=this.konvaNode.absolutePosition(),o=e.container().getBoundingClientRect(),i=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(o.top+t.y)+"px",s.style.left=String(o.left+t.x)+"px",s.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*i.x)+"px",s.style.fontSize=String(this.konvaNode.fontSize()*i.x)+"px",s.style.border="none",s.style.padding="0",s.style.margin="0",s.style.overflow="hidden",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 d=this.konvaNode.rotation();d&&(s.style.transform="rotateZ("+String(d)+"deg)"),s.style.height="auto",s.focus(),s.select(),this._syncTextareaRafId=globalThis.requestAnimationFrame(()=>{this._syncTextareaPosition();});for(let c of this._onEditStartCallbacks)c();this._keyHandler=c=>{if(c.key==="Enter"&&(c.ctrlKey||c.metaKey)){c.preventDefault(),this._saveAndClose(false);return}if(c.key==="Escape"){c.preventDefault(),this._saveAndClose(true);return}globalThis.requestAnimationFrame(()=>{this._textarea&&(this._textarea.style.height="auto",this._textarea.style.height=String(this._textarea.scrollHeight+this.konvaNode.fontSize())+"px");});},this._clickHandler=c=>{c.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;if(this.konvaNode.text(t),!e){let o=this._textarea,i=this.konvaNode.getAbsoluteScale(),s=i.x||i.y||1,r=o.scrollHeight/s,l=this.konvaNode.height();Number.isFinite(r)&&r>l&&this.konvaNode.height(r);}this._syncTextareaRafId!==null&&(globalThis.cancelAnimationFrame(this._syncTextareaRafId),this._syncTextareaRafId=null),this._keyHandler&&this._textarea.removeEventListener("keydown",this._keyHandler),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.konvaNode.show(),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 Re=class{constructor(n,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 M__default.default.Layer,this._world=new M__default.default.Group,this._layer.add(this._world),this._stage=n,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(n){let e=new Ue(n);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(n){let e=new xe(n);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(n){let e=new Xe(n);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(n){let e=new ze(n);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(n){let e=new We(n);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(n){let e=new Oe(n);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(n){let e=new Ve(n);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(n){let e=new Ie(n);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(n){let e=new Fe(n);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(n){let e=new Ye(n);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(n){let e=new de(n);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(n){this._eventBus.emit("node:removed",n),n.remove(),this._nodes.delete(n.id),this._listCacheInvalidated=true,this._scheduleBatchDraw();}findById(n){return this._nodes.get(n)}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 n=globalThis.requestAnimationFrame;n(()=>{this._batchDrawScheduled=false,this._layer.batchDraw();});}};var pe=class{constructor(n=16){a(this,"_lastTime",0);a(this,"_throttle");this._throttle=n;}shouldExecute(){let n=Date.now();return n-this._lastTime<this._throttle?false:(this._lastTime=n,true)}reset(){this._lastTime=0;}setThrottle(n){this._throttle=n;}getThrottle(){return this._throttle}};var je=class{constructor(n={}){a(this,"_enabled");a(this,"_levels");a(this,"_currentScale",1);a(this,"_appliedNodes",new Map);this._enabled=n.enabled??true,this._levels=n.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(n){return this._enabled?this._levels.find(t=>n>=t.minScale&&n<t.maxScale)??null:null}applyLOD(n,e){if(!this._enabled)return;this._currentScale=e;let t=this._getLODLevel(e);if(!t?.simplify){this._restoreNode(n);return}let o=n.getKonvaNode(),i=this._appliedNodes.get(n.id);i!==t&&(i||(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(n.id,t));}_restoreNode(n){let e=n.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(n.id),delete e._originalLOD);}applyToAll(n,e){if(this._enabled)for(let t of n)this.applyLOD(t,e);}restoreAll(n){for(let e of n)this._restoreNode(e);this._appliedNodes.clear();}enable(){this._enabled=true;}disable(n){this._enabled=false,this.restoreAll(n);}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(n){this._levels=n;}};var Ze=class{constructor(n,e,t,o={}){this._stage=n;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,"_updateScheduled",false);a(this,"_lod",null);this._enabled=o.enabled??true,this._bufferZone=o.bufferZone??200,this._throttle=new pe(o.throttleMs??16),o.lod&&(this._lod=new je(o.lod)),this._updateViewport(),this._setupListeners(),this._enabled&&this.updateVisibility();}_updateViewport(){let n=this._world.scaleX(),e=this._world.position();this._viewport={x:-e.x/n-this._bufferZone,y:-e.y/n-this._bufferZone,width:this._stage.width()/n+this._bufferZone*2,height:this._stage.height()/n+this._bufferZone*2};}_getNodeBBox(n){let t=n.getKonvaNode().getClientRect({relativeTo:this._world});return {x:t.x,y:t.y,width:t.width,height:t.height}}_isNodeVisible(n){let e=this._getNodeBBox(n);return !(e.x+e.width<this._viewport.x||e.x>this._viewport.x+this._viewport.width||e.y+e.height<this._viewport.y||e.y>this._viewport.y+this._viewport.height)}updateVisibility(){if(!this._enabled||!this._throttle.shouldExecute())return;let n=this._nodeManager.list(),e=new Set,t=0;for(let o of n){let i=this._isNodeVisible(o),s=o.getKonvaNode();i?(e.add(o.id),this._hiddenNodes.has(o.id)&&(s.visible(true),s.listening(true),this._hiddenNodes.delete(o.id),t++)):this._hiddenNodes.has(o.id)||(s.visible(false),s.listening(false),this._hiddenNodes.add(o.id),t++);}if(this._visibleNodes=e,this._lod?.enabled&&t>0){let o=this._world.scaleX();for(let i of n)e.has(i.id)&&this._lod.applyLOD(i,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",n=>{this._visibleNodes.delete(n.id),this._hiddenNodes.delete(n.id);});}_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 n of this._hiddenNodes){let e=this._nodeManager.findById(n);if(e){let t=e.getKonvaNode();t.visible(true),t.listening(true);}}this._hiddenNodes.clear(),this._visibleNodes.clear(),this._nodeManager.layer.batchDraw();}}getStats(){let n=this._nodeManager.list().length,e=this._visibleNodes.size,t=this._hiddenNodes.size;return {total:n,visible:e,hidden:t,cullingRate:n>0?t/n*100:0}}setBufferZone(n){this._bufferZone=n,this._updateViewport(),this._scheduleUpdate();}setThrottle(n){this._throttle=new pe(n);}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 n=this._nodeManager.list();this._lod.restoreAll(n);}}};var qe=class{constructor(n){a(this,"_plugin");a(this,"_addons",new Set);a(this,"_core");this._plugin=n;}_attachAll(n){this._core=n,this._addons.forEach(e=>{e.attach(this._plugin,n);});}_detachAll(n){this._addons.forEach(e=>{e.detach(this._plugin,n);}),this._core=void 0;}add(n){let e=Array.isArray(n)?n:[n];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(n){let e=Array.isArray(n)?n:[n];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(n){return this._addons.has(n)}clear(){if(this._core){let n=this._core;this._addons.forEach(e=>{e.detach(this._plugin,n);});}this._addons.clear();}};var H=class{constructor(){a(this,"addons");this.addons=new qe(this);}attach(n){this.onAttach(n),this.addons._attachAll(n);}detach(n){this.addons._detachAll(n),this.onDetach(n);}};var Be=class{constructor(n,e=[]){a(this,"_core");a(this,"_items",[]);this._core=n,e.length&&this.addPlugins(e);}addPlugins(n){let e=[];for(let t of n)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(n){let e=[];for(let t of n){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 n=[...this._items];for(let e of n)e.detach(this._core);this._items=[];for(let e of n)this._core.eventBus.emit("plugin:removed",e.constructor.name);return n}list(){return [...this._items]}get(n){return this._items.find(e=>e.constructor.name===n)}};var ot=class{constructor(n){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 n=this.container.offsetWidth,e=this.container.offsetHeight;(n!==this._stage.width()||e!==this._stage.height())&&this.setSize({width:n,height:e});});this.container=n.container,this._initialWidth=n.width??800,this._initialHeight=n.height??800,this._autoResize=n.autoResize??true,this._backgroundColor=n.backgroundColor??"#1e1e1e",this._draggable=n.draggable??true,this._minScale=n.minScale??.1,this._maxScale=n.maxScale??500,this._stage=new M__default.default.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 Ae,this._gridLayer=new M__default.default.Layer({listening:false}),this._stage.add(this._gridLayer),this.nodes=new Re(this._stage,this._eventBus),this.camera=new Ee({stage:this._stage,target:this.nodes.world,eventBus:this._eventBus,initialScale:1,draggable:false,minScale:this._minScale,maxScale:this._maxScale}),this.virtualization=new Ze(this._stage,this.nodes.world,this.nodes,n.virtualization),this.plugins=new Be(this),n.plugins?.length&&this.plugins.addPlugins(n.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:n,height:e}){this._stage.size({width:n,height:e}),this._stage.fire("resize"),this._eventBus.emit("stage:resized",{width:n,height:e});}setBackgroundColor(n){this.container.style.background=n;}setDraggable(n){this._stage.draggable(n),this._draggable=n;}setAutoResize(n){this._autoResize!==n&&(this._autoResize=n,n?(this._setupAutoResize(),this._handleResize()):this._resizeObserver?(this._resizeObserver.disconnect(),this._resizeObserver=null):globalThis.removeEventListener("resize",this._handleResize));}};var Me=class{constructor(){a(this,"_actions",[]);a(this,"_currentIndex",-1);}push(n){this._currentIndex<this._actions.length-1&&this.pop(this._currentIndex+1),this._actions.push(n),this._currentIndex=this._actions.length-1,this._debug("push",n);}pop(n){if(n<0||n>this._actions.length)return;let e=this._actions.splice(n);this._currentIndex=Math.min(this._currentIndex,this._actions.length-1),this._debug("pop",{fromIndex:n,removedCount:e.length});}select(n){if(n<-1||n>=this._actions.length)return;let e=this._currentIndex;this._currentIndex=n,this._debug("select",{oldIndex:e,newIndex:n});}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 n=this._actions[this._currentIndex];return this._currentIndex--,this._debug("undo",{action:n,newIndex:this._currentIndex}),n??null}redo(){if(!this.canRedo())return this._debug("redo","cannot redo - at end"),null;this._currentIndex++;let n=this._actions[this._currentIndex];return this._debug("redo",{action:n,newIndex:this._currentIndex}),n??null}clear(){this._actions=[],this._currentIndex=-1,this._debug("clear","history cleared");}getAction(n){return n<0||n>=this._actions.length?null:this._actions[n]??null}_debug(n,e){}};var _e=class{constructor(){a(this,"_scheduled",false);}schedule(n){this._scheduled||(this._scheduled=true,globalThis.requestAnimationFrame(()=>{this._scheduled=false,n();}));}isScheduled(){return this._scheduled}cancel(){this._scheduled=false;}};var $e=class{constructor(n){a(this,"deps");this.deps=n;}ensure(n){this.deps.ensureTempMulti(n);}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(n){return this.deps.isInsideTempByTarget?this.deps.isInsideTempByTarget(n):false}};function Ne(C){if(C instanceof M__default.default.Group){let n=C.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false});return {x:n.x,y:n.y,width:n.width,height:n.height}}return {x:0,y:0,width:C.width(),height:C.height()}}function ke(C,n){let{x:e,y:t,width:o,height:i}=n;switch(C){case "top-left":return {x:e+o,y:t+i};case "top-right":return {x:e,y:t+i};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+i/2};case "middle-right":return {x:e,y:t+i/2};case "top-center":return {x:e+o/2,y:t+i};case "bottom-center":return {x:e+o/2,y:t};default:return null}}function fe(C,n,e,t=6){if(!C||!n||!e)return;let o=e.getClientRect({skipShadow:true,skipStroke:false}),i=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),s=e.getAbsoluteScale(),r=Math.abs(s.x)||1,l=Math.abs(s.y)||1,d=i.width*r,c=i.height*l,h=(()=>{let _=e.getAbsoluteTransform().decompose();return typeof _.rotation=="number"?_.rotation:0})(),u=Math.abs((h%180+180)%180)>.5,p=n.findOne(".top-center"),f=n.findOne(".middle-right"),m=n.findOne(".bottom-center"),v=n.findOne(".middle-left");if(p){let _=u?d:o.width,g=t;p.setAttrs({opacity:0,width:_,height:g,offsetX:_/2,offsetY:0});}if(m){let _=u?d:o.width,g=t;m.setAttrs({opacity:0,width:_,height:g,offsetX:_/2,offsetY:g});}if(v){let _=t,g=u?c:o.height;v.setAttrs({opacity:0,width:_,height:g,offsetX:0,offsetY:g/2});}if(f){let _=t,g=u?c:o.height;f.setAttrs({opacity:0,width:_,height:g,offsetX:_,offsetY:g/2});}}function re(C){return new M__default.default.Circle({name:C,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 Je=class{constructor(n){a(this,"core");a(this,"getKonvaNode");a(this,"getTransformer");a(this,"onUpdate");a(this,"group",null);a(this,"handles",{tl:null,tr:null,br:null,bl:null});a(this,"dragState",null);a(this,"centerAbsStart",null);this.core=n.core,this.getKonvaNode=n.getNode,this.getTransformer=n.getTransformer,n.onUpdate&&(this.onUpdate=n.onUpdate);}attach(){if(!this.getKonvaNode())return;let e=this.core.nodes.layer;this.detach();let t=new M__default.default.Group({name:"rotate-handles-group",listening:true});e.add(t),this.group=t;let o=re("rotate-tl"),i=re("rotate-tr"),s=re("rotate-br"),r=re("rotate-bl");t.add(o),t.add(i),t.add(s),t.add(r),this.handles={tl:o,tr:i,br:s,bl:r};let l=d=>{d.on("mouseenter.rotate",()=>{this.core.stage.container().style.cursor="pointer";}),d.on("mouseleave.rotate",()=>{this.core.stage.container().style.cursor="default";}),d.on("dragstart.rotate",()=>{let c=this.getKonvaNode();if(!c)return;let h=c.getAbsoluteTransform().decompose();this.centerAbsStart=this.getNodeCenterAbs(c);let u=this.core.stage.getPointerPosition()??d.getAbsolutePosition(),p=Math.atan2(u.y-this.centerAbsStart.y,u.x-this.centerAbsStart.x)*180/Math.PI;this.dragState={base:h.rotation||0,start:p},this.core.stage.draggable(false),this.core.stage.container().style.cursor="grabbing",this.getTransformer()?.moveToTop(),this.placeBelowTransformer();}),d.on("dragmove.rotate",c=>{let h=this.getKonvaNode();if(!h||!this.dragState)return;let u=this.centerAbsStart??this.getNodeCenterAbs(h),p=this.core.stage.getPointerPosition()??d.getAbsolutePosition(),f=Math.atan2(p.y-u.y,p.x-u.x)*180/Math.PI,m=this.dragState.base+(f-this.dragState.start),v=this.getTransformer();if(c.evt.shiftKey&&v){let g=x=>{let w=x%360;return w<0&&(w+=360),w},b=(x,w)=>g(x-w+180)-180,y=Array.isArray(v.rotationSnaps())?v.rotationSnaps().map(x=>g(x)):void 0,N=typeof v.rotationSnapTolerance=="function"?v.rotationSnapTolerance():5;if(y?.length){let x=g(m),w=m,k=1/0;for(let T of y){let A=Math.abs(b(x,T));A<k&&A<=N&&(w=T,k=A);}k!==1/0&&(m=w);}}if(h.rotation(m),this.centerAbsStart){let g=this.getNodeCenterAbs(h),b=this.centerAbsStart.x-g.x,y=this.centerAbsStart.y-g.y,N=h.getParent();if(N){let x=N.getAbsoluteTransform().copy().invert(),w=x.point({x:g.x,y:g.y}),k=x.point({x:g.x+b,y:g.y+y}),T=h.x()+(k.x-w.x),A=h.y()+(k.y-w.y);h.position({x:T,y:A});}}let _=this.getTransformer();_?.forceUpdate(),_&&fe(this.core,_,h),this.updatePosition(),this.placeBelowTransformer(),this.core.nodes.layer.batchDraw(),this.onUpdate&&this.onUpdate();}),d.on("dragend.rotate",()=>{this.dragState=null,this.centerAbsStart=null,this.core.stage.draggable(false),this.updatePosition(),this.placeBelowTransformer(),this.core.stage.container().style.cursor="pointer",this.onUpdate&&this.onUpdate();});};l(o),l(i),l(s),l(r),this.updatePosition(),this.placeBelowTransformer();}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 n=this.getKonvaNode();if(!n||!this.group)return;let e=n.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),t=e.width,o=e.height;if(t<=0||o<=0)return;let i=n.getAbsoluteTransform().copy(),s=x=>i.point(x),r=12,l=s({x:e.x+t/2,y:e.y+o/2}),d=s({x:e.x,y:e.y}),c=s({x:e.x+t,y:e.y}),h=s({x:e.x+t,y:e.y+o}),u=s({x:e.x,y:e.y+o}),p=x=>{let w=x.x-l.x,k=x.y-l.y,T=Math.hypot(w,k)||1;return {x:w/T,y:k/T}},f=p(d),m=p(c),v=p(h),_=p(u),g={x:d.x+f.x*r,y:d.y+f.y*r},b={x:c.x+m.x*r,y:c.y+m.y*r},y={x:h.x+v.x*r,y:h.y+v.y*r},N={x:u.x+_.x*r,y:u.y+_.y*r};this.handles.tl&&this.handles.tl.absolutePosition(g),this.handles.tr&&this.handles.tr.absolutePosition(b),this.handles.br&&this.handles.br.absolutePosition(y),this.handles.bl&&this.handles.bl.absolutePosition(N),this.placeBelowTransformer();}placeBelowTransformer(){if(!this.group)return;let n=this.getTransformer(),e=this.core.nodes.layer;if(n&&n.getLayer()===e){let t=n.zIndex(),o=this.group.zIndex();if(o>=t){let i=o-t+1;for(let s=0;s<i&&this.group.zIndex()>0;s++)this.group.moveDown();}}else this.group.moveToBottom();}getNodeCenterAbs(n){let e=n.getAbsoluteTransform().copy(),t=n.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),o=t.x+t.width/2,i=t.y+t.height/2;return e.point({x:o,y:i})}};var Qe=class{constructor(n){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=n;}attach(n,e){this.detach(),this.boundNode=n,this.keepRatioPredicate=e?.keepRatioCornerOnlyShift??null;let t=this.core.nodes.layer,o=new M__default.default.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([n]),o.boundBoxFunc((r,l)=>{let c=Math.max(1,Math.abs(l.width)),h=Math.max(1,Math.abs(l.height));return {...l,width:c,height:h}}),this.tr=o,fe(this.core,o,n);let i=()=>{let r=typeof o.getActiveAnchor=="function"?o.getActiveAnchor():"",l=r==="top-left"||r==="top-right"||r==="bottom-left"||r==="bottom-right",d=this.keepRatioPredicate?this.keepRatioPredicate():false;o.keepRatio(l&&d);};o.on("transformstart.overlayKeepRatio",()=>{i();let l=(typeof o.getActiveAnchor=="function"?o.getActiveAnchor():"")??"",d=Ne(n),c=ke(l,d);if(!c){this.transformOppositeCorner=null;return}let h=n.getAbsoluteTransform();this.transformOppositeCorner=h.point({x:c.x,y:c.y});}),o.on("transform.overlayKeepRatio",i);let s=()=>{if(this.boundNode){if(this.transformOppositeCorner){let l=(typeof o.getActiveAnchor=="function"?o.getActiveAnchor():"")??"",d=this.boundNode.getAbsoluteTransform(),c=Ne(this.boundNode),h=ke(l,c);if(!h)return;let u=d.point({x:h.x,y:h.y}),p=this.transformOppositeCorner.x-u.x,f=this.transformOppositeCorner.y-u.y,m=this.boundNode.getParent();if(m&&(Math.abs(p)>.01||Math.abs(f)>.01)){let v=m.getAbsoluteTransform().copy().invert(),_=this.boundNode.getAbsolutePosition(),g={x:_.x+p,y:_.y+f},b=v.point(g);this.boundNode.position(b);}}this.tr?.forceUpdate(),fe(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),t.batchDraw();}};o.on("transform.overlayFrameTransform",s),o.on("transformend.overlayFrameTransform",()=>{this.transformOppositeCorner=null,s();}),this.ensureSizeLabel(),this.updateSizeLabel(),this.updateHitRect(),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null),this.rotateCtrl=new Je({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();}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(),fe(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 n=this.core.nodes.layer;this.sizeLabel&&this.sizeLabel.destroy();let e=new M__default.default.Label({listening:false,opacity:.95}),t=new M__default.default.Tag({fill:"#2b83ff",cornerRadius:4,lineJoin:"round"}),o=new M__default.default.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),n.add(e),this.sizeLabel=e;}updateSizeLabel(){if(!this.boundNode||!this.sizeLabel)return;let n=this.core.nodes.world,e=this.boundNode.getClientRect({skipShadow:true,skipStroke:true}),t=e.width/Math.max(1e-6,n.scaleX()),o=e.height/Math.max(1e-6,n.scaleY()),i=Math.max(0,Math.round(t)),s=Math.max(0,Math.round(o));this.sizeLabel.getText().text(String(i)+" \xD7 "+String(s));let l=8,d=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:d-u/2,y:c}),this.sizeLabel.moveToTop();}updateHitRect(){if(!this.boundNode)return;let n=this.core.nodes.layer,e=this.boundNode.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),t={x:e.x,y:e.y},o=e.width,i=e.height;if(!this.hitRect){let s=new M__default.default.Rect({name:"overlay-hit",x:t.x,y:t.y,width:o,height:i,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 M__default.default.Container?(this.boundNode.add(s),s.moveToBottom(),this.hitRect=s,n.batchDraw()):s.destroy();return}this.hitRect.position(t),this.hitRect.size({width:o,height:i}),this.hitRect.moveToBottom();}};var ve=class extends H{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,"_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,"_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 pe(16));a(this,"_uiUpdateDebounce",new _e);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 _=false;if(this._selected){let g=t.getPointerPosition();if(g){let b=this._selected.getKonvaNode(),y=b.getClientRect({skipShadow:true,skipStroke:false});if(g.x>=y.x&&g.x<=y.x+y.width&&g.y>=y.y&&g.y<=y.y+y.height&&(_=true,typeof b.startDrag=="function")){let x=b,w=3,k=e.evt.clientX,T=e.evt.clientY,A=typeof x.draggable=="function"?x.draggable():false,R=t.draggable(),D=false,B=L=>{let ee=Math.abs(L.evt.clientX-k),j=Math.abs(L.evt.clientY-T);!D&&(ee>w||j>w)&&(D=true,typeof x.draggable=="function"&&!A&&x.draggable(true),b.on("dragstart.selection-once-bbox",()=>{t.draggable(false);}),b.on("dragend.selection-once-bbox",()=>{t.draggable(R),typeof x.draggable=="function"&&x.draggable(this._options.dragEnabled?true:A),this._selected&&(this._refreshTransformer(),this._core?.nodes.layer.batchDraw()),b.off(".selection-once-bbox");}),b.startDrag(),e.cancelBubble=true);},K=()=>{!D&&this._options.deselectOnEmptyClick&&this._clearSelection(),t.off("mousemove.selection-once-bbox"),t.off("mouseup.selection-once-bbox");};t.on("mousemove.selection-once-bbox",B),t.on("mouseup.selection-once-bbox",K);}}}_||this._options.deselectOnEmptyClick&&this._clearSelection();return}let i=e.target;if(!this._options.selectablePredicate(i))return;let s=this._findBaseNodeByTarget(i);if(!s)return;if(this._selected){let _=this._selected.getKonvaNode();((b,y)=>{let N=y;for(;N;){if(N===b)return true;N=N.getParent();}return false})(_,i)&&(s=this._selected);}let r=s.getKonvaNode();r instanceof M__default.default.Group&&this._disableGroupChildrenDragging(r);let l=3,d=e.evt.clientX,c=e.evt.clientY,h=false,u=_=>{if(h)return;let g=Math.abs(_.evt.clientX-d),b=Math.abs(_.evt.clientY-c);(g>l||b>l)&&(h=true,typeof r.startDrag=="function"&&r.startDrag(),this._core?.stage.off("mousemove.selection-once"),this._core?.stage.off("mouseup.selection-once"));},p=()=>{this._core?.stage.off("mousemove.selection-once"),this._core?.stage.off("mouseup.selection-once");};if(this._core.stage.on("mousemove.selection-once",u),this._core.stage.on("mouseup.selection-once",p),typeof r.isDragging=="function"&&r.isDragging())return;let f=typeof r.draggable=="function",m=f?r.draggable():false,v=t.draggable();f&&r.draggable(true),r.on("dragstart.selection-once",()=>{t.draggable(false);}),r.on("dragend.selection-once",()=>{t.draggable(v),f&&(this._options.dragEnabled?r.draggable(true):r.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,i=e.target;if((()=>{if(!!!this._tempMultiGroup){let b=i;for(;b;){if(b instanceof M__default.default.Group&&typeof b.name=="function"){let y=b.name();if(typeof y=="string"&&(y.includes("temp-multi-group")||y.includes("area-temp-group")))return true}b=b.getParent();}return false}let g=i;for(;g;){if(g===this._tempMultiGroup)return true;g=g.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(i===t||i.getLayer()!==o){this._destroyHoverTr();return}let l=this._core.nodes.list().map(_=>_.getKonvaNode()),d=new Set(l),c=_=>{let g=_;for(;g;){if(d.has(g))return g;g=g.getParent();}return null},u=(_=>{let g=_,b=null;for(;g;)d.has(g)&&g instanceof M__default.default.Group&&(b=g),g=g.getParent();return b})(i),p=c(i),f=e.evt.ctrlKey,m=f?p??u:u??p;if(!f&&this._selected&&p&&!(this._selected.getKonvaNode()instanceof M__default.default.Group)){let _=this._selected.getKonvaNode();u&&((b,y,N)=>{if(!N)return false;let x=(w,k)=>{let T=k;for(;T;){if(T===w)return true;T=T.getParent();}return false};return x(N,b)&&x(N,y)})(_,p,u)&&_!==p&&(m=p);}if(!m){this._destroyHoverTr();return}if(!this._options.selectablePredicate(m)){this._destroyHoverTr();return}if(this._selected){let _=this._selected.getKonvaNode();if(f?m===_:m===_||((y,N)=>{let x=N;for(;x;){if(x===y)return true;x=x.getParent();}return false})(_,m)){this._destroyHoverTr();return}}let v=this._ensureHoverTr();v.nodes([m]),v.visible(true),v.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:i=true,selectablePredicate:s}=e;this._options={dragEnabled:t,enableTransformer:o,deselectOnEmptyClick:i,selectablePredicate:s??(()=>true),autoPanEnabled:e.autoPanEnabled??true,autoPanEdgePx:e.autoPanEdgePx??40,autoPanMaxSpeedPx:e.autoPanMaxSpeedPx??24},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 $e({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 i=t.getPointerPosition();if(i){let s=t.width(),r=t.height(),l=this._autoPanEdgePx,d=0,c=0,h=Math.max(0,l-i.x),u=Math.max(0,i.x-(s-l)),p=Math.max(0,l-i.y),f=Math.max(0,i.y-(r-l)),m=v=>Math.min(1,v/l);if(d=this._autoPanMaxSpeedPx*(m(u)-m(h)),c=this._autoPanMaxSpeedPx*(m(f)-m(p)),d!==0||c!==0){if(e.x(e.x()-d),e.y(e.y()-c),this._draggingNode&&typeof this._draggingNode.setAbsolutePosition=="function"){let v=this._draggingNode.getAbsolutePosition();this._draggingNode.setAbsolutePosition({x:v.x+d,y:v.y+c}),this._transformer?.forceUpdate();}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",r=>{if(!this._core)return;let l=this._core.stage,d=this._core.nodes.layer;if(r.evt.button!==0)return;if(r.target===l||r.target.getLayer()!==d){if(!!l.getAttr("_skipSelectionEmptyClickOnce")){l.setAttr("_skipSelectionEmptyClickOnce",false),r.cancelBubble=true;return}this._options.deselectOnEmptyClick&&(this._destroyTempMulti(),this._clearSelection());return}let c=r.target;if(!this._options.selectablePredicate(c))return;if(r.evt.shiftKey||r.evt.ctrlKey||r.evt.metaKey){let u=this._findBaseNodeByTarget(c);if(!u)return;let f=u.getKonvaNode().getParent();if(f&&f instanceof M__default.default.Group&&f!==this._core.nodes.world)return;if(this._tempMultiSet.size===0&&this._selected&&this._selected!==u&&(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(u)?this._tempMultiSet.delete(u):this._tempMultiSet.add(u),this._tempMultiSet.size===0){this._destroyTempMulti(),this._clearSelection();return}if(this._tempMultiSet.size===1){let v=this._tempMultiSet.values().next(),_=v.done?void 0:v.value;_&&(this._destroyTempMulti(),this._select(_),this._scheduleBatchDraw());return}this._ensureTempMulti(Array.from(this._tempMultiSet)),this._scheduleBatchDraw();return}let h=this._findBaseNodeByTarget(c);h&&(this._destroyTempMulti(),this._select(h),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 d=this._selected.getKonvaNode();if(d instanceof M__default.default.Group&&typeof d.isAncestorOf=="function"&&d.isAncestorOf(r.target)){r.cancelBubble=true;let c=null;for(let h of this._core.nodes.list()){let u=h.getKonvaNode();if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(u)&&u!==d&&typeof u.isAncestorOf=="function"&&u.isAncestorOf(r.target)){let p=true;for(let f of this._core.nodes.list()){if(f===h)continue;let m=f.getKonvaNode();if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(m)&&typeof u.isAncestorOf=="function"&&u.isAncestorOf(m)&&typeof m.isAncestorOf=="function"&&m.isAncestorOf(r.target)){p=false;break}}if(p){c=h;break}}}if(c??(c=this._core.nodes.list().find(h=>h.getKonvaNode()===r.target)??null),c){this._select(c);let h=c.getKonvaNode();typeof h.draggable=="function"&&h.draggable(true),d instanceof M__default.default.Group&&(this._parentGroupDuringChildEdit=d,this._parentGroupPrevDraggable=typeof d.draggable=="function"?d.draggable():null,typeof d.draggable=="function"&&d.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",r=>{if(!this._options.autoPanEnabled)return;let l=r.target;this._options.selectablePredicate(l)&&(this._draggingNode=l,this._startAutoPanLoop());}),o.on("dragend.selectionAutoPan",()=>{this._draggingNode=null,this._stopAutoPanLoop();});let i=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());}));};i.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._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),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 M__default.default.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 i=globalThis.requestAnimationFrame;i(()=>{this._dragMoveScheduled=false,this._scheduleBatchDraw();});}),o.on("dragend.selection",()=>{let i={};typeof o.x=="function"&&(i.x=o.x()),typeof o.y=="function"&&(i.y=o.y()),typeof o.width=="function"&&(i.width=o.width()),typeof o.height=="function"&&(i.height=o.height()),typeof o.rotation=="function"&&(i.rotation=o.rotation()),typeof o.scaleX=="function"&&(i.scaleX=o.scaleX()),typeof o.scaleY=="function"&&(i.scaleY=o.scaleY()),t.eventBus.emit("node:transformed",e,i);}),o.on("transformend.selection",()=>{let i={};typeof o.x=="function"&&(i.x=o.x()),typeof o.y=="function"&&(i.y=o.y()),typeof o.width=="function"&&(i.width=o.width()),typeof o.height=="function"&&(i.height=o.height()),typeof o.rotation=="function"&&(i.rotation=o.rotation()),typeof o.scaleX=="function"&&(i.scaleX=o.scaleX()),typeof o.scaleY=="function"&&(i.scaleY=o.scaleY()),this._core?.eventBus.emit("node:transformed",e,i);}),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",i=>{let s=i.evt.button;(s===1||s===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 o=e.getAbsoluteTransform().copy(),i=t.copy();i.invert();let s=o.multiply(i);for(let r of this._tempMultiNodes){let l=this._tempMultiInitialTransforms.get(r);if(!l)continue;let d=s.copy().multiply(l),c=r.getParent();if(!c)continue;let h=c.getAbsoluteTransform().copy();h.invert();let p=h.multiply(d).decompose();typeof r.position=="function"&&r.position({x:p.x,y:p.y}),typeof r.rotation=="function"&&r.rotation(p.rotation),typeof r.scale=="function"&&r.scale({x:p.scaleX,y:p.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,i=1/0,s=-1/0,r=-1/0;for(let l of e){let c=l.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false}),h=t.getAbsoluteTransform().copy().invert(),u=[h.point({x:c.x,y:c.y}),h.point({x:c.x+c.width,y:c.y}),h.point({x:c.x+c.width,y:c.y+c.height}),h.point({x:c.x,y:c.y+c.height})];for(let p of u)o=Math.min(o,p.x),i=Math.min(i,p.y),s=Math.max(s,p.x),r=Math.max(r,p.y);}return !isFinite(o)||!isFinite(i)||!isFinite(s)||!isFinite(r)?null:{x:o,y:i,width:s-o,height:r-i}}_ensureTempMulti(e){if(!this._core)return;let t=this._core.nodes.world,o=this._core.nodes.layer;this._tempMultiSet.clear();for(let u of e)this._tempMultiSet.add(u);let i=e.map(u=>u.getKonvaNode());if(this._tempMultiGroup&&this._tempMultiNodes.length>0){if(this._tempMultiNodes.length===i.length&&i.every(p=>this._tempMultiNodes.includes(p)))return;this._destroyTempMulti();}let s=this._computeUnionBBox(e);if(!s)return;this._tempMultiNodes=i;let r=new M__default.default.Group({name:"temp-multi-overlay",x:s.x,y:s.y});t.add(r),this._tempMultiGroup=r;let l=new M__default.default.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 Qe(this._core)),this._tempOverlay.attach(r,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed});let d=this._core.stage,c=d.draggable();r.draggable(true);let h=null;r.on("dragstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();for(let u of this._tempMultiNodes)this._tempMultiInitialTransforms.set(u,u.getAbsoluteTransform().copy());h=r.getAbsoluteTransform().copy(),d.draggable(false),this._draggingNode=r,this._startAutoPanLoop(),this._tempOverlay?.hideOverlaysForDrag();}),r.on("dragmove.tempMulti",()=>{h&&(this._applyOverlayTransformToNodes(r,h),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("dragend.tempMulti",()=>{if(d.draggable(c),this._draggingNode=null,this._stopAutoPanLoop(),this._tempOverlay?.restoreOverlaysAfterDrag(),this._core){let p=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiSet){let v=f.getKonvaNode().getAbsoluteTransform().copy(),g=p.copy().multiply(v).decompose();this._core.eventBus.emit("node:transformed",f,{x:g.x,y:g.y,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY});}}this._updateTempMultiOverlayBBox(),h=null,this._tempMultiInitialTransforms.clear(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),r.on("transformstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();for(let u of this._tempMultiNodes)this._tempMultiInitialTransforms.set(u,u.getAbsoluteTransform().copy());h=r.getAbsoluteTransform().copy();}),r.on("transform.tempMulti",()=>{h&&(this._applyOverlayTransformToNodes(r,h),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("transformend.tempMulti",()=>{if(this._core){let p=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiSet){let v=f.getKonvaNode().getAbsoluteTransform().copy(),g=p.copy().multiply(v).decompose();this._core.eventBus.emit("node:transformed",f,{x:g.x,y:g.y,rotation:g.rotation,scaleX:g.scaleX,scaleY:g.scaleY});}}this._updateTempMultiOverlayBBox(),h=null,this._tempMultiInitialTransforms.clear(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),o.batchDraw(),this._core.eventBus.emit("selection:multi:created",e);}_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}),i=o.getKonvaNode(),s=[],r=[...this._tempMultiNodes].sort((u,p)=>u.zIndex()-p.zIndex()),l=Math.max(...r.map(u=>u.zIndex()));for(let u of r){let p=u.getAbsolutePosition();i.add(u),u.setAbsolutePosition(p),typeof u.draggable=="function"&&u.draggable(false);let f=this._core.nodes.list().find(m=>m.getKonvaNode()===u);f&&s.push(f);}let d=this._core.nodes.world,c=i.zIndex(),h=l;if(c<h){let u=h-c;for(let p=0;p<u&&i.zIndex()<d.children.length-1;p++)i.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 i.draggable=="function"&&i.draggable(true),this._core.eventBus.emit("group:created",o,s),this._select(o),this._core.stage.batchDraw();}_tryUngroupSelectedGroup(){if(!this._core||!this._selected)return;let e=this._selected.getKonvaNode();if(!(e instanceof M__default.default.Group))return;let t=[...e.getChildren()],o=this._core.nodes.world,i=[];for(let r of t){let l=r.getAbsoluteTransform().copy();o.add(r);let d=o.getAbsoluteTransform().copy();d.invert();let h=d.multiply(l).decompose();typeof r.position=="function"?r.position({x:h.x,y:h.y}):r.setAbsolutePosition({x:h.x,y:h.y}),typeof r.rotation=="function"&&r.rotation(h.rotation),typeof r.scale=="function"&&r.scale({x:h.scaleX,y:h.scaleY}),typeof r.draggable=="function"&&r.draggable(true);for(let u of this._core.nodes.list())if(u.getKonvaNode()===r){i.push(u);break}}let s=this._selected;this._selected=null,this._transformer?.destroy(),this._transformer=null,this._destroySizeLabel(),this._core.eventBus.emit("group:ungrouped",s,i),this._core.nodes.remove(s),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 M__default.default.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 M__default.default.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,h=l.height,u=l.x,p=l.y;return (c<0||c<1)&&(c=1),(h<0||h<1)&&(h=1),{...l,x:u,y:p,width:c,height:h}}),this._transformer=t,this._restyleSideAnchors(),this._setupCornerRadiusHandles(false),this._setupRotateHandles(),this._setupSizeLabel();let o=()=>{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",()=>{o(),this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel();let r=this._selected?.getKonvaNode(),d=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"";if(!r){this._transformOppositeCorner=null;return}let c=Ne(r),h=ke(d,c);if(!h){this._transformOppositeCorner=null;return}let u=r.getAbsoluteTransform();this._transformOppositeCorner=u.point({x:h.x,y:h.y});}),t.on("transform.keepratio",o),t.on("transform.corner-sync",()=>{let r=this._selected?.getKonvaNode();if(r&&(this._bakeRectScale(r),this._transformOppositeCorner)){let d=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"",c=r.getAbsoluteTransform(),h=Ne(r),u=ke(d,h);if(!u)return;let p=c.point({x:u.x,y:u.y}),f=this._transformOppositeCorner.x-p.x,m=this._transformOppositeCorner.y-p.y,v=r.getParent();if(v&&(Math.abs(f)>.01||Math.abs(m)>.01)){let _=v.getAbsoluteTransform().copy().invert(),g=r.getAbsolutePosition(),b={x:g.x+f,y:g.y+m},y=_.point(b);r.position(y);}}this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();}),t.on("transformend.corner-sync",()=>{this._cornerHandlesSuppressed=false,this._transformOppositeCorner=null,this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();});let i=this._selected.getKonvaNode();i.off(".overlay-sync");let s=()=>{this._restyleSideAnchors(),this._scheduleUIUpdate(),this._scheduleBatchDraw();};i.on("widthChange.overlay-sync heightChange.overlay-sync scaleXChange.overlay-sync scaleYChange.overlay-sync rotationChange.overlay-sync xChange.overlay-sync yChange.overlay-sync",s),this._scheduleBatchDraw();}_restyleSideAnchors(){if(!this._core||!this._selected||!this._transformer)return;let e=this._selected.getKonvaNode();fe(this._core,this._transformer,e);}_setupRotateHandles(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroyRotateHandles();let t=new M__default.default.Group({name:"rotate-handles-group",listening:true});e.add(t),t.moveToTop(),this._rotateHandlesGroup=t;let o=re("rotate-tl"),i=re("rotate-tr"),s=re("rotate-br"),r=re("rotate-bl");t.add(o),t.add(i),t.add(s),t.add(r),this._rotateHandles={tl:o,tr:i,br:s,bl:r};let l=c=>{c.on("dragstart.rotate",()=>{if(!this._selected)return;let h=this._selected.getKonvaNode(),u=h.getAbsoluteTransform().decompose(),p=this._getNodeCenterAbs(h);this._rotateCenterAbsStart=p;let f=this._core?.stage.getPointerPosition()??c.getAbsolutePosition(),m=Math.atan2(f.y-p.y,f.x-p.x)*180/Math.PI;this._rotateDragState={base:u.rotation||0,start:m},this._core&&(this._prevStageDraggableBeforeRotate=this._core.stage.draggable()),typeof h.draggable=="function"&&h.draggable(false),this._core?.stage.draggable(false),this._core&&(this._core.stage.container().style.cursor="grabbing");}),c.on("dragmove.rotate",h=>{if(!this._core||!this._selected||!this._rotateDragState)return;let u=this._selected.getKonvaNode(),p=this._rotateCenterAbsStart??this._getNodeCenterAbs(u),f=this._core.stage.getPointerPosition()??c.getAbsolutePosition(),m=Math.atan2(f.y-p.y,f.x-p.x)*180/Math.PI,v=this._rotateDragState.base+(m-this._rotateDragState.start),_=b=>{let y=b%360;return y<0&&(y+=360),y},g=(b,y)=>_(b-y+180)-180;if(h.evt.shiftKey){let b=this._transformer,y,N=5;if(b){let x=b.rotationSnaps();Array.isArray(x)&&(y=x.map(k=>_(k)));let w=b.rotationSnapTolerance();typeof w=="number"&&(N=w);}if(y?.length){let x=_(v),w=v,k=1/0;for(let T of y){let A=Math.abs(g(x,T));A<k&&A<=N&&(w=T,k=A);}k!==1/0&&(v=w);}}if(u.rotation(v),this._rotateCenterAbsStart){let b=this._getNodeCenterAbs(u),y=this._rotateCenterAbsStart.x-b.x,N=this._rotateCenterAbsStart.y-b.y,x=u.getParent();if(x){let w=x.getAbsoluteTransform().copy().invert(),k=w.point({x:b.x,y:b.y}),T=w.point({x:b.x+y,y:b.y+N}),A=u.x()+(T.x-k.x),R=u.y()+(T.y-k.y);typeof u.position=="function"&&u.position({x:A,y:R});}}this._transformer?.forceUpdate(),this._restyleSideAnchors(),this._core.nodes.layer.batchDraw(),this._scheduleUIUpdate();}),c.on("dragend.rotate",()=>{if(this._rotateDragState=null,this._rotateCenterAbsStart=null,this._selected){let h=this._selected.getKonvaNode();this._options.dragEnabled&&typeof h.draggable=="function"&&h.draggable(true);let u={x:h.x(),y:h.y(),rotation:h.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(i),l(s),l(r);let d=c=>{this._core&&(this._core.stage.container().style.cursor=c);};this._rotateHandles.tl&&(this._rotateHandles.tl.on("mouseenter.rotate-cursor",()=>{d("pointer");}),this._rotateHandles.tl.on("mouseleave.rotate-cursor",()=>{d("default");})),this._rotateHandles.tr&&(this._rotateHandles.tr.on("mouseenter.rotate-cursor",()=>{d("pointer");}),this._rotateHandles.tr.on("mouseleave.rotate-cursor",()=>{d("default");})),this._rotateHandles.br&&(this._rotateHandles.br.on("mouseenter.rotate-cursor",()=>{d("pointer");}),this._rotateHandles.br.on("mouseleave.rotate-cursor",()=>{d("default");})),this._rotateHandles.bl&&(this._rotateHandles.bl.on("mouseenter.rotate-cursor",()=>{d("pointer");}),this._rotateHandles.bl.on("mouseleave.rotate-cursor",()=>{d("default");})),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})}_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,i=t.height;if(o<=0||i<=0)return;let s=e.getAbsoluteTransform().copy(),r=k=>s.point(k),l=12,d=r({x:t.x+o/2,y:t.y+i/2}),c=r({x:t.x,y:t.y}),h=r({x:t.x+o,y:t.y}),u=r({x:t.x+o,y:t.y+i}),p=r({x:t.x,y:t.y+i}),f=k=>{let T=k.x-d.x,A=k.y-d.y,R=Math.hypot(T,A)||1;return {x:T/R,y:A/R}},m=f(c),v=f(h),_=f(u),g=f(p),b={x:c.x+m.x*l,y:c.y+m.y*l},y={x:h.x+v.x*l,y:h.y+v.y*l},N={x:u.x+_.x*l,y:u.y+_.y*l},x={x:p.x+g.x*l,y:p.y+g.y*l};this._rotateHandles.tl&&this._rotateHandles.tl.absolutePosition(b),this._rotateHandles.tr&&this._rotateHandles.tr.absolutePosition(y),this._rotateHandles.br&&this._rotateHandles.br.absolutePosition(N),this._rotateHandles.bl&&this._rotateHandles.bl.absolutePosition(x);let w=this._rotateHandlesGroup.getParent();if(w){let k=w.getAbsoluteTransform().decompose(),T=1/(Math.abs(k.scaleX)||1),A=1/(Math.abs(k.scaleY)||1);this._rotateHandles.tl&&this._rotateHandles.tl.scale({x:T,y:A}),this._rotateHandles.tr&&this._rotateHandles.tr.scale({x:T,y:A}),this._rotateHandles.br&&this._rotateHandles.br.scale({x:T,y:A}),this._rotateHandles.bl&&this._rotateHandles.bl.scale({x:T,y:A});}this._rotateHandlesGroup.moveToTop();}_setupSizeLabel(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroySizeLabel();let t=new M__default.default.Label({listening:false,opacity:.95}),o=new M__default.default.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),i=new M__default.default.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:4,fill:"#ffffff"});t.add(o),t.add(i),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}),i=e.getAbsoluteTransform().decompose(),s=this._core.nodes.world.getAbsoluteTransform().decompose(),r=Math.abs(i.scaleX)||1,l=Math.abs(i.scaleY)||1,d=Math.abs(s.scaleX)||1,c=Math.abs(s.scaleY)||1,h=o.width*(r/d),u=o.height*(l/c),p=Math.max(0,Math.round(h)),f=Math.max(0,Math.round(u));this._sizeLabel.getText().text(String(p)+" \xD7 "+String(f));let v=8,_=t.x+t.width/2,g=t.y+t.height+v,y=this._sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this._sizeLabel.absolutePosition({x:_,y:g}),this._sizeLabel.offsetX(y/2),this._sizeLabel.offsetY(0);let N=this._sizeLabel.getParent();if(N){let x=N.getAbsoluteTransform().decompose(),w=1/(Math.abs(x.scaleX)||1),k=1/(Math.abs(x.scaleY)||1);this._sizeLabel.scale({x:w,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 M__default.default.Rect||e instanceof M__default.default.Image}_getCornerRadiusArray(e){let t=e.cornerRadius();if(Array.isArray(t)){let[i=0,s=0,r=0,l=0]=t;return [i||0,s||0,r||0,l||0]}let o=typeof t=="number"?t:0;return [o,o,o,o]}_setCornerRadiusArray(e,t){let[o,i,s,r]=t;o===i&&i===s&&s===r?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,i=this._core.stage;this._destroyCornerRadiusHandles();let s=new M__default.default.Group({name:"corner-radius-handles-group",listening:true});o.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 S=i.getPointerPosition();if(!S){this._cornerHandlesGroup.visible(false);return}let E=o.getIntersection(S);E&&this._cornerHandlesGroup.isAncestorOf(E)||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=i.getPointerPosition();if(r&&this._core.nodes.world.scaleX()>=.3){let P=o.getIntersection(r);P&&(P===t||t.isAncestorOf(P))&&this._cornerHandlesGroup.visible(true);}let l=()=>{let S=t.width(),E=t.height(),P=t.getAbsoluteScale(),I=1/(Math.abs(P.x)||1),F=1/(Math.abs(P.y)||1),U=12*I,z=12*F,J=Math.max(0,S/2-U),oe=Math.max(0,E/2-z),Q=Math.min(J,oe);return {tl:{corner:{x:U,y:z},sign:{x:1,y:1},side:Q},tr:{corner:{x:S-U,y:z},sign:{x:-1,y:1},side:Q},br:{corner:{x:S-U,y:E-z},sign:{x:-1,y:-1},side:Q},bl:{corner:{x:U,y:E-z},sign:{x:1,y:-1},side:Q}}},d=(S,E)=>{let P=t.getAbsoluteTransform().copy(),I=X=>P.copy().invert().point(X),F=X=>P.point(X),z=l()[E],J=I(S),oe=J.x-z.corner.x,Q=J.y-z.corner.y,G=(z.sign.x*oe+z.sign.y*Q)/2;G=Math.max(0,Math.min(z.side,G));let W={x:z.corner.x+z.sign.x*G,y:z.corner.y+z.sign.y*G};return {snappedAbs:F(W),r:G,meta:z}},c=S=>new M__default.default.Line({name:S,points:[],stroke:e?"#4a90e2":"",strokeWidth:e?1:0,dash:e?[4,4]:[],closed:true,listening:false}),h=c("corner-square-tl"),u=c("corner-square-tr"),p=c("corner-square-br"),f=c("corner-square-bl");s.add(h,u,p,f);let m=S=>{let E=new M__default.default.Circle({name:S,radius:4,fill:"#ffffff",stroke:"#4a90e2",strokeWidth:1.5,draggable:true,dragOnTop:true,hitStrokeWidth:16});return E.on("mouseenter.corner-radius",()=>{this._core&&(this._core.stage.container().style.cursor="default");}),E},v=m("corner-radius-tl"),_=m("corner-radius-tr"),g=m("corner-radius-br"),b=m("corner-radius-bl");s.add(v,_,g,b),this._cornerHandles={tl:v,tr:_,br:g,bl:b};let y={tl:0,tr:1,br:2,bl:3},N=false,x=null,w=false,k=()=>{let S=t.getAbsoluteTransform().copy(),E=t.width(),P=t.height();return S.point({x:E/2,y:P/2})},T=()=>{let S={};return this._cornerHandles.tl&&(S.tl=this._cornerHandles.tl.getAbsolutePosition()),this._cornerHandles.tr&&(S.tr=this._cornerHandles.tr.getAbsolutePosition()),this._cornerHandles.br&&(S.br=this._cornerHandles.br.getAbsolutePosition()),this._cornerHandles.bl&&(S.bl=this._cornerHandles.bl.getAbsolutePosition()),S},A=(S,E=8)=>{let P=k();return Math.hypot(S.x-P.x,S.y-P.y)<=E},R=(S,E=6)=>{let P=k();return Math.min(Math.abs(S.x-P.x),Math.abs(S.y-P.y))<=E},D=(S,E=8)=>{let P=T(),I=0;return ["tl","tr","br","bl"].forEach(F=>{let U=P[F];U&&Math.hypot(U.x-S.x,U.y-S.y)<=E&&I++;}),I>=2},B=S=>{if(!N||x)return;let E=k(),P=S.x-E.x,I=S.y-E.y,F=Math.hypot(P,I);if(F<.1)return;P/=F,I/=F;let U=t.getAbsoluteTransform().copy(),z=l(),J=["tl","tr","br","bl"].reduce((G,W)=>{let ie=z[W],X=U.point(ie.corner),ne=X.x-E.x,V=X.y-E.y,$=Math.hypot(ne,V)||1;return G[W]={x:ne/$,y:V/$},G},{}),oe="tl",Q=-1/0;["tl","tr","br","bl"].forEach(G=>{let W=J[G],ie=P*W.x+I*W.y;ie>Q&&(Q=ie,oe=G);}),x=oe;},K=S=>E=>{B(E);let P=x??S,{snappedAbs:I,r:F,meta:U}=d(E,P),z=t.width(),J=t.height(),oe=Math.max(0,Math.min(z,J)/2),Q=U.side>0?F/U.side:0,G=Math.round(Q*oe);G=Math.max(0,Math.min(G,oe));let W=this._getCornerRadiusArray(t),ie=y[P];return w?W[ie]=G:(W[0]=G,W[1]=G,W[2]=G,W[3]=G),this._setCornerRadiusArray(t,W),this._showRadiusLabelForCorner(ie),L(),this._core?.nodes.layer.batchDraw(),I};v.dragBoundFunc(K("tl")),_.dragBoundFunc(K("tr")),g.dragBoundFunc(K("br")),b.dragBoundFunc(K("bl"));let L=()=>{let{tl:S,tr:E,br:P,bl:I}=this._cornerHandles;if(!S||!E||!P||!I)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 F=t.getAbsoluteTransform().copy(),U=o.getAbsoluteTransform().copy().invert(),z=X=>F.point(X),J=X=>U.point(F.point(X)),oe=l(),Q=this._getCornerRadiusArray(t),G=(X,ne,V)=>{let $=oe[X],ye=t.width(),De=t.height(),we=Math.max(0,Math.min(ye,De)/2),Le=Math.max(0,Math.min(we,Q[ne]||0)),Ge=we>0?Le/we:0,bt=Math.max(0,Math.min($.side,Ge*$.side)),St={x:$.corner.x+$.sign.x*bt,y:$.corner.y+$.sign.y*bt};V.absolutePosition(z(St));},W=(X,ne)=>{let V=oe[X],$=V.corner,ye={x:V.corner.x+V.sign.x*V.side,y:V.corner.y+V.sign.y*V.side},De=J({x:$.x,y:$.y}),we=J({x:ye.x,y:$.y}),Le=J({x:ye.x,y:ye.y}),Ge=J({x:$.x,y:ye.y});ne.points([De.x,De.y,we.x,we.y,Le.x,Le.y,Ge.x,Ge.y]);};W("tl",h),W("tr",u),W("br",p),W("bl",f),G("tl",0,S),G("tr",1,E),G("br",2,P),G("bl",3,I);let ie=this._cornerHandlesGroup?.getParent();if(ie){let X=ie.getAbsoluteTransform().decompose(),ne=1/(Math.abs(X.scaleX)||1),V=1/(Math.abs(X.scaleY)||1);S.scale({x:ne,y:V}),E.scale({x:ne,y:V}),P.scale({x:ne,y:V}),I.scale({x:ne,y:V});}this._cornerHandlesGroup?.moveToTop();};this._updateCornerRadiusHandlesPosition=L;let ee=(S,E)=>{w=!!E?.evt?.altKey;let P=S.getAbsolutePosition();if(N=A(P,8)||R(P,6)||D(P,8),x=null,N){let I=this._core?.stage.getPointerPosition()??P;B(I);}},j=(S,E)=>P=>{w=P.evt.altKey;},ae=()=>{if(N=false,x=null,w=false,this._selected&&this._core){let S=this._selected.getKonvaNode(),E={x:S.x(),y:S.y()};typeof S.width=="function"&&(E.width=S.width()),typeof S.height=="function"&&(E.height=S.height()),this._core.eventBus.emit("node:transformed",this._selected,E);}};v.on("dragstart.corner-radius",S=>{ee(v,S);}),_.on("dragstart.corner-radius",S=>{ee(_,S);}),g.on("dragstart.corner-radius",S=>{ee(g,S);}),b.on("dragstart.corner-radius",S=>{ee(b,S);}),v.on("dragmove.corner-radius",j()),_.on("dragmove.corner-radius",j()),g.on("dragmove.corner-radius",j()),b.on("dragmove.corner-radius",j()),v.on("dragend.corner-radius",ae),_.on("dragend.corner-radius",ae),g.on("dragend.corner-radius",ae),b.on("dragend.corner-radius",ae);let Y=S=>()=>{this._showRadiusLabelForCorner(S);},Z=()=>{this._hideRadiusLabel();},te=S=>()=>{this._showRadiusLabelForCorner(S);};v.on("mouseenter.corner-radius",Y(0)),_.on("mouseenter.corner-radius",Y(1)),g.on("mouseenter.corner-radius",Y(2)),b.on("mouseenter.corner-radius",Y(3)),v.on("mouseleave.corner-radius",Z),_.on("mouseleave.corner-radius",Z),g.on("mouseleave.corner-radius",Z),b.on("mouseleave.corner-radius",Z),v.on("dragstart.corner-radius",Y(0)),_.on("dragstart.corner-radius",Y(1)),g.on("dragstart.corner-radius",Y(2)),b.on("dragstart.corner-radius",Y(3)),v.on("dragmove.corner-radius",te(0)),_.on("dragmove.corner-radius",te(1)),g.on("dragmove.corner-radius",te(2)),b.on("dragmove.corner-radius",te(3)),v.on("dragend.corner-radius",Z),_.on("dragend.corner-radius",Z),g.on("dragend.corner-radius",Z),b.on("dragend.corner-radius",Z);let se=()=>{if(!this._selected)return;this._selected.getKonvaNode().draggable(false);},le=()=>{if(!this._selected)return;let S=this._selected.getKonvaNode();this._options.dragEnabled&&S.draggable(true);};v.on("mousedown.corner-radius touchstart.corner-radius",se),_.on("mousedown.corner-radius touchstart.corner-radius",se),g.on("mousedown.corner-radius touchstart.corner-radius",se),b.on("mousedown.corner-radius touchstart.corner-radius",se),v.on("mouseup.corner-radius touchend.corner-radius",le),_.on("mouseup.corner-radius touchend.corner-radius",le),g.on("mouseup.corner-radius touchend.corner-radius",le),b.on("mouseup.corner-radius touchend.corner-radius",le);let q=".corner-squares",me=false,be=()=>{me||(me=true,M__default.default.Util.requestAnimFrame(()=>{me=false,L(),this._core?.nodes.layer.batchDraw();}));};i.on(["wheel","resize","xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(S=>S+q).join(" "),be),o.on(["xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(S=>S+q).join(" "),be),t.on(["dragmove","transform","xChange","yChange","widthChange","heightChange","rotationChange","scaleXChange","scaleYChange","positionChange","scaleChange"].map(S=>S+q).join(" "),be),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,()=>{L(),this._core?.nodes.layer.batchDraw();}),this._transformer.on("transformend"+q,()=>{this._cornerHandlesSuppressed=false,be();})),s.on("destroy"+q,()=>{i.off(q),o.off(q),t.off(q),this._transformer?.off(q);}),L(),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 M__default.default.Rect))return;let t=e.scaleX(),o=e.scaleY();if(t===1&&o===1)return;let i=e.getAbsolutePosition(),s=e.width(),r=e.height(),l=Math.abs(t)*s,d=Math.abs(o)*r;e.width(l),e.height(d),e.scaleX(1),e.scaleY(1),e.setAbsolutePosition(i);}_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}),i=o.width,s=o.height;if(i<=0||s<=0)return;let r=t.getAbsoluteTransform().copy(),l=w=>r.point(w),d=t.getAbsoluteScale(),c=1/(Math.abs(d.x)||1),h=1/(Math.abs(d.y)||1),u=12*c,p=12*h,f=this._getCornerRadiusArray(t),m=Math.min(i,s)/2||1,v=w=>{let k=Math.hypot(w.x,w.y)||1;return {x:w.x/k,y:w.y/k}},_=[v({x:i/2-u,y:s/2-p}),v({x:-(i/2-u),y:s/2-p}),v({x:-(i/2-u),y:-(s/2-p)}),v({x:i/2-u,y:-(s/2-p)})],g=l({x:o.x+u+_[0].x*Math.min(m,f[0]),y:o.y+p+_[0].y*Math.min(m,f[0])}),b=l({x:o.x+i-u+_[1].x*Math.min(m,f[1]),y:o.y+p+_[1].y*Math.min(m,f[1])}),y=l({x:o.x+i-u+_[2].x*Math.min(m,f[2]),y:o.y+s-p+_[2].y*Math.min(m,f[2])}),N=l({x:o.x+u+_[3].x*Math.min(m,f[3]),y:o.y+s-p+_[3].y*Math.min(m,f[3])});this._cornerHandles.tl&&this._cornerHandles.tl.absolutePosition(g),this._cornerHandles.tr&&this._cornerHandles.tr.absolutePosition(b),this._cornerHandles.br&&this._cornerHandles.br.absolutePosition(y),this._cornerHandles.bl&&this._cornerHandles.bl.absolutePosition(N);let x=this._cornerHandlesGroup.getParent();if(x){let w=x.getAbsoluteTransform().decompose(),k=1/(Math.abs(w.scaleX)||1),T=1/(Math.abs(w.scaleY)||1);this._cornerHandles.tl&&this._cornerHandles.tl.scale({x:k,y:T}),this._cornerHandles.tr&&this._cornerHandles.tr.scale({x:k,y:T}),this._cornerHandles.br&&this._cornerHandles.br.scale({x:k,y:T}),this._cornerHandles.bl&&this._cornerHandles.bl.scale({x:k,y:T});}this._cornerHandlesGroup.moveToTop();}_updateCornerRadiusHandlesVisibility(){if(!this._core||!this._selected||!this._cornerHandlesGroup)return;let t=this._core.nodes.world.scaleX(),o=this._core.stage,i=this._core.nodes.layer,s=this._selected.getKonvaNode(),r=o.getPointerPosition();if(!r){t<.3&&this._cornerHandlesGroup.visible(false);return}if(t<.3){this._cornerHandlesGroup.visible(false);return}let l=i.getIntersection(r);if(l){let d=l===s||s.isAncestorOf(l),c=this._cornerHandlesGroup.isAncestorOf(l);d||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 M__default.default.Label({listening:false,opacity:.95}),o=new M__default.default.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),i=new M__default.default.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:4,fill:"#ffffff"});return t.add(o),t.add(i),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 r=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(r),o.offsetY(0);let d=o.getParent();if(d){let c=d.getAbsoluteTransform().decompose(),h=1/(Math.abs(c.scaleX)||1),u=1/(Math.abs(c.scaleY)||1);o.scale({x:h,y:u});}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,i=this._getCornerRadiusArray(o),s=Math.round(i[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 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 i=o.getKonvaNode();if(typeof i.isAncestorOf=="function"&&i.isAncestorOf(e)){let s=true;for(let r of this._core.nodes.list()){if(r===o)continue;let l=r.getKonvaNode();if(typeof l.isAncestorOf=="function"&&l.isAncestorOf(i)){s=false;break}}s&&(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 i=o;typeof i.draggable=="function"&&i.draggable(false);}}};var it=class extends H{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,"_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 M__default.default.Layer({name:"area-selection-layer",listening:false});e.stage.add(t),this._layer=t,this._rect=new M__default.default.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",i=>{if(i.evt.button!==0||i.target!==o&&i.target.getLayer()===e.nodes.layer)return;let s=o.getPointerPosition();if(!s||!this._rect)return;let r=o.findOne(".ruler-layer");if(r&&i.target.getLayer()===r)return;let l=o.findOne(".guides-layer");if(l&&i.target.getLayer()===l)return;let d=30;s.y<=d||s.x<=d||(this._selecting=true,this._start={x:s.x,y:s.y},this._rect.visible(true),this._rect.position({x:s.x,y:s.y}),this._rect.size({width:0,height:0}),this._layer?.batchDraw(),this._lastPickedBaseNodes=[]);}),o.on("mousemove.area",()=>{if(!this._selecting||!this._rect||!this._start)return;let i=o.getPointerPosition();if(!i)return;let s=30;if(i.y<=s||i.x<=s){this._selecting=false,this._rect.visible(false),this._layer?.batchDraw();return}let l=Math.min(this._start.x,i.x),d=Math.min(this._start.y,i.y),c=Math.abs(i.x-this._start.x),h=Math.abs(i.y-this._start.y);this._rect.position({x:l,y:d}),this._rect.size({width:c,height:h}),this._layer?.batchDraw();let u={x:l,y:d,width:c,height:h},p=this._core?.nodes.list()??[],f=new Set;for(let _ of p){if(_ instanceof de)continue;let g=_.getKonvaNode();if(g.getLayer()!==this._core?.nodes.layer)continue;let y=g.getClientRect({skipShadow:true,skipStroke:false});if(this._rectsIntersect(u,y)){let N=this._findOwningGroupBaseNode(g);f.add(N??_);}}let m=Array.from(f),v=this._getSelectionPlugin();if(m.length>0&&(this._lastPickedBaseNodes=m),v){let _=v.getMultiGroupController();m.length>0&&_.ensure(m),this._core?.stage.batchDraw();}}),o.on("mouseup.area",i=>{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(),s&&(this._skipNextClick=true,this._core?.stage.setAttr("_skipSelectionEmptyClickOnce",true),i.cancelBubble=true);}),o.on("click.area",i=>{if(!this._core)return;if(this._skipNextClick){this._skipNextClick=false,i.cancelBubble=true;return}if(i.evt.shiftKey)return;let r=this._getSelectionPlugin()?.getMultiGroupController(),l=!!r?.isActive();if(!l&&!this._isPermanentGroupSelected())return;let d=i.target,c=this._currentGroupNode();c?this._isAncestor(c,d)||this._clearSelection():l&&r&&(r.isInsideTempByTarget(d)||(r.destroy(),this._core.stage.batchDraw()));});}onDetach(e){e.stage.off(".area"),this._clearSelection(),this._layer&&this._layer.destroy(),this._layer=null,this._rect=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 i=this._core.nodes.list(),s=[];for(let d of i){let c=d.getKonvaNode();if(c.getLayer()!==this._core.nodes.layer)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 d of s){let c=r.find(u=>u.getKonvaNode()===d)??null,h=this._findOwningGroupBaseNode(d);h?l.add(h):c&&!(c instanceof de)&&l.add(c);}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(r=>r instanceof de),i=e,s=null;for(;i;){let r=o.find(l=>l.getKonvaNode()===i)??null;r&&(s=r),i=i.getParent();}return s}_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 de&&o.getKonvaNode()===t)}_currentGroupNode(){if(!this._transformer)return null;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return t&&t instanceof M__default.default.Group?t:null}};var st=class extends H{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:i,shiftKey:s}=e;if(this._isTouchpadWheel(e)){if(s){let l=-(Math.abs(o)>=Math.abs(i)?o:i);this._pan(l,0);}else {let r=-o,l=-i;this._pan(r,l);}return}if(s){let r=i<0?-Math.abs(i):Math.abs(i);this._pan(r,0);}else {let r=-i;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 i=this._core.stage.getPointerPosition();i&&(this._last={x:i.x,y:i.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 o=t.x-this._last.x,i=t.y-this._last.y;this._pan(o,i),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 i=this._core.camera.panStep;switch(e.key){case "ArrowLeft":e.preventDefault(),this._pan(i,0);return;case "ArrowRight":e.preventDefault(),this._pan(-i,0);return;case "ArrowUp":e.preventDefault(),this._pan(0,i);return;case "ArrowDown":e.preventDefault(),this._pan(0,-i);return}}});let{target:t=globalThis,zoomStep:o=1.1,panStep:i=40,ignoreEditableTargets:s=true,enableArrows:r=true,enablePanning:l=true,allowMiddleButtonPan:d=true,allowRightButtonPan:c=true,disableContextMenu:h=true}=e;this._options={target:t,zoomStep:o,panStep:i,ignoreEditableTargets:s,enableArrows:r,enablePanning:l,allowMiddleButtonPan:d,allowRightButtonPan:c,disableContextMenu:h};}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",i=>{i.evt.ctrlKey||(i.evt.preventDefault(),i.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,i=o.x()+e,s=o.y()+t;o.position({x:i,y:s}),this._core.eventBus.emit("camera:pan",{dx:e,dy:t,position:{x:i,y:s}}),this._core.stage.batchDraw();}};var rt=class extends H{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=(h,u)=>{if(!this._visible||!this._core)return;let p=this._core.stage,f=this._core.nodes.world,m=f.scaleX();if(this._minScaleToShow!=null&&m<this._minScaleToShow)return;let v=p.width(),_=p.height(),g=f.scaleX(),b=f.scaleY(),y=Math.max(1,this._stepX)*Math.max(1e-6,g),N=Math.max(1,this._stepY)*Math.max(1e-6,b),x=(f.x()%y+y)%y,w=(f.y()%N+N)%N;h.beginPath(),h.lineWidth=this._lineWidth,h.strokeStyle=this._color;for(let k=x;k<=v;k+=y)h.moveTo(k,0),h.lineTo(k,_);for(let k=w;k<=_;k+=N)h.moveTo(0,k),h.lineTo(v,k);h.stroke();},i=new M__default.default.Shape({listening:false,sceneFunc:o});t.add(i),this._layer=t,this._shape=i;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 h of this._transformersCache)h.moveToTop();this._shape?.moveToTop();for(let h of this._transformersCache)h.moveToTop();})(),this._dragMoveHandler=h=>{if(!this._core||!this._enableSnap)return;let u=this._core.stage,p=this._core.nodes.world,f=h.target;if(f===u||f instanceof M__default.default.Layer)return;let m=this._core.nodes.layer,v=f,_=false;for(;v;){if(v===m){_=true;break}v=v.getParent();}if(!_)return;let g=f;if(typeof g.draggable=="function"&&!g.draggable())return;let b=f.getAbsolutePosition(),y=p.scaleX()||1,N=p.scaleY()||1;if(this._minScaleToShow!=null?y>=this._minScaleToShow:false){let w=(b.x-p.x())/y,k=(b.y-p.y())/N,T=Math.max(1,this._stepX),A=Math.max(1,this._stepY),R=Math.round(w/T)*T,D=Math.round(k/A)*A,B=R*y+p.x(),K=D*N+p.y();(Math.abs(B-b.x)>.001||Math.abs(K-b.y)>.001)&&f.absolutePosition({x:B,y:K});}else {let w=(b.x-p.x())/y,k=(b.y-p.y())/N,T=Math.max(1,this._stepX),A=Math.max(1,this._stepY),R=Math.round(w/T)*T,D=Math.round(k/A)*A,B=R*y+p.x(),K=D*N+p.y();(Math.abs(B-b.x)>.001||Math.abs(K-b.y)>.001)&&f.absolutePosition({x:B,y:K});}},s.on("dragmove.grid",this._dragMoveHandler);let d=h=>{let u=h;if((typeof u.getClassName=="function"?u.getClassName():"")!=="Transformer")return;let f=h,m=(v,_)=>{let g=_;if(!this._enableSnap||!this._core||!(typeof u.nodes=="function"?u.nodes():[])[0])return g;let N=typeof u.getActiveAnchor=="function"?u.getActiveAnchor():"";if(N==="rotater")return g;let x=Math.max(1,this._stepX),w=Math.max(1,this._stepY),k=typeof N=="string"?N:"",T=this._core.nodes.world.getAbsoluteTransform(),A=T.copy();A.invert();let R=g.x,D=g.x+g.width,B=g.y,K=g.y+g.height,L=A.point({x:R,y:B}).x,ee=A.point({x:D,y:B}).x,j=A.point({x:R,y:B}).y,ae=A.point({x:R,y:K}).y,Y=L,Z=ee,te=j,se=ae,le=(I,F)=>Math.round((I+1e-9)/F)*F;k.includes("left")&&(Y=le(L,x)),k.includes("right")&&(Z=le(ee,x)),k.includes("top")&&(te=le(j,w)),k.includes("bottom")&&(se=le(ae,w)),Z-Y<x&&(k.includes("left")?Y=Z-x:Z=Y+x),se-te<w&&(k.includes("top")?te=se-w:se=te+w);let q=T.point({x:Y,y:te}).x,me=T.point({x:Y,y:te}).y,be=T.point({x:Z,y:te}).x,S=T.point({x:Y,y:se}).y,E=I=>Math.round(I*1e3)/1e3;return {x:E(q),y:E(me),width:E(be-q),height:E(S-me),rotation:g.rotation}};globalThis.queueMicrotask(()=>{f.boundBoxFunc(m);});},c=h=>{d(h);let u=h,p=typeof u.getChildren=="function"?u.getChildren():[];for(let f of p)c(f);};c(e.nodes.layer),this._nodesAddHandler=h=>{let u=h.child??h.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 m of this._transformersCache)m.moveToTop();}},this._nodesRemoveHandler=h=>{let u=h.child??h.target,p=v=>{let _=v;(typeof _.getClassName=="function"?_.getClassName():"")==="Transformer"&&v.boundBoxFunc?.(void 0);let b=typeof _.getChildren=="function"?_.getChildren():[];for(let y of b)p(y);};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 v of this._transformersCache)v.moveToTop();},e.nodes.layer.on("add.grid",this._nodesAddHandler),e.nodes.layer.on("remove.grid",this._nodesRemoveHandler),e.nodes.layer.on("cornerRadiusChange.grid",h=>{let u=h.target;if((typeof u.getClassName=="function"?u.getClassName():"")!=="Rect")return;let f=u.cornerRadius;if(typeof f!="function")return;let m=f.call(u),v=y=>{u.cornerRadius(y);},_=this._core?.stage,g=_?.scaleX()??1,b=this._minScaleToShow!=null?g>=this._minScaleToShow:false;if(Array.isArray(m)){let y=m.map(N=>{if(b){let x=_?.scaleX()??1,w=_?.scaleY()??1,k=N*(.5*(x+w));return Math.max(0,Math.round(k))/Math.max(1e-6,.5*(x+w))}else return Math.max(0,Math.round(N))});v(y);}else if(typeof m=="number")if(b){let y=_?.scaleX()??1,N=_?.scaleY()??1,x=m*(.5*(y+N)),w=Math.max(0,Math.round(x));v(w/Math.max(1e-6,.5*(y+N)));}else v(Math.max(0,Math.round(m)));});}_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 at=class extends H{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 r=t.getChildren();for(let l of r){let d=this._findBaseNodeByKonva(l);if(d){let c=this._captureTransformState(d);this._dragStartStateCache.set(d.id,c),this._debug("dragstart (temp-multi child)",{nodeId:d.id});}}return}let i=this._findBaseNodeByKonva(t);if(i){let s=this._captureTransformState(i);this._dragStartStateCache.set(i.id,s),this._debug("dragstart",{nodeId:i.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 o=t.name();if(typeof o=="string"&&o.includes("temp-multi-group")){this._isBatchMode=true,this._batchBuffer=[];let r=t.getChildren();for(let l of r){let d=this._findBaseNodeByKonva(l);if(d){let c=this._captureTransformState(d);this._dragStartStateCache.set(d.id,c),this._debug("transformstart (temp-multi child)",{nodeId:d.id});}}return}let i=this._findBaseNodeByKonva(t);if(i){let s=this._captureTransformState(i);this._dragStartStateCache.set(i.id,s),this._debug("transformstart",{nodeId:i.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),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),i=this._buildAfterState(e,t);if(!o){this._debug("transform - no before state, saving current",e.id),this._dragStartStateCache.set(e.id,i);return}if(this._statesEqual(o,i)){this._debug("transform skipped - no changes",e.id);return}let s={type:"transform",nodeId:e.id,before:o,after:i,timestamp:Date.now()};this._debug("transform recorded",{nodeId:e.id,before:o,after:i,batchMode:this._isBatchMode}),this._isBatchMode?(this._batchBuffer.push(s),this._scheduleBatchCommit()):(this._history.push(s),this._trimHistoryIfNeeded()),this._dragStartStateCache.set(e.id,i);});a(this,"_onZIndexChanged",(e,t,o)=>{if(this._isUndoRedoInProgress)return;let i={type:"zIndex",nodeId:e.id,before:{zIndex:t},after:{zIndex:o},timestamp:Date.now()};this._history.push(i),this._trimHistoryIfNeeded();});a(this,"_onGroupCreated",(e,t)=>{if(this._isUndoRedoInProgress)return;let o=t.map(r=>this._serializeNode(r)),i=t.map(r=>r.id),s={type:"group",nodeId:e.id,before:{childIds:i,childStates:o},after:this._serializeNode(e),timestamp:Date.now()};this._history.push(s),this._trimHistoryIfNeeded();});a(this,"_onGroupUngrouped",(e,t)=>{if(this._isUndoRedoInProgress)return;let o=this._serializeNode(e),i=t.map(r=>this._serializeNode(r)),s={type:"ungroup",nodeId:e.id,before:o,after:{childStates:i},timestamp:Date.now()};this._history.push(s),this._trimHistoryIfNeeded();});this._history=new Me;let{target:t=globalThis,ignoreEditableTargets:o=true,maxHistoryLength:i=100}=e;this._options={target:t,ignoreEditableTargets:o,maxHistoryLength:i};}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 i=this._core.nodes.findById(e.nodeId);i&&this._core.nodes.remove(i);}else o&&this._recreateNode(o);break;case "remove":if(t==="before")o&&this._recreateNode(o);else {let i=this._core.nodes.findById(e.nodeId);i&&this._core.nodes.remove(i);}break;case "transform":if(o&&typeof o=="object"){let i=this._core.nodes.findById(e.nodeId);this._debug("transform apply",{nodeId:e.nodeId,nodeFound:!!i,state:o}),i&&this._applyTransformState(i,o);}break;case "zIndex":if(o&&typeof o=="object"&&"zIndex"in o){let i=this._core.nodes.findById(e.nodeId);i&&i.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 i=t==="before"?[...e.children].reverse():e.children;for(let s of i)this._applyActionState(s,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 i=o;typeof t.cornerRadius=="number"&&typeof i.cornerRadius=="function"&&i.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 i=e.before;this._core.nodes.remove(o);for(let s of i.childStates)this._recreateNode(s);}}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 i=e.after;this._core.nodes.remove(o);for(let s of i.childStates)this._recreateNode(s);}}}_recreateNode(e){if(!this._core)return null;let{nodeType:t,attrs:o}=e,{id:i,zIndex:s,...r}=o;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 "group":{if(l=this._core.nodes.addGroup(r),e.children&&e.children.length>0){let d=l.getKonvaNode();for(let c of e.children){let h=this._recreateNode(c);h&&h.getKonvaNode().moveTo(d);}}break}default:return this._debug("recreateNode",`unknown type: ${t}`),null}if(e.parentId){let d=this._core.nodes.findById(e.parentId);if(d){let c=d.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(),o=t.getAttrs(),i=this._getNodeType(t),s={nodeType:i,nodeId:e.id,attrs:{...o}},r=t.getParent();if(r&&this._core){let l=this._findBaseNodeByKonva(r);if(l&&l.id!==e.id){let d=this._core.nodes.world;r!==d&&(s.parentId=l.id);}}if(i==="group"){let d=t.getChildren();s.children=[];for(let c of d){let h=this._findBaseNodeByKonva(c);h&&s.children.push(this._serializeNode(h));}}return s}_captureTransformState(e){let t=e.getKonvaNode(),o=t.getAbsoluteTransform().decompose(),i={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"&&(i.width=t.width()),typeof t.height=="function"&&(i.height=t.height());let s=t;return typeof s.cornerRadius=="function"&&(i.cornerRadius=s.cornerRadius()),i}_buildAfterState(e,t){let o=e.getKonvaNode(),i=t.x??o.x(),s=t.y??o.y(),r=t.rotation??o.rotation(),l=t.scaleX??o.scaleX(),d=t.scaleY??o.scaleY(),c={absX:i,absY:s,absRotation:r,absScaleX:l,absScaleY:d,x:i,y:s,rotation:r,scaleX:l,scaleY:d};typeof o.width=="function"&&(c.width=t.width??o.width()),typeof o.height=="function"&&(c.height=t.height??o.height());let h=o;return typeof h.cornerRadius=="function"&&(c.cornerRadius=h.cornerRadius()),c}_getNodeType(e){let t=e.getClassName();return {Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Image:"image",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 i=["absX","absY","absRotation","absScaleX","absScaleY"];for(let r of i){let l=e[r],d=t[r];if(typeof l=="number"&&typeof d=="number"){if(Math.abs(l-d)>.001)return false}else if(l!==d)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 dt=class extends H{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 M__default.default.Layer({name:"logo-layer",listening:false}),this._core.stage.add(this._layer),this._image=new M__default.default.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){M__default.default.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(),i=e.scaleX(),s=e.position(),r={x:Math.floor(t/2),y:Math.floor(o/2)};this._image.scale({x:1/i,y:1/i});let l=this._width,d=this._height;this._image.size({width:l,height:d}),this._image.offset({x:l/2,y:d/2});let c=(r.x-s.x)/i,h=(r.y-s.y)/i;this._image.position({x:c,y:h}),this._image.opacity(this._opacity),this._layer&&this._layer.moveToBottom();}};var ht=class extends H{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_clipboard",null);a(this,"_selectionPlugin");a(this,"_onKeyDown",e=>{if(!this._core)return;if(!this._selectionPlugin){let i=this._core.plugins.list().find(s=>s instanceof ve);i&&(this._selectionPlugin=i);}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 i=this._getSelectedNodes();if(i.length===1&&i[0]instanceof xe){e.preventDefault(),i[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"){e.preventDefault(),this._handlePaste();return}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);}onDetach(e){this._options.target.removeEventListener("keydown",this._onKeyDown),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(i=>this._serializeNode(i)),o=this._computeSelectionWorldCenter(e);this._clipboard={nodes:t,center:o},this._core&&this._core.eventBus.emit("clipboard:copy",e);}_handleCut(){let e=this._getSelectedNodes();if(e.length===0)return;let t=e.map(i=>this._serializeNode(i)),o=this._computeSelectionWorldCenter(e);this._clipboard={nodes:t,center:o},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 i of this._clipboard.nodes){let s=i.position.x-t.x,r=i.position.y-t.y,l=this._deserializeNode(i,{x:e.x+s,y:e.y+r});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 i=e.getChildren(),s=this._core.nodes.list(),r=new Set;for(let l of i){let d=s.find(c=>c.getKonvaNode()===l);d&&r.add(d);}if(r.size>0)return Array.from(r)}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(),i=this._getNodeTypeFromKonva(t),s={x:0,y:0};if(this._core){let d=t.getAbsolutePosition(),h=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(d);s={x:h.x,y:h.y};}let r={type:i,config:{...o,id:void 0},position:s};if(i==="group"){let d=t.getChildren(),c=[];for(let h of d){let u=this._serializeKonvaNode(h);u&&c.push(u);}c.length>0&&(r.children=c);}return r}_serializeKonvaNode(e){if(!this._core)return null;let t=e.getAttrs(),i=e.getClassName().toLowerCase();i==="rect"&&(i="shape");let s={type:i,config:{...t,id:void 0},position:{x:e.x(),y:e.y()}};if(e instanceof M__default.default.Group){let r=e.getChildren(),l=[];for(let d of r){let c=this._serializeKonvaNode(d);c&&l.push(c);}l.length>0&&(s.children=l);}return s}_getNodeTypeFromKonva(e){let t=e.getClassName();return {Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Image:"image",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,...i}=e.config,s={...i,x:t.x,y:t.y};try{let r=null;switch(e.type){case "shape":r=this._core.nodes.addShape(s);break;case "text":r=this._core.nodes.addText(s);break;case "circle":r=this._core.nodes.addCircle(s);break;case "ellipse":r=this._core.nodes.addEllipse(s);break;case "arc":r=this._core.nodes.addArc(s);break;case "star":r=this._core.nodes.addStar(s);break;case "arrow":r=this._core.nodes.addArrow(s);break;case "ring":r=this._core.nodes.addRing(s);break;case "regularPolygon":case "regularpolygon":r=this._core.nodes.addRegularPolygon(s);break;case "image":r=this._core.nodes.addImage(s);break;case "label":return globalThis.console.warn("LabelNode is not supported for copy/paste yet"),null;case "group":{r=this._core.nodes.addGroup(s);let d=r.getKonvaNode();if(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),e.children&&e.children.length>0)for(let c of e.children){let h=this._deserializeNode(c,{x:c.position.x,y:c.position.y});if(h){let u=h.getKonvaNode();typeof u.draggable=="function"&&u.draggable(!1),u.moveTo(d);}}break}default:return globalThis.console.warn(`Unknown node type: ${e.type}`),null}let l=r.getKonvaNode();return e.config.scaleX!==void 0&&l.scaleX(e.config.scaleX),e.config.scaleY!==void 0&&l.scaleY(e.config.scaleY),e.config.rotation!==void 0&&l.rotation(e.config.rotation),e.config.skewX!==void 0&&l.skewX(e.config.skewX),e.config.skewY!==void 0&&l.skewY(e.config.skewY),e.config.offsetX!==void 0&&l.offsetX(e.config.offsetX),e.config.offsetY!==void 0&&l.offsetY(e.config.offsetY),r}catch(r){return globalThis.console.error("Failed to deserialize node:",r),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,o=t.width(),i=t.height();return e.x>=0&&e.x<=o&&e.y>=0&&e.y<=i}_getScreenCenter(){if(!this._core)return {x:0,y:0};let e=this._core.stage,t=this._core.nodes.world,o=e.width()/2,i=e.height()/2,r=t.getAbsoluteTransform().copy().invert().point({x:o,y:i});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 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,i=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),o=Math.min(o,f.y),i=Math.max(i,f.x+f.width),s=Math.max(s,f.y+f.height);}if(!isFinite(t)||!isFinite(o)||!isFinite(i)||!isFinite(s))return {x:0,y:0};let r=(t+i)/2,l=(o+s)/2,h=this._core.nodes.world.getAbsoluteTransform().copy().invert().point({x:r,y:l});return {x:h.x,y:h.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 i=o.zIndex();o.moveUp();let s=o.zIndex();this._syncGroupZIndex(o),this._core&&i!==s&&this._core.eventBus.emit("node:zIndexChanged",t,i,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 o=e[t];if(!o)continue;let i=o.getKonvaNode();if(this._isNodeInsidePermanentGroup(i))continue;let s=i.zIndex();i.moveDown();let r=i.zIndex();this._syncGroupZIndex(i),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",o,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((o,i)=>{let s=o.getKonvaNode(),r=i.getKonvaNode();return s.zIndex()-r.zIndex()});for(let o of t){let i=o.getKonvaNode();if(this._isNodeInsidePermanentGroup(i))continue;let s=i.zIndex();i.moveToTop();let r=i.zIndex();this._syncGroupZIndex(i),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",o,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((o,i)=>{let s=o.getKonvaNode();return i.getKonvaNode().zIndex()-s.zIndex()});for(let o of t){let i=o.getKonvaNode();if(this._isNodeInsidePermanentGroup(i))continue;let s=i.zIndex();i.moveToBottom();let r=i.zIndex();this._syncGroupZIndex(i),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",o,s,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_isNodeInsidePermanentGroup(e){if(e instanceof M__default.default.Group)return false;let t=e.getParent();return !(!t||!(t instanceof M__default.default.Group)||t===this._core?.nodes.world)}_syncGroupZIndex(e){let t=e.getParent();t&&(e instanceof M__default.default.Group||t instanceof M__default.default.Group&&t.name());}};var ge=class extends H{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:i=30,snapToGrid:s=true,gridStep:r=1}=e;this._options={guideColor:t,activeColor:o,rulerThicknessPx:i,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 M__default.default.Layer({name:"guides-layer"}),e.stage.add(this._guidesLayer),this._guidesLayer.moveToTop();let o=e.stage,i=this._options.rulerThicknessPx;o.on("mousedown.ruler-guides",()=>{let r=o.getPointerPosition();if(!r)return;let l=o.getIntersection(r);l&&(l.name()==="guide-h"||l.name()==="guide-v")||(r.y<=i&&r.x>=i?this._startCreateGuide("h"):r.x<=i&&r.y>=i?this._startCreateGuide("v"):this._setActiveGuide(null));}),o.on("mousemove.ruler-guides",()=>{let r=o.getPointerPosition();if(!r)return;let l=o.getIntersection(r);if(l){let d=l.name();if(d==="guide-h"||d==="guide-v"||d.includes("_anchor")||d.includes("rotater")||l.draggable())return}r.y<=i&&r.x>=i?o.container().style.cursor="ns-resize":r.x<=i&&r.y>=i?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(),i=e.y(),s=this._core.stage.width(),r=this._core.stage.height(),l=[0,0,s,0],d=[0,0,0,r];for(let c of this._guides){let h=c.worldCoord;if(c.name()==="guide-h"){let p=i+h*t;c.position({x:0,y:p}),c.points(l);}else {let p=o+h*t;c.position({x:p,y:0}),c.points(d);}}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,i=o.scaleX(),s=t.getPointerPosition();if(!s)return;let r=e==="h"?(s.y-o.y())/i:(s.x-o.x())/i,l=this._snapToGrid(r),d=new M__default.default.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,m=f.scaleX();if(e==="h"){let v=(p.y-f.y())/m,_=this._snapToGrid(v);return {x:0,y:f.y()+_*m}}else {let v=(p.x-f.x())/m,_=this._snapToGrid(v);return {x:f.x()+_*m,y:0}}}});d.worldCoord=l,d.on("mouseenter",()=>{this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize"),this._scheduleBatchDraw();}),d.on("mouseleave",()=>{this._core&&!this._draggingGuide&&(this._core.stage.container().style.cursor="default"),this._scheduleBatchDraw();}),d.on("click",()=>{this._setActiveGuide(d);}),d.on("dragstart",()=>{let p=d;this._draggingGuide={type:e,line:p},this._setActiveGuide(p),this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize");}),d.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(),m=d.getAbsolutePosition(),v=e==="h"?(m.y-p.y())/f:(m.x-p.x())/f,_=this._snapToGrid(v);d.worldCoord=_,this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize",this._rulerLayerCache&&this._rulerLayerCache.batchDraw();}));}),d.on("dragend",()=>{this._draggingGuide=null,this._core&&(this._core.stage.container().style.cursor=e==="h"?"ns-resize":"ew-resize");});let c=d;this._guidesLayer.add(c),this._guides.push(c),this._setActiveGuide(c),e==="h"?(d.position({x:0,y:o.y()+l*i}),d.points([0,0,t.width(),0])):(d.position({x:o.x()+l*i,y:0}),d.points([0,0,0,t.height()])),this._draggingGuide={type:e,line:c};let h=()=>{if(!this._draggingGuide||!this._core)return;let p=this._core.stage.getPointerPosition();if(!p)return;let f=this._core.nodes.world,m=f.scaleX(),v=e==="h"?(p.y-f.y())/m:(p.x-f.x())/m,_=this._snapToGrid(v);d.worldCoord=_,e==="h"?(d.position({x:0,y:f.y()+_*m}),d.points([0,0,this._core.stage.width(),0])):(d.position({x:f.x()+_*m,y:0}),d.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",h),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 Ce=class extends H{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 _e);a(this,"_transformersCache",[]);a(this,"_cacheInvalidated",true);let{highlightColor:t="#2b83ff",highlightOpacity:o=.3,rulerThicknessPx:i=30}=e;this._options={highlightColor:t,highlightOpacity:o,rulerThicknessPx:i};}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 m of this._hHighlights)m.destroy();this._hHighlights=[];for(let m of this._vHighlights)m.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,i=t.width(),s=t.height(),r=this._options.rulerThicknessPx,l=o.scaleX(),d=o.x(),c=o.y(),h=[],u=[];for(let m of e){let v=m.getClientRect({relativeTo:o}),_=d+v.x*l,g=d+(v.x+v.width)*l,b=c+v.y*l,y=c+(v.y+v.height)*l;if(_<i&&g>r){let N=Math.max(r,_),x=Math.min(i,g);N<x&&h.push({start:N,end:x});}if(b<s&&y>r){let N=Math.max(r,b),x=Math.min(s,y);N<x&&u.push({start:N,end:x});}}let p=this._mergeSegments(h),f=this._mergeSegments(u);if(this._hGroup)for(let m of p){let v=new M__default.default.Rect({x:m.start,y:0,width:m.end-m.start,height:r,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-h"});this._hGroup.add(v),v.setZIndex(1),this._hHighlights.push(v);}if(this._vGroup)for(let m of f){let v=new M__default.default.Rect({x:0,y:m.start,width:r,height:m.end-m.start,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-v"});this._vGroup.add(v),v.setZIndex(1),this._vHighlights.push(v);}this._highlightLayer.batchDraw();}_collectNodes(e,t){let o=e.getClassName(),i=e.name(),r=["overlay-hit","ruler-","guide-","_anchor","back","rotater"].some(l=>i.includes(l));if(!(o==="Transformer"||o==="Layer"||r))if(o==="Group"){let d=e.getChildren();if(d.length===0)return;for(let c of d)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),o=t[0];if(!o)return [];let i=[],s={start:o.start,end:o.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):(i.push(s),s={start:l.start,end:l.end}));}return i.push(s),i}_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 i=o.nodes();for(let s of i)e.includes(s)||e.push(s);}}catch{}let t=[];for(let o of e)this._collectNodes(o,t);return t}update(){this._updateHighlights();}};var Te=class extends H{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 ge);return e&&"getActiveGuide"in e&&"removeActiveGuide"in e&&e.getActiveGuide.call(e)?(e.removeActiveGuide.call(e),true):false}};var ct=class extends H{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:i=10,color:s="#8c8c8c",bgColor:r="#2c2c2c",borderColor:l="#1f1f1f",enabled:d=true}=e;this._options={thicknessPx:t,fontFamily:o,fontSizePx:i,color:s,bgColor:r,borderColor:l,enabled:d};}_calculateNiceStep(e){if(!isFinite(e)||e<=0)return 1;let t=Math.pow(10,Math.floor(Math.log10(e))),o=e/t,i;return o<=1?i=1:o<=2?i=2:o<=5?i=5:i=10,i*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,s=50/e,r=this._calculateNiceStep(s);r<1&&(r=1);let l=r*e,d,c,h,u;l>=60?(d=r*10,c=r*5,h=r,u=r):l>=40?(d=r*10,c=r*5,h=r*5,u=r):(d=r*10,c=r*5,h=r*10,u=r);let p={step:r,stepPx:l,majorStep:d,mediumStep:c,labelStep:h,drawStep:u,drawStepEpsilon:u*.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,p),p}onAttach(e){this._core=e,this._layer=new M__default.default.Layer({name:"ruler-layer",listening:true}),this._options.enabled&&e.stage.add(this._layer),this._hGroup=new M__default.default.Group({listening:true}),this._vGroup=new M__default.default.Group({listening:true}),this._layer.add(this._hGroup),this._layer.add(this._vGroup),this._hBg=new M__default.default.Rect({fill:this._options.bgColor,listening:true,name:"ruler-h-bg"}),this._vBg=new M__default.default.Rect({fill:this._options.bgColor,listening:true,name:"ruler-v-bg"}),this._hGroup.add(this._hBg),this._vGroup.add(this._vBg),this._hBorder=new M__default.default.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._vBorder=new M__default.default.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._hGroup.add(this._hBorder),this._vGroup.add(this._vBorder),this._hTicksShape=new M__default.default.Shape({listening:false,sceneFunc:i=>{let s=this._getActiveGuideInfo();this._drawHorizontalRuler(i,s);}}),this._hGroup.add(this._hTicksShape),this._vTicksShape=new M__default.default.Shape({listening:false,sceneFunc:i=>{let s=this._getActiveGuideInfo();this._drawVerticalRuler(i,s);}}),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 i=o;if(i.strokeWidth()===2){let s=i.worldCoord,r=i.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,o){if(!this._core)return;let i=this._core.stage,s=this._core.nodes.world,r=s.scaleX()||1e-9,l=this._options.thicknessPx,d=t==="h",c=d?i.width():i.height(),h=d?s.x():s.y(),u=o?.type===(d?"v":"h")?o.coord:null,p=this._getStepsConfig(r),{majorStep:f,mediumStep:m,labelStep:v,drawStep:_,drawStepEpsilon:g,majorTickLength:b,mediumTickLength:y,minorTickLength:N,fontString:x}=p;e.save();let w=-h/r,k=Math.floor(w/_)*_,T=[],A=[],R=[],D=[],B=null;for(let K=k;;K+=_){let L=h+K*r;if(L>c)break;if(L<0)continue;if(u!==null&&Math.abs(K-u)<g){B=L,D.push({pos:L,text:this._formatNumber(K)});continue}let j=Math.abs(K%f)<g,ae=!j&&Math.abs(K%m)<g;j?T.push(L):ae?A.push(L):R.push(L),Math.abs(K%v)<g&&D.push({pos:L,text:this._formatNumber(K)});}if(R.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.4,e.lineWidth=1,e.beginPath();for(let K of R)d?(e.moveTo(K,l),e.lineTo(K,l-N)):(e.moveTo(l,K),e.lineTo(l-N,K));e.stroke();}if(A.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.6,e.lineWidth=1,e.beginPath();for(let K of A)d?(e.moveTo(K,l),e.lineTo(K,l-y)):(e.moveTo(l,K),e.lineTo(l-y,K));e.stroke();}if(T.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.9,e.lineWidth=1,e.beginPath();for(let K of T)d?(e.moveTo(K,l),e.lineTo(K,l-b)):(e.moveTo(l,K),e.lineTo(l-b,K));e.stroke();}if(B!==null&&(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),d?(e.moveTo(B,l),e.lineTo(B,l-b)):(e.moveTo(l,B),e.lineTo(l-b,B)),e.stroke()),D.length>0){e.font=x,e.textBaseline="top",e.textAlign="left";for(let K of D){let L=K.pos===B;if(e.globalAlpha=L?1:.9,e.fillStyle=L?"#ff8c00":this._options.color,d)e.fillText(K.text,K.pos+4,4);else {let j=K.pos+4;e.setTransform(0,-1,1,0,4,j),e.fillText(K.text,0,0),e.setTransform(1,0,0,1,0,0);}}}if(u!==null){let K=h+u*r;if(K>=0&&K<=c&&!(Math.abs(u%_)<g))if(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),d?(e.moveTo(K,l),e.lineTo(K,l-b)):(e.moveTo(l,K),e.lineTo(l-b,K)),e.stroke(),e.fillStyle="#ff8c00",e.font=x,e.textBaseline="top",e.textAlign="left",d)e.fillText(this._formatNumber(u),K+4,4);else {let j=K+4;e.setTransform(0,-1,1,0,4,j),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(),o=e.height(),i=this._options.thicknessPx;this._hBg&&this._hBg.size({width:t,height:i}),this._vBg&&this._vBg.size({width:i,height:o}),this._hBorder&&this._hBorder.points([0,i,t,i]),this._vBorder&&this._vBorder.points([i,0,i,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 i=e?this._panThrottleMs:this._redrawThrottleMs;if(o>=i)globalThis.requestAnimationFrame(()=>{this._redrawScheduled=false,this._lastRedrawTime=globalThis.performance.now(),this._redraw();});else {let s=i-o;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 ut=class extends H{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_layer",null);a(this,"_dragMoveHandler",null);a(this,"_dragEndHandler",null);a(this,"_nodesAddHandler",null);a(this,"_nodesRemoveHandler",null);let{guidelineColor:t="#8e3e2c",guidelineWidth:o=1,guidelineDash:i=[0,0],thresholdPx:s=8}=e;this._options={guidelineColor:t,guidelineWidth:o,guidelineDash:i,thresholdPx:s};}_applyGapSnappingForDrag(e,t,o){if(!this._core)return;let i=this._options.thresholdPx,s=e.getClientRect({skipShadow:true,skipStroke:false}),r=o.x-t.x,l=o.y-t.y,d={x:s.x+r,y:s.y+l,width:s.width,height:s.height},c=this._collectOtherNodeBoxes(e),h=i+1,u=0,p=i+1,f=0;for(let m of c){let v=m.box;if(!(d.y>v.y+v.height||d.y+d.height<v.y)){let b=d.x,y=d.x+d.width,N=v.x,x=v.x+v.width;if(N>=y){let w=N-y;w>0&&w<h&&(h=w,u=w);}if(x<=b){let w=b-x;w>0&&w<h&&(h=w,u=-w);}}if(!(d.x>v.x+v.width||d.x+d.width<v.x)){let b=d.y,y=d.y+d.height,N=v.y,x=v.y+v.height;if(N>=y){let w=N-y;w>0&&w<p&&(p=w,f=w);}if(x<=b){let w=b-x;w>0&&w<p&&(p=w,f=-w);}}}h<=i&&(o.x+=u),p<=i&&(o.y+=f);}onAttach(e){this._core=e;let t=new M__default.default.Layer({name:"snap-guides-layer"});e.stage.add(t),t.moveToTop(),this._layer=t,this._dragMoveHandler=i=>{this._onDragMove(i);},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=i=>{let r=i.child??i.target;this._walkAttachTransformers(r);},this._nodesRemoveHandler=i=>{let r=i.child??i.target;this._walkDetachTransformers(r);},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,i=e.target;if(i===t||i instanceof M__default.default.Layer)return;let s=i,r=false;for(;s;){if(s===o){r=true;break}s=s.getParent();}if(!r)return;let l=i;if(typeof l.draggable=="function"&&!l.draggable())return;this._clearGuides();let d=this._getLineGuideStops(i),c=this._getObjectSnappingEdges(i),h=this._getGuides(d,c);if(!h.length)return;let u=i.absolutePosition(),p={...u};for(let f of h)f.orientation==="V"?p.x=f.lineGuide+f.offset:p.y=f.lineGuide+f.offset;this._applyGapSnappingForDrag(i,u,p),i.absolutePosition(p),this._drawDragGuides(i);}_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),i=this._collectOtherNodeBoxes(e);if(!i.length)return;let s=16;for(let r of o){let l=[];for(let p of i){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 d=l.slice(0,s);if(!d.length)continue;let c=0;for(let p of d)p.tExit>c&&(c=p.tExit);if(c<=0)continue;let h;r.dir==="right"?h=[0,0,c,0]:r.dir==="left"?h=[0,0,-c,0]:r.dir==="down"?h=[0,0,0,c]:h=[0,0,0,-c];let u=new M__default.default.Line({points:h,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 d){let f=p.tEnter,m=p.tExit,v=this._pointOnRay(r.origin,r.dir,f),_=this._pointOnRay(r.origin,r.dir,m),g=p.box,b=0,y=0;if(r.dir==="right"){let N=t.x+t.width,x=g.x,w=g.x+g.width;b=x-N,y=w-N;}else if(r.dir==="left"){let N=t.x,x=g.x,w=g.x+g.width;b=N-w,y=N-x;}else if(r.dir==="down"){let N=t.y+t.height,x=g.y,w=g.y+g.height;b=x-N,y=w-N;}else {let N=t.y,x=g.y,w=g.y+g.height;b=N-w,y=N-x;}b=Math.max(0,b),y=Math.max(0,y),this._drawRayMarkerWithLabel(v.x,v.y,b,r.dir),this._drawRayMarkerWithLabel(_.x,_.y,y,r.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,i){if(!this._layer)return;let s=4,r=new M__default.default.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 M__default.default.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=[],o=e.x+e.width/2,i=e.y+e.height/2;t.push({origin:{x:o,y:i},dir:"up"},{origin:{x:o,y:i},dir:"down"},{origin:{x:o,y:i},dir:"left"},{origin:{x:o,y:i},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:i},dir:"left"},{origin:{x:e.x+e.width,y:i},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},d={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:d,dir:"down"},{origin:d,dir:"left"}),t}_collectOtherNodeBoxes(e){let t=[];if(!this._core)return t;let o=this._core.nodes.list();for(let i of o){let s=i.getKonvaNode();if(s===e)continue;let r=s,l=e;if(typeof r.isAncestorOf=="function"&&r.isAncestorOf(e)||typeof l.isAncestorOf=="function"&&l.isAncestorOf(s))continue;let d=s.getClientRect({skipShadow:true,skipStroke:false});t.push({node:s,box:{x:d.x,y:d.y,width:d.width,height:d.height}});}return t}_intersectRayWithBox(e,t,o){let i=e.x,s=e.y,r=o.x,l=o.y,d=o.x+o.width,c=o.y+o.height;if(t==="right"||t==="left"){if(s<l||s>c)return null;if(t==="right"){if(d<=i)return null;let h=Math.max(r,i),u=d,p=h-i,f=u-i;return f<=0||f<=p?null:{tEnter:p,tExit:f}}else {if(r>=i)return null;let h=Math.min(d,i),u=r,p=i-h,f=i-u;return f<=0||f<=p?null:{tEnter:p,tExit:f}}}if(i<r||i>d)return null;if(t==="down"){if(c<=s)return null;let h=Math.max(l,s),u=c,p=h-s,f=u-s;return f<=0||f<=p?null:{tEnter:p,tExit:f}}else {if(l>=s)return null;let h=Math.min(c,s),u=l,p=s-h,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,o=[0,t.width()/2,t.width()],i=[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 d=l,c=e;if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(e)||typeof c.isAncestorOf=="function"&&c.isAncestorOf(l))continue;let h=l.getClientRect({skipShadow:true,skipStroke:false});o.push(h.x,h.x+h.width,h.x+h.width/2),i.push(h.y,h.y+h.height,h.y+h.height/2);}return {vertical:o,horizontal:i}}_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=[],i=[],s=this._options.thresholdPx;for(let l of e.vertical)for(let d of t.vertical){let c=Math.abs(l-d.guide);c<s&&o.push({lineGuide:l,diff:c,snap:d.snap,offset:d.offset});}for(let l of e.horizontal)for(let d of t.horizontal){let c=Math.abs(l-d.guide);c<s&&i.push({lineGuide:l,diff:c,snap:d.snap,offset:d.offset});}let r=[];if(o.length>0){let[l]=[...o].sort((d,c)=>d.diff-c.diff);l&&r.push({lineGuide:l.lineGuide,offset:l.offset,orientation:"V",snap:l.snap});}if(i.length>0){let[l]=[...i].sort((d,c)=>d.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,o=typeof t.getChildren=="function"?t.getChildren():[];for(let i of o)this._walkAttachTransformers(i);}_attachTransformer(e){let t=e;if((typeof t.getClassName=="function"?t.getClassName():"")!=="Transformer")return;let i=e;i.off(".snap-guides-resize"),i.on("transform.snap-guides-resize",()=>{this._handleTransformerTransform(i);}),i.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 i=typeof t.getChildren=="function"?t.getChildren():[];for(let s of i)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 i=(typeof e.nodes=="function"?e.nodes():[])[0];if(!i)return;let s=i,r=typeof s.getLayer=="function"?s.getLayer():null;if(!r||r!==this._core.nodes.layer)return;this._clearGuides();let l=this._getLineGuideStops(i),d=this._getObjectSnappingEdges(i),c=this._getGuides(l,d);if(!c.length)return;let h=i.absolutePosition();for(let u of c)u.orientation==="V"?h.x=u.lineGuide+u.offset:h.y=u.lineGuide+u.offset;i.absolutePosition(h),this._drawResizeGuides(e,i,c);}_drawResizeGuides(e,t,o){if(!this._core||!this._layer)return;let i=typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"";if(!i)return;let s=t.getClientRect({skipShadow:true,skipStroke:false}),r=o.some(p=>p.orientation==="V"),l=o.some(p=>p.orientation==="H"),c=this._buildResizeRays(i,s).filter(p=>!((p.dir==="left"||p.dir==="right")&&!l||(p.dir==="up"||p.dir==="down")&&!r));if(!c.length)return;let h=this._collectOtherNodeBoxes(t);if(!h.length)return;let u=16;for(let p of c){let f=[];for(let b of h){let y=this._intersectRayWithBox(p.origin,p.dir,b.box);y&&f.push({...y,box:b.box});}if(!f.length)continue;f.sort((b,y)=>b.tEnter-y.tEnter);let m=f.slice(0,u);if(!m.length)continue;let v=0;for(let b of m)b.tExit>v&&(v=b.tExit);if(v<=0)continue;let _;p.dir==="right"?_=[0,0,v,0]:p.dir==="left"?_=[0,0,-v,0]:p.dir==="down"?_=[0,0,0,v]:_=[0,0,0,-v];let g=new M__default.default.Line({points:_,stroke:this._options.guidelineColor,strokeWidth:this._options.guidelineWidth,name:"snap-guid-line",dash:this._options.guidelineDash,listening:false});this._layer.add(g),g.absolutePosition({x:p.origin.x,y:p.origin.y});for(let b of m){let y=b.tEnter,N=b.tExit,x=this._pointOnRay(p.origin,p.dir,y),w=this._pointOnRay(p.origin,p.dir,N),k=b.box,T=0,A=0;if(p.dir==="right"){let R=s.x+s.width,D=k.x,B=k.x+k.width;T=D-R,A=B-R;}else if(p.dir==="left"){let R=s.x,D=k.x,B=k.x+k.width;T=R-B,A=R-D;}else if(p.dir==="down"){let R=s.y+s.height,D=k.y,B=k.y+k.height;T=D-R,A=B-R;}else {let R=s.y,D=k.y,B=k.y+k.height;T=R-B,A=R-D;}T=Math.max(0,T),A=Math.max(0,A),this._drawRayMarkerWithLabel(x.x,x.y,T,p.dir),this._drawRayMarkerWithLabel(w.x,w.y,A,p.dir);}}this._layer.batchDraw();}_buildResizeRays(e,t){let o={x:t.x,y:t.y},i={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:o,dir:"up"},{origin:o,dir:"left"});break;case "top-right":l.push({origin:i,dir:"up"},{origin:i,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:o,dir:"up"},{origin:o,dir:"left"});break;case "middle-right":l.push({origin:i,dir:"up"},{origin:i,dir:"right"});break;case "top-center":l.push({origin:o,dir:"up"},{origin:o,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 o=t,i=typeof o.name=="function"?o.name():"";if(i.startsWith("rotate-")||i==="rotate-handles-group"||i.startsWith("corner-radius-")||i==="corner-radius-handles-group")return true;t=t.getParent();}return false}};var ce=class{attach(n){this.onAttach(n);}detach(n){this.onDetach(n);}};var pt=class extends ce{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(),i=Array.isArray(o)?o:[],s=t,r=typeof s.red=="function"?s.red():0,l=typeof s.green=="function"?s.green():0,d=typeof s.blue=="function"?s.blue():0,c=typeof s.alpha=="function"?s.alpha():1,h=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:[...i],prevRed:r,prevGreen:l,prevBlue:d,prevAlpha:c,prevHue:h,prevSaturation:u,prevLuminance:p,mouseEnterHandler:()=>{},mouseLeaveHandler:()=>{},hadHover:false};f.mouseEnterHandler=()=>{if(f.hadHover=true,t.cache({pixelRatio:this.pixelRatio}),this.mode==="sepia"){let m=t.filters(),v=Array.isArray(m)?m:[];v.includes(M__default.default.Filters.Sepia)||t.filters([...v,M__default.default.Filters.Sepia]);}else {let m=t.filters(),v=Array.isArray(m)?m:[];v.includes(M__default.default.Filters.HSL)||t.filters([...v,M__default.default.Filters.HSL]);let _=this.intensity,g=18,b=.2,y=g*_,N=b*_;switch(this.mode){case "warm":{typeof s.hue=="function"&&s.hue(f.prevHue+y),typeof s.saturation=="function"&&s.saturation(f.prevSaturation+N);break}case "cool":{typeof s.hue=="function"&&s.hue(f.prevHue-y),typeof s.saturation=="function"&&s.saturation(f.prevSaturation+N);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 o=e.getKonvaNode();o.off("mouseenter.imageHoverFilterAddon",t.mouseEnterHandler),o.off("mouseleave.imageHoverFilterAddon",t.mouseLeaveHandler),o.filters(t.prevFilters);let i=o;(this.mode==="warm"||this.mode==="cool")&&(typeof i.red=="function"&&i.red(t.prevRed),typeof i.green=="function"&&i.green(t.prevGreen),typeof i.blue=="function"&&i.blue(t.prevBlue),typeof i.alpha=="function"&&i.alpha(t.prevAlpha)),o.getLayer()?.batchDraw(),o.clearCache(),this.nodes.delete(e);}};var ue=class{attach(n,e){this.onAttach(n,e);}detach(n,e){this.onDetach(n,e);}};var ft=class extends ue{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(s=>s instanceof ge);if(o){this._instance=o,this._owned=false;return}let i=new ge(this._options);t.plugins.addPlugins([i]),this._instance=i,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var gt=class extends ue{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(s=>s instanceof Ce);if(o){this._instance=o,this._owned=false;return}let i=new Ce(this._options);t.plugins.addPlugins([i]),this._instance=i,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var _t=class extends ue{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(s=>s instanceof Te);if(o){this._instance=o,this._owned=false;return}let i=new Te(this._options);t.plugins.addPlugins([i]),this._instance=i,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 ce{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 mt=class extends ce{constructor(){super(...arguments);a(this,"nodes",new WeakMap);}onAttach(e){if(this.nodes.has(e))return;let t=o=>{if(o.cancelled)return;let i=this.normalize(o.newText);i!==o.newText&&(e.setText(i),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():""}};exports.AreaSelectionPlugin=it;exports.CameraHotkeysPlugin=st;exports.CameraManager=Ee;exports.CoreEngine=ot;exports.DebounceHelper=_e;exports.EventBus=Ae;exports.GridPlugin=rt;exports.HistoryManager=Me;exports.HistoryPlugin=at;exports.ImageHoverFilterAddon=pt;exports.LogoPlugin=dt;exports.NodeAddon=ce;exports.NodeAddons=Pe;exports.NodeHotkeysPlugin=ht;exports.NodeManager=Re;exports.PluginAddon=ue;exports.Plugins=Be;exports.RulerGuidesAddon=ft;exports.RulerGuidesPlugin=ge;exports.RulerHighlightAddon=gt;exports.RulerHighlightPlugin=Ce;exports.RulerManagerAddon=_t;exports.RulerManagerPlugin=Te;exports.RulerPlugin=ct;exports.SelectionPlugin=ve;exports.ShapeHoverHighlightAddon=vt;exports.TextAutoTrimAddon=mt;exports.ThrottleHelper=pe;exports.VisualGuidesPlugin=ut;
1
+ 'use strict';var H=require('konva');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var H__default=/*#__PURE__*/_interopDefault(H);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(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,r=(i.deltaY>0?-1:1)>0?e*n:e/n;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 ze=class extends B{constructor(i={}){let e=new H__default.default.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 Fe=class extends B{constructor(i={}){let e=new H__default.default.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 We=class extends B{constructor(i={}){let e=new H__default.default.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 Ve=class extends B{constructor(i={}){let e=new H__default.default.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(),n=1e3/this._targetFps;if(this._lastDrawTime!==0&&t-this._lastDrawTime<n){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)),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 r=i.getContext("2d");r&&(r.setTransform(o,0,0,o,0,0),this._canvas=i,this._ctx=r,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)),r=this._logicalHeight||Math.max(1,Math.round(this._node.height()||this._options.fallbackHeight));if(o*r*n*n>this._maxCanvasPixels){let l=Math.sqrt(this._maxCanvasPixels/(o*r));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: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=n,e.fillRect(0,0,c,u),e.strokeStyle=o,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 Xe=class extends B{constructor(e={}){let t=new H__default.default.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 n=globalThis.document.createElement("canvas");return this._canvas=n,this.konvaNode.setAttr("src",e),new Promise((o,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(n,(s,l)=>{if(n.width=l.width,n.height=l.height,s.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(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,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 ue=class extends B{constructor(i={}){let e=new H__default.default.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__default.default.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 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 r=globalThis.Image??null;if(!r){o(new Error("Image constructor is not available in current environment"));return}let s=new r,l=t;s.crossOrigin=l,s.onload=()=>{n(s);},s.onerror=()=>{o(new Error(`Failed to load image: ${e}`));},s.src=e;})}remove(){this._placeholder.stop(),super.remove();}};var Ue=class extends B{constructor(i={}){let e=new H__default.default.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 Ze=class extends B{constructor(i={}){let e=new H__default.default.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 je=class extends B{constructor(i){let e=new H__default.default.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 qe=class extends B{constructor(i={}){let e=new H__default.default.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 $e=class extends B{constructor(e={}){let t=new H__default.default.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,n){this.konvaNode.setAttr("src",e),this._isLoading=true,this._isLoaded=false,this._placeholder.start();try{await new Promise((o,r)=>{H__default.default.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),o();},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}`);n&&n(h),r(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 Ne=class extends B{constructor(e={}){let t=new H__default.default.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__default.default.Group&&t instanceof H__default.default.Group)){this._openTextarea();return}if(!this._groupEditClickResetAttached){let o=this.konvaNode.getStage();o&&(this._groupEditClickResetAttached=true,o.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(),n=Math.max(1,this.konvaNode.width()*e);this.konvaNode.width(n);let o=this.konvaNode.height(),r=Math.max(1,o*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 n=this.konvaNode.wrap(),o=t.split(`
2
+ `);if(n==="none")return Math.max(1,o.length);let r=Math.max(0,e),s=0;for(let l of o){if(l.length===0){s+=1;continue}if(n==="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 n=this._getWrappedLineCount(t),o=this.konvaNode.fontSize()*this.konvaNode.lineHeight(),r=Math.ceil(n*o+e);Number.isFinite(r)&&r>this.konvaNode.height()&&this.konvaNode.height(r);}_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 s=Math.ceil(o+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(),n=t.x||t.y||1,o=this.konvaNode.padding()*2,r=e.scrollWidth,s=e.scrollHeight,l=Math.max(1,r/n+o),h=Math.max(1,s/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(),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(n.top+t.y)+"px",r.style.left=String(n.left+t.x)+"px",r.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*o.x)+"px",r.style.fontSize=String(this.konvaNode.fontSize()*o.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 n of this._onTextChangeCallbacks)n({oldText:this._oldText,newText:t,cancelled:e});for(let n of this._onEditEndCallbacks)n();}};var Je=class extends B{constructor(e={}){let t=new H__default.default.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 n=this.konvaNode.getAttrs(),o=t.loop??n.loop??false,r=t.muted??n.muted??false,s=t.autoplay??n.autoplay,l=t.currentTime??n.currentTime??0,h=t.volume??n.volume??1,p=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=r,d.currentTime=l,d.volume=h,d.playbackRate=p,d.load(),this._videoElement=d,this.konvaNode.setAttr("src",e),this.konvaNode.setAttr("loop",o),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__default.default.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 Re=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__default.default.Layer,this._world=new H__default.default.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 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}addText(i){let e=new Ne(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 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}addEllipse(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}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 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}addArrow(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}addRing(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}addRegularPolygon(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}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 $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}addVideo(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}addGif(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}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 fe=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 Qe=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 et=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,"_updateScheduled",false);a(this,"_lod",null);this._enabled=n.enabled??true,this._bufferZone=n.bufferZone??200,this._throttle=new fe(n.throttleMs??16),n.lod&&(this._lod=new Qe(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=this._getNodeBBox(i);return !(e.x+e.width<this._viewport.x||e.x>this._viewport.x+this._viewport.width||e.y+e.height<this._viewport.y||e.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),r=n.getKonvaNode();o?(e.add(n.id),this._hiddenNodes.has(n.id)&&(r.visible(true),r.listening(true),this._hiddenNodes.delete(n.id),t++)):this._hiddenNodes.has(n.id)||(r.visible(false),r.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);});}_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 fe(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 tt=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 tt(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 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 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__default.default.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__default.default.Layer({listening:false}),this._stage.add(this._gridLayer),this.nodes=new Re(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 et(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=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 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,n.appendChild(s),n.appendChild(d),n.appendChild(h),n.appendChild(l),n.appendChild(c),n.appendChild(p),t.appendChild(n);let u=e.stage.container();u.style.position=u.style.position||"relative",u.appendChild(t),this._rootEl=t,this._controlsEl=n,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,v=_.findIndex(N=>Math.abs(N-m)<.001);v<0&&(v=0);let b=_[(v+1)%_.length];typeof b=="number"&&Number.isFinite(b)&&b>0&&f.setPlaybackRate(b),this._syncControls();});}_updateRangeFill(e,t){let n=Math.max(0,Math.min(1,t)),o=Math.round(n*100),r=this._options.uiTrackFilledColor,s=this._options.uiTrackColor;e.style.background="linear-gradient(to right, "+r+" 0%, "+r+" "+String(o)+"%, "+s+" "+String(o)+"%, "+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=n=>{if(!this._rootEl||!this._selectedVideoNode)return;let o=n.target,r=typeof o?.name=="function"?o.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 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 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 _=o.width/360,m=this._uiMode==="full"?.75:this._uiMode==="compact"?.68:.6,v=Math.max(m,Math.min(1,_));this._controlsEl.style.transform="scale("+String(v)+")";let N=Math.max(64,Math.min(240,o.height))/240,y=Math.max(10,Math.min(28,28*N)),w=Math.max(4,Math.min(10,10*N)),x=this._controlsEl.getBoundingClientRect(),k=x.width,C=x.height,P=o.y+o.height+y+w,A=o.y-y-w-C,L=Math.max(0,c-C-this._options.marginPx),R=P;P>L&&A>=0&&(R=A),R=Math.max(this._options.marginPx,Math.min(L,R));let E=o.x+o.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(R)+"px",this._controlsEl.style.right="",this._controlsEl.style.bottom="";}let u=typeof n.cornerRadius=="function"?n.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,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),r=n%60,s=r<10?"0"+String(r):String(r);return String(o)+":"+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 ke(S){if(S instanceof H__default.default.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__default.default.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 Se(S,i){let{x:e,y:t,width:n,height:o}=i;switch(S){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 ge(S,i,e,t=6){if(!S||!i||!e)return;let n=e.getClientRect({skipShadow:true,skipStroke:false}),o=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),r=e.getAbsoluteScale(),s=Math.abs(r.x)||1,l=Math.abs(r.y)||1,h=o.width*s,p=o.height*l,d=(()=>{let m=e.getAbsoluteTransform().decompose();return typeof m.rotation=="number"?m.rotation:0})(),c=Math.abs((d%180+180)%180)>.5,u=i.findOne(".top-center"),f=i.findOne(".middle-right"),g=i.findOne(".bottom-center"),_=i.findOne(".middle-left");if(u){let m=c?h:n.width,v=t;u.setAttrs({opacity:0,width:m,height:v,offsetX:m/2,offsetY:0});}if(g){let m=c?h:n.width,v=t;g.setAttrs({opacity:0,width:m,height:v,offsetX:m/2,offsetY:v});}if(_){let m=t,v=c?p:n.height;_.setAttrs({opacity:0,width:m,height:v,offsetX:0,offsetY:v/2});}if(f){let m=t,v=c?p:n.height;f.setAttrs({opacity:0,width:m,height:v,offsetX:m,offsetY:v/2});}}function he(S){return new H__default.default.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 ot=class{constructor(i){a(this,"core");a(this,"getKonvaNode");a(this,"getTransformer");a(this,"onUpdate");a(this,"group",null);a(this,"handles",{tl:null,tr:null,br:null,bl:null});a(this,"dragState",null);a(this,"centerAbsStart",null);this.core=i.core,this.getKonvaNode=i.getNode,this.getTransformer=i.getTransformer,i.onUpdate&&(this.onUpdate=i.onUpdate);}attach(){if(!this.getKonvaNode())return;let e=this.core.nodes.layer;this.detach();let t=new H__default.default.Group({name:"rotate-handles-group",listening:true});e.add(t),this.group=t;let n=he("rotate-tl"),o=he("rotate-tr"),r=he("rotate-br"),s=he("rotate-bl");t.add(n),t.add(o),t.add(r),t.add(s),this.handles={tl:n,tr:o,br:r,bl:s};let l=h=>{h.on("mouseenter.rotate",()=>{this.core.stage.container().style.cursor="pointer";}),h.on("mouseleave.rotate",()=>{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},this.core.stage.draggable(false),this.core.stage.container().style.cursor="grabbing",this.getTransformer()?.moveToTop(),this.placeBelowTransformer();}),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),_=this.getTransformer();if(p.evt.shiftKey&&_){let v=w=>{let x=w%360;return x<0&&(x+=360),x},b=(w,x)=>v(w-x+180)-180,N=Array.isArray(_.rotationSnaps())?_.rotationSnaps().map(w=>v(w)):void 0,y=typeof _.rotationSnapTolerance=="function"?_.rotationSnapTolerance():5;if(N?.length){let w=v(g),x=g,k=1/0;for(let C of N){let P=Math.abs(b(w,C));P<k&&P<=y&&(x=C,k=P);}k!==1/0&&(g=x);}}if(d.rotation(g),this.centerAbsStart){let v=this.getNodeCenterAbs(d),b=this.centerAbsStart.x-v.x,N=this.centerAbsStart.y-v.y,y=d.getParent();if(y){let w=y.getAbsoluteTransform().copy().invert(),x=w.point({x:v.x,y:v.y}),k=w.point({x:v.x+b,y:v.y+N}),C=d.x()+(k.x-x.x),P=d.y()+(k.y-x.y);d.position({x:C,y:P});}}let m=this.getTransformer();m?.forceUpdate(),m&&ge(this.core,m,d),this.updatePosition(),this.placeBelowTransformer(),this.core.nodes.layer.batchDraw(),this.onUpdate&&this.onUpdate();}),h.on("dragend.rotate",()=>{this.dragState=null,this.centerAbsStart=null,this.core.stage.draggable(false),this.updatePosition(),this.placeBelowTransformer(),this.core.stage.container().style.cursor="pointer",this.onUpdate&&this.onUpdate();});};l(n),l(o),l(r),l(s),this.updatePosition(),this.placeBelowTransformer();}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(),r=w=>o.point(w),s=12,l=r({x:e.x+t/2,y:e.y+n/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+n}),c=r({x:e.x,y:e.y+n}),u=w=>{let x=w.x-l.x,k=w.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),v={x:h.x+f.x*s,y:h.y+f.y*s},b={x:p.x+g.x*s,y:p.y+g.y*s},N={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(v),this.handles.tr&&this.handles.tr.absolutePosition(b),this.handles.br&&this.handles.br.absolutePosition(N),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(),n=this.group.zIndex();if(n>=t){let o=n-t+1;for(let r=0;r<o&&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}),n=t.x+t.width/2,o=t.y+t.height/2;return e.point({x:n,y:o})}};var it=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 H__default.default.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.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=n,ge(this.core,n,i);let o=()=>{let s=typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"",l=s==="top-left"||s==="top-right"||s==="bottom-left"||s==="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=ke(i),p=Se(l,h);if(!p){this.transformOppositeCorner=null;return}let d=i.getAbsoluteTransform();this.transformOppositeCorner=d.point({x:p.x,y:p.y});}),n.on("transform.overlayKeepRatio",o);let r=()=>{if(this.boundNode){if(this.transformOppositeCorner){let l=(typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"")??"",h=this.boundNode.getAbsoluteTransform(),p=ke(this.boundNode),d=Se(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(),v={x:m.x+u,y:m.y+f},b=_.point(v);this.boundNode.position(b);}}this.tr?.forceUpdate(),ge(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),t.batchDraw();}};n.on("transform.overlayFrameTransform",r),n.on("transformend.overlayFrameTransform",()=>{this.transformOppositeCorner=null,r();}),this.ensureSizeLabel(),this.updateSizeLabel(),this.updateHitRect(),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null),this.rotateCtrl=new ot({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();}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(),ge(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__default.default.Label({listening:false,opacity:.95}),t=new H__default.default.Tag({fill:"#2b83ff",cornerRadius:4,lineJoin:"round"}),n=new H__default.default.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)),r=Math.max(0,Math.round(n));this.sizeLabel.getText().text(String(o)+" \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},n=e.width,o=e.height;if(!this.hitRect){let r=new H__default.default.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});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__default.default.Container?(this.boundNode.add(r),r.moveToBottom(),this.hitRect=r,i.batchDraw()):r.destroy();return}this.hitRect.position(t),this.hitRect.size({width:n,height:o}),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,"_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,"_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 fe(16));a(this,"_uiUpdateDebounce",new me);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 b=false;if(this._selected){let N=t.getPointerPosition();if(N){let y=this._selected.getKonvaNode(),w=y.getClientRect({skipShadow:true,skipStroke:false});if(N.x>=w.x&&N.x<=w.x+w.width&&N.y>=w.y&&N.y<=w.y+w.height&&(b=true,typeof y.startDrag=="function")){let k=y,C=3,P=e.evt.clientX,A=e.evt.clientY,L=typeof k.draggable=="function"?k.draggable():false,R=t.draggable(),E=false,O=X=>{let re=Math.abs(X.evt.clientX-P),F=Math.abs(X.evt.clientY-A);!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(R),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);}}}b||this._options.deselectOnEmptyClick&&this._clearSelection();return}let o=e.target;if(!this._options.selectablePredicate(o))return;let r=this._findBaseNodeByTarget(o);if(!r)return;let s=r,l=this._selected;if(l){let b=l.getKonvaNode();((y,w)=>{let x=w;for(;x;){if(x===y)return true;x=x.getParent();}return false})(b,o)&&(s=l);}let h=s.getKonvaNode();h instanceof H__default.default.Group&&this._disableGroupChildrenDragging(h);let p=3,d=e.evt.clientX,c=e.evt.clientY,u=false,f=b=>{if(u)return;let N=Math.abs(b.evt.clientX-d),y=Math.abs(b.evt.clientY-c);(N>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,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(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,n=this._core.nodes.layer,o=e.target;if((()=>{if(!!!this._tempMultiGroup){let b=o;for(;b;){if(b instanceof H__default.default.Group&&typeof b.name=="function"){let N=b.name();if(typeof N=="string"&&(N.includes("temp-multi-group")||N.includes("area-temp-group")))return true}b=b.getParent();}return false}let v=o;for(;v;){if(v===this._tempMultiGroup)return true;v=v.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(o===t||o.getLayer()!==n){this._destroyHoverTr();return}let l=this._core.nodes.list().map(m=>m.getKonvaNode()),h=new Set(l),p=m=>{let v=m;for(;v;){if(h.has(v))return v;v=v.getParent();}return null},c=(m=>{let v=m,b=null;for(;v;)h.has(v)&&v instanceof H__default.default.Group&&(b=v),v=v.getParent();return b})(o),u=p(o),f=e.evt.ctrlKey,g=f?u??c:c??u;if(!f&&this._selected&&u&&!(this._selected.getKonvaNode()instanceof H__default.default.Group)){let m=this._selected.getKonvaNode();c&&((b,N,y)=>{if(!y)return false;let w=(x,k)=>{let C=k;for(;C;){if(C===x)return true;C=C.getParent();}return false};return w(y,b)&&w(y,N)})(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||((N,y)=>{let w=y;for(;w;){if(w===N)return true;w=w.getParent();}return false})(m,g)){this._destroyHoverTr();return}}let _=this._ensureHoverTr();_.nodes([g]),_.visible(true),_.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:r}=e;if(this._options={dragEnabled:t,enableTransformer:n,deselectOnEmptyClick:o,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,n=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let o=t.getPointerPosition();if(o){let r=t.width(),s=t.height(),l=this._autoPanEdgePx,h=0,p=0,d=Math.max(0,l-o.x),c=Math.max(0,o.x-(r-l)),u=Math.max(0,l-o.y),f=Math.max(0,o.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._draggingNode&&typeof this._draggingNode.setAbsolutePosition=="function"){let _=this._draggingNode.getAbsolutePosition();this._draggingNode.setAbsolutePosition({x:_.x+h,y:_.y+p}),this._transformer?.forceUpdate();}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();}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__default.default.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__default.default.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__default.default.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",s=>{if(!this._options.autoPanEnabled)return;let l=s.target;this._options.selectablePredicate(l)&&(this._draggingNode=l,this._startAutoPanLoop());}),n.on("dragend.selectionAutoPan",()=>{this._draggingNode=null,this._stopAutoPanLoop();});let o=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());}));};o.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 n=e.getKonvaNode();this._prevDraggable=n.draggable(),this._options.dragEnabled&&typeof n.draggable=="function"&&n.draggable(true),n instanceof H__default.default.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 r=o.evt.button;(r===1||r===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 n=e.getAbsoluteTransform().copy(),o=t.copy();o.invert();let r=n.multiply(o);for(let s of this._tempMultiNodes){let l=this._tempMultiInitialTransforms.get(s);if(!l)continue;let h=r.copy().multiply(l),p=s.getParent();if(!p)continue;let d=p.getAbsoluteTransform().copy();d.invert();let u=d.multiply(h).decompose();typeof s.position=="function"&&s.position({x:u.x,y:u.y}),typeof s.rotation=="function"&&s.rotation(u.rotation),typeof s.scale=="function"&&s.scale({x:u.scaleX,y:u.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,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)n=Math.min(n,u.x),o=Math.min(o,u.y),r=Math.max(r,u.x),s=Math.max(s,u.y);}return !isFinite(n)||!isFinite(o)||!isFinite(r)||!isFinite(s)?null:{x:n,y:o,width:r-n,height:s-o}}_ensureTempMulti(e){if(!this._core)return;let t=this._core.nodes.world,n=this._core.nodes.layer;this._tempMultiSet.clear();for(let c of e)this._tempMultiSet.add(c);let o=e.map(c=>c.getKonvaNode());if(this._tempMultiGroup&&this._tempMultiNodes.length>0){if(this._tempMultiNodes.length===o.length&&o.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=o;let s=new H__default.default.Group({name:"temp-multi-overlay",x:r.x,y:r.y});t.add(s),this._tempMultiGroup=s;let l=new H__default.default.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 it(this._core)),this._tempOverlay.attach(s,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed});let h=this._core.stage,p=h.draggable();s.draggable(true);let d=null;s.on("dragstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();for(let c of this._tempMultiNodes)this._tempMultiInitialTransforms.set(c,c.getAbsoluteTransform().copy());d=s.getAbsoluteTransform().copy(),h.draggable(false),this._draggingNode=s,this._startAutoPanLoop(),this._tempOverlay?.hideOverlaysForDrag();}),s.on("dragmove.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(s,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),s.on("dragend.tempMulti",()=>{if(h.draggable(p),this._draggingNode=null,this._stopAutoPanLoop(),this._tempOverlay?.restoreOverlaysAfterDrag(),this._core){let u=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiSet){let _=f.getKonvaNode().getAbsoluteTransform().copy(),v=u.copy().multiply(_).decompose();this._core.eventBus.emit("node:transformed",f,{x:v.x,y:v.y,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY});}}this._updateTempMultiOverlayBBox(),d=null,this._tempMultiInitialTransforms.clear(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),s.on("transformstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();for(let c of this._tempMultiNodes)this._tempMultiInitialTransforms.set(c,c.getAbsoluteTransform().copy());d=s.getAbsoluteTransform().copy();}),s.on("transform.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(s,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),s.on("transformend.tempMulti",()=>{if(this._core){let u=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiSet){let _=f.getKonvaNode().getAbsoluteTransform().copy(),v=u.copy().multiply(_).decompose();this._core.eventBus.emit("node:transformed",f,{x:v.x,y:v.y,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY});}}this._updateTempMultiOverlayBBox(),d=null,this._tempMultiInitialTransforms.clear(),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")));}_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 n=e.addGroup({x:t.x,y:t.y,draggable:true}),o=n.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();o.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=o.zIndex(),d=l;if(p<d){let c=d-p;for(let u=0;u<c&&o.zIndex()<h.children.length-1;u++)o.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 o.draggable=="function"&&o.draggable(true),this._core.eventBus.emit("group:created",n,r),this._select(n),this._core.stage.batchDraw();}_tryUngroupSelectedGroup(){if(!this._core||!this._selected)return;let e=this._selected.getKonvaNode();if(!(e instanceof H__default.default.Group))return;let t=[...e.getChildren()],n=this._core.nodes.world,o=[];for(let s of t){let l=s.getAbsoluteTransform().copy();n.add(s);let h=n.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){o.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,o),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__default.default.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__default.default.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 n=()=>{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",()=>{n(),this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel(),this._startAutoPanLoop();let s=this._selected?.getKonvaNode(),h=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"";if(!s){this._transformOppositeCorner=null;return}let p=ke(s),d=Se(h,p);if(!d){this._transformOppositeCorner=null;return}let c=s.getAbsoluteTransform();this._transformOppositeCorner=c.point({x:d.x,y:d.y});}),t.on("transform.keepratio",n),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=ke(s),c=Se(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(),v=s.getAbsolutePosition(),b={x:v.x+f,y:v.y+g},N=m.point(b);s.position(N);}}this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();}),t.on("transformend.corner-sync",()=>{this._cornerHandlesSuppressed=false,this._transformOppositeCorner=null,this._restyleSideAnchors(),this._stopAutoPanLoop(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();});let o=this._selected.getKonvaNode();o.off(".overlay-sync");let r=()=>{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",r),this._scheduleBatchDraw();}_restyleSideAnchors(){if(!this._core||!this._selected||!this._transformer)return;let e=this._selected.getKonvaNode();ge(this._core,this._transformer,e);}_setupRotateHandles(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroyRotateHandles();let t=new H__default.default.Group({name:"rotate-handles-group",listening:true});e.add(t),this._rotateHandlesGroup=t;let n=he("rotate-tl"),o=he("rotate-tr"),r=he("rotate-br"),s=he("rotate-bl");t.add(n),t.add(o),t.add(r),t.add(s),this._rotateHandles={tl:n,tr:o,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),v=_+45;this._applyRotatedCursor(v);let b=y=>{let w=y%360;return w<0&&(w+=360),w},N=(y,w)=>b(y-w+180)-180;if(c.evt.shiftKey){let y=this._transformer,w,x=5;if(y){let k=y.rotationSnaps();Array.isArray(k)&&(w=k.map(P=>b(P)));let C=y.rotationSnapTolerance();typeof C=="number"&&(x=C);}if(w?.length){let k=b(m),C=m,P=1/0;for(let A of w){let L=Math.abs(N(k,A));L<P&&L<=x&&(C=A,P=L);}P!==1/0&&(m=C);}}if(u.rotation(m),this._rotateCenterAbsStart){let y=this._getNodeCenterAbs(u),w=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}),A=C.point({x:y.x+w,y:y.y+x}),L=u.x()+(A.x-P.x),R=u.y()+(A.y-P.y);typeof u.position=="function"&&u.position({x:L,y:R});}}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(n),l(o),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,b=Math.atan2(_,g)*180/Math.PI+45;this._setRotateCursor(b);}),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(),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=`
4
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
5
+ <g transform="rotate(${e.toString()} 12 12)">
6
+ <g clip-path="url(#clip0_36_31)">
7
+ <g filter="url(#filter0_d_36_31)">
8
+ <path d="M4 6.15927C4 6.15927 9.71429 2.49547 15.4286 8.19463C21.1429 13.8938 18.2857 20 18.2857 20" stroke="white" stroke-width="2"/>
9
+ </g>
10
+ <g filter="url(#filter1_d_36_31)">
11
+ <path d="M0.724195 7.73427L3.27834 2.11403L6.69072 9.31897L0.724195 7.73427Z" fill="black"/>
12
+ <path d="M3.28396 2.82664L6.14311 8.86349L1.1435 7.53589L3.28396 2.82664Z" stroke="white" stroke-width="0.6"/>
13
+ </g>
14
+ <g filter="url(#filter2_d_36_31)">
15
+ <path d="M17.26 22.5868L15.3995 16.7004L22.7553 19.774L17.26 22.5868Z" fill="black"/>
16
+ <path d="M15.8803 17.2264L22.0436 19.8017L17.439 22.1588L15.8803 17.2264Z" stroke="white" stroke-width="0.6"/>
17
+ </g>
18
+ <path d="M4 6.15927C4 6.15927 9.71429 2.49547 15.4286 8.19463C21.1429 13.8938 18.2857 20 18.2857 20" stroke="black"/>
19
+ </g>
20
+ <defs>
21
+ <filter id="filter0_d_36_31" x="-0.539062" y="2" width="22.5391" height="22.4229" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
22
+ <feFlood flood-opacity="0" result="BackgroundImageFix"/>
23
+ <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
24
+ <feOffset dx="-1" dy="1"/>
25
+ <feGaussianBlur stdDeviation="1.5"/>
26
+ <feComposite in2="hardAlpha" operator="out"/>
27
+ <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.9 0"/>
28
+ <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_36_31"/>
29
+ <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_36_31" result="shape"/>
30
+ </filter>
31
+ <filter id="filter1_d_36_31" x="-0.275879" y="2.11426" width="9.96631" height="11.2046" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
32
+ <feFlood flood-opacity="0" result="BackgroundImageFix"/>
33
+ <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
34
+ <feOffset dx="1" dy="2"/>
35
+ <feGaussianBlur stdDeviation="1"/>
36
+ <feComposite in2="hardAlpha" operator="out"/>
37
+ <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0"/>
38
+ <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_36_31"/>
39
+ <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_36_31" result="shape"/>
40
+ </filter>
41
+ <filter id="filter2_d_36_31" x="12.3994" y="15.7002" width="11.3555" height="9.88672" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
42
+ <feFlood flood-opacity="0" result="BackgroundImageFix"/>
43
+ <feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
44
+ <feOffset dx="-1" dy="1"/>
45
+ <feGaussianBlur stdDeviation="1"/>
46
+ <feComposite in2="hardAlpha" operator="out"/>
47
+ <feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.5 0"/>
48
+ <feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_36_31"/>
49
+ <feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_36_31" result="shape"/>
50
+ </filter>
51
+ <clipPath id="clip0_36_31">
52
+ <rect width="24" height="24" fill="white"/>
53
+ </clipPath>
54
+ </defs>
55
+ </g>
56
+ </svg>
57
+ `.trim(),o=`data:image/svg+xml,${encodeURIComponent(t)}`,r=this._core.stage.container();r.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 r=e.getAbsoluteTransform().copy(),s=k=>r.point(k),l=12,h=s({x:t.x+n/2,y:t.y+o/2}),p=s({x:t.x,y:t.y}),d=s({x:t.x+n,y:t.y}),c=s({x:t.x+n,y:t.y+o}),u=s({x:t.x,y:t.y+o}),f=k=>{let C=k.x-h.x,P=k.y-h.y,A=Math.hypot(C,P)||1;return {x:C/A,y:P/A}},g=f(p),_=f(d),m=f(c),v=f(u),b={x:p.x+g.x*l,y:p.y+g.y*l},N={x:d.x+_.x*l,y:d.y+_.y*l},y={x:c.x+m.x*l,y:c.y+m.y*l},w={x:u.x+v.x*l,y:u.y+v.y*l};this._rotateHandles.tl&&this._rotateHandles.tl.absolutePosition(b),this._rotateHandles.tr&&this._rotateHandles.tr.absolutePosition(N),this._rotateHandles.br&&this._rotateHandles.br.absolutePosition(y),this._rotateHandles.bl&&this._rotateHandles.bl.absolutePosition(w);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__default.default.Label({listening:false,opacity:.95}),n=new H__default.default.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),o=new H__default.default.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:4,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(),r=this._core.nodes.world.getAbsoluteTransform().decompose(),s=Math.abs(o.scaleX)||1,l=Math.abs(o.scaleY)||1,h=Math.abs(r.scaleX)||1,p=Math.abs(r.scaleY)||1,d=n.width*(s/h),c=n.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,v=t.y+t.height+_,N=this._sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this._sizeLabel.absolutePosition({x:m,y:v}),this._sizeLabel.offsetX(N/2),this._sizeLabel.offsetY(0);let y=this._sizeLabel.getParent();if(y){let w=y.getAbsoluteTransform().decompose(),x=1/(Math.abs(w.scaleX)||1),k=1/(Math.abs(w.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__default.default.Rect||e instanceof H__default.default.Image}_getCornerRadiusArray(e){let t=e.cornerRadius();if(Array.isArray(t)){let[o=0,r=0,s=0,l=0]=t;return [o||0,r||0,s||0,l||0]}let n=typeof t=="number"?t:0;return [n,n,n,n]}_setCornerRadiusArray(e,t){let[n,o,r,s]=t;n===o&&o===r&&r===s?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 r=new H__default.default.Group({name:"corner-radius-handles-group",listening:true});n.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=o.getPointerPosition();if(!T){this._cornerHandlesGroup.visible(false);return}let K=n.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=o.getPointerPosition();if(s&&this._core.nodes.world.scaleX()>=.3){let M=n.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),Y=1/(Math.abs(M.y)||1),U=12*G,z=12*Y,Q=Math.max(0,T/2-U),oe=Math.max(0,K/2-z),ee=Math.min(Q,oe);return {tl:{corner:{x:U,y:z},sign:{x:1,y:1},side:ee},tr:{corner:{x:T-U,y:z},sign:{x:-1,y:1},side:ee},br:{corner:{x:T-U,y:K-z},sign:{x:-1,y:-1},side:ee},bl:{corner:{x:U,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),Y=V=>M.point(V),z=l()[K],Q=G(T),oe=Q.x-z.corner.x,ee=Q.y-z.corner.y,I=(z.sign.x*oe+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:Y(W),r:I,meta:z}},p=T=>new H__default.default.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__default.default.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"),v=g("corner-radius-br"),b=g("corner-radius-bl");r.add(_,m,v,b),this._cornerHandles={tl:_,tr:m,br:v,bl:b};let N={tl:0,tr:1,br:2,bl:3},y=false,w=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},A=(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(Y=>{let U=M[Y];U&&Math.hypot(U.x-T.x,U.y-T.y)<=K&&G++;}),G>=2},R=T=>{if(!y||w)return;let K=k(),M=T.x-K.x,G=T.y-K.y,Y=Math.hypot(M,G);if(Y<.1)return;M/=Y,G/=Y;let U=t.getAbsoluteTransform().copy(),z=l(),Q=["tl","tr","br","bl"].reduce((I,W)=>{let se=z[W],V=U.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},{}),oe="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,oe=I);}),w=oe;},E=T=>K=>{R(K);let M=w??T,{snappedAbs:G,r:Y,meta:U}=h(K,M),z=t.width(),Q=t.height(),oe=Math.max(0,Math.min(z,Q)/2),ee=U.side>0?Y/U.side:0,I=Math.round(ee*oe);I=Math.max(0,Math.min(I,oe));let W=this._getCornerRadiusArray(t),se=N[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")),v.dragBoundFunc(E("br")),b.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 Y=t.getAbsoluteTransform().copy(),U=n.getAbsoluteTransform().copy().invert(),z=V=>Y.point(V),Q=V=>U.point(Y.point(V)),oe=l(),ee=this._getCornerRadiusArray(t),I=(V,ie,Z)=>{let J=oe[V],we=t.width(),Oe=t.height(),xe=Math.max(0,Math.min(we,Oe)/2),Ie=Math.max(0,Math.min(xe,ee[ie]||0)),Ge=xe>0?Ie/xe:0,Et=Math.max(0,Math.min(J.side,Ge*J.side)),Ht={x:J.corner.x+J.sign.x*Et,y:J.corner.y+J.sign.y*Et};Z.absolutePosition(z(Ht));},W=(V,ie)=>{let Z=oe[V],J=Z.corner,we={x:Z.corner.x+Z.sign.x*Z.side,y:Z.corner.y+Z.sign.y*Z.side},Oe=Q({x:J.x,y:J.y}),xe=Q({x:we.x,y:J.y}),Ie=Q({x:we.x,y:we.y}),Ge=Q({x:J.x,y:we.y});ie.points([Oe.x,Oe.y,xe.x,xe.y,Ie.x,Ie.y,Ge.x,Ge.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)||A(M,6)||L(M,8),w=null,y){let G=this._core?.stage.getPointerPosition()??M;R(G);}},X=(T,K)=>M=>{x=M.evt.altKey;},re=()=>{if(y=false,w=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);}),v.on("dragstart.corner-radius",T=>{j(v,T);}),b.on("dragstart.corner-radius",T=>{j(b,T);}),_.on("dragmove.corner-radius",X()),m.on("dragmove.corner-radius",X()),v.on("dragmove.corner-radius",X()),b.on("dragmove.corner-radius",X()),_.on("dragend.corner-radius",re),m.on("dragend.corner-radius",re),v.on("dragend.corner-radius",re),b.on("dragend.corner-radius",re);let F=T=>()=>{this._showRadiusLabelForCorner(T);},q=()=>{this._hideRadiusLabel();},ne=T=>()=>{this._showRadiusLabelForCorner(T);};_.on("mouseenter.corner-radius",F(0)),m.on("mouseenter.corner-radius",F(1)),v.on("mouseenter.corner-radius",F(2)),b.on("mouseenter.corner-radius",F(3)),_.on("mouseleave.corner-radius",q),m.on("mouseleave.corner-radius",q),v.on("mouseleave.corner-radius",q),b.on("mouseleave.corner-radius",q),_.on("dragstart.corner-radius",F(0)),m.on("dragstart.corner-radius",F(1)),v.on("dragstart.corner-radius",F(2)),b.on("dragstart.corner-radius",F(3)),_.on("dragmove.corner-radius",ne(0)),m.on("dragmove.corner-radius",ne(1)),v.on("dragmove.corner-radius",ne(2)),b.on("dragmove.corner-radius",ne(3)),_.on("dragend.corner-radius",q),m.on("dragend.corner-radius",q),v.on("dragend.corner-radius",q),b.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),v.on("mousedown.corner-radius touchstart.corner-radius",de),b.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),v.on("mouseup.corner-radius touchend.corner-radius",ce),b.on("mouseup.corner-radius touchend.corner-radius",ce);let $=".corner-squares",be=false,ye=()=>{be||(be=true,H__default.default.Util.requestAnimFrame(()=>{be=false,O(),this._core?.nodes.layer.batchDraw();}));};o.on(["wheel","resize","xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(T=>T+$).join(" "),ye),n.on(["xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(T=>T+$).join(" "),ye),t.on(["dragmove","transform","xChange","yChange","widthChange","heightChange","rotationChange","scaleXChange","scaleYChange","positionChange","scaleChange"].map(T=>T+$).join(" "),ye),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,ye();})),r.on("destroy"+$,()=>{o.off($),n.off($),t.off($),this._transformer?.off($);}),O(),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 H__default.default.Rect))return;let t=e.scaleX(),n=e.scaleY();if(t===1&&n===1)return;let o=e.getAbsolutePosition(),r=e.width(),s=e.height(),l=Math.abs(t)*r,h=Math.abs(n)*s;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,r=n.height;if(o<=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(o,r)/2||1,_=x=>{let k=Math.hypot(x.x,x.y)||1;return {x:x.x/k,y:x.y/k}},m=[_({x:o/2-c,y:r/2-u}),_({x:-(o/2-c),y:r/2-u}),_({x:-(o/2-c),y:-(r/2-u)}),_({x:o/2-c,y:-(r/2-u)})],v=l({x:n.x+c+m[0].x*Math.min(g,f[0]),y:n.y+u+m[0].y*Math.min(g,f[0])}),b=l({x:n.x+o-c+m[1].x*Math.min(g,f[1]),y:n.y+u+m[1].y*Math.min(g,f[1])}),N=l({x:n.x+o-c+m[2].x*Math.min(g,f[2]),y:n.y+r-u+m[2].y*Math.min(g,f[2])}),y=l({x:n.x+c+m[3].x*Math.min(g,f[3]),y:n.y+r-u+m[3].y*Math.min(g,f[3])});this._cornerHandles.tl&&this._cornerHandles.tl.absolutePosition(v),this._cornerHandles.tr&&this._cornerHandles.tr.absolutePosition(b),this._cornerHandles.br&&this._cornerHandles.br.absolutePosition(N),this._cornerHandles.bl&&this._cornerHandles.bl.absolutePosition(y);let w=this._cornerHandlesGroup.getParent();if(w){let x=w.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(),n=this._core.stage,o=this._core.nodes.layer,r=this._selected.getKonvaNode(),s=n.getPointerPosition();if(!s){t<.3&&this._cornerHandlesGroup.visible(false);return}if(t<.3){this._cornerHandlesGroup.visible(false);return}let l=o.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__default.default.Label({listening:false,opacity:.95}),n=new H__default.default.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),o=new H__default.default.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 s=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(s),n.offsetY(0);let h=n.getParent();if(h){let p=h.getAbsoluteTransform().decompose(),d=1/(Math.abs(p.scaleX)||1),c=1/(Math.abs(p.scaleY)||1);n.scale({x:d,y:c});}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),r=Math.round(o[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 n=this._selected.getKonvaNode();if(n===e)return this._selected;if(typeof n.isAncestorOf=="function"&&n.isAncestorOf(e))return this._selected}let t=null;for(let n of this._core.nodes.list()){let o=n.getKonvaNode();if(typeof o.isAncestorOf=="function"&&o.isAncestorOf(e)){let r=true;for(let s of this._core.nodes.list()){if(s===n)continue;let l=s.getKonvaNode();if(typeof l.isAncestorOf=="function"&&l.isAncestorOf(o)){r=false;break}}r&&(t=n);}}if(t)return t;for(let n of this._core.nodes.list())if(n.getKonvaNode()===e)return n;return null}_disableGroupChildrenDragging(e){let t=e.getChildren();for(let n of t){let o=n;typeof o.draggable=="function"&&o.draggable(false);}}};var ct=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__default.default.Layer({name:"area-selection-layer",listening:false});e.stage.add(t),this._layer=t,this._rect=new H__default.default.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||o.target!==n&&o.target.getLayer()===e.nodes.layer)return;let r=n.getPointerPosition();if(!r||!this._rect)return;let s=n.findOne(".ruler-layer");if(s&&o.target.getLayer()===s)return;let l=n.findOne(".guides-layer");if(l&&o.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());}),n.on("mousemove.area",()=>{if(!this._selecting||!this._rect||!this._start)return;let o=n.getPointerPosition();if(!o)return;let r=Math.min(this._start.x,o.x),s=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: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 v=_.getClientRect({skipShadow:true,skipStroke:false});if(this._rectsIntersect(p,v)){let b=this._findOwningGroupBaseNode(_);c.add(b??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();}}),n.on("mouseup.area",o=>{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),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 s=this._getSelectionPlugin()?.getMultiGroupController(),l=!!s?.isActive();if(!l&&!this._isPermanentGroupSelected())return;let h=o.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,n=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let o=t.getPointerPosition();if(o){let r=t.width(),s=t.height(),l=this._autoPanEdgePx,h=0,p=0,d=Math.max(0,l-o.x),c=Math.max(0,o.x-(r-l)),u=Math.max(0,l-o.y),f=Math.max(0,o.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),v=Math.min(this._start.y,_.y),b=Math.abs(_.x-this._start.x),N=Math.abs(_.y-this._start.y);this._rect.position({x:m,y:v}),this._rect.size({width:b,height:N});}}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(),r=[];for(let h of o){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 n=this._getSelectionPlugin();n&&(t.length>0?(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 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 n=this._core.nodes.list().filter(s=>s instanceof ue),o=e,r=null;for(;o;){let s=n.find(l=>l.getKonvaNode()===o)??null;s&&(r=s),o=o.getParent();}return r}_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 ue&&n.getKonvaNode()===t)}_currentGroupNode(){if(!this._transformer)return null;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return t&&t instanceof H__default.default.Group?t:null}};var ut=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:n,deltaY:o,shiftKey:r}=e;if(this._isTouchpadWheel(e)){if(r){let l=-(Math.abs(n)>=Math.abs(o)?n:o);this._pan(l,0);}else {let s=-n,l=-o;this._pan(s,l);}return}if(r){let s=o<0?-Math.abs(o):Math.abs(o);this._pan(s,0);}else {let s=-o;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 o=this._core.stage.getPointerPosition();o&&(this._last={x:o.x,y:o.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 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:r=true,enableArrows:s=true,enablePanning:l=true,allowMiddleButtonPan:h=true,allowRightButtonPan:p=true,disableContextMenu:d=true}=e;this._options={target:t,zoomStep:n,panStep:o,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 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,r=n.y()+t;n.position({x:o,y:r}),this._core.eventBus.emit("camera:pan",{dx:e,dy:t,position:{x:o,y:r}}),this._core.stage.batchDraw();}};var le=class{attach(i){this.onAttach(i);}detach(i){this.onDetach(i);}};var pt=class extends te{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;}},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);}},ft=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: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 pt,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 s=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(n);await this._handleDataTransfer(t,{x:s.x,y:s.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 c=o[d];if(c){if(c.kind==="file"){let u=c.getAsFile();if(u?.type==="image/svg+xml"||u?.name.toLowerCase().endsWith(".svg")){n?.preventDefault(),await this._pasteSvgFile(u,t);return}if(u&&(u.type.startsWith("video/")||this._looksLikeVideoFile(u))){n?.preventDefault(),await this._pasteVideoFile(u,t);return}if(u&&(u.type.startsWith("image/")||u.type==="")){n?.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){n?.preventDefault(),this._pasteSvgText(f,t);return}let g=c.type==="text/html"?this._htmlToText(u):u;if(g.trim().length>0){n?.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")){n?.preventDefault(),await this._pasteSvgFile(c,t);return}if(c.type.startsWith("video/")||this._looksLikeVideoFile(c)){n?.preventDefault(),await this._pasteVideoFile(c,t);return}if(c.type.startsWith("image/")||c.type===""){n?.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){n?.preventDefault(),this._pasteSvgText(h,t);return}let p=this._htmlToText(l||s);if(p.trim().length>0){n?.preventDefault(),this._core.nodes.addText({x:t.x,y:t.y,text:p});return}}_pasteSvgText(e,t){if(!this._core)return;let n=this._svgTextToSrc(e),o=this._extractSvgSize(e),r=this._fitIntoMaxSize(o,this._options.maxImageSize);this._core.nodes.addSvg({x:t.x,y:t.y,src:n,width:r.width,height:r.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),r=this._fitIntoMaxSize(o,this._options.maxImageSize);this._core.nodes.addImage({x:t.x,y:t.y,src:n,width:r.width,height:r.height}).addons.add(new rt(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 r=o.getVideoElement(),s=r?{width:r.videoWidth||0,height:r.videoHeight||0}:{width:0,height:0},l=this._fitIntoMaxSize(s,this._options.maxImageSize);o.setSize({width:l.width,height:l.height}),o.addons.add(new rt(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 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,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,s=t.getAbsoluteTransform().copy().invert().point({x:n,y:o});return {x:s.x,y:s.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 r=o.result;if(typeof r=="string"){t(r);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 r=n.lastIndexOf("</svg>");return r===-1?null:t.slice(o,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,n=/\bheight\s*=\s*["']([^"']+)["']/i,o=t.exec(e),r=n.exec(e),s=o?.[1]?this._parseSvgNumber(o[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,n)=>{let o=globalThis.Image??null;if(!o){n(new Error("Image constructor is not available in current environment"));return}let r=new o;r.onload=()=>{t({width:r.naturalWidth||r.width,height:r.naturalHeight||r.height});},r.onerror=()=>{n(new Error("Failed to load clipboard image"));},r.src=e;})}};var gt=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,n=(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(),v=f.scaleX(),b=f.scaleY(),N=Math.max(1,this._stepX)*Math.max(1e-6,v),y=Math.max(1,this._stepY)*Math.max(1e-6,b),w=(f.x()%N+N)%N,x=(f.y()%y+y)%y;d.beginPath(),d.lineWidth=this._lineWidth,d.strokeStyle=this._color;for(let k=w;k<=_;k+=N)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();},o=new H__default.default.Shape({listening:false,sceneFunc:n});t.add(o),this._layer=t,this._shape=o;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__default.default.Layer)return;let g=this._core.nodes.layer,_=f,m=false;for(;_;){if(_===g){m=true;break}_=_.getParent();}if(!m)return;let v=f;if(typeof v.draggable=="function"&&!v.draggable())return;let b=f.getAbsolutePosition(),N=u.scaleX()||1,y=u.scaleY()||1;if(this._minScaleToShow!=null?N>=this._minScaleToShow:false){let x=(b.x-u.x())/N,k=(b.y-u.y())/y,C=Math.max(1,this._stepX),P=Math.max(1,this._stepY),A=Math.round(x/C)*C,L=Math.round(k/P)*P,R=A*N+u.x(),E=L*y+u.y();(Math.abs(R-b.x)>.001||Math.abs(E-b.y)>.001)&&f.absolutePosition({x:R,y:E});}else {let x=(b.x-u.x())/N,k=(b.y-u.y())/y,C=Math.max(1,this._stepX),P=Math.max(1,this._stepY),A=Math.round(x/C)*C,L=Math.round(k/P)*P,R=A*N+u.x(),E=L*y+u.y();(Math.abs(R-b.x)>.001||Math.abs(E-b.y)>.001)&&f.absolutePosition({x:R,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 v=m;if(!this._enableSnap||!this._core||!(typeof c.nodes=="function"?c.nodes():[])[0])return v;let y=typeof c.getActiveAnchor=="function"?c.getActiveAnchor():"";if(y==="rotater")return v;let w=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 A=v.x,L=v.x+v.width,R=v.y,E=v.y+v.height,O=P.point({x:A,y:R}).x,j=P.point({x:L,y:R}).x,X=P.point({x:A,y:R}).y,re=P.point({x:A,y:E}).y,F=O,q=j,ne=X,de=re,ce=(G,Y)=>Math.round((G+1e-9)/Y)*Y;k.includes("left")&&(F=ce(O,w)),k.includes("right")&&(q=ce(j,w)),k.includes("top")&&(ne=ce(X,x)),k.includes("bottom")&&(de=ce(re,x)),q-F<w&&(k.includes("left")?F=q-w:q=F+w),de-ne<x&&(k.includes("top")?ne=de-x:de=ne+x);let $=C.point({x:F,y:ne}).x,be=C.point({x:F,y:ne}).y,ye=C.point({x:q,y:ne}).x,T=C.point({x:F,y:de}).y,K=G=>Math.round(G*1e3)/1e3;return {x:K($),y:K(be),width:K(ye-$),height:K(T-be),rotation:v.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 b=typeof m.getChildren=="function"?m.getChildren():[];for(let N of b)u(N);};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),_=N=>{c.cornerRadius(N);},m=this._core?.stage,v=m?.scaleX()??1,b=this._minScaleToShow!=null?v>=this._minScaleToShow:false;if(Array.isArray(g)){let N=g.map(y=>{if(b){let w=m?.scaleX()??1,x=m?.scaleY()??1,k=y*(.5*(w+x));return Math.max(0,Math.round(k))/Math.max(1e-6,.5*(w+x))}else return Math.max(0,Math.round(y))});_(N);}else if(typeof g=="number")if(b){let N=m?.scaleX()??1,y=m?.scaleY()??1,w=g*(.5*(N+y)),x=Math.max(0,Math.round(w));_(x/Math.max(1e-6,.5*(N+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 _t=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,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 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 o=this._findBaseNodeByKonva(t);if(o){let r=this._captureTransformState(o);this._dragStartStateCache.set(o.id,r),this._debug("dragstart",{nodeId:o.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 n=t.name();if(typeof n=="string"&&n.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 o=this._findBaseNodeByKonva(t);if(o){let r=this._captureTransformState(o);this._dragStartStateCache.set(o.id,r),this._debug("transformstart",{nodeId:o.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),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 r={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(r),this._scheduleBatchCommit()):(this._history.push(r),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(s=>this._serializeNode(s)),o=t.map(s=>s.id),r={type:"group",nodeId:e.id,before:{childIds:o,childStates:n},after:this._serializeNode(e),timestamp:Date.now()};this._history.push(r),this._trimHistoryIfNeeded();});a(this,"_onGroupUngrouped",(e,t)=>{if(this._isUndoRedoInProgress)return;let n=this._serializeNode(e),o=t.map(s=>this._serializeNode(s)),r={type:"ungroup",nodeId:e.id,before:n,after:{childStates:o},timestamp:Date.now()};this._history.push(r),this._trimHistoryIfNeeded();});this._history=new Be;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 r of o)this._applyActionState(r,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 r of o.childStates)this._recreateNode(r);}}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 r of o.childStates)this._recreateNode(r);}}}_recreateNode(e){if(!this._core)return null;let{nodeType:t,attrs:n}=e,{id:o,zIndex:r,...s}=n;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(),n=t.getAttrs(),o=this._getNodeType(t),r={nodeType:o,nodeId:e.id,attrs:{...n}},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(o==="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(),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 r=t;return typeof r.cornerRadius=="function"&&(o.cornerRadius=r.cornerRadius()),o}_buildAfterState(e,t){let n=e.getKonvaNode(),o=t.x??n.x(),r=t.y??n.y(),s=t.rotation??n.rotation(),l=t.scaleX??n.scaleX(),h=t.scaleY??n.scaleY(),p={absX:o,absY:r,absRotation:s,absScaleX:l,absScaleY:h,x:o,y:r,rotation:s,scaleX:l,scaleY:h};typeof n.width=="function"&&(p.width=t.width??n.width()),typeof n.height=="function"&&(p.height=t.height??n.height());let d=n;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 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 s of o){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 vt=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__default.default.Layer({name:"logo-layer",listening:false}),this._core.stage.add(this._layer),this._image=new H__default.default.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__default.default.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(),r=e.position(),s={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 p=(s.x-r.x)/o,d=(s.y-r.y)/o;this._image.position({x:p,y:d}),this._image.opacity(this._opacity),this._layer&&this._layer.moveToBottom();}};var st="flowscape:nodes:",bt=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 n=e.clipboardData?.getData("text/plain")??"";if(!n.startsWith(st))return;let o=n.slice(st.length),r=null;try{r=JSON.parse(o);}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 o=this._core.plugins.list().find(r=>r instanceof ve);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 Ne){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(`${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(o=>this._serializeNode(o)),n=this._computeSelectionWorldCenter(e);this._clipboard={nodes:t,center:n};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(),n=[];for(let o of this._clipboard.nodes){let r=o.position.x-t.x,s=o.position.y-t.y,l=this._deserializeNode(o,{x:e.x+r,y:e.y+s});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(),r=this._core.nodes.list(),s=new Set;for(let l of o){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 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),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}=n,d={type:o,config:p,position:r};if(o==="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(),n=e.getClassName(),o=n.toLowerCase();if(o==="rect"&&(o="shape"),n==="Image"){let c=e.getAttrs().flowscapeNodeType;c==="svg"?o="svg":c==="gif"?o="gif":c==="video"?o="video":o="image";}let{id:r,image:s,video:l,...h}=t,p={type:o,config:h,position:{x:e.x(),y:e.y()}};if(e instanceof H__default.default.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:n,...o}=e.config,r=o.placeholder,{placeholder:s,...l}=o,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,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,s=t.getAbsoluteTransform().copy().invert().point({x:n,y:o});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 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,r=Number.NEGATIVE_INFINITY;for(let c of e){let f=c.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),r=Math.max(r,f.y+f.height);}if(!isFinite(t)||!isFinite(n)||!isFinite(o)||!isFinite(r))return {x:0,y:0};let s=(t+o)/2,l=(n+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 n=t.getKonvaNode();if(this._isNodeInsidePermanentGroup(n))continue;let o=n.zIndex();n.moveUp();let r=n.zIndex();this._syncGroupZIndex(n),this._core&&o!==r&&this._core.eventBus.emit("node:zIndexChanged",t,o,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 n=e[t];if(!n)continue;let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let r=o.zIndex();o.moveDown();let s=o.zIndex();this._syncGroupZIndex(o),this._core&&r!==s&&this._core.eventBus.emit("node:zIndexChanged",n,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((n,o)=>{let r=n.getKonvaNode(),s=o.getKonvaNode();return r.zIndex()-s.zIndex()});for(let n of t){let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let r=o.zIndex();o.moveToTop();let s=o.zIndex();this._syncGroupZIndex(o),this._core&&r!==s&&this._core.eventBus.emit("node:zIndexChanged",n,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((n,o)=>{let r=n.getKonvaNode();return o.getKonvaNode().zIndex()-r.zIndex()});for(let n of t){let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let r=o.zIndex();o.moveToBottom();let s=o.zIndex();this._syncGroupZIndex(o),this._core&&r!==s&&this._core.eventBus.emit("node:zIndexChanged",n,r,s);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_isNodeInsidePermanentGroup(e){if(e instanceof H__default.default.Group)return false;let t=e.getParent();return !(!t||!(t instanceof H__default.default.Group)||t===this._core?.nodes.world)}_syncGroupZIndex(e){let t=e.getParent();t&&(e instanceof H__default.default.Group||t instanceof H__default.default.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:n="#2b83ff",rulerThicknessPx:o=30,snapToGrid:r=true,gridStep:s=1}=e;this._options={guideColor:t,activeColor:n,rulerThicknessPx:o,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__default.default.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 s=n.getPointerPosition();if(!s)return;let l=n.getIntersection(s);l&&(l.name()==="guide-h"||l.name()==="guide-v")||(s.y<=o&&s.x>=o?this._startCreateGuide("h"):s.x<=o&&s.y>=o?this._startCreateGuide("v"):this._setActiveGuide(null));}),n.on("mousemove.ruler-guides",()=>{let s=n.getPointerPosition();if(!s)return;let l=n.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<=o&&s.x>=o?n.container().style.cursor="ns-resize":s.x<=o&&s.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(),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=o+d*t;p.position({x:0,y:u}),p.points(l);}else {let u=n+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,n=this._core.nodes.world,o=n.scaleX(),r=t.getPointerPosition();if(!r)return;let s=e==="h"?(r.y-n.y())/o:(r.x-n.x())/o,l=this._snapToGrid(s),h=new H__default.default.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: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: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 Ce=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: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(),r=t.height(),s=this._options.rulerThicknessPx,l=n.scaleX(),h=n.x(),p=n.y(),d=[],c=[];for(let g of e){let _=g.getClientRect({relativeTo:n}),m=h+_.x*l,v=h+(_.x+_.width)*l,b=p+_.y*l,N=p+(_.y+_.height)*l;if(m<o&&v>s){let y=Math.max(s,m),w=Math.min(o,v);y<w&&d.push({start:y,end:w});}if(b<r&&N>s){let y=Math.max(s,b),w=Math.min(r,N);y<w&&c.push({start:y,end:w});}}let u=this._mergeSegments(d),f=this._mergeSegments(c);if(this._hGroup)for(let g of u){let _=new H__default.default.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__default.default.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 n=e.getClassName(),o=e.name(),s=["overlay-hit","ruler-","guide-","_anchor","back","rotater"].some(l=>o.includes(l));if(!(n==="Transformer"||n==="Layer"||s))if(n==="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),n=t[0];if(!n)return [];let o=[],r={start:n.start,end:n.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):(o.push(r),r={start:l.start,end:l.end}));}return o.push(r),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 r of o)e.includes(r)||e.push(r);}}catch{}let t=[];for(let n of e)this._collectNodes(n,t);return t}update(){this._updateHighlights();}};var Ee=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 yt=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:n="Inter, Calibri, Arial, sans-serif",fontSizePx:o=10,color:r="#8c8c8c",bgColor:s="#2c2c2c",borderColor:l="#1f1f1f",enabled:h=true}=e;this._options={thicknessPx:t,fontFamily:n,fontSizePx:o,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))),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,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: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,u),u}onAttach(e){this._core=e,this._layer=new H__default.default.Layer({name:"ruler-layer",listening:true}),this._options.enabled&&e.stage.add(this._layer),this._hGroup=new H__default.default.Group({listening:true}),this._vGroup=new H__default.default.Group({listening:true}),this._layer.add(this._hGroup),this._layer.add(this._vGroup),this._hBg=new H__default.default.Rect({fill:this._options.bgColor,listening:true,name:"ruler-h-bg"}),this._vBg=new H__default.default.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__default.default.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._vBorder=new H__default.default.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._hGroup.add(this._hBorder),this._vGroup.add(this._vBorder),this._hTicksShape=new H__default.default.Shape({listening:false,sceneFunc:o=>{let r=this._getActiveGuideInfo();this._drawHorizontalRuler(o,r);}}),this._hGroup.add(this._hTicksShape),this._vTicksShape=new H__default.default.Shape({listening:false,sceneFunc:o=>{let r=this._getActiveGuideInfo();this._drawVerticalRuler(o,r);}}),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 r=o.worldCoord,s=o.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,n){if(!this._core)return;let o=this._core.stage,r=this._core.nodes.world,s=r.scaleX()||1e-9,l=this._options.thicknessPx,h=t==="h",p=h?o.width():o.height(),d=h?r.x():r.y(),c=n?.type===(h?"v":"h")?n.coord:null,u=this._getStepsConfig(s),{majorStep:f,mediumStep:g,labelStep:_,drawStep:m,drawStepEpsilon:v,majorTickLength:b,mediumTickLength:N,minorTickLength:y,fontString:w}=u;e.save();let x=-d/s,k=Math.floor(x/m)*m,C=[],P=[],A=[],L=[],R=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)<v){R=O,L.push({pos:O,text:this._formatNumber(E)});continue}let X=Math.abs(E%f)<v,re=!X&&Math.abs(E%g)<v;X?C.push(O):re?P.push(O):A.push(O),Math.abs(E%_)<v&&L.push({pos:O,text:this._formatNumber(E)});}if(A.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.4,e.lineWidth=1,e.beginPath();for(let E of A)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-N)):(e.moveTo(l,E),e.lineTo(l-N,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-b)):(e.moveTo(l,E),e.lineTo(l-b,E));e.stroke();}if(R!==null&&(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(R,l),e.lineTo(R,l-b)):(e.moveTo(l,R),e.lineTo(l-b,R)),e.stroke()),L.length>0){e.font=w,e.textBaseline="top",e.textAlign="left";for(let E of L){let O=E.pos===R;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)<v))if(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(E,l),e.lineTo(E,l-b)):(e.moveTo(l,E),e.lineTo(l-b,E)),e.stroke(),e.fillStyle="#ff8c00",e.font=w,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(),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 r=o-n;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 wt=class extends D{constructor(e={}){super();a(this,"_core");a(this,"_options");a(this,"_layer",null);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:r=8}=e;this._options={guidelineColor:t,guidelineWidth:n,guidelineDash:o,thresholdPx:r};}_applyGapSnappingForDrag(e,t,n){if(!this._core)return;let o=this._options.thresholdPx,r=e.getClientRect({skipShadow:true,skipStroke:false}),s=n.x-t.x,l=n.y-t.y,h={x:r.x+s,y:r.y+l,width:r.width,height:r.height},p=this._collectOtherNodeBoxes(e),d=o+1,c=0,u=o+1,f=0;for(let g of p){let _=g.box;if(!(h.y>_.y+_.height||h.y+h.height<_.y)){let b=h.x,N=h.x+h.width,y=_.x,w=_.x+_.width;if(y>=N){let x=y-N;x>0&&x<d&&(d=x,c=x);}if(w<=b){let x=b-w;x>0&&x<d&&(d=x,c=-x);}}if(!(h.x>_.x+_.width||h.x+h.width<_.x)){let b=h.y,N=h.y+h.height,y=_.y,w=_.y+_.height;if(y>=N){let x=y-N;x>0&&x<u&&(u=x,f=x);}if(w<=b){let x=b-w;x>0&&x<u&&(u=x,f=-x);}}}d<=o&&(n.x+=c),u<=o&&(n.y+=f);}onAttach(e){this._core=e;let t=new H__default.default.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 s=o.child??o.target;this._walkAttachTransformers(s);},this._nodesRemoveHandler=o=>{let s=o.child??o.target;this._walkDetachTransformers(s);},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 H__default.default.Layer)return;let r=o,s=false;for(;r;){if(r===n){s=true;break}r=r.getParent();}if(!s)return;let l=o;if(typeof l.draggable=="function"&&!l.draggable())return;this._clearGuides();let h=this._getLineGuideStops(o),p=this._getObjectSnappingEdges(o),d=this._getGuides(h,p);if(!d.length)return;let c=o.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(o,c,u),o.absolutePosition(u),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 r=16;for(let s of n){let l=[];for(let u of o){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__default.default.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),v=u.box,b=0,N=0;if(s.dir==="right"){let y=t.x+t.width,w=v.x,x=v.x+v.width;b=w-y,N=x-y;}else if(s.dir==="left"){let y=t.x,w=v.x,x=v.x+v.width;b=y-x,N=y-w;}else if(s.dir==="down"){let y=t.y+t.height,w=v.y,x=v.y+v.height;b=w-y,N=x-y;}else {let y=t.y,w=v.y,x=v.y+v.height;b=y-x,N=y-w;}b=Math.max(0,b),N=Math.max(0,N),this._drawRayMarkerWithLabel(_.x,_.y,b,s.dir),this._drawRayMarkerWithLabel(m.x,m.y,N,s.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 r=4,s=new H__default.default.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__default.default.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=[],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 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 n=this._core.nodes.list();for(let o of n){let r=o.getKonvaNode();if(r===e)continue;let s=r,l=e;if(typeof s.isAncestorOf=="function"&&s.isAncestorOf(e)||typeof l.isAncestorOf=="function"&&l.isAncestorOf(r))continue;let h=r.getClientRect({skipShadow:true,skipStroke:false});t.push({node:r,box:{x:h.x,y:h.y,width:h.width,height:h.height}});}return t}_intersectRayWithBox(e,t,n){let o=e.x,r=e.y,s=n.x,l=n.y,h=n.x+n.width,p=n.y+n.height;if(t==="right"||t==="left"){if(r<l||r>p)return null;if(t==="right"){if(h<=o)return null;let d=Math.max(s,o),c=h,u=d-o,f=c-o;return f<=0||f<=u?null:{tEnter:u,tExit:f}}else {if(s>=o)return null;let d=Math.min(h,o),c=s,u=o-d,f=o-c;return f<=0||f<=u?null:{tEnter:u,tExit:f}}}if(o<s||o>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,n=[0,t.width()/2,t.width()],o=[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});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=[],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&&n.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&&o.push({lineGuide:l,diff:p,snap:h.snap,offset:h.offset});}let s=[];if(n.length>0){let[l]=[...n].sort((h,p)=>h.diff-p.diff);l&&s.push({lineGuide:l.lineGuide,offset:l.offset,orientation:"V",snap:l.snap});}if(o.length>0){let[l]=[...o].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,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 r of o)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 o=(typeof e.nodes=="function"?e.nodes():[])[0];if(!o)return;let r=o,s=typeof r.getLayer=="function"?r.getLayer():null;if(!s||s!==this._core.nodes.layer)return;this._clearGuides();let l=this._getLineGuideStops(o),h=this._getObjectSnappingEdges(o),p=this._getGuides(l,h);if(!p.length)return;let d=o.absolutePosition();for(let c of p)c.orientation==="V"?d.x=c.lineGuide+c.offset:d.y=c.lineGuide+c.offset;o.absolutePosition(d),this._drawResizeGuides(e,o,p);}_drawResizeGuides(e,t,n){if(!this._core||!this._layer)return;let o=typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"";if(!o)return;let r=t.getClientRect({skipShadow:true,skipStroke:false}),s=n.some(u=>u.orientation==="V"),l=n.some(u=>u.orientation==="H"),p=this._buildResizeRays(o,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 b of d){let N=this._intersectRayWithBox(u.origin,u.dir,b.box);N&&f.push({...N,box:b.box});}if(!f.length)continue;f.sort((b,N)=>b.tEnter-N.tEnter);let g=f.slice(0,c);if(!g.length)continue;let _=0;for(let b of g)b.tExit>_&&(_=b.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 v=new H__default.default.Line({points:m,stroke:this._options.guidelineColor,strokeWidth:this._options.guidelineWidth,name:"snap-guid-line",dash:this._options.guidelineDash,listening:false});this._layer.add(v),v.absolutePosition({x:u.origin.x,y:u.origin.y});for(let b of g){let N=b.tEnter,y=b.tExit,w=this._pointOnRay(u.origin,u.dir,N),x=this._pointOnRay(u.origin,u.dir,y),k=b.box,C=0,P=0;if(u.dir==="right"){let A=r.x+r.width,L=k.x,R=k.x+k.width;C=L-A,P=R-A;}else if(u.dir==="left"){let A=r.x,L=k.x,R=k.x+k.width;C=A-R,P=A-L;}else if(u.dir==="down"){let A=r.y+r.height,L=k.y,R=k.y+k.height;C=L-A,P=R-A;}else {let A=r.y,L=k.y,R=k.y+k.height;C=A-R,P=A-L;}C=Math.max(0,C),P=Math.max(0,P),this._drawRayMarkerWithLabel(w.x,w.y,C,u.dir),this._drawRayMarkerWithLabel(x.x,x.y,P,u.dir);}}this._layer.batchDraw();}_buildResizeRays(e,t){let n={x:t.x,y:t.y},o={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: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: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: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:s,dir:"down"},{origin:s,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 xt=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(),n=t.filters(),o=Array.isArray(n)?n:[],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:[...o],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__default.default.Filters.Sepia)||t.filters([..._,H__default.default.Filters.Sepia]);}else {let g=t.filters(),_=Array.isArray(g)?g:[];_.includes(H__default.default.Filters.HSL)||t.filters([..._,H__default.default.Filters.HSL]);let m=this.intensity,v=18,b=.2,N=v*m,y=b*m;switch(this.mode){case "warm":{typeof r.hue=="function"&&r.hue(f.prevHue+N),typeof r.saturation=="function"&&r.saturation(f.prevSaturation+y);break}case "cool":{typeof r.hue=="function"&&r.hue(f.prevHue-N),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 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 Nt=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 n=t.plugins.list().find(r=>r instanceof _e);if(n){this._instance=n,this._owned=false;return}let o=new _e(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 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 n=t.plugins.list().find(r=>r instanceof Ce);if(n){this._instance=n,this._owned=false;return}let o=new Ce(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 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 n=t.plugins.list().find(r=>r instanceof Ee);if(n){this._instance=n,this._owned=false;return}let o=new Ee(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 Tt=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(),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 Ct=class extends le{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():""}};exports.AreaSelectionPlugin=ct;exports.CameraHotkeysPlugin=ut;exports.CameraManager=Ae;exports.ContentFromClipboardPlugin=ft;exports.CoreEngine=dt;exports.DebounceHelper=me;exports.EventBus=Ke;exports.GridPlugin=gt;exports.HistoryManager=Be;exports.HistoryPlugin=_t;exports.ImageHoverFilterAddon=xt;exports.LogoPlugin=vt;exports.MediaPlaceholder=ae;exports.NodeAddon=le;exports.NodeAddons=Me;exports.NodeHotkeysPlugin=bt;exports.NodeManager=Re;exports.PluginAddon=te;exports.Plugins=Le;exports.RulerGuidesAddon=Nt;exports.RulerGuidesPlugin=_e;exports.RulerHighlightAddon=kt;exports.RulerHighlightPlugin=Ce;exports.RulerManagerAddon=St;exports.RulerManagerPlugin=Ee;exports.RulerPlugin=yt;exports.SelectionPlugin=ve;exports.ShapeHoverHighlightAddon=Tt;exports.TextAutoTrimAddon=Ct;exports.ThrottleHelper=fe;exports.VideoOverlayAddon=De;exports.VisualGuidesPlugin=wt;