@flowscape-ui/core-sdk 1.0.8 → 2.0.0
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/LICENSE +21 -21
- package/README.md +124 -384
- package/dist/index.cjs +1 -112
- package/dist/index.d.cts +6073 -2467
- package/dist/index.d.ts +6073 -2467
- package/dist/index.js +1 -112
- package/package.json +110 -105
package/dist/index.cjs
CHANGED
|
@@ -1,112 +1 @@
|
|
|
1
|
-
'use strict';var G=require('konva');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);var dn=Object.defineProperty;var cn=(y,i,e)=>i in y?dn(y,i,{enumerable:true,configurable:true,writable:true,value:e}):y[i]=e;var l=(y,i,e)=>cn(y,typeof i!="symbol"?i+"":i,e);var Be=class{constructor(){l(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 Le=class{constructor(i){l(this,"_stage");l(this,"_eventBus");l(this,"_target");l(this,"_scale");l(this,"_minScale");l(this,"_maxScale");l(this,"_zoomStep");l(this,"_panStep");l(this,"_wheelScheduled",false);l(this,"_pendingWheelEvent",null);this._stage=i.stage,this._eventBus=i.eventBus,this._target=i.target??i.stage,this._scale=i.initialScale??1,this._minScale=i.minScale??.1,this._maxScale=i.maxScale??5,this._zoomStep=i.zoomStep??1.05,this._panStep=i.panStep??40,this._initWheelZoom();}_initWheelZoom(){this._stage.on("wheel",i=>{if(i.evt.preventDefault(),this._pendingWheelEvent=i.evt,this._wheelScheduled)return;this._wheelScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._wheelScheduled=false,this._pendingWheelEvent&&(this._handleWheel(this._pendingWheelEvent),this._pendingWheelEvent=null);});});}_handleWheel(i){let e=this._target.scaleX()||1,t=this._stage.getPointerPosition();if(!t)return;let n=this._zoomStep,s=(i.deltaY>0?-1:1)>0?e*n:e/n;s=Math.max(this._minScale,Math.min(this._maxScale,s));let r={x:(t.x-this._target.x())/e,y:(t.y-this._target.y())/e};this._target.scale({x:s,y:s});let a={x:t.x-r.x*s,y:t.y-r.y*s};this._target.position(a),this._stage.batchDraw(),this._scale=s,this._eventBus.emit("camera:zoom",{scale:this._scale,position:a});}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 De=class{constructor(i){l(this,"_node");l(this,"_addons",new Set);this._node=i;}add(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)||(this._addons.add(t),t.attach(this._node));return this._node}remove(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)&&(this._addons.delete(t),t.detach(this._node));return this._node}list(){return Array.from(this._addons)}has(i){return this._addons.has(i)}clear(){this._addons.forEach(i=>{i.detach(this._node);}),this._addons.clear();}};var D=class{constructor(i,e={}){l(this,"konvaNode");l(this,"id");l(this,"addons");this.konvaNode=i,this.id=e.id??`node_${String(Date.now())}_${String(Math.random())}`,this.addons=new De(this),e.x&&this.konvaNode.x(e.x),e.y&&this.konvaNode.y(e.y),e.width&&this.konvaNode.width(e.width),e.height&&this.konvaNode.height(e.height),e.rotation!==void 0&&this.konvaNode.rotation(e.rotation);}getKonvaNode(){return this.konvaNode}setPosition({x:i,y:e}){return this.konvaNode.position({x:i,y:e}),this}getPosition(){return this.konvaNode.position()}remove(){this.addons.clear(),this.konvaNode.destroy();}};var Ze=class extends D{constructor(i={}){let e=new G__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 qe=class extends D{constructor(i={}){let e=new G__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 $e=class extends D{constructor(i={}){let e=new G__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 Je=class extends D{constructor(i={}){let e=new G__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 A=class extends D{constructor(e){let t={draggable:e.draggable??true};e.name!==void 0&&(t.name=e.name);let n=new G__default.default.Group(t);super(n,e);l(this,"_rect");l(this,"_contentGroup");l(this,"_container");let o=e.width,s=e.height,r=e.background??"#ffffff",a=new G__default.default.Group({clip:{x:0,y:0,width:o,height:s}}),h={x:0,y:0,width:o,height:s,fill:r},c=new G__default.default.Rect(h),d=new G__default.default.Group;a.add(c),a.add(d),this.konvaNode.add(a),this._rect=c,this._contentGroup=d,this._container=a;let u=this.konvaNode;u._frameOrigGetClientRect||(u._frameOrigGetClientRect=u.getClientRect.bind(u),u.getClientRect=f=>c.getClientRect(f));}getRect(){return this._rect}getContentGroup(){return this._contentGroup}resize(e,t){this._rect.width(e),this._rect.height(t),this._container.clip({x:0,y:0,width:e,height:t});}};var gn={text:"",textColor:"#bdbdbd",font:"12px sans-serif",backgroundColor:"#1f1f1f",borderColor:"transparent",baseSpinnerColor:"#6b6b6b",accentSpinnerColor:"#2b83ff",lineWidth:2,fallbackWidth:150,fallbackHeight:150},ce=class{constructor(i,e){l(this,"_node");l(this,"_options");l(this,"_rafId",null);l(this,"_startTime",0);l(this,"_lastDrawTime",0);l(this,"_canvas",null);l(this,"_ctx",null);l(this,"_logicalWidth",0);l(this,"_logicalHeight",0);l(this,"_pixelRatio",1);l(this,"_maxPixelRatio",3);l(this,"_maxCanvasPixels",15e5);l(this,"_targetFps",30);l(this,"_tick",()=>{let i=this._canvas,e=this._ctx;if(!i||!e)return;let t=globalThis.performance.now(),n=1e3/this._targetFps;if(this._lastDrawTime!==0&&t-this._lastDrawTime<n){this._rafId=globalThis.requestAnimationFrame(this._tick);return}this._lastDrawTime=t;let s=(t-this._startTime)/1e3,r=this._getPixelRatio();r!==this._pixelRatio&&this._logicalWidth>0&&this._logicalHeight>0&&(i.width=Math.max(1,Math.round(this._logicalWidth*r)),i.height=Math.max(1,Math.round(this._logicalHeight*r)),e.setTransform(r,0,0,r,0,0),this._pixelRatio=r),this._draw(s),this._node.getLayer()?.batchDraw(),this._rafId=globalThis.requestAnimationFrame(this._tick);});this._node=i,this._options={...gn,...e??{}};}setOptions(i){this._options={...this._options,...i},this._draw(0),this._node.getLayer()?.batchDraw();}start(){if(this.stop(),typeof document>"u")return;let i=globalThis.document.createElement("canvas"),e=this._node.size(),t=Math.max(1,Math.round(e.width||this._options.fallbackWidth)),n=Math.max(1,Math.round(e.height||this._options.fallbackHeight)),o=this._getPixelRatio();i.width=Math.max(1,Math.round(t*o)),i.height=Math.max(1,Math.round(n*o));let s=i.getContext("2d");s&&(s.setTransform(o,0,0,o,0,0),this._canvas=i,this._ctx=s,this._logicalWidth=t,this._logicalHeight=n,this._pixelRatio=o,this._node.image(i),this._startTime=globalThis.performance.now(),this._lastDrawTime=0,this._tick());}stop(){this._rafId!==null&&(globalThis.cancelAnimationFrame(this._rafId),this._rafId=null),this._canvas=null,this._ctx=null,this._logicalWidth=0,this._logicalHeight=0,this._pixelRatio=1,this._startTime=0,this._lastDrawTime=0;}_getPixelRatio(){let i=globalThis.devicePixelRatio||1,e=this._node.getAbsoluteScale(),t=Math.max(1e-6,Math.max(e.x,e.y)),n=Math.max(1,i*t);n=Math.min(this._maxPixelRatio,n);let o=this._logicalWidth||Math.max(1,Math.round(this._node.width()||this._options.fallbackWidth)),s=this._logicalHeight||Math.max(1,Math.round(this._node.height()||this._options.fallbackHeight));if(o*s*n*n>this._maxCanvasPixels){let a=Math.sqrt(this._maxCanvasPixels/(o*s));n=Math.max(1,Math.min(n,a));}return n}_draw(i){let e=this._ctx,t=this._canvas;if(!e||!t)return;let{backgroundColor:n,borderColor:o,baseSpinnerColor:s,accentSpinnerColor:r,text:a,textColor:h,font:c,lineWidth:d}=this._options,u=this._logicalWidth||Math.max(1,Math.round(t.width/this._pixelRatio)),f=this._logicalHeight||Math.max(1,Math.round(t.height/this._pixelRatio));e.clearRect(0,0,u,f),e.fillStyle=n,e.fillRect(0,0,u,f),e.strokeStyle=o,e.lineWidth=d,e.strokeRect(1,1,u-2,f-2);let p=u/2,g=f/2,_=Math.max(10,Math.min(u,f)*.12);e.beginPath(),e.strokeStyle=s,e.lineWidth=Math.max(2,_*.25),e.arc(p,g,_,0,Math.PI*2),e.stroke(),e.beginPath(),e.strokeStyle=r,e.lineWidth=Math.max(2,_*.25),e.lineCap="round";let m=i*Math.PI*2;e.arc(p,g,_,m,m+Math.PI*.9),e.stroke(),e.fillStyle=h,e.font=c,e.textAlign="center",e.textBaseline="top",e.fillText(a,p,Math.min(f-14,g+_+8));}};var et=class extends D{constructor(e={}){let t=new G__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);l(this,"_canvas",null);l(this,"_placeholder");l(this,"_isLoaded",false);l(this,"_isPlaying",false);l(this,"_giflerLoaded",false);l(this,"_frameIndex",0);this._placeholder=new ce(this.konvaNode,e.placeholder),this._ensureGiflerLibrary(),e.src&&this.setSrc(e.src,e);}async setSrc(e,t={}){if(this._cleanup(),typeof document>"u")throw new Error("GifNode requires a browser environment with document object");await this._ensureGiflerLibrary(),this._placeholder.start();let n=globalThis.document.createElement("canvas");return this._canvas=n,this.konvaNode.setAttr("src",e),new Promise((o,s)=>{if(!globalThis.window.gifler){let r=new Error("Gifler library is not loaded");t.onError&&t.onError(r),s(r);return}try{globalThis.window.gifler(e).frames(n,(r,a)=>{if(n.width=a.width,n.height=a.height,r.drawImage(a.buffer,0,0),this._isLoaded||(this._placeholder.stop(),this.konvaNode.image(n),this._isLoaded=!0,this._isPlaying=t.autoplay??!0,t.onLoad&&t.onLoad(this),o(this)),this._isPlaying){this._frameIndex++,t.onFrame&&t.onFrame(this,this._frameIndex);let h=this.konvaNode.getLayer();h&&h.batchDraw();}});}catch(r){this._placeholder.stop();let a=new Error(`Failed to load GIF: ${e}. ${r.message}`);this._isLoaded=false,t.onError&&t.onError(a),s(a);}})}play(){return this._isPlaying=true,this}pause(){return this._isPlaying=false,this}isPlaying(){return this._isPlaying}isLoaded(){return this._isLoaded}getFrameIndex(){return this._frameIndex}getCanvas(){return this._canvas}getSize(){return this.konvaNode.size()}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}async _ensureGiflerLibrary(){if(this._giflerLoaded||globalThis.window.gifler){this._giflerLoaded=true;return}if(typeof document>"u")throw new Error("GifNode requires a browser environment");let e=globalThis.document.querySelector('script[src*="gifler"]');return e?new Promise((t,n)=>{if(globalThis.window.gifler){this._giflerLoaded=true,t();return}e.addEventListener("load",()=>{this._giflerLoaded=true,t();}),e.addEventListener("error",()=>{n(new Error("Failed to load gifler library"));});}):new Promise((t,n)=>{let o=globalThis.document.createElement("script");o.src="https://unpkg.com/gifler@0.1.0/gifler.min.js",o.onload=()=>{this._giflerLoaded=true,t();},o.onerror=()=>{n(new Error("Failed to load gifler library"));},globalThis.document.head.appendChild(o);})}_cleanup(){this._placeholder.stop(),this._isPlaying=false,this._isLoaded=false,this._frameIndex=0,this._canvas=null;}remove(){this._cleanup(),super.remove();}};var ge=class extends D{constructor(i={}){let e=new G__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 tt=class extends D{constructor(e={}){let t=new G__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);l(this,"_placeholder");this._placeholder=new ce(this.konvaNode,e.placeholder),!e.image&&e.src&&(this.konvaNode.setAttr("src",e.src),this.setSrc(e.src));}getSize(){return this.konvaNode.size()}async setSrc(e,t="anonymous"){this.konvaNode.setAttr("src",e),this._placeholder.start();let n=await this._loadHTMLImage(e,t);return this._placeholder.stop(),this.konvaNode.image(n),this.konvaNode.getLayer()?.batchDraw(),this}setImage(e){return this.konvaNode.image(e),this.konvaNode.getLayer()?.batchDraw(),this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this}getCornerRadius(){return this.konvaNode.cornerRadius()}_loadHTMLImage(e,t="anonymous"){return new Promise((n,o)=>{let s=globalThis.Image??null;if(!s){o(new Error("Image constructor is not available in current environment"));return}let r=new s,a=t;r.crossOrigin=a,r.onload=()=>{n(r);},r.onerror=()=>{o(new Error(`Failed to load image: ${e}`));},r.src=e;})}remove(){this._placeholder.stop(),super.remove();}};var nt=class extends D{constructor(i={}){let e=new G__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 ot=class extends D{constructor(i={}){let e=new G__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 it=class extends D{constructor(i){let e=new G__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 st=class extends D{constructor(i={}){let e=new G__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 rt=class extends D{constructor(e={}){let t=new G__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);l(this,"_isLoading",false);l(this,"_isLoaded",false);l(this,"_placeholder");this._placeholder=new ce(this.konvaNode,e.placeholder),e.src&&this.setSrc(e.src,e.onLoad,e.onError);}isLoading(){return this._isLoading}isLoaded(){return this._isLoaded}getSize(){return this.konvaNode.size()}async setSrc(e,t,n){this.konvaNode.setAttr("src",e),this._isLoading=true,this._isLoaded=false,this._placeholder.start();try{await new Promise((o,s)=>{G__default.default.Image.fromURL(e,r=>{this._placeholder.stop(),this.konvaNode.image(r.image());let a=this.konvaNode.getLayer();a&&a.batchDraw(),this._isLoading=!1,this._isLoaded=!0,t&&t(this),o();},r=>{this._placeholder.stop(),this._isLoading=!1,this._isLoaded=!1;let a=r instanceof Error?r.message:typeof r=="string"?r:"Unknown error",h=new Error(`Failed to load SVG: ${e}. ${a}`);n&&n(h),s(h);});});}catch(o){throw this._placeholder.stop(),this._isLoading=false,this._isLoaded=false,o}return this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}remove(){this._placeholder.stop(),super.remove();}};var Ee=class extends D{constructor(e={}){let t=new G__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);l(this,"_editable");l(this,"_isEditing",false);l(this,"_textarea",null);l(this,"_onTextChangeCallbacks",[]);l(this,"_onEditStartCallbacks",[]);l(this,"_onEditEndCallbacks",[]);l(this,"_pendingGroupEditDblClick",false);l(this,"_groupEditClickResetAttached",false);l(this,"_oldText","");l(this,"_keyHandler",null);l(this,"_clickHandler",null);l(this,"_syncTextareaRafId",null);l(this,"_inputHandler",null);l(this,"_prevWrap",null);this._editable=e.editable??true,this._editable&&this._setupEditHandler(),this._setupTransformHandler();}getText(){return this.konvaNode.text()}setText(e){return this.konvaNode.text(e),this}setFontSize(e){return this.konvaNode.fontSize(e),this}setFontFamily(e){return this.konvaNode.fontFamily(e),this}setFill(e){return this.konvaNode.fill(e),this}setAlign(e){return this.konvaNode.align(e),this}setPadding(e){return this.konvaNode.padding(e),this}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this}setLineHeight(e){return this.konvaNode.lineHeight(e),this}setVerticalAlign(e){return this.konvaNode.verticalAlign(e),this}isEditable(){return this._editable}setEditable(e){return this._editable===e?this:(this._editable=e,e?this._setupEditHandler():(this.konvaNode.off("dblclick.textEdit dbltap.textEdit"),this._isEditing&&this.cancelEdit()),this)}isEditing(){return this._isEditing}startEdit(){this._isEditing||this._openTextarea();}finishEdit(){!this._isEditing||!this._textarea||this._saveAndClose(false);}cancelEdit(){!this._isEditing||!this._textarea||this._saveAndClose(true);}onTextChange(e){return this._onTextChangeCallbacks.push(e),this}offTextChange(e){let t=this._onTextChangeCallbacks.indexOf(e);return t!==-1&&this._onTextChangeCallbacks.splice(t,1),this}onEditStart(e){return this._onEditStartCallbacks.push(e),this}offEditStart(e){let t=this._onEditStartCallbacks.indexOf(e);return t!==-1&&this._onEditStartCallbacks.splice(t,1),this}onEditEnd(e){return this._onEditEndCallbacks.push(e),this}offEditEnd(e){let t=this._onEditEndCallbacks.indexOf(e);return t!==-1&&this._onEditEndCallbacks.splice(t,1),this}_setupEditHandler(){this.konvaNode.on("dblclick.textEdit dbltap.textEdit",()=>{let e=this.konvaNode.getParent(),t=e?e.getParent():null;if(!(e instanceof G__default.default.Group&&t instanceof G__default.default.Group)){this._openTextarea();return}if(!this._groupEditClickResetAttached){let o=this.konvaNode.getStage();o&&(this._groupEditClickResetAttached=true,o.on("mousedown.textEditGroupReset",s=>{s.target!==this.konvaNode&&(this._pendingGroupEditDblClick=false);}));}if(!this._isEditing){if(!this._pendingGroupEditDblClick){this._pendingGroupEditDblClick=true;return}this._pendingGroupEditDblClick=false,this._openTextarea();}});}_setupTransformHandler(){this.konvaNode.on("transform.textResize",()=>{let e=this.konvaNode.scaleX(),t=this.konvaNode.scaleY(),n=Math.max(1,this.konvaNode.width()*e);this.konvaNode.width(n);let o=this.konvaNode.height(),s=Math.max(1,o*t);this.konvaNode.height(s),this.konvaNode.scaleX(1),this.konvaNode.scaleY(1),this._ensureHeightFitsWrappedText();}),this.konvaNode.on("transformend.textResize",()=>{this._ensureHeightFitsWrappedText(),this.konvaNode.getLayer()?.batchDraw();});}_getWrappedLineCount(e){let t=this.konvaNode.text();if(!t)return 1;let n=this.konvaNode.wrap(),o=t.split(`
|
|
2
|
-
`);if(n==="none")return Math.max(1,o.length);let s=Math.max(0,e),r=0;for(let a of o){if(a.length===0){r+=1;continue}if(n==="char"){let d="";for(let u of a){let f=d+u;if(this.konvaNode.measureSize(f).width<=s||d.length===0){d=f;continue}r+=1,d=u;}d.length>0&&(r+=1);continue}let h=a.split(/\s+/g),c="";for(let d of h){if(!d)continue;let u=c?c+" "+d:d;if(this.konvaNode.measureSize(u).width<=s||c.length===0){c=u;continue}r+=1,c=d;}c.length>0&&(r+=1);}return Math.max(1,r)}_ensureHeightFitsWrappedText(){let e=this.konvaNode.padding()*2,t=this.konvaNode.width()-e;if(this.konvaNode.wrap()==="none")return;let n=this._getWrappedLineCount(t),o=this.konvaNode.fontSize()*this.konvaNode.lineHeight(),s=Math.ceil(n*o+e);Number.isFinite(s)&&s>this.konvaNode.height()&&this.konvaNode.height(s);}_ensureWidthFitsText(){let e=this.konvaNode.padding()*2,n=this.konvaNode.text().split(`
|
|
3
|
-
`),o=0;for(let a of n){let h=this.konvaNode.measureSize(a);h.width>o&&(o=h.width);}let r=Math.ceil(o+e+2);Number.isFinite(r)&&r>this.konvaNode.width()&&this.konvaNode.width(r);}_syncNodeSizeFromTextarea(){if(!this._isEditing||!this._textarea)return;let e=this._textarea,t=this.konvaNode.getAbsoluteScale(),n=t.x||t.y||1,o=this.konvaNode.padding()*2,s=e.scrollWidth,r=e.scrollHeight,a=Math.max(1,s/n+o),h=Math.max(1,r/n+o);Number.isFinite(a)&&a!==this.konvaNode.width()&&this.konvaNode.width(a),Number.isFinite(h)&&h!==this.konvaNode.height()&&this.konvaNode.height(h);}_syncTextareaPosition(){if(!this._isEditing||!this._textarea)return;let e=this.konvaNode.getStage();if(!e)return;this._syncNodeSizeFromTextarea();let t=this.konvaNode.absolutePosition(),n=e.container().getBoundingClientRect(),o=this.konvaNode.getAbsoluteScale();this._textarea.style.top=String(n.top+t.y)+"px",this._textarea.style.left=String(n.left+t.x)+"px",this._textarea.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*o.x)+"px",this._textarea.style.fontSize=String(this.konvaNode.fontSize()*o.x)+"px",this._syncTextareaRafId=globalThis.requestAnimationFrame(()=>{this._syncTextareaPosition();});}_openTextarea(){if(this._isEditing)return;let e=this.konvaNode.getStage();if(!e)return;this._isEditing=true,this._oldText=this.konvaNode.text(),this._prevWrap=this.konvaNode.wrap(),this.konvaNode.wrap("none"),this.konvaNode.opacity(0),this.konvaNode.listening(false),e.batchDraw();let t=this.konvaNode.absolutePosition(),n=e.container().getBoundingClientRect(),o=this.konvaNode.getAbsoluteScale(),s=globalThis.document.createElement("textarea");globalThis.document.body.appendChild(s),this._textarea=s,s.value=this.konvaNode.text(),s.style.position="absolute",s.style.top=String(n.top+t.y)+"px",s.style.left=String(n.left+t.x)+"px",s.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*o.x)+"px",s.style.fontSize=String(this.konvaNode.fontSize()*o.x)+"px",s.style.border="none",s.style.padding="0",s.style.margin="0",s.style.overflow="hidden",s.wrap="off",s.style.whiteSpace="pre",s.style.background="none",s.style.outline="none",s.style.resize="none",s.style.lineHeight=String(this.konvaNode.lineHeight()),s.style.fontFamily=this.konvaNode.fontFamily(),s.style.transformOrigin="left top",s.style.textAlign=this.konvaNode.align();let r=this.konvaNode.fill();s.style.color=typeof r=="string"?r:"#000000";let a=this.konvaNode.fontStyle();s.style.fontStyle=a.includes("italic")?"italic":"normal",s.style.fontWeight=a.includes("bold")?"bold":"normal";let h=this.konvaNode.rotation();h&&(s.style.transform="rotateZ("+String(h)+"deg)"),s.style.height="auto",s.focus(),s.select();let c=()=>{if(!this._textarea)return;this._textarea.style.height="auto",this._textarea.style.height=String(this._textarea.scrollHeight)+"px",this._syncNodeSizeFromTextarea();let d=this.konvaNode.getAbsoluteScale(),u=d.x||d.y||1;this._textarea.style.width=String((this.konvaNode.width()-this.konvaNode.padding()*2)*u)+"px",this.konvaNode.getLayer()?.batchDraw();};this._inputHandler=()=>{globalThis.requestAnimationFrame(()=>{c();});},s.addEventListener("input",this._inputHandler),c(),this._syncTextareaRafId=globalThis.requestAnimationFrame(()=>{this._syncTextareaPosition();});for(let d of this._onEditStartCallbacks)d();this._keyHandler=d=>{if(d.key==="Enter"&&(d.ctrlKey||d.metaKey)){d.preventDefault(),this._saveAndClose(false);return}if(d.key==="Escape"){d.preventDefault(),this._saveAndClose(true);return}globalThis.requestAnimationFrame(()=>{c();});},this._clickHandler=d=>{d.target!==s&&this._saveAndClose(false);},s.addEventListener("keydown",this._keyHandler),globalThis.setTimeout(()=>{this._clickHandler&&(globalThis.addEventListener("click",this._clickHandler),globalThis.addEventListener("touchstart",this._clickHandler));});}_saveAndClose(e){if(!this._textarea)return;let t=e?this._oldText:this._textarea.value;this.konvaNode.text(t),e||this._syncNodeSizeFromTextarea(),this._syncTextareaRafId!==null&&(globalThis.cancelAnimationFrame(this._syncTextareaRafId),this._syncTextareaRafId=null),this._keyHandler&&this._textarea.removeEventListener("keydown",this._keyHandler),this._inputHandler&&this._textarea.removeEventListener("input",this._inputHandler),this._clickHandler&&(globalThis.removeEventListener("click",this._clickHandler),globalThis.removeEventListener("touchstart",this._clickHandler)),this._textarea.remove(),this._textarea=null,this._keyHandler=null,this._clickHandler=null,this._inputHandler=null,this._prevWrap&&(this.konvaNode.wrap(this._prevWrap),this._prevWrap=null),this._ensureWidthFitsText(),this._ensureHeightFitsWrappedText(),this.konvaNode.opacity(1),this.konvaNode.listening(true),this.konvaNode.getStage()?.batchDraw(),this._isEditing=false,this._pendingGroupEditDblClick=false;for(let n of this._onTextChangeCallbacks)n({oldText:this._oldText,newText:t,cancelled:e});for(let n of this._onEditEndCallbacks)n();}};var at=class extends D{constructor(e={}){let t=new G__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);l(this,"_videoElement",null);l(this,"_animation",null);l(this,"_placeholder");l(this,"_isPlaying",false);l(this,"_isLoaded",false);this._placeholder=new ce(this.konvaNode,{fallbackWidth:320,fallbackHeight:240,...e.placeholder??{}}),e.src&&this.setSrc(e.src,e);}async setSrc(e,t={}){if(this._cleanup(),typeof document>"u")throw new Error("VideoNode requires a browser environment with document object");let n=this.konvaNode.getAttrs(),o=t.loop??n.loop??false,s=t.muted??n.muted??false,r=t.autoplay??n.autoplay,a=t.currentTime??n.currentTime??0,h=t.volume??n.volume??1,c=t.playbackRate??n.playbackRate??1;this._placeholder.start();let d=globalThis.document.createElement("video");return d.preload="auto",d.src=e,d.loop=o,d.muted=s,d.currentTime=a,d.volume=h,d.playbackRate=c,d.load(),this._videoElement=d,this.konvaNode.setAttr("src",e),this.konvaNode.setAttr("loop",o),this.konvaNode.setAttr("muted",s),this.konvaNode.setAttr("currentTime",a),this.konvaNode.setAttr("autoplay",r),this._ensureAnimation(),new Promise((u,f)=>{let p=false,g=()=>{p||(p=true,this._isLoaded=true,this._placeholder.stop(),this.konvaNode.image(d),this.konvaNode.getLayer()?.batchDraw(),r&&this.play(),u(this));};d.addEventListener("loadedmetadata",()=>{t.onLoadedMetadata&&t.onLoadedMetadata(this,d);}),d.addEventListener("loadeddata",()=>{g();}),d.addEventListener("canplay",()=>{g();}),d.addEventListener("error",()=>{if(p)return;p=true,this._placeholder.stop();let _=new Error(`Failed to load video: ${e}`);this._isLoaded=false,t.onError&&t.onError(_),f(_);}),t.onPlay&&d.addEventListener("play",()=>{t.onPlay&&t.onPlay(this);}),t.onPause&&d.addEventListener("pause",()=>{t.onPause&&t.onPause(this);}),t.onEnded&&d.addEventListener("ended",()=>{t.onEnded&&t.onEnded(this);});})}async play(){if(!this._videoElement)throw new Error("Video element is not initialized");this._ensureAnimation();try{await this._videoElement.play(),this._isPlaying=!0,this._animation?.start();}catch(e){let t=e;t.name==="NotAllowedError"||t.message.includes("user didn't interact")?globalThis.console.warn("Video autoplay blocked by browser policy. User interaction required.",t.message):globalThis.console.error("Failed to play video:",t.message);}return this}pause(){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.pause(),this._isPlaying=false,this._animation?.stop(),this}stop(){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.pause(),this._videoElement.currentTime=0,this._isPlaying=false,this._animation?.stop(),this}setCurrentTime(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.currentTime=e,this.konvaNode.setAttr("currentTime",e),this}getCurrentTime(){return this._videoElement?this._videoElement.currentTime:0}getDuration(){return this._videoElement?this._videoElement.duration:0}setVolume(e){if(!this._videoElement)throw new Error("Video element is not initialized");let t=Math.max(0,Math.min(1,e));return this._videoElement.volume=t,this.konvaNode.setAttr("volume",t),this}getVolume(){return this._videoElement?this._videoElement.volume:0}setMuted(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.muted=e,this.konvaNode.setAttr("muted",e),this}isMuted(){return this._videoElement?this._videoElement.muted:false}setLoop(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.loop=e,this.konvaNode.setAttr("loop",e),this}isLoop(){return this._videoElement?this._videoElement.loop:false}setPlaybackRate(e){if(!this._videoElement)throw new Error("Video element is not initialized");return this._videoElement.playbackRate=e,this.konvaNode.setAttr("playbackRate",e),this}getPlaybackRate(){return this._videoElement?this._videoElement.playbackRate:1}isPlaying(){return this._isPlaying}isLoaded(){return this._isLoaded}getVideoElement(){return this._videoElement}getSize(){return this.konvaNode.size()}setSize({width:e,height:t}){return this.konvaNode.size({width:e,height:t}),this.konvaNode.getLayer()?.batchDraw(),this}setCornerRadius(e){return this.konvaNode.cornerRadius(e),this.konvaNode.getLayer()?.batchDraw(),this}getCornerRadius(){return this.konvaNode.cornerRadius()}setOpacity(e){return this.konvaNode.opacity(e),this.konvaNode.getLayer()?.batchDraw(),this}getOpacity(){return this.konvaNode.opacity()}_ensureAnimation(){if(this._animation)return;let e=this.konvaNode.getLayer();e&&(this._animation=new G__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 Oe=class{constructor(i,e){l(this,"_layer");l(this,"_world");l(this,"_nodes",new Map);l(this,"_stage");l(this,"_eventBus");l(this,"_frameLabels",new Map);l(this,"_selectedFrame",null);l(this,"_batchDrawScheduled",false);l(this,"_listCache",null);l(this,"_listCacheInvalidated",true);l(this,"_hadFrameInLastMultiSelection",false);this._layer=new G__default.default.Layer,this._world=new G__default.default.Group,this._layer.add(this._world),this._stage=i,this._stage.add(this._layer),this._eventBus=e,this._eventBus.on("node:created",n=>{this._attachFrameAutogroupHandlers(n);}),this._eventBus.on("node:removed",n=>{if(n instanceof A){let o=this._frameLabels.get(n);o&&(o.destroy(),this._frameLabels.delete(n));}}),this._eventBus.on("node:transformed",n=>{n instanceof A&&this._updateFrameLabelsPosition();});let t=()=>{this._updateFrameLabelsPosition();};this._eventBus.on("camera:zoom",t),this._eventBus.on("camera:setZoom",t),this._eventBus.on("camera:reset",t),this._eventBus.on("camera:pan",t),this._eventBus.on("node:selected",n=>{for(let[,o]of this._frameLabels.entries()){let s=o._baseFill;o.fill(s);}if(n instanceof A){this._selectedFrame=n;let o=this._frameLabels.get(n);if(o){let s=o._hoverFill;o.fill(s);}this._enforceFrameDraggableInvariant(n);}else this._selectedFrame=null;this._layer.batchDraw();}),this._eventBus.on("node:deselected",n=>{n instanceof A&&this._enforceFrameDraggableInvariant(n);}),this._eventBus.on("selection:multi:created",n=>{for(let[,o]of this._frameLabels.entries()){let s=o._baseFill;o.fill(s);}this._selectedFrame=null,this._hadFrameInLastMultiSelection=false;for(let o of n)if(o instanceof A){let s=this._frameLabels.get(o);if(s){let r=s._hoverFill;s.fill(r);}this._selectedFrame||(this._selectedFrame=o),this._hadFrameInLastMultiSelection=true;}this._layer.batchDraw();}),this._eventBus.on("selection:multi:destroyed",()=>{if(this._hadFrameInLastMultiSelection){for(let[,n]of this._frameLabels.entries()){let o=n._baseFill;n.fill(o);}this._hadFrameInLastMultiSelection=false,this._layer.batchDraw();}}),this._eventBus.on("selection:cleared",()=>{this._selectedFrame=null;for(let[,n]of this._frameLabels.entries()){let o=n._baseFill;n.fill(o);}this._layer.batchDraw();for(let n of this._nodes.values())n instanceof A&&this._enforceFrameDraggableInvariant(n);});}get layer(){return this._layer}get world(){return this._world}get stage(){return this._stage}get eventBus(){return this._eventBus}addShape(i){let e=new it(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addText(i){let e=new Ee(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addImage(i){let e=new tt(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addCircle(i){let e=new $e(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addEllipse(i){let e=new Je(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addArc(i){let e=new Ze(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addStar(i){let e=new st(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addArrow(i){let e=new qe(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addRing(i){let e=new ot(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addRegularPolygon(i){let e=new nt(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addGroup(i){let e=new ge(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addSvg(i){let e=new rt(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addVideo(i){let e=new at(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addGif(i){let e=new et(i);return this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw(),e}addFrame(i){let e=new A(i);this._world.add(e.getKonvaNode()),this._nodes.set(e.id,e),this._listCacheInvalidated=true,this._eventBus.emit("node:created",e),this._scheduleBatchDraw();let t=i.label??i.name??"Frame",n=i.labelColor??"#ffffff",o=i.labelHoverColor??"#2683ff",s=new G__default.default.Text({text:t,fontSize:12,fill:n,listening:true});s._baseFill=n,s._hoverFill=o,this._layer.add(s),this._frameLabels.set(e,s);let r=s.fill();s.on("mouseenter.frame-label-ui",()=>{s.fill(o),this._layer.batchDraw();}),s.on("mouseleave.frame-label-ui",()=>{this._selectedFrame!==e&&(s.fill(r),this._layer.batchDraw());}),s.on("click.frame-label-ui tap.frame-label-ui",h=>{let c=h.evt,d=c.shiftKey,u=c.ctrlKey||c.metaKey;this._eventBus.emit("frame:label-clicked",e,{shiftKey:d,ctrlKey:u});}),s.on("mousedown.frame-label-drag",h=>{if(h.evt.button!==0)return;let c=this._stage,d=e.getKonvaNode(),u=3,f=h.evt.clientX,p=h.evt.clientY,g=c.draggable(),_=false,m=v=>{let w=Math.abs(v.evt.clientX-f),x=Math.abs(v.evt.clientY-p);!_&&(w>u||x>u)&&(_=true,d.on("dragstart.frame-label-drag-once",()=>{c.draggable(false),this._eventBus.emit("frame:label-dragstart",e);}),d.on("dragend.frame-label-drag-once",()=>{c.draggable(g),d.off(".frame-label-drag-once"),this._eventBus.emit("frame:label-clicked",e),this._eventBus.emit("frame:label-dragend",e);}),typeof d.startDrag=="function"&&d.startDrag(),h.cancelBubble=true);},b=()=>{c.off("mousemove.frame-label-drag-temp",m),c.off("mouseup.frame-label-drag-temp",b);};c.on("mousemove.frame-label-drag-temp",m),c.on("mouseup.frame-label-drag-temp",b);}),s.on("dblclick.frame-label-ui dbltap.frame-label-ui",h=>{h.cancelBubble=true;let c=this._stage.container(),d=s.text(),u=globalThis.document.createElement("input");u.type="text",u.value=d,u.maxLength=40,u.style.position="absolute",u.style.boxSizing="border-box";let f=s.getClientRect({skipShadow:true,skipStroke:true});u.style.left=String(f.x)+"px",u.style.top=String(f.y)+"px",u.style.width=String(f.width||80)+"px",u.style.height=String(f.height||16)+"px",u.style.backgroundColor="transparent",u.style.color=n,u.style.border="none",u.style.outline="none";let p=String(s.fontSize())+"px",g=s.fontFamily()||"sans-serif";u.style.fontSize=p,u.style.fontFamily=g;let _=s.visible();s.visible(false),this._layer.batchDraw();let m=globalThis.document.createElement("span");m.style.position="absolute",m.style.visibility="hidden",m.style.whiteSpace="pre",m.style.fontSize=p,m.style.fontFamily=g,c.appendChild(m);let b=()=>{let T=u.value||" ";m.textContent=T;let K=m.getBoundingClientRect(),L=16;u.style.width=String(K.width+L)+"px";};c.appendChild(u),u.focus(),u.select(),b();let v=false,w=()=>{v||(v=true,u.removeEventListener("keydown",k),u.removeEventListener("blur",S),u.removeEventListener("input",C),u.parentNode===c&&c.removeChild(u),m.parentNode===c&&c.removeChild(m),s.visible(_),this._layer.batchDraw());},x=()=>{if(v)return;let T=u.value.trim();T.length>=1&&T.length<=40&&T!==d&&(s.text(T),this._eventBus.emit("frame:label-changed",e,T),this._layer.batchDraw()),w();},N=()=>{v||w();},k=T=>{T.key==="Escape"?(T.preventDefault(),N()):T.key==="Enter"&&(T.preventDefault(),x());},C=()=>{b();},S=()=>{x();};u.addEventListener("keydown",k),u.addEventListener("blur",S),u.addEventListener("input",C);});let a=e.getKonvaNode();return a.on("dragmove.frame-label",()=>{this._updateFrameLabelsPosition();}),a.on("transform.frame-label",()=>{this._updateFrameLabelsPosition();}),a.on("xChange.frame-label yChange.frame-label widthChange.frame-label heightChange.frame-label scaleXChange.frame-label scaleYChange.frame-label rotationChange.frame-label",()=>{this._updateFrameLabelsPosition();}),this._updateFrameLabelsPosition(),e}remove(i){this._eventBus.emit("node:removed",i),i.remove(),this._nodes.delete(i.id),this._listCacheInvalidated=true,this._scheduleBatchDraw();}findById(i){return this._nodes.get(i)}list(){return (this._listCacheInvalidated||!this._listCache)&&(this._listCache=Array.from(this._nodes.values()),this._listCacheInvalidated=false),this._listCache}_scheduleBatchDraw(){if(this._batchDrawScheduled)return;this._batchDrawScheduled=true;let i=globalThis.requestAnimationFrame;i(()=>{this._batchDrawScheduled=false,this._layer.batchDraw();});}_listFrames(){let i=[];for(let e of this._nodes.values())e instanceof A&&i.push(e);return i}_attachFrameAutogroupHandlers(i){if(i instanceof A)return;let e=i.getKonvaNode();e.on("dragmove.frame-autogroup",()=>{let t=this._stage.getPointerPosition();if(!t)return;let n=e.getParent(),o=this._world,s=null;e:for(let a of this._listFrames()){let h=n,c=a.getContentGroup();for(;h&&h!==o;){if(h===c){s=a;break e}h=h.getParent();}}let r=null;for(let a of this._listFrames()){let c=a.getRect().getClientRect({skipShadow:true,skipStroke:true});if(t.x>=c.x&&t.x<=c.x+c.width&&t.y>=c.y&&t.y<=c.y+c.height){r=a;break}}if(s){if(!r||r!==s){let a=e.getAbsolutePosition();this._world.add(e),e.setAbsolutePosition(a),this._layer.batchDraw();let d=s.getContentGroup().getChildren().length>0,u=s.getKonvaNode();typeof u.draggable=="function"&&u.draggable(!d),this._eventBus.emit("frame:children-changed",s,d);}return}if(r&&n!==r.getContentGroup()){let a=e.getAbsolutePosition(),h=r.getContentGroup();h.add(e),e.setAbsolutePosition(a),this._layer.batchDraw();let c=h.getChildren().length>0,d=r.getKonvaNode();typeof d.draggable=="function"&&d.draggable(!c),this._eventBus.emit("frame:children-changed",r,c);}});}_updateFrameLabelsPosition(){for(let[i,e]of this._frameLabels.entries()){let n=i.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false}),o=16,s=n.x,r=n.y-o;e.absolutePosition({x:s,y:r}),e.offsetX(0),e.offsetY(0);}this._layer.batchDraw();}_enforceFrameDraggableInvariant(i){let t=i.getContentGroup().getChildren().length>0,n=i.getKonvaNode();typeof n.draggable=="function"&&n.draggable(!t);}};var ve=class{constructor(i=16){l(this,"_lastTime",0);l(this,"_throttle");this._throttle=i;}shouldExecute(){let i=Date.now();return i-this._lastTime<this._throttle?false:(this._lastTime=i,true)}reset(){this._lastTime=0;}setThrottle(i){this._throttle=i;}getThrottle(){return this._throttle}};var lt=class{constructor(i={}){l(this,"_enabled");l(this,"_levels");l(this,"_currentScale",1);l(this,"_appliedNodes",new Map);this._enabled=i.enabled??true,this._levels=i.levels??[{minScale:0,maxScale:.1,simplify:true,disableStroke:true,disableShadow:true,disablePerfectDraw:true},{minScale:.1,maxScale:.3,simplify:true,disableShadow:true,disablePerfectDraw:true},{minScale:.3,maxScale:1/0,simplify:false}];}_getLODLevel(i){return this._enabled?this._levels.find(t=>i>=t.minScale&&i<t.maxScale)??null:null}applyLOD(i,e){if(!this._enabled)return;this._currentScale=e;let t=this._getLODLevel(e);if(!t?.simplify){this._restoreNode(i);return}let n=i.getKonvaNode(),o=this._appliedNodes.get(i.id);o!==t&&(o||(n._originalLOD={stroke:n.stroke?.(),strokeEnabled:n.strokeEnabled(),shadow:n.shadowEnabled(),perfectDraw:n.perfectDrawEnabled?.()}),t.disableStroke&&n.strokeEnabled(false),t.disableShadow&&n.shadowEnabled(false),t.disablePerfectDraw&&n.perfectDrawEnabled&&n.perfectDrawEnabled(false),this._appliedNodes.set(i.id,t));}_restoreNode(i){let e=i.getKonvaNode(),t=e._originalLOD;t&&(e.strokeEnabled(t.strokeEnabled),e.shadowEnabled(t.shadow),t.perfectDraw!==void 0&&e.perfectDrawEnabled&&e.perfectDrawEnabled(t.perfectDraw),this._appliedNodes.delete(i.id),delete e._originalLOD);}applyToAll(i,e){if(this._enabled)for(let t of i)this.applyLOD(t,e);}restoreAll(i){for(let e of i)this._restoreNode(e);this._appliedNodes.clear();}enable(){this._enabled=true;}disable(i){this._enabled=false,this.restoreAll(i);}get enabled(){return this._enabled}get currentScale(){return this._currentScale}getStats(){return {enabled:this._enabled,currentScale:this._currentScale,appliedNodes:this._appliedNodes.size,currentLevel:this._getLODLevel(this._currentScale)}}setLevels(i){this._levels=i;}};var dt=class{constructor(i,e,t,n={}){this._stage=i;this._world=e;this._nodeManager=t;l(this,"_enabled");l(this,"_bufferZone");l(this,"_throttle");l(this,"_viewport",{x:0,y:0,width:0,height:0});l(this,"_visibleNodes",new Set);l(this,"_hiddenNodes",new Set);l(this,"_tempMultiNodeIds",new Set);l(this,"_updateScheduled",false);l(this,"_lod",null);this._enabled=n.enabled??true,this._bufferZone=n.bufferZone??200,this._throttle=new ve(n.throttleMs??16),n.lod&&(this._lod=new lt(n.lod)),this._updateViewport(),this._setupListeners(),this._enabled&&this.updateVisibility();}_updateViewport(){let i=this._world.scaleX(),e=this._world.position();this._viewport={x:-e.x/i-this._bufferZone,y:-e.y/i-this._bufferZone,width:this._stage.width()/i+this._bufferZone*2,height:this._stage.height()/i+this._bufferZone*2};}_getNodeBBox(i){let t=i.getKonvaNode().getClientRect({relativeTo:this._world});return {x:t.x,y:t.y,width:t.width,height:t.height}}_isNodeVisible(i){let e=i.getKonvaNode();if(this._tempMultiNodeIds.has(i.id))return true;let t=e.getParent();if(t&&t instanceof G__default.default.Group&&t!==this._world)return true;let n=this._getNodeBBox(i);return !(n.x+n.width<this._viewport.x||n.x>this._viewport.x+this._viewport.width||n.y+n.height<this._viewport.y||n.y>this._viewport.y+this._viewport.height)}updateVisibility(){if(!this._enabled||!this._throttle.shouldExecute())return;let i=this._nodeManager.list(),e=new Set,t=0;for(let n of i){let o=this._isNodeVisible(n),s=n.getKonvaNode();o?(e.add(n.id),this._hiddenNodes.has(n.id)&&(s.visible(true),s.listening(true),this._hiddenNodes.delete(n.id),t++)):this._hiddenNodes.has(n.id)||(s.visible(false),s.listening(false),this._hiddenNodes.add(n.id),t++);}if(this._visibleNodes=e,this._lod?.enabled&&t>0){let n=this._world.scaleX();for(let o of i)e.has(o.id)&&this._lod.applyLOD(o,n);}t>0&&this._nodeManager.layer.batchDraw();}_setupListeners(){this._world.on("xChange yChange scaleXChange scaleYChange",()=>{this._scheduleUpdate();}),typeof globalThis.window<"u"&&globalThis.window.addEventListener("resize",()=>{this._updateViewport(),this._scheduleUpdate();}),this._nodeManager.eventBus.on("node:removed",i=>{this._visibleNodes.delete(i.id),this._hiddenNodes.delete(i.id),this._tempMultiNodeIds.delete(i.id);}),this._nodeManager.eventBus.on("selection:multi:created",i=>{this._tempMultiNodeIds.clear();for(let e of i)this._tempMultiNodeIds.add(e.id);}),this._nodeManager.eventBus.on("selection:multi:destroyed",()=>{this._tempMultiNodeIds.clear();});}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=true,globalThis.requestAnimationFrame(()=>{this._updateViewport(),this.updateVisibility(),this._updateScheduled=false;}));}enable(){this._enabled||(this._enabled=true,this.updateVisibility());}disable(){if(this._enabled){this._enabled=false;for(let i of this._hiddenNodes){let e=this._nodeManager.findById(i);if(e){let t=e.getKonvaNode();t.visible(true),t.listening(true);}}this._hiddenNodes.clear(),this._visibleNodes.clear(),this._nodeManager.layer.batchDraw();}}getStats(){let i=this._nodeManager.list().length,e=this._visibleNodes.size,t=this._hiddenNodes.size;return {total:i,visible:e,hidden:t,cullingRate:i>0?t/i*100:0}}setBufferZone(i){this._bufferZone=i,this._updateViewport(),this._scheduleUpdate();}setThrottle(i){this._throttle=new ve(i);}get enabled(){return this._enabled}get viewport(){return {...this._viewport}}forceUpdate(){this._throttle.reset(),this._updateViewport(),this.updateVisibility();}get lod(){return this._lod}destroy(){if(this.disable(),this._visibleNodes.clear(),this._hiddenNodes.clear(),this._lod){let i=this._nodeManager.list();this._lod.restoreAll(i);}}};var ct=class{constructor(i){l(this,"_plugin");l(this,"_addons",new Set);l(this,"_core");this._plugin=i;}_attachAll(i){this._core=i,this._addons.forEach(e=>{e.attach(this._plugin,i);});}_detachAll(i){this._addons.forEach(e=>{e.detach(this._plugin,i);}),this._core=void 0;}add(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)||(this._addons.add(t),this._core&&t.attach(this._plugin,this._core));return this._plugin}remove(i){let e=Array.isArray(i)?i:[i];for(let t of e)this._addons.has(t)&&(this._addons.delete(t),this._core&&t.detach(this._plugin,this._core));return this._plugin}list(){return Array.from(this._addons)}has(i){return this._addons.has(i)}clear(){if(this._core){let i=this._core;this._addons.forEach(e=>{e.detach(this._plugin,i);});}this._addons.clear();}};var O=class{constructor(){l(this,"addons");this.addons=new ct(this);}attach(i){this.onAttach(i),this.addons._attachAll(i);}detach(i){this.addons._detachAll(i),this.onDetach(i);}};var Ie=class{constructor(i,e=[]){l(this,"_core");l(this,"_items",[]);this._core=i,e.length&&this.addPlugins(e);}addPlugins(i){let e=[];for(let t of i)this._items.includes(t)||(this._items.push(t),t.attach(this._core),e.push(t),this._core.eventBus.emit("plugin:added",t.constructor.name));return e}removePlugins(i){let e=[];for(let t of i){let n=this._items.indexOf(t);n!==-1&&(t.detach(this._core),this._items.splice(n,1),e.push(t),this._core.eventBus.emit("plugin:removed",t.constructor.name));}return e}removeAllPlugins(){let i=[...this._items];for(let e of i)e.detach(this._core);this._items=[];for(let e of i)this._core.eventBus.emit("plugin:removed",e.constructor.name);return i}list(){return [...this._items]}get(i){return this._items.find(e=>e.constructor.name===i)}};var xt=class{constructor(i){l(this,"_stage");l(this,"_eventBus");l(this,"_initialWidth");l(this,"_initialHeight");l(this,"_autoResize");l(this,"_backgroundColor");l(this,"_draggable");l(this,"_minScale");l(this,"_maxScale");l(this,"_gridLayer");l(this,"_resizeObserver",null);l(this,"container");l(this,"nodes");l(this,"camera");l(this,"virtualization");l(this,"plugins");l(this,"_handleResize",()=>{if(!this._autoResize)return;let i=this.container.offsetWidth,e=this.container.offsetHeight;(i!==this._stage.width()||e!==this._stage.height())&&this.setSize({width:i,height:e});});this.container=i.container,this.container.style.visibility="hidden",this._initialWidth=i.width??800,this._initialHeight=i.height??800,this._autoResize=i.autoResize??true,this._backgroundColor=i.backgroundColor??"#1e1e1e",this._draggable=i.draggable??true,this._minScale=i.minScale??.1,this._maxScale=i.maxScale??500,this._stage=new G__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 Be,this._gridLayer=new G__default.default.Layer({listening:false}),this._stage.add(this._gridLayer),this.nodes=new Oe(this._stage,this._eventBus),this.camera=new Le({stage:this._stage,target:this.nodes.world,eventBus:this._eventBus,initialScale:1,draggable:false,minScale:this._minScale,maxScale:this._maxScale}),this.virtualization=new dt(this._stage,this.nodes.world,this.nodes,i.virtualization),this.plugins=new Ie(this),i.plugins?.length&&this.plugins.addPlugins(i.plugins),this._autoResize&&this._setupAutoResize();}_setupAutoResize(){typeof ResizeObserver<"u"?(this._resizeObserver=new ResizeObserver(()=>{this._handleResize();}),this._resizeObserver.observe(this.container)):globalThis.addEventListener("resize",this._handleResize);}destroy(){this._resizeObserver?(this._resizeObserver.disconnect(),this._resizeObserver=null):globalThis.removeEventListener("resize",this._handleResize),this._stage.destroy();}get eventBus(){return this._eventBus}get stage(){return this._stage}get gridLayer(){return this._gridLayer}get draggable(){return this._draggable}get autoResize(){return this._autoResize}get backgroundColor(){return this._backgroundColor}get initialWidth(){return this._initialWidth}get initialHeight(){return this._initialHeight}get minScale(){return this._minScale}get maxScale(){return this._maxScale}setSize({width:i,height:e}){this._stage.size({width:i,height:e}),this._stage.fire("resize"),this._eventBus.emit("stage:resized",{width:i,height:e});}setBackgroundColor(i){this.container.style.background=i;}setDraggable(i){this._stage.draggable(i),this._draggable=i;}setAutoResize(i){this._autoResize!==i&&(this._autoResize=i,i?(this._setupAutoResize(),this._handleResize()):this._resizeObserver?(this._resizeObserver.disconnect(),this._resizeObserver=null):globalThis.removeEventListener("resize",this._handleResize));}showContainer(){this.container.style.visibility="visible";}};var Ge=class{constructor(){l(this,"_actions",[]);l(this,"_currentIndex",-1);}push(i){this._currentIndex<this._actions.length-1&&this.pop(this._currentIndex+1),this._actions.push(i),this._currentIndex=this._actions.length-1,this._debug("push",i);}pop(i){if(i<0||i>this._actions.length)return;let e=this._actions.splice(i);this._currentIndex=Math.min(this._currentIndex,this._actions.length-1),this._debug("pop",{fromIndex:i,removedCount:e.length});}select(i){if(i<-1||i>=this._actions.length)return;let e=this._currentIndex;this._currentIndex=i,this._debug("select",{oldIndex:e,newIndex:i});}getCurrentIndex(){return this._currentIndex}get length(){return this._actions.length}getActions(){return [...this._actions]}canUndo(){return this._currentIndex>=0}canRedo(){return this._currentIndex<this._actions.length-1}undo(){if(!this.canUndo())return this._debug("undo","cannot undo - at beginning"),null;let i=this._actions[this._currentIndex];return this._currentIndex--,this._debug("undo",{action:i,newIndex:this._currentIndex}),i??null}redo(){if(!this.canRedo())return this._debug("redo","cannot redo - at end"),null;this._currentIndex++;let i=this._actions[this._currentIndex];return this._debug("redo",{action:i,newIndex:this._currentIndex}),i??null}clear(){this._actions=[],this._currentIndex=-1,this._debug("clear","history cleared");}getAction(i){return i<0||i>=this._actions.length?null:this._actions[i]??null}_debug(i,e){}};var oe=class{attach(i,e){this.onAttach(i,e);}detach(i,e){this.onDetach(i,e);}};var He=class extends oe{constructor(e={}){super();l(this,"_core",null);l(this,"_rootEl",null);l(this,"_controlsEl",null);l(this,"_playBtn",null);l(this,"_muteBtn",null);l(this,"_speedBtn",null);l(this,"_timeLabel",null);l(this,"_seekInput",null);l(this,"_volInput",null);l(this,"_selectedVideoNode",null);l(this,"_selectedVideoEl",null);l(this,"_hiddenForDrag",false);l(this,"_hiddenForSize",false);l(this,"_hiddenForTransform",false);l(this,"_hiddenForZoom",false);l(this,"_hiddenForWorldScale",false);l(this,"_hiddenForNotReady",false);l(this,"_uiMode","full");l(this,"_zoomUnhideTimeoutId",null);l(this,"_onKonvaDragStart",null);l(this,"_onKonvaDragEnd",null);l(this,"_onKonvaTransformStart",null);l(this,"_onKonvaTransformEnd",null);l(this,"_onLayerTransformStart",null);l(this,"_onLayerTransformEnd",null);l(this,"_onLayerDragStart",null);l(this,"_onLayerDragEnd",null);l(this,"_rafId",null);l(this,"_options");l(this,"_onNodeSelected",null);l(this,"_onNodeDeselected",null);l(this,"_onSelectionCleared",null);l(this,"_onNodeTransformed",null);l(this,"_onStageResized",null);l(this,"_onCameraChanged",null);l(this,"_onWorldChanged",null);l(this,"_onTimeUpdate",null);l(this,"_onLoadedMetadata",null);l(this,"_onCanPlay",null);l(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=p=>{let g=p.target;g instanceof HTMLInputElement&&g.type==="range"||p.stopPropagation();};n.addEventListener("pointerdown",o),n.addEventListener("mousedown",o),n.addEventListener("touchstart",o),n.addEventListener("wheel",p=>{p.ctrlKey&&p.preventDefault();},{passive:false});let s=p=>{let g=globalThis.document.createElement("button");return g.type="button",g.textContent=p,g.style.height="28px",g.style.minWidth="34px",g.style.padding="0 10px",g.style.borderRadius="8px",g.style.border="1px solid "+this._options.uiBorderColor,g.style.background="rgba(0,0,0,0.12)",g.style.color=this._options.uiTextColor,g.style.cursor="pointer",g.style.fontSize="12px",g.style.fontFamily="Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",g.style.lineHeight="28px",g.style.whiteSpace="nowrap",g},r=s("Play");r.style.minWidth="56px";let a=s("Mute");a.style.minWidth="56px";let h=globalThis.document.createElement("span");h.textContent="0:00 / 0:00",h.style.color=this._options.uiTextColor,h.style.opacity="0.9",h.style.fontSize="12px",h.style.fontFamily="Inter, system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell",h.style.whiteSpace="nowrap";let c=s("1x"),d=globalThis.document.createElement("input");d.type="range",d.min="0",d.max="0",d.step="0.01",d.value="0",d.style.flex="1",d.style.height="6px",d.style.cursor="pointer",d.style.accentColor=this._options.uiAccentColor;let u=globalThis.document.createElement("input");u.type="range",u.min="0",u.max="1",u.step="0.01",u.value="1",u.style.width="90px",u.style.height="6px",u.style.cursor="pointer",u.style.accentColor=this._options.uiAccentColor,n.appendChild(r),n.appendChild(d),n.appendChild(h),n.appendChild(a),n.appendChild(u),n.appendChild(c),t.appendChild(n);let f=e.stage.container();f.style.position=f.style.position||"relative",f.appendChild(t),this._rootEl=t,this._controlsEl=n,this._playBtn=r,this._muteBtn=a,this._speedBtn=c,this._timeLabel=h,this._seekInput=d,this._volInput=u,this._updateRangeFill(d,0),this._updateRangeFill(u,1),r.addEventListener("click",()=>{let p=this._selectedVideoNode,g=this._selectedVideoEl;!p||!g||(g.paused?p.play():p.pause(),this._syncControls());}),d.addEventListener("input",()=>{let p=this._selectedVideoNode,g=this._selectedVideoEl;if(!p||!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,_));p.setCurrentTime(m),this._updateRangeFill(d,g.duration>0?m/g.duration:0),this._syncControls();}),a.addEventListener("click",()=>{let p=this._selectedVideoNode,g=this._selectedVideoEl;if(!p||!g)return;let _=!g.muted;p.setMuted(_),!_&&g.volume<=0&&p.setVolume(.8),this._syncControls();}),u.addEventListener("input",()=>{let p=this._selectedVideoNode,g=this._selectedVideoEl;if(!p||!g)return;let _=Math.max(0,Math.min(1,Number(u.value)));p.setVolume(_),_>0&&g.muted&&p.setMuted(false),this._updateRangeFill(u,_),this._syncControls();}),c.addEventListener("click",()=>{let p=this._selectedVideoNode,g=this._selectedVideoEl;if(!p||!g)return;let _=this._options.speeds;if(!Array.isArray(_)||_.length===0)return;let m=g.playbackRate,b=_.findIndex(w=>Math.abs(w-m)<.001);b<0&&(b=0);let v=_[(b+1)%_.length];typeof v=="number"&&Number.isFinite(v)&&v>0&&p.setPlaybackRate(v),this._syncControls();});}_updateRangeFill(e,t){let n=Math.max(0,Math.min(1,t)),o=Math.round(n*100),s=this._options.uiTrackFilledColor,r=this._options.uiTrackColor;e.style.background="linear-gradient(to right, "+s+" 0%, "+s+" "+String(o)+"%, "+r+" "+String(o)+"%, "+r+" 100%)",e.style.borderRadius="999px",e.style.border="none",e.style.outline="none";}_tryShowForNode(e){if(!this._core)return;if(!e||typeof e.getKonvaNode!="function"){this._hide();return}let t=e.getKonvaNode();if((t&&typeof t.getAttr=="function"?t.getAttr("flowscapeNodeType"):void 0)!=="video"){this._hide();return}this._show(e);}_show(e){this._rootEl&&(this._selectedVideoNode=e,this._selectedVideoEl=e.getVideoElement(),this._bindKonvaDragEvents(),this._bindKonvaTransformEvents(),this._bindVideoEvents(),this._hiddenForZoom=false,this._hiddenForTransform=false,this._hiddenForNotReady=!this._isVideoReady(),this._rootEl.style.display=this._hiddenForNotReady?"none":"block",this._hiddenForSize=false,this._scheduleSync(),this._syncControls());}_hide(){this._rootEl&&(this._rootEl.style.display="none"),this._hiddenForDrag=false,this._hiddenForSize=false,this._hiddenForTransform=false,this._hiddenForZoom=false,this._hiddenForWorldScale=false,this._hiddenForNotReady=false,this._unbindKonvaDragEvents(),this._unbindKonvaTransformEvents(),this._unbindVideoEvents(),this._selectedVideoNode=null,this._selectedVideoEl=null;}_bindLayerInteractionEvents(e){let t=e.nodes.layer;typeof t.on!="function"||typeof t.off!="function"||(this._unbindLayerInteractionEvents(e),this._onLayerTransformStart=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onLayerTransformEnd=()=>{if(this._rootEl&&this._selectedVideoNode){if(this._hiddenForTransform=false,this._hiddenForDrag||this._hiddenForZoom||this._hiddenForSize||this._hiddenForNotReady){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}},this._onLayerDragStart=n=>{if(!this._rootEl||!this._selectedVideoNode)return;let o=n.target,s=typeof o?.name=="function"?o.name():void 0;typeof s=="string"&&s.startsWith("rotate-")&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onLayerDragEnd=()=>{if(this._rootEl&&this._selectedVideoNode){if(this._hiddenForTransform=false,this._hiddenForDrag||this._hiddenForZoom||this._hiddenForSize||this._hiddenForNotReady){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}},t.on("transformstart.videoOverlayLayer",this._onLayerTransformStart),t.on("transformend.videoOverlayLayer",this._onLayerTransformEnd),t.on("dragstart.videoOverlayLayer",this._onLayerDragStart),t.on("dragend.videoOverlayLayer",this._onLayerDragEnd));}_unbindLayerInteractionEvents(e){let t=e.nodes.layer;typeof t.off=="function"&&(t.off(".videoOverlayLayer"),this._onLayerTransformStart=null,this._onLayerTransformEnd=null,this._onLayerDragStart=null,this._onLayerDragEnd=null);}_bindKonvaDragEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.on!="function"||typeof e.off!="function"||(this._unbindKonvaDragEvents(),this._onKonvaDragStart=()=>{this._rootEl&&(this._hiddenForDrag=true,this._rootEl.style.display="none");},this._onKonvaDragEnd=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForDrag=false,this._rootEl.style.display="block",this._scheduleSync());},e.on("dragstart.videoOverlay",this._onKonvaDragStart),e.on("dragend.videoOverlay",this._onKonvaDragEnd));}_unbindKonvaDragEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.off=="function"&&(e.off(".videoOverlay"),this._onKonvaDragStart=null,this._onKonvaDragEnd=null);}_bindKonvaTransformEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.on!="function"||typeof e.off!="function"||(this._unbindKonvaTransformEvents(),this._onKonvaTransformStart=()=>{this._rootEl&&(this._hiddenForTransform=true,this._rootEl.style.display="none");},this._onKonvaTransformEnd=()=>{this._rootEl&&this._selectedVideoNode&&(this._hiddenForTransform=false,this._rootEl.style.display="block",this._scheduleSync());},e.on("transformstart.videoOverlayTransform",this._onKonvaTransformStart),e.on("transformend.videoOverlayTransform",this._onKonvaTransformEnd));}_unbindKonvaTransformEvents(){if(!this._selectedVideoNode)return;let e=this._selectedVideoNode.getKonvaNode();typeof e.off=="function"&&(e.off(".videoOverlayTransform"),this._onKonvaTransformStart=null,this._onKonvaTransformEnd=null);}_hideTemporarilyForZoom(){this._rootEl&&this._selectedVideoNode&&(this._hiddenForZoom=true,this._rootEl.style.display="none",this._zoomUnhideTimeoutId!=null&&globalThis.clearTimeout(this._zoomUnhideTimeoutId),this._zoomUnhideTimeoutId=globalThis.setTimeout(()=>{this._zoomUnhideTimeoutId=null,this._rootEl&&this._selectedVideoNode&&(this._hiddenForZoom=false,!(this._hiddenForDrag||this._hiddenForTransform||this._hiddenForSize)&&(this._rootEl.style.display="block",this._scheduleSync()));},this._options.hideDuringCameraZoomMs));}_bindVideoEvents(){let e=this._selectedVideoEl;e&&(this._onTimeUpdate=()=>{this._syncControls();},this._onLoadedMetadata=()=>{this._syncControls(),this._maybeShowWhenReady();},this._onCanPlay=()=>{this._syncControls(),this._maybeShowWhenReady();},this._onPlayPauseSync=()=>{this._syncControls();},e.addEventListener("timeupdate",this._onTimeUpdate),e.addEventListener("loadedmetadata",this._onLoadedMetadata),e.addEventListener("canplay",this._onCanPlay),e.addEventListener("play",this._onPlayPauseSync),e.addEventListener("pause",this._onPlayPauseSync));}_unbindVideoEvents(){let e=this._selectedVideoEl;if(!e){this._onTimeUpdate=null,this._onLoadedMetadata=null,this._onPlayPauseSync=null;return}this._onTimeUpdate&&e.removeEventListener("timeupdate",this._onTimeUpdate),this._onLoadedMetadata&&e.removeEventListener("loadedmetadata",this._onLoadedMetadata),this._onCanPlay&&e.removeEventListener("canplay",this._onCanPlay),this._onPlayPauseSync&&(e.removeEventListener("play",this._onPlayPauseSync),e.removeEventListener("pause",this._onPlayPauseSync)),this._onTimeUpdate=null,this._onLoadedMetadata=null,this._onCanPlay=null,this._onPlayPauseSync=null;}_isVideoReady(){let e=this._selectedVideoEl;return !e||!Number.isFinite(e.duration)||e.duration<=0?false:e.readyState>=1}_maybeShowWhenReady(){if(!this._rootEl||!this._selectedVideoNode)return;if(!this._isVideoReady()){this._hiddenForNotReady=true,this._rootEl.style.display="none";return}if(this._hiddenForNotReady){if(this._hiddenForNotReady=false,this._hiddenForDrag||this._hiddenForTransform||this._hiddenForZoom||this._hiddenForSize){this._rootEl.style.display="none";return}this._rootEl.style.display="block",this._scheduleSync();}}_scheduleSync(){this._rafId==null&&(this._rafId=globalThis.requestAnimationFrame(()=>{this._rafId=null,this._syncPosition();}));}_syncPosition(){if(!this._core||!this._rootEl||!this._selectedVideoNode||this._hiddenForDrag||this._hiddenForTransform||this._hiddenForZoom)return;if(!this._isVideoReady()){this._hiddenForNotReady=true,this._rootEl.style.display="none";return}this._hiddenForNotReady&&(this._hiddenForNotReady=false,this._rootEl.style.display="block");let e=this._core.nodes.world.scaleX(),t=this._options.maxWorldScaleToShow;if(t!=null&&e>=t){this._hiddenForWorldScale=true,this._rootEl.style.display="none";return}this._hiddenForWorldScale&&(this._hiddenForWorldScale=false,this._rootEl.style.display="block");let n=this._selectedVideoNode.getKonvaNode(),o=n.getClientRect?n.getClientRect({skipShadow:true,skipStroke:false}):null;if(!o)return;if(o.width<140||o.height<64){this._hiddenForSize=true,this._rootEl.style.display="none";return}let a=e,h=o.width<260||o.height<110||a<.55?"mini":o.width<340||o.height<135||a<.75?"compact":"full";this._applyUiMode(h),this._hiddenForSize&&(this._hiddenForSize=false,this._rootEl.style.display="block");let c=this._core.stage.container(),d=c.clientWidth,u=c.clientHeight;if(this._rootEl.style.left="0px",this._rootEl.style.top="0px",this._rootEl.style.width=String(d)+"px",this._rootEl.style.height=String(u)+"px",this._controlsEl){let _=o.width/360,m=this._uiMode==="full"?.75:this._uiMode==="compact"?.68:.6,b=Math.max(m,Math.min(1,_));this._controlsEl.style.transform="scale("+String(b)+")";let w=Math.max(64,Math.min(240,o.height))/240,x=Math.max(10,Math.min(28,28*w)),N=Math.max(4,Math.min(10,10*w)),k=this._controlsEl.getBoundingClientRect(),C=k.width,S=k.height,T=o.y+o.height+x+N,K=o.y-x-N-S,L=Math.max(0,u-S-this._options.marginPx),R=T;T>L&&K>=0&&(R=K),R=Math.max(this._options.marginPx,Math.min(L,R));let P=o.x+o.width/2,I=Math.max(0,d-C-this._options.marginPx),X=P-C/2;X=Math.max(this._options.marginPx,Math.min(I,X)),this._controlsEl.style.left=String(X)+"px",this._controlsEl.style.top=String(R)+"px",this._controlsEl.style.right="",this._controlsEl.style.bottom="";}let f=typeof n.cornerRadius=="function"?n.cornerRadius():0,p=0;if(Array.isArray(f)){let _=f[0];p=typeof _=="number"&&Number.isFinite(_)?_:0;}else p=typeof f=="number"&&Number.isFinite(f)?f:0;this._rootEl.style.borderRadius=String(Math.max(0,p))+"px";}_syncControls(){let e=this._selectedVideoEl;if(e){if(this._playBtn&&(this._playBtn.textContent=e.paused?"Play":"Pause"),this._muteBtn){let t=e.muted||e.volume<=0;this._muteBtn.textContent=t?"Muted":"Mute",this._muteBtn.style.color=t?this._options.uiMutedTextColor:this._options.uiTextColor;}if(this._seekInput){let t=Number.isFinite(e.duration)&&e.duration>0?e.duration:0,n=t>0?Math.max(0,Math.min(1,e.currentTime/t)):0;this._seekInput.max=String(t),this._seekInput.value=String(t>0?Math.max(0,Math.min(t,e.currentTime)):0),this._updateRangeFill(this._seekInput,n),this._timeLabel&&(this._timeLabel.textContent=this._formatTime(e.currentTime)+" / "+this._formatTime(t));}if(this._volInput&&(this._volInput.value=String(Math.max(0,Math.min(1,e.volume))),this._updateRangeFill(this._volInput,Math.max(0,Math.min(1,e.volume)))),this._speedBtn){let t=e.playbackRate;this._speedBtn.textContent=String(Math.round(t*100)/100)+"x";}}}_formatTime(e){let t=Number.isFinite(e)&&e>0?e:0,n=Math.floor(t),o=Math.floor(n/60),s=n%60,r=s<10?"0"+String(s):String(s);return String(o)+":"+r}_applyUiMode(e){this._controlsEl&&this._uiMode!==e&&(this._uiMode=e,this._timeLabel&&(this._timeLabel.style.display=e==="full"?"inline":"none"),this._volInput&&(this._volInput.style.display=e==="full"||e==="compact"?"block":"none"),this._speedBtn&&(this._speedBtn.style.display=e==="full"?"inline-flex":"none"),this._controlsEl.style.gap=e==="full"?"10px":"8px",this._controlsEl.style.padding=e==="full"?"8px 10px":"6px 8px",this._seekInput&&(this._seekInput.style.minWidth=e==="mini"?"80px":"120px"));}};var we=class{constructor(){l(this,"_scheduled",false);}schedule(i){this._scheduled||(this._scheduled=true,globalThis.requestAnimationFrame(()=>{this._scheduled=false,i();}));}isScheduled(){return this._scheduled}cancel(){this._scheduled=false;}};var ht=class{constructor(i){l(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 Pe(y){if(y instanceof G__default.default.Group){let i=y.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false});return {x:i.x,y:i.y,width:i.width,height:i.height}}if(y instanceof G__default.default.Shape&&typeof y.getSelfRect=="function"){let i=y.getSelfRect();return {x:i.x,y:i.y,width:i.width,height:i.height}}return {x:0,y:0,width:y.width(),height:y.height()}}function Ke(y,i){let{x:e,y:t,width:n,height:o}=i;switch(y){case "top-left":return {x:e+n,y:t+o};case "top-right":return {x:e,y:t+o};case "bottom-right":return {x:e,y:t};case "bottom-left":return {x:e+n,y:t};case "middle-left":return {x:e+n,y:t+o/2};case "middle-right":return {x:e,y:t+o/2};case "top-center":return {x:e+n/2,y:t+o};case "bottom-center":return {x:e+n/2,y:t};default:return null}}function _e(y,i,e,t=6){if(!y||!i||!e)return;let o=e instanceof G__default.default.Group&&typeof e.name=="function"&&e.name().includes("temp-multi-overlay")?e.findOne(".temp-multi-overlay-rect"):null,s=o?o.getClientRect({skipShadow:true,skipStroke:true}):e.getClientRect({skipShadow:true,skipStroke:false}),r=o?o.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}):e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),a=e.getAbsoluteScale(),h=Math.abs(a.x)||1,c=Math.abs(a.y)||1,d=r.width*h,u=r.height*c,f=(()=>{let v=e.getAbsoluteTransform().decompose();return typeof v.rotation=="number"?v.rotation:0})(),p=Math.abs((f%180+180)%180)>.5,g=i.findOne(".top-center"),_=i.findOne(".middle-right"),m=i.findOne(".bottom-center"),b=i.findOne(".middle-left");if(g){let v=p?d:s.width,w=t;g.setAttrs({opacity:0,width:v,height:w,offsetX:v/2,offsetY:0});}if(m){let v=p?d:s.width,w=t;m.setAttrs({opacity:0,width:v,height:w,offsetX:v/2,offsetY:w});}if(b){let v=t,w=p?u:s.height;b.setAttrs({opacity:0,width:v,height:w,offsetX:0,offsetY:w/2});}if(_){let v=t,w=p?u:s.height;_.setAttrs({opacity:0,width:v,height:w,offsetX:v,offsetY:w/2});}}function fe(y){return new G__default.default.Circle({name:y,radius:4,width:25,height:25,fill:"#ffffff",stroke:"#2b83ff",strokeWidth:1.5,opacity:0,hitStrokeWidth:16,draggable:true,dragOnTop:true,listening:true,cursor:"pointer"})}var ut=class{constructor(i){l(this,"core");l(this,"getKonvaNode");l(this,"getTransformer");l(this,"onUpdate");l(this,"setRotateCursor");l(this,"clearRotateCursor");l(this,"onRotateStart");l(this,"onRotateMove");l(this,"onRotateEnd");l(this,"group",null);l(this,"handles",{tl:null,tr:null,br:null,bl:null});l(this,"dragState",null);l(this,"centerAbsStart",null);l(this,"cursorSvgCache",null);this.core=i.core,this.getKonvaNode=i.getNode,this.getTransformer=i.getTransformer,i.onUpdate&&(this.onUpdate=i.onUpdate),i.setRotateCursor&&(this.setRotateCursor=i.setRotateCursor),i.clearRotateCursor&&(this.clearRotateCursor=i.clearRotateCursor),i.onRotateStart&&(this.onRotateStart=i.onRotateStart),i.onRotateMove&&(this.onRotateMove=i.onRotateMove),i.onRotateEnd&&(this.onRotateEnd=i.onRotateEnd);}attach(){if(!this.getKonvaNode())return;let e=this.core.nodes.layer;this.detach();let t=new G__default.default.Group({name:"rotate-handles-group",listening:true});e.add(t),this.group=t;let n=fe("rotate-tl"),o=fe("rotate-tr"),s=fe("rotate-br"),r=fe("rotate-bl");t.add(n),t.add(o),t.add(s),t.add(r),this.handles={tl:n,tr:o,br:s,bl:r};let a=h=>{h.on("mouseenter.rotate",()=>{let c=this.getKonvaNode();if(!c){this.core.stage.container().style.cursor="pointer";return}let d=this.getNodeCenterAbs(c),u=h.getAbsolutePosition(),f=u.x-d.x,p=u.y-d.y,m=Math.atan2(p,f)*180/Math.PI+45;this.setRotateCursor?this.setRotateCursor(m):this.applyRotatedCursor(m);}),h.on("mouseleave.rotate",()=>{this.clearRotateCursor?this.clearRotateCursor():this.core.stage.container().style.cursor="default";}),h.on("dragstart.rotate",()=>{let c=this.getKonvaNode();if(!c)return;let d=c.getAbsoluteTransform().decompose();this.centerAbsStart=this.getNodeCenterAbs(c);let u=this.core.stage.getPointerPosition()??h.getAbsolutePosition(),f=Math.atan2(u.y-this.centerAbsStart.y,u.x-this.centerAbsStart.x)*180/Math.PI;this.dragState={base:d.rotation||0,start:f};let p=f+90;this.setRotateCursor?this.setRotateCursor(p):this.applyRotatedCursor(p),this.getTransformer()?.moveToTop(),this.placeBelowTransformer(),this.onRotateStart&&this.onRotateStart(),c.fire("rotate:start");}),h.on("dragmove.rotate",c=>{let d=this.getKonvaNode();if(!d||!this.dragState)return;let u=this.centerAbsStart??this.getNodeCenterAbs(d),f=this.core.stage.getPointerPosition()??h.getAbsolutePosition(),p=Math.atan2(f.y-u.y,f.x-u.x)*180/Math.PI,g=this.dragState.base+(p-this.dragState.start),_=p+45;this.setRotateCursor?this.setRotateCursor(_):this.applyRotatedCursor(_);let m=this.getTransformer();if(c.evt.shiftKey&&m){let v=k=>{let C=k%360;return C<0&&(C+=360),C},w=(k,C)=>v(k-C+180)-180,x=Array.isArray(m.rotationSnaps())?m.rotationSnaps().map(k=>v(k)):void 0,N=typeof m.rotationSnapTolerance=="function"?m.rotationSnapTolerance():5;if(x?.length){let k=v(g),C=g,S=1/0;for(let T of x){let K=Math.abs(w(k,T));K<S&&K<=N&&(C=T,S=K);}S!==1/0&&(g=C);}}if(d.rotation(g),this.centerAbsStart){let v=this.getNodeCenterAbs(d),w=this.centerAbsStart.x-v.x,x=this.centerAbsStart.y-v.y,N=d.getParent();if(N){let k=N.getAbsoluteTransform().copy().invert(),C=k.point({x:v.x,y:v.y}),S=k.point({x:v.x+w,y:v.y+x}),T=d.x()+(S.x-C.x),K=d.y()+(S.y-C.y);d.position({x:T,y:K});}}let b=this.getTransformer();b?.forceUpdate(),b&&_e(this.core,b,d),this.updatePosition(),this.placeBelowTransformer(),this.core.nodes.layer.batchDraw(),this.onUpdate&&this.onUpdate(),this.onRotateMove&&this.onRotateMove(),d.fire("rotate:move");}),h.on("dragend.rotate",()=>{this.dragState=null,this.centerAbsStart=null,this.core.stage.draggable(false),this.updatePosition(),this.placeBelowTransformer();let c=this.core.stage.container();c.style.cursor="grab",this.onUpdate&&this.onUpdate();let d=this.getKonvaNode();this.onRotateEnd&&this.onRotateEnd(),d&&d.fire("rotate:end");});};a(n),a(o),a(s),a(r),this.updatePosition(),this.placeBelowTransformer();}applyRotatedCursor(i){let e=this.core.stage.container(),t=(i%360+360)%360;if(this.cursorSvgCache?.angle===t){e.style.cursor=this.cursorSvgCache.url;return}let n=`
|
|
4
|
-
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
5
|
-
<g transform="rotate(${t.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(),s=`url("data:image/svg+xml,${encodeURIComponent(n)}") 12 12, grab`;e.style.cursor=s,this.cursorSvgCache={angle:t,url:s};}detach(){this.group&&(this.group.destroy(),this.group=null),this.handles={tl:null,tr:null,br:null,bl:null},this.dragState=null,this.centerAbsStart=null;}moveToTop(){this.placeBelowTransformer();}updatePosition(){let i=this.getKonvaNode();if(!i||!this.group)return;let e=i.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),t=e.width,n=e.height;if(t<=0||n<=0)return;let o=i.getAbsoluteTransform().copy(),s=N=>o.point(N),r=12,a=s({x:e.x+t/2,y:e.y+n/2}),h=s({x:e.x,y:e.y}),c=s({x:e.x+t,y:e.y}),d=s({x:e.x+t,y:e.y+n}),u=s({x:e.x,y:e.y+n}),f=N=>{let k=N.x-a.x,C=N.y-a.y,S=Math.hypot(k,C)||1;return {x:k/S,y:C/S}},p=f(h),g=f(c),_=f(d),m=f(u),b={x:h.x+p.x*r,y:h.y+p.y*r},v={x:c.x+g.x*r,y:c.y+g.y*r},w={x:d.x+_.x*r,y:d.y+_.y*r},x={x:u.x+m.x*r,y:u.y+m.y*r};this.handles.tl&&this.handles.tl.absolutePosition(b),this.handles.tr&&this.handles.tr.absolutePosition(v),this.handles.br&&this.handles.br.absolutePosition(w),this.handles.bl&&this.handles.bl.absolutePosition(x),this.placeBelowTransformer();}placeBelowTransformer(){if(!this.group)return;let i=this.getTransformer(),e=this.core.nodes.layer;if(i?.getLayer()===e){let t=i.zIndex(),n=this.group.zIndex();if(n>=t){let o=n-t+1;for(let s=0;s<o&&this.group.zIndex()>0;s++)this.group.moveDown();}}else this.group.moveToBottom();}getNodeCenterAbs(i){let e=i.getAbsoluteTransform().copy(),t=i.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),n=t.x+t.width/2,o=t.y+t.height/2;return e.point({x:n,y:o})}};var Fe=class{constructor(i){l(this,"core");l(this,"tr",null);l(this,"sizeLabel",null);l(this,"rotateGroup",null);l(this,"rotateCtrl",null);l(this,"keepRatioPredicate",null);l(this,"boundNode",null);l(this,"hitRect",null);l(this,"transformOppositeCorner",null);l(this,"trWasVisibleBeforeDrag",false);l(this,"labelWasVisibleBeforeDrag",false);l(this,"rotateWasVisibleBeforeDrag",false);l(this,"rotateCtrlWasAttachedBeforeDrag",false);this.core=i;}attach(i,e){this.detach(),this.boundNode=i,this.keepRatioPredicate=e?.keepRatioCornerOnlyShift??null;let t=this.core.nodes.layer,n=new G__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.forceUpdate(),n.boundBoxFunc((r,a)=>{let c=Math.max(1,Math.abs(a.width)),d=Math.max(1,Math.abs(a.height));return {...a,width:c,height:d}}),this.tr=n,_e(this.core,n,i),globalThis.queueMicrotask(()=>{!this.tr||!this.boundNode||(this.tr.forceUpdate(),_e(this.core,this.tr,this.boundNode),this.core.nodes.layer.batchDraw());});let o=()=>{let r=typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"",a=r==="top-left"||r==="top-right"||r==="bottom-left"||r==="bottom-right",h=this.keepRatioPredicate?this.keepRatioPredicate():false;n.keepRatio(a&&h);};n.on("transformstart.overlayKeepRatio",()=>{o();let a=(typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"")??"",h=Pe(i),c=Ke(a,h);if(!c){this.transformOppositeCorner=null;return}let d=i.getAbsoluteTransform();this.transformOppositeCorner=d.point({x:c.x,y:c.y});}),n.on("transform.overlayKeepRatio",o);let s=()=>{if(this.boundNode){if(this.transformOppositeCorner){let a=(typeof n.getActiveAnchor=="function"?n.getActiveAnchor():"")??"",h=this.boundNode.getAbsoluteTransform(),c=Pe(this.boundNode),d=Ke(a,c);if(!d)return;let u=h.point({x:d.x,y:d.y}),f=this.transformOppositeCorner.x-u.x,p=this.transformOppositeCorner.y-u.y,g=this.boundNode.getParent();if(g&&(Math.abs(f)>.01||Math.abs(p)>.01)){let _=g.getAbsoluteTransform().copy().invert(),m=this.boundNode.getAbsolutePosition(),b={x:m.x+f,y:m.y+p},v=_.point(b);this.boundNode.position(v);}}this.tr?.forceUpdate(),_e(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),t.batchDraw();}};n.on("transform.overlayFrameTransform",s),n.on("transformend.overlayFrameTransform",()=>{this.transformOppositeCorner=null,s();}),this.ensureSizeLabel(),this.updateSizeLabel(),this.updateHitRect(),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null),this.rotateCtrl=new ut({core:this.core,getNode:()=>this.boundNode,getTransformer:()=>this.tr,onUpdate:()=>{this.forceUpdate(),this.core.nodes.layer.batchDraw();}}),this.rotateCtrl.attach(),this.rotateCtrl.updatePosition(),this.tr.moveToTop(),t.batchDraw();}shiftTransformReferencePoint(i,e){this.transformOppositeCorner&&(this.transformOppositeCorner={x:this.transformOppositeCorner.x+i,y:this.transformOppositeCorner.y+e});}detach(){this.tr&&(this.tr.off(".overlayKeepRatio"),this.tr.off(".overlayFrameTransform"),this.tr.destroy(),this.tr=null),this.transformOppositeCorner=null,this.sizeLabel&&(this.sizeLabel.destroy(),this.sizeLabel=null),this.hitRect&&(this.hitRect.destroy(),this.hitRect=null),this.rotateGroup&&(this.rotateGroup.destroy(),this.rotateGroup=null),this.rotateCtrl&&(this.rotateCtrl.detach(),this.rotateCtrl=null);}forceUpdate(){this.boundNode&&(this.tr?.forceUpdate(),_e(this.core,this.tr,this.boundNode),this.rotateCtrl?.updatePosition(),this.tr?.moveToTop(),this.updateSizeLabel(),this.updateHitRect());}onWorldChanged(){this.forceUpdate();}hideOverlaysForDrag(){this.tr?(this.trWasVisibleBeforeDrag=this.tr.visible(),this.tr.visible(false)):this.trWasVisibleBeforeDrag=false,this.sizeLabel?(this.labelWasVisibleBeforeDrag=this.sizeLabel.visible(),this.sizeLabel.visible(false)):this.labelWasVisibleBeforeDrag=false,this.rotateGroup?(this.rotateWasVisibleBeforeDrag=this.rotateGroup.visible(),this.rotateGroup.visible(false)):this.rotateWasVisibleBeforeDrag=false,this.rotateCtrl?(this.rotateCtrlWasAttachedBeforeDrag=true,this.rotateCtrl.detach()):this.rotateCtrlWasAttachedBeforeDrag=false;}restoreOverlaysAfterDrag(){this.tr&&this.trWasVisibleBeforeDrag&&this.tr.visible(true),this.sizeLabel&&this.labelWasVisibleBeforeDrag&&this.sizeLabel.visible(true),this.rotateGroup&&this.rotateWasVisibleBeforeDrag&&this.rotateGroup.visible(true),this.rotateCtrl&&this.rotateCtrlWasAttachedBeforeDrag&&(this.rotateCtrl.attach(),this.rotateCtrl.updatePosition(),this.tr?.moveToTop()),this.trWasVisibleBeforeDrag=false,this.labelWasVisibleBeforeDrag=false,this.rotateWasVisibleBeforeDrag=false,this.rotateCtrlWasAttachedBeforeDrag=false,this.forceUpdate();}ensureSizeLabel(){let i=this.core.nodes.layer;this.sizeLabel&&this.sizeLabel.destroy();let e=new G__default.default.Label({listening:false,opacity:.95}),t=new G__default.default.Tag({fill:"#2b83ff",cornerRadius:4,lineJoin:"round"}),n=new G__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)),s=Math.max(0,Math.round(n));this.sizeLabel.getText().text(String(o)+" \xD7 "+String(s));let a=8,h=e.x+e.width/2,c=e.y+e.height+a,u=this.sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this.sizeLabel.setAttrs({x:h-u/2,y:c}),this.sizeLabel.moveToTop();}updateHitRect(){if(!this.boundNode)return;let i=this.core.nodes.layer,e=this.boundNode.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),t={x:e.x,y:e.y},n=e.width,o=e.height;if(!this.hitRect){let s=new G__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});s.on("mousedown.overlayHit",r=>{if(r.evt.button!==0)return;r.cancelBubble=true;let a=this.boundNode;typeof a.startDrag=="function"&&a.startDrag();}),this.boundNode instanceof G__default.default.Container?(this.boundNode.add(s),s.moveToBottom(),this.hitRect=s,i.batchDraw()):s.destroy();return}this.hitRect.position(t),this.hitRect.size({width:n,height:o}),this.hitRect.moveToBottom();}};var xe=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_selected",null);l(this,"_prevDraggable",null);l(this,"_transformer",null);l(this,"_transformerWasVisibleBeforeDrag",false);l(this,"_cornerHandlesWereVisibleBeforeDrag",false);l(this,"_sizeLabelWasVisibleBeforeDrag",false);l(this,"_rotateHandlesWereVisibleBeforeDrag",false);l(this,"_cornerHandlesGroup",null);l(this,"_cornerHandles",{tl:null,tr:null,br:null,bl:null});l(this,"_cornerHandlesSuppressed",false);l(this,"_transformOppositeCorner",null);l(this,"_isTransforming",false);l(this,"_sizeLabel",null);l(this,"_radiusLabel",null);l(this,"_rotateHandlesGroup",null);l(this,"_rotateHandles",{tl:null,tr:null,br:null,bl:null});l(this,"_rotateDragState",null);l(this,"_rotateCenterAbsStart",null);l(this,"_prevStageDraggableBeforeRotate",null);l(this,"_worldSyncRafId",null);l(this,"_onCameraZoomEvent",null);l(this,"_onFrameChildrenChangedBound",null);l(this,"_onFrameLabelClickedBound",null);l(this,"_onFrameLabelDragStartBound",null);l(this,"_onFrameLabelDragEndBound",null);l(this,"_hoverTr",null);l(this,"_isPointerDown",false);l(this,"_autoPanRafId",null);l(this,"_autoPanActive",false);l(this,"_autoPanEdgePx");l(this,"_autoPanMaxSpeedPx");l(this,"_draggingNode",null);l(this,"_tempMultiTransformingGroup",null);l(this,"_ratioKeyPressed",false);l(this,"_onGlobalKeyDown",null);l(this,"_onGlobalKeyUp",null);l(this,"_tempMultiSet",new Set);l(this,"_tempMultiNodes",[]);l(this,"_tempMultiInitialTransforms",new Map);l(this,"_tempMultiGroup",null);l(this,"_tempOverlay",null);l(this,"_multiCtrl",null);l(this,"_parentGroupDuringChildEdit",null);l(this,"_parentGroupPrevDraggable",null);l(this,"_dragMoveScheduled",false);l(this,"_batchDrawScheduled",false);l(this,"_hoverThrottle",new ve(16));l(this,"_uiUpdateDebounce",new we);l(this,"_onMouseDown",e=>{if(!this._core||e.evt.button!==0)return;let t=this._core.stage,n=this._core.nodes.layer;if(e.target===t||e.target.getLayer()!==n){let w=false;if(this._selected){let x=t.getPointerPosition();if(x){let N=this._selected.getKonvaNode(),k=N.getClientRect({skipShadow:true,skipStroke:false});if(x.x>=k.x&&x.x<=k.x+k.width&&x.y>=k.y&&x.y<=k.y+k.height&&(w=true,typeof N.startDrag=="function")){let S=N,T=3,K=e.evt.clientX,L=e.evt.clientY,R=typeof S.draggable=="function"?S.draggable():false,P=t.draggable(),I=false,X=J=>{let W=Math.abs(J.evt.clientX-K),$=Math.abs(J.evt.clientY-L);!I&&(W>T||$>T)&&(I=true,this._selected instanceof A||typeof S.draggable=="function"&&!R&&S.draggable(true),N.on("dragstart.selection-once-bbox",()=>{t.draggable(false);}),N.on("dragend.selection-once-bbox",()=>{t.draggable(P),this._selected instanceof A||typeof S.draggable=="function"&&S.draggable(this._options.dragEnabled?true:R),this._selected&&(this._refreshTransformer(),this._core?.nodes.layer.batchDraw()),N.off(".selection-once-bbox");}),N.startDrag(),e.cancelBubble=true);},U=()=>{!I&&this._options.deselectOnEmptyClick&&this._clearSelection(),t.off("mousemove.selection-once-bbox"),t.off("mouseup.selection-once-bbox");};t.on("mousemove.selection-once-bbox",X),t.on("mouseup.selection-once-bbox",U);}}}w||this._options.deselectOnEmptyClick&&this._clearSelection();return}let o=e.target;if(!this._options.selectablePredicate(o)){if(this._selected){let w=t.getPointerPosition();if(w){let x=this._selected.getKonvaNode(),N=x.getClientRect({skipShadow:true,skipStroke:false});if(w.x>=N.x&&w.x<=N.x+N.width&&w.y>=N.y&&w.y<=N.y+N.height&&typeof x.startDrag=="function"){let C=x,S=3,T=e.evt.clientX,K=e.evt.clientY,L=typeof C.draggable=="function"?C.draggable():false,R=t.draggable(),P=false,I=U=>{let J=Math.abs(U.evt.clientX-T),W=Math.abs(U.evt.clientY-K);!P&&(J>S||W>S)&&(P=true,this._selected instanceof A||typeof C.draggable=="function"&&!L&&C.draggable(true),x.on("dragstart.selection-once-bbox2",()=>{t.draggable(false);}),x.on("dragend.selection-once-bbox2",()=>{t.draggable(R),this._selected instanceof A||typeof C.draggable=="function"&&C.draggable(this._options.dragEnabled?true:L),this._selected&&(this._refreshTransformer(),this._core?.nodes.layer.batchDraw()),x.off(".selection-once-bbox2");}),x.startDrag(),e.cancelBubble=true);},X=()=>{!P&&this._options.deselectOnEmptyClick&&this._clearSelection(),t.off("mousemove.selection-once-bbox2"),t.off("mouseup.selection-once-bbox2");};t.on("mousemove.selection-once-bbox2",I),t.on("mouseup.selection-once-bbox2",X);}}}return}let s=this._findBaseNodeByTarget(o);if(!s)return;let r=s,a=this._selected;if(a){let w=a.getKonvaNode();((N,k)=>{let C=k;for(;C;){if(C===N)return true;C=C.getParent();}return false})(w,o)&&(r=a);}let h=r.getKonvaNode();h instanceof G__default.default.Group&&this._disableGroupChildrenDragging(h);let c=3,d=e.evt.clientX,u=e.evt.clientY,f=false,p=w=>{if(f)return;let x=Math.abs(w.evt.clientX-d),N=Math.abs(w.evt.clientY-u);(x>c||N>c)&&(f=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",p),this._core.stage.on("mouseup.selection-once",g),typeof h.isDragging=="function"&&h.isDragging())return;let _=r instanceof A,m=typeof h.draggable=="function"&&!_,b=m?h.draggable():false,v=t.draggable();m&&h.draggable(true),h.on("dragstart.selection-once",()=>{t.draggable(false);}),h.on("dragend.selection-once",()=>{t.draggable(v),m&&(this._options.dragEnabled?h.draggable(true):h.draggable(b)),this._select(r);});});l(this,"_onHoverMoveThrottled",e=>{this._hoverThrottle.shouldExecute()&&this._onHoverMove(e);});l(this,"_onHoverMove",e=>{if(!this._core)return;let t=this._core.stage,n=this._core.nodes.layer,o=e.target;if((()=>{if(!!!this._tempMultiGroup){let v=o;for(;v;){if(v instanceof G__default.default.Group&&typeof v.name=="function"){let w=v.name();if(typeof w=="string"&&(w.includes("temp-multi-group")||w.includes("area-temp-group")))return true}v=v.getParent();}return false}let b=o;for(;b;){if(b===this._tempMultiGroup)return true;b=b.getParent();}return false})()){this._destroyHoverTr();return}let r=typeof e.evt.buttons=="number"?e.evt.buttons:0;if(this._isPointerDown||r&1){this._destroyHoverTr();return}if(o===t||o.getLayer()!==n){this._destroyHoverTr();return}let a=this._core.nodes.list().map(m=>m.getKonvaNode()),h=new Set(a),c=m=>{let b=m;for(;b;){if(h.has(b))return b;b=b.getParent();}return null},u=(m=>{let b=m,v=null;for(;b;)h.has(b)&&b instanceof G__default.default.Group&&(v=b),b=b.getParent();return v})(o),f=c(o),p=e.evt.ctrlKey,g=p?f??u:u??f;{let m=this._core.nodes.list().filter(v=>v instanceof A),b=false;for(let v of m){let w=v.getContentGroup();if(o===w||typeof w.isAncestorOf=="function"&&w.isAncestorOf(o)){b=true;break}}if(b){let v=this._core.nodes.list().filter(S=>!(S instanceof A)).map(S=>S.getKonvaNode()),w=new Set(v),x=S=>{let T=S;for(;T;){if(w.has(T))return T;T=T.getParent();}return null},k=(S=>{let T=S,K=null;for(;T;)w.has(T)&&T instanceof G__default.default.Group&&(K=T),T=T.getParent();return K})(o),C=x(o);g=p?C??k:k??C;}}if(!p&&this._selected&&f&&!(this._selected.getKonvaNode()instanceof G__default.default.Group)){let m=this._selected.getKonvaNode();u&&((v,w,x)=>{if(!x)return false;let N=(k,C)=>{let S=C;for(;S;){if(S===k)return true;S=S.getParent();}return false};return N(x,v)&&N(x,w)})(m,f,u)&&m!==f&&(g=f);}if(!g){this._destroyHoverTr();return}if(!this._options.selectablePredicate(g)){this._destroyHoverTr();return}if(this._selected){let m=this._selected.getKonvaNode();if(p?g===m:g===m||((w,x)=>{let N=x;for(;N;){if(N===w)return true;N=N.getParent();}return false})(m,g)){this._destroyHoverTr();return}}let _=this._ensureHoverTr();_.nodes([g]),_.visible(true),_.moveToTop(),n.batchDraw();});l(this,"_onHoverDown",()=>{this._isPointerDown=true,this._destroyHoverTr();});l(this,"_onHoverUp",()=>{this._isPointerDown=false;});l(this,"_onHoverLeave",e=>{this._destroyHoverTr();});l(this,"_onNodeRemoved",e=>{this._selected&&this._selected===e&&this._clearSelection();});let{dragEnabled:t=true,enableTransformer:n=true,deselectOnEmptyClick:o=true,selectablePredicate:s}=e,r=s??(()=>true);if(this._options={dragEnabled:t,enableTransformer:n,deselectOnEmptyClick:o,selectablePredicate:a=>r(a)?this._isSelectableByFrameRules(a):false,autoPanEnabled:e.autoPanEnabled??true,autoPanEdgePx:e.autoPanEdgePx??40,autoPanMaxSpeedPx:e.autoPanMaxSpeedPx??24,enableVideoOverlay:e.enableVideoOverlay??false},e.enableVideoOverlay){let a=typeof e.enableVideoOverlay=="object"?e.enableVideoOverlay:{};this.addons.add(new He(a));}this._autoPanEdgePx=this._options.autoPanEdgePx,this._autoPanMaxSpeedPx=this._options.autoPanMaxSpeedPx;}getSelected(){return this._selected}getMultiGroupController(){if(!this._core)throw new Error("Core is not attached");return this._multiCtrl??(this._multiCtrl=new ht({ensureTempMulti:e=>{this._ensureTempMulti(e);},destroyTempMulti:()=>{this._destroyTempMulti();},commitTempMultiToGroup:()=>{this._commitTempMultiToGroup();},isActive:()=>!!this._tempMultiGroup||this._tempMultiSet.size>0,forceUpdate:()=>{this._tempOverlay?.forceUpdate();},onWorldChanged:()=>{this._tempOverlay?.onWorldChanged();},isInsideTempByTarget:e=>this._tempMultiGroup?e===this._tempMultiGroup?true:e.isAncestorOf(this._tempMultiGroup)||this._tempMultiGroup.isAncestorOf(e):false})),this._multiCtrl}_startAutoPanLoop(){if(!this._core||this._autoPanRafId!=null)return;this._autoPanActive=true;let e=this._core.nodes.world,t=this._core.stage,n=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let o=t.getPointerPosition();if(o){let s=t.width(),r=t.height(),a=this._autoPanEdgePx,h=0,c=0,d=Math.max(0,a-o.x),u=Math.max(0,o.x-(s-a)),f=Math.max(0,a-o.y),p=Math.max(0,o.y-(r-a)),g=_=>Math.min(1,_/a);if(h=this._autoPanMaxSpeedPx*(g(u)-g(d)),c=this._autoPanMaxSpeedPx*(g(p)-g(f)),h!==0||c!==0){e.x(e.x()-h),e.y(e.y()-c);let _=e.position();if(this._core.eventBus.emit("camera:pan",{dx:-h,dy:-c,position:{x:_.x,y:_.y}}),this._isTransforming&&this._transformOppositeCorner&&(this._transformOppositeCorner={x:this._transformOppositeCorner.x-h,y:this._transformOppositeCorner.y-c}),this._tempMultiTransformingGroup&&this._tempOverlay&&this._tempOverlay.shiftTransformReferencePoint(-h,-c),this._draggingNode&&typeof this._draggingNode.setAbsolutePosition=="function"){let m=this._draggingNode.getAbsolutePosition();this._draggingNode.setAbsolutePosition({x:m.x+h,y:m.y+c}),this._transformer?.forceUpdate();}if(this._isTransforming){let m=t.getPointerPosition();if(m){let b=t.container(),v=b.getBoundingClientRect();try{b.dispatchEvent(new MouseEvent("mousemove",{bubbles:!0,cancelable:!0,clientX:v.left+m.x,clientY:v.top+m.y}));}catch{}}}if(this._tempMultiTransformingGroup){let m=t.getPointerPosition();if(m){let b=t.container(),v=b.getBoundingClientRect();try{b.dispatchEvent(new MouseEvent("mousemove",{bubbles:!0,cancelable:!0,clientX:v.left+m.x,clientY:v.top+m.y}));}catch{}}}this._core.nodes.layer.batchDraw();}}this._autoPanRafId=globalThis.requestAnimationFrame(n);};this._autoPanRafId=globalThis.requestAnimationFrame(n);}_stopAutoPanLoop(){this._autoPanActive=false,this._autoPanRafId!=null&&(globalThis.cancelAnimationFrame(this._autoPanRafId),this._autoPanRafId=null);}_scheduleBatchDraw(){if(this._batchDrawScheduled)return;this._batchDrawScheduled=true;let e=globalThis.requestAnimationFrame;e(()=>{this._batchDrawScheduled=false,this._core?.stage.batchDraw();});}setOptions(e){this._options={...this._options,...e},this._core&&this._refreshTransformer(),typeof e.autoPanEdgePx=="number"&&(this._autoPanEdgePx=e.autoPanEdgePx),typeof e.autoPanMaxSpeedPx=="number"&&(this._autoPanMaxSpeedPx=e.autoPanMaxSpeedPx),e.autoPanEnabled===false&&this._stopAutoPanLoop();}selectSingleFromArea(e){this._destroyTempMulti(),this._select(e),this._scheduleBatchDraw();}clearSelectionFromAreaLasso(){this._destroyTempMulti(),this._clearSelection();}onAttach(e){this._core=e;let t=e.stage;t.on("mousedown.selection",this._onMouseDown),t.on("click.selection",r=>{if(!this._core)return;let a=this._core.stage,h=this._core.nodes.layer;if(!!a.getAttr("_skipSelectionEmptyClickOnce")){a.setAttr("_skipSelectionEmptyClickOnce",false),r.cancelBubble=true;return}if(r.evt.button!==0)return;if(r.target===a||r.target.getLayer()!==h){this._options.deselectOnEmptyClick&&(this._destroyTempMulti(),this._clearSelection());return}let d=r.target;if(!this._options.selectablePredicate(d)){this._options.deselectOnEmptyClick&&(this._destroyTempMulti(),this._clearSelection());return}if(r.evt.shiftKey||r.evt.ctrlKey||r.evt.metaKey){let f=this._findBaseNodeByTarget(d);if(!f)return;let g=f.getKonvaNode().getParent();if(g&&g instanceof G__default.default.Group){let _=this._core.nodes.world;if(g!==_&&!this._core.nodes.list().filter(v=>v instanceof A).some(v=>v.getContentGroup()===g))return}if(this._tempMultiSet.size===0&&this._selected&&this._selected!==f&&(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(f)?this._tempMultiSet.delete(f):this._tempMultiSet.add(f),this._tempMultiSet.size===0){this._destroyTempMulti(),this._clearSelection();return}if(this._tempMultiSet.size===1){let m=this._tempMultiSet.values().next(),b=m.done?void 0:m.value;b&&(this._destroyTempMulti(),this._select(b),this._scheduleBatchDraw());return}this._ensureTempMulti(Array.from(this._tempMultiSet)),this._scheduleBatchDraw();return}let u=this._findBaseNodeByTarget(d);u&&(this._destroyTempMulti(),this._select(u),this._scheduleBatchDraw());}),t.on("dblclick.selection",r=>{if(!this._core)return;let a=this._core.nodes.layer;if(r.target===t||r.target.getLayer()!==a||r.evt.button!==0||!this._selected)return;let h=this._selected.getKonvaNode();if(h instanceof G__default.default.Group&&typeof h.isAncestorOf=="function"&&h.isAncestorOf(r.target)){r.cancelBubble=true;let c=null;for(let d of this._core.nodes.list()){let u=d.getKonvaNode();if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(u)&&u!==h&&typeof u.isAncestorOf=="function"&&u.isAncestorOf(r.target)){let f=true;for(let p of this._core.nodes.list()){if(p===d)continue;let g=p.getKonvaNode();if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(g)&&typeof u.isAncestorOf=="function"&&u.isAncestorOf(g)&&typeof g.isAncestorOf=="function"&&g.isAncestorOf(r.target)){f=false;break}}if(f){c=d;break}}}if(c??(c=this._core.nodes.list().find(d=>d.getKonvaNode()===r.target)??null),c){this._select(c);let d=c.getKonvaNode();c instanceof A||typeof d.draggable=="function"&&d.draggable(true),h instanceof G__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",r=>{if(!this._options.autoPanEnabled)return;let a=r.target,h=a.getParent(),c=p=>p&&typeof p.name=="function"&&p.name()||"",d=c(a),u=c(h);if(d.startsWith("rotate-")||u==="rotate-handles-group")return;let f=a;if(this._selected instanceof A){let p=t.getPointerPosition();if(p){let g=this._selected.getKonvaNode(),_=g.getClientRect({skipShadow:true,skipStroke:false});p.x>=_.x&&p.x<=_.x+_.width&&p.y>=_.y&&p.y<=_.y+_.height&&(f=g);}}this._draggingNode=f,this._startAutoPanLoop();}),n.on("dragend.selectionAutoPan",()=>{this._draggingNode=null,this._stopAutoPanLoop();});let o=this._core.nodes.world,s=()=>{this._core&&this._worldSyncRafId==null&&(this._worldSyncRafId=globalThis.requestAnimationFrame(()=>{this._worldSyncRafId=null,this._core&&((this._transformer||this._cornerHandlesGroup||this._rotateHandlesGroup||this._sizeLabel||this._tempMultiGroup)&&(this._transformer?.forceUpdate(),this._hoverTr?.forceUpdate(),this._restyleSideAnchors(),this._updateCornerRadiusHandlesPosition(),this._updateRotateHandlesPosition(),this._updateSizeLabel(),this._updateCornerRadiusHandlesVisibility(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw()),this._destroyHoverTr());}));};o.on("xChange.selectionCamera yChange.selectionCamera scaleXChange.selectionCamera scaleYChange.selectionCamera",s),this._onCameraZoomEvent=()=>{s();},e.eventBus.on("camera:zoom",this._onCameraZoomEvent),e.eventBus.on("camera:setZoom",this._onCameraZoomEvent),e.eventBus.on("camera:reset",this._onCameraZoomEvent),this._onFrameChildrenChangedBound=(r,a)=>{let h=r,c=!!a;if(!this._selected||this._selected!==h)return;let d=this._selected.getKonvaNode();typeof d.draggable=="function"&&(this._prevDraggable=d.draggable()),c&&this._clearSelection();},e.eventBus.on("frame:children-changed",this._onFrameChildrenChangedBound),this._onFrameLabelClickedBound=r=>{let a=r;this._destroyTempMulti(),this._select(a),this._scheduleBatchDraw();},e.eventBus.on("frame:label-clicked",this._onFrameLabelClickedBound),this._onFrameLabelDragStartBound=()=>{this._core&&(this._transformer&&this._transformer.visible(false),this._cornerHandlesGroup&&this._cornerHandlesGroup.visible(false),this._rotateHandlesGroup&&this._rotateHandlesGroup.visible(false),this._sizeLabel&&this._sizeLabel.visible(false),this._hoverTr&&this._hoverTr.visible(false),this._tempOverlay?.hideOverlaysForDrag(),this._core.stage.batchDraw());},this._onFrameLabelDragEndBound=()=>{this._core&&(this._selected&&this._refreshTransformer(),this._tempOverlay?.restoreOverlaysAfterDrag(),this._core.stage.batchDraw());},e.eventBus.on("frame:label-dragstart",this._onFrameLabelDragStartBound),e.eventBus.on("frame:label-dragend",this._onFrameLabelDragEndBound),this._onGlobalKeyDown=r=>{r.key==="Shift"&&(this._ratioKeyPressed=true);let a=r.ctrlKey||r.metaKey;a&&!r.shiftKey&&r.code==="KeyG"&&(r.preventDefault(),this._commitTempMultiToGroup()),a&&r.shiftKey&&r.code==="KeyG"&&(r.preventDefault(),this._tryUngroupSelectedGroup());},this._onGlobalKeyUp=r=>{r.key==="Shift"&&(this._ratioKeyPressed=false);},globalThis.addEventListener("keydown",this._onGlobalKeyDown),globalThis.addEventListener("keyup",this._onGlobalKeyUp);}onDetach(e){this._destroyTempMulti(),this._clearSelection(),e.stage.off(".selection"),e.stage.off(".hover"),this._core?.nodes.layer.off(".hover"),this._core?.nodes.world.off(".selectionCamera"),this._core?.nodes.layer.off(".selectionAutoPan"),this._worldSyncRafId!=null&&(globalThis.cancelAnimationFrame(this._worldSyncRafId),this._worldSyncRafId=null),this._onCameraZoomEvent&&(e.eventBus.off("camera:zoom",this._onCameraZoomEvent),e.eventBus.off("camera:setZoom",this._onCameraZoomEvent),e.eventBus.off("camera:reset",this._onCameraZoomEvent),this._onCameraZoomEvent=null),this._onFrameChildrenChangedBound&&(e.eventBus.off("frame:children-changed",this._onFrameChildrenChangedBound),this._onFrameChildrenChangedBound=null),this._onFrameLabelClickedBound&&(e.eventBus.off("frame:label-clicked",this._onFrameLabelClickedBound),this._onFrameLabelClickedBound=null),this._onFrameLabelDragStartBound&&(e.eventBus.off("frame:label-dragstart",this._onFrameLabelDragStartBound),this._onFrameLabelDragStartBound=null),this._onFrameLabelDragEndBound&&(e.eventBus.off("frame:label-dragend",this._onFrameLabelDragEndBound),this._onFrameLabelDragEndBound=null),e.eventBus.off("node:removed",this._onNodeRemoved),this._destroyHoverTr(),this._onGlobalKeyDown&&globalThis.removeEventListener("keydown",this._onGlobalKeyDown),this._onGlobalKeyUp&&globalThis.removeEventListener("keyup",this._onGlobalKeyUp),this._onGlobalKeyDown=null,this._onGlobalKeyUp=null;}_select(e){if(!this._core)return;let t=this._core;this._clearSelection();let n=e.getKonvaNode();this._prevDraggable=n.draggable(),this._options.dragEnabled&&typeof n.draggable=="function"&&n.draggable(true),n instanceof G__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 s=o.evt.button;(s===1||s===2)&&typeof n.draggable=="function"&&n.draggable(false);});}_clearSelection(){if(!this._selected)return;let e=this._selected,t=this._selected.getKonvaNode();if(typeof t.draggable=="function"&&this._prevDraggable!==null&&t.draggable(this._prevDraggable),this._prevDraggable=null,this._parentGroupDuringChildEdit){let n=this._parentGroupDuringChildEdit;typeof n.draggable=="function"&&this._parentGroupPrevDraggable!==null&&n.draggable(this._parentGroupPrevDraggable),this._parentGroupDuringChildEdit=null,this._parentGroupPrevDraggable=null;}t.off(".selection"),t.off(".selection-once"),this._destroyCornerRadiusHandles(),this._destroyRotateHandles(),this._destroySizeLabel(),this._transformer&&(this._transformer.destroy(),this._transformer=null),this._selected=null,this._core&&(this._core.eventBus.emit("node:deselected",e),this._core.eventBus.emit("selection:cleared")),this._core?.stage.batchDraw();}_applyOverlayTransformToNodes(e,t){if(!this._core)return;let o=this._core.nodes.world.getAbsoluteTransform().copy(),r=o.copy().invert().multiply(e.getAbsoluteTransform().copy()),a=t.copy();a.invert();let h=r.multiply(a);for(let c of this._tempMultiNodes){let d=this._tempMultiInitialTransforms.get(c);if(!d)continue;let u=h.copy().multiply(d),f=o.copy().multiply(u),p=c.getParent();if(!p)continue;let g=p.getAbsoluteTransform().copy();g.invert();let m=g.multiply(f).decompose();typeof c.position=="function"&&c.position({x:m.x,y:m.y}),typeof c.rotation=="function"&&c.rotation(m.rotation),typeof c.scale=="function"&&c.scale({x:m.scaleX,y:m.scaleY});}}_updateTempMultiOverlayBBox(){if(!this._core||!this._tempMultiGroup)return;let e=this._computeUnionBBox(Array.from(this._tempMultiSet));if(!e)return;this._tempMultiGroup.position({x:e.x,y:e.y});let t=this._tempMultiGroup.findOne(".temp-multi-overlay-rect");t&&t.size({width:e.width,height:e.height});}_computeUnionBBox(e){if(e.length===0||!this._core)return null;let t=this._core.nodes.world,n=1/0,o=1/0,s=-1/0,r=-1/0;for(let a of e){let c=a.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false}),d=t.getAbsoluteTransform().copy().invert(),u=[d.point({x:c.x,y:c.y}),d.point({x:c.x+c.width,y:c.y}),d.point({x:c.x+c.width,y:c.y+c.height}),d.point({x:c.x,y:c.y+c.height})];for(let f of u)n=Math.min(n,f.x),o=Math.min(o,f.y),s=Math.max(s,f.x),r=Math.max(r,f.y);}return !isFinite(n)||!isFinite(o)||!isFinite(s)||!isFinite(r)?null:{x:n,y:o,width:s-n,height:r-o}}_ensureTempMulti(e){if(!this._core)return;let t=this._core.nodes.world,n=this._core.nodes.layer;this._tempMultiSet.clear();for(let u of e)this._tempMultiSet.add(u);let o=e.map(u=>u.getKonvaNode());if(this._tempMultiGroup&&this._tempMultiNodes.length>0){if(this._tempMultiNodes.length===o.length&&o.every(f=>this._tempMultiNodes.includes(f)))return;this._destroyTempMultiOverlayOnly(),this._tempMultiSet.clear();for(let f of e)this._tempMultiSet.add(f);}let s=this._computeUnionBBox(e);if(!s)return;this._tempMultiNodes=o;let r=new G__default.default.Group({name:"temp-multi-overlay",x:s.x,y:s.y});t.add(r),this._tempMultiGroup=r;let a=new G__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(a),this._tempOverlay??(this._tempOverlay=new Fe(this._core)),this._tempOverlay.attach(r,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed}),this._tempOverlay.forceUpdate();let h=this._core.stage,c=h.draggable();r.draggable(true);let d=null;r.on("dragstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let u=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiNodes)if(u){let p=u.copy().multiply(f.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(f,p);}else this._tempMultiInitialTransforms.set(f,f.getAbsoluteTransform().copy());d=u?u.copy().multiply(r.getAbsoluteTransform().copy()):r.getAbsoluteTransform().copy(),h.draggable(false),this._draggingNode=r,this._tempMultiTransformingGroup=r,this._startAutoPanLoop(),this._tempOverlay?.hideOverlaysForDrag();}),r.on("dragmove.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(r,d),this._autogroupTempMultiInFrames(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("rotate:start.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let u=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiNodes)if(u){let p=u.copy().multiply(f.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(f,p);}else this._tempMultiInitialTransforms.set(f,f.getAbsoluteTransform().copy());d=u?u.copy().multiply(r.getAbsoluteTransform().copy()):r.getAbsoluteTransform().copy();}),r.on("rotate:move.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(r,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("rotate:end.tempMulti",()=>{r.fire("transformend.tempMulti");}),r.on("dragend.tempMulti",()=>{if(h.draggable(c),this._draggingNode=null,this._stopAutoPanLoop(),this._tempMultiTransformingGroup=null,this._tempOverlay?.restoreOverlaysAfterDrag(),r.scale({x:1,y:1}),r.rotation(0),r.skew({x:0,y:0}),this._core){let f=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let p of this._tempMultiSet){let _=p.getKonvaNode().getAbsoluteTransform().copy(),b=f.copy().multiply(_).decompose();this._core.eventBus.emit("node:transformed",p,{x:b.x,y:b.y,rotation:b.rotation,scaleX:b.scaleX,scaleY:b.scaleY});}this._autogroupTempMultiInFrames();}this._updateTempMultiOverlayBBox(),this._tempMultiInitialTransforms.clear(),this._tempMultiTransformingGroup=null,this._stopAutoPanLoop(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),r.on("transformstart.tempMulti",()=>{this._tempMultiInitialTransforms.clear();let u=this._core?.nodes.world.getAbsoluteTransform().copy().invert();for(let f of this._tempMultiNodes)if(u){let p=u.copy().multiply(f.getAbsoluteTransform().copy());this._tempMultiInitialTransforms.set(f,p);}else this._tempMultiInitialTransforms.set(f,f.getAbsoluteTransform().copy());d=u?u.copy().multiply(r.getAbsoluteTransform().copy()):r.getAbsoluteTransform().copy(),this._tempMultiTransformingGroup=r,this._startAutoPanLoop();}),r.on("transform.tempMulti",()=>{d&&(this._applyOverlayTransformToNodes(r,d),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw());}),r.on("transformend.tempMulti",()=>{if(this._core){let p=this._core.nodes.world.getAbsoluteTransform().copy().invert();for(let g of this._tempMultiSet){let m=g.getKonvaNode().getAbsoluteTransform().copy(),v=p.copy().multiply(m).decompose();this._core.eventBus.emit("node:transformed",g,{x:v.x,y:v.y,rotation:v.rotation,scaleX:v.scaleX,scaleY:v.scaleY});}}let u=this._tempOverlay;u?.detach(),globalThis.requestAnimationFrame(()=>{if(!this._core||!this._tempMultiGroup||this._tempMultiGroup!==r)return;r.scale({x:1,y:1}),r.rotation(0),r.skew({x:0,y:0}),this._updateTempMultiOverlayBBox();let f=u??this._tempOverlay??(this._tempOverlay=new Fe(this._core));f.attach(r,{keepRatioCornerOnlyShift:()=>this._ratioKeyPressed}),f.forceUpdate(),this._scheduleBatchDraw();}),d=null,this._tempMultiInitialTransforms.clear(),this._tempMultiTransformingGroup=null,this._stopAutoPanLoop(),this._tempOverlay?.forceUpdate(),this._scheduleBatchDraw();}),n.batchDraw(),this._core.eventBus.emit("selection:multi:created",e);}_destroyTempMultiOverlayOnly(){this._core&&this._tempMultiGroup&&(this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null,this._tempMultiNodes=[],this._tempMultiInitialTransforms.clear(),this._core.nodes.layer.batchDraw(),this._core.eventBus.emit("selection:multi:destroyed"));}_destroyTempMulti(){this._core&&(!this._tempMultiGroup&&this._tempMultiSet.size===0||(this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup&&(this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null),this._tempMultiNodes=[],this._tempMultiInitialTransforms.clear(),this._tempMultiSet.clear(),this._core.nodes.layer.batchDraw(),this._core.eventBus.emit("selection:multi:destroyed")));}_autogroupTempMultiInFrames(){if(!this._core||this._tempMultiSet.size===0)return;let e=this._core.nodes,t=e.world,n=this._core.stage,o=e.list().filter(s=>s instanceof A);if(o.length!==0)for(let s of this._tempMultiSet){if(s instanceof A)continue;let r=s.getKonvaNode(),a=r.getParent();if(!a)continue;let h=null;e:for(let u of o){let f=a,p=u.getContentGroup();for(;f&&f!==t;){if(f===p){h=u;break e}f=f.getParent();}}let c=null,d=n.getPointerPosition();if(d){for(let u of o){let p=u.getRect().getClientRect({skipShadow:true,skipStroke:true});if(d.x>=p.x&&d.x<=p.x+p.width&&d.y>=p.y&&d.y<=p.y+p.height){c=u;break}}if(h){if(!c||c!==h){let u=r.getAbsolutePosition();t.add(r),r.setAbsolutePosition(u);let p=h.getContentGroup().getChildren().length>0,g=h.getKonvaNode();typeof g.draggable=="function"&&g.draggable(!p);}continue}if(c&&a!==c.getContentGroup()){let u=r.getAbsolutePosition(),f=c.getContentGroup();f.add(r),r.setAbsolutePosition(u);let p=f.getChildren().length>0,g=c.getKonvaNode();typeof g.draggable=="function"&&g.draggable(!p);}}}}_commitTempMultiToGroup(){if(!this._core||!this._tempMultiGroup||this._tempMultiSet.size<2)return;let e=Array.from(this._tempMultiSet),t=e.some(m=>m instanceof A),n=e.some(m=>!(m instanceof A));if(t){n?globalThis.console.warn("[SelectionPlugin] Grouping FrameNode with other nodes is not allowed. Operation is ignored."):globalThis.console.warn("[SelectionPlugin] Grouping FrameNode instances into a permanent group is not allowed. Operation is ignored.");return}let o=this._core.nodes,s=o.world,r=this._computeUnionBBox(e);if(!r)return;let a=o.list().filter(m=>m instanceof A),h=null;e:for(let m of e){let b=m.getKonvaNode(),v=null,w=b.getParent();for(;w&&w!==s;){for(let x of a){let N=x.getContentGroup();if(w===N){v=x;break}}if(v)break;w=w.getParent();}if(!v){h=null;break e}if(!h)h=v;else if(h!==v){h=null;break e}}let c=o.addGroup({x:r.x,y:r.y,draggable:true}),d=c.getKonvaNode();if(h){let m=d.getAbsolutePosition();h.getContentGroup().add(d),d.setAbsolutePosition(m);}let u=[],f=[...this._tempMultiNodes].sort((m,b)=>m.zIndex()-b.zIndex()),p=Math.max(...f.map(m=>m.zIndex()));for(let m of f){let b=m.getAbsolutePosition();d.add(m),m.setAbsolutePosition(b),typeof m.draggable=="function"&&m.draggable(false);let v=this._core.nodes.list().find(w=>w.getKonvaNode()===m);v&&u.push(v);}let g=d.zIndex(),_=p;if(g<_){let m=_-g;for(let b=0;b<m&&d.zIndex()<s.children.length-1;b++)d.moveUp();}this._tempOverlay&&(this._tempOverlay.detach(),this._tempOverlay=null),this._tempMultiGroup.off(".tempMulti"),this._tempMultiGroup.destroy(),this._tempMultiGroup=null,this._tempMultiNodes=[],this._tempMultiSet.clear(),typeof d.draggable=="function"&&d.draggable(true),this._core.eventBus.emit("group:created",c,u),this._select(c),this._core.stage.batchDraw();}_tryUngroupSelectedGroup(){if(!this._core||!this._selected)return;let e=this._selected.getKonvaNode();if(!(e instanceof G__default.default.Group))return;let t=[...e.getChildren()],n=this._core.nodes.world,s=this._core.nodes.list().filter(c=>c instanceof A),r=null;if(s.length>0)e:for(let c of s){let d=c.getContentGroup(),u=e.getParent();for(;u&&u!==n;){if(u===d){r=c;break e}u=u.getParent();}}let a=[];for(let c of t){let d=c.getAbsoluteTransform().copy(),u=r?r.getContentGroup():n;u.add(c);let f=u.getAbsoluteTransform().copy();f.invert();let g=f.multiply(d).decompose();typeof c.position=="function"?c.position({x:g.x,y:g.y}):c.setAbsolutePosition({x:g.x,y:g.y}),typeof c.rotation=="function"&&c.rotation(g.rotation),typeof c.scale=="function"&&c.scale({x:g.scaleX,y:g.scaleY});let _=false;for(let m of this._core.nodes.list())if(m.getKonvaNode()===c){m instanceof A&&(_=true),a.push(m);break}!_&&typeof c.draggable=="function"&&c.draggable(true);}let h=this._selected;this._selected=null,this._transformer?.destroy(),this._transformer=null,this._destroySizeLabel(),this._core.eventBus.emit("group:ungrouped",h,a),this._core.nodes.remove(h),this._core.stage.batchDraw();}_ensureHoverTr(){if(!this._core)throw new Error("Core is not attached");if(this._hoverTr?.getParent())return this._hoverTr;let e=new G__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);}_isSelectableByFrameRules(e){let t=this._findBaseNodeByTarget(e);return t&&t instanceof A?!(t.getContentGroup().getChildren().length>0):true}_refreshTransformer(){if(!this._core||(this._transformer&&(this._transformer.destroy(),this._transformer=null),!this._options.enableTransformer||!this._selected))return;let e=this._core.nodes.layer,t=new G__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,a)=>{let c=a.width,d=a.height,u=a.x,f=a.y;return (c<0||c<1)&&(c=1),(d<0||d<1)&&(d=1),{...a,x:u,y:f,width:c,height:d}}),this._transformer=t,this._restyleSideAnchors(),this._setupCornerRadiusHandles(false),this._setupRotateHandles(),this._setupSizeLabel();let n=()=>{let r=typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"",a=r==="top-left"||r==="top-right"||r==="bottom-left"||r==="bottom-right";t.keepRatio(a&&this._ratioKeyPressed);};t.on("transformstart.keepratio",()=>{n(),this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel(),this._isTransforming=true,this._startAutoPanLoop();let r=this._selected?.getKonvaNode(),h=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"";if(!r){this._transformOppositeCorner=null,this._isTransforming=false;return}let c=Pe(r),d=Ke(h,c);if(!d){this._transformOppositeCorner=null,this._isTransforming=false;return}let u=r.getAbsoluteTransform();this._transformOppositeCorner=u.point({x:d.x,y:d.y});}),t.on("transform.keepratio",n),t.on("transform.corner-sync",()=>{let r=this._selected,a=r?.getKonvaNode();if(a){if(r instanceof A){let h=r,c=Math.abs(a.scaleX?.()??1),d=Math.abs(a.scaleY?.()??1),u=h.getRect(),f=u.width(),p=u.height(),g=f*c,_=p*d;h.resize(g,_),typeof a.scaleX=="function"&&a.scaleX(1),typeof a.scaleY=="function"&&a.scaleY(1);}else this._bakeRectScale(a);if(this._transformOppositeCorner){let c=(typeof t.getActiveAnchor=="function"?t.getActiveAnchor():"")??"",d=a.getAbsoluteTransform(),u=Pe(a),f=Ke(c,u);if(!f)return;let p=d.point({x:f.x,y:f.y}),g=this._transformOppositeCorner.x-p.x,_=this._transformOppositeCorner.y-p.y,m=a.getParent();if(m&&(Math.abs(g)>.01||Math.abs(_)>.01)){let b=m.getAbsoluteTransform().copy().invert(),v=a.getAbsolutePosition(),w={x:v.x+g,y:v.y+_},x=b.point(w);a.position(x);}}}this._restyleSideAnchors(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();}),t.on("transformend.corner-sync",()=>{this._cornerHandlesSuppressed=false,this._transformOppositeCorner=null,this._isTransforming=false,this._restyleSideAnchors(),this._stopAutoPanLoop(),this._scheduleUIUpdate(),this._core?.nodes.layer.batchDraw();});let o=this._selected.getKonvaNode();o.off(".overlay-sync");let s=()=>{this._restyleSideAnchors(),this._scheduleUIUpdate(),this._scheduleBatchDraw();};o.on("widthChange.overlay-sync heightChange.overlay-sync scaleXChange.overlay-sync scaleYChange.overlay-sync rotationChange.overlay-sync xChange.overlay-sync yChange.overlay-sync",s),globalThis.queueMicrotask(()=>{this._core&&this._selected&&this._transformer===t&&(this._transformer.forceUpdate(),this._restyleSideAnchors(),this._scheduleBatchDraw());}),this._scheduleBatchDraw();}_restyleSideAnchors(){if(!this._core||!this._selected||!this._transformer)return;let e=this._selected.getKonvaNode();_e(this._core,this._transformer,e);}_setupRotateHandles(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroyRotateHandles();let t=new G__default.default.Group({name:"rotate-handles-group",listening:true});e.add(t),this._rotateHandlesGroup=t;let n=fe("rotate-tl"),o=fe("rotate-tr"),s=fe("rotate-br"),r=fe("rotate-bl");t.add(n),t.add(o),t.add(s),t.add(r),this._rotateHandles={tl:n,tr:o,br:s,bl:r};let a=d=>{d.on("dragstart.rotate",()=>{if(!this._selected)return;let u=this._selected.getKonvaNode(),f=u.getAbsoluteTransform().decompose(),p=this._getNodeCenterAbs(u);this._rotateCenterAbsStart=p;let g=this._core?.stage.getPointerPosition()??d.getAbsolutePosition(),_=Math.atan2(g.y-p.y,g.x-p.x)*180/Math.PI;this._rotateDragState={base:f.rotation||0,start:_},this._core&&(this._prevStageDraggableBeforeRotate=this._core.stage.draggable()),typeof u.draggable=="function"&&u.draggable(false),this._core?.stage.draggable(false);let m=_+90;this._applyRotatedCursor(m);}),d.on("dragmove.rotate",u=>{if(!this._core||!this._selected||!this._rotateDragState)return;let f=this._selected.getKonvaNode(),p=this._rotateCenterAbsStart??this._getNodeCenterAbs(f),g=this._core.stage.getPointerPosition()??d.getAbsolutePosition(),_=Math.atan2(g.y-p.y,g.x-p.x)*180/Math.PI,m=this._rotateDragState.base+(_-this._rotateDragState.start),b=_+45;this._applyRotatedCursor(b);let v=x=>{let N=x%360;return N<0&&(N+=360),N},w=(x,N)=>v(x-N+180)-180;if(u.evt.shiftKey){let x=this._transformer,N,k=5;if(x){let C=x.rotationSnaps();Array.isArray(C)&&(N=C.map(T=>v(T)));let S=x.rotationSnapTolerance();typeof S=="number"&&(k=S);}if(N?.length){let C=v(m),S=m,T=1/0;for(let K of N){let L=Math.abs(w(C,K));L<T&&L<=k&&(S=K,T=L);}T!==1/0&&(m=S);}}if(f.rotation(m),this._rotateCenterAbsStart){let x=this._getNodeCenterAbs(f),N=this._rotateCenterAbsStart.x-x.x,k=this._rotateCenterAbsStart.y-x.y,C=f.getParent();if(C){let S=C.getAbsoluteTransform().copy().invert(),T=S.point({x:x.x,y:x.y}),K=S.point({x:x.x+N,y:x.y+k}),L=f.x()+(K.x-T.x),R=f.y()+(K.y-T.y);typeof f.position=="function"&&f.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 u=this._selected,f=u.getKonvaNode();!(u instanceof A)&&this._options.dragEnabled&&typeof f.draggable=="function"&&f.draggable(true);let p={x:f.x(),y:f.y(),rotation:f.rotation()};this._core?.eventBus.emit("node:transformed",this._selected,p);}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");});};a(n),a(o),a(s),a(r);let h=d=>{this._core&&(this._core.stage.container().style.cursor=d);},c=d=>{d.on("mouseenter.rotate-cursor",()=>{if(!this._core||!this._selected)return;let u=this._selected.getKonvaNode(),f=this._getNodeCenterAbs(u),p=d.getAbsolutePosition(),g=p.x-f.x,_=p.y-f.y,v=Math.atan2(_,g)*180/Math.PI+45;this._setRotateCursor(v);}),d.on("mouseleave.rotate-cursor",()=>{h("default");});};this._rotateHandles.tl&&c(this._rotateHandles.tl),this._rotateHandles.tr&&c(this._rotateHandles.tr),this._rotateHandles.br&&c(this._rotateHandles.br),this._rotateHandles.bl&&c(this._rotateHandles.bl),this._updateRotateHandlesPosition();}_destroyRotateHandles(){this._rotateHandlesGroup&&(this._rotateHandlesGroup.destroy(),this._rotateHandlesGroup=null),this._rotateHandles={tl:null,tr:null,br:null,bl:null},this._rotateDragState=null;}_getNodeCenterAbs(e){let t=e.getAbsoluteTransform().copy(),n=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false});return t.point({x:n.x+n.width/2,y:n.y+n.height/2})}_setRotateCursor(e){this._core&&this._applyRotatedCursor(e);}_applyRotatedCursor(e){if(!this._core)return;let t=`
|
|
58
|
-
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
59
|
-
<g transform="rotate(${e.toString()} 12 12)">
|
|
60
|
-
<g clip-path="url(#clip0_36_31)">
|
|
61
|
-
<g filter="url(#filter0_d_36_31)">
|
|
62
|
-
<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"/>
|
|
63
|
-
</g>
|
|
64
|
-
<g filter="url(#filter1_d_36_31)">
|
|
65
|
-
<path d="M0.724195 7.73427L3.27834 2.11403L6.69072 9.31897L0.724195 7.73427Z" fill="black"/>
|
|
66
|
-
<path d="M3.28396 2.82664L6.14311 8.86349L1.1435 7.53589L3.28396 2.82664Z" stroke="white" stroke-width="0.6"/>
|
|
67
|
-
</g>
|
|
68
|
-
<g filter="url(#filter2_d_36_31)">
|
|
69
|
-
<path d="M17.26 22.5868L15.3995 16.7004L22.7553 19.774L17.26 22.5868Z" fill="black"/>
|
|
70
|
-
<path d="M15.8803 17.2264L22.0436 19.8017L17.439 22.1588L15.8803 17.2264Z" stroke="white" stroke-width="0.6"/>
|
|
71
|
-
</g>
|
|
72
|
-
<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"/>
|
|
73
|
-
</g>
|
|
74
|
-
<defs>
|
|
75
|
-
<filter id="filter0_d_36_31" x="-0.539062" y="2" width="22.5391" height="22.4229" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
|
76
|
-
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
|
|
77
|
-
<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"/>
|
|
78
|
-
<feOffset dx="-1" dy="1"/>
|
|
79
|
-
<feGaussianBlur stdDeviation="1.5"/>
|
|
80
|
-
<feComposite in2="hardAlpha" operator="out"/>
|
|
81
|
-
<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"/>
|
|
82
|
-
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_36_31"/>
|
|
83
|
-
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_36_31" result="shape"/>
|
|
84
|
-
</filter>
|
|
85
|
-
<filter id="filter1_d_36_31" x="-0.275879" y="2.11426" width="9.96631" height="11.2046" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
|
86
|
-
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
|
|
87
|
-
<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"/>
|
|
88
|
-
<feOffset dx="1" dy="2"/>
|
|
89
|
-
<feGaussianBlur stdDeviation="1"/>
|
|
90
|
-
<feComposite in2="hardAlpha" operator="out"/>
|
|
91
|
-
<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"/>
|
|
92
|
-
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_36_31"/>
|
|
93
|
-
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_36_31" result="shape"/>
|
|
94
|
-
</filter>
|
|
95
|
-
<filter id="filter2_d_36_31" x="12.3994" y="15.7002" width="11.3555" height="9.88672" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
|
|
96
|
-
<feFlood flood-opacity="0" result="BackgroundImageFix"/>
|
|
97
|
-
<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"/>
|
|
98
|
-
<feOffset dx="-1" dy="1"/>
|
|
99
|
-
<feGaussianBlur stdDeviation="1"/>
|
|
100
|
-
<feComposite in2="hardAlpha" operator="out"/>
|
|
101
|
-
<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"/>
|
|
102
|
-
<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_36_31"/>
|
|
103
|
-
<feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_36_31" result="shape"/>
|
|
104
|
-
</filter>
|
|
105
|
-
<clipPath id="clip0_36_31">
|
|
106
|
-
<rect width="24" height="24" fill="white"/>
|
|
107
|
-
</clipPath>
|
|
108
|
-
</defs>
|
|
109
|
-
</g>
|
|
110
|
-
</svg>
|
|
111
|
-
`.trim(),o=`data:image/svg+xml,${encodeURIComponent(t)}`,s=this._core.stage.container();s.style.cursor=`url("${o}") 12 12, grab`;}_updateRotateHandlesPosition(){if(!this._core||!this._selected||!this._rotateHandlesGroup)return;let e=this._selected.getKonvaNode(),t=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:false}),n=t.width,o=t.height;if(n<=0||o<=0)return;let s=e.getAbsoluteTransform().copy(),r=C=>s.point(C),a=12,h=r({x:t.x+n/2,y:t.y+o/2}),c=r({x:t.x,y:t.y}),d=r({x:t.x+n,y:t.y}),u=r({x:t.x+n,y:t.y+o}),f=r({x:t.x,y:t.y+o}),p=C=>{let S=C.x-h.x,T=C.y-h.y,K=Math.hypot(S,T)||1;return {x:S/K,y:T/K}},g=p(c),_=p(d),m=p(u),b=p(f),v={x:c.x+g.x*a,y:c.y+g.y*a},w={x:d.x+_.x*a,y:d.y+_.y*a},x={x:u.x+m.x*a,y:u.y+m.y*a},N={x:f.x+b.x*a,y:f.y+b.y*a};this._rotateHandles.tl&&this._rotateHandles.tl.absolutePosition(v),this._rotateHandles.tr&&this._rotateHandles.tr.absolutePosition(w),this._rotateHandles.br&&this._rotateHandles.br.absolutePosition(x),this._rotateHandles.bl&&this._rotateHandles.bl.absolutePosition(N);let k=this._rotateHandlesGroup.getParent();if(k){let C=k.getAbsoluteTransform().decompose(),S=1/(Math.abs(C.scaleX)||1),T=1/(Math.abs(C.scaleY)||1);this._rotateHandles.tl&&this._rotateHandles.tl.scale({x:S,y:T}),this._rotateHandles.tr&&this._rotateHandles.tr.scale({x:S,y:T}),this._rotateHandles.br&&this._rotateHandles.br.scale({x:S,y:T}),this._rotateHandles.bl&&this._rotateHandles.bl.scale({x:S,y:T});}}_setupSizeLabel(){if(!this._core||!this._selected)return;let e=this._core.nodes.layer;this._destroySizeLabel();let t=new G__default.default.Label({listening:false,opacity:.95}),n=new G__default.default.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000"}),o=new G__default.default.Text({text:"",fontFamily:"Inter, Calibri, Arial, sans-serif",fontSize:12,padding:6,fill:"#ffffff"});t.add(n),t.add(o),e.add(t),this._sizeLabel=t,this._updateSizeLabel();}_scheduleUIUpdate(){this._uiUpdateDebounce.schedule(()=>{this._updateSizeLabel(),this._updateRotateHandlesPosition(),this._updateCornerRadiusHandlesPosition();});}_updateSizeLabel(){if(!this._core||!this._selected||!this._sizeLabel)return;let e=this._selected.getKonvaNode(),t=e.getClientRect({skipShadow:true,skipStroke:false}),n=e.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),o=e.getAbsoluteTransform().decompose(),s=this._core.nodes.world.getAbsoluteTransform().decompose(),r=Math.abs(o.scaleX)||1,a=Math.abs(o.scaleY)||1,h=Math.abs(s.scaleX)||1,c=Math.abs(s.scaleY)||1,d=n.width*(r/h),u=n.height*(a/c),f=Math.max(0,Math.round(d)),p=Math.max(0,Math.round(u));this._sizeLabel.getText().text(String(f)+" \xD7 "+String(p));let _=8,m=t.x+t.width/2,b=t.y+t.height+_,w=this._sizeLabel.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width;this._sizeLabel.absolutePosition({x:m,y:b}),this._sizeLabel.offsetX(w/2),this._sizeLabel.offsetY(0);let x=this._sizeLabel.getParent();if(x){let N=x.getAbsoluteTransform().decompose(),k=1/(Math.abs(N.scaleX)||1),C=1/(Math.abs(N.scaleY)||1);this._sizeLabel.scale({x:k,y:C});}this._sizeLabel.moveToTop(),this._transformer&&this._transformer.moveToTop(),this._cornerHandlesGroup&&this._cornerHandlesGroup.moveToTop();}_destroySizeLabel(){this._sizeLabel&&(this._sizeLabel.destroy(),this._sizeLabel=null);}_isCornerRadiusSupported(e){return e instanceof G__default.default.Rect||e instanceof G__default.default.Image}_getCornerRadiusArray(e){let t=e.cornerRadius();if(Array.isArray(t)){let[o=0,s=0,r=0,a=0]=t;return [o||0,s||0,r||0,a||0]}let n=typeof t=="number"?t:0;return [n,n,n,n]}_setCornerRadiusArray(e,t){let[n,o,s,r]=t;n===o&&o===s&&s===r?e.cornerRadius(n):e.cornerRadius(t);}_setupCornerRadiusHandles(e=false){if(!this._core||!this._selected)return;let t=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(t))return;let n=this._core.nodes.layer,o=this._core.stage;this._destroyCornerRadiusHandles();let s=new G__default.default.Group({name:"corner-radius-handles-group",listening:true});n.add(s),s.moveToTop(),s.visible(false),this._cornerHandlesGroup=s,t.off(".cornerRadiusHover"),t.on("mouseenter.cornerRadiusHover",()=>{!this._core||!this._cornerHandlesGroup||this._core.nodes.world.scaleX()<.3||this._cornerHandlesGroup.visible(true);}),t.on("mouseleave.cornerRadiusHover",()=>{if(!this._cornerHandlesGroup)return;let E=o.getPointerPosition();if(!E){this._cornerHandlesGroup.visible(false);return}let M=n.getIntersection(E);M&&this._cornerHandlesGroup.isAncestorOf(M)||this._cornerHandlesGroup.visible(false);}),s.on("mouseenter.cornerRadiusHover",()=>{!this._core||!this._cornerHandlesGroup||this._core.nodes.world.scaleX()<.3||this._cornerHandlesGroup.visible(true);}),s.on("mouseleave.cornerRadiusHover",()=>{this._cornerHandlesGroup&&this._cornerHandlesGroup.visible(false);});let r=o.getPointerPosition();if(r&&this._core.nodes.world.scaleX()>=.3){let B=n.getIntersection(r);B&&(B===t||t.isAncestorOf(B))&&this._cornerHandlesGroup.visible(true);}let a=()=>{let E=t.width(),M=t.height(),B=t.getAbsoluteScale(),F=1/(Math.abs(B.x)||1),j=1/(Math.abs(B.y)||1),Z=12*F,z=12*j,te=Math.max(0,E/2-Z),se=Math.max(0,M/2-z),ne=Math.min(te,se);return {tl:{corner:{x:Z,y:z},sign:{x:1,y:1},side:ne},tr:{corner:{x:E-Z,y:z},sign:{x:-1,y:1},side:ne},br:{corner:{x:E-Z,y:M-z},sign:{x:-1,y:-1},side:ne},bl:{corner:{x:Z,y:M-z},sign:{x:1,y:-1},side:ne}}},h=(E,M)=>{let B=t.getAbsoluteTransform().copy(),F=Y=>B.copy().invert().point(Y),j=Y=>B.point(Y),z=a()[M],te=F(E),se=te.x-z.corner.x,ne=te.y-z.corner.y,H=(z.sign.x*se+z.sign.y*ne)/2;H=Math.max(0,Math.min(z.side,H));let V={x:z.corner.x+z.sign.x*H,y:z.corner.y+z.sign.y*H};return {snappedAbs:j(V),r:H,meta:z}},c=E=>new G__default.default.Line({name:E,points:[],stroke:e?"#4a90e2":"",strokeWidth:e?1:0,dash:e?[4,4]:[],closed:true,listening:false}),d=c("corner-square-tl"),u=c("corner-square-tr"),f=c("corner-square-br"),p=c("corner-square-bl");s.add(d,u,f,p);let g=E=>{let M=new G__default.default.Circle({name:E,radius:4,fill:"#ffffff",stroke:"#4a90e2",strokeWidth:1.5,draggable:true,dragOnTop:true,hitStrokeWidth:16});return M.on("mouseenter.corner-radius",()=>{this._core&&(this._core.stage.container().style.cursor="default");}),M},_=g("corner-radius-tl"),m=g("corner-radius-tr"),b=g("corner-radius-br"),v=g("corner-radius-bl");s.add(_,m,b,v),this._cornerHandles={tl:_,tr:m,br:b,bl:v};let w={tl:0,tr:1,br:2,bl:3},x=false,N=null,k=false,C=()=>{let E=t.getAbsoluteTransform().copy(),M=t.width(),B=t.height();return E.point({x:M/2,y:B/2})},S=()=>{let E={};return this._cornerHandles.tl&&(E.tl=this._cornerHandles.tl.getAbsolutePosition()),this._cornerHandles.tr&&(E.tr=this._cornerHandles.tr.getAbsolutePosition()),this._cornerHandles.br&&(E.br=this._cornerHandles.br.getAbsolutePosition()),this._cornerHandles.bl&&(E.bl=this._cornerHandles.bl.getAbsolutePosition()),E},T=(E,M=8)=>{let B=C();return Math.hypot(E.x-B.x,E.y-B.y)<=M},K=(E,M=6)=>{let B=C();return Math.min(Math.abs(E.x-B.x),Math.abs(E.y-B.y))<=M},L=(E,M=8)=>{let B=S(),F=0;return ["tl","tr","br","bl"].forEach(j=>{let Z=B[j];Z&&Math.hypot(Z.x-E.x,Z.y-E.y)<=M&&F++;}),F>=2},R=E=>{if(!x||N)return;let M=C(),B=E.x-M.x,F=E.y-M.y,j=Math.hypot(B,F);if(j<.1)return;B/=j,F/=j;let Z=t.getAbsoluteTransform().copy(),z=a(),te=["tl","tr","br","bl"].reduce((H,V)=>{let de=z[V],Y=Z.point(de.corner),re=Y.x-M.x,q=Y.y-M.y,ee=Math.hypot(re,q)||1;return H[V]={x:re/ee,y:q/ee},H},{}),se="tl",ne=-1/0;["tl","tr","br","bl"].forEach(H=>{let V=te[H],de=B*V.x+F*V.y;de>ne&&(ne=de,se=H);}),N=se;},P=E=>M=>{R(M);let B=N??E,{snappedAbs:F,r:j,meta:Z}=h(M,B),z=t.width(),te=t.height(),se=Math.max(0,Math.min(z,te)/2),ne=Z.side>0?j/Z.side:0,H=Math.round(ne*se);H=Math.max(0,Math.min(H,se));let V=this._getCornerRadiusArray(t),de=w[B];return k?V[de]=H:(V[0]=H,V[1]=H,V[2]=H,V[3]=H),this._setCornerRadiusArray(t,V),this._showRadiusLabelForCorner(de),I(),this._core?.nodes.layer.batchDraw(),F};_.dragBoundFunc(P("tl")),m.dragBoundFunc(P("tr")),b.dragBoundFunc(P("br")),v.dragBoundFunc(P("bl"));let I=()=>{let{tl:E,tr:M,br:B,bl:F}=this._cornerHandles;if(!E||!M||!B||!F)return;if(this._cornerHandlesSuppressed){this._cornerHandlesGroup?.visible(false),this._radiusLabel?.visible(false);return}if(this._core&&this._cornerHandlesGroup&&this._radiusLabel){if(this._core.nodes.world.scaleX()<.3){this._cornerHandlesGroup.visible(false),this._radiusLabel.visible(false);return}this._cornerHandlesGroup.visible(true);}let j=t.getAbsoluteTransform().copy(),Z=n.getAbsoluteTransform().copy().invert(),z=Y=>j.point(Y),te=Y=>Z.point(j.point(Y)),se=a(),ne=this._getCornerRadiusArray(t),H=(Y,re,q)=>{let ee=se[Y],Se=t.width(),Xe=t.height(),Te=Math.max(0,Math.min(Se,Xe)/2),Ye=Math.max(0,Math.min(Te,ne[re]||0)),je=Te>0?Ye/Te:0,Yt=Math.max(0,Math.min(ee.side,je*ee.side)),ln={x:ee.corner.x+ee.sign.x*Yt,y:ee.corner.y+ee.sign.y*Yt};q.absolutePosition(z(ln));},V=(Y,re)=>{let q=se[Y],ee=q.corner,Se={x:q.corner.x+q.sign.x*q.side,y:q.corner.y+q.sign.y*q.side},Xe=te({x:ee.x,y:ee.y}),Te=te({x:Se.x,y:ee.y}),Ye=te({x:Se.x,y:Se.y}),je=te({x:ee.x,y:Se.y});re.points([Xe.x,Xe.y,Te.x,Te.y,Ye.x,Ye.y,je.x,je.y]);};V("tl",d),V("tr",u),V("br",f),V("bl",p),H("tl",0,E),H("tr",1,M),H("br",2,B),H("bl",3,F);let de=this._cornerHandlesGroup?.getParent();if(de){let Y=de.getAbsoluteTransform().decompose(),re=1/(Math.abs(Y.scaleX)||1),q=1/(Math.abs(Y.scaleY)||1);E.scale({x:re,y:q}),M.scale({x:re,y:q}),B.scale({x:re,y:q}),F.scale({x:re,y:q});}this._cornerHandlesGroup?.moveToTop();};this._updateCornerRadiusHandlesPosition=I;let X=(E,M)=>{k=!!M?.evt?.altKey;let B=E.getAbsolutePosition();if(x=T(B,8)||K(B,6)||L(B,8),N=null,x){let F=this._core?.stage.getPointerPosition()??B;R(F);}},U=(E,M)=>B=>{k=B.evt.altKey;},J=()=>{if(x=false,N=null,k=false,this._selected&&this._core){let E=this._selected.getKonvaNode(),M={x:E.x(),y:E.y()};typeof E.width=="function"&&(M.width=E.width()),typeof E.height=="function"&&(M.height=E.height()),this._core.eventBus.emit("node:transformed",this._selected,M);}};_.on("dragstart.corner-radius",E=>{X(_,E);}),m.on("dragstart.corner-radius",E=>{X(m,E);}),b.on("dragstart.corner-radius",E=>{X(b,E);}),v.on("dragstart.corner-radius",E=>{X(v,E);}),_.on("dragmove.corner-radius",U()),m.on("dragmove.corner-radius",U()),b.on("dragmove.corner-radius",U()),v.on("dragmove.corner-radius",U()),_.on("dragend.corner-radius",J),m.on("dragend.corner-radius",J),b.on("dragend.corner-radius",J),v.on("dragend.corner-radius",J);let W=E=>()=>{this._showRadiusLabelForCorner(E);},$=()=>{this._hideRadiusLabel();},ie=E=>()=>{this._showRadiusLabelForCorner(E);};_.on("mouseenter.corner-radius",W(0)),m.on("mouseenter.corner-radius",W(1)),b.on("mouseenter.corner-radius",W(2)),v.on("mouseenter.corner-radius",W(3)),_.on("mouseleave.corner-radius",$),m.on("mouseleave.corner-radius",$),b.on("mouseleave.corner-radius",$),v.on("mouseleave.corner-radius",$),_.on("dragstart.corner-radius",W(0)),m.on("dragstart.corner-radius",W(1)),b.on("dragstart.corner-radius",W(2)),v.on("dragstart.corner-radius",W(3)),_.on("dragmove.corner-radius",ie(0)),m.on("dragmove.corner-radius",ie(1)),b.on("dragmove.corner-radius",ie(2)),v.on("dragmove.corner-radius",ie(3)),_.on("dragend.corner-radius",$),m.on("dragend.corner-radius",$),b.on("dragend.corner-radius",$),v.on("dragend.corner-radius",$);let ue=()=>{if(!this._selected)return;this._selected.getKonvaNode().draggable(false),this._restyleSideAnchors();},pe=()=>{if(!this._selected)return;let E=this._selected,M=E.getKonvaNode();this._options.dragEnabled&&!(E instanceof A)&&typeof M.draggable=="function"&&M.draggable(true),this._restyleSideAnchors();};_.on("mousedown.corner-radius touchstart.corner-radius",ue),m.on("mousedown.corner-radius touchstart.corner-radius",ue),b.on("mousedown.corner-radius touchstart.corner-radius",ue),v.on("mousedown.corner-radius touchstart.corner-radius",ue),_.on("mouseup.corner-radius touchend.corner-radius",pe),m.on("mouseup.corner-radius touchend.corner-radius",pe),b.on("mouseup.corner-radius touchend.corner-radius",pe),v.on("mouseup.corner-radius touchend.corner-radius",pe);let Q=".corner-squares",ke=false,Ce=()=>{ke||(ke=true,G__default.default.Util.requestAnimFrame(()=>{ke=false,I(),this._core?.nodes.layer.batchDraw();}));};o.on(["wheel","resize","xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(E=>E+Q).join(" "),Ce),n.on(["xChange","yChange","positionChange","scaleXChange","scaleYChange","scaleChange"].map(E=>E+Q).join(" "),Ce),t.on(["dragmove","transform","xChange","yChange","widthChange","heightChange","rotationChange","scaleXChange","scaleYChange","positionChange","scaleChange"].map(E=>E+Q).join(" "),Ce),this._transformer&&(this._transformer.on("transformstart"+Q,()=>{this._cornerHandlesSuppressed=true,this._cornerHandlesGroup?.visible(false),this._hideRadiusLabel(),this._core?.nodes.layer.batchDraw();}),this._transformer.on("transform"+Q,()=>{I(),this._core?.nodes.layer.batchDraw();}),this._transformer.on("transformend"+Q,()=>{this._cornerHandlesSuppressed=false,Ce();})),s.on("destroy"+Q,()=>{o.off(Q),n.off(Q),t.off(Q),this._transformer?.off(Q);}),I(),n.batchDraw();}_destroyCornerRadiusHandles(){this._cornerHandlesGroup&&(this._cornerHandlesGroup.destroy(),this._cornerHandlesGroup=null),this._cornerHandles={tl:null,tr:null,br:null,bl:null},this._core&&(this._core.stage.container().style.cursor="default"),this._destroyRadiusLabel(),this._selected&&this._selected.getKonvaNode().off(".overlay-sync");}_bakeRectScale(e){if(!(e instanceof G__default.default.Rect))return;let t=e.scaleX(),n=e.scaleY();if(t===1&&n===1)return;let o=e.getAbsolutePosition(),s=e.width(),r=e.height(),a=Math.abs(t)*s,h=Math.abs(n)*r;e.width(a),e.height(h),e.scaleX(1),e.scaleY(1),e.setAbsolutePosition(o);}_updateCornerRadiusHandlesPosition(){if(!this._core||!this._selected||!this._cornerHandlesGroup)return;let e=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(e))return;let t=e,n=t.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}),o=n.width,s=n.height;if(o<=0||s<=0)return;let r=t.getAbsoluteTransform().copy(),a=k=>r.point(k),h=t.getAbsoluteScale(),c=1/(Math.abs(h.x)||1),d=1/(Math.abs(h.y)||1),u=12*c,f=12*d,p=this._getCornerRadiusArray(t),g=Math.min(o,s)/2||1,_=k=>{let C=Math.hypot(k.x,k.y)||1;return {x:k.x/C,y:k.y/C}},m=[_({x:o/2-u,y:s/2-f}),_({x:-(o/2-u),y:s/2-f}),_({x:-(o/2-u),y:-(s/2-f)}),_({x:o/2-u,y:-(s/2-f)})],b=a({x:n.x+u+m[0].x*Math.min(g,p[0]),y:n.y+f+m[0].y*Math.min(g,p[0])}),v=a({x:n.x+o-u+m[1].x*Math.min(g,p[1]),y:n.y+f+m[1].y*Math.min(g,p[1])}),w=a({x:n.x+o-u+m[2].x*Math.min(g,p[2]),y:n.y+s-f+m[2].y*Math.min(g,p[2])}),x=a({x:n.x+u+m[3].x*Math.min(g,p[3]),y:n.y+s-f+m[3].y*Math.min(g,p[3])});this._cornerHandles.tl&&this._cornerHandles.tl.absolutePosition(b),this._cornerHandles.tr&&this._cornerHandles.tr.absolutePosition(v),this._cornerHandles.br&&this._cornerHandles.br.absolutePosition(w),this._cornerHandles.bl&&this._cornerHandles.bl.absolutePosition(x);let N=this._cornerHandlesGroup.getParent();if(N){let k=N.getAbsoluteTransform().decompose(),C=1/(Math.abs(k.scaleX)||1),S=1/(Math.abs(k.scaleY)||1);this._cornerHandles.tl&&this._cornerHandles.tl.scale({x:C,y:S}),this._cornerHandles.tr&&this._cornerHandles.tr.scale({x:C,y:S}),this._cornerHandles.br&&this._cornerHandles.br.scale({x:C,y:S}),this._cornerHandles.bl&&this._cornerHandles.bl.scale({x:C,y:S});}this._cornerHandlesGroup.moveToTop();}_updateCornerRadiusHandlesVisibility(){if(!this._core||!this._selected||!this._cornerHandlesGroup)return;let t=this._core.nodes.world.scaleX(),n=this._core.stage,o=this._core.nodes.layer,s=this._selected.getKonvaNode(),r=n.getPointerPosition();if(!r){t<.3&&this._cornerHandlesGroup.visible(false);return}if(t<.3){this._cornerHandlesGroup.visible(false);return}let a=o.getIntersection(r);if(a){let h=a===s||s.isAncestorOf(a),c=this._cornerHandlesGroup.isAncestorOf(a);h||c?this._cornerHandlesGroup.visible(true):this._cornerHandlesGroup.visible(false);}else this._cornerHandlesGroup.visible(false);}_ensureRadiusLabel(){if(!this._core)return null;if(this._radiusLabel)return this._radiusLabel;let e=this._core.nodes.layer,t=new G__default.default.Label({listening:false,opacity:.95}),n=new G__default.default.Tag({fill:"#2b83ff",cornerRadius:4,shadowColor:"#000",shadowBlur:6,shadowOpacity:.25}),o=new G__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 r=n.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true}).width,a={x:8,y:8};n.absolutePosition({x:e.x-a.x,y:e.y+a.y}),n.offsetX(r),n.offsetY(0);let h=n.getParent();if(h){let c=h.getAbsoluteTransform().decompose(),d=1/(Math.abs(c.scaleX)||1),u=1/(Math.abs(c.scaleY)||1);n.scale({x:d,y:u});}n.visible(true),n.moveToTop(),this._transformer&&this._transformer.moveToTop();}_showRadiusLabelForCorner(e){if(!this._core||!this._selected)return;let t=this._selected.getKonvaNode();if(!this._isCornerRadiusSupported(t))return;let n=t,o=this._getCornerRadiusArray(n),s=Math.round(o[e]),r=e===0?this._cornerHandles.tl:e===1?this._cornerHandles.tr:e===2?this._cornerHandles.br:this._cornerHandles.bl;if(!r)return;let a=r.getAbsolutePosition();this._updateRadiusLabelAt(a,"Radius "+String(s));}_hideRadiusLabel(){this._radiusLabel&&this._radiusLabel.visible(false);}_destroyRadiusLabel(){this._radiusLabel&&(this._radiusLabel.destroy(),this._radiusLabel=null);}_findBaseNodeByTarget(e){if(!this._core)return null;if(this._selected){let r=this._selected.getKonvaNode();if(r===e)return this._selected;if(typeof r.isAncestorOf=="function"&&r.isAncestorOf(e))return this._selected}let t=this._core.nodes.list(),n=t.filter(r=>r instanceof A),o=false;for(let r of n){let a=r.getContentGroup();if(e===a||typeof a.isAncestorOf=="function"&&a.isAncestorOf(e)){o=true;break}}if(o){let r=t.filter(h=>!(h instanceof A)),a=null;for(let h of r){let c=h.getKonvaNode();if(typeof c.isAncestorOf!="function"||!c.isAncestorOf(e))continue;let d=true;for(let u of r){if(u===h)continue;let f=u.getKonvaNode();if(typeof f.isAncestorOf=="function"&&f.isAncestorOf(c)){d=false;break}}if(d){a=h;break}}if(a)return a;for(let h of r)if(h.getKonvaNode()===e)return h}let s=null;for(let r of this._core.nodes.list()){let a=r.getKonvaNode();if(typeof a.isAncestorOf=="function"&&a.isAncestorOf(e)){let h=true;for(let c of this._core.nodes.list()){if(c===r)continue;let d=c.getKonvaNode();if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(a)){h=false;break}}h&&(s=r);}}if(s)return s;for(let r of this._core.nodes.list())if(r.getKonvaNode()===e)return r;return null}_disableGroupChildrenDragging(e){let t=e.getChildren();for(let n of t){let o=n;typeof o.draggable=="function"&&o.draggable(false);}}};var Ct=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_layer",null);l(this,"_rect",null);l(this,"_start",null);l(this,"_transformer",null);l(this,"_selecting",false);l(this,"_skipNextClick",false);l(this,"_lastPickedBaseNodes",[]);l(this,"_autoPanRafId",null);l(this,"_autoPanActive",false);l(this,"_autoPanEdgePx",50);l(this,"_autoPanMaxSpeedPx",20);l(this,"_options");this._options={rectStroke:e.rectStroke??"#2b83ff",rectFill:e.rectFill??"#2b83ff",rectStrokeWidth:e.rectStrokeWidth??1,rectOpacity:e.rectOpacity??.15,enableKeyboardShortcuts:e.enableKeyboardShortcuts??true};}onAttach(e){this._core=e;let t=new G__default.default.Layer({name:"area-selection-layer",listening:false});e.stage.add(t),this._layer=t,this._rect=new G__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)return;let s=o.target,r=e.nodes.layer;if(s!==n&&s.getLayer()===r){let p=this._core?.nodes.list()??[],g=false;for(let v of p){if(!(v instanceof A))continue;let w=v.getKonvaNode(),x=v.getContentGroup(),N=s,k=false;for(;N;){if(N===w){k=true;break}N=N.getParent();}if(!k||s===x||x.isAncestorOf(s))continue;let S=x.getChildren().length>0,T=w,K=typeof T.draggable=="function"?T.draggable():true;if(S&&!K){g=true;break}}if(!g)return;let _=this._getSelectionPlugin(),m=_?.getSelected(),b=n.getPointerPosition();if(m&&b){let w=m.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false});if(b.x>=w.x&&b.x<=w.x+w.width&&b.y>=w.y&&b.y<=w.y+w.height)return}_&&_.clearSelectionFromAreaLasso();}let a=n.getPointerPosition();if(!a||!this._rect)return;let c=this._getSelectionPlugin()?.getSelected();if(c){let g=c.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false});if(a.x>=g.x&&a.x<=g.x+g.width&&a.y>=g.y&&a.y<=g.y+g.height)return}let d=n.findOne(".ruler-layer");if(d&&o.target.getLayer()===d)return;let u=n.findOne(".guides-layer");if(u&&o.target.getLayer()===u)return;let f=30;a.y<=f||a.x<=f||(this._selecting=true,this._start={x:a.x,y:a.y},this._rect.visible(true),this._rect.position({x:a.x,y:a.y}),this._rect.size({width:0,height:0}),this._layer?.batchDraw(),this._lastPickedBaseNodes=[],this._startAutoPanLoop());}),n.on("mousemove.area",()=>{if(!this._selecting||!this._rect||!this._start)return;let o=n.getPointerPosition();if(!o)return;let s=Math.min(this._start.x,o.x),r=Math.min(this._start.y,o.y),a=Math.abs(o.x-this._start.x),h=Math.abs(o.y-this._start.y);this._rect.position({x:s,y:r}),this._rect.size({width:a,height:h}),this._layer?.batchDraw();let c={x:s,y:r,width:a,height:h},d=this._core?.nodes.list()??[],u=new Set,f=new Set;for(let _ of d){if(_ instanceof ge)continue;let m=_.getKonvaNode();if(m.getLayer()!==this._core?.nodes.layer)continue;if(_ instanceof A){let N=_.getRect().getClientRect({skipShadow:true,skipStroke:true});_.getContentGroup().getChildren().length>0?this._rectContains(c,N)&&(u.add(_),f.add(_)):this._rectsIntersect(c,N)&&u.add(_);continue}let v=false;for(let x of f){let N=x.getContentGroup();if(m===N||N.isAncestorOf(m)){v=true;break}}if(v)continue;let w=m.getClientRect({skipShadow:true,skipStroke:false});if(this._rectsIntersect(c,w)){let x=this._findOwningGroupBaseNode(m);u.add(x??_);}}let p=Array.from(u),g=this._getSelectionPlugin();if(p.length>0&&(this._lastPickedBaseNodes=p),g){let _=g.getMultiGroupController();p.length>0&&_.ensure(p),this._core?.stage.batchDraw();}}),n.on("mouseup.area",o=>{if(!this._selecting)return;let s=false;if(this._rect?.visible()){let r=this._rect.size();s=r.width>2||r.height>2;}this._finalizeArea(),this._stopAutoPanLoop(),s&&(this._skipNextClick=true,this._core?.stage.setAttr("_skipSelectionEmptyClickOnce",true),o.cancelBubble=true);}),n.on("click.area",o=>{if(!this._core)return;if(this._skipNextClick){this._skipNextClick=false,o.cancelBubble=true;return}if(o.evt.shiftKey)return;let r=this._getSelectionPlugin()?.getMultiGroupController(),a=!!r?.isActive();if(!a&&!this._isPermanentGroupSelected())return;let h=o.target,c=this._currentGroupNode();c?this._isAncestor(c,h)||this._clearSelection():a&&r&&(r.isInsideTempByTarget(h)||(r.destroy(),this._core.stage.batchDraw()));});}onDetach(e){e.stage.off(".area"),this._stopAutoPanLoop(),this._clearSelection(),this._layer&&this._layer.destroy(),this._layer=null,this._rect=null;}_rectContains(e,t){return t.x>=e.x&&t.y>=e.y&&t.x+t.width<=e.x+e.width&&t.y+t.height<=e.y+e.height}_startAutoPanLoop(){if(!this._core||this._autoPanRafId!=null)return;this._autoPanActive=true;let e=this._core.nodes.world,t=this._core.stage,n=()=>{if(this._autoPanRafId=null,!this._core||!this._autoPanActive)return;let o=t.getPointerPosition();if(o){let s=t.width(),r=t.height(),a=this._autoPanEdgePx,h=0,c=0,d=Math.max(0,a-o.x),u=Math.max(0,o.x-(s-a)),f=Math.max(0,a-o.y),p=Math.max(0,o.y-(r-a)),g=_=>Math.min(1,_/a);if(h=this._autoPanMaxSpeedPx*(g(u)-g(d)),c=this._autoPanMaxSpeedPx*(g(p)-g(f)),h!==0||c!==0){e.x(e.x()-h),e.y(e.y()-c);let _=e.position();if(this._core.eventBus.emit("camera:pan",{dx:-h,dy:-c,position:{x:_.x,y:_.y}}),this._start&&(this._start.x-=h,this._start.y-=c),this._rect&&this._start){let m=t.getPointerPosition();if(m){let b=Math.min(this._start.x,m.x),v=Math.min(this._start.y,m.y),w=Math.abs(m.x-this._start.x),x=Math.abs(m.y-this._start.y);this._rect.position({x:b,y:v}),this._rect.size({width:w,height:x});}}this._layer?.batchDraw(),this._core.nodes.layer.batchDraw();}}this._autoPanRafId=globalThis.requestAnimationFrame(n);};this._autoPanRafId=globalThis.requestAnimationFrame(n);}_stopAutoPanLoop(){this._autoPanActive=false,this._autoPanRafId!=null&&(globalThis.cancelAnimationFrame(this._autoPanRafId),this._autoPanRafId=null);}_finalizeArea(){if(!this._core||!this._rect||!this._start)return;this._selecting=false;let e=this._rect.getClientRect({skipStroke:true});this._rect.visible(false),this._layer?.batchDraw();let t=[];if(this._lastPickedBaseNodes.length>0)t=[...this._lastPickedBaseNodes];else {let o=this._core.nodes.list(),s=[];for(let h of o){let c=h.getKonvaNode();if(c.getLayer()!==this._core.nodes.layer)continue;if(h instanceof A){let p=h.getRect().getClientRect({skipShadow:true,skipStroke:true});if(h.getContentGroup().getChildren().length>0)this._rectContains(e,p)&&s.push(c);else {let m=c.getClientRect({skipShadow:true,skipStroke:false});this._rectsIntersect(e,m)&&s.push(c);}continue}let u=c.getClientRect({skipShadow:true,skipStroke:false});this._rectsIntersect(e,u)&&s.push(c);}let r=this._core.nodes.list(),a=new Set;for(let h of s){let c=r.find(u=>u.getKonvaNode()===h)??null,d=this._findOwningGroupBaseNode(h);d?a.add(d):c&&!(c instanceof ge)&&a.add(c);}t=Array.from(a);}let n=this._getSelectionPlugin();if(n)if(t.length===1){let o=t[0];o&&n.selectSingleFromArea(o);}else t.length>1?(n.getMultiGroupController().ensure(t),this._core.stage.batchDraw()):n.getMultiGroupController().destroy();this._lastPickedBaseNodes=[];}_clearSelection(){this._isPermanentGroupSelected()&&(this._transformer&&this._transformer.destroy(),this._transformer=null,this._core?.stage.batchDraw());let t=this._getSelectionPlugin()?.getMultiGroupController();t&&t.destroy();}_getSelectionPlugin(){return this._core?this._core.plugins.list().find(t=>t instanceof xe)??null:null}_rectsIntersect(e,t){return e.x<=t.x+t.width&&e.x+e.width>=t.x&&e.y<=t.y+t.height&&e.y+e.height>=t.y}_findOwningGroupBaseNode(e){if(!this._core)return null;let n=this._core.nodes.list().filter(r=>r instanceof ge),o=e,s=null;for(;o;){let r=n.find(a=>a.getKonvaNode()===o)??null;r&&(s=r),o=o.getParent();}return s}_isAncestor(e,t){let n=t;for(;n;){if(n===e)return true;n=n.getParent();}return false}_isPermanentGroupSelected(){if(!this._transformer)return false;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return !t||!this._core?false:this._core.nodes.list().some(n=>n instanceof ge&&n.getKonvaNode()===t)}_currentGroupNode(){if(!this._transformer)return null;let t=(typeof this._transformer.nodes=="function"?this._transformer.nodes():[])[0];return t&&t instanceof G__default.default.Group?t:null}};var St=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_attached",false);l(this,"_panning",false);l(this,"_last",null);l(this,"_prevCursor",null);l(this,"_prevStageDraggable");l(this,"_onMouseDownDOM",null);l(this,"_onMouseMoveDOM",null);l(this,"_onMouseUpDOM",null);l(this,"_onMouseLeaveDOM",null);l(this,"_panningCursorRafId",null);l(this,"_onCameraPanEvent",e=>{this._core&&this._panning&&this._applyPanningCursor();});l(this,"_onWheelDOM",e=>{if(!this._core||e.ctrlKey)return;e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation?.();let{deltaX:n,deltaY:o,shiftKey:s}=e;if(this._isTouchpadWheel(e)){if(s){let a=-(Math.abs(n)>=Math.abs(o)?n:o);this._pan(a,0);}else {let r=-n,a=-o;this._pan(r,a);}return}if(s){let r=o<0?-Math.abs(o):Math.abs(o);this._pan(r,0);}else {let r=-o;this._pan(0,r);}});l(this,"_onContextMenuDOM",e=>{this._options.disableContextMenu&&e.preventDefault();});l(this,"_handleKeyDown",e=>{if(this._options.ignoreEditableTargets&&this._isEditableTarget(e.target)||!this._core)return;let t=e.code==="Equal"||e.code==="NumpadAdd",n=e.code==="Minus"||e.code==="NumpadSubtract";if(t||n){e.preventDefault(),t?this._core.camera.zoomIn():this._core.camera.zoomOut();return}if(this._options.enableArrows){let o=this._core.camera.panStep;switch(e.key){case "ArrowLeft":e.preventDefault(),this._pan(o,0);return;case "ArrowRight":e.preventDefault(),this._pan(-o,0);return;case "ArrowUp":e.preventDefault(),this._pan(0,o);return;case "ArrowDown":e.preventDefault(),this._pan(0,-o);return}}});let{target:t=globalThis,zoomStep:n=1.1,panStep:o=40,ignoreEditableTargets:s=true,enableArrows:r=true,enablePanning:a=true,allowMiddleButtonPan:h=true,allowRightButtonPan:c=true,disableContextMenu:d=true}=e;this._options={target:t,zoomStep:n,panStep:o,ignoreEditableTargets:s,enableArrows:r,enablePanning:a,allowMiddleButtonPan:h,allowRightButtonPan:c,disableContextMenu:d};}setOptions(e){let t=this._options.disableContextMenu;if(this._options={...this._options,...e},this._attached&&this._core&&(typeof e.zoomStep=="number"&&this._core.camera.setZoomStep(this._options.zoomStep),typeof e.panStep=="number"&&this._core.camera.setPanStep(this._options.panStep),typeof e.disableContextMenu=="boolean"&&e.disableContextMenu!==t)){let n=this._core.stage.container();this._options.disableContextMenu?n.addEventListener("contextmenu",this._onContextMenuDOM):n.removeEventListener("contextmenu",this._onContextMenuDOM);}}onAttach(e){this._core=e;let t=this._core.stage;if(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){let o=t.container();this._onMouseDownDOM=s=>{if(!this._core||!this._options.enablePanning)return;let r=s.button;if(!(this._options.allowMiddleButtonPan&&r===1||this._options.allowRightButtonPan&&r===2))return;this._panning=true,this._core.stage.setPointersPositions(s);let h=this._core.stage.getPointerPosition();h&&(this._last={x:h.x,y:h.y}),this._applyPanningCursor(),this._startPanningCursorLoop(),this._core.eventBus.emit("camera:panStart",{button:r}),s.preventDefault();},this._onMouseMoveDOM=s=>{if(!this._core||!this._options.enablePanning||!this._panning||!this._last)return;this._applyPanningCursor(),this._core.stage.setPointersPositions(s);let r=this._core.stage.getPointerPosition();if(!r)return;let a=r.x-this._last.x,h=r.y-this._last.y;this._pan(a,h),this._last={x:r.x,y:r.y},s.preventDefault();},this._onMouseUpDOM=s=>{this._options.enablePanning&&this._panning&&(this._panning=false,this._last=null,this._stopPanningCursorLoop(),this._restoreCursor(),this._core&&this._core.eventBus.emit("camera:panEnd"));},this._onMouseLeaveDOM=s=>{this._options.enablePanning&&this._panning&&(this._panning=false,this._last=null,this._stopPanningCursorLoop(),this._restoreCursor(),this._core&&this._core.eventBus.emit("camera:panEnd"));},o.addEventListener("mousedown",this._onMouseDownDOM,{capture:true}),o.addEventListener("mousemove",this._onMouseMoveDOM,{capture:true}),o.addEventListener("mouseup",this._onMouseUpDOM,{capture:true}),o.addEventListener("mouseleave",this._onMouseLeaveDOM,{capture:true}),this._options.disableContextMenu&&o.addEventListener("contextmenu",this._onContextMenuDOM),this._core.eventBus.on("camera:pan",this._onCameraPanEvent);}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._stopPanningCursorLoop(),this._options.target.removeEventListener("keydown",this._handleKeyDown);let n=e.stage;if(n.off(".cameraHotkeysGuard"),n.container().removeEventListener("wheel",this._onWheelDOM),this._options.enablePanning){let o=n.container();o.removeEventListener("contextmenu",this._onContextMenuDOM),this._onMouseDownDOM&&o.removeEventListener("mousedown",this._onMouseDownDOM),this._onMouseMoveDOM&&o.removeEventListener("mousemove",this._onMouseMoveDOM),this._onMouseUpDOM&&o.removeEventListener("mouseup",this._onMouseUpDOM),this._onMouseLeaveDOM&&o.removeEventListener("mouseleave",this._onMouseLeaveDOM),this._onMouseDownDOM=null,this._onMouseMoveDOM=null,this._onMouseUpDOM=null,this._onMouseLeaveDOM=null,e.eventBus.off("camera:pan",this._onCameraPanEvent);}this._prevStageDraggable!==void 0&&n.draggable(this._prevStageDraggable),this._attached=false,this._last=null,this._prevCursor=null;}_applyPanningCursor(){if(!this._core)return;let e=this._core.stage.container();this._prevCursor??(this._prevCursor=e.style.cursor||null),e.style.cursor="grabbing";}_startPanningCursorLoop(){if(this._panningCursorRafId!=null)return;let e=()=>{this._panningCursorRafId=null,!(!this._panning||!this._core)&&(this._applyPanningCursor(),this._panningCursorRafId=globalThis.requestAnimationFrame(e));};this._panningCursorRafId=globalThis.requestAnimationFrame(e);}_stopPanningCursorLoop(){this._panningCursorRafId!=null&&(globalThis.cancelAnimationFrame(this._panningCursorRafId),this._panningCursorRafId=null);}_restoreCursor(){if(!this._core)return;let e=this._core.stage.container();this._prevCursor!==null?(e.style.cursor=this._prevCursor,this._prevCursor=null):e.style.removeProperty("cursor");}_isEditableTarget(e){let t=e;if(!t)return false;let n=t.tagName;return t.isContentEditable||n==="INPUT"||n==="TEXTAREA"||n==="SELECT"}_isTouchpadWheel(e){return e.deltaMode===0&&(Math.abs(e.deltaX)>0||Math.abs(e.deltaY)<50)}_pan(e,t){if(!this._core)return;let n=this._core.nodes.world,o=n.x()+e,s=n.y()+t;n.position({x:o,y:s}),this._core.eventBus.emit("camera:pan",{dx:e,dy:t,position:{x:o,y:s}}),this._core.stage.batchDraw();}};var he=class{attach(i){this.onAttach(i);}detach(i){this.onDetach(i);}};var Tt=class extends oe{constructor(){super(...arguments);l(this,"_container",null);l(this,"_onDragOver",null);l(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;}},ft=class extends he{constructor(e){super();l(this,"_objectUrl");l(this,"_revoked",false);this._objectUrl=e;}onAttach(e){}onDetach(){this._revoked||(URL.revokeObjectURL(this._objectUrl),this._revoked=true);}},Et=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_dragDropAddon",null);l(this,"_middlePressed",false);l(this,"_onContainerMouseDown",null);l(this,"_onContainerMouseUp",null);l(this,"_onPaste",e=>{if(this._middlePressed){e.preventDefault();return}this._onPasteAsync(e);});let{target:t=globalThis,ignoreEditableTargets:n=true}=e;this._options={target:t,ignoreEditableTargets:n,maxImageSize:e.maxImageSize??Number.POSITIVE_INFINITY,enableDragDrop:e.enableDragDrop??true},this._options.enableDragDrop&&(this._dragDropAddon=new Tt,this.addons.add(this._dragDropAddon));}onAttach(e){this._core=e,this._options.target.addEventListener("paste",this._onPaste);let t=this._core.stage.container();this._onContainerMouseDown=n=>{n.button===1&&(this._middlePressed=false);},this._onContainerMouseUp=n=>{n.button===1&&(this._middlePressed=true);},t.addEventListener("mousedown",this._onContainerMouseDown,{capture:true}),t.addEventListener("mouseup",this._onContainerMouseUp,{capture:true});}onDetach(e){this._options.target.removeEventListener("paste",this._onPaste),this._core=void 0;let t=e.stage.container();this._onContainerMouseDown&&t.removeEventListener("mousedown",this._onContainerMouseDown),this._onContainerMouseUp&&t.removeEventListener("mouseup",this._onContainerMouseUp),this._onContainerMouseDown=null,this._onContainerMouseUp=null;}async _onPasteAsync(e){await this._handlePaste(e),this._resetAltKeyStuck();}async _handlePaste(e){if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let t=e.clipboardData;if(!t)return;let n=this._getPastePosition();await this._handleDataTransfer(t,n,e);}async handleDrop(e){if(!this._core)return;let t=e.dataTransfer;if(!t)return;e.preventDefault(),e.stopImmediatePropagation(),this._core.stage.setPointersPositions(e);let n=this._core.stage.getPointerPosition();if(!n)return;let r=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(n);await this._handleDataTransfer(t,{x:r.x,y:r.y},e),this._resetAltKeyStuck();}_resetAltKeyStuck(){try{let e=new KeyboardEvent("keyup",{key:"Alt",code:"AltLeft",bubbles:!0}),t=this._options.target;typeof t.dispatchEvent=="function"?t.dispatchEvent(e):typeof globalThis.dispatchEvent=="function"&&globalThis.dispatchEvent(e);}catch{}}async _handleDataTransfer(e,t,n){if(!this._core)return;let o=Array.from(e.items);for(let d=o.length-1;d>=0;d--){let u=o[d];if(u){if(u.kind==="file"){let f=u.getAsFile();if(f?.type==="image/svg+xml"||f?.name.toLowerCase().endsWith(".svg")){n?.preventDefault(),await this._pasteSvgFile(f,t);return}if(f&&(f.type.startsWith("video/")||this._looksLikeVideoFile(f))){n?.preventDefault(),await this._pasteVideoFile(f,t);return}if(f&&(f.type.startsWith("image/")||f.type==="")){n?.preventDefault(),await this._pasteImageFile(f,t);return}}if(u.kind==="string"&&(u.type==="text/plain"||u.type==="text/html")){let f=await this._getAsString(u),p=this._extractSvgMarkup(f);if(p){n?.preventDefault(),this._pasteSvgText(p,t);return}let g=u.type==="text/html"?this._htmlToText(f):f;if(g.trim().length>0){n?.preventDefault(),this._core.nodes.addText({x:t.x,y:t.y,text:g});return}}}}let s=Array.from(e.files??[]);for(let d=s.length-1;d>=0;d--){let u=s[d];if(u){if(u.type==="image/svg+xml"||u.name.toLowerCase().endsWith(".svg")){n?.preventDefault(),await this._pasteSvgFile(u,t);return}if(u.type.startsWith("video/")||this._looksLikeVideoFile(u)){n?.preventDefault(),await this._pasteVideoFile(u,t);return}if(u.type.startsWith("image/")||u.type===""){n?.preventDefault(),await this._pasteImageFile(u,t);return}}}let r=e.getData("text/plain")||"",a=e.getData("text/html")||"",h=this._extractSvgMarkup(a)??this._extractSvgMarkup(r);if(h){n?.preventDefault(),this._pasteSvgText(h,t);return}let c=this._htmlToText(a||r);if(c.trim().length>0){n?.preventDefault(),this._core.nodes.addText({x:t.x,y:t.y,text:c});return}}_pasteSvgText(e,t){if(!this._core)return;let n=this._svgTextToSrc(e),o=this._extractSvgSize(e),s=this._fitIntoMaxSize(o,this._options.maxImageSize);this._core.nodes.addSvg({x:t.x,y:t.y,src:n,width:s.width,height:s.height});}async _pasteSvgFile(e,t){let n=await this._readFileAsText(e);this._pasteSvgText(n,t);}async _pasteImageFile(e,t){if(!this._core)return;let n=URL.createObjectURL(e);try{let o=await this._loadImageSize(n),s=this._fitIntoMaxSize(o,this._options.maxImageSize);this._core.nodes.addImage({x:t.x,y:t.y,src:n,width:s.width,height:s.height}).addons.add(new ft(n));}catch(o){throw URL.revokeObjectURL(n),o}}async _pasteVideoFile(e,t){if(!this._core)return;let n=URL.createObjectURL(e);try{let o=this._core.nodes.addVideo({x:t.x,y:t.y,width:320,height:240,autoplay:!0,loop:!0,muted:!1,volume:1});await o.setSrc(n,{autoplay:!0,loop:!0,muted:!1,volume:1});let s=o.getVideoElement(),r=s?{width:s.videoWidth||0,height:s.videoHeight||0}:{width:0,height:0},a=this._fitIntoMaxSize(r,this._options.maxImageSize);o.setSize({width:a.width,height:a.height}),o.addons.add(new ft(n));}catch(o){throw URL.revokeObjectURL(n),o}}_fitIntoMaxSize(e,t){if(!isFinite(e.width)||!isFinite(e.height)||e.width<=0||e.height<=0)return {width:150,height:150};if(!isFinite(t)||t<=0)return e;let n=Math.max(e.width,e.height);if(n<=t)return e;let o=t/n;return {width:Math.max(1,Math.round(e.width*o)),height:Math.max(1,Math.round(e.height*o))}}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_getPastePosition(){if(!this._core)return {x:0,y:0};let t=this._core.stage.getPointerPosition();if(t&&this._isPointerOnScreen(t)){let s=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(t);return {x:s.x,y:s.y}}return this._getScreenCenter()}_isPointerOnScreen(e){if(!this._core)return false;let t=this._core.stage,n=t.width(),o=t.height();return e.x>=0&&e.x<=n&&e.y>=0&&e.y<=o}_getScreenCenter(){if(!this._core)return {x:0,y:0};let e=this._core.stage,t=this._core.nodes.world,n=e.width()/2,o=e.height()/2,r=t.getAbsoluteTransform().copy().invert().point({x:n,y:o});return {x:r.x,y:r.y}}_getAsString(e){return new Promise(t=>{e.getAsString(n=>{t(n);});})}_looksLikeVideoFile(e){let t=typeof e.name=="string"?e.name.toLowerCase():"";return t?t.endsWith(".mp4")||t.endsWith(".webm")||t.endsWith(".mov")||t.endsWith(".m4v")||t.endsWith(".mkv")||t.endsWith(".avi"):false}_htmlToText(e){let t=globalThis.DOMParser??null;return t?new t().parseFromString(e,"text/html").body.textContent||"":e}_readFileAsText(e){return new Promise((t,n)=>{let o=new FileReader;o.onload=()=>{let s=o.result;if(typeof s=="string"){t(s);return}n(new Error("Failed to read clipboard SVG"));},o.onerror=()=>{n(new Error("Failed to read clipboard SVG"));},o.readAsText(e);})}_extractSvgMarkup(e){let t=e.trim(),n=t.toLowerCase(),o=n.indexOf("<svg");if(o===-1)return null;let s=n.lastIndexOf("</svg>");return s===-1?null:t.slice(o,s+6)}_svgTextToSrc(e){return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(e)}`}_parseSvgNumber(e){let t=Number.parseFloat(e);return Number.isFinite(t)?t:0}_extractSvgSize(e){let t=/\bwidth\s*=\s*["']([^"']+)["']/i,n=/\bheight\s*=\s*["']([^"']+)["']/i,o=t.exec(e),s=n.exec(e),r=o?.[1]?this._parseSvgNumber(o[1]):0,a=s?.[1]?this._parseSvgNumber(s[1]):0;if(r>0&&a>0)return {width:r,height:a};let c=/\bviewBox\s*=\s*["']([^"']+)["']/i.exec(e);if(c?.[1]){let d=c[1].trim().split(/[\s,]+/),u=d.length>=4?d[2]:void 0,f=d.length>=4?d[3]:void 0,p=u?this._parseSvgNumber(u):0,g=f?this._parseSvgNumber(f):0;if(p>0&&g>0)return {width:p,height:g}}return {width:150,height:150}}_loadImageSize(e){return new Promise((t,n)=>{let o=globalThis.Image??null;if(!o){n(new Error("Image constructor is not available in current environment"));return}let s=new o;s.onload=()=>{t({width:s.naturalWidth||s.width,height:s.naturalHeight||s.height});},s.onerror=()=>{n(new Error("Failed to load clipboard image"));},s.src=e;})}};var Pt=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_layer",null);l(this,"_shape",null);l(this,"_stepX");l(this,"_stepY");l(this,"_color");l(this,"_lineWidth");l(this,"_visible");l(this,"_minScaleToShow");l(this,"_enableSnap");l(this,"_dragMoveHandler",null);l(this,"_nodesAddHandler",null);l(this,"_nodesRemoveHandler",null);l(this,"_redrawScheduled",false);l(this,"_transformersCache",[]);l(this,"_cacheInvalidated",true);this._stepX=Math.max(1,e.stepX??1),this._stepY=Math.max(1,e.stepY??1),this._color=e.color??"#2b313a",this._lineWidth=e.lineWidth??1,this._visible=e.visible??true,this._minScaleToShow=e.minScaleToShow??8,this._enableSnap=e.enableSnap??true;}onAttach(e){this._core=e;let t=e.nodes.layer,n=(d,u)=>{if(!this._visible||!this._core)return;let f=this._core.stage,p=this._core.nodes.world,g=p.scaleX();if(this._minScaleToShow!=null&&g<this._minScaleToShow)return;let _=f.width(),m=f.height(),b=p.scaleX(),v=p.scaleY(),w=Math.max(1,this._stepX)*Math.max(1e-6,b),x=Math.max(1,this._stepY)*Math.max(1e-6,v),N=(p.x()%w+w)%w,k=(p.y()%x+x)%x;d.beginPath(),d.lineWidth=this._lineWidth,d.strokeStyle=this._color;for(let C=N;C<=_;C+=w)d.moveTo(C,0),d.lineTo(C,m);for(let C=k;C<=m;C+=x)d.moveTo(0,C),d.lineTo(_,C);d.stroke();},o=new G__default.default.Shape({listening:false,sceneFunc:n});t.add(o),this._layer=t,this._shape=o;let s=e.stage,r=e.nodes.world;s.on("resize.grid",()=>{this._scheduleRedraw();}),r.on("xChange.grid yChange.grid scaleXChange.grid scaleYChange.grid",()=>{this._scheduleRedraw();}),(()=>{this._cacheInvalidated&&(this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false);for(let d of this._transformersCache)d.moveToTop();this._shape?.moveToTop();for(let d of this._transformersCache)d.moveToTop();})(),this._dragMoveHandler=d=>{if(!this._core||!this._enableSnap)return;let u=this._core.stage,f=this._core.nodes.world,p=d.target;if(p===u||p instanceof G__default.default.Layer)return;let g=this._core.nodes.layer,_=p,m=false;for(;_;){if(_===g){m=true;break}_=_.getParent();}if(!m)return;let b=p;if(typeof b.draggable=="function"&&!b.draggable())return;let v=p.getAbsolutePosition(),w=f.scaleX()||1,x=f.scaleY()||1;if(this._minScaleToShow!=null?w>=this._minScaleToShow:false){let k=(v.x-f.x())/w,C=(v.y-f.y())/x,S=Math.max(1,this._stepX),T=Math.max(1,this._stepY),K=Math.round(k/S)*S,L=Math.round(C/T)*T,R=K*w+f.x(),P=L*x+f.y();(Math.abs(R-v.x)>.001||Math.abs(P-v.y)>.001)&&p.absolutePosition({x:R,y:P});}else {let k=(v.x-f.x())/w,C=(v.y-f.y())/x,S=Math.max(1,this._stepX),T=Math.max(1,this._stepY),K=Math.round(k/S)*S,L=Math.round(C/T)*T,R=K*w+f.x(),P=L*x+f.y();(Math.abs(R-v.x)>.001||Math.abs(P-v.y)>.001)&&p.absolutePosition({x:R,y:P});}},s.on("dragmove.grid",this._dragMoveHandler);let h=d=>{let u=d;if((typeof u.getClassName=="function"?u.getClassName():"")!=="Transformer")return;let p=d,g=(_,m)=>{let b=m;if(!this._enableSnap||!this._core||!(typeof u.nodes=="function"?u.nodes():[])[0])return b;let x=typeof u.getActiveAnchor=="function"?u.getActiveAnchor():"";if(x==="rotater")return b;let N=Math.max(1,this._stepX),k=Math.max(1,this._stepY),C=typeof x=="string"?x:"",S=this._core.nodes.world.getAbsoluteTransform(),T=S.copy();T.invert();let K=b.x,L=b.x+b.width,R=b.y,P=b.y+b.height,I=T.point({x:K,y:R}).x,X=T.point({x:L,y:R}).x,U=T.point({x:K,y:R}).y,J=T.point({x:K,y:P}).y,W=I,$=X,ie=U,ue=J,pe=(F,j)=>Math.round((F+1e-9)/j)*j;C.includes("left")&&(W=pe(I,N)),C.includes("right")&&($=pe(X,N)),C.includes("top")&&(ie=pe(U,k)),C.includes("bottom")&&(ue=pe(J,k)),$-W<N&&(C.includes("left")?W=$-N:$=W+N),ue-ie<k&&(C.includes("top")?ie=ue-k:ue=ie+k);let Q=S.point({x:W,y:ie}).x,ke=S.point({x:W,y:ie}).y,Ce=S.point({x:$,y:ie}).x,E=S.point({x:W,y:ue}).y,M=F=>Math.round(F*1e3)/1e3;return {x:M(Q),y:M(ke),width:M(Ce-Q),height:M(E-ke),rotation:b.rotation}};globalThis.queueMicrotask(()=>{p.boundBoxFunc(g);});},c=d=>{h(d);let u=d,f=typeof u.getChildren=="function"?u.getChildren():[];for(let p of f)c(p);};c(e.nodes.layer),this._nodesAddHandler=d=>{let u=d.child??d.target;c(u);let f=u;if((typeof f.getClassName=="function"?f.getClassName():"")==="Transformer"){this._cacheInvalidated=true,u.moveToTop(),this._shape?.moveToTop(),this._transformersCache=t.find("Transformer"),this._cacheInvalidated=false;for(let g of this._transformersCache)g.moveToTop();}},this._nodesRemoveHandler=d=>{let u=d.child??d.target,f=_=>{let m=_;(typeof m.getClassName=="function"?m.getClassName():"")==="Transformer"&&_.boundBoxFunc?.(void 0);let v=typeof m.getChildren=="function"?m.getChildren():[];for(let w of v)f(w);};f(u);let p=u;(typeof p.getClassName=="function"?p.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 u=d.target;if((typeof u.getClassName=="function"?u.getClassName():"")!=="Rect")return;let p=u.cornerRadius;if(typeof p!="function")return;let g=p.call(u),_=w=>{u.cornerRadius(w);},m=this._core?.stage,b=m?.scaleX()??1,v=this._minScaleToShow!=null?b>=this._minScaleToShow:false;if(Array.isArray(g)){let w=g.map(x=>{if(v){let N=m?.scaleX()??1,k=m?.scaleY()??1,C=x*(.5*(N+k));return Math.max(0,Math.round(C))/Math.max(1e-6,.5*(N+k))}else return Math.max(0,Math.round(x))});_(w);}else if(typeof g=="number")if(v){let w=m?.scaleX()??1,x=m?.scaleY()??1,N=g*(.5*(w+x)),k=Math.max(0,Math.round(N));_(k/Math.max(1e-6,.5*(w+x)));}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 Kt=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_history");l(this,"_options");l(this,"_isUndoRedoInProgress",false);l(this,"_dragStartStateCache",new Map);l(this,"_isBatchMode",false);l(this,"_batchBuffer",[]);l(this,"_batchCommitTimer",null);l(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}});l(this,"_onDragStart",e=>{if(this._isUndoRedoInProgress)return;let t=e.target;this._debug("dragstart raw target",{targetName:t.name(),targetClassName:t.getClassName(),targetId:t.id()});let n=t.name();if(typeof n=="string"&&n.includes("temp-multi-group")){this._isBatchMode=true,this._batchBuffer=[];let r=t.getChildren();for(let a of r){let h=this._findBaseNodeByKonva(a);if(h){let c=this._captureTransformState(h);this._dragStartStateCache.set(h.id,c),this._debug("dragstart (temp-multi child)",{nodeId:h.id});}}return}let o=this._findBaseNodeByKonva(t);if(o){let s=this._captureTransformState(o);this._dragStartStateCache.set(o.id,s),this._debug("dragstart",{nodeId:o.id,state:s});}else this._debug("dragstart - baseNode not found for target");});l(this,"_onDragEnd",e=>{});l(this,"_onTransformStart",e=>{if(this._isUndoRedoInProgress)return;let t=e.target;this._debug("transformstart raw target",{targetName:t.name(),targetClassName:t.getClassName(),targetId:t.id()});let n=t.name();if(typeof n=="string"&&n.includes("temp-multi-group")){this._isBatchMode=true,this._batchBuffer=[];let r=t.getChildren();for(let a of r){let h=this._findBaseNodeByKonva(a);if(h){let c=this._captureTransformState(h);this._dragStartStateCache.set(h.id,c),this._debug("transformstart (temp-multi child)",{nodeId:h.id});}}return}let o=this._findBaseNodeByKonva(t);if(o){let s=this._captureTransformState(o);this._dragStartStateCache.set(o.id,s),this._debug("transformstart",{nodeId:o.id,state:s});}else this._debug("transformstart - baseNode not found for target");});l(this,"_onTransformEnd",e=>{});l(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();});l(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);});l(this,"_onNodeTransformed",(e,t)=>{if(this._isUndoRedoInProgress){this._debug("node:transformed skipped (undo/redo in progress)",e.id);return}let n=this._dragStartStateCache.get(e.id),o=this._buildAfterState(e,t);if(!n){this._debug("transform - no before state, saving current",e.id),this._dragStartStateCache.set(e.id,o);return}if(this._statesEqual(n,o)){this._debug("transform skipped - no changes",e.id);return}let s={type:"transform",nodeId:e.id,before:n,after:o,timestamp:Date.now()};this._debug("transform recorded",{nodeId:e.id,before:n,after:o,batchMode:this._isBatchMode}),this._isBatchMode?(this._batchBuffer.push(s),this._scheduleBatchCommit()):(this._history.push(s),this._trimHistoryIfNeeded()),this._dragStartStateCache.set(e.id,o);});l(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();});l(this,"_onGroupCreated",(e,t)=>{if(this._isUndoRedoInProgress)return;let n=t.map(r=>this._serializeNode(r)),o=t.map(r=>r.id),s={type:"group",nodeId:e.id,before:{childIds:o,childStates:n},after:this._serializeNode(e),timestamp:Date.now()};this._history.push(s),this._trimHistoryIfNeeded();});l(this,"_onGroupUngrouped",(e,t)=>{if(this._isUndoRedoInProgress)return;let n=this._serializeNode(e),o=t.map(r=>this._serializeNode(r)),s={type:"ungroup",nodeId:e.id,before:n,after:{childStates:o},timestamp:Date.now()};this._history.push(s),this._trimHistoryIfNeeded();});this._history=new Ge;let{target:t=globalThis,ignoreEditableTargets:n=true,maxHistoryLength:o=100}=e;this._options={target:t,ignoreEditableTargets:n,maxHistoryLength:o};}getHistoryManager(){return this._history}startBatch(){this._batchCommitTimer!==null&&(globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=null),this._isBatchMode=true,this._batchBuffer=[],this._debug("batch started");}commitBatch(){this._batchCommitTimer!==null&&(globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=null),this._finishBatch();}isBatchMode(){return this._isBatchMode}onAttach(e){this._core=e,this._options.target.addEventListener("keydown",this._onKeyDown),e.eventBus.on("node:created",this._onNodeCreated),e.eventBus.on("node:removed",this._onNodeRemoved),e.eventBus.on("node:transformed",this._onNodeTransformed),e.eventBus.on("node:zIndexChanged",this._onZIndexChanged),e.eventBus.on("group:created",this._onGroupCreated),e.eventBus.on("group:ungrouped",this._onGroupUngrouped);let t=e.nodes.world,n=e.nodes.layer;t.on("dragstart.history",this._onDragStart),t.on("dragend.history",this._onDragEnd),n.on("transformstart.history",this._onTransformStart),n.on("transformend.history",this._onTransformEnd),this._debug("attached");}onDetach(e){this._options.target.removeEventListener("keydown",this._onKeyDown),e.eventBus.off("node:created",this._onNodeCreated),e.eventBus.off("node:removed",this._onNodeRemoved),e.eventBus.off("node:transformed",this._onNodeTransformed),e.eventBus.off("node:zIndexChanged",this._onZIndexChanged),e.eventBus.off("group:created",this._onGroupCreated),e.eventBus.off("group:ungrouped",this._onGroupUngrouped),e.nodes.world.off(".history"),e.nodes.layer.off(".history"),this._core=void 0,this._dragStartStateCache.clear(),this._debug("detached");}_isEditableTarget(e){if(!e||!(e instanceof HTMLElement))return false;let t=e.tagName.toLowerCase();return !!(t==="input"||t==="textarea"||e.isContentEditable)}_finishBatch(){if(!this._isBatchMode||this._batchBuffer.length===0){this._isBatchMode=false,this._batchBuffer=[];return}let e={type:"batch",nodeId:"",before:null,after:null,timestamp:Date.now(),children:[...this._batchBuffer]};this._debug("batch recorded",{childCount:this._batchBuffer.length}),this._history.push(e),this._trimHistoryIfNeeded(),this._isBatchMode=false,this._batchBuffer=[];}_performUndo(){if(!this._core)return;let e=this._history.undo();if(!e){this._debug("undo","nothing to undo");return}this._isUndoRedoInProgress=true;try{this._applyActionState(e,"before"),this._debug("undo applied",e);}finally{this._isUndoRedoInProgress=false;}this._core.stage.batchDraw();}_performRedo(){if(!this._core)return;let e=this._history.redo();if(!e){this._debug("redo","nothing to redo");return}this._isUndoRedoInProgress=true;try{this._applyActionState(e,"after"),this._debug("redo applied",e);}finally{this._isUndoRedoInProgress=false;}this._core.stage.batchDraw();}_applyActionState(e,t){if(!this._core)return;let n=t==="before"?e.before:e.after;switch(e.type){case "create":if(t==="before"){let o=this._core.nodes.findById(e.nodeId);o&&this._core.nodes.remove(o);}else n&&this._recreateNode(n);break;case "remove":if(t==="before")n&&this._recreateNode(n);else {let o=this._core.nodes.findById(e.nodeId);o&&this._core.nodes.remove(o);}break;case "transform":if(n&&typeof n=="object"){let o=this._core.nodes.findById(e.nodeId);this._debug("transform apply",{nodeId:e.nodeId,nodeFound:!!o,state:n}),o&&this._applyTransformState(o,n);}break;case "zIndex":if(n&&typeof n=="object"&&"zIndex"in n){let o=this._core.nodes.findById(e.nodeId);o&&o.getKonvaNode().zIndex(n.zIndex);}break;case "group":this._applyGroupAction(e,t);break;case "ungroup":this._applyUngroupAction(e,t);break;case "batch":if(e.children){let o=t==="before"?[...e.children].reverse():e.children;for(let s of o)this._applyActionState(s,t);}break;default:this._debug("unknown action type",e.type);}}_applyTransformState(e,t){let n=e.getKonvaNode();this._debug("applyTransformState",{nodeId:e.id,current:{x:n.x(),y:n.y(),rotation:n.rotation(),scaleX:n.scaleX(),scaleY:n.scaleY()},target:t}),typeof t.x=="number"&&n.x(t.x),typeof t.y=="number"&&n.y(t.y),typeof t.width=="number"&&typeof n.width=="function"&&n.width(t.width),typeof t.height=="number"&&typeof n.height=="function"&&n.height(t.height),typeof t.rotation=="number"&&n.rotation(t.rotation),typeof t.scaleX=="number"&&n.scaleX(t.scaleX),typeof t.scaleY=="number"&&n.scaleY(t.scaleY);let o=n;typeof t.cornerRadius=="number"&&typeof o.cornerRadius=="function"&&o.cornerRadius(t.cornerRadius),this._dragStartStateCache.set(e.id,this._captureTransformState(e));}_applyGroupAction(e,t){if(this._core){if(t==="before"){let n=this._core.nodes.findById(e.nodeId);if(n&&e.before){let o=e.before;this._core.nodes.remove(n);for(let s of o.childStates)this._recreateNode(s);}}else if(e.after){let n=e.after;this._recreateNode(n);}}}_applyUngroupAction(e,t){if(this._core)if(t==="before"){if(e.before){let n=e.before;this._recreateNode(n);}}else {let n=this._core.nodes.findById(e.nodeId);if(n&&e.after){let o=e.after;this._core.nodes.remove(n);for(let s of o.childStates)this._recreateNode(s);}}}_recreateNode(e){if(!this._core)return null;let{nodeType:t,attrs:n}=e,{id:o,zIndex:s,...r}=n;try{let a=null;switch(t){case "shape":a=this._core.nodes.addShape(r);break;case "text":a=this._core.nodes.addText(r);break;case "circle":a=this._core.nodes.addCircle(r);break;case "ellipse":a=this._core.nodes.addEllipse(r);break;case "arc":a=this._core.nodes.addArc(r);break;case "star":a=this._core.nodes.addStar(r);break;case "arrow":a=this._core.nodes.addArrow(r);break;case "ring":a=this._core.nodes.addRing(r);break;case "regularPolygon":case "regularpolygon":a=this._core.nodes.addRegularPolygon(r);break;case "image":a=this._core.nodes.addImage(r);break;case "svg":a=this._core.nodes.addSvg(r);break;case "group":{if(a=this._core.nodes.addGroup(r),e.children&&e.children.length>0){let h=a.getKonvaNode();for(let c of e.children){let d=this._recreateNode(c);d&&d.getKonvaNode().moveTo(h);}}break}default:return this._debug("recreateNode",`unknown type: ${t}`),null}if(e.parentId){let h=this._core.nodes.findById(e.parentId);if(h){let c=h.getKonvaNode();a.getKonvaNode().moveTo(c),this._debug("recreateNode - moved to parent",{nodeId:a.id,parentId:e.parentId});}}return this._debug("recreateNode",{nodeType:t,nodeId:a.id,parentId:e.parentId}),a}catch(a){return this._debug("recreateNode error",a),null}}_scheduleBatchCommit(){this._batchCommitTimer!==null&&globalThis.clearTimeout(this._batchCommitTimer),this._batchCommitTimer=globalThis.setTimeout(()=>{this._batchCommitTimer=null,this._finishBatch();},50);}_serializeNode(e){let t=e.getKonvaNode(),n=t.getAttrs(),o=this._getNodeType(t),s={nodeType:o,nodeId:e.id,attrs:{...n}},r=t.getParent();if(r&&this._core){let a=this._findBaseNodeByKonva(r);if(a&&a.id!==e.id){let h=this._core.nodes.world;r!==h&&(s.parentId=a.id);}}if(o==="group"){let h=t.getChildren();s.children=[];for(let c of h){let d=this._findBaseNodeByKonva(c);d&&d.id!==e.id&&s.children.push(this._serializeNode(d));}}return s}_captureTransformState(e){let t=e.getKonvaNode(),n=t.getAbsoluteTransform().decompose(),o={absX:n.x,absY:n.y,absRotation:n.rotation,absScaleX:n.scaleX,absScaleY:n.scaleY,x:t.x(),y:t.y(),rotation:t.rotation(),scaleX:t.scaleX(),scaleY:t.scaleY()};typeof t.width=="function"&&(o.width=t.width()),typeof t.height=="function"&&(o.height=t.height());let s=t;return typeof s.cornerRadius=="function"&&(o.cornerRadius=s.cornerRadius()),o}_buildAfterState(e,t){let n=e.getKonvaNode(),o=t.x??n.x(),s=t.y??n.y(),r=t.rotation??n.rotation(),a=t.scaleX??n.scaleX(),h=t.scaleY??n.scaleY(),c={absX:o,absY:s,absRotation:r,absScaleX:a,absScaleY:h,x:o,y:s,rotation:r,scaleX:a,scaleY:h};typeof n.width=="function"&&(c.width=t.width??n.width()),typeof n.height=="function"&&(c.height=t.height??n.height());let d=n;return typeof d.cornerRadius=="function"&&(c.cornerRadius=d.cornerRadius()),c}_getNodeType(e){let t=e.getClassName();return t==="Image"?e.getAttrs().flowscapeNodeType==="svg"?"svg":"image":{Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Group:"group",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon"}[t]??t.toLowerCase()}_findBaseNodeByKonva(e){if(!this._core)return null;for(let n of this._core.nodes.list())if(n.getKonvaNode()===e)return n;let t=e.getParent();for(;t;){for(let n of this._core.nodes.list())if(n.getKonvaNode()===t)return n;t=t.getParent();}return null}_statesEqual(e,t){let o=["absX","absY","absRotation","absScaleX","absScaleY"];for(let r of o){let a=e[r],h=t[r];if(typeof a=="number"&&typeof h=="number"){if(Math.abs(a-h)>.001)return false}else if(a!==h)return false}let s=["width","height","cornerRadius"];for(let r of s)if(e[r]!==t[r])return false;return true}_trimHistoryIfNeeded(){if(!(this._options.maxHistoryLength<=0))for(;this._history.length>this._options.maxHistoryLength;){this._history.pop(0);break}}_debug(e,t){}};var At=class extends O{constructor(e){super();l(this,"_core");l(this,"_layer");l(this,"_image");l(this,"_src");l(this,"_width");l(this,"_height");l(this,"_opacity");this._src=e.src,this._width=e.width,this._height=e.height,this._opacity=e.opacity??1;}onAttach(e){this._core=e,this._layer=new G__default.default.Layer({name:"logo-layer",listening:false}),this._core.stage.add(this._layer),this._image=new G__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){G__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(),s=e.position(),r={x:Math.floor(t/2),y:Math.floor(n/2)};this._image.scale({x:1/o,y:1/o});let a=this._width,h=this._height;this._image.size({width:a,height:h}),this._image.offset({x:a/2,y:h/2});let c=(r.x-s.x)/o,d=(r.y-s.y)/o;this._image.position({x:c,y:d}),this._image.opacity(this._opacity),this._layer&&this._layer.moveToBottom();}};var pt="flowscape:nodes:",Rt=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_clipboard",null);l(this,"_selectionPlugin");l(this,"_isAltPressed",false);l(this,"_isMouseDown",false);l(this,"_isCameraPanning",false);l(this,"_cloneStartPos",null);l(this,"_clonedNodes",[]);l(this,"_cloneOriginals",[]);l(this,"_cloneDragEventsStarted",false);l(this,"_clonePrevDraggable",new Map);l(this,"_prevCursor",null);l(this,"_isCloneCursorActive",false);l(this,"_doubleCursorCss",null);l(this,"_cloneOriginalsHidden",false);l(this,"_cloneAutoPanRafId",null);l(this,"_cloneAutoPanActive",false);l(this,"_cloneAutoPanEdgePx",40);l(this,"_cloneAutoPanMaxSpeedPx",24);l(this,"_onCameraPanStart",e=>{this._isCameraPanning=true,this._restoreCursor();});l(this,"_onCameraPanEnd",()=>{this._isCameraPanning=false,this._updateCloneCursor();});l(this,"_onPaste",e=>{if(!this._core||this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))return;let n=e.clipboardData?.getData("text/plain")??"";if(!n.startsWith(pt))return;let o=n.slice(pt.length),s=null;try{s=JSON.parse(o);}catch{s=null;}if(!(!s||!Array.isArray(s.nodes)||s.nodes.length===0)&&s.nodes.length>0){e.preventDefault(),e.stopImmediatePropagation(),this._clipboard=s,this._handlePaste();return}});l(this,"_onKeyDown",e=>{if(!this._core)return;if(!this._selectionPlugin){let o=this._core.plugins.list().find(s=>s instanceof xe);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 Ee){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}if(!n&&t&&e.code==="KeyF"){let o=this._getSelectedNodes();if(o.length===0){e.preventDefault();return}e.preventDefault(),this._centerOnSelection(o);return}if(e.key==="Alt"){if(this._isAltPressed=true,this._isCameraPanning){this._restoreCursor();return}this._isMouseDown&&this._clonedNodes.length>0&&this._cloneOriginalsHidden&&(this._cloneOriginals.forEach(o=>{o.node.getKonvaNode().visible(true);}),this._cloneOriginalsHidden=false),this._updateCloneCursor();}}});l(this,"_onKeyUp",e=>{if(e.key==="Alt"){if(this._isAltPressed=false,this._isCameraPanning){this._restoreCursor();return}this._isMouseDown&&this._clonedNodes.length>0&&!this._cloneOriginalsHidden&&(this._cloneOriginals.forEach(t=>{t.node.getKonvaNode().visible(false);}),this._cloneOriginalsHidden=true),this._restoreCursor();}});l(this,"_onMouseDown",e=>{if(!(this._options.ignoreEditableTargets&&this._isEditableTarget(e.target))&&!this._isCameraPanning&&e.button===0&&this._isAltPressed){if(this._isOverCornerRadiusHandle())return;this._isMouseDown=true,this._handleCloneStart(e);}});l(this,"_onMouseUp",e=>{e.button===0&&(this._isMouseDown=false,this._handleCloneEnd());});l(this,"_onMouseMove",e=>{if(this._options.ignoreEditableTargets&&this._isEditableTarget(e.target)){this._restoreCursor();return}if(this._isCameraPanning){this._restoreCursor();return}if(this._isMouseDown&&this._clonedNodes.length>0){this._handleCloneMove(e),this._updateCloneCursor(true);return}this._updateCloneCursor();});let{target:t=globalThis,ignoreEditableTargets:n=true}=e;this._options={target:t,ignoreEditableTargets:n};}_startCloneAutoPanLoop(){if(!this._core||this._cloneAutoPanRafId!=null)return;this._cloneAutoPanActive=true;let e=this._core,t=e.stage,n=e.nodes.world,o=()=>{if(this._cloneAutoPanRafId=null,!this._cloneAutoPanActive||!this._core)return;if(!this._isMouseDown||this._clonedNodes.length===0||!this._cloneStartPos){this._cloneAutoPanRafId=globalThis.requestAnimationFrame(o);return}let s=t.getPointerPosition();if(s){let r=t.width(),a=t.height(),h=this._cloneAutoPanEdgePx,c=Math.max(0,h-s.x),d=Math.max(0,s.x-(r-h)),u=Math.max(0,h-s.y),f=Math.max(0,s.y-(a-h)),p=m=>Math.min(1,m/h),g=this._cloneAutoPanMaxSpeedPx*(p(d)-p(c)),_=this._cloneAutoPanMaxSpeedPx*(p(f)-p(u));if(g!==0||_!==0){n.x(n.x()-g),n.y(n.y()-_);let m=n.position();e.eventBus.emit("camera:pan",{dx:-g,dy:-_,position:{x:m.x,y:m.y}});let v=t.container().getBoundingClientRect();try{this._handleCloneMove(new MouseEvent("mousemove",{bubbles:!0,cancelable:!0,clientX:v.left+s.x,clientY:v.top+s.y}));}catch{}}}this._cloneAutoPanRafId=globalThis.requestAnimationFrame(o);};this._cloneAutoPanRafId=globalThis.requestAnimationFrame(o);}_stopCloneAutoPanLoop(){this._cloneAutoPanActive=false,this._cloneAutoPanRafId!=null&&(globalThis.cancelAnimationFrame(this._cloneAutoPanRafId),this._cloneAutoPanRafId=null);}_getHoveredNodeUnderPointer(){if(!this._core)return null;let e=this._core.stage,t=e.getPointerPosition();if(!t)return null;let n=e.getIntersection(t);if(!n)return null;let o=[];for(let r of this._core.nodes.list()){let a=r.getKonvaNode();if(n===a){o.push(r);continue}let h=a;typeof h.isAncestorOf=="function"&&h.isAncestorOf(n)&&o.push(r);}if(o.length===0)return null;if(o.length===1)return o[0]??null;let s=o[0]??null;if(!s)return null;for(let r of o){if(r===s)continue;let a=r.getKonvaNode(),h=s.getKonvaNode(),c=h,d=a;if(typeof c.isAncestorOf=="function"&&c.isAncestorOf(a)){s=r;continue}typeof d.isAncestorOf=="function"&&d.isAncestorOf(h);}return s}onAttach(e){this._core=e,this._options.target.addEventListener("keydown",this._onKeyDown),this._options.target.addEventListener("paste",this._onPaste),this._options.target.addEventListener("mousedown",this._onMouseDown),this._options.target.addEventListener("mouseup",this._onMouseUp),this._options.target.addEventListener("mousemove",this._onMouseMove),this._options.target.addEventListener("keydown",this._onKeyDown),this._options.target.addEventListener("keyup",this._onKeyUp),e.eventBus.on("camera:panStart",this._onCameraPanStart),e.eventBus.on("camera:panEnd",this._onCameraPanEnd);}onDetach(e){this._options.target.removeEventListener("keydown",this._onKeyDown),this._options.target.removeEventListener("paste",this._onPaste),this._options.target.removeEventListener("mousedown",this._onMouseDown),this._options.target.removeEventListener("mouseup",this._onMouseUp),this._options.target.removeEventListener("mousemove",this._onMouseMove),this._options.target.removeEventListener("keydown",this._onKeyDown),this._options.target.removeEventListener("keyup",this._onKeyUp),e.eventBus.off("camera:panStart",this._onCameraPanStart),e.eventBus.off("camera:panEnd",this._onCameraPanEnd),this._stopCloneAutoPanLoop(),this._core=void 0,this._selectionPlugin=void 0,this._clipboard=null,this._clonedNodes=[],this._cloneStartPos=null,this._restoreCursor();}_updateCloneCursor(e=false){if(!this._core)return;if(this._isCameraPanning){this._restoreCursor();return}if(!this._isAltPressed){this._restoreCursor();return}if(e){let c=this._core.stage.container();this._isCloneCursorActive||(this._prevCursor=c.style.cursor,this._isCloneCursorActive=true),c.style.cursor=this._getDoubleCursorCss();return}let t=this._core.stage,n=t.getPointerPosition();if(!n){this._restoreCursor();return}let o=t.getIntersection(n);if(!o){this._restoreCursor();return}if(this._isOverCornerRadiusHandle()){this._restoreCursor();return}let s=this._core.nodes.layer,r=o,a=false;for(;r;){if(r===s){a=true;break}r=r.getParent();}if(!a){this._restoreCursor();return}let h=t.container();this._isCloneCursorActive||(this._prevCursor=h.style.cursor,this._isCloneCursorActive=true),h.style.cursor=this._getDoubleCursorCss();}_isOverCornerRadiusHandle(){if(!this._core)return false;let e=this._core.stage,t=e.getPointerPosition();if(!t)return false;let n=e.getIntersection(t);if(!n)return false;let o=r=>r&&typeof r.name=="function"&&r.name()||"",s=n;for(;s;){let r=o(s);if(r.startsWith("corner-radius-")||r==="corner-radius-handles-group")return true;s=s.getParent();}return false}_getDoubleCursorCss(){if(this._doubleCursorCss)return this._doubleCursorCss;let t=encodeURIComponent('<svg width="32" height="32" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg"><g filter="url(#filter0_d_8_108)"><path fill-rule="evenodd" clip-rule="evenodd" d="M28.6355 15.5813L14.0108 8.87001L17.4698 24.7135L21.6964 18.4558L28.6355 15.5813Z" fill="white"/><path d="M27.3848 15.5575L21.5049 17.994L21.3663 18.0517L21.2823 18.1757L17.709 23.4657L14.712 9.74208L27.3848 15.5575Z" stroke="white" stroke-miterlimit="16"/></g><g filter="url(#filter1_d_8_108)"><path fill-rule="evenodd" clip-rule="evenodd" d="M27 15.5068L15 10L17.8382 23L21.3062 17.8654L27 15.5068Z" fill="white"/><path d="M25.75 15.4824L21.1152 17.4033L20.9756 17.4609L20.8916 17.5859L18.0771 21.751L15.7012 10.8721L25.75 15.4824Z" stroke="#363B3E" stroke-miterlimit="16"/></g><g filter="url(#filter2_d_8_108)"><path fill-rule="evenodd" clip-rule="evenodd" d="M22 15.5068L10 10L12.8382 23L16.3062 17.8654L22 15.5068Z" fill="#363B3E"/><path d="M10.209 9.5459L22.209 15.0527L23.25 15.5303L22.1914 15.9688L16.6367 18.2695L13.2529 23.2803L12.5986 24.248L12.3496 23.1064L9.51172 10.1064L9.29785 9.12793L10.209 9.5459Z" stroke="white" stroke-miterlimit="16"/></g><defs><filter id="filter0_d_8_108" x="11.0108" y="6.87001" width="20.6247" height="21.8435" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><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"/><feOffset dy="1"/><feGaussianBlur stdDeviation="1.5"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.12 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_8_108"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_8_108" result="shape"/></filter><filter id="filter1_d_8_108" x="12" y="8" width="18" height="19" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><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"/><feOffset dy="1"/><feGaussianBlur stdDeviation="1.5"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_8_108"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_8_108" result="shape"/></filter><filter id="filter2_d_8_108" x="5.59552" y="6.25522" width="19.8216" height="23.2402" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB"><feFlood flood-opacity="0" result="BackgroundImageFix"/><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"/><feOffset dy="1"/><feGaussianBlur stdDeviation="1.5"/><feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.25 0"/><feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_8_108"/><feBlend mode="normal" in="SourceGraphic" in2="effect1_dropShadow_8_108" result="shape"/></filter></defs></svg>');return this._doubleCursorCss=`url("data:image/svg+xml,${t}") 16 16, copy`,this._doubleCursorCss}_restoreCursor(){if(!this._core||!this._isCloneCursorActive)return;let e=this._core.stage.container();e.style.cursor=this._prevCursor??"",this._prevCursor=null,this._isCloneCursorActive=false;}_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(`${pt}${JSON.stringify(this._clipboard)}`);}catch{globalThis.console.error("Failed to copy to clipboard");}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(`${pt}${JSON.stringify(this._clipboard)}`);}catch{globalThis.console.error("Failed to cut to clipboard");}this._deleteNodes(e),this._core&&this._core.eventBus.emit("clipboard:cut",e);}_handlePaste(){if(!this._core||!this._clipboard||this._clipboard.nodes.length===0)return;let e=this._getPastePosition(),t=this._getClipboardCenter(),n=[];for(let o of this._clipboard.nodes){let s=o.position.x-t.x,r=o.position.y-t.y,a=this._deserializeNode(o,{x:e.x+s,y:e.y+r});a&&n.push(a);}n.length>0&&this._core.eventBus.emit("clipboard:paste",n),this._core.nodes.layer.batchDraw();}_detachClonesFromFrame(e){if(!this._core)return;let t=this._core.nodes.list().filter(n=>n instanceof A);if(t.length!==0)for(let n of this._clonedNodes){let o=n.getKonvaNode(),s=o.getParent();if(!s)continue;let r=t.find(u=>u.getContentGroup()===s);if(!r)continue;let h=r.getKonvaNode().getClientRect({skipShadow:true,skipStroke:false});if(e.x>=h.x&&e.x<=h.x+h.width&&e.y>=h.y&&e.y<=h.y+h.height)continue;let d=o.absolutePosition();this._core.nodes.world.add(o),o.absolutePosition({x:d.x,y:d.y});}}_handleDelete(){let e=this._getSelectedNodes();e.length!==0&&this._deleteNodes(e);}_getSelectedNodes(){if(!this._selectionPlugin)return [];let e=this._selectionPlugin._tempMultiGroup;if(e&&typeof e.getChildren=="function"&&this._core){let o=e.getChildren(),s=this._core.nodes.list(),r=new Set;for(let a of o){let h=s.find(c=>c.getKonvaNode()===a);h&&r.add(h);}if(r.size>0)return Array.from(r)}let t=this._selectionPlugin._tempMultiSet;if(t&&t.size>0)return Array.from(t);let n=this._selectionPlugin._selected;return n?[n]:[]}_deleteNodes(e){if(!this._core)return;if(this._selectionPlugin){let n=this._selectionPlugin;typeof n._destroyTempMulti=="function"&&n._destroyTempMulti(),typeof n._clearSelection=="function"&&n._clearSelection();}let t=this._core.plugins.get("HistoryPlugin");e.length>1&&t&&t.startBatch();for(let n of e)this._core.nodes.remove(n);e.length>1&&t&&t.commitBatch();}_serializeNode(e){let t=e.getKonvaNode(),n=t.getAttrs(),o=this._getNodeTypeFromKonva(t),s={x:0,y:0};if(this._core){let p=t.getAbsolutePosition(),_=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(p);s={x:_.x,y:_.y};}let{id:r,image:a,video:h,visible:c,...d}=n,u={type:o,config:d,position:s};if(o==="group"){let p=t.getChildren(),g=[];for(let _ of p){let m=this._serializeKonvaNode(_);m&&g.push(m);}g.length>0&&(u.children=g);}return u}_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 f=e.getAttrs().flowscapeNodeType;f==="svg"?o="svg":f==="gif"?o="gif":f==="video"?o="video":o="image";}let{id:s,image:r,video:a,visible:h,...c}=t,d={type:o,config:c,position:{x:e.x(),y:e.y()}};if(e instanceof G__default.default.Group){let u=e.getChildren(),f=[];for(let p of u){let g=this._serializeKonvaNode(p);g&&f.push(g);}f.length>0&&(d.children=f);}return d}_getNodeTypeFromKonva(e){let t=e.getClassName();if(t==="Image"){let s=e.getAttrs().flowscapeNodeType;return s==="svg"?"svg":s==="gif"?"gif":s==="video"?"video":"image"}return {Rect:"shape",Circle:"circle",Ellipse:"ellipse",Text:"text",Group:"group",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon",Label:"label"}[t]??t.toLowerCase()}_deserializeNode(e,t){if(!this._core)return null;let{zIndex:n,...o}=e.config,s=o.placeholder,{placeholder:r,...a}=o,h={...a,...s?{placeholder:s}:{},x:t.x,y:t.y};try{let c=null;switch(e.type){case "shape":c=this._core.nodes.addShape(h);break;case "text":c=this._core.nodes.addText(h);break;case "circle":c=this._core.nodes.addCircle(h);break;case "ellipse":c=this._core.nodes.addEllipse(h);break;case "arc":c=this._core.nodes.addArc(h);break;case "star":c=this._core.nodes.addStar(h);break;case "arrow":c=this._core.nodes.addArrow(h);break;case "ring":c=this._core.nodes.addRing(h);break;case "regularPolygon":case "regularpolygon":c=this._core.nodes.addRegularPolygon(h);break;case "image":c=this._core.nodes.addImage(h);break;case "svg":c=this._core.nodes.addSvg(h);break;case "gif":c=this._core.nodes.addGif(h);break;case "video":c=this._core.nodes.addVideo(h);break;case "label":return globalThis.console.warn("LabelNode is not supported for copy/paste yet"),null;case "group":{c=this._core.nodes.addGroup(h);let u=c.getKonvaNode();if(e.config.scaleX!==void 0&&u.scaleX(e.config.scaleX),e.config.scaleY!==void 0&&u.scaleY(e.config.scaleY),e.config.rotation!==void 0&&u.rotation(e.config.rotation),e.config.skewX!==void 0&&u.skewX(e.config.skewX),e.config.skewY!==void 0&&u.skewY(e.config.skewY),e.config.offsetX!==void 0&&u.offsetX(e.config.offsetX),e.config.offsetY!==void 0&&u.offsetY(e.config.offsetY),e.children&&e.children.length>0)for(let f of e.children){let p=this._deserializeNode(f,{x:f.position.x,y:f.position.y});if(p){let g=p.getKonvaNode();typeof g.draggable=="function"&&g.draggable(!1),g.moveTo(u);}}break}default:return globalThis.console.warn(`Unknown node type: ${e.type}`),null}let d=c.getKonvaNode();return e.config.scaleX!==void 0&&d.scaleX(e.config.scaleX),e.config.scaleY!==void 0&&d.scaleY(e.config.scaleY),e.config.rotation!==void 0&&d.rotation(e.config.rotation),e.config.skewX!==void 0&&d.skewX(e.config.skewX),e.config.skewY!==void 0&&d.skewY(e.config.skewY),e.config.offsetX!==void 0&&d.offsetX(e.config.offsetX),e.config.offsetY!==void 0&&d.offsetY(e.config.offsetY),c}catch(c){return globalThis.console.error("Failed to deserialize node:",c),null}}_getPastePosition(){if(!this._core)return {x:0,y:0};let t=this._core.stage.getPointerPosition();if(t&&this._isPointerOnScreen(t)){let s=this._core.nodes.world.getAbsoluteTransform().copy().invert().point(t);return {x:s.x,y:s.y}}return this._getScreenCenter()}_isPointerOnScreen(e){if(!this._core)return false;let t=this._core.stage,n=t.width(),o=t.height();return e.x>=0&&e.x<=n&&e.y>=0&&e.y<=o}_getScreenCenter(){if(!this._core)return {x:0,y:0};let e=this._core.stage,t=this._core.nodes.world,n=e.width()/2,o=e.height()/2,r=t.getAbsoluteTransform().copy().invert().point({x:n,y:o});return {x:r.x,y:r.y}}_getClipboardCenter(){if(!this._clipboard||this._clipboard.nodes.length===0)return {x:0,y:0};if(this._clipboard.center)return this._clipboard.center;let e=0,t=0;for(let n of this._clipboard.nodes)e+=n.position.x,t+=n.position.y;return {x:e/this._clipboard.nodes.length,y:t/this._clipboard.nodes.length}}_computeSelectionWorldCenter(e){if(!this._core||e.length===0)return {x:0,y:0};let t=Number.POSITIVE_INFINITY,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let u of e){let p=u.getKonvaNode().getClientRect({skipShadow:true,skipStroke:true});t=Math.min(t,p.x),n=Math.min(n,p.y),o=Math.max(o,p.x+p.width),s=Math.max(s,p.y+p.height);}if(!isFinite(t)||!isFinite(n)||!isFinite(o)||!isFinite(s))return {x:0,y:0};let r=(t+o)/2,a=(n+s)/2,d=this._core.nodes.world.getAbsoluteTransform().copy().invert().point({x:r,y:a});return {x:d.x,y:d.y}}_centerOnSelection(e){if(!this._core||e.length===0)return;let t=this._computeSelectionWorldCenter(e),n=this._core.stage,o=this._core.nodes.world,r=o.getAbsoluteTransform().point({x:t.x,y:t.y}),a={x:n.width()/2,y:n.height()/2},h=a.x-r.x,c=a.y-r.y,d=o.x()+h,u=o.y()+c;o.position({x:d,y:u}),this._core.eventBus.emit("camera:pan",{dx:h,dy:c,position:{x:d,y:u}}),n.batchDraw();}_handleMoveUp(){let e=this._getSelectedNodes();if(e.length!==0){for(let t of e){let n=t.getKonvaNode();if(this._isNodeInsidePermanentGroup(n))continue;let o=n.zIndex();n.moveUp();let s=n.zIndex();this._syncGroupZIndex(n),this._core&&o!==s&&this._core.eventBus.emit("node:zIndexChanged",t,o,s);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}}_handleMoveDown(){let e=this._getSelectedNodes();if(e.length!==0){for(let t=e.length-1;t>=0;t--){let n=e[t];if(!n)continue;let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let s=o.zIndex();o.moveDown();let r=o.zIndex();this._syncGroupZIndex(o),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",n,s,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}}_handleMoveToTop(){let e=this._getSelectedNodes();if(e.length===0)return;let t=[...e].sort((n,o)=>{let s=n.getKonvaNode(),r=o.getKonvaNode();return s.zIndex()-r.zIndex()});for(let n of t){let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let s=o.zIndex();o.moveToTop();let r=o.zIndex();this._syncGroupZIndex(o),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",n,s,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_handleMoveToBottom(){let e=this._getSelectedNodes();if(e.length===0)return;let t=[...e].sort((n,o)=>{let s=n.getKonvaNode();return o.getKonvaNode().zIndex()-s.zIndex()});for(let n of t){let o=n.getKonvaNode();if(this._isNodeInsidePermanentGroup(o))continue;let s=o.zIndex();o.moveToBottom();let r=o.zIndex();this._syncGroupZIndex(o),this._core&&s!==r&&this._core.eventBus.emit("node:zIndexChanged",n,s,r);}this._core&&(this._core.nodes.layer.draw(),this._core.stage.batchDraw());}_isNodeInsidePermanentGroup(e){if(e instanceof G__default.default.Group)return false;let t=e.getParent();return !(!t||!(t instanceof G__default.default.Group)||t===this._core?.nodes.world)}_syncGroupZIndex(e){let t=e.getParent();t&&(e instanceof G__default.default.Group||t instanceof G__default.default.Group&&t.name());}_handleCloneStart(e){if(!this._core||!this._selectionPlugin)return;let t=this._getSelectedNodes(),n=this._getHoveredNodeUnderPointer(),o=n?n.getKonvaNode():null,s=n;if(o&&!(o instanceof G__default.default.Group)&&!t.some(d=>d===n||d.id&&n?.id&&d.id===n.id)){let d=this._core.nodes.list().filter(u=>{let f=u.getKonvaNode();if(!(f instanceof G__default.default.Group))return false;let p=f;return typeof p.isAncestorOf=="function"&&p.isAncestorOf(o)});if(d.length>0){let u=d[0]??null;for(let f of d){if(!u||f===u)continue;let p=f.getKonvaNode(),_=u.getKonvaNode();typeof _.isAncestorOf=="function"&&_.isAncestorOf(p)&&(u=f);}u&&(s=u);}}let r=!!s&&t.some(c=>{if(c===s||c.id&&s.id&&c.id===s.id)return true;let d=c.getKonvaNode(),u=s.getKonvaNode();if(d instanceof G__default.default.Group){let f=d;if(typeof f.isAncestorOf=="function"&&f.isAncestorOf(u))return true}return false}),a=s&&!r?[s]:t;if(a.length===0)return;if(this._cloneOriginals=a.map(c=>{let d=c.getKonvaNode(),u=typeof d.draggable=="function"?d.draggable():false;return typeof d.stopDrag=="function"&&d.stopDrag(),typeof d.draggable=="function"&&d.draggable(false),{node:c,draggable:u}}),this._selectionPlugin.clearSelectionFromAreaLasso(),this._cloneDragEventsStarted=false,this._clonedNodes=a.map(c=>{try{let d=this._serializeNode(c),u=this._deserializeNode(d,d.position),f=c.getKonvaNode(),p=f.getParent(),g=u.getKonvaNode(),_=f.absolutePosition();p&&p!==g.getParent()&&p.add(g),g.absolutePosition({x:_.x,y:_.y});let m=g;return typeof m.visible=="function"&&m.visible(!0),u._originalAbsPos={x:_.x,y:_.y},u}catch{return null}}).filter(c=>c!==null),this._clonePrevDraggable.clear(),!this._isAltPressed&&this._cloneOriginals.length>0){let c=this._cloneOriginals.map(d=>d.node);this._deleteNodes(c);}else this._cloneOriginals.forEach(c=>{c.node.getKonvaNode().visible(true);});this._clonedNodes.forEach(c=>{let d=c.getKonvaNode();if(typeof d.draggable=="function"){let u=d.draggable();this._clonePrevDraggable.set(d,u),d.draggable(true);}});let h=this._core.stage.getPointerPosition();h&&(this._cloneStartPos=h),this._cloneOriginalsHidden=false,this._startCloneAutoPanLoop();}_handleCloneMove(e){if(!this._core||!this._cloneStartPos||this._clonedNodes.length===0)return;let t=this._core.stage.getPointerPosition();if(!t)return;this._detachClonesFromFrame(t),this._cloneOriginals.forEach(r=>{let a=r.node.getKonvaNode();typeof a.stopDrag=="function"&&a.stopDrag();});let n=t.x-this._cloneStartPos.x,o=t.y-this._cloneStartPos.y;this._clonedNodes.forEach(r=>{let a=r.getKonvaNode(),h=a.absolutePosition(),c=r._originalAbsPos??{x:h.x,y:h.y};a.absolutePosition({x:c.x+n,y:c.y+o});});let s=this._core.stage;this._cloneDragEventsStarted||(this._clonedNodes.forEach(r=>{let a=r.getKonvaNode();s.fire("dragstart",{target:a,evt:e});}),this._cloneDragEventsStarted=true),this._clonedNodes.forEach(r=>{let a=r.getKonvaNode();s.fire("dragmove",{target:a,evt:e});}),this._core.nodes.layer.batchDraw();}_handleCloneEnd(){let e=[...this._clonedNodes],t=this._cloneOriginals.map(n=>n.node);if(this._cloneOriginals.forEach(n=>{let o=n.node.getKonvaNode();typeof o.stopDrag=="function"&&o.stopDrag(),typeof o.draggable=="function"&&o.draggable(n.draggable);}),!this._isAltPressed&&t.length>0?this._deleteNodes(t):this._cloneOriginals.forEach(n=>{let o=n.node.getKonvaNode();typeof o.visible=="function"&&o.visible(true);}),this._cloneOriginals=[],this._selectionPlugin&&e.length>0)if(e.length===1){let n=e[0];n&&this._selectionPlugin.selectSingleFromArea(n);}else this._selectionPlugin.getMultiGroupController().ensure(e);if(this._core&&this._cloneDragEventsStarted){let n=this._core.stage;e.forEach(o=>{let s=o.getKonvaNode();n.fire("dragend",{target:s});});}if(this._cloneDragEventsStarted=false,e.forEach(n=>{let o=n.getKonvaNode();if(typeof o.draggable!="function")return;let s=this._clonePrevDraggable.get(o);s!=null&&o.draggable(s);}),this._clonePrevDraggable.clear(),this._core&&e.length>0){let n=this._core;e.forEach(s=>{let r=s.getKonvaNode(),a={};typeof r.x=="function"&&(a.x=r.x()),typeof r.y=="function"&&(a.y=r.y()),n.eventBus.emit("node:transformed",s,a);});let o=n.plugins.get("PersistencePlugin");if(o&&typeof o.save=="function")try{o.save();}catch{globalThis.console.error("Failed to save clone");}}this._cloneStartPos=null,this._clonedNodes=[],this._cloneOriginalsHidden=false,this._stopCloneAutoPanLoop();}};var Sn=["image","video","gif","svg"];function Qt(y){let i=y.getKonvaNode(),e=i.getClassName(),t=i.getAttr("flowscapeNodeType");return t||({Text:"text",Image:"image",Rect:"shape",Circle:"circle",Ellipse:"ellipse",Arc:"arc",Star:"star",Arrow:"arrow",Ring:"ring",RegularPolygon:"regularPolygon",Group:"group"}[e]??"shape")}function Bt(y){return Sn.includes(y)}function ze(y){return typeof y.getContentGroup=="function"}function We(y){return y.getKonvaNode().getClassName()==="Group"&&!ze(y)}function en(){return `blob_${String(Date.now())}_${Math.random().toString(36).substring(2,11)}`}function Tn(y){return y.startsWith("blob:")||y.startsWith("data:")}async function En(y){if(!Tn(y))return null;try{let i=await globalThis.fetch(y);return i.ok?await i.blob():null}catch{return null}}function Pn(y){return new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{let o=t.result.split(",")[1];o?i(o):e(new Error("Failed to extract base64"));},t.onerror=()=>{e(new Error("Failed to convert blob to base64"));},t.readAsDataURL(y);})}function Kn(y,i){let e=globalThis.atob(y),t=new Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return new Blob([new Uint8Array(t)],{type:i})}function gt(y,i,e){let t=y.getKonvaNode(),n=Qt(y),o=t.getAttrs(),s={};for(let[h,c]of Object.entries(o))typeof c=="function"||c instanceof HTMLElement||c instanceof HTMLImageElement||c instanceof HTMLVideoElement||c instanceof HTMLCanvasElement||h==="image"||h==="container"||(s[h]=c);if(Bt(n)){let h=t.scaleX(),c=t.scaleY();(h!==1||c!==1)&&(s.width=t.width()*h,s.height=t.height()*c,s.scaleX=1,s.scaleY=1);}let r={id:y.id,type:n,attrs:s,zIndex:t.zIndex()};if(Bt(n)){let h=o.src;if(h){let c=i.get(h);c||(c=en(),i.set(h,c)),r.blobId=c;}}let a=e.get(y.id);return a&&(r.parentFrameId=a),r}function tn(y,i,e,t){let n=y.getKonvaNode(),o=n.getAttrs(),s={};for(let[u,f]of Object.entries(o))typeof f=="function"||f instanceof HTMLElement||u==="container"||(s[u]=f);let r=y.getRect();s.width=r.width(),s.height=r.height(),s.background=r.fill();let a={id:y.id,type:"frame",attrs:s,zIndex:n.zIndex()},h=y.getContentGroup(),c=[],d=new Map;for(let u of h.getChildren()){let f=false;for(let[,p]of i)if(p.getKonvaNode()===u){t.set(p.id,y.id),We(p)?c.push(_t(p,i,e,t,d)):c.push(gt(p,e,t)),f=true;break}if(!f&&u.getClassName()==="Group"){let p=nn(u,i,e,t);p&&c.push(p);}}return c.length>0&&(a.children=c),a}function nn(y,i,e,t){let n=y.getAttrs(),o={};for(let[c,d]of Object.entries(n))typeof d=="function"||d instanceof HTMLElement||c==="container"||(o[c]=d);let s=n.id??`group_${String(Date.now())}_${Math.random().toString(36).substring(2,11)}`,r={id:s,type:"group",attrs:o,zIndex:y.zIndex()},a=[],h=new Map;for(let c of y.getChildren()){let d=false;for(let[,u]of i)if(u.getKonvaNode()===c){h.set(u.id,s),We(u)?a.push(_t(u,i,e,t,h)):a.push(gt(u,e,t)),d=true;break}if(!d&&c.getClassName()==="Group"){let u=nn(c,i,e,t);u&&a.push(u);}}return a.length>0&&(r.children=a),r}function _t(y,i,e,t,n){let o=y.getKonvaNode(),s=o.getAttrs(),r={};for(let[c,d]of Object.entries(s))typeof d=="function"||d instanceof HTMLElement||c==="container"||(r[c]=d);let a={id:y.id,type:"group",attrs:r,zIndex:o.zIndex()},h=[];for(let c of o.getChildren())for(let[,d]of i)if(d.getKonvaNode()===c){n.set(d.id,y.id),We(d)?h.push(_t(d,i,e,t,n)):ze(d)?h.push(tn(d,i,e,t)):h.push(gt(d,e,t));break}return h.length>0&&(a.children=h),a}function Jt(y,i,e){let{type:t,attrs:n,blobId:o}=i,s=n.src;o&&e.has(o)&&(s=e.get(o));let r={...n,id:i.id};s&&(r.src=s);try{switch(t){case "text":return y.nodes.addText(r);case "image":return y.nodes.addImage(r);case "video":return y.nodes.addVideo(r);case "gif":return y.nodes.addGif(r);case "svg":return y.nodes.addSvg(r);case "circle":return y.nodes.addCircle(r);case "ellipse":return y.nodes.addEllipse(r);case "arc":return y.nodes.addArc(r);case "star":return y.nodes.addStar(r);case "arrow":return y.nodes.addArrow(r);case "ring":return y.nodes.addRing(r);case "regularPolygon":return y.nodes.addRegularPolygon(r);case "group":return y.nodes.addGroup(r);case "frame":return y.nodes.addFrame(r);default:return y.nodes.addShape(r)}}catch(a){return globalThis.console.error(`Failed to create node of type ${t}:`,a),null}}function mt(y,i={}){let e=y.nodes.list(),t=i.blobUrlToId?new Map(i.blobUrlToId):new Map,n=new Map,o=new Map,s=[],r=new Map;for(let d of e)r.set(d.id,d);for(let d of e)if(ze(d)){let u=d,f=u.getContentGroup();for(let p of f.getChildren())for(let[g,_]of r)if(_.getKonvaNode()===p){n.set(g,u.id);break}}for(let d of e)if(We(d)){let u=d.getKonvaNode();for(let f of u.getChildren())for(let[p,g]of r)if(g.getKonvaNode()===f){o.set(p,d.id);break}}for(let d of e)n.has(d.id)||o.has(d.id)||(ze(d)?s.push(tn(d,r,t,n)):We(d)?s.push(_t(d,r,t,n,o)):s.push(gt(d,t,n)));let a=y.nodes.world,h={x:a.x(),y:a.y(),scale:a.scaleX()},c=Array.from(t.values());return {version:1,timestamp:Date.now(),nodes:s,camera:h,blobIds:c}}async function on(y){let i=y.nodes.list(),e=new Map,t=new Map;for(let n of i){let o=Qt(n);if(!Bt(o))continue;let r=n.getKonvaNode().getAttr("src");if(!r||t.has(r))continue;let a=await En(r);if(a){let h=en();t.set(r,h),e.set(h,{id:h,blob:a,originalUrl:r});}}return e}function vt(y,i,e={}){let{blobUrls:t=new Map,clearExisting:n=true}=e;if(n){let c=y.nodes.list();for(let d of [...c])y.nodes.remove(d);}let o=new Map,s=new Map;for(let c of i.nodes){let d=Jt(y,c,t);if(d){o.set(c.id,d),s.set(c.id,c.zIndex);let u=d.getKonvaNode(),f=c.attrs;f.scaleX!==void 0&&u.scaleX(f.scaleX),f.scaleY!==void 0&&u.scaleY(f.scaleY),f.rotation!==void 0&&u.rotation(f.rotation),f.skewX!==void 0&&u.skewX(f.skewX),f.skewY!==void 0&&u.skewY(f.skewY),f.offsetX!==void 0&&u.offsetX(f.offsetX),f.offsetY!==void 0&&u.offsetY(f.offsetY);}}let r=(c,d)=>{if(!c.children)return;let u=[...c.children].sort((f,p)=>f.zIndex-p.zIndex);for(let f of u){let p=Jt(y,f,t);if(p){let g=p.getKonvaNode(),_=f.attrs;_.scaleX!==void 0&&g.scaleX(_.scaleX),_.scaleY!==void 0&&g.scaleY(_.scaleY),_.rotation!==void 0&&g.rotation(_.rotation),_.skewX!==void 0&&g.skewX(_.skewX),_.skewY!==void 0&&g.skewY(_.skewY),_.offsetX!==void 0&&g.offsetX(_.offsetX),_.offsetY!==void 0&&g.offsetY(_.offsetY);let m=f.attrs.x??0,b=f.attrs.y??0;g.remove(),d.add(g),g.x(m),g.y(b),o.set(f.id,p),f.type==="group"&&f.children&&r(f,g);}}};for(let c of i.nodes)if(c.type==="frame"&&c.children){let d=o.get(c.id);if(d&&ze(d)){let f=d.getContentGroup();r(c,f);}}for(let c of i.nodes)if(c.type==="group"&&c.children){let d=o.get(c.id);if(d){let u=d.getKonvaNode();r(c,u);}}let a=[...i.nodes].filter(c=>!c.parentFrameId&&c.type!=="frame").sort((c,d)=>c.zIndex-d.zIndex);for(let c of a){let d=o.get(c.id);d&&d.getKonvaNode().moveToTop();}let h=[...i.nodes].filter(c=>c.type==="frame").sort((c,d)=>c.zIndex-d.zIndex);for(let c of h){let d=o.get(c.id);d&&d.getKonvaNode().moveToTop();}y.camera.setZoom(i.camera.scale),y.nodes.world.position({x:i.camera.x,y:i.camera.y}),y.nodes.layer.batchDraw();}async function Lt(y){let i=mt(y),e=await on(y),t={};for(let[n,o]of e){let s=await Pn(o.blob);t[n]={data:s,mimeType:o.blob.type,originalUrl:o.originalUrl};}return JSON.stringify({...i,embeddedBlobs:t},null,2)}function Dt(y,i,e={}){let t=JSON.parse(i),n=new Map;if(t.embeddedBlobs)for(let[o,s]of Object.entries(t.embeddedBlobs)){let r=Kn(s.data,s.mimeType),a=URL.createObjectURL(r);n.set(o,a);}vt(y,t,{...e,blobUrls:n});}function Ot(y,i){let e=new Map;for(let t of y.blobIds){let n=i.get(t);n&&e.set(t,URL.createObjectURL(n));}return e}function Ue(y){for(let i of y.values())URL.revokeObjectURL(i);y.clear();}var Mn="flowscape-persistence";var ae="canvas",le="blobs",sn=()=>{if(typeof globalThis.indexedDB<"u")return globalThis.indexedDB;throw new Error("IndexedDB is not available in this environment")},Ve=class{constructor(i=Mn){this._dbName=i;l(this,"_db",null);l(this,"_dbPromise",null);}async init(){if(!this._db){if(this._dbPromise){await this._dbPromise;return}this._dbPromise=this._openDatabase(),this._db=await this._dbPromise;}}_openDatabase(){return new Promise((i,e)=>{let t;try{t=sn();}catch(o){e(o instanceof Error?o:new Error(String(o)));return}let n=t.open(this._dbName,1);n.onerror=()=>{e(new Error(`Failed to open IndexedDB: ${n.error?.message??"Unknown error"}`));},n.onsuccess=()=>{i(n.result);},n.onupgradeneeded=o=>{let s=o.target.result;s.objectStoreNames.contains(ae)||s.createObjectStore(ae,{keyPath:"id"}),s.objectStoreNames.contains(le)||s.createObjectStore(le,{keyPath:"id"});};})}_getDb(){if(!this._db)throw new Error("PersistenceStorage not initialized. Call init() first.");return this._db}async saveCanvasState(i,e){let t=this._getDb();return new Promise((n,o)=>{let r=t.transaction([ae],"readwrite").objectStore(ae),a={id:i,state:e,updatedAt:Date.now()},h=r.put(a);h.onerror=()=>{o(new Error(`Failed to save canvas state: ${h.error?.message??"Unknown error"}`));},h.onsuccess=()=>{n();};})}async loadCanvasState(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([ae],"readonly").objectStore(ae).get(i);r.onerror=()=>{n(new Error(`Failed to load canvas state: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t(r.result);};})}async deleteCanvasState(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([ae],"readwrite").objectStore(ae).delete(i);r.onerror=()=>{n(new Error(`Failed to delete canvas state: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t();};})}async listCanvasStates(){let i=this._getDb();return new Promise((e,t)=>{let s=i.transaction([ae],"readonly").objectStore(ae).getAll();s.onerror=()=>{t(new Error(`Failed to list canvas states: ${s.error?.message??"Unknown error"}`));},s.onsuccess=()=>{e(s.result);};})}async saveBlob(i,e,t){let n=this._getDb();return new Promise((o,s)=>{let a=n.transaction([le],"readwrite").objectStore(le),h={id:i,blob:e,mimeType:e.type,originalUrl:t},c=a.put(h);c.onerror=()=>{s(new Error(`Failed to save blob: ${c.error?.message??"Unknown error"}`));},c.onsuccess=()=>{o();};})}async loadBlob(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([le],"readonly").objectStore(le).get(i);r.onerror=()=>{n(new Error(`Failed to load blob: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t(r.result);};})}async deleteBlob(i){let e=this._getDb();return new Promise((t,n)=>{let r=e.transaction([le],"readwrite").objectStore(le).delete(i);r.onerror=()=>{n(new Error(`Failed to delete blob: ${r.error?.message??"Unknown error"}`));},r.onsuccess=()=>{t();};})}async loadBlobs(i){let e=new Map;for(let t of i){let n=await this.loadBlob(t);n&&e.set(t,n);}return e}async saveBlobs(i){for(let[e,t]of i)await this.saveBlob(e,t.blob,t.originalUrl);}async listBlobIds(){let i=this._getDb();return new Promise((e,t)=>{let s=i.transaction([le],"readonly").objectStore(le).getAllKeys();s.onerror=()=>{t(new Error(`Failed to list blob IDs: ${s.error?.message??"Unknown error"}`));},s.onsuccess=()=>{e(s.result);};})}async cleanupUnusedBlobs(i){let e=await this.listBlobIds(),t=0;for(let n of e)i.has(n)||(await this.deleteBlob(n),t++);return t}async clearAll(){let i=this._getDb();return new Promise((e,t)=>{let n=i.transaction([ae,le],"readwrite");n.onerror=()=>{t(new Error(`Failed to clear storage: ${n.error?.message??"Unknown error"}`));},n.oncomplete=()=>{e();},n.objectStore(ae).clear(),n.objectStore(le).clear();})}close(){this._db&&(this._db.close(),this._db=null,this._dbPromise=null);}async deleteDatabase(){return this.close(),new Promise((i,e)=>{let t=sn().deleteDatabase(this._dbName);t.onerror=()=>{e(new Error(`Failed to delete database: ${t.error?.message??"Unknown error"}`));},t.onsuccess=()=>{i();};})}};var It=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_storage");l(this,"_canvasId");l(this,"_debounceMs");l(this,"_autoRestore");l(this,"_debug");l(this,"_saveTimer",null);l(this,"_isRestoring",false);l(this,"_blobUrls",new Map);l(this,"_initialized",false);l(this,"_blobUrlToId",new Map);l(this,"_onNodeCreated",e=>{if(this._isRestoring)return;this._captureBlobFromNode(e);let t=e.getKonvaNode();t.className==="Text"&&t.on("textChange.persistence",this._onTextChange),this._scheduleSave();});l(this,"_onNodeChange",e=>{this._isRestoring||this._scheduleSave();});l(this,"_onClipboardPaste",e=>{if(!this._isRestoring){for(let t of e)this._captureBlobFromNode(t);this._scheduleSave();}});l(this,"_onNodeTransformed",(e,t)=>{this._isRestoring||this._scheduleSave();});l(this,"_onCameraChange",()=>{this._isRestoring||this._scheduleSave();});l(this,"_onKonvaDragEnd",()=>{this._isRestoring||this._scheduleSave();});l(this,"_onKonvaTransformEnd",()=>{this._isRestoring||this._scheduleSave();});l(this,"_onTextChange",()=>{this._isRestoring||(this._log("Text changed, scheduling save"),this._scheduleSave());});this._canvasId=e.canvasId??"default",this._debounceMs=e.debounceMs??300,this._autoRestore=e.autoRestore??true,this._debug=e.debug??false,this._storage=new Ve(e.dbName);}onAttach(e){this._core=e,this._initialize();}onDetach(e){this._unsubscribeFromEvents(e),this._cancelPendingSave(),Ue(this._blobUrls),this._storage.close(),this._core=void 0,this._initialized=false;}async _initialize(){if(this._core)try{if(await this._storage.init(),this._log("Storage initialized"),this._autoRestore)try{await this.restore();}catch(e){e instanceof Error&&this._core.eventBus.emit("persistence:restore:error",{error:e.message});}finally{this._core.showContainer();}this._subscribeToEvents(this._core),this._initialized=!0,this._log("Plugin initialized");}catch(e){globalThis.console.error("[PersistencePlugin] Failed to initialize:",e);}}_subscribeToEvents(e){let t=e.eventBus;t.on("node:created",this._onNodeCreated),t.on("node:removed",this._onNodeChange),t.on("node:transformed",this._onNodeTransformed),t.on("node:zIndexChanged",this._onNodeChange),t.on("group:created",this._onNodeChange),t.on("group:ungrouped",this._onNodeChange),t.on("clipboard:paste",this._onClipboardPaste),t.on("camera:zoom",this._onCameraChange),t.on("camera:setZoom",this._onCameraChange),t.on("camera:pan",this._onCameraChange),t.on("camera:reset",this._onCameraChange),e.nodes.world.on("dragend.persistence",this._onKonvaDragEnd),e.nodes.layer.on("transformend.persistence",this._onKonvaTransformEnd),this._log("Subscribed to events");}_unsubscribeFromEvents(e){let t=e.eventBus;t.off("node:created",this._onNodeCreated),t.off("node:removed",this._onNodeChange),t.off("node:transformed",this._onNodeTransformed),t.off("node:zIndexChanged",this._onNodeChange),t.off("group:created",this._onNodeChange),t.off("group:ungrouped",this._onNodeChange),t.off("clipboard:paste",this._onClipboardPaste),t.off("camera:zoom",this._onCameraChange),t.off("camera:setZoom",this._onCameraChange),t.off("camera:pan",this._onCameraChange),t.off("camera:reset",this._onCameraChange),e.nodes.world.off(".persistence"),e.nodes.layer.off(".persistence"),this._log("Unsubscribed from events");}async _captureBlobFromNode(e){let n=e.getKonvaNode().getAttr("src");if(n?.startsWith("blob:")&&!this._blobUrlToId.has(n))try{let o=await globalThis.fetch(n);if(!o.ok)return;let s=await o.blob(),r=`blob_${String(Date.now())}_${Math.random().toString(36).substring(2,11)}`;await this._storage.saveBlob(r,s,n),this._blobUrlToId.set(n,r),this._log(`Captured blob: ${n} -> ${r}`);}catch(o){this._log(`Failed to capture blob from ${n}: ${String(o)}`);}}_subscribeToTextNodes(){if(!this._core)return;let e=this._core.nodes.list();for(let t of e){let n=t.getKonvaNode();n.className==="Text"&&(n.off("textChange.persistence"),n.on("textChange.persistence",this._onTextChange));}}_scheduleSave(){this._cancelPendingSave(),this._saveTimer=globalThis.setTimeout(()=>{this.save();},this._debounceMs);}_cancelPendingSave(){this._saveTimer&&(globalThis.clearTimeout(this._saveTimer),this._saveTimer=null);}async save(){if(!(!this._core||!this._initialized))try{await this._captureAllBlobUrls();let e=mt(this._core,{blobUrlToId:this._blobUrlToId});await this._storage.saveCanvasState(this._canvasId,JSON.stringify(e));let t=new Set(e.blobIds);await this._storage.cleanupUnusedBlobs(t),this._log("Saved canvas state");}catch(e){globalThis.console.error("[PersistencePlugin] Failed to save:",e);}}async restore(){if(!this._core)return false;try{let e=await this._storage.loadCanvasState(this._canvasId);if(!e)return this._log("No saved state found"),!1;let t=JSON.parse(e.state),n=new Map;for(let o of t.blobIds){let s=await this._storage.loadBlob(o);s&&n.set(o,s.blob);}Ue(this._blobUrls),this._blobUrls=Ot(t,n),this._blobUrlToId.clear();for(let[o,s]of this._blobUrls)this._blobUrlToId.set(s,o);this._isRestoring=!0;try{vt(this._core,t,{blobUrls:this._blobUrls,clearExisting:!0});}finally{this._isRestoring=!1;}return this._subscribeToTextNodes(),this._core.eventBus.emit("camera:pan",{dx:0,dy:0,position:{x:t.camera.x,y:t.camera.y}}),this._log("Restored canvas state"),!0}catch(e){return globalThis.console.error("[PersistencePlugin] Failed to restore:",e),false}}async clear(){try{await this._storage.deleteCanvasState(this._canvasId),await this._storage.clearAll(),Ue(this._blobUrls),this._log("Cleared saved state");}catch(e){globalThis.console.error("[PersistencePlugin] Failed to clear:",e);}}async exportToJSON(){if(!this._core)throw new Error("Plugin not attached to CoreEngine");return Lt(this._core)}importFromJSON(e){if(!this._core)throw new Error("Plugin not attached to CoreEngine");this._isRestoring=true,Dt(this._core,e,{clearExisting:true}),this._isRestoring=false,this._subscribeToTextNodes();let t=JSON.parse(e);this._core.eventBus.emit("camera:pan",{dx:0,dy:0,position:{x:t.camera?.x??0,y:t.camera?.y??0}}),this.save();}async downloadJSON(e="canvas.json"){let t=await this.exportToJSON(),n=new Blob([t],{type:"application/json"}),o=URL.createObjectURL(n),s=globalThis.document.createElement("a");s.href=o,s.download=e,s.click(),URL.revokeObjectURL(o);}uploadJSON(){return new Promise((e,t)=>{let n=globalThis.document.createElement("input");n.type="file",n.accept=".json,application/json",n.onchange=()=>{let o=n.files?.[0];if(!o){e();return}let s=new FileReader;s.onload=()=>{try{let r=s.result;this.importFromJSON(r),e();}catch(r){t(r instanceof Error?r:new Error(String(r)));}},s.onerror=()=>{t(new Error("Failed to read file"));},s.readAsText(o);},n.click();})}async hasSavedState(){return await this._storage.loadCanvasState(this._canvasId)!==null}getStorage(){return this._storage}getCanvasId(){return this._canvasId}async setCanvasId(e){this._canvasId=e,this._autoRestore&&this._initialized&&await this.restore();}_log(e){this._debug&&globalThis.console.log(`[PersistencePlugin] ${e}`);}async _captureAllBlobUrls(){if(!this._core)return;let e=this._core.nodes.list();for(let t of e)await this._captureBlobFromNode(t);}};var ye=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_guidesLayer",null);l(this,"_guides",[]);l(this,"_activeGuide",null);l(this,"_draggingGuide",null);l(this,"_rulerLayerCache",null);l(this,"_updateScheduled",false);l(this,"_dragMoveScheduled",false);l(this,"_batchDrawScheduled",false);let{guideColor:t="#8e3e2c",activeColor:n="#2b83ff",rulerThicknessPx:o=30,snapToGrid:s=true,gridStep:r=1}=e;this._options={guideColor:t,activeColor:n,rulerThicknessPx:o,snapToGrid:s,gridStep:r};}onAttach(e){if(this._core=e,!e.stage.findOne(".ruler-layer"))throw new Error("RulerGuidesPlugin requires RulerPlugin to be added to the CoreEngine first. Please add RulerPlugin before RulerGuidesPlugin.");this._guidesLayer=new G__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 r=n.getPointerPosition();if(!r)return;let a=n.getIntersection(r);a&&(a.name()==="guide-h"||a.name()==="guide-v")||(r.y<=o&&r.x>=o?this._startCreateGuide("h"):r.x<=o&&r.y>=o?this._startCreateGuide("v"):this._setActiveGuide(null));}),n.on("mousemove.ruler-guides",()=>{let r=n.getPointerPosition();if(!r)return;let a=n.getIntersection(r);if(a){let h=a.name();if(h==="guide-h"||h==="guide-v"||h.includes("_anchor")||h.includes("rotater")||a.draggable())return}r.y<=o&&r.x>=o?n.container().style.cursor="ns-resize":r.x<=o&&r.y>=o?n.container().style.cursor="ew-resize":this._draggingGuide||(n.container().style.cursor="default");}),this._rulerLayerCache=e.stage.findOne(".ruler-layer"),e.nodes.world.on("xChange.ruler-guides yChange.ruler-guides scaleXChange.ruler-guides scaleYChange.ruler-guides",()=>{this._scheduleUpdate();}),n.on("resize.ruler-guides",()=>{this._scheduleUpdate();}),e.stage.batchDraw();}onDetach(e){e.stage.off(".ruler-guides"),e.nodes.world.off(".ruler-guides"),this._guidesLayer&&(this._guidesLayer.destroy(),this._guidesLayer=null),this._guides=[],this._activeGuide=null,this._draggingGuide=null;}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=true,globalThis.requestAnimationFrame(()=>{this._updateScheduled=false,this._updateGuidesPositions();}));}_updateGuidesPositions(){if(!this._core||this._guides.length===0)return;let e=this._core.nodes.world,t=e.scaleX(),n=e.x(),o=e.y(),s=this._core.stage.width(),r=this._core.stage.height(),a=[0,0,s,0],h=[0,0,0,r];for(let c of this._guides){let d=c.worldCoord;if(c.name()==="guide-h"){let f=o+d*t;c.position({x:0,y:f}),c.points(a);}else {let f=n+d*t;c.position({x:f,y:0}),c.points(h);}}this._guidesLayer?.batchDraw();}_snapToGrid(e){if(!this._options.snapToGrid)return Math.round(e);let t=this._options.gridStep;return Math.round(e/t)*t}_scheduleBatchDraw(){this._batchDrawScheduled||(this._batchDrawScheduled=true,globalThis.requestAnimationFrame(()=>{this._batchDrawScheduled=false,this._core?.stage.batchDraw();}));}_startCreateGuide(e){if(!this._core||!this._guidesLayer)return;let t=this._core.stage,n=this._core.nodes.world,o=n.scaleX(),s=t.getPointerPosition();if(!s)return;let r=e==="h"?(s.y-n.y())/o:(s.x-n.x())/o,a=this._snapToGrid(r),h=new G__default.default.Line({name:e==="h"?"guide-h":"guide-v",stroke:this._options.guideColor,strokeWidth:1,opacity:1,draggable:true,hitStrokeWidth:8,dragBoundFunc:f=>{if(!this._core)return f;let p=this._core.nodes.world,g=p.scaleX();if(e==="h"){let _=(f.y-p.y())/g,m=this._snapToGrid(_);return {x:0,y:p.y()+m*g}}else {let _=(f.x-p.x())/g,m=this._snapToGrid(_);return {x:p.x()+m*g,y:0}}}});h.worldCoord=a,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 f=h;this._draggingGuide={type:e,line:f},this._setActiveGuide(f),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 f=this._core.nodes.world,p=f.scaleX(),g=h.getAbsolutePosition(),_=e==="h"?(g.y-f.y())/p:(g.x-f.x())/p,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 c=h;this._guidesLayer.add(c),this._guides.push(c),this._setActiveGuide(c),e==="h"?(h.position({x:0,y:n.y()+a*o}),h.points([0,0,t.width(),0])):(h.position({x:n.x()+a*o,y:0}),h.points([0,0,0,t.height()])),this._draggingGuide={type:e,line:c};let d=()=>{if(!this._draggingGuide||!this._core)return;let f=this._core.stage.getPointerPosition();if(!f)return;let p=this._core.nodes.world,g=p.scaleX(),_=e==="h"?(f.y-p.y())/g:(f.x-p.x())/g,m=this._snapToGrid(_);h.worldCoord=m,e==="h"?(h.position({x:0,y:p.y()+m*g}),h.points([0,0,this._core.stage.width(),0])):(h.position({x:p.x()+m*g,y:0}),h.points([0,0,0,this._core.stage.height()])),this._scheduleBatchDraw();},u=()=>{this._draggingGuide=null,this._core&&(this._core.stage.off("mousemove.guide-create"),this._core.stage.off("mouseup.guide-create"));};t.on("mousemove.guide-create",d),t.on("mouseup.guide-create",u),this._scheduleBatchDraw();}_setActiveGuide(e){this._activeGuide&&this._activeGuide!==e&&(this._activeGuide.stroke(this._options.guideColor),this._activeGuide.strokeWidth(1)),this._activeGuide=e,e&&(e.stroke(this._options.activeColor),e.strokeWidth(2)),this._rulerLayerCache&&this._rulerLayerCache.batchDraw(),this._core?.stage.fire("guidesChanged.ruler"),this._scheduleBatchDraw();}getActiveGuide(){return this._activeGuide}getActiveGuideInfo(){if(!this._activeGuide)return null;let e=this._activeGuide.worldCoord;return {type:this._activeGuide.name()==="guide-h"?"h":"v",coord:e}}removeActiveGuide(){this._activeGuide&&(this._activeGuide.destroy(),this._guides=this._guides.filter(e=>e!==this._activeGuide),this._activeGuide=null,this._scheduleBatchDraw());}getGuides(){return [...this._guides]}clearGuides(){this._guides.forEach(e=>e.destroy()),this._guides=[],this._activeGuide=null,this._scheduleBatchDraw();}};var Ae=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_highlightLayer",null);l(this,"_hGroup",null);l(this,"_vGroup",null);l(this,"_hHighlights",[]);l(this,"_vHighlights",[]);l(this,"_updateDebounce",new we);l(this,"_transformersCache",[]);l(this,"_cacheInvalidated",true);let{highlightColor:t="#2b83ff",highlightOpacity:n=.3,rulerThicknessPx:o=30}=e;this._options={highlightColor:t,highlightOpacity:n,rulerThicknessPx:o};}onAttach(e){this._core=e;let t=e.stage.findOne(".ruler-layer");if(!t){globalThis.console.warn("RulerHighlightPlugin: RulerPlugin not found. Please add RulerPlugin before RulerHighlightPlugin. Plugin will not work without RulerPlugin.");return}this._highlightLayer=t;let n=t.find("Group");if(n.length>=2)this._hGroup=n[0],this._vGroup=n[1];else {globalThis.console.warn("RulerHighlightPlugin: Could not find ruler groups");return}e.nodes.world.on("xChange.ruler-highlight yChange.ruler-highlight scaleXChange.ruler-highlight scaleYChange.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("resize.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("transform.ruler-highlight transformend.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("click.ruler-highlight",()=>{this._invalidateCache(),this._scheduleUpdate();}),e.stage.on("dragmove.ruler-highlight",()=>{this._scheduleUpdate();}),e.stage.on("mouseup.ruler-highlight",()=>{this._invalidateCache(),this._scheduleUpdate();}),this._updateHighlights();}onDetach(e){try{e.stage.off(".ruler-highlight"),e.nodes.world.off(".ruler-highlight");}catch{}this._hHighlights.forEach(t=>{try{t.destroy();}catch{}}),this._vHighlights.forEach(t=>{try{t.destroy();}catch{}}),this._hHighlights=[],this._vHighlights=[],this._highlightLayer=null,this._hGroup=null,this._vGroup=null;}_scheduleUpdate(){this._updateDebounce.schedule(()=>{this._updateHighlights();});}_invalidateCache(){this._cacheInvalidated=true;}_updateHighlights(){if(!this._core||!this._highlightLayer)return;for(let g of this._hHighlights)g.destroy();this._hHighlights=[];for(let g of this._vHighlights)g.destroy();this._vHighlights=[];let e=this._getSelectedKonvaNodes();if(e.length===0){this._highlightLayer.batchDraw();return}let t=this._core.stage,n=this._core.nodes.world,o=t.width(),s=t.height(),r=this._options.rulerThicknessPx,a=n.scaleX(),h=n.x(),c=n.y(),d=[],u=[];for(let g of e){let _=g.getClientRect({relativeTo:n}),m=h+_.x*a,b=h+(_.x+_.width)*a,v=c+_.y*a,w=c+(_.y+_.height)*a;if(m<o&&b>r){let x=Math.max(r,m),N=Math.min(o,b);x<N&&d.push({start:x,end:N});}if(v<s&&w>r){let x=Math.max(r,v),N=Math.min(s,w);x<N&&u.push({start:x,end:N});}}let f=this._mergeSegments(d),p=this._mergeSegments(u);if(this._hGroup)for(let g of f){let _=new G__default.default.Rect({x:g.start,y:0,width:g.end-g.start,height:r,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-h"});this._hGroup.add(_),_.setZIndex(1),this._hHighlights.push(_);}if(this._vGroup)for(let g of p){let _=new G__default.default.Rect({x:0,y:g.start,width:r,height:g.end-g.start,fill:this._options.highlightColor,opacity:this._options.highlightOpacity,listening:false,name:"ruler-highlight-v"});this._vGroup.add(_),_.setZIndex(1),this._vHighlights.push(_);}this._highlightLayer.batchDraw();}_collectNodes(e,t){let n=e.getClassName(),o=e.name(),r=["overlay-hit","ruler-","guide-","_anchor","back","rotater"].some(a=>o.includes(a));if(!(n==="Transformer"||n==="Layer"||r))if(n==="Group"){let h=e.getChildren();if(h.length===0)return;for(let c of h)this._collectNodes(c,t);}else t.includes(e)||t.push(e);}_mergeSegments(e){if(e.length===0)return [];let t=e.slice().sort((r,a)=>r.start-a.start),n=t[0];if(!n)return [];let o=[],s={start:n.start,end:n.end};for(let r=1;r<t.length;r++){let a=t[r];a&&(a.start<=s.end+1?s.end=Math.max(s.end,a.end):(o.push(s),s={start:a.start,end:a.end}));}return o.push(s),o}_getSelectedKonvaNodes(){if(!this._core)return [];let e=[];try{this._cacheInvalidated&&(this._transformersCache=this._core.stage.find("Transformer"),this._cacheInvalidated=!1);for(let n of this._transformersCache){let o=n.nodes();for(let s of o)e.includes(s)||e.push(s);}}catch{}let t=[];for(let n of e)this._collectNodes(n,t);return t}update(){this._updateHighlights();}};var Re=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_visible",true);l(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 ye);return e&&"getActiveGuide"in e&&"removeActiveGuide"in e&&e.getActiveGuide.call(e)?(e.removeActiveGuide.call(e),true):false}};var Gt=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_layer",null);l(this,"_hGroup");l(this,"_vGroup");l(this,"_hBg");l(this,"_vBg");l(this,"_hTicksShape");l(this,"_vTicksShape");l(this,"_hBorder");l(this,"_vBorder");l(this,"_redrawScheduled",false);l(this,"_lastRedrawTime",0);l(this,"_redrawThrottleMs",16);l(this,"_panThrottleMs",32);l(this,"_cachedActiveGuide",null);l(this,"_cacheInvalidated",true);l(this,"_stepsCache",new Map);let{thicknessPx:t=30,fontFamily:n="Inter, Calibri, Arial, sans-serif",fontSizePx:o=10,color:s="#8c8c8c",bgColor:r="#2c2c2c",borderColor:a="#1f1f1f",enabled:h=true}=e;this._options={thicknessPx:t,fontFamily:n,fontSizePx:o,color:s,bgColor:r,borderColor:a,enabled:h};}_calculateNiceStep(e){if(!isFinite(e)||e<=0)return 1;let t=Math.pow(10,Math.floor(Math.log10(e))),n=e/t,o;return n<=1?o=1:n<=2?o=2:n<=5?o=5:o=10,o*t}_formatNumber(e){return Math.round(e).toString()}_getStepsConfig(e){let t=this._stepsCache.get(e);if(t)return t;let n=this._options.thicknessPx,s=50/e,r=this._calculateNiceStep(s);r<1&&(r=1);let a=r*e,h,c,d,u;a>=60?(h=r*10,c=r*5,d=r,u=r):a>=40?(h=r*10,c=r*5,d=r*5,u=r):(h=r*10,c=r*5,d=r*10,u=r);let f={step:r,stepPx:a,majorStep:h,mediumStep:c,labelStep:d,drawStep:u,drawStepEpsilon:u*.01,majorTickLength:n*.6,mediumTickLength:n*.4,minorTickLength:n*.25,fontString:`${String(this._options.fontSizePx)}px ${this._options.fontFamily}`};if(this._stepsCache.size>10){let p=this._stepsCache.keys().next().value;p!==void 0&&this._stepsCache.delete(p);}return this._stepsCache.set(e,f),f}onAttach(e){this._core=e,this._layer=new G__default.default.Layer({name:"ruler-layer",listening:true}),this._options.enabled&&e.stage.add(this._layer),this._hGroup=new G__default.default.Group({listening:true}),this._vGroup=new G__default.default.Group({listening:true}),this._layer.add(this._hGroup),this._layer.add(this._vGroup),this._hBg=new G__default.default.Rect({fill:this._options.bgColor,listening:true,name:"ruler-h-bg"}),this._vBg=new G__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 G__default.default.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._vBorder=new G__default.default.Line({stroke:this._options.borderColor,strokeWidth:1,listening:false}),this._hGroup.add(this._hBorder),this._vGroup.add(this._vBorder),this._hTicksShape=new G__default.default.Shape({listening:false,sceneFunc:o=>{let s=this._getActiveGuideInfo();this._drawHorizontalRuler(o,s);}}),this._hGroup.add(this._hTicksShape),this._vTicksShape=new G__default.default.Shape({listening:false,sceneFunc:o=>{let s=this._getActiveGuideInfo();this._drawVerticalRuler(o,s);}}),this._vGroup.add(this._vTicksShape);let t=e.stage,n=e.nodes.world;t.on("resize.ruler",()=>{this._scheduleRedraw();}),n.on("xChange.ruler yChange.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw(true);}),n.on("scaleXChange.ruler scaleYChange.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw(false);}),t.on("guidesChanged.ruler",()=>{this._invalidateGuideCache(),this._scheduleRedraw();}),this._redraw(),e.stage.batchDraw();}onDetach(e){e.stage.off(".ruler"),e.nodes.world.off(".ruler"),this._layer&&(this._layer.destroy(),this._layer=null);}_getActiveGuideInfo(){if(!this._core)return null;if(!this._cacheInvalidated)return this._cachedActiveGuide;let e=this._core.stage.findOne(".guides-layer");if(!e)return this._cachedActiveGuide=null,this._cacheInvalidated=false,null;let t=e.find("Line");for(let n of t){let o=n;if(o.strokeWidth()===2){let s=o.worldCoord,r=o.name()==="guide-h"?"h":"v";return this._cachedActiveGuide={type:r,coord:s},this._cacheInvalidated=false,this._cachedActiveGuide}}return this._cachedActiveGuide=null,this._cacheInvalidated=false,null}_invalidateGuideCache(){this._cacheInvalidated=true;}_drawRuler(e,t,n){if(!this._core)return;let o=this._core.stage,s=this._core.nodes.world,r=s.scaleX()||1e-9,a=this._options.thicknessPx,h=t==="h",c=h?o.width():o.height(),d=h?s.x():s.y(),u=n?.type===(h?"v":"h")?n.coord:null,f=this._getStepsConfig(r),{majorStep:p,mediumStep:g,labelStep:_,drawStep:m,drawStepEpsilon:b,majorTickLength:v,mediumTickLength:w,minorTickLength:x,fontString:N}=f;e.save();let k=-d/r,C=Math.floor(k/m)*m,S=[],T=[],K=[],L=[],R=null;for(let P=C;;P+=m){let I=d+P*r;if(I>c)break;if(I<0)continue;if(u!==null&&Math.abs(P-u)<b){R=I,L.push({pos:I,text:this._formatNumber(P)});continue}let U=Math.abs(P%p)<b,J=!U&&Math.abs(P%g)<b;U?S.push(I):J?T.push(I):K.push(I),Math.abs(P%_)<b&&L.push({pos:I,text:this._formatNumber(P)});}if(K.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.4,e.lineWidth=1,e.beginPath();for(let P of K)h?(e.moveTo(P,a),e.lineTo(P,a-x)):(e.moveTo(a,P),e.lineTo(a-x,P));e.stroke();}if(T.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.6,e.lineWidth=1,e.beginPath();for(let P of T)h?(e.moveTo(P,a),e.lineTo(P,a-w)):(e.moveTo(a,P),e.lineTo(a-w,P));e.stroke();}if(S.length>0){e.strokeStyle=this._options.color,e.globalAlpha=.9,e.lineWidth=1,e.beginPath();for(let P of S)h?(e.moveTo(P,a),e.lineTo(P,a-v)):(e.moveTo(a,P),e.lineTo(a-v,P));e.stroke();}if(R!==null&&(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(R,a),e.lineTo(R,a-v)):(e.moveTo(a,R),e.lineTo(a-v,R)),e.stroke()),L.length>0){e.font=N,e.textBaseline="top",e.textAlign="left";for(let P of L){let I=P.pos===R;if(e.globalAlpha=I?1:.9,e.fillStyle=I?"#ff8c00":this._options.color,h)e.fillText(P.text,P.pos+4,4);else {let U=P.pos+4;e.setTransform(0,-1,1,0,4,U),e.fillText(P.text,0,0),e.setTransform(1,0,0,1,0,0);}}}if(u!==null){let P=d+u*r;if(P>=0&&P<=c&&!(Math.abs(u%m)<b))if(e.strokeStyle="#ff8c00",e.globalAlpha=1,e.lineWidth=2,e.beginPath(),h?(e.moveTo(P,a),e.lineTo(P,a-v)):(e.moveTo(a,P),e.lineTo(a-v,P)),e.stroke(),e.fillStyle="#ff8c00",e.font=N,e.textBaseline="top",e.textAlign="left",h)e.fillText(this._formatNumber(u),P+4,4);else {let U=P+4;e.setTransform(0,-1,1,0,4,U),e.fillText(this._formatNumber(u),0,0),e.setTransform(1,0,0,1,0,0);}}e.restore();}_drawHorizontalRuler(e,t){this._drawRuler(e,"h",t);}_drawVerticalRuler(e,t){this._drawRuler(e,"v",t);}_redraw(){if(!this._core||!this._layer)return;let e=this._core.stage,t=e.width(),n=e.height(),o=this._options.thicknessPx;this._hBg&&this._hBg.size({width:t,height:o}),this._vBg&&this._vBg.size({width:o,height:n}),this._hBorder&&this._hBorder.points([0,o,t,o]),this._vBorder&&this._vBorder.points([o,0,o,n]),this._layer.batchDraw();}_scheduleRedraw(e=false){if(!this._core||!this._layer)return;let n=globalThis.performance.now()-this._lastRedrawTime;if(this._redrawScheduled)return;this._redrawScheduled=true;let o=e?this._panThrottleMs:this._redrawThrottleMs;if(n>=o)globalThis.requestAnimationFrame(()=>{this._redrawScheduled=false,this._lastRedrawTime=globalThis.performance.now(),this._redraw();});else {let s=o-n;globalThis.setTimeout(()=>{globalThis.requestAnimationFrame(()=>{this._redrawScheduled=false,this._lastRedrawTime=globalThis.performance.now(),this._redraw();});},s);}}show(){this._core&&this._layer&&(this._core.stage.add(this._layer),this._layer.moveToTop(),this._redraw(),this._core.stage.batchDraw());}hide(){this._layer?.getStage()&&(this._layer.remove(),this._core?.stage.batchDraw());}toggle(){this._layer?.getStage()?this.hide():this.show();}isVisible(){return !!this._layer?.getStage()}};var Ht=class extends O{constructor(e={}){super();l(this,"_core");l(this,"_options");l(this,"_layer",null);l(this,"_maxGuideDistancePx",1200);l(this,"_dragMoveHandler",null);l(this,"_dragEndHandler",null);l(this,"_nodesAddHandler",null);l(this,"_nodesRemoveHandler",null);let{guidelineColor:t="#8e3e2c",guidelineWidth:n=1,guidelineDash:o=[0,0],thresholdPx:s=8}=e;this._options={guidelineColor:t,guidelineWidth:n,guidelineDash:o,thresholdPx:s};}_applyGapSnappingForDrag(e,t,n){if(!this._core)return;let o=this._options.thresholdPx,s=e.getClientRect({skipShadow:true,skipStroke:false}),r=n.x-t.x,a=n.y-t.y,h={x:s.x+r,y:s.y+a,width:s.width,height:s.height},c=this._collectOtherNodeBoxes(e),d=o+1,u=0,f=o+1,p=0;for(let g of c){let _=g.box;if(!(h.y>_.y+_.height||h.y+h.height<_.y)){let v=h.x,w=h.x+h.width,x=_.x,N=_.x+_.width;if(x>=w){let k=x-w;k>0&&k<d&&(d=k,u=k);}if(N<=v){let k=v-N;k>0&&k<d&&(d=k,u=-k);}}if(!(h.x>_.x+_.width||h.x+h.width<_.x)){let v=h.y,w=h.y+h.height,x=_.y,N=_.y+_.height;if(x>=w){let k=x-w;k>0&&k<f&&(f=k,p=k);}if(N<=v){let k=v-N;k>0&&k<f&&(f=k,p=-k);}}}d<=o&&(n.x+=u),f<=o&&(n.y+=p);}onAttach(e){this._core=e;let t=new G__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 r=o.child??o.target;this._walkAttachTransformers(r);},this._nodesRemoveHandler=o=>{let r=o.child??o.target;this._walkDetachTransformers(r);},n.on("add.snap-guides",this._nodesAddHandler),n.on("remove.snap-guides",this._nodesRemoveHandler),this._attachExistingTransformers();}onDetach(e){e.stage.off(".snap-guides"),e.nodes.layer.off(".snap-guides");let t=e.nodes.layer.find("Transformer");for(let n of t)n.off(".snap-guides-resize");this._layer&&(this._layer.destroy(),this._layer=null),this._dragMoveHandler=null,this._dragEndHandler=null,this._nodesAddHandler=null,this._nodesRemoveHandler=null,this._core=void 0;}_onDragMove(e){if(!this._core||!this._layer)return;if(this._isVisualLinesShouldCleared(e.target)){this._clearGuides();return}let t=this._core.stage,n=this._core.nodes.layer,o=e.target;if(o===t||o instanceof G__default.default.Layer)return;let s=o,r=false;for(;s;){if(s===n){r=true;break}s=s.getParent();}if(!r)return;let a=o;if(typeof a.draggable=="function"&&!a.draggable())return;this._clearGuides();let h=this._getLineGuideStops(o),c=this._getObjectSnappingEdges(o),d=this._getGuides(h,c);if(!d.length)return;let u=o.absolutePosition(),f={...u};for(let p of d)p.orientation==="V"?f.x=p.lineGuide+p.offset:f.y=p.lineGuide+p.offset;this._applyGapSnappingForDrag(o,u,f),o.absolutePosition(f),this._drawDragGuides(o);}_clearGuides(){if(!this._layer)return;let e=this._layer.find(".snap-guid-line");for(let t of e)t.destroy();this._layer.batchDraw();}_drawDragGuides(e){if(!this._core||!this._layer)return;let t=e.getClientRect({skipShadow:true,skipStroke:false}),n=this._buildDragRays(t),o=this._collectOtherNodeBoxes(e);if(!o.length)return;let s=16;for(let r of n){let a=[];for(let f of o){let p=this._intersectRayWithBox(r.origin,r.dir,f.box);p&&a.push({...p,box:f.box});}if(!a.length)continue;a.sort((f,p)=>f.tEnter-p.tEnter);let h=a.slice(0,s);if(!h.length)continue;let c=0;for(let f of h)f.tExit>c&&(c=f.tExit);if(c<=0)continue;let d;r.dir==="right"?d=[0,0,c,0]:r.dir==="left"?d=[0,0,-c,0]:r.dir==="down"?d=[0,0,0,c]:d=[0,0,0,-c];let u=new G__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(u),u.absolutePosition({x:r.origin.x,y:r.origin.y});for(let f of h){let p=f.tEnter,g=f.tExit,_=this._pointOnRay(r.origin,r.dir,p),m=this._pointOnRay(r.origin,r.dir,g),b=f.box,v=0,w=0;if(r.dir==="right"){let x=t.x+t.width,N=b.x,k=b.x+b.width;v=N-x,w=k-x;}else if(r.dir==="left"){let x=t.x,N=b.x,k=b.x+b.width;v=x-k,w=x-N;}else if(r.dir==="down"){let x=t.y+t.height,N=b.y,k=b.y+b.height;v=N-x,w=k-x;}else {let x=t.y,N=b.y,k=b.y+b.height;v=x-k,w=x-N;}v=Math.max(0,v),w=Math.max(0,w),this._drawRayMarkerWithLabel(_.x,_.y,v,r.dir),this._drawRayMarkerWithLabel(m.x,m.y,w,r.dir);}}this._layer.batchDraw();}_pointOnRay(e,t,n){return t==="right"?{x:e.x+n,y:e.y}:t==="left"?{x:e.x-n,y:e.y}:t==="down"?{x:e.x,y:e.y+n}:{x:e.x,y:e.y-n}}_drawRayMarkerWithLabel(e,t,n,o){if(!this._layer)return;let s=4,r=new G__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 a=new G__default.default.Line({points:[-s,s,s,-s],stroke:this._options.guidelineColor,strokeWidth:1,name:"snap-guid-line",listening:false});this._layer.add(a),a.absolutePosition({x:e,y:t});}_buildDragRays(e){let t=[],n=e.x+e.width/2,o=e.y+e.height/2;t.push({origin:{x:n,y:o},dir:"up"},{origin:{x:n,y:o},dir:"down"},{origin:{x:n,y:o},dir:"left"},{origin:{x:n,y:o},dir:"right"}),t.push({origin:{x:n,y:e.y},dir:"up"},{origin:{x:n,y:e.y+e.height},dir:"down"},{origin:{x:e.x,y:o},dir:"left"},{origin:{x:e.x+e.width,y:o},dir:"right"});let s={x:e.x,y:e.y},r={x:e.x+e.width,y:e.y},a={x:e.x+e.width,y:e.y+e.height},h={x:e.x,y:e.y+e.height};return t.push({origin:s,dir:"up"},{origin:s,dir:"left"},{origin:r,dir:"up"},{origin:r,dir:"right"},{origin:a,dir:"down"},{origin:a,dir:"right"},{origin:h,dir:"down"},{origin:h,dir:"left"}),t}_collectOtherNodeBoxes(e){let t=[];if(!this._core)return t;let n=this._core.nodes.list(),o=e.getClientRect({skipShadow:true,skipStroke:false}),s=o.x+o.width/2,r=o.y+o.height/2,a=this._core.nodes.world;for(let h of n){let c=h.getKonvaNode();if(c===e)continue;let d=c,u=e;if(typeof d.isAncestorOf=="function"&&d.isAncestorOf(e)||typeof u.isAncestorOf=="function"&&u.isAncestorOf(c))continue;let f=c.getParent(),p=e.getParent();if(f&&p&&f===p&&f!==a&&f instanceof G__default.default.Group)continue;let g=c.getClientRect({skipShadow:true,skipStroke:false}),_=g.x+g.width/2,m=g.y+g.height/2,b=_-s,v=m-r;Math.sqrt(b*b+v*v)>this._maxGuideDistancePx||t.push({node:c,box:{x:g.x,y:g.y,width:g.width,height:g.height}});}return t}_intersectRayWithBox(e,t,n){let o=e.x,s=e.y,r=n.x,a=n.y,h=n.x+n.width,c=n.y+n.height;if(t==="right"||t==="left"){if(s<a||s>c)return null;if(t==="right"){if(h<=o)return null;let d=Math.max(r,o),u=h,f=d-o,p=u-o;return p<=0||p<=f?null:{tEnter:f,tExit:p}}else {if(r>=o)return null;let d=Math.min(h,o),u=r,f=o-d,p=o-u;return p<=0||p<=f?null:{tEnter:f,tExit:p}}}if(o<r||o>h)return null;if(t==="down"){if(c<=s)return null;let d=Math.max(a,s),u=c,f=d-s,p=u-s;return p<=0||p<=f?null:{tEnter:f,tExit:p}}else {if(a>=s)return null;let d=Math.min(c,s),u=a,f=s-d,p=s-u;return p<=0||p<=f?null:{tEnter:f,tExit:p}}}_getLineGuideStops(e){if(!this._core)return {vertical:[],horizontal:[]};let t=this._core.stage,n=[0,t.width()/2,t.width()],o=[0,t.height()/2,t.height()],s=this._core.nodes.list();for(let r of s){let a=r.getKonvaNode();if(a===e)continue;let h=a,c=e;if(typeof h.isAncestorOf=="function"&&h.isAncestorOf(e)||typeof c.isAncestorOf=="function"&&c.isAncestorOf(a))continue;let d=a.getClientRect({skipShadow:true,skipStroke:false});n.push(d.x,d.x+d.width,d.x+d.width/2),o.push(d.y,d.y+d.height,d.y+d.height/2);}return {vertical:n,horizontal:o}}_getObjectSnappingEdges(e){let t=e.getClientRect({skipShadow:true,skipStroke:false}),n=e.absolutePosition();return {vertical:[{guide:Math.round(t.x),offset:Math.round(n.x-t.x),snap:"start"},{guide:Math.round(t.x+t.width/2),offset:Math.round(n.x-t.x-t.width/2),snap:"center"},{guide:Math.round(t.x+t.width),offset:Math.round(n.x-t.x-t.width),snap:"end"}],horizontal:[{guide:Math.round(t.y),offset:Math.round(n.y-t.y),snap:"start"},{guide:Math.round(t.y+t.height/2),offset:Math.round(n.y-t.y-t.height/2),snap:"center"},{guide:Math.round(t.y+t.height),offset:Math.round(n.y-t.y-t.height),snap:"end"}]}}_getGuides(e,t){let n=[],o=[],s=this._options.thresholdPx;for(let a of e.vertical)for(let h of t.vertical){let c=Math.abs(a-h.guide);c<s&&n.push({lineGuide:a,diff:c,snap:h.snap,offset:h.offset});}for(let a of e.horizontal)for(let h of t.horizontal){let c=Math.abs(a-h.guide);c<s&&o.push({lineGuide:a,diff:c,snap:h.snap,offset:h.offset});}let r=[];if(n.length>0){let[a]=[...n].sort((h,c)=>h.diff-c.diff);a&&r.push({lineGuide:a.lineGuide,offset:a.offset,orientation:"V",snap:a.snap});}if(o.length>0){let[a]=[...o].sort((h,c)=>h.diff-c.diff);a&&r.push({lineGuide:a.lineGuide,offset:a.offset,orientation:"H",snap:a.snap});}return r}_attachExistingTransformers(){if(!this._core)return;let e=this._core.nodes.layer;this._walkAttachTransformers(e);}_walkAttachTransformers(e){this._attachTransformer(e);let t=e,n=typeof t.getChildren=="function"?t.getChildren():[];for(let o of n)this._walkAttachTransformers(o);}_attachTransformer(e){let t=e;if((typeof t.getClassName=="function"?t.getClassName():"")!=="Transformer")return;let o=e;o.off(".snap-guides-resize"),o.on("transform.snap-guides-resize",()=>{this._handleTransformerTransform(o);}),o.on("transformend.snap-guides-resize",()=>{this._clearGuides();});}_walkDetachTransformers(e){let t=e;(typeof t.getClassName=="function"?t.getClassName():"")==="Transformer"&&e.off(".snap-guides-resize");let o=typeof t.getChildren=="function"?t.getChildren():[];for(let s of o)this._walkDetachTransformers(s);}_handleTransformerTransform(e){if(!this._core||!this._layer)return;if((typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"")==="rotater"||this._isVisualLinesShouldCleared(e)){this._clearGuides();return}let o=(typeof e.nodes=="function"?e.nodes():[])[0];if(!o)return;let s=o,r=typeof s.getLayer=="function"?s.getLayer():null;if(!r||r!==this._core.nodes.layer)return;this._clearGuides();let a=this._getLineGuideStops(o),h=this._getObjectSnappingEdges(o),c=this._getGuides(a,h);if(!c.length)return;let d=o.absolutePosition();for(let u of c)u.orientation==="V"?d.x=u.lineGuide+u.offset:d.y=u.lineGuide+u.offset;o.absolutePosition(d),this._drawResizeGuides(e,o,c);}_drawResizeGuides(e,t,n){if(!this._core||!this._layer)return;let o=typeof e.getActiveAnchor=="function"?e.getActiveAnchor():"";if(!o)return;let s=t.getClientRect({skipShadow:true,skipStroke:false}),r=n.some(f=>f.orientation==="V"),a=n.some(f=>f.orientation==="H"),c=this._buildResizeRays(o,s).filter(f=>!((f.dir==="left"||f.dir==="right")&&!a||(f.dir==="up"||f.dir==="down")&&!r));if(!c.length)return;let d=this._collectOtherNodeBoxes(t);if(!d.length)return;let u=16;for(let f of c){let p=[];for(let v of d){let w=this._intersectRayWithBox(f.origin,f.dir,v.box);w&&p.push({...w,box:v.box});}if(!p.length)continue;p.sort((v,w)=>v.tEnter-w.tEnter);let g=p.slice(0,u);if(!g.length)continue;let _=0;for(let v of g)v.tExit>_&&(_=v.tExit);if(_<=0)continue;let m;f.dir==="right"?m=[0,0,_,0]:f.dir==="left"?m=[0,0,-_,0]:f.dir==="down"?m=[0,0,0,_]:m=[0,0,0,-_];let b=new G__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(b),b.absolutePosition({x:f.origin.x,y:f.origin.y});for(let v of g){let w=v.tEnter,x=v.tExit,N=this._pointOnRay(f.origin,f.dir,w),k=this._pointOnRay(f.origin,f.dir,x),C=v.box,S=0,T=0;if(f.dir==="right"){let K=s.x+s.width,L=C.x,R=C.x+C.width;S=L-K,T=R-K;}else if(f.dir==="left"){let K=s.x,L=C.x,R=C.x+C.width;S=K-R,T=K-L;}else if(f.dir==="down"){let K=s.y+s.height,L=C.y,R=C.y+C.height;S=L-K,T=R-K;}else {let K=s.y,L=C.y,R=C.y+C.height;S=K-R,T=K-L;}S=Math.max(0,S),T=Math.max(0,T),this._drawRayMarkerWithLabel(N.x,N.y,S,f.dir),this._drawRayMarkerWithLabel(k.x,k.y,T,f.dir);}}this._layer.batchDraw();}_buildResizeRays(e,t){let n={x:t.x,y:t.y},o={x:t.x+t.width,y:t.y},s={x:t.x+t.width,y:t.y+t.height},r={x:t.x,y:t.y+t.height},a=[];switch(e){case "top-left":a.push({origin:n,dir:"up"},{origin:n,dir:"left"});break;case "top-right":a.push({origin:o,dir:"up"},{origin:o,dir:"right"});break;case "bottom-right":a.push({origin:s,dir:"down"},{origin:s,dir:"right"});break;case "bottom-left":a.push({origin:r,dir:"down"},{origin:r,dir:"left"});break;case "middle-left":a.push({origin:n,dir:"up"},{origin:n,dir:"left"});break;case "middle-right":a.push({origin:o,dir:"up"},{origin:o,dir:"right"});break;case "top-center":a.push({origin:n,dir:"up"},{origin:n,dir:"left"});break;case "bottom-center":a.push({origin:r,dir:"down"},{origin:r,dir:"left"});break;}return a}_isVisualLinesShouldCleared(e){let t=e;for(;t;){let n=t,o=typeof n.name=="function"?n.name():"";if(o.startsWith("rotate-")||o==="rotate-handles-group"||o.startsWith("corner-radius-")||o==="corner-radius-handles-group")return true;t=t.getParent();}return false}};var Ft=class extends he{constructor(e={}){super();l(this,"mode");l(this,"intensity");l(this,"pixelRatio");l(this,"nodes",new WeakMap);this.mode=e.mode??"sepia";let t=e.intensity??.4;this.intensity=Math.max(0,Math.min(1,t)),this.pixelRatio=e.pixelRatio??3;}onAttach(e){if(this.nodes.has(e))return;let t=e.getKonvaNode(),n=t.filters(),o=Array.isArray(n)?n:[],s=t,r=typeof s.red=="function"?s.red():0,a=typeof s.green=="function"?s.green():0,h=typeof s.blue=="function"?s.blue():0,c=typeof s.alpha=="function"?s.alpha():1,d=typeof s.hue=="function"?s.hue():0,u=typeof s.saturation=="function"?s.saturation():0,f=typeof s.luminance=="function"?s.luminance():0,p={prevFilters:[...o],prevRed:r,prevGreen:a,prevBlue:h,prevAlpha:c,prevHue:d,prevSaturation:u,prevLuminance:f,mouseEnterHandler:()=>{},mouseLeaveHandler:()=>{},hadHover:false};p.mouseEnterHandler=()=>{if(p.hadHover=true,t.cache({pixelRatio:this.pixelRatio}),this.mode==="sepia"){let g=t.filters(),_=Array.isArray(g)?g:[];_.includes(G__default.default.Filters.Sepia)||t.filters([..._,G__default.default.Filters.Sepia]);}else {let g=t.filters(),_=Array.isArray(g)?g:[];_.includes(G__default.default.Filters.HSL)||t.filters([..._,G__default.default.Filters.HSL]);let m=this.intensity,b=18,v=.2,w=b*m,x=v*m;switch(this.mode){case "warm":{typeof s.hue=="function"&&s.hue(p.prevHue+w),typeof s.saturation=="function"&&s.saturation(p.prevSaturation+x);break}case "cool":{typeof s.hue=="function"&&s.hue(p.prevHue-w),typeof s.saturation=="function"&&s.saturation(p.prevSaturation+x);break}}}t.getLayer()?.batchDraw();},p.mouseLeaveHandler=()=>{p.hadHover&&(t.filters(p.prevFilters),(this.mode==="warm"||this.mode==="cool")&&(typeof s.red=="function"&&s.red(p.prevRed),typeof s.green=="function"&&s.green(p.prevGreen),typeof s.blue=="function"&&s.blue(p.prevBlue),typeof s.alpha=="function"&&s.alpha(p.prevAlpha),typeof s.hue=="function"&&s.hue(p.prevHue),typeof s.saturation=="function"&&s.saturation(p.prevSaturation),typeof s.luminance=="function"&&s.luminance(p.prevLuminance)),t.getLayer()?.batchDraw(),t.clearCache());},t.on("mouseenter.imageHoverFilterAddon",p.mouseEnterHandler),t.on("mouseleave.imageHoverFilterAddon",p.mouseLeaveHandler),this.nodes.set(e,p);}onDetach(e){let t=this.nodes.get(e);if(!t)return;let n=e.getKonvaNode();n.off("mouseenter.imageHoverFilterAddon",t.mouseEnterHandler),n.off("mouseleave.imageHoverFilterAddon",t.mouseLeaveHandler),n.filters(t.prevFilters);let o=n;(this.mode==="warm"||this.mode==="cool")&&(typeof o.red=="function"&&o.red(t.prevRed),typeof o.green=="function"&&o.green(t.prevGreen),typeof o.blue=="function"&&o.blue(t.prevBlue),typeof o.alpha=="function"&&o.alpha(t.prevAlpha)),n.getLayer()?.batchDraw(),n.clearCache(),this.nodes.delete(e);}};var zt=class extends oe{constructor(e={}){super();l(this,"_options");l(this,"_instance",null);l(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let n=t.plugins.list().find(s=>s instanceof ye);if(n){this._instance=n,this._owned=false;return}let o=new ye(this._options);t.plugins.addPlugins([o]),this._instance=o,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Wt=class extends oe{constructor(e={}){super();l(this,"_options");l(this,"_instance",null);l(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let n=t.plugins.list().find(s=>s instanceof Ae);if(n){this._instance=n,this._owned=false;return}let o=new Ae(this._options);t.plugins.addPlugins([o]),this._instance=o,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Ut=class extends oe{constructor(e={}){super();l(this,"_options");l(this,"_instance",null);l(this,"_owned",false);this._options=e;}onAttach(e,t){if(this._instance)return;let n=t.plugins.list().find(s=>s instanceof Re);if(n){this._instance=n,this._owned=false;return}let o=new Re(this._options);t.plugins.addPlugins([o]),this._instance=o,this._owned=true;}onDetach(e,t){this._instance&&(this._owned&&t.plugins.removePlugins([this._instance]),this._instance=null,this._owned=false);}};var Vt=class extends he{constructor(e={}){super();l(this,"stroke");l(this,"strokeWidth");l(this,"fill");l(this,"mode");l(this,"nodes",new WeakMap);this.stroke=e.stroke??"#1976d2",this.strokeWidth=e.strokeWidth??2,this.fill=e.fill??"rgba(255, 255, 0, 0.25)",this.mode=e.mode??"stroke";}onAttach(e){if(this.nodes.has(e))return;let t=e.getKonvaNode(),n={mouseEnterHandler:()=>{},mouseLeaveHandler:()=>{},prevStroke:e.getStroke(),prevStrokeWidth:e.getStrokeWidth(),prevStrokeEnabled:t.strokeEnabled(),prevFill:t.fill(),prevFillEnabled:t.fillEnabled(),hadHover:false};n.mouseEnterHandler=()=>{n.prevStroke=e.getStroke(),n.prevStrokeWidth=e.getStrokeWidth(),n.prevStrokeEnabled=t.strokeEnabled(),n.prevFill=t.fill(),n.prevFillEnabled=t.fillEnabled(),n.hadHover=true,(this.mode==="stroke"||this.mode==="both")&&(t.strokeEnabled(true),t.stroke(this.stroke),t.strokeWidth(this.strokeWidth)),(this.mode==="fill"||this.mode==="both")&&(t.fillEnabled(true),t.fill(this.fill)),t.getLayer()?.batchDraw();},n.mouseLeaveHandler=()=>{n.hadHover&&(t.strokeEnabled(n.prevStrokeEnabled),typeof n.prevStroke=="string"&&t.stroke(n.prevStroke),t.strokeWidth(n.prevStrokeWidth),t.fillEnabled(n.prevFillEnabled),typeof n.prevFill=="string"&&t.fill(n.prevFill),t.getLayer()?.batchDraw());},t.on("mouseenter.shapeHoverHighlightAddon",n.mouseEnterHandler),t.on("mouseleave.shapeHoverHighlightAddon",n.mouseLeaveHandler),this.nodes.set(e,n);}onDetach(e){let t=this.nodes.get(e);if(!t)return;let n=e.getKonvaNode();n.off("mouseenter.shapeHoverHighlightAddon",t.mouseEnterHandler),n.off("mouseleave.shapeHoverHighlightAddon",t.mouseLeaveHandler),t.hadHover&&(n.strokeEnabled(t.prevStrokeEnabled),typeof t.prevStroke=="string"&&n.stroke(t.prevStroke),n.strokeWidth(t.prevStrokeWidth),n.fillEnabled(t.prevFillEnabled),typeof t.prevFill=="string"&&n.fill(t.prevFill),n.getLayer()?.batchDraw()),this.nodes.delete(e);}};var Xt=class extends he{constructor(){super(...arguments);l(this,"nodes",new WeakMap);}onAttach(e){if(this.nodes.has(e))return;let t=n=>{if(n.cancelled)return;let o=this.normalize(n.newText);o!==n.newText&&(e.setText(o),e.getKonvaNode().getLayer()?.batchDraw());};e.onTextChange(t),this.nodes.set(e,{handler:t});}onDetach(e){let t=this.nodes.get(e);t&&(e.offTextChange(t.handler),this.nodes.delete(e));}normalize(e){return e?e.replace(/[ \t]+/g," ").trim():""}};var An={desktopFrame:{width:1920,height:1080,template:"Figma desktop",label:"Desktop"}};
|
|
112
|
-
exports.AreaSelectionPlugin=Ct;exports.CameraHotkeysPlugin=St;exports.CameraManager=Le;exports.ContentFromClipboardPlugin=Et;exports.CoreEngine=xt;exports.DebounceHelper=we;exports.EventBus=Be;exports.FrameNode=A;exports.GridPlugin=Pt;exports.HistoryManager=Ge;exports.HistoryPlugin=Kt;exports.ImageHoverFilterAddon=Ft;exports.LogoPlugin=At;exports.MediaPlaceholder=ce;exports.NodeAddon=he;exports.NodeAddons=De;exports.NodeHotkeysPlugin=Rt;exports.NodeManager=Oe;exports.PersistencePlugin=It;exports.PersistenceStorage=Ve;exports.PluginAddon=oe;exports.Plugins=Ie;exports.RulerGuidesAddon=zt;exports.RulerGuidesPlugin=ye;exports.RulerHighlightAddon=Wt;exports.RulerHighlightPlugin=Ae;exports.RulerManagerAddon=Ut;exports.RulerManagerPlugin=Re;exports.RulerPlugin=Gt;exports.SelectionPlugin=xe;exports.ShapeHoverHighlightAddon=Vt;exports.TextAutoTrimAddon=Xt;exports.ThrottleHelper=ve;exports.VideoOverlayAddon=He;exports.VisualGuidesPlugin=Ht;exports.createBlobUrlMap=Ot;exports.deserializeCanvas=vt;exports.exportCanvasToJSON=Lt;exports.extractBlobs=on;exports.frameTemplates=An;exports.importCanvasFromJSON=Dt;exports.revokeBlobUrls=Ue;exports.serializeCanvas=mt;
|
|
1
|
+
'use strict';var j=require('konva'),culori=require('culori');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var j__default=/*#__PURE__*/_interopDefault(j);var lr=Object.defineProperty;var dr=(g,e,t)=>e in g?lr(g,e,{enumerable:true,configurable:true,writable:true,value:t}):g[e]=t;var n=(g,e,t)=>dr(g,typeof e!="symbol"?e+"":e,t);var Q=class{constructor(){n(this,"_listeners",{});}on(e,t){return this._listeners[e]||(this._listeners[e]=new Set),this._listeners[e].add(t),()=>{this._listeners[e].delete(t);}}emit(e,t){this._listeners[e]?.forEach(i=>i(t));}clear(){Object.values(this._listeners).forEach(e=>e?.clear());}};var vt=Math.PI,Ao=Math.PI*2,Lo=Math.PI/2,Do=Math.PI/4,Xe=Math.PI/180,$e=180/Math.PI,qe=1e-6,Ho=1e-9,$=34028235e31,ht=-34028235e31,No=11920929e-14;var _=class g{static isValidNumber(e){return Number.isFinite(e)&&e<=$&&e>=ht}static toF32(e){return Number.isNaN(e)?0:e===1/0?$:e===-1/0?ht:e>$?$:e<ht?ht:e}static add(e,t){return this.toF32(this.toF32(e)+this.toF32(t))}static sub(e,t){return this.toF32(this.toF32(e)-this.toF32(t))}static mul(e,t){return this.toF32(this.toF32(e)*this.toF32(t))}static div(e,t){return t===0?0:this.toF32(this.toF32(e)/this.toF32(t))}static neg(e){return -this.toF32(e)}static abs(e){return Math.abs(this.toF32(e))}static min(e,t){let i=this.toF32(e),r=this.toF32(t);return i<r?i:r}static max(e,t){let i=this.toF32(e),r=this.toF32(t);return i>r?i:r}static clamp(e,t,i){let r=this.toF32(e),o=this.toF32(t),s=this.toF32(i);if(o>s){let a=o;o=s,s=a;}return r<o?o:r>s?s:r}static nearlyEqual(e,t,i=qe){return this.abs(this.toF32(e)-this.toF32(t))<=this.abs(i)}static lerp(e,t,i){let r=this.toF32(e),o=this.toF32(t),s=this.toF32(i);return this.toF32(r+(o-r)*s)}static round(e){return Math.round(this.toF32(e))}static floor(e){return Math.floor(this.toF32(e))}static ceil(e){return Math.ceil(this.toF32(e))}static sin(e){return this.toF32(Math.sin(this.toF32(e)))}static cos(e){return this.toF32(Math.cos(e))}static tan(e){return this.toF32(Math.tan(e))}static atan(e){return this.toF32(Math.atan(e))}static atan2(e,t){return this.toF32(Math.atan2(e,t))}static asin(e){let t=this.clamp(e,-1,1);return this.toF32(Math.asin(t))}static acos(e){let t=this.clamp(e,-1,1);return this.toF32(Math.acos(t))}static radToDeg(e){return g.toF32(e*$e)}static degToRad(e){return g.toF32(e*Xe)}static normalizeRad(e){let t=vt*2,r=g.toF32(e)%t;return r>vt?r-=t:r<-vt&&(r+=t),g.toF32(r)}static normalizeDeg(e){let i=g.toF32(e)%360;return i>180?i-=360:i<-180&&(i+=360),g.toF32(i)}};var J=class J{constructor(){n(this,"_events",new Q);n(this,"_x");n(this,"_y");n(this,"_scale");n(this,"_rotation");n(this,"_minScale");n(this,"_maxScale");n(this,"_viewport");n(this,"_locks");this._x=0,this._y=0,this._scale=1,this._rotation=0,this._minScale=J.DEFAULT_MIN_SCALE,this._maxScale=J.DEFAULT_MAX_SCALE,this._viewport={width:1,height:1},this._locks={x:false,y:false,scale:false,rotation:false};}onChange(e){return this._events.on("change",e)}getState(){return {x:this._x,y:this._y,scale:this._scale,rotation:this._rotation}}getViewport(){return this._viewport}worldToScreen(e){return this._worldToScreenWithState(e,this._viewport,{x:this._x,y:this._y,scale:this._scale,rotation:this._rotation})}screenToWorld(e){return this._screenToWorldWithState(e,this._viewport,{x:this._x,y:this._y,scale:this._scale,rotation:this._rotation})}setLimits(e,t){let i=_.toF32(e),r=_.toF32(t);this._minScale===i&&this._maxScale===r||(this._minScale=i,this._maxScale=r);}setPosition(e,t){this._update({x:e,y:t});}setViewportSize(e,t){this._viewport={width:_.clamp(e,1,e),height:_.clamp(t,1,t)};}setScale(e){this._update({scale:_.clamp(e,this._minScale,this._maxScale)});}setRotationRadians(e){this._update({rotation:e});}reset(){this._update({x:0,y:0,scale:1,rotation:0});}update(e){this._update(e);}panByScreen(e,t){let i=-(e/this._scale),r=-(t/this._scale),{x:o,y:s}=this._rotate({x:i,y:r},this._rotation);this._update({x:this._x+o,y:this._y+s});}zoomAtScreen(e,t){let i=this.getState(),r=_.clamp(i.scale*t,this._minScale,this._maxScale),o=this.screenToWorld(e),s={...i,scale:r},a=this._screenToWorldWithState(e,this._viewport,s);this._update({scale:r,x:i.x+(o.x-a.x),y:i.y+(o.y-a.y)});}rotateAtScreen(e,t){let i=this.getState(),r=this.screenToWorld(e),o={...i,rotation:i.rotation+t},s=this._screenToWorldWithState(e,this._viewport,o);this._update({rotation:o.rotation,x:i.x+(r.x-s.x),y:i.y+(r.y-s.y)});}fitToRect(e,t){let i=t?.padding??0,r=t?.resetRotation??false,o=e.width+i*2,s=e.height+i*2,a=r?0:this._rotation,l,d;if(a===0)l=this._viewport.width/o,d=this._viewport.height/s;else {let m=_.abs(_.cos(a)),b=_.abs(_.sin(a)),f=this._viewport.width*m+this._viewport.height*b,y=this._viewport.width*b+this._viewport.height*m;l=f/o,d=y/s;}let c=_.min(l,d),h=_.toF32(e.x+e.width/2),u=_.toF32(e.y+e.height/2);this._update({x:h,y:u,scale:c,rotation:a});}lockX(){this._locks.x=true;}lockY(){this._locks.y=true;}lockScale(){this._locks.scale=true;}lockRotation(){this._locks.rotation=true;}lock(){this._locks={x:true,y:true,scale:true,rotation:true};}unlockX(){this._locks.x=false;}unlockY(){this._locks.y=false;}unlockScale(){this._locks.scale=false;}unlockRotation(){this._locks.rotation=false;}unlock(){this._locks={x:false,y:false,scale:false,rotation:false};}isLocked(){return this._locks.x&&this._locks.y&&this._locks.scale&&this._locks.rotation}getLocks(){return {...this._locks}}_rotate(e,t){let i=_.cos(t),r=_.sin(t);return {x:_.toF32(e.x*i-e.y*r),y:_.toF32(e.x*r+e.y*i)}}_update(e){let t=this.getState();e.x!==void 0&&!this._locks.x&&(this._x=e.x),e.y!==void 0&&!this._locks.y&&(this._y=e.y),e.scale!==void 0&&!this._locks.scale&&(this._scale=_.clamp(e.scale,this._minScale,this._maxScale)),e.rotation!==void 0&&!this._locks.rotation&&(this._rotation=e.rotation),this._emitIfChanged(t);}_worldToScreenWithState(e,t,i){let r=t.width/2,o=t.height/2,s={x:e.x-i.x,y:e.y-i.y},a=this._rotate(s,-i.rotation),l={x:a.x*i.scale,y:a.y*i.scale};return {x:l.x+r,y:l.y+o}}_screenToWorldWithState(e,t,i){let r=t.width/2,o=t.height/2,s={x:e.x-r,y:e.y-o},a={x:s.x/i.scale,y:s.y/i.scale},l=this._rotate(a,i.rotation);return {x:l.x+i.x,y:l.y+i.y}}_emitIfChanged(e){let t=this.getState();(e.x!==t.x||e.y!==t.y||e.scale!==t.scale||e.rotation!==t.rotation)&&this._events.emit("change",t);}};n(J,"DEFAULT_MIN_SCALE",.01),n(J,"DEFAULT_MAX_SCALE",500);var xt=J;var St=class{constructor(){n(this,"_enabled",true);n(this,"_events",new Q);}onChange(e){return this._events.on("change",e)}isEnabled(){return this._enabled}enable(){this.setEnabled(true);}disable(){this.setEnabled(false);}setEnabled(e){this._enabled!==e&&(this._enabled=e,this._onEnabledChanged(e));}_onEnabledChanged(e){this._events.emit("change",e);}};var wt=class{constructor(){n(this,"_position");n(this,"_scale");n(this,"_rotation");n(this,"_pivot");this._position={x:0,y:0},this._rotation=0,this._scale={x:1,y:1},this._pivot={x:.5,y:.5};}getX(){return this._position.x}getY(){return this._position.y}getPosition(){return {...this._position}}setX(e){let t=_.toF32(e);this._position.x!==t&&(this._position.x=t);}setY(e){let t=_.toF32(e);this._position.y!==t&&(this._position.y=t);}setPosition(e,t){let i=_.toF32(e),r=_.toF32(t);this._position.x===i&&this._position.y===r||(this._position.x=i,this._position.y=r);}translateX(e){e!==0&&(this._position.x=_.add(this._position.x,e));}translateY(e){e!==0&&(this._position.y=_.add(this._position.y,e));}translate(e,t){e===0&&t===0||(this._position.x=_.add(this._position.x,e),this._position.y=_.add(this._position.y,t));}getScaleX(){return this._scale.x}getScaleY(){return this._scale.y}getScale(){return {...this._scale}}setScaleX(e){let t=_.toF32(e);this._scale.x!==t&&(this._scale.x=t);}setScaleY(e){let t=_.toF32(e);this._scale.y!==t&&(this._scale.y=t);}setScale(e,t){let i=_.toF32(e),r=_.toF32(t);this._scale.x===i&&this._scale.y===r||(this._scale.x=i,this._scale.y=r);}getRotation(){return this._rotation}setRotation(e){let t=_.normalizeRad(e);this._rotation!==t&&(this._rotation=t);}rotate(e){e!==0&&(this._rotation=_.normalizeRad(_.add(this._rotation,e)));}getPivotX(){return this._pivot.x}getPivotY(){return this._pivot.y}getPivot(){return {...this._pivot}}setPivotX(e){let t=_.toF32(e);this._pivot.x!==t&&(this._pivot.x=t);}setPivotY(e){let t=_.toF32(e);this._pivot.y!==t&&(this._pivot.y=t);}setPivot(e,t){let i=_.toF32(e),r=_.toF32(t);this._pivot.x===i&&this._pivot.y===r||(this._pivot.x=i,this._pivot.y=r);}getLocalMatrix(e,t){let i=_.mul(e,this._pivot.x),r=_.mul(t,this._pivot.y);return this._composeMatrix(this._position,this._scale,this._rotation,i,r)}_composeMatrix(e,t,i,r,o){let s=_.cos(i),a=_.sin(i),l=_.mul(s,t.x),d=_.mul(a,t.x),c=_.mul(-a,t.y),h=_.mul(s,t.y);return {a:l,b:d,c,d:h,tx:_.toF32(e.x-(l*r+c*o)),ty:_.toF32(e.y-(d*r+h*o))}}};var It=class{constructor(e){n(this,"_root");n(this,"_shape");n(this,"_renderer");n(this,"_getDrawInput");this._renderer=e.renderer,this._getDrawInput=e.getDrawInput,this._root=new j__default.default.Group({listening:false,perfectDrawEnabled:false}),this._shape=new j__default.default.Shape({listening:false,perfectDrawEnabled:false,sceneFunc:(t,i)=>{let r=this._getDrawInput();this._renderer.draw(t,{camera:{scale:r.camera.scale},viewportAabbWorld:r.viewportAabbWorld}),t.fillStrokeShape(i);}}),this._root.add(this._shape);}getRoot(){return this._root}destroy(){this._root.destroy();}setOptions(e){this._renderer.setOptions(e);}getOptions(){return this._renderer.getOptions()}getGridStepWorld(){return this._renderer.getGridStepWorld()}};var Ct=class{constructor(){n(this,"_opts",{enabled:true,size:50,majorEvery:5,minCellPx:6,maxLines:1500,minorAlpha:1,majorAlpha:1,axisAlpha:1,showAxis:true});}setOptions(e){this._opts={...this._opts,...e};}getOptions(){return this._opts}getGridStepWorld(){let e=Math.max(1e-6,this._opts.size),t=e*Math.max(1,this._opts.majorEvery);return {minor:e,major:t}}draw(e,t){let i=this._opts;if(!i.enabled)return;let r=t.camera,o=t.viewportAabbWorld,s=o.x,a=o.x+o.width,l=o.y,d=o.y+o.height,c=Math.max(1e-6,i.size);if(c*r.scale<i.minCellPx)return;let u=c*Math.max(1,i.majorEvery);if(Math.ceil((a-s)/c)+1+(Math.ceil((d-l)/c)+1)>i.maxLines)return;let b=Math.floor(s/c)*c,f=Math.floor(l/c)*c,y=Math.floor(s/u)*u,x=Math.floor(l/u)*u;e.save(),e.globalCompositeOperation="difference",e.lineWidth=1/r.scale,e.strokeStyle=`rgba(255,255,255,${i.minorAlpha})`,e.beginPath();for(let v=b;v<=a;v+=c)e.moveTo(v,l),e.lineTo(v,d);for(let v=f;v<=d;v+=c)e.moveTo(s,v),e.lineTo(a,v);e.stroke(),e.strokeStyle=`rgba(255,255,255,${i.majorAlpha})`,e.beginPath();for(let v=y;v<=a;v+=u)e.moveTo(v,l),e.lineTo(v,d);for(let v=x;v<=d;v+=u)e.moveTo(s,v),e.lineTo(a,v);e.stroke(),i.showAxis&&(e.strokeStyle=`rgba(77,163,255,${i.axisAlpha})`,e.beginPath(),e.moveTo(0,l),e.lineTo(0,d),e.moveTo(s,0),e.lineTo(a,0),e.stroke()),e.restore();}};var Ze={Backspace:8,Tab:9,Enter:13,Pause:19,Escape:27,Space:32,Digit0:48,Digit1:49,Digit2:50,Digit3:51,Digit4:52,Digit5:53,Digit6:54,Digit7:55,Digit8:56,Digit9:57,KeyA:97,KeyB:98,KeyC:99,KeyD:100,KeyE:101,KeyF:102,KeyG:103,KeyH:104,KeyI:105,KeyJ:106,KeyK:107,KeyL:108,KeyM:109,KeyN:110,KeyO:111,KeyP:112,KeyQ:113,KeyR:114,KeyS:115,KeyT:116,KeyU:117,KeyV:118,KeyW:119,KeyX:120,KeyY:121,KeyZ:122,Minus:45,Equal:61,BracketLeft:91,BracketRight:93,Backslash:92,Semicolon:59,Quote:39,Backquote:96,Comma:44,Period:46,Slash:47,Delete:127,Insert:277,Home:278,End:279,PageUp:280,PageDown:281,ArrowUp:273,ArrowDown:274,ArrowLeft:276,ArrowRight:275,Numpad0:256,Numpad1:257,Numpad2:258,Numpad3:259,Numpad4:260,Numpad5:261,Numpad6:262,Numpad7:263,Numpad8:264,Numpad9:265,NumpadDecimal:266,NumpadDivide:267,NumpadMultiply:268,NumpadSubtract:269,NumpadAdd:270,NumpadEnter:271,NumpadEqual:272,F1:282,F2:283,F3:284,F4:285,F5:286,F6:287,F7:288,F8:289,F9:290,F10:291,F11:292,F12:293,F13:294,F14:295,F15:296,NumLock:300,CapsLock:301,ScrollLock:302,ShiftLeft:304,ShiftRight:303,ControlLeft:306,ControlRight:305,AltLeft:308,AltRight:307,MetaLeft:310,MetaRight:309,ContextMenu:319,PrintScreen:316};function Fe(g){return Ze[g]??0}function tn(g){return g in Ze}var p=class p{static onInput(e){this._onInputCallback=e;}static configure(e){Object.assign(this._options,e);}static get inputString(){return this._inputString}static get anyKey(){return this._keys.size>0}static get anyKeyDown(){return this._keysDown.size>0}static get ctrlPressed(){return this._keys.has(306)||this._keys.has(305)}static get shiftPressed(){return this._keys.has(304)||this._keys.has(303)}static get altPressed(){return this._keys.has(308)||this._keys.has(307)}static get metaPressed(){return this._keys.has(310)||this._keys.has(309)||this._keys.has(311)||this._keys.has(312)}static get isAnyModifierPressed(){return this.ctrlPressed||this.shiftPressed||this.altPressed||this.metaPressed}static get mousePosition(){return {...this._mousePosition}}static get mousePositionDelta(){return {...this._mouseDelta}}static get mousePositionDeltaNormalized(){let e=this._mouseDelta.x,t=this._mouseDelta.y,i=Math.sqrt(e*e+t*t);return i===0?{x:0,y:0}:{x:e/i,y:t/i}}static get mouseScrollDelta(){return {...this._mouseScroll}}static get mouseScrollX(){return this._mouseScroll.x}static get mouseScrollY(){return this._mouseScroll.y}static get mouseInside(){return this._mouseInside}static get anyMouseButton(){return this._mouseButtons.size>0}static get anyMouseButtonDown(){return this._mouseButtonsDown.size>0}static get scrollCtrl(){return this._scrollCtrl}static get scrollShift(){return this._scrollShift}static get scrollAlt(){return this._scrollAlt}static get scrollMeta(){return this._scrollMeta}static get cursor(){return this._cursor}static get pointerPosition(){return {...this._pointerPosition}}static get pointerDelta(){return {...this._pointerDelta}}static get pointerDown(){return this._pointerDown}static get pointerInside(){return this._pointerInside}static get pointerCaptured(){return this._pointerCaptured}static get pointerType(){return this._pointerType}static get pointerPressure(){return this._pointerPressure}static get activePointerId(){return this._activePointerId}static get coalescedEvents(){return this._coalescedEvents}static get predictedEvents(){return this._predictedEvents}static getKey(e){return this._keys.has(e)}static getKeyDown(e){return this._keysDown.has(e)}static getKeyUp(e){return this._keysUp.has(e)}static getKeyCombo(...e){return e.every(t=>this._keys.has(t))}static setCursor(e){this._cursor!==e&&(this._cursor=e,this._applyCursor());}static resetCursor(){this.setCursor("default");}static getKeyDownCombo(...e){return e.every(t=>this._keys.has(t))&&e.some(t=>this._keysDown.has(t))}static getKeyRepeat(e,t){let i=t?.delay??400,r=t?.interval??16,o=performance.now();if(this.getKeyDown(e))return this._keyHoldStart.set(e,o),this._keyLastRepeat.set(e,o),true;if(!this.getKey(e))return this._keyHoldStart.delete(e),this._keyLastRepeat.delete(e),false;let s=this._keyHoldStart.get(e),a=this._keyLastRepeat.get(e);return s===void 0||a===void 0||o-s<i?false:o-a>=r?(this._keyLastRepeat.set(e,o),true):false}static onceKeyDown(e,t){this._onceKeyDownCallbacks.has(e)||this._onceKeyDownCallbacks.set(e,new Set),this._onceKeyDownCallbacks.get(e).add(t);}static getMouseButton(e){return this._mouseButtons.has(e)}static getMouseButtonPressOrigin(e){let t=this._mouseButtonDragOrigin.get(e);return t?{...t}:{x:0,y:0}}static getMouseButtonDown(e){return this._mouseButtonsDown.has(e)}static getMouseButtonUp(e){return this._mouseButtonsUp.has(e)}static getMouseButtonHoldDuration(e){let t=this._mouseButtonHoldStart.get(e);return t===void 0?0:performance.now()-t}static getMouseDragDelta(e){let t=this._mouseButtonDragOrigin.get(e);return t===void 0?{x:0,y:0}:{x:this._mousePosition.x-t.x,y:this._mousePosition.y-t.y}}static getMouseButtonClickCount(e,t=300){let i=this._mouseButtonLastClickTime.get(e);return i===void 0||performance.now()-i>t?0:this._mouseButtonClickCount.get(e)??0}static getMouseButtonDoubleClick(e,t=300){return this.getMouseButtonDown(e)&&this.getMouseButtonClickCount(e,t)===2}static getMouseButtonTripleClick(e,t=300){return this.getMouseButtonDown(e)&&this.getMouseButtonClickCount(e,t)===3}static getMouseDragDistance(e){let t=this.getMouseDragDelta(e);return Math.sqrt(t.x*t.x+t.y*t.y)}static isMouseButtonHeld(e,t){return this.getMouseButtonHoldDuration(e)>=t}static lockPointer(e){e.requestPointerLock();}static unlockPointer(){document.exitPointerLock();}static get isPointerLocked(){return document.pointerLockElement!==null}static getModifiers(){return {ctrl:this.ctrlPressed,shift:this.shiftPressed,alt:this.altPressed,meta:this.metaPressed}}static getKeyDownOnce(e){return this.getKeyDown(e)}static getAxisValue(e,t){let i=this._keys.has(e)?-1:0,r=this._keys.has(t)?1:0;return i+r}static getVector(e,t,i,r){let o=this.getAxisValue(e,t),s=this.getAxisValue(i,r),a=Math.sqrt(o*o+s*s);return a===0?{x:0,y:0}:{x:o/a,y:s/a}}static isIdle(e){return performance.now()-this._lastInputTime>e}static _initialize(){this._initialized||(this._initialized=true,window.addEventListener("keydown",this._onKeyDown),window.addEventListener("keyup",this._onKeyUp),window.addEventListener("blur",this._resetAll));}static _registerSurface(e){this._initialize(),!this._surfaces.has(e)&&(e.addEventListener("mousedown",this._onMouseDown),e.addEventListener("mouseup",this._onMouseUp),e.addEventListener("mousemove",this._onMouseMove),e.addEventListener("mouseenter",this._onMouseEnter),e.addEventListener("mouseleave",this._onMouseLeave),e.addEventListener("wheel",this._onWheel,{passive:false}),e.addEventListener("contextmenu",this._onContextMenu),e.addEventListener("pointerdown",this._onPointerDown),e.addEventListener("pointermove",this._onPointerMove),e.addEventListener("pointerup",this._onPointerUp),e.addEventListener("pointercancel",this._onPointerCancel),e.addEventListener("pointerenter",this._onPointerEnter),e.addEventListener("pointerleave",this._onPointerLeave),e.addEventListener("pointerover",this._onPointerOver),e.addEventListener("pointerout",this._onPointerOut),e.addEventListener("gotpointercapture",this._onGotPointerCapture),e.addEventListener("lostpointercapture",this._onLostPointerCapture),this._surfaces.add(e),e.style.cursor=this._cursor);}static _unregisterSurface(e){this._surfaces.has(e)&&(e.removeEventListener("mousedown",this._onMouseDown),e.removeEventListener("mouseup",this._onMouseUp),e.removeEventListener("mousemove",this._onMouseMove),e.removeEventListener("mouseenter",this._onMouseEnter),e.removeEventListener("mouseleave",this._onMouseLeave),e.removeEventListener("wheel",this._onWheel),e.removeEventListener("contextmenu",this._onContextMenu),e.removeEventListener("pointerdown",this._onPointerDown),e.removeEventListener("pointermove",this._onPointerMove),e.removeEventListener("pointerup",this._onPointerUp),e.removeEventListener("pointercancel",this._onPointerCancel),e.removeEventListener("pointerenter",this._onPointerEnter),e.removeEventListener("pointerleave",this._onPointerLeave),e.removeEventListener("pointerover",this._onPointerOver),e.removeEventListener("pointerout",this._onPointerOut),e.removeEventListener("gotpointercapture",this._onGotPointerCapture),e.removeEventListener("lostpointercapture",this._onLostPointerCapture),this._surfaces.delete(e));}static _destroy(){this._initialized&&(this._surfaces.forEach(e=>this._unregisterSurface(e)),window.removeEventListener("keydown",this._onKeyDown),window.removeEventListener("keyup",this._onKeyUp),window.removeEventListener("blur",this._resetAll),this._initialized=false,this._resetAll(),this._mouseDelta={x:0,y:0},this._mouseScroll={x:0,y:0},this._pointerDelta={x:0,y:0},this._inputString="",this._onceKeyDownCallbacks.clear());}static _endFrame(){this._keysDown.clear(),this._keysUp.clear(),this._mouseButtonsDown.clear(),this._mouseButtonsUp.clear(),this._mouseDelta={x:0,y:0},this._mouseScroll={x:0,y:0},this._pointerDelta={x:0,y:0},this._coalescedEvents=[],this._predictedEvents=[],this._inputString="";}static _updateMousePosition(e){let t={x:e.clientX,y:e.clientY};this._mouseDelta.x+=t.x-this._mousePosition.x,this._mouseDelta.y+=t.y-this._mousePosition.y,this._mousePosition=t;}static _updatePointerPosition(e){let t={x:e.clientX,y:e.clientY};this._pointerDelta={x:t.x-this._pointerPosition.x,y:t.y-this._pointerPosition.y},this._pointerPosition=t;}static _applyCursor(){for(let e of this._surfaces)e.style.cursor=this._cursor;}static _emitInput(e){this._onInputCallback?.(e);}};n(p,"_keys",new Set),n(p,"_keysDown",new Set),n(p,"_keysUp",new Set),n(p,"_keyHoldStart",new Map),n(p,"_keyLastRepeat",new Map),n(p,"_onceKeyDownCallbacks",new Map),n(p,"_mouseButtons",new Set),n(p,"_mouseButtonsDown",new Set),n(p,"_mouseButtonsUp",new Set),n(p,"_mouseButtonHoldStart",new Map),n(p,"_mouseButtonDragOrigin",new Map),n(p,"_mouseButtonClickCount",new Map),n(p,"_mouseButtonLastClickTime",new Map),n(p,"_mousePosition",{x:0,y:0}),n(p,"_mouseDelta",{x:0,y:0}),n(p,"_mouseScroll",{x:0,y:0}),n(p,"_mouseInside",false),n(p,"_scrollCtrl",false),n(p,"_scrollShift",false),n(p,"_scrollAlt",false),n(p,"_scrollMeta",false),n(p,"_activePointerId",null),n(p,"_pointerCaptured",false),n(p,"_pointerInside",false),n(p,"_pointerDown",false),n(p,"_pointerPosition",{x:0,y:0}),n(p,"_pointerDelta",{x:0,y:0}),n(p,"_pointerType","mouse"),n(p,"_pointerPressure",0),n(p,"_coalescedEvents",[]),n(p,"_predictedEvents",[]),n(p,"_cursor","default"),n(p,"_lastInputTime",performance.now()),n(p,"_inputString",""),n(p,"_options",{preventAltDefault:false,preventContextMenu:false,preventWheelDefault:false,usePointerCapture:true}),n(p,"_initialized",false),n(p,"_surfaces",new Set),n(p,"_onInputCallback",null),n(p,"_onKeyDown",e=>{let t=Fe(e.code);if(t!==0){if(p.altPressed&&e.cancelable&&p._options.preventAltDefault&&e.preventDefault(),!p._keys.has(t)){p._keysDown.add(t);let i=p._onceKeyDownCallbacks.get(t);i&&(i.forEach(r=>r()),p._onceKeyDownCallbacks.delete(t));}p._keys.add(t),e.key.length===1&&(p._inputString+=e.key),p._lastInputTime=performance.now(),p._emitInput({type:"keydown",keyCode:t});}}),n(p,"_onKeyUp",e=>{let t=Fe(e.code);t!==0&&(p.altPressed&&e.cancelable&&p._options.preventAltDefault&&e.preventDefault(),p._keys.delete(t),p._keysUp.add(t),p._lastInputTime=performance.now(),p._emitInput({type:"keyup",keyCode:t}));}),n(p,"_onMouseDown",e=>{if(!p._mouseButtons.has(e.button)){p._mouseButtonsDown.add(e.button),p._mouseButtonHoldStart.set(e.button,performance.now()),p._mouseButtonDragOrigin.set(e.button,{...p._mousePosition});let t=performance.now(),i=p._mouseButtonLastClickTime.get(e.button)??0,r=p._mouseButtonClickCount.get(e.button)??0;p._mouseButtonClickCount.set(e.button,t-i<300?r+1:1),p._mouseButtonLastClickTime.set(e.button,t);}p._mouseButtons.add(e.button),p._updateMousePosition(e),p._lastInputTime=performance.now(),p._emitInput({type:"mousedown",mouseButton:e.button});}),n(p,"_onMouseUp",e=>{p._mouseButtons.delete(e.button),p._mouseButtonsUp.add(e.button),p._mouseButtonHoldStart.delete(e.button),p._mouseButtonDragOrigin.delete(e.button),p._updateMousePosition(e),p._lastInputTime=performance.now(),p._emitInput({type:"mouseup",mouseButton:e.button});}),n(p,"_onMouseMove",e=>{p._updateMousePosition(e),p._lastInputTime=performance.now(),p._emitInput({type:"mousemove"});}),n(p,"_onMouseEnter",e=>{p._mouseInside=true,p._updateMousePosition(e),p._emitInput({type:"mouseenter"});}),n(p,"_onMouseLeave",e=>{p._mouseInside=false,p._updateMousePosition(e),p._mouseDelta={x:0,y:0},p._emitInput({type:"mouseleave"});}),n(p,"_onWheel",e=>{p._options.preventWheelDefault&&e.cancelable&&e.preventDefault(),p._mouseScroll={x:e.deltaX,y:e.deltaY},p._scrollCtrl=e.ctrlKey,p._scrollShift=e.shiftKey,p._scrollAlt=e.altKey,p._scrollMeta=e.metaKey,p._updateMousePosition(e),p._lastInputTime=performance.now(),p._emitInput({type:"wheel"});}),n(p,"_onContextMenu",e=>{p._options.preventContextMenu&&e.preventDefault();}),n(p,"_onPointerDown",e=>{p._pointerDown=true,p._activePointerId=e.pointerId,p._pointerType=e.pointerType,p._pointerPressure=e.pressure,p._updatePointerPosition(e),p._lastInputTime=performance.now(),p._options.usePointerCapture&&e.currentTarget.setPointerCapture(e.pointerId),p._emitInput({type:"pointerdown",mouseButton:e.button});}),n(p,"_onPointerMove",e=>{p._pointerPressure=e.pressure,p._coalescedEvents=e.getCoalescedEvents?.()??[],p._predictedEvents=e.getPredictedEvents?.()??[],p._updatePointerPosition(e),p._lastInputTime=performance.now(),p._emitInput({type:"pointermove"});}),n(p,"_onPointerUp",e=>{p._pointerDown=false,p._pointerPressure=0,p._updatePointerPosition(e),p._lastInputTime=performance.now(),p._options.usePointerCapture&&e.currentTarget instanceof Element&&e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId),p._activePointerId===e.pointerId&&(p._activePointerId=null),p._emitInput({type:"pointerup",mouseButton:e.button});}),n(p,"_onPointerCancel",e=>{p._pointerDown=false,p._pointerPressure=0,p._activePointerId=null,p._mouseButtons.clear(),p._mouseButtonsDown.clear(),p._mouseButtonsUp.clear(),p._mouseButtonHoldStart.clear(),p._mouseButtonDragOrigin.clear(),p._options.usePointerCapture&&e.currentTarget instanceof Element&&e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId),p._emitInput({type:"pointercancel"});}),n(p,"_onPointerEnter",e=>{p._pointerInside=true,p._updatePointerPosition(e),p._emitInput({type:"pointerenter"});}),n(p,"_onPointerLeave",e=>{p._pointerInside=false,p._updatePointerPosition(e),p._pointerDelta={x:0,y:0},p._emitInput({type:"pointerleave"});}),n(p,"_onPointerOver",e=>{p._pointerInside=true,p._updatePointerPosition(e),p._emitInput({type:"pointerover"});}),n(p,"_onPointerOut",e=>{p._updatePointerPosition(e),p._emitInput({type:"pointerout"});}),n(p,"_onGotPointerCapture",e=>{p._pointerCaptured=true,p._emitInput({type:"gotpointercapture"});}),n(p,"_onLostPointerCapture",e=>{p._pointerCaptured=false,p._emitInput({type:"lostpointercapture"});}),n(p,"_resetAll",()=>{p._keys.clear(),p._keysDown.clear(),p._keysUp.clear(),p._mouseButtons.clear(),p._mouseButtonsDown.clear(),p._mouseButtonsUp.clear(),p._mouseButtonHoldStart.clear(),p._mouseButtonDragOrigin.clear();});var S=p;var tt=class{constructor(){n(this,"_items",new Map);}add(e){this._items.set(String(e.id),e);}remove(e){return this._items.delete(String(e))}getById(e){return this._items.get(String(e))??null}getAll(){return Array.from(this._items.values())}clear(){this._items.clear();}};var et=class{constructor(){n(this,"moduleManager",new tt);n(this,"_target",null);n(this,"_isAttached",false);n(this,"_isDestroyed",false);}attach(e){if(!this._isDestroyed){this._target=e,this._isAttached=true;for(let t of this.moduleManager.getAll())t.attach(e);this._onAttach(e);}}detach(){if(!(!this._isAttached||this._target===null)){this._onDetach();for(let e of this.moduleManager.getAll())e.detach();this._target=null,this._isAttached=false;}}update(){if(!(!this._isAttached||this._target===null||this._isDestroyed)){this._onBeforeUpdate();for(let e of this.moduleManager.getAll())e.update();this._onAfterUpdate();}}destroy(){if(!this._isDestroyed){this.detach();for(let e of this.moduleManager.getAll())e.destroy();this.moduleManager.clear(),this._isDestroyed=true,this._onDestroy();}}addModule(e){if(this._isDestroyed)return;let t=this.moduleManager.getById(e.id);t&&(this._isAttached&&t.detach(),t.destroy(),this.moduleManager.remove(t.id)),this.moduleManager.add(e),this._isAttached&&this._target!==null&&e.attach(this._target),this._onModuleAdded(e);}removeModule(e){let t=this.moduleManager.getById(e);if(!t)return false;this._isAttached&&t.detach(),t.destroy();let i=this.moduleManager.remove(e);return i&&this._onModuleRemoved(t),i}getTarget(){return this._target}get isAttached(){return this._isAttached}get isDestroyed(){return this._isDestroyed}_onAttach(e){}_onDetach(){}_onBeforeUpdate(){}_onAfterUpdate(){}_onDestroy(){}_onModuleAdded(e){}_onModuleRemoved(e){}};var Tt=class{constructor(){n(this,"id","world-zoom");n(this,"_context",null);n(this,"_dragAccum",0);n(this,"_ctrlMouseZoomStartPoint",null);}attach(e){this._context=e;}detach(){this._context=null,this._dragAccum=0,this._ctrlMouseZoomStartPoint=null;}destroy(){this.detach();}update(){this._context&&(this._updateZoomFromKeyboard(),this._updateCtrlWheelZoom(),this._updateCtrlMouseZoom());}_getCamera(){return this._context.world.getCamera()}_emitChange(){this._context.emitChange();}_updateCtrlWheelZoom(){let{options:e}=this._context;if(!e.zoomEnabled)return;S.configure({preventWheelDefault:true});let t=S.mouseScrollDelta;if(t.x===0&&t.y===0||!S.scrollCtrl)return;let i=this._toStagePoint(S.mousePosition),r=t.y>0?1/e.zoomFactor:e.zoomFactor;this._getCamera().zoomAtScreen(i,r),this._emitChange();}_updateZoomFromKeyboard(){let{options:e,stage:t}=this._context;if(!e.zoomEnabled)return;let i={x:t.width()/2,y:t.height()/2};if(S.getKeyDownCombo(306,61)||S.getKeyDownCombo(305,61)){this._getCamera().zoomAtScreen(i,e.zoomFactor),this._emitChange();return}(S.getKeyDownCombo(306,45)||S.getKeyDownCombo(305,45))&&(this._getCamera().zoomAtScreen(i,1/e.zoomFactor),this._emitChange());}_updateCtrlMouseZoom(){let{options:e}=this._context;if(!e.zoomEnabled)return;if(!(S.ctrlPressed&&S.getMouseButton(2))){this._ctrlMouseZoomStartPoint=null,this._dragAccum=0;return}if(this._ctrlMouseZoomStartPoint===null){let s=S.getMouseButtonPressOrigin(2);this._ctrlMouseZoomStartPoint=this._toStagePoint(s);}let i=S.mousePositionDelta.y;if(i===0)return;this._dragAccum+=i;let r=4,o=this._ctrlMouseZoomStartPoint;for(;Math.abs(this._dragAccum)>=r;){let s=this._dragAccum>0?1/e.zoomFactor:e.zoomFactor;this._getCamera().zoomAtScreen(o,s),this._dragAccum-=Math.sign(this._dragAccum)*r;}this._emitChange();}_toStagePoint(e){let t=this._context.stage,i=t.container().getBoundingClientRect(),r=t.width()||1,o=t.height()||1,s=i.width>0?i.width/r:1,a=i.height>0?i.height/o:1;return {x:(e.x-i.left)/s,y:(e.y-i.top)/a}}};var Rt=class{constructor(){n(this,"id","world-pan");n(this,"_context",null);n(this,"_isDragging",false);n(this,"_activeButton",null);}attach(e){this._context=e,S.configure({preventContextMenu:true});}detach(){this._stopDrag(),this._context=null;}destroy(){this.detach();}update(){if(this._context){if(!this._context.options.enabled){this._stopDrag();return}this._updateDragPanState(),this._updateWheelPan(),this._updateDragPan(),this._updateKeyboardPan();}}_getCamera(){return this._context.world.getCamera()}_emitChange(){this._context.emitChange();}_stopDrag(){this._isDragging=false,this._activeButton=null,this._context&&(this._context.stage.container().style.cursor="");}_canStartRightPan(){return S.getMouseButtonDown(2)&&!S.ctrlPressed}_canStartMiddlePan(){return S.getMouseButtonDown(1)}_updateDragPanState(){if(!this._context)return;let e=this._context.stage;if(!this._isDragging){if(this._canStartRightPan()){this._isDragging=true,this._activeButton=2,e.container().style.cursor="grab";return}if(this._canStartMiddlePan()){this._isDragging=true,this._activeButton=1,e.container().style.cursor="grab";return}return}if(this._activeButton!==null&&S.getMouseButtonUp(this._activeButton)){this._stopDrag(),this._emitChange();return}this._activeButton!==null&&!S.getMouseButton(this._activeButton)&&(this._stopDrag(),this._emitChange());}_updateWheelPan(){let e=S.mouseScrollDelta;if(e.x===0&&e.y===0||S.scrollCtrl)return;let t=e.x,i=e.y;S.scrollShift&&Math.abs(t)<.01&&(t=i,i=0),this._getCamera().panByScreen(-t,-i),this._emitChange();}_updateDragPan(){if(!this._isDragging)return;let e=S.mousePositionDelta;e.x===0&&e.y===0||(this._getCamera().panByScreen(e.x,e.y),this._emitChange());}_updateKeyboardPan(){if(!this._context)return;let{options:e}=this._context,t=0,i=0;if(S.getKeyRepeat(276)&&(t+=1),S.getKeyRepeat(275)&&(t-=1),S.getKeyRepeat(273)&&(i+=1),S.getKeyRepeat(274)&&(i-=1),t===0&&i===0)return;let o=(S.shiftPressed?e.keyboardPanSpeed*e.keyboardPanShiftMultiplier:e.keyboardPanSpeed)/60;this._getCamera().panByScreen(t*o,i*o),this._emitChange();}};var Qe=class extends et{constructor(){super();n(this,"id",0);this.addModule(new Tt),this.addModule(new Rt);}};var Mt=class{constructor(){n(this,"id","overlay-hover");n(this,"_context",null);}attach(e){this._context=e;}detach(){if(!this._context)return;let e=this._context.overlay.getHoveredNode()!==null;this._context.overlay.clearHoveredNode(),e&&this._context.emitChange(),this._context=null;}destroy(){this.detach();}update(){this._context&&this._updateHover();}_updateHover(){let{overlay:e,world:t}=this._context;if(!e.isEnabled()){if(!(e.getHoveredNode()!==null))return;e.clearHoveredNode(),this._context.emitChange();return}if(!S.pointerInside){if(!(e.getHoveredNode()!==null))return;e.clearHoveredNode(),this._context.emitChange();return}let i=this._getStagePointerFromInput(),r=t.getCamera().screenToWorld(i),o=t.findTopNodeAt(r);e.getHoveredNode()?.id!==o?.id&&(o?e.setHoveredNode(o):e.clearHoveredNode(),this._context.emitChange());}_getStagePointerFromInput(){let e=this._context.stage.container().getBoundingClientRect();return {x:S.pointerPosition.x-e.left,y:S.pointerPosition.y-e.top}}};var O=class extends St{constructor(t,i,r,o){super();n(this,"type");n(this,"id");n(this,"_width");n(this,"_height");this.type=r,this.id=o,this._width=t,this._height=i;}getWidth(){return this._width}getHeight(){return this._height}getSize(){return {width:this._width,height:this._height}}setWidth(t){let i=_.toF32(t);this._width!==i&&(this._width=i);}setHeight(t){let i=_.toF32(t);this._height!==i&&(this._height=i);}setSize(t,i){let r=_.toF32(t),o=_.toF32(i);this._width===r&&this._height===o||(this._width=r,this._height=o);}destroy(){this._width=0,this._height=0;}};var ut=(r=>(r[r.Background=0]="Background",r[r.World=1]="World",r[r.Overlay=2]="Overlay",r[r.UI=3]="UI",r))(ut||{});var Je={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dimgrey:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightgrey:"#d3d3d3",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightslategrey:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370db",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#db7093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",rebeccapurple:"#663399",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",slategrey:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",velvet:"#902C3E",transparent:"#00000000"};function ti(g,e,t){let i=[],r=0,o=e.map(a=>a.replace("()","(")),s=t.replace("()","(");for(;r<g.length;){let a=-1,l="";for(let u of o){let m=g.indexOf(u,r);m!==-1&&(a===-1||m<a)&&(a=m,l=u);}if(a===-1)break;let d=a+l.length-1,c=0,h=-1;for(let u=d;u<g.length;u++)if(g[u]==="("?c++:g[u]===")"&&c--,c===0){h=u;break}if(h!==-1){let u=g.substring(d+1,h).trim();u.length>0&&i.push(`${s}${u})`),r=h+1;}else break}return i.join(", ")}var H=g=>Math.min(1,Math.max(0,g)),F=g=>Math.min(255,Math.max(0,Math.round(g)));var E=class g{constructor(e=1,t=0,i=0,r=1){n(this,"_value");this._value={r:H(e),g:H(t),b:H(i),a:H(r)};}static isValidString(e){try{return this.fromString(e),!0}catch{return false}}static fromFloat(e=1,t=0,i=0,r=1){return new g(e,t,i,r)}static fromRGBA(e,t,i,r=1){let o=F(e),s=F(t),a=F(i),l=H(r);return new g(o/255,s/255,a/255,l)}static fromHex(e){let t=new g;return t.setFromHex(e),t}static fromString(e){let t=new g;return t.setFromString(e),t}setColorFloat(e){return e.r!==void 0&&(this._value.r=H(e.r)),e.g!==void 0&&(this._value.g=H(e.g)),e.b!==void 0&&(this._value.b=H(e.b)),e.a!==void 0&&(this._value.a=H(e.a)),this}setColorRGBA(e,t,i,r=1){if([e,t,i,r].some(o=>isNaN(o)))throw new Error(`Invalid color values: r=${e}, g=${t}, b=${i}, a=${r}`);if([e,t,i].some(o=>o<0||o>255))throw new Error(`RGB values must be in 0-255 range: r=${e}, g=${t}, b=${i}`);if(r<0||r>1)throw new Error(`Alpha value must be in 0-1 range: a=${r}`);return this._value={r:H(F(e)/255),g:H(F(t)/255),b:H(F(i)/255),a:H(r)},this}setFromHex(e){let t=e.trim().replace(/^#/,"");if(![3,6,8].includes(t.length))throw new Error(`Invalid hex length: ${e}`);if(t.length===3)return this.setColorRGBA(parseInt(t.charAt(0)+t.charAt(0),16),parseInt(t.charAt(1)+t.charAt(1),16),parseInt(t.charAt(2)+t.charAt(2),16));if(t.length===6)return this.setColorRGBA(parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16));if(t.length===8)return this.setColorRGBA(parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16),parseInt(t.slice(6,8),16)/255);throw new Error(`Invalid hex color: ${e}`)}setFromString(e){let t=e.trim().toLowerCase();if(t.startsWith("#"))return this.setFromHex(t);if(t.startsWith("rgb(")||t.startsWith("rgba(")){let o=t.slice(t.indexOf("(")+1,-1).split(",").map(c=>c.trim()),s=Number(o[0]),a=Number(o[1]),l=Number(o[2]),d=o[3]!==void 0?Number(o[3]):1;return this.setColorRGBA(s,a,l,d)}let i=Je[t];if(i)return this.setFromHex(i);throw new Error(`Unsupported color format: ${e}`)}getFloat(){return {...this._value}}getRGBA(){return {r:F(this._value.r*255),g:F(this._value.g*255),b:F(this._value.b*255),a:this._value.a??1}}toRgbString(){let{r:e,g:t,b:i}=this.getRGBA();return `rgb(${e}, ${t}, ${i})`}toRgbaString(){let{r:e,g:t,b:i,a:r}=this.getRGBA(),o=r===void 0?1:Math.round(r*1e3)/1e3;return `rgba(${e}, ${t}, ${i}, ${o})`}toHexString(e=false){let{r:t,g:i,b:r,a:o}=this.getRGBA(),s=a=>a.toString(16).padStart(2,"0");return e?`#${s(t)}${s(i)}${s(r)}${s(Math.round((o??1)*255))}`:`#${s(t)}${s(i)}${s(r)}`}toString(e=false){return e?this.toRgbaString():this.toRgbString()}reset(){return this._value={r:1,g:0,b:0,a:1},this}equals(e){let t=this._value,i=e._value;return t.r===i.r&&t.g===i.g&&t.b===i.b&&t.a===i.a}static lerp(e,t,i){let r=e._value,o=t._value;return new g(r.r+(o.r-r.r)*i,r.g+(o.g-r.g)*i,r.b+(o.b-r.b)*i,r.a+(o.a-r.a)*i)}};var cr=(o=>(o.Top="top",o.Right="right",o.Bottom="bottom",o.Left="left",o.Center="center",o))(cr||{});var k=class k{constructor(e){k._stops=e,k._isRepeating=false;}getStops(){return k._stops.map(t=>t)}isRepeating(){return k._isRepeating}setRepeating(e){k._isRepeating=e;}static isDirection(e){if(typeof e=="number")return !!(!Number.isNaN(e)&&Number.isFinite(e));let t=e.toLowerCase().trim();if(t.endsWith("deg")){let i=parseFloat(t);return !(Number.isNaN(i)||!Number.isFinite(i))}return this._directionsMap[t]!==void 0}static _parseString(e){let t=k._extractGradientValues(e);return t.length===0?[]:t.map(i=>this._parseColorStops(i))}static _parseColorStops(e){let t=e.split(/,(?![^(]*\))/).map(o=>o.trim());if(t.length===0||t.length===1&&t[0]==="")return {direction:this._defaultDirection,stops:[]};let i=this._defaultDirection;if(t.length>0){let o=t[0].toLowerCase(),s=o.endsWith("deg"),a=o.startsWith("to ")&&this._directionsMap[o]!==void 0;if(s||a){let l=t.shift();i=this._parseDirection(l);}}let r=[];for(let o of t){let s=o.match(/(-?[\d.]+)%/g),a=o.replace(/(-?[\d.]+)%/g,"").trim(),l=E.fromString(a);if(s&&s.length>=2)s.forEach(d=>{r.push({offset:Math.round(parseFloat(d)/100*1e3)/1e3,color:l});});else {let d=s?Math.round(parseFloat(s[0])/100*1e3)/1e3:null;r.push({offset:d,color:l});}}r[0]?.offset===null&&(r[0].offset=0),r[r.length-1]?.offset===null&&(r[r.length-1].offset=1);for(let o=0;o<r.length;o++)if(r[o].offset===null){let s=o-1;for(;s>=0&&r[s].offset===null;)s--;let a=o+1;for(;a<r.length&&r[a].offset===null;)a++;let l=r[s].offset,d=r[a].offset,c=a-s,h=l+(d-l)*((o-s)/c);r[o].offset=Math.round(h*1e3)/1e3;}return {direction:i,stops:r}}static _extractGradientValues(e){let t=[],i="gradient(",r=0;for(;r<e.length;){let o=e.indexOf(i,r);if(o===-1)break;let s=o+i.length-1,a=0,l=-1;for(let d=s;d<e.length;d++)if(e[d]==="("?a++:e[d]===")"&&a--,a===0){l=d;break}if(l!==-1){let d=e.substring(s+1,l).trim();t.push(d),r=l+1;}else break}return t}static _parseDirection(e){if(typeof e=="number")return !Number.isNaN(e)&&Number.isFinite(e)?e:this._defaultDirection;let t=e.toLowerCase().trim();if(t.endsWith("deg")){let i=parseFloat(t);return Number.isNaN(i)||!Number.isFinite(i)?this._defaultDirection:i}return this._directionsMap[t]??this._defaultDirection}};n(k,"_directionsMap",{"to top":0,"to right":90,"to bottom":180,"to left":270,"to top right":45,"to bottom right":135,"to bottom left":225,"to top left":315,"to right top":45,"to right bottom":135,"to left bottom":225,"to left top":315}),n(k,"_stops"),n(k,"_isRepeating"),n(k,"_defaultDirection",180);var Pt=k;var hr=(d=>(d.Center="center",d.Top="top",d.Bottom="bottom",d.Left="left",d.Right="right",d.TopLeft="top left",d.TopRight="top right",d.BottomLeft="bottom left",d.BottomRight="bottom right",d))(hr||{}),Et=class g{constructor(e,t,i,r){n(this,"kind","conic");n(this,"_angle");n(this,"_position");n(this,"_repeating");n(this,"_stops");this._angle=e,this._position=t,this._repeating=r,this._stops=g._normalizeStops(i);}static fromString(e){let t=e.trim(),i=t.startsWith("repeating-conic-gradient"),r=t.startsWith("conic-gradient");if(!i&&!r)throw new Error("[ConicGradient] Invalid gradient string");let o=t.indexOf("("),s=t.lastIndexOf(")");if(o===-1||s===-1||s<=o)throw new Error("[ConicGradient] Malformed gradient string");let l=t.slice(o+1,s).trim().split(/,(?![^(]*\))/).map(u=>u.trim()),d="0deg",c="center";if(l.length>0&&(l[0].includes("from ")||l[0].includes("at "))){let u=l[0],m=u.match(/from\s+([^ ]+)/);m&&(d=m[1]);let b=u.match(/at\s+(.+)$/);b&&(c=b[1].trim().replace(/\s+/g," ")),l.shift();}let h=l.map(u=>{let m=u.trim(),b=m.split(/\s+/);if(b.length===1)return {color:E.fromString(m)};let f=b[b.length-1];if(/^-?\d*\.?\d+(%|deg)?$/.test(f)){let x=m.slice(0,m.lastIndexOf(f)).trim();return {color:E.fromString(x),offset:this._parseOffset(f)}}return {color:E.fromString(m)}});return g.fromStops(h,{angle:d,position:c,repeating:i})}getNormalizedPosition(){let e=this._position.toLowerCase(),t={center:{x:.5,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1},left:{x:0,y:.5},right:{x:1,y:.5},"top left":{x:0,y:0},"top right":{x:1,y:0},"bottom left":{x:0,y:1},"bottom right":{x:1,y:1},"left top":{x:0,y:0},"right top":{x:1,y:0},"left bottom":{x:0,y:1},"right bottom":{x:1,y:1}};if(t[e])return t[e];let i=e.split(/\s+/),r=this._parseCoord(i[0]),o=i.length>1?this._parseCoord(i[1]):.5;return {x:r,y:o}}_parseCoord(e){let t=parseFloat(e);return e.includes("%")?t/100:t}static fromStops(e,t={}){let i=t.angle??"0deg",r=t.position??"at center",o=t.repeating??false,s=e.map(l=>({color:typeof l.color=="string"?E.fromString(l.color):l.color,offset:g._parseOffset(l.offset)})),a=g._fillMissingOffsets(s);return new g(i,r,a,o)}static isValidString(e){try{return this.fromString(e),!0}catch{return false}}getStops(){return this._stops.map(e=>({offset:e.offset,color:e.color}))}getAngle(){return this._angle}getPosition(){return this._position}isRepeating(){return this._repeating}static _parseOffset(e){if(e===void 0)return Number.NaN;if(typeof e=="number")return e;let t=e.toLowerCase(),i=parseFloat(t);return isNaN(i)?Number.NaN:t.endsWith("%")?i/100:t.endsWith("deg")?i/360:i}static _normalizeStops(e){if(e.length<2)throw new Error("[ConicGradient] Need at least 2 stops");return e.map(t=>({color:t.color,offset:H(t.offset)})).sort((t,i)=>t.offset-i.offset)}static _fillMissingOffsets(e){let t=e.map(o=>({...o}));if(!t.some(o=>Number.isFinite(o.offset))){for(let o=0;o<t.length;o++)t[o].offset=o/(t.length-1);return t}t[0]&&!Number.isFinite(t[0].offset)&&(t[0].offset=0),t[t.length-1]&&!Number.isFinite(t[t.length-1].offset)&&(t[t.length-1].offset=1);let r=0;for(;r<t.length;){if(Number.isFinite(t[r].offset)){r++;continue}let o=r-1,s=r;for(;s<t.length&&!Number.isFinite(t[s].offset);)s++;let a=t[o].offset,l=t[s].offset,d=s-o-1,c=(l-a)/(d+1);for(let h=1;h<=d;h++)t[o+h].offset=a+c*h;r=s+1;}for(let o of t)o.offset=H(o.offset);return t}};var At=class g{constructor(e,t,i){n(this,"kind","diamond");n(this,"_position");n(this,"_repeating");n(this,"_stops");this._stops=e,this._position=t,this._repeating=i;}static isValidString(e){try{return this.fromString(e),!0}catch{return false}}static fromString(e){let t=e.trim(),i=t.startsWith("repeating-diamond-gradient"),r=t.startsWith("diamond-gradient");if(!i&&!r)throw new Error(`[DiamondGradient] Expected diamond-gradient but got: "${t}"`);let o=t.indexOf("("),s=t.lastIndexOf(")");if(o===-1||s===-1)throw new Error("[DiamondGradient] Invalid syntax");let l=t.slice(o+1,s).trim().split(/,(?![^(]*\))/),d="center";if(l.length>0&&l[0].includes("at ")){let m=l[0].trim(),b=m.indexOf("at");d=m.slice(b+2).trim().replace(/\s+/g," "),l.shift();}let h=l.map(m=>{let b=m.trim(),f=b.split(/\s+/);if(f.length===1)return {color:E.fromString(b)};let y=f[f.length-1];if(/^-?\d*\.?\d+(%|px)?$/.test(y)){let v=b.slice(0,b.lastIndexOf(y)).trim();return {color:E.fromString(v),offset:y}}return {color:E.fromString(b)}}).map(m=>({color:typeof m.color=="string"?E.fromString(m.color):m.color,offset:this._parseOffset(m.offset)})),u=this._fillMissingOffsets(h);return new g(u,d,i)}getNormalizedPosition(){let e=this._position.toLowerCase(),t={center:{x:.5,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1},left:{x:0,y:.5},right:{x:1,y:.5},"top left":{x:0,y:0},"top right":{x:1,y:0},"bottom left":{x:0,y:1},"bottom right":{x:1,y:1}};if(t[e])return t[e];let i=e.split(/\s+/),r=i[0].includes("%")?parseFloat(i[0])/100:.5,o=i[1]&&i[1].includes("%")?parseFloat(i[1])/100:.5;return {x:r,y:o}}static _parseOffset(e){if(e===void 0)return Number.NaN;if(typeof e=="number")return e;let t=parseFloat(e);return isNaN(t)?Number.NaN:e.toString().includes("%")?t/100:t}static _fillMissingOffsets(e){let t=e.map(i=>({...i}));if(!t.some(i=>Number.isFinite(i.offset)))t.forEach((i,r)=>i.offset=r/(t.length-1));else {Number.isFinite(t[0].offset)||(t[0].offset=0),Number.isFinite(t[t.length-1].offset)||(t[t.length-1].offset=1);for(let i=1;i<t.length-1;i++)if(!Number.isFinite(t[i].offset)){let r=i+1;for(;r<t.length&&!Number.isFinite(t[r].offset);)r++;let o=t[i-1].offset,s=t[r].offset,a=r-i,l=(s-o)/(a+1);for(let d=0;d<a;d++)t[i+d].offset=o+l*(d+1);i=r-1;}}return t}getStops(){return this._stops}isRepeating(){return this._repeating}getPosition(){return this._position}};var Lt=class g extends Pt{constructor(t,i){super(t);n(this,"_direction");this._direction=i;}getDirection(){return this._direction}static fromString(t){let i=t.toLowerCase().includes("repeating-linear"),o=ti(t,i?["repeating-linear-gradient()"]:["linear-gradient()"],"gradient()"),s=this._parseString(o);if(s===void 0||s.length===0)throw new Error("No valid gradient string");return this.fromStops(s[0],i)}static fromStops(t,i=false){if(!i){let m=new g(t.stops,t.direction);return m.setRepeating(false),m}let r=[...t.stops].sort((m,b)=>m.offset-b.offset),o=r[0],s=r[r.length-1],a=s.offset-o.offset;if(a<=0)return new g(t.stops,t.direction);let l=[],d=Math.floor(-s.offset/a),c=Math.ceil((1-o.offset)/a);for(let m=d;m<=c;m++){let b=m*a;for(let f of r){let y=f.offset+b;y>=-1e-3&&y<=1.001&&l.push({color:f.color,offset:Math.max(0,Math.min(1,y))});}}let h=l.sort((m,b)=>m.offset-b.offset),u=new g(h,t.direction);return u.setRepeating(true),u}static isValidString(t){try{return this.fromString(t),!0}catch{return false}}};var Dt=class g{constructor(e){n(this,"kind","mesh");n(this,"_points");this._points=e;}static fromPoints(e){if(e.length===0)throw new Error("[MeshGradient] At least one point is required");return new g(e)}static isValidString(e){let t=e.trim();return t.startsWith("mesh-gradient(")&&t.endsWith(")")}static fromString(e){if(!this.isValidString(e))throw new Error(`[MeshGradient] Invalid mesh-gradient string: "${e}"`);let t=e.indexOf("("),i=e.lastIndexOf(")"),s=e.slice(t+1,i).trim().split(/,(?![^(]*\))/).map(a=>{let l=a.trim(),d=l.match(/circle\s+([\d.]+)/),c=d?parseFloat(d[1]):.5,h=l.match(/at\s+(-?[\d.]+)%\s+(-?[\d.]+)%/),u=h?parseFloat(h[1])/100:.5,m=h?parseFloat(h[2])/100:.5,b=l.split(/\s+/),f=b[b.length-1];return {x:u,y:m,radius:c,color:E.fromString(f)}});return new g(s)}getPoints(){return this._points.map(e=>({...e}))}getStops(){return []}isRepeating(){return false}};var ur=(d=>(d.Center="center",d.Top="top",d.Bottom="bottom",d.Left="left",d.Right="right",d.TopLeft="top left",d.TopRight="top right",d.BottomLeft="bottom left",d.BottomRight="bottom right",d))(ur||{}),Ht=class g{constructor(e,t){n(this,"kind","radial");n(this,"_shape");n(this,"_position");n(this,"_extent");n(this,"_repeating");n(this,"_stops");this._stops=g._normalizeStops(e),this._shape=t.shape,this._position=t.position,this._extent=t.extent,this._repeating=t.repeating;}static fromStops(e,t={}){let i=t.shape??"ellipse",r=t.position??"center",o=t.extent??"farthest-corner",s=t.repeating??false,a=e.map(d=>({color:typeof d.color=="string"?E.fromString(d.color):d.color,offset:g._parseOffset(d.offset)})),l=g._fillMissingOffsets(a);return new g(l,{shape:i,position:r,extent:o,repeating:s})}static isValidString(e){try{let t=e.trim();return t.startsWith("radial-gradient")||t.startsWith("repeating-radial-gradient")}catch{return false}}static fromString(e){let t=e.trim(),i=t.startsWith("repeating-radial-gradient"),r=t.startsWith("radial-gradient");if(!i&&!r)throw new Error(`[RadialGradient] Expected radial-gradient but got: "${t}"`);let o=t.indexOf("("),s=t.lastIndexOf(")");if(o===-1||s===-1)throw new Error("[RadialGradient] Invalid syntax");let l=t.slice(o+1,s).trim().split(/,(?![^(]*\))/),d="ellipse",c="center",h="farthest-corner",u=l[0].trim();if(/circle|ellipse|at|closest|farthest/.test(u)){if(u.includes("circle")&&(d="circle"),u.includes("ellipse")&&(d="ellipse"),u.includes("at")){let y=u.indexOf("at");c=u.slice(y+2).trim().replace(/\s+/g," ");}let f=["closest-side","closest-corner","farthest-side","farthest-corner"];for(let y of f)if(u.includes(y)){h=y;break}l.shift();}let b=l.map(f=>{let y=f.trim(),x=y.split(/\s+/);if(x.length===1)return {color:E.fromString(y)};let v=x[x.length-1];if(/^-?\d*\.?\d+(%|px|deg)?$/.test(v)){let I=y.slice(0,y.lastIndexOf(v)).trim();return {color:E.fromString(I),offset:v}}return {color:E.fromString(y)}});return g.fromStops(b,{shape:d,position:c,extent:h,repeating:i})}getNormalizedPosition(){let e=this._position.toLowerCase(),t={center:{x:.5,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1},left:{x:0,y:.5},right:{x:1,y:.5},"top left":{x:0,y:0},"left top":{x:0,y:0},"top right":{x:1,y:0},"right top":{x:1,y:0},"bottom left":{x:0,y:1},"left bottom":{x:0,y:1},"bottom right":{x:1,y:1},"right bottom":{x:1,y:1}};if(t[e])return t[e];let i=e.split(/\s+/),r=this._parseCoord(i[0]),o=i.length>1?this._parseCoord(i[1]):.5;return {x:r,y:o}}_parseCoord(e){let t=parseFloat(e);return e.includes("%")?t/100:t}getStops(){return this._stops}getShape(){return this._shape}getPosition(){return this._position}getExtent(){return this._extent}isRepeating(){return this._repeating}static _parseOffset(e){if(e===void 0)return Number.NaN;if(typeof e=="number")return e;let t=parseFloat(e);return isNaN(t)?Number.NaN:e.toString().includes("%")?t/100:t}static _normalizeStops(e){if(e.length<2)throw new Error("[RadialGradient] Need at least 2 stops");return [...e].sort((t,i)=>t.offset-i.offset)}static _fillMissingOffsets(e){let t=e.map(i=>({...i}));if(t.length<2)throw new Error("[RadialGradient] Need at least 2 stops");if(!t.some(i=>Number.isFinite(i.offset)))t.forEach((i,r)=>i.offset=r/(t.length-1));else {Number.isFinite(t[0].offset)||(t[0].offset=0),Number.isFinite(t[t.length-1].offset)||(t[t.length-1].offset=1);for(let i=1;i<t.length-1;i++)if(!Number.isFinite(t[i].offset)){let r=i+1;for(;r<t.length&&!Number.isFinite(t[r].offset);)r++;let o=t[i-1].offset,s=t[r].offset,a=r-i,l=(s-o)/(a+1);for(let d=0;d<a;d++)t[i+d].offset=o+l*(d+1);i=r-1;}}return t}};var pt=class pt extends O{constructor(t,i){super(t,i,0,0);n(this,"_fill");n(this,"_image");n(this,"_imageOpacity");n(this,"_imageWidth");n(this,"_imageHeight");n(this,"_imageX");n(this,"_imageY");n(this,"_imageOffsetX");n(this,"_imageOffsetY");this._fill=pt.DEFAULT_FILL,this._image="",this._imageWidth="100%",this._imageHeight="100%",this._imageX="50%",this._imageY="50%",this._imageOffsetX=0,this._imageOffsetY=0,this._imageOpacity=1;}getImageOpacity(){return this._imageOpacity}setImageOpacity(t){let i=_.clamp(t,0,1);this._imageOpacity!==i&&(this._imageOpacity=i);}getFill(){return typeof this._fill=="string"?this._fill:culori.formatRgb(this._fill)}setFill(t){let i=t.trim();i!==this._fill&&(culori.parse(i)!==void 0&&(this._fill=i),(Lt.isValidString(i)||Ht.isValidString(i)||Et.isValidString(i)||At.isValidString(i)||Dt.isValidString(i))&&(this._fill=i));}getImage(){return this._image}setImage(t){t!==this._image&&(this._image=t);}getImageWidth(){return this._computeImageWidth(this._imageWidth)}getImageHeight(){return this._computeImageHeight(this._imageHeight)}getImageSize(){return {width:this.getImageWidth(),height:this.getImageHeight()}}setImageWidth(t){t!==this._imageWidth&&(this._imageWidth=t);}setImageHeight(t){t!==this._imageHeight&&(this._imageHeight=t);}setImageSize(t,i){t===this._imageWidth&&i===this._imageHeight||(this._imageWidth=t,this._imageHeight=i);}getImageX(){return this._computeImageX(this._imageX)}getImageY(){return this._computeImageY(this._imageY)}getImagePosition(){return {x:this.getImageX(),y:this.getImageY()}}setImageX(t){t!==this._imageX&&(this._imageX=t);}setImageY(t){t!==this._imageY&&(this._imageY=t);}setImagePosition(t,i){t===this._imageX&&i===this._imageY||(this._imageX=t,this._imageY=i);}destroy(){this._fill=pt.DEFAULT_FILL,this._image="",this._imageWidth=0,this._imageHeight=0,this._imageX=0,this._imageY=0,super.destroy();}getImageOffsetX(){return this._computeImageOffsetX(this._imageOffsetX)}getImageOffsetY(){return this._computeImageOffsetY(this._imageOffsetY)}getImageOffset(){return {x:this.getImageOffsetX(),y:this.getImageOffsetY()}}setImageOffsetX(t){t!==this._imageOffsetX&&(this._imageOffsetX=t);}setImageOffsetY(t){t!==this._imageOffsetY&&(this._imageOffsetY=t);}setImageOffset(t,i){t===this._imageOffsetX&&i===this._imageOffsetY||(this._imageOffsetX=t,this._imageOffsetY=i);}_computeImageWidth(t){return this._resolveSize(t,this.getWidth())}_computeImageHeight(t){return this._resolveSize(t,this.getHeight())}_computeImageX(t){return this._resolvePosition(t,this.getWidth())}_computeImageY(t){return this._resolvePosition(t,this.getHeight())}_resolveSize(t,i){return typeof t=="number"?Math.max(0,t):this._resolvePercent(t,i)}_resolvePosition(t,i){return typeof t=="number"?t:this._resolvePercent(t,i)}_computeImageOffsetX(t){return this._resolveOffset(t,this.getImageWidth())}_computeImageOffsetY(t){return this._resolveOffset(t,this.getImageHeight())}_resolveOffset(t,i){return typeof t=="number"?t:this._resolvePercent(t,i)}_resolvePercent(t,i){let r=Number.parseFloat(t);return Number.isFinite(r)?i*r/100:0}};n(pt,"DEFAULT_FILL",{mode:"rgb",r:30,g:30,b:30});var Nt=pt;var it=class it extends O{constructor(t,i){super(t,i,1,1);n(this,"_camera",new xt);n(this,"_nodes");this._nodes=[],this._camera.setLimits(it.DEFAULT_CAMERA_ZOOM_MIN,it.DEFAULT_CAMERA_ZOOM_MAX);}findNodeById(t){let i=this._nodes.find(r=>r.id===t);if(!i)throw new Error(`Node with id "${String(t)}" was not found.`);return i}findNodeByName(t){return this._nodes.filter(i=>i.getName()===t)}getNodes(){return [...this._nodes]}setNodes(t){this.deleteNodes(),this._nodes.push(...t);}addNode(t){return this._nodes.some(r=>r.id===t.id)?false:(this._nodes.push(t),true)}deleteNode(t){let i=this._nodes.findIndex(r=>r.id===t);return i===-1?false:(this._nodes.splice(i,1),true)}deleteNodes(){this._nodes.length=0;}getViewportWorldCorners(){let{width:t,height:i}=this.getSize(),r=this._camera.screenToWorld({x:0,y:0}),o=this._camera.screenToWorld({x:t,y:0}),s=this._camera.screenToWorld({x:t,y:i}),a=this._camera.screenToWorld({x:0,y:i});return [r,o,s,a]}getViewportWorldAABB(){let[t,i,r,o]=this.getViewportWorldCorners(),s=[t.x,i.x,r.x,o.x],a=[t.y,i.y,r.y,o.y],l=_.toF32(Math.min(...s)),d=_.toF32(Math.max(...s)),c=_.toF32(Math.min(...a)),h=_.toF32(Math.max(...a));return {x:l,y:c,width:_.sub(d,l),height:_.sub(h,c)}}findTopNodeAt(t){for(let i=this._nodes.length-1;i>=0;i--){let r=this._nodes[i];if(r!==void 0&&r.isVisibleInHierarchy()&&r.hitTest(t))return r}return null}destroy(){this.deleteNodes(),this._camera.reset(),super.destroy();}setWidth(t){super.setWidth(t),this._camera.setViewportSize(this.getWidth(),this.getHeight());}setHeight(t){super.setHeight(t),this._camera.setViewportSize(this.getWidth(),this.getHeight());}setSize(t,i){super.setSize(t,i),this._camera.setViewportSize(this.getWidth(),this.getHeight());}getCamera(){return this._camera}};n(it,"DEFAULT_CAMERA_ZOOM_MIN",.001),n(it,"DEFAULT_CAMERA_ZOOM_MAX",500);var kt=it;var Bt=class{constructor(){n(this,"_handlers",new Map);}getHandlers(){return [...this._handlers.values()]}register(e){let t=e.getType();if(this._handlers.has(t))throw new Error(`Overlay handler "${t}" is already registered.`);this._handlers.set(t,e);}get(e){return this._handlers.get(e)??null}has(e){return this._handlers.has(e)}remove(e){let t=this._handlers.get(e);return t?(t.destroy(),this._handlers.delete(e)):false}clear(){for(let e of this._handlers.values())e.clear();}destroy(){for(let e of this._handlers.values())e.destroy();this._handlers.clear();}};var Ot=class Ot{constructor(){n(this,"_enabled");n(this,"_node");this._enabled=true,this._node=null;}getType(){return Ot.TYPE}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}getNode(){return this._node}getNodeId(){return this._node?.id??null}hasNode(){return this._node!==null}setNode(e){this._node?.id!==e?.id&&(this._node=e);}clearNode(){this._node!==null&&(this._node=null);}clear(){this._node=null;}destroy(){this.clear(),this._enabled=false;}};n(Ot,"TYPE","hover");var rt=Ot;var Ft=class Ft{constructor(){n(this,"_enabled");n(this,"_node");this._enabled=false,this._node=null;}getType(){return Ft.TYPE}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}hasNode(){return this._node!==null}getNode(){return this._node}getNodeId(){return this._node?.id??null}setNode(e){this._node=e,this._enabled=true;}clearNode(){this._node=null,this._enabled=false;}getObbCorners(){return this._node?this._node.getWorldViewCorners():[]}containsPoint(e){return !this._enabled||!this._node?false:this._node.hitTest(e)}clear(){this.clearNode();}destroy(){this.clearNode();}};n(Ft,"TYPE","transform");var ot=Ft;var Wt=class Wt{constructor(){n(this,"_enabled");n(this,"_node");this._enabled=false,this._node=null;}getType(){return Wt.TYPE}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}hasNode(){return this._node!==null}getNode(){return this._node}getNodeId(){return this._node?.id??null}setNode(e){this._node=e,this._enabled=true;}clearNode(){this._node=null,this._enabled=false;}getObbCorners(){return this._node?this._node.getWorldViewCorners():[]}getPivotWorldPoint(){if(!this._enabled||!this._node)return null;let e=this._node,t=e.getWorldMatrix(),i=e.getPivot(),r=e.getWidth(),o=e.getHeight(),s={x:i.x*r,y:i.y*o};return {x:t.a*s.x+t.c*s.y+t.tx,y:t.b*s.x+t.d*s.y+t.ty}}clear(){this.clearNode();}destroy(){this.clearNode();}};n(Wt,"TYPE","transform-pivot");var V=Wt;var Gt=class Gt{constructor(){n(this,"_enabled");n(this,"_node");this._enabled=false,this._node=null;}getType(){return Gt.TYPE}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}hasNode(){return this._node!==null}getNode(){return this._node}getNodeId(){return this._node?.id??null}setNode(e){this._node=e,this._enabled=true;}clearNode(){this._node=null,this._enabled=false;}getObbCorners(){return this._node?this._node.getWorldViewCorners():[]}containsPoint(e){if(!this._enabled||!this._node)return false;let t=this._node.getWorldViewCorners();if(t.length<4)return false;let[i,r,o,s]=t,a=this._normalize(this._subtractPoints(r,i)),l=this._normalize(this._subtractPoints(s,i)),d=this._distance(i,r),c=this._distance(i,s),h=this._subtractPoints(e,i),u=this._dot(h,a),m=this._dot(h,l);return u>=0&&u<=d&&m>=0&&m<=c}clear(){this.clearNode();}destroy(){this.clearNode();}_subtractPoints(e,t){return {x:e.x-t.x,y:e.y-t.y}}_dot(e,t){return e.x*t.x+e.y*t.y}_distance(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}_normalize(e){let t=Math.hypot(e.x,e.y);return t===0?{x:0,y:0}:{x:e.x/t,y:e.y/t}}};n(Gt,"TYPE","transform-position");var K=Gt;var gr=["n","e","s","w","ne","nw","se","sw"],Vt=class Vt{constructor(){n(this,"_enabled");n(this,"_node");this._enabled=false,this._node=null;}getType(){return Vt.TYPE}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}hasNode(){return this._node!==null}getNode(){return this._node}getNodeId(){return this._node?.id??null}setNode(e){this._node=e,this._enabled=true;}clearNode(){this._node=null,this._enabled=false;}getAvailableAxes(){return gr}getHandleWorldPoint(e){if(!this._enabled||!this._node)return null;let t=this._node.getWorldViewCorners();if(t.length<4)return null;let[i,r,o,s]=t;switch(e){case "nw":return i;case "ne":return r;case "se":return o;case "sw":return s;case "n":return this._getMidpoint(i,r);case "e":return this._getMidpoint(r,o);case "s":return this._getMidpoint(s,o);case "w":return this._getMidpoint(i,s);default:return null}}getEdgeWorldPoints(e){if(!this._enabled||!this._node)return null;let t=this._node.getWorldViewCorners();if(t.length<4)return null;let[i,r,o,s]=t;switch(e){case "n":return [i,r];case "e":return [r,o];case "s":return [s,o];case "w":return [i,s];default:return null}}hitTestAxis(e){return !this._enabled||!this._node,null}clear(){this.clearNode();}destroy(){this.clearNode();}_getMidpoint(e,t){return {x:(e.x+t.x)*.5,y:(e.y+t.y)*.5}}};n(Vt,"TYPE","transform-resize");var z=Vt;var _r=["ne","nw","se","sw"],Kt=class Kt{constructor(){n(this,"_enabled");n(this,"_node");this._enabled=false,this._node=null;}getType(){return Kt.TYPE}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}hasNode(){return this._node!==null}getNode(){return this._node}getNodeId(){return this._node?.id??null}getPivotWorldPoint(){if(!this._enabled||!this._node)return null;let e=this._node,t=e.getWorldMatrix(),i=e.getPivot(),r=e.getWidth(),o=e.getHeight(),s={x:i.x*r,y:i.y*o};return {x:t.a*s.x+t.c*s.y+t.tx,y:t.b*s.x+t.d*s.y+t.ty}}setNode(e){this._node=e,this._enabled=true;}clearNode(){this._node=null,this._enabled=false;}getAvailableAxes(){return _r}getObbCorners(){return this._node?this._node.getWorldViewCorners():[]}getHandleWorldPoint(e){if(!this._enabled||!this._node)return null;let t=this._node.getWorldViewCorners();if(t.length<4)return null;let[i,r,o,s]=t,a=this._normalize({x:r.x-i.x,y:r.y-i.y}),l=this._normalize({x:s.x-i.x,y:s.y-i.y}),d=0;switch(e){case "nw":return this._addPoints(i,this._addPoints(this._scalePoint(a,-d),this._scalePoint(l,-d)));case "ne":return this._addPoints(r,this._addPoints(this._scalePoint(a,d),this._scalePoint(l,-d)));case "se":return this._addPoints(o,this._addPoints(this._scalePoint(a,d),this._scalePoint(l,d)));case "sw":return this._addPoints(s,this._addPoints(this._scalePoint(a,-d),this._scalePoint(l,d)));default:return null}}clear(){this.clearNode();}destroy(){this.clearNode();}_addPoints(e,t){return {x:e.x+t.x,y:e.y+t.y}}_scalePoint(e,t){return {x:e.x*t,y:e.y*t}}_normalize(e){let t=Math.hypot(e.x,e.y);return t===0?{x:0,y:0}:{x:e.x/t,y:e.y/t}}};n(Kt,"TYPE","transform-rotate");var U=Kt;var fr=["tl","tr","br","bl"];var zt=class zt{constructor(){n(this,"_enabled");n(this,"_node");n(this,"_inset");n(this,"_debugEnabled",false);this._enabled=false,this._node=null,this._inset=10;}isDebugEnabled(){return this._debugEnabled}setDebugEnabled(e){this._debugEnabled=e;}getType(){return zt.TYPE}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}hasNode(){return this._node!==null}getNode(){return this._node}getNodeId(){return this._node?.id??null}setNode(e){this._node=e,this._enabled=true;}clearNode(){this._node=null,this._enabled=false;}getAvailableAxes(){return fr}getHandleWorldPoint(e){let t=this.getSection(e);if(!t)return null;let i=this._getSectionDiagonalPoint(t),r={x:i.x-t.origin.x,y:i.y-t.origin.y},o=Math.hypot(r.x,r.y);if(o<=1e-6)return t.origin;let s=this._getCornerRadiusValue(e),a=this._getSectionMaxRadius(t);if(a<=1e-6)return t.origin;let l=Math.max(0,Math.min(s/a,1)),d=o*l,c={x:r.x/o,y:r.y/o};return {x:t.origin.x+c.x*d,y:t.origin.y+c.y*d}}getHandleWorldPoints(){let e=this.getHandleWorldPoint("tl"),t=this.getHandleWorldPoint("tr"),i=this.getHandleWorldPoint("br"),r=this.getHandleWorldPoint("bl");return !e||!t||!i||!r?null:{tl:e,tr:t,br:i,bl:r}}getSection(e){if(!this._enabled||!this._node)return null;let t=this._node.getWorldViewCorners();if(t.length<4)return null;let[i,r,o,s]=t,a=this._getSectionSize();switch(e){case "tl":return this._createSection(e,i,r,s,a);case "tr":return this._createSection(e,r,i,o,a);case "br":return this._createSection(e,o,s,r,a);case "bl":return this._createSection(e,s,o,i,a);default:return null}}clear(){this.clearNode();}destroy(){this.clearNode();}_getDistance(e,t){return Math.hypot(t.x-e.x,t.y-e.y)}_normalize(e){let t=Math.hypot(e.x,e.y);return t<=1e-6?{x:0,y:0}:{x:e.x/t,y:e.y/t}}_getSectionSize(){if(!this._enabled||!this._node)return 0;let e=this._node.getWorldViewCorners();if(e.length<4)return 0;let[t,i,r,o]=e,s=this._getDistance(t,i),a=this._getDistance(t,o);return Math.min(s,a)*.5}_getCornerRadiusValue(e){if(!this._node)return 0;let t=this._node.getCornerRadius();switch(e){case "tl":return t.tl;case "tr":return t.tr;case "br":return t.br;case "bl":return t.bl;default:return 0}}_getSectionDiagonalPoint(e){return {x:e.xAxisPoint.x+e.yAxisPoint.x-e.origin.x,y:e.xAxisPoint.y+e.yAxisPoint.y-e.origin.y}}_createSection(e,t,i,r,o){let s=this._normalize({x:i.x-t.x,y:i.y-t.y}),a=this._normalize({x:r.x-t.x,y:r.y-t.y}),l={x:t.x+s.x*this._inset+a.x*this._inset,y:t.y+s.y*this._inset+a.y*this._inset},d=Math.max(0,o-this._inset);return {axis:e,origin:l,xAxisPoint:{x:l.x+s.x*d,y:l.y+s.y*d},yAxisPoint:{x:l.x+a.x*d,y:l.y+a.y*d},inset:this._inset,width:d,height:d}}_getSectionMaxRadius(e){return Math.max(0,Math.min(e.width,e.height)+e.inset)}};n(zt,"TYPE","corner-radius");var Y=zt;var Ut=class extends O{constructor(t,i){super(t,i,2,2);n(this,"_selectedNodes");n(this,"_handlerManager");this._selectedNodes=[],this._handlerManager=new Bt,this._handlerManager.register(new rt),this._handlerManager.register(new ot),this._handlerManager.register(new z),this._handlerManager.register(new K),this._handlerManager.register(new U),this._handlerManager.register(new V),this._handlerManager.register(new Y);}getHoveredNode(){return this._getHoverHandle().getNode()}getHoveredNodeId(){return this._getHoverHandle().getNodeId()}setHoveredNode(t){let i=this._getHoverHandle();i.getNodeId()!==(t?.id??null)&&(t?(i.setNode(t),i.setEnabled(true)):(i.clearNode(),i.setEnabled(false)));}clearHoveredNode(){let t=this._getHoverHandle();t.hasNode()&&(t.clearNode(),t.setEnabled(false));}getSelectedNodes(){return [...this._selectedNodes]}getSelectedNodeIds(){return this._selectedNodes.map(t=>t.id)}isNodeSelected(t){return this._selectedNodes.some(i=>i.id===t)}setSelectedNodes(t){this._selectedNodes.length=0;for(let i of t)this._selectedNodes.some(o=>o.id===i.id)||this._selectedNodes.push(i);}addSelectedNode(t){return this._selectedNodes.some(r=>r.id===t.id)?false:(this._selectedNodes.push(t),true)}removeSelectedNode(t){let i=this._selectedNodes.findIndex(r=>r.id===t);return i===-1?false:(this._selectedNodes.splice(i,1),true)}clearSelectedNodes(){this._selectedNodes.length=0;}getHandlerManager(){return this._handlerManager}clear(){this._selectedNodes.length=0,this._handlerManager.clear();}destroy(){this.clear(),this._handlerManager.destroy(),super.destroy();}_getHoverHandle(){let t=this._handlerManager.get(rt.TYPE);if(!(t instanceof rt))throw new Error("Hover handle is not registered.");return t}};var Yt=class{constructor(){n(this,"_modules");this._modules=new Map;}register(e){let t=e.getType();if(this._modules.has(t))throw new Error(`UI module "${t}" is already registered.`);this._modules.set(t,e);}unregister(e){let t=this._modules.get(e);return t?(t.destroy(),this._modules.delete(e),true):false}get(e){return this._modules.get(e)??null}has(e){return this._modules.has(e)}getAll(){return [...this._modules.values()]}clear(){for(let e of this._modules.values())e.clear();}destroy(){for(let e of this._modules.values())e.destroy();this._modules.clear();}};var Xt=class{constructor(e){n(this,"_type");n(this,"_enabled");this._type=e,this._enabled=true;}getType(){return this._type}isEnabled(){return this._enabled}setEnabled(e){this._enabled!==e&&(this._enabled=e);}attach(e){}detach(){}clear(){}update(){}destroy(){this.detach();}};var mt=class mt{constructor(e){n(this,"_id");n(this,"_value");n(this,"_color");n(this,"_thickness");n(this,"_visible");this._id=e,this._value=0,this._color=mt.DEFAULT_COLOR,this._thickness=1,this._visible=true;}getId(){return this._id}isVisible(){return this._visible}getValue(){return this._value}setVisible(e){this._visible!==e&&(this._visible=e);}setValue(e){this._value!==e&&(this._value=_.toF32(e));}getColor(){return culori.formatRgb(this._color)}setColor(e){let t=culori.parse(e);if(!t)throw new Error(`Invalid color value: "${e}"`);culori.formatRgb(this._color)!==culori.formatRgb(t)&&(this._color=t);}getThickness(){return this._thickness}setThickness(e){let t=_.max(1,_.round(e));this._thickness!==t&&(this._thickness=t);}reset(){this._value=0,this._color=mt.DEFAULT_COLOR,this._thickness=1,this._visible=true;}};n(mt,"DEFAULT_COLOR",{mode:"rgb",r:0,g:0,b:0});var $t=mt;var R=class R extends Xt{constructor(t){super(R.TYPE);n(this,"_world");n(this,"_cornerVisible");n(this,"_thickness");n(this,"_background");n(this,"_tickColor");n(this,"_textColor");n(this,"_font");n(this,"_minLabelPx");n(this,"_minTickPx");n(this,"_minMajorTickPx");n(this,"_root",null);n(this,"_portal",null);n(this,"_topWrap",null);n(this,"_leftWrap",null);n(this,"_corner",null);n(this,"_topCanvas",null);n(this,"_leftCanvas",null);n(this,"_guidesHorizontal",[]);n(this,"_guidesVertical",[]);n(this,"_guideElementsHorizontal",new Map);n(this,"_guideElementsVertical",new Map);n(this,"_guideIdCounter",1);n(this,"_focusedGuideId",null);n(this,"_focusedGuideAxis",null);n(this,"_activeGuidePreview",null);n(this,"_activeGuideAxis",null);n(this,"_activeGuidePointerId",null);n(this,"_activeGuideOwner",null);n(this,"_activeDraggedGuideId",null);n(this,"_activeDraggedGuideAxis",null);n(this,"_onTopPointerDown",t=>{if(!this._portal||!this._topWrap)return;t.preventDefault();let i=this._portal.getBoundingClientRect();this._startGuideDrag("horizontal",t.clientY-i.top,t.pointerId,this._topWrap);});n(this,"_onLeftPointerDown",t=>{if(!this._portal||!this._leftWrap)return;t.preventDefault();let i=this._portal.getBoundingClientRect();this._startGuideDrag("vertical",t.clientX-i.left,t.pointerId,this._leftWrap);});n(this,"_onWindowPointerDown",t=>{if(!(t.target instanceof HTMLElement)){this._clearFocusedGuide();return}t.target.closest("[data-ruler-guide='true']")||this._clearFocusedGuide();});n(this,"_onWindowPointerMove",t=>{if(!this._portal||t.pointerId!==this._activeGuidePointerId)return;t.preventDefault();let i=this._portal.getBoundingClientRect(),r=this._world.getCamera();if(this._activeDraggedGuideId!==null&&this._activeDraggedGuideAxis){let o=this._activeDraggedGuideAxis,s=this._getGuideByAxisAndId(o,this._activeDraggedGuideId);s&&(o==="vertical"?s.setValue(r.screenToWorld({x:t.clientX-i.left,y:0}).x):s.setValue(r.screenToWorld({x:0,y:t.clientY-i.top}).y),this._syncGuideElements());return}this._activeGuidePreview&&this._activeGuideAxis&&(this._activeGuideAxis==="vertical"?this._activeGuidePreview.style.left=`${t.clientX-i.left}px`:this._activeGuidePreview.style.top=`${t.clientY-i.top}px`);});n(this,"_onWindowPointerUp",t=>{if(!this._portal||t.pointerId!==this._activeGuidePointerId)return;if(t.preventDefault(),!this._activeGuidePreview||!this._activeGuideAxis){this._cancelActiveGuideDrag();return}let i=this._portal.getBoundingClientRect(),r=this._world.getCamera(),o=this._thickness+2,s=this._activeGuideAxis;if(s==="vertical"){let a=Math.round(t.clientX-i.left);a>o&&this._addGuide(s,r.screenToWorld({x:a,y:0}).x);}else {let a=Math.round(t.clientY-i.top);a>o&&this._addGuide(s,r.screenToWorld({x:0,y:a}).y);}this._cancelActiveGuideDrag();});n(this,"_onWindowKeyDown",t=>{t.key!=="Delete"&&t.key!=="Backspace"||this._focusedGuideId===null||this._focusedGuideAxis===null||(t.preventDefault(),this._removeGuide(this._focusedGuideAxis,this._focusedGuideId),this._focusedGuideId=null,this._focusedGuideAxis=null);});n(this,"_onGuidePointerDown",(t,i,r)=>{this._portal&&(t.preventDefault(),t.stopPropagation(),this._focusGuide(i,r),this._cancelActiveGuideDrag(),this._activeGuidePointerId=t.pointerId,this._activeGuideAxis=i,this._activeDraggedGuideId=r,this._activeDraggedGuideAxis=i,window.addEventListener("pointermove",this._onWindowPointerMove,{passive:false}),window.addEventListener("pointerup",this._onWindowPointerUp,{passive:false}));});this._world=t,this._cornerVisible=true,this._thickness=R.DEFAULT_THICKNESS,this._background=R.DEFAULT_BACKGROUND,this._tickColor=R.DEFAULT_TICK_COLOR,this._textColor=R.DEFAULT_TEXT_COLOR,this._font=R.DEFAULT_FONT,this._minLabelPx=R.DEFAULT_MIN_LABEL_PX,this._minTickPx=R.DEFAULT_MIN_TICK_PX,this._minMajorTickPx=R.DEFAULT_MIN_MAJOR_TICK_PX;}isCornerVisible(){return this._cornerVisible}setCornerVisible(t){this._cornerVisible!==t&&(this._cornerVisible=t,this._syncCornerVisibility());}getThickness(){return this._thickness}setThickness(t){let i=Math.max(0,_.toF32(t));this._thickness!==i&&(this._thickness=i,this._syncLayout());}getBackground(){return this._background}setBackground(t){let i=t.trim();this._background!==i&&(this._background=i,this._syncStyles());}getTickColor(){return this._tickColor}setTickColor(t){let i=t.trim();this._tickColor!==i&&(this._tickColor=i);}getTextColor(){return this._textColor}setTextColor(t){let i=t.trim();this._textColor!==i&&(this._textColor=i);}getFont(){return this._font}setFont(t){let i=t.trim();this._font!==i&&(this._font=i);}getMinLabelPx(){return this._minLabelPx}setMinLabelPx(t){let i=Math.max(0,_.toF32(t));this._minLabelPx!==i&&(this._minLabelPx=i);}getMinTickPx(){return this._minTickPx}setMinTickPx(t){let i=Math.max(0,_.toF32(t));this._minTickPx!==i&&(this._minTickPx=i);}getMinMajorTickPx(){return this._minMajorTickPx}setMinMajorTickPx(t){let i=Math.max(0,_.toF32(t));this._minMajorTickPx!==i&&(this._minMajorTickPx=i);}getGuideHorizontalRulerById(t){return this._guidesHorizontal.find(i=>i.getId()===t)??null}getGuideVerticalRulerById(t){return this._guidesVertical.find(i=>i.getId()===t)??null}getGuidesHorizontalRuler(){return [...this._guidesHorizontal]}getGuidesVerticalRuler(){return [...this._guidesVertical]}addGuideForHorizontalRuler(t){return this._addGuide("horizontal",t)}addGuideForVerticalRuler(t){return this._addGuide("vertical",t)}removeGuideFromHorizontalRuler(t){return this._removeGuide("horizontal",t)}removeGuideFromVerticalRuler(t){return this._removeGuide("vertical",t)}clearGuidesFromHorizontal(){this._clearGuides("horizontal");}clearGuidesFromVertical(){this._clearGuides("vertical");}clearGuides(){this._clearGuides("horizontal"),this._clearGuides("vertical");}attach(t){this.detach(),this._root=t,this._createDOM(),this._syncLayout(),this._syncStyles(),this._syncCornerVisibility(),this._syncGuideElements(),this._topWrap?.addEventListener("pointerdown",this._onTopPointerDown,{passive:false}),this._leftWrap?.addEventListener("pointerdown",this._onLeftPointerDown,{passive:false}),window.addEventListener("pointerdown",this._onWindowPointerDown,true),window.addEventListener("keydown",this._onWindowKeyDown,true);}detach(){this._topWrap?.removeEventListener("pointerdown",this._onTopPointerDown),this._leftWrap?.removeEventListener("pointerdown",this._onLeftPointerDown),window.removeEventListener("pointerdown",this._onWindowPointerDown,true),window.removeEventListener("keydown",this._onWindowKeyDown,true),window.removeEventListener("pointermove",this._onWindowPointerMove),window.removeEventListener("pointerup",this._onWindowPointerUp),this._cancelActiveGuideDrag(),this._portal?.remove(),this._portal=null,this._topWrap=null,this._leftWrap=null,this._corner=null,this._topCanvas=null,this._leftCanvas=null,this._root=null;}clear(){this.clearGuides();}update(){this._portal&&(this._portal.style.display=this.isEnabled()?"block":"none",this.isEnabled()&&(this._syncGuideElements(),this._draw()));}destroy(){this.clear(),super.destroy();}_addGuide(t,i){let r=t==="horizontal"?this._guidesHorizontal:this._guidesVertical,o=t==="horizontal"?this._guideElementsHorizontal:this._guideElementsVertical;if(r.length>=100||!this._portal)return false;this._clearFocusedGuide();let s=new $t(this._guideIdCounter++);s.setValue(i),s.setColor(R.FOCUSED_GUIDE_COLOR);let a=this._createGuideElement(t,s);return this._portal.appendChild(a),r.push(s),o.set(s.getId(),a),this._focusedGuideId=s.getId(),this._focusedGuideAxis=t,this._syncGuideElements(),true}_removeGuide(t,i){let r=t==="horizontal"?this._guidesHorizontal:this._guidesVertical,o=t==="horizontal"?this._guideElementsHorizontal:this._guideElementsVertical,s=r.findIndex(a=>a.getId()===i);return s===-1?false:(r.splice(s,1),o.get(i)?.remove(),o.delete(i),this._focusedGuideAxis===t&&this._focusedGuideId===i&&(this._focusedGuideId=null,this._focusedGuideAxis=null),true)}_clearGuides(t){let i=t==="horizontal"?this._guidesHorizontal:this._guidesVertical,r=t==="horizontal"?this._guideElementsHorizontal:this._guideElementsVertical;for(let o of i)r.get(o.getId())?.remove();i.length=0,r.clear();}_focusGuide(t,i){if(this._focusedGuideId===i&&this._focusedGuideAxis===t)return;this._clearFocusedGuide();let r=this._getGuideByAxisAndId(t,i);r&&(r.setColor(R.FOCUSED_GUIDE_COLOR),this._focusedGuideId=i,this._focusedGuideAxis=t,this._syncGuideElements());}_clearFocusedGuide(){if(this._focusedGuideId===null||this._focusedGuideAxis===null)return;this._getGuideByAxisAndId(this._focusedGuideAxis,this._focusedGuideId)?.setColor(R.DEFAULT_GUIDE_COLOR),this._focusedGuideId=null,this._focusedGuideAxis=null,this._syncGuideElements();}_getGuideByAxisAndId(t,i){return t==="horizontal"?this.getGuideHorizontalRulerById(i):this.getGuideVerticalRulerById(i)}_startGuideDrag(t,i,r,o){if(!this._portal)return;this._cancelActiveGuideDrag();let s=document.createElement("div");s.style.cssText="position:absolute; pointer-events:none; z-index:20;",s.style.background=R.FOCUSED_GUIDE_COLOR,t==="vertical"?(s.style.cssText+="top:0; bottom:0; width:1px;",s.style.left=`${i}px`):(s.style.cssText+="left:0; right:0; height:1px;",s.style.top=`${i}px`),this._portal.appendChild(s),this._activeGuidePreview=s,this._activeGuideAxis=t,this._activeGuidePointerId=r,this._activeGuideOwner=o;try{o.setPointerCapture(r);}catch{}window.addEventListener("pointermove",this._onWindowPointerMove,{passive:false}),window.addEventListener("pointerup",this._onWindowPointerUp,{passive:false});}_cancelActiveGuideDrag(){if(this._activeGuideOwner&&this._activeGuidePointerId!==null)try{this._activeGuideOwner.releasePointerCapture(this._activeGuidePointerId);}catch{}window.removeEventListener("pointermove",this._onWindowPointerMove),window.removeEventListener("pointerup",this._onWindowPointerUp),this._activeGuidePreview?.remove(),this._activeGuidePreview=null,this._activeGuideAxis=null,this._activeGuidePointerId=null,this._activeGuideOwner=null,this._activeDraggedGuideId=null,this._activeDraggedGuideAxis=null;}_createDOM(){if(!this._root)return;let t=document.createElement("div");t.className="flowscape-ui-ruler",t.style.cssText="position:absolute; left:0; top:0; width:100%; height:100%; pointer-events:none;";let i=document.createElement("div");i.className="flowscape-ui-ruler-top",i.style.cssText="position:absolute; pointer-events:auto;",i.appendChild(this._createCanvas());let r=document.createElement("div");r.className="flowscape-ui-ruler-left",r.style.cssText="position:absolute; pointer-events:auto;",r.appendChild(this._createCanvas());let o=document.createElement("div");o.className="flowscape-ui-ruler-corner",o.style.cssText="position:absolute; pointer-events:none;",t.appendChild(i),t.appendChild(r),t.appendChild(o),this._root.appendChild(t),this._portal=t,this._topWrap=i,this._leftWrap=r,this._corner=o,this._topCanvas=i.firstElementChild,this._leftCanvas=r.firstElementChild;}_createCanvas(){let t=document.createElement("canvas");return t.style.cssText="display:block; width:100%; height:100%;",t}_createGuideElement(t,i){let r=document.createElement("div");r.style.cssText="position:absolute; pointer-events:auto; z-index:15;",r.dataset.rulerGuide="true";let o=document.createElement("div");return o.style.cssText="position:absolute; pointer-events:none;",o.style.background=i.getColor(),t==="vertical"?(r.style.cssText+="top:0; bottom:0; width:10px; cursor:ew-resize;",o.style.cssText+="top:0; bottom:0; left:50%; transform:translateX(-50%);",o.style.width=`${Math.max(1,i.getThickness())}px`):(r.style.cssText+="left:0; right:0; height:10px; cursor:ns-resize;",o.style.cssText+="left:0; right:0; top:50%; transform:translateY(-50%);",o.style.height=`${Math.max(1,i.getThickness())}px`),r.appendChild(o),this._applyGuideElementStyles(r,t,i),r.addEventListener("pointerdown",s=>{this._onGuidePointerDown(s,t,i.getId());}),r}_applyGuideElementStyles(t,i,r){t.style.display=r.isVisible()?"block":"none";let o=t.firstElementChild;if(!o)return;let s=this._world.getCamera();if(o.style.background=r.getColor(),i==="vertical"){let a=s.worldToScreen({x:r.getValue(),y:0}).x;t.style.left=`${a-5}px`,o.style.width=`${Math.max(1,r.getThickness())}px`;}else {let a=s.worldToScreen({x:0,y:r.getValue()}).y;t.style.top=`${a-5}px`,o.style.height=`${Math.max(1,r.getThickness())}px`;}}_syncLayout(){if(!this._topWrap||!this._leftWrap||!this._corner)return;let t=`${this._thickness}px`;this._topWrap.style.left=t,this._topWrap.style.top="0",this._topWrap.style.right="0",this._topWrap.style.height=t,this._leftWrap.style.left="0",this._leftWrap.style.top=t,this._leftWrap.style.bottom="0",this._leftWrap.style.width=t,this._corner.style.left="0",this._corner.style.top="0",this._corner.style.width=t,this._corner.style.height=t;}_syncStyles(){if(!this._topWrap||!this._leftWrap||!this._corner)return;let t="1px solid rgba(255,255,255,0.35)";this._topWrap.style.background=this._background,this._leftWrap.style.background=this._background,this._corner.style.background=this._background,this._topWrap.style.borderBottom=t,this._leftWrap.style.borderRight=t,this._corner.style.borderBottom=t,this._corner.style.borderRight=t,this._topWrap.style.cursor="n-resize",this._leftWrap.style.cursor="w-resize";}_syncCornerVisibility(){this._corner&&(this._corner.style.display=this._cornerVisible?"block":"none");}_syncGuideElements(){for(let t of this._guidesHorizontal){let i=this._guideElementsHorizontal.get(t.getId());i&&this._applyGuideElementStyles(i,"horizontal",t);}for(let t of this._guidesVertical){let i=this._guideElementsVertical.get(t.getId());i&&this._applyGuideElementStyles(i,"vertical",t);}}_draw(){if(!this._root||!this._topCanvas||!this._leftCanvas)return;let t=window.devicePixelRatio||1,i=this._root.clientWidth,r=this._root.clientHeight;if(i<=1||r<=1)return;let o=this._world.getCamera().getState();this._resizeCanvas(this._topCanvas,i-this._thickness,this._thickness,t),this._resizeCanvas(this._leftCanvas,this._thickness,r-this._thickness,t);let s=this._topCanvas.getContext("2d"),a=this._leftCanvas.getContext("2d");!s||!a||(this._drawTop(s,i-this._thickness,this._thickness,t,o),this._drawLeft(a,this._thickness,r-this._thickness,t,o));}_drawTop(t,i,r,o,s){t.save(),t.setTransform(o,0,0,o,0,0),t.clearRect(0,0,i,r),t.strokeStyle=this._tickColor,t.fillStyle=this._textColor,t.font=this._font,t.textBaseline="top";let a=this._getRulerStepWorld(s.scale),l=i+this._thickness,d=s.x-l/2/s.scale,c=s.x+l/2/s.scale,h=Math.floor(d/a)-2,u=Math.ceil(c/a)+2;for(let m=h;m<=u;m++){let b=m*a,f=(b-d)*s.scale-this._thickness;if(f<-50||f>i+50)continue;let y=this._edgeFadeAlpha(f,40);if(y<=.01)continue;let x=m%1===0,v=x?Math.max(6,r*.35):Math.max(3,r*.18),w=Math.round(f)+.5;if(t.save(),t.globalAlpha=y,t.beginPath(),t.moveTo(w,r),t.lineTo(w,r-v),t.stroke(),x){let I=String(Math.round(b));t.fillText(I,w-t.measureText(I).width/2,2);}t.restore();}t.restore();}_drawLeft(t,i,r,o,s){t.save(),t.setTransform(o,0,0,o,0,0),t.clearRect(0,0,i,r),t.strokeStyle=this._tickColor,t.fillStyle=this._textColor,t.font=this._font,t.textBaseline="middle";let a=this._getRulerStepWorld(s.scale),l=r+this._thickness,d=s.y-l/2/s.scale,c=s.y+l/2/s.scale,h=Math.floor(d/a)-2,u=Math.ceil(c/a)+2;for(let m=h;m<=u;m++){let b=m*a,f=(b-d)*s.scale-this._thickness;if(f<-50||f>r+50)continue;let y=this._edgeFadeAlpha(f,40);if(y<=.01)continue;let x=m%1===0,v=x?Math.max(6,i*.35):Math.max(3,i*.18),w=Math.round(f)+.5;t.save(),t.globalAlpha=y,t.beginPath(),t.moveTo(i,w),t.lineTo(i-v,w),t.stroke(),x&&(t.translate(8,w),t.rotate(-Math.PI/2),t.textAlign="center",t.textBaseline="middle",t.fillText(String(Math.round(b)),0,0)),t.restore();}t.restore();}_resizeCanvas(t,i,r,o){let s=Math.max(1,Math.floor(i*o)),a=Math.max(1,Math.floor(r*o));t.width!==s&&(t.width=s),t.height!==a&&(t.height=a);}_getRulerStepWorld(t){let i=Math.max(this._minLabelPx,60)/Math.max(t,1e-6),r=[1,2,5,10,20,50,100,200,500,1e3,2e3,5e3,1e4,2e4,5e4];return r.find(o=>o>=i)??r[r.length-1]??1e3}_edgeFadeAlpha(t,i){if(t>=i)return 1;let r=Math.max(0,Math.min(1,t/i));return r*r*(3-2*r)}};n(R,"TYPE","ruler"),n(R,"DEFAULT_BACKGROUND","rgba(30,30,30,0.92)"),n(R,"DEFAULT_TICK_COLOR","rgba(255,255,255,0.55)"),n(R,"DEFAULT_TEXT_COLOR","rgba(255,255,255,0.80)"),n(R,"DEFAULT_FONT","11px system-ui, -apple-system, Segoe UI, Roboto, sans-serif"),n(R,"DEFAULT_GUIDE_COLOR","#0D93F3"),n(R,"FOCUSED_GUIDE_COLOR","#F35D0D"),n(R,"DEFAULT_THICKNESS",22),n(R,"DEFAULT_MIN_LABEL_PX",110),n(R,"DEFAULT_MIN_TICK_PX",8),n(R,"DEFAULT_MIN_MAJOR_TICK_PX",20);var qt=R;var jt=class extends O{constructor(t,i,r){super(i,r,3,3);n(this,"_manager");this._manager=new Yt,this._enabled=true,this._manager.register(new qt(t));}getManager(){return this._manager}clear(){this._manager.clear();}destroy(){this.clear(),this._manager.destroy(),super.destroy();}};var Zt=class{constructor(){n(this,"id","overlay-transform-move");n(this,"_context",null);n(this,"_isMoving",false);n(this,"_moveStartWorldPoint",null);n(this,"_moveStartNodePosition",null);}attach(e){this._context=e;}detach(){this._resetMoveSession(),this._context=null;}destroy(){this.detach();}update(){this._context&&this._isMoving&&(this._updateMoveFromInput(),this._tryEndMove());}isActive(){return this._isMoving}hitTest(e){if(!this._context)return false;let{overlay:t,world:i}=this._context;if(!t.isEnabled())return false;let r=t.getHandlerManager().get(K.TYPE);if(!r||!r.isEnabled()||!r.hasNode())return false;let o=i.getCamera().screenToWorld(e);return r.containsPoint(o)}tryBegin(e){if(!this._context)return false;let{overlay:t,world:i}=this._context;if(!t.isEnabled())return false;let r=t.getHandlerManager().get(K.TYPE);if(!r||!r.isEnabled()||!r.hasNode())return false;let o=i.getCamera().screenToWorld(e);if(!r.containsPoint(o))return false;let s=r.getNode();return s?(this._isMoving=true,this._moveStartWorldPoint=o,this._moveStartNodePosition=s.getPosition(),S.setCursor("grab"),true):false}hasNode(){return this._getHandle()?.hasNode()??false}getNodeId(){return this._getHandle()?.getNodeId()??null}setNode(e){this._getHandle()?.setNode(e);}clearNode(){this._getHandle()?.clearNode();}_updateMoveFromInput(){if(!this._context||!this._isMoving||!this._moveStartWorldPoint||!this._moveStartNodePosition)return;let{world:e}=this._context,i=this._getHandle()?.getNode();if(!i)return;let r=this._getStagePointerFromInput(),o=e.getCamera().screenToWorld(r),s=o.x-this._moveStartWorldPoint.x,a=o.y-this._moveStartWorldPoint.y;i.setPosition(_.toF32(Math.round(this._moveStartNodePosition.x+s)),_.toF32(Math.round(this._moveStartNodePosition.y+a))),this._context.emitChange();}_tryEndMove(){this._isMoving&&(S.getMouseButtonUp(0)||!S.getMouseButton(0))&&this._resetMoveSession();}_resetMoveSession(){this._isMoving=false,this._moveStartWorldPoint=null,this._moveStartNodePosition=null,S.resetCursor();}_getHandle(){return this._context?this._context.overlay.getHandlerManager().get(K.TYPE):null}_getStagePointerFromInput(){let e=this._context.stage.container().getBoundingClientRect();return {x:S.pointerPosition.x-e.left,y:S.pointerPosition.y-e.top}}};function W(g){let e=g.a*g.d-g.b*g.c;if(e===0)throw new Error("Can't invert a matrix with zero determinant");let t=1/e;return {a:g.d*t,b:-g.b*t,c:-g.c*t,d:g.a*t,tx:(g.c*g.ty-g.d*g.tx)*t,ty:(g.b*g.tx-g.a*g.ty)*t}}var Qt=class{constructor(){n(this,"id","overlay-transform-pivot");n(this,"_context",null);n(this,"_isPivoting",false);}attach(e){this._context=e;}detach(){this._resetPivotSession(),this._context=null;}destroy(){this.detach();}update(){this._context&&this._isPivoting&&(this._updatePivotFromInput(),this._tryEndPivot());}isActive(){return this._isPivoting}hitTest(e){if(!this._context)return false;let{overlay:t}=this._context;return t.isEnabled()?this._hitTestPivot(e):false}tryBegin(e){if(!this._context)return false;let{overlay:t}=this._context;if(!t.isEnabled())return false;let i=this._getHandle();return !i||!i.isEnabled()||!i.hasNode()||!this._hitTestPivot(e)?false:(this._isPivoting=true,true)}hasNode(){return this._getHandle()?.hasNode()??false}getNodeId(){return this._getHandle()?.getNodeId()??null}setNode(e){this._getHandle()?.setNode(e);}clearNode(){this._getHandle()?.clearNode();}_updatePivotFromInput(){if(!this._context||!this._isPivoting)return;let{world:e}=this._context,t=this._getHandle(),i=t?.getNode();if(!i)return;let r=i.getWidth(),o=i.getHeight();if(r===0||o===0)return;let s=this._getStagePointerFromInput(),a=e.getCamera().screenToWorld(s),l=i.getWorldMatrix();try{let d=W(l),c={x:d.a*a.x+d.c*a.y+d.tx,y:d.b*a.x+d.d*a.y+d.ty},h=c.x/r,u=c.y/o;i.setPivot(h,u);let m=t?.getPivotWorldPoint();if(!m)return;let b=a.x-m.x,f=a.y-m.y;i.setPosition(i.getX()+b,i.getY()+f),this._context.emitChange();}catch{return}}_tryEndPivot(){this._isPivoting&&(S.getMouseButtonUp(0)||!S.getMouseButton(0))&&this._resetPivotSession();}_resetPivotSession(){this._isPivoting=false;}_getHandle(){return this._context?this._context.overlay.getHandlerManager().get(V.TYPE):null}_hitTestPivot(e){let{world:t}=this._context,i=this._getHandle();if(!i||!i.isEnabled()||!i.hasNode())return false;let r=i.getPivotWorldPoint();if(!r)return false;let s=t.getCamera().worldToScreen(r),a=10,l=e.x-s.x,d=e.y-s.y;return Math.hypot(l,d)<=a}_getStagePointerFromInput(){let e=this._context.stage.container().getBoundingClientRect();return {x:S.pointerPosition.x-e.left,y:S.pointerPosition.y-e.top}}};var Jt=class{constructor(){n(this,"id","overlay-transform-resize");n(this,"_context",null);n(this,"_isResizing",false);n(this,"_activeResizeAxis",null);n(this,"_resizeStartWorldPoint",null);n(this,"_resizeStartWidth",0);n(this,"_resizeStartHeight",0);n(this,"_resizeStartCorners",null);}attach(e){this._context=e;}detach(){this._resetResizeSession(),this._context=null;}destroy(){this.detach();}update(){if(this._context){if(this._isResizing){this._updateResizeFromInput(),this._tryEndResize();return}this._updateHoverCursor();}}isActive(){return this._isResizing}hitTest(e){if(!this._context)return false;let{overlay:t}=this._context;return t.isEnabled()?this._hitTestResizeAxis(e)!==null:false}tryBegin(e){if(!this._context)return false;let{overlay:t,world:i}=this._context;if(!t.isEnabled())return false;let r=this._getHandle();if(!r||!r.isEnabled()||!r.hasNode())return false;let o=this._hitTestResizeAxis(e);if(!o)return false;let s=r.getNode();if(!s)return false;let a=s.getWorldCorners();return a.length<4?false:(this._isResizing=true,this._activeResizeAxis=o,this._resizeStartWorldPoint=i.getCamera().screenToWorld(e),this._resizeStartWidth=s.getWidth(),this._resizeStartHeight=s.getHeight(),this._resizeStartCorners=[a[0],a[1],a[2],a[3]],S.setCursor(this._getResizeCursor(o)),true)}hasNode(){return this._getHandle()?.hasNode()??false}getNodeId(){return this._getHandle()?.getNodeId()??null}setNode(e){this._getHandle()?.setNode(e);}clearNode(){this._getHandle()?.clearNode();}getHoverAxis(e){if(!this._context)return null;let{overlay:t}=this._context;return t.isEnabled()?this._hitTestResizeAxis(e):null}getCursor(e){return this._getResizeCursor(e)}getHoverCursor(e){if(!this._context)return null;if(this._isResizing)return this._activeResizeAxis?this._getResizeCursor(this._activeResizeAxis):null;let t=this._hitTestResizeAxis(e);return t?this._getResizeCursor(t):null}_resetResizeSession(){this._isResizing=false,this._activeResizeAxis=null,this._resizeStartWorldPoint=null,this._resizeStartWidth=0,this._resizeStartHeight=0,this._resizeStartCorners=null,S.resetCursor();}_updateResizeFromInput(){if(!this._context||!this._isResizing||!this._activeResizeAxis||!this._resizeStartWorldPoint||!this._resizeStartCorners)return;let{world:e}=this._context,i=this._getHandle()?.getNode();if(!i)return;let r=this._getStagePointerFromInput(),o=e.getCamera().screenToWorld(r),s=this._subtractPoints(o,this._resizeStartWorldPoint),[a,l,d,c]=this._resizeStartCorners,h=this._normalize(this._subtractPoints(l,a)),u=this._normalize(this._subtractPoints(c,a)),m=this._dot(s,h),b=this._dot(s,u),f=this._resizeStartWidth,y=this._resizeStartHeight,x=f,v=y,w=a,I=false,C=false;switch(this._activeResizeAxis){case "e":x=f+m,w=a;break;case "w":x=f-m,w=l,I=true;break;case "s":v=y+b,w=a;break;case "n":v=y-b,w=c,C=true;break;case "se":x=f+m,v=y+b,w=a;break;case "sw":x=f-m,v=y+b,w=l,I=true;break;case "ne":x=f+m,v=y-b,w=c,C=true;break;case "nw":x=f-m,v=y-b,w=d,I=true,C=true;break}let T=Math.abs(x),A=Math.abs(v),P=I?-Math.max(x,0):Math.min(x,0),D=C?-Math.max(v,0):Math.min(v,0),bt=this._addPoints(w,this._addPoints(this._scalePoint(h,P),this._scalePoint(u,D))),yt=this._addPoints(bt,this._addPoints(this._scalePoint(h,T/2),this._scalePoint(u,A/2)));i.setPosition(yt.x,yt.y),i.setSize(T,A),this._context.emitChange();}_tryEndResize(){this._isResizing&&(S.getMouseButtonUp(0)||!S.getMouseButton(0))&&this._resetResizeSession();}_getHandle(){return this._context?this._context.overlay.getHandlerManager().get(z.TYPE):null}_getStagePointerFromInput(){let e=this._context.stage.container().getBoundingClientRect();return {x:S.pointerPosition.x-e.left,y:S.pointerPosition.y-e.top}}_hitTestResizeAxis(e){let{world:t}=this._context,i=this._getHandle();if(!i||!i.isEnabled()||!i.hasNode())return null;let r=t.getCamera(),o=4,s=6;for(let a of ["nw","ne","se","sw"]){let l=i.getHandleWorldPoint(a);if(!l)continue;let d=r.worldToScreen(l);if(e.x>=d.x-o&&e.x<=d.x+o&&e.y>=d.y-o&&e.y<=d.y+o)return a}for(let a of ["n","e","s","w"]){let l=i.getEdgeWorldPoints(a);if(!l)continue;let d=r.worldToScreen(l[0]),c=r.worldToScreen(l[1]);if(this._isPointNearSegment(e,d,c,s))return a}return null}_isPointNearSegment(e,t,i,r){return this._distanceToSegment(e,t,i)<=r}_distanceToSegment(e,t,i){let r=i.x-t.x,o=i.y-t.y;if(r===0&&o===0)return Math.hypot(e.x-t.x,e.y-t.y);let s=Math.max(0,Math.min(1,((e.x-t.x)*r+(e.y-t.y)*o)/(r*r+o*o)));return Math.hypot(e.x-(t.x+r*s),e.y-(t.y+o*s))}_subtractPoints(e,t){return {x:e.x-t.x,y:e.y-t.y}}_addPoints(e,t){return {x:e.x+t.x,y:e.y+t.y}}_scalePoint(e,t){return {x:e.x*t,y:e.y*t}}_dot(e,t){return e.x*t.x+e.y*t.y}_normalize(e){let t=Math.hypot(e.x,e.y);return t===0?{x:0,y:0}:{x:e.x/t,y:e.y/t}}_updateHoverCursor(){if(!this._context)return;let{overlay:e}=this._context;if(!e.isEnabled())return;let t=this._getStagePointerFromInput(),i=this._hitTestResizeAxis(t);i&&S.setCursor(this._getResizeCursor(i));}_getResizeCursor(e){switch(e){case "ne":case "sw":return "nesw-resize";case "nw":case "se":return "nwse-resize";case "n":case "s":return "ns-resize";case "e":case "w":return "ew-resize";default:return "default"}}};var te=class{constructor(){n(this,"id","overlay-transform-rotate");n(this,"_context",null);n(this,"_isRotating",false);n(this,"_rotateStartWorldPoint",null);n(this,"_rotateStartNodeRotation",0);n(this,"_rotatePivotWorldPoint",null);}attach(e){this._context=e;}detach(){this._resetRotateSession(),this._context=null;}destroy(){this.detach();}update(){this._context&&this._isRotating&&(this._updateRotateFromInput(),this._tryEndRotate());}isActive(){return this._isRotating}hitTest(e){if(!this._context)return false;let{overlay:t}=this._context;return t.isEnabled()?this._hitTestRotateAxis(e)!==null:false}tryBegin(e){if(!this._context)return false;let{overlay:t,world:i}=this._context;if(!t.isEnabled())return false;let r=this._getHandle();if(!r||!r.isEnabled()||!r.hasNode()||!this._hitTestRotateAxis(e))return false;let s=r.getNode();if(!s)return false;let a=r.getPivotWorldPoint();return a?(this._isRotating=true,this._rotateStartWorldPoint=i.getCamera().screenToWorld(e),this._rotateStartNodeRotation=s.getRotation(),this._rotatePivotWorldPoint=a,S.setCursor("crosshair"),true):false}hasNode(){return this._getHandle()?.hasNode()??false}getNodeId(){return this._getHandle()?.getNodeId()??null}setNode(e){this._getHandle()?.setNode(e);}clearNode(){this._getHandle()?.clearNode();}getHoverCursor(e){if(!this._context)return null;if(this._isRotating)return "crosshair";let{overlay:t}=this._context;return !t.isEnabled()||!this._hitTestRotateAxis(e)?null:"crosshair"}_updateRotateFromInput(){if(!this._context||!this._isRotating||!this._rotateStartWorldPoint||!this._rotatePivotWorldPoint)return;let{world:e}=this._context,i=this._getHandle()?.getNode();if(!i)return;let r=this._getStagePointerFromInput(),o=e.getCamera().screenToWorld(r),s=this._subtractPoints(this._rotateStartWorldPoint,this._rotatePivotWorldPoint),a=this._subtractPoints(o,this._rotatePivotWorldPoint),l=Math.atan2(s.y,s.x),h=(Math.atan2(a.y,a.x)-l)*180/Math.PI;i.setRotation(this._rotateStartNodeRotation+h),this._context.emitChange();}_tryEndRotate(){this._isRotating&&(S.getMouseButtonUp(0)||!S.getMouseButton(0))&&this._resetRotateSession();}_resetRotateSession(){this._isRotating=false,this._rotateStartWorldPoint=null,this._rotateStartNodeRotation=0,this._rotatePivotWorldPoint=null,S.resetCursor();}_getHandle(){return this._context?this._context.overlay.getHandlerManager().get(U.TYPE):null}_hitTestRotateAxis(e){let{world:t}=this._context,i=this._getHandle();if(!i||!i.isEnabled()||!i.hasNode())return null;let r=t.getCamera(),o=16;for(let s of ["ne","nw","se","sw"]){let a=i.getHandleWorldPoint(s);if(!a)continue;let l=r.worldToScreen(a),d=e.x-l.x,c=e.y-l.y;if(Math.hypot(d,c)<=o)return s}return null}_getStagePointerFromInput(){let e=this._context.stage.container().getBoundingClientRect();return {x:S.pointerPosition.x-e.left,y:S.pointerPosition.y-e.top}}_subtractPoints(e,t){return {x:e.x-t.x,y:e.y-t.y}}};var ee=class{constructor(){n(this,"id","overlay-transform");n(this,"_context",null);n(this,"_moduleManager",new tt);this.addModule(new te),this.addModule(new Zt),this.addModule(new Jt),this.addModule(new Qt);}addModule(e){this._moduleManager.add(e),this._context&&e.attach(this._context);}removeModule(e){let t=this._moduleManager.getById(e);return t?(t.detach(),t.destroy(),this._moduleManager.remove(e)):false}attach(e){this._context=e;for(let t of this._moduleManager.getAll())t.attach(e);}detach(){for(let e of this._moduleManager.getAll())e.detach();this._context=null;}destroy(){this.detach();for(let e of this._moduleManager.getAll())e.destroy();this._moduleManager.clear();}update(){if(!this._context)return;let e=this._context.getInteractionOwner();if(e!==null&&e!==this.id)return;let t=this._moduleManager.getAll(),i=t.find(l=>l.isActive());if(i){i.update(),i.isActive()||this._context.endInteraction(this.id);return}let r=this._getStagePointerFromInput(),o=null;for(let l=t.length-1;l>=0;l--){let d=t[l];if(!d||!d.getHoverCursor)continue;let c=d.getHoverCursor(r);if(c){o=c;break}}if(o?S.setCursor(o):S.resetCursor(),!S.getMouseButtonDown(0))return;let s=this._context.overlay.getHoveredNode(),a=this._getActiveNodeId();if(s&&a!==s.id){this._setNodeForAllModules(s)&&this._context.emitChange();return}if(a!==null)for(let l=t.length-1;l>=0;l--){let d=t[l];if(d!==void 0&&d.hitTest(r)){if(!this._context.tryBeginInteraction(this.id)||d.tryBegin(r))return;this._context.endInteraction(this.id);}}s||this._clearAllModules()&&this._context.emitChange();}_getActiveNodeId(){for(let e of this._moduleManager.getAll())if(e.hasNode())return e.getNodeId();return null}_setNodeForAllModules(e){let t=false;for(let i of this._moduleManager.getAll())i.getNodeId()!==e.id&&(i.setNode(e),t=true);return t}_clearAllModules(){let e=false;for(let t of this._moduleManager.getAll())t.hasNode()&&(t.clearNode(),e=true);return e}_getStagePointerFromInput(){let e=this._context.stage.container().getBoundingClientRect();return {x:S.pointerPosition.x-e.left,y:S.pointerPosition.y-e.top}}};var ie=class{constructor(){n(this,"id","overlay-corner-radius");n(this,"_context",null);n(this,"_isDragging",false);n(this,"_singleMode",false);n(this,"_activeAxis",null);n(this,"_candidateAxes",[]);n(this,"_dragStartScreenPoint",null);}attach(e){this._context=e,S.configure({preventAltDefault:true});}detach(){this._resetSession(),this._context=null;}destroy(){this.detach();}update(){if(!this._context)return;let e=this._context.getInteractionOwner();if(e!==null&&e!==this.id)return;if(this._isDragging){this._updateDrag(),this._tryEndDrag();return}if(!S.getMouseButtonDown(0))return;let t=this._getStagePointerFromInput();if(this._hitTest(t)&&this._tryBegin())return;let r=this._context.overlay.getHoveredNode(),o=this._getHandle();if(o){if(r&&this._isCornerRadiusSupported(r)){o.getNodeId()!==r.id&&(o.setNode(r),this._context.emitChange());return}o.hasNode()&&(o.clearNode(),this._context.emitChange());}}_tryBegin(){let e=this._getHandle(),t=e?.getNode();if(!e||!t||!this._context)return false;let i=this._getStagePointerFromInput(),r=this._getHitAxes(i);return r.length===0||!this._context.tryBeginInteraction(this.id)?false:(this._isDragging=true,this._dragStartScreenPoint=i,this._candidateAxes=r,r.length===1?this._activeAxis=r[0]??null:this._activeAxis=null,S.setCursor("pointer"),true)}_updateDrag(){if(!this._activeAxis){let x=this._getStagePointerFromInput(),v=this._resolveAxisFromDirection(x);if(!v)return;this._activeAxis=v;}if(!this._context||!this._isDragging||!this._activeAxis)return;this._singleMode=S.altPressed??false;let e=this._getHandle(),t=e?.getNode();if(!e||!t)return;let i=this._getStagePointerFromInput(),r=this._context.world.getCamera().screenToWorld(i),o=e.getSection(this._activeAxis);if(!o)return;let s={x:o.xAxisPoint.x+o.yAxisPoint.x-o.origin.x,y:o.xAxisPoint.y+o.yAxisPoint.y-o.origin.y},a={x:s.x-o.origin.x,y:s.y-o.origin.y},l=Math.hypot(a.x,a.y);if(l<=1e-6)return;let d={x:a.x/l,y:a.y/l},c={x:r.x-o.origin.x,y:r.y-o.origin.y},h=c.x*d.x+c.y*d.y,m=Math.max(0,Math.min(h,l))/l,b=Math.max(0,Math.min(o.width,o.height)+o.inset),f=_.toF32(m*b),y=t.getCornerRadius();this._singleMode?y[this._activeAxis]=f:(y.tl=f,y.tr=f,y.br=f,y.bl=f),t.setCornerRadius(y),this._context.emitChange();}_tryEndDrag(){(S.getMouseButtonUp(0)||!S.getMouseButton(0))&&this._resetSession();}_resetSession(){this._activeAxis=null,this._candidateAxes=[],this._dragStartScreenPoint=null,this._isDragging=false,this._activeAxis=null,this._singleMode=false,this._context&&(this._context.endInteraction(this.id),S.resetCursor());}_hitTest(e){let t=this._getHandle();if(!t||!t.isEnabled()||!t.hasNode())return null;let i=this._context.world.getCamera(),r=8;for(let o of ["tl","tr","br","bl"]){let s=t.getHandleWorldPoint(o);if(!s)continue;let a=i.worldToScreen(s),l=e.x-a.x,d=e.y-a.y;if(Math.hypot(l,d)<=r)return o}return null}_isCornerRadiusSupported(e){return typeof e.getCornerRadius=="function"&&typeof e.setCornerRadius=="function"}_getHandle(){return this._context?this._context.overlay.getHandlerManager().get(Y.TYPE):null}_getStagePointerFromInput(){let e=this._context.stage.container().getBoundingClientRect();return {x:S.pointerPosition.x-e.left,y:S.pointerPosition.y-e.top}}_getHitAxes(e){let t=this._getHandle();if(!t||!t.isEnabled()||!t.hasNode())return [];let i=this._context.world.getCamera(),r=8,o=[];for(let s of ["tl","tr","br","bl"]){let a=t.getHandleWorldPoint(s);if(!a)continue;let l=i.worldToScreen(a),d=e.x-l.x,c=e.y-l.y;Math.hypot(d,c)<=r&&o.push(s);}return o}_resolveAxisFromDirection(e){let t=this._getHandle();if(!t||!t.hasNode()||!this._dragStartScreenPoint)return null;let i={x:e.x-this._dragStartScreenPoint.x,y:e.y-this._dragStartScreenPoint.y},r=Math.hypot(i.x,i.y);if(r<5)return null;let o={x:i.x/r,y:i.y/r},s=null,a=-1/0;for(let l of this._candidateAxes){let d=t.getSection(l),c=t.getHandleWorldPoint(l);if(!d||!c)continue;let h=this._context.world.getCamera().worldToScreen(c),u=this._context.world.getCamera().worldToScreen(d.origin),m={x:u.x-h.x,y:u.y-h.y},b=Math.hypot(m.x,m.y);if(b<=1e-6)continue;let f={x:m.x/b,y:m.y/b},y=o.x*f.x+o.y*f.y;y>a&&(a=y,s=l);}return s}};var ei=class extends et{constructor(){super();n(this,"id",1);this.addModule(new Mt),this.addModule(new ie),this.addModule(new ee);}};function ii(g,e){return {a:g.a*e.a+g.c*e.b,b:g.b*e.a+g.d*e.b,c:g.a*e.c+g.c*e.d,d:g.b*e.c+g.d*e.d,tx:g.a*e.tx+g.c*e.ty+g.tx,ty:g.b*e.tx+g.d*e.ty+g.ty}}var ri=(u=>(u.Base="base-node",u.Group="group-node",u.Rect="rect-node",u.Ellipse="ellipse-node",u.Star="star-node",u.Polygon="polygon-node",u.Line="line-node",u.Text="text-node",u.Frame="frame-node",u.Image="image-node",u.Video="video-node",u.Path="path-node",u))(ri||{});var X=class X{constructor(e,t="base-node",i="Node"){n(this,"type");n(this,"id");n(this,"_opacity");n(this,"_isVisible");n(this,"_isLocked");n(this,"_isVisibleInHierarchy");n(this,"_isLockedInHierarchy");n(this,"_name");n(this,"_parent");n(this,"_children");n(this,"_width");n(this,"_height");n(this,"_transform");n(this,"_isWorldMatrixDirty");n(this,"_isHierarchyLocalOBBDirty");n(this,"_isHierarchyWorldAABBDirty");n(this,"_cachedWorldMatrix");n(this,"_cachedHierarchyLocalOBB");n(this,"_cachedHierarchyWorldAABB");this.id=e,this.type=t,this._name=this._sanitizeNodeName(i),this._isVisible=true,this._isLocked=false,this._isVisibleInHierarchy=true,this._isLockedInHierarchy=false,this._isWorldMatrixDirty=true,this._cachedWorldMatrix=null,this._isHierarchyLocalOBBDirty=true,this._isHierarchyWorldAABBDirty=true,this._cachedHierarchyLocalOBB=null,this._cachedHierarchyWorldAABB=null,this._width=0,this._height=0,this._opacity=1,this._children=[],this._parent=null,this._transform=new wt;}getOpacity(){return this._opacity}setOpacity(e){if(!Number.isFinite(e))return;let t=Math.max(0,Math.min(1,e));t!==this._opacity&&(this._opacity=t);}setDirty(){if(this.setHierarchyBoundsDirty(),!this._isWorldMatrixDirty){this._isWorldMatrixDirty=true,this._cachedWorldMatrix=null;for(let e of this._children)e.setDirty();}}setHierarchyBoundsDirty(){let e=this._isHierarchyLocalOBBDirty,t=this._isHierarchyWorldAABBDirty;e&&t||(this._isHierarchyLocalOBBDirty=true,this._isHierarchyWorldAABBDirty=true,this._cachedHierarchyLocalOBB=null,this._cachedHierarchyWorldAABB=null,this._parent&&this._parent.setHierarchyBoundsDirty());}traverse(e){if(e(this)!==false)for(let i of this._children)i.traverse(e);}getName(){return this._name}setName(e){let t=this._sanitizeNodeName(e);t!==this._name&&(this._name=t);}getWidth(){return this._width}setWidth(e){this.isLockedInHierarchy()!==true&&e!==this._width&&(this._width=Math.max(0,e),this.setDirty());}getHeight(){return this._height}setHeight(e){this.isLockedInHierarchy()!==true&&e!==this._height&&(this._height=Math.max(0,e),this.setDirty());}getSize(){return {width:this._width,height:this._height}}setSize(e,t){if(this.isLockedInHierarchy()===true)return;let i=_.max(0,e),r=_.max(0,t);i===this._width&&r===this._height||(this._width=i,this._height=r,this.setDirty());}getScaledWidth(){return _.mul(this.getWidth(),this.getScaleX())}getScaledHeight(){return _.mul(this.getHeight(),this.getScaleY())}getScaledSize(){return {width:this.getScaledWidth(),height:this.getScaledHeight()}}isVisible(){return this._isVisible}isVisibleInHierarchy(){return this._isVisibleInHierarchy}setVisible(e){this._isVisible!==e&&(this._isVisible=e,this._updateHierarchyVisibility(),this.setHierarchyBoundsDirty());}isLocked(){return this._isLocked}isLockedInHierarchy(){return this._isLockedInHierarchy}setLocked(e){this._isLocked!==e&&(this._isLocked=e,this._updateHierarchyLock());}getParent(){return this._parent}setParent(e){this._parent!==e&&e.addChild(this);}removeParent(){this._parent&&this._parent.removeChild(this);}getChildren(){return [...this._children]}addChild(e){if(e.id===this.id)throw new Error("Node cannot be added to itself");if(X.isAncestor(this,e))throw new Error("Cyclic dependency: cannot add an ancestor as a child");if(e.getParent()===this)return;let t=e.getParent();t&&t.removeChild(e),this._children.push(e),e._setParentInternal(this),this.setHierarchyBoundsDirty();}removeChild(e){let t=this._children.indexOf(e);if(t===-1)return;this._children.splice(t,1);let i=e;i.getParent()===this&&i._setParentInternal(null),this.setHierarchyBoundsDirty();}getX(){return this._transform.getX()}getY(){return this._transform.getY()}getPosition(){return this._transform.getPosition()}setX(e){if(this.isLockedInHierarchy()===true)return;let t=_.toF32(e);this._transform.getX()!==t&&(this._transform.setX(t),this.setDirty());}setY(e){if(this.isLockedInHierarchy()===true)return;let t=_.toF32(e);this._transform.getY()!==t&&(this._transform.setY(t),this.setDirty());}setPosition(e,t){if(this.isLockedInHierarchy()===true)return;let i=this._transform.getPosition(),r=_.toF32(e),o=_.toF32(t);i.x===r&&i.y===o||(this._transform.setPosition(r,o),this.setDirty());}translateX(e){this.isLockedInHierarchy()!==true&&e!==0&&(this._transform.translateX(e),this.setDirty());}translateY(e){this.isLockedInHierarchy()!==true&&e!==0&&(this._transform.translateY(e),this.setDirty());}translate(e,t){this.isLockedInHierarchy()!==true&&(e===0&&t===0||(this._transform.translate(e,t),this.setDirty()));}getScaleX(){return this._transform.getScaleX()}getScaleY(){return this._transform.getScaleY()}getScale(){return this._transform.getScale()}setScaleX(e){if(this.isLockedInHierarchy()===true)return;let t=_.toF32(e);this._transform.getScaleX()!==t&&(this._transform.setScaleX(t),this.setDirty());}setScaleY(e){if(this.isLockedInHierarchy()===true)return;let t=_.toF32(e);this._transform.getScaleY()!==t&&(this._transform.setScaleY(t),this.setDirty());}setScale(e,t){if(this.isLockedInHierarchy()===true)return;let i=_.toF32(e),r=_.toF32(t),o=this._transform.getScale();o.x===i&&o.y===r||(this._transform.setScale(i,r),this.setDirty());}getRotation(){return _.radToDeg(this._transform.getRotation())}getWorldRotation(){let e=this.getRotation(),t=this._parent;for(;t;)e+=t.getRotation(),t=t.getParent();return _.toF32(e)}setRotation(e){if(this.isLockedInHierarchy())return;let t=_.degToRad(e);this._transform.getRotation()!==t&&(this._transform.setRotation(t),this.setDirty());}rotate(e){if(this.isLockedInHierarchy())return;let t=_.degToRad(e);this._transform.getRotation()!==t&&(this._transform.rotate(t),this.setDirty());}getPivotX(){return this._transform.getPivotX()}getPivotY(){return this._transform.getPivotY()}getPivot(){return this._transform.getPivot()}setPivotX(e){if(this.isLockedInHierarchy()===true)return;let t=_.toF32(e);this.getPivotX()!==t&&(this._transform.setPivotX(t),this.setDirty());}setPivotY(e){if(this.isLockedInHierarchy()===true)return;let t=_.toF32(e);this.getPivotY()!==t&&(this._transform.setPivotY(t),this.setDirty());}setPivot(e,t){if(this.isLockedInHierarchy()===true)return;let i=this._transform.getPivot(),r=_.toF32(e),o=_.toF32(t);i.x===r&&i.y===o||(this._transform.setPivot(r,o),this.setDirty());}getLocalMatrix(){return this._transform.getLocalMatrix(this._width,this._height)}getWorldMatrix(){if(!this._isWorldMatrixDirty&&this._cachedWorldMatrix)return this._cachedWorldMatrix;let e=this.getLocalMatrix();if(!this._parent)this._cachedWorldMatrix=e;else {let t=this._parent.getWorldMatrix();this._cachedWorldMatrix=ii(t,e);}return this._isWorldMatrixDirty=false,this._cachedWorldMatrix}getWorldCorners(){let e=this.getWorldMatrix(),t=this.getLocalOBB(),i=t.x,r=t.y,o=t.width,s=t.height;return [this._applyMatrixToPoint(e,{x:i,y:r}),this._applyMatrixToPoint(e,{x:_.add(i,o),y:r}),this._applyMatrixToPoint(e,{x:_.add(i,o),y:_.add(r,s)}),this._applyMatrixToPoint(e,{x:i,y:_.add(r,s)})]}getLocalOBB(){return {x:0,y:0,width:this._width,height:this._height}}getWorldOBB(){let e=this.getWorldCorners(),t={x:_.toF32((e[0].x+e[2].x)/2),y:_.toF32((e[0].y+e[2].y)/2)},i=Math.hypot(e[1].x-e[0].x,e[1].y-e[0].y),r=Math.hypot(e[2].x-e[1].x,e[2].y-e[1].y);return {center:t,width:_.toF32(i),height:_.toF32(r),rotation:this.getWorldRotation()}}getWorldAABB(){return this._getAABBFromPoints(this.getWorldCorners())}getHierarchyLocalOBB(){if(!this._isHierarchyLocalOBBDirty&&this._cachedHierarchyLocalOBB)return this._cachedHierarchyLocalOBB;let e=this.getLocalOBB(),t=e.x,i=e.y,r=e.x+e.width,o=e.y+e.height;for(let s of this._children){let a=s;if(!a.isVisibleInHierarchy())continue;let l=a.getHierarchyLocalOBB(),d=a.getLocalMatrix(),c=[{x:l.x,y:l.y},{x:l.x+l.width,y:l.y},{x:l.x+l.width,y:l.y+l.height},{x:l.x,y:l.y+l.height}];for(let h of c){let u=this._applyMatrixToPoint(d,h);u.x<t&&(t=u.x),u.y<i&&(i=u.y),u.x>r&&(r=u.x),u.y>o&&(o=u.y);}}return this._cachedHierarchyLocalOBB={x:_.toF32(t),y:_.toF32(i),width:_.sub(r,t),height:_.sub(o,i)},this._isHierarchyLocalOBBDirty=false,this._cachedHierarchyLocalOBB}getHierarchyWorldOBB(){let e=this.getHierarchyLocalOBB(),t=this.getWorldMatrix(),i=[this._applyMatrixToPoint(t,{x:e.x,y:e.y}),this._applyMatrixToPoint(t,{x:e.x+e.width,y:e.y}),this._applyMatrixToPoint(t,{x:e.x+e.width,y:e.y+e.height}),this._applyMatrixToPoint(t,{x:e.x,y:e.y+e.height})],r={x:_.toF32((i[0].x+i[2].x)/2),y:_.toF32((i[0].y+i[2].y)/2)},o=Math.hypot(i[1].x-i[0].x,i[1].y-i[0].y),s=Math.hypot(i[2].x-i[1].x,i[2].y-i[1].y);return {center:r,width:_.toF32(o),height:_.toF32(s),rotation:this.getWorldRotation()}}getHierarchyWorldAABB(){if(!this._isHierarchyWorldAABBDirty&&this._cachedHierarchyWorldAABB)return this._cachedHierarchyWorldAABB;let e=this.getHierarchyLocalOBB(),t=this.getWorldMatrix(),r=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}].map(o=>this._applyMatrixToPoint(t,o));return this._cachedHierarchyWorldAABB=this._getAABBFromPoints(r),this._isHierarchyWorldAABBDirty=false,this._cachedHierarchyWorldAABB}hitTest(e){let t=this.getWorldAABB();if(e.x<t.x||e.x>t.x+t.width||e.y<t.y||e.y>t.y+t.height)return false;let i=this.getWorldMatrix();try{let r=W(i),o=this._applyMatrixToPoint(r,e);return o.x>=0&&o.x<=this._width&&o.y>=0&&o.y<=this._height}catch{return false}}static isAncestor(e,t){let i=new Set,r=e;for(;r;){if(r===t)return true;if(i.has(r.id))return false;i.add(r.id),r=r.getParent();}return false}static hasAncestor(e,t){let i=new Set,r=e.getParent();for(;r;){if(r===t)return true;if(i.has(r))return false;i.add(r),r=r.getParent();}return false}toJSON(){return {...this._serializeBase(),...this._serializeExtra()}}static fromJSON(e){let t=new this(e.id,e.name);return t.setPosition(e.x,e.y),t.setSize(e.width,e.height),t.setRotation(e.rotation),t.setScale(e.scaleX,e.scaleY),t.setVisible(e.visible),t.setLocked(e.locked),t}_serializeBase(){let e=this.getPosition(),t=this.getScale();return {id:this.id,type:this.type,name:this._name,x:e.x,y:e.y,width:this._width,height:this._height,rotation:this.getRotation(),scaleX:t.x,scaleY:t.y,visible:this._isVisible,locked:this._isLocked,parentId:this._parent?this._parent.id:null,children:this._children.map(i=>i.id)}}_serializeExtra(){return {}}_sanitizeNodeName(e){let t=String(e);return t=t.normalize("NFKC"),t=t.replace(/[\x00-\x1F\x7F-\x9F]/g,""),t=t.replace(/[\u00AD\u200B-\u200F\u202A-\u202E\u2060-\u2064\uFEFF]/g,""),t=t.replace(/\s+/g," ").trim(),t.length>X.NAME_MAX_LENGTH&&(t=t.slice(0,X.NAME_MAX_LENGTH).trimEnd()),t.length===0&&(t=X.DEFAULT_NODE_NAME),t}_applyMatrixToPoint(e,t){return {x:_.toF32(e.a*t.x+e.c*t.y+e.tx),y:_.toF32(e.b*t.x+e.d*t.y+e.ty)}}_setParentInternal(e){this._parent=e,this._updateHierarchyVisibility(),this._updateHierarchyLock(),this.setDirty();}_updateHierarchyVisibility(){let e=this._parent?this._parent._isVisibleInHierarchy:true;this._isVisibleInHierarchy=this._isVisible&&e;for(let t of this._children)t._updateHierarchyVisibility();}_updateHierarchyLock(){let e=this._parent?this._parent._isLockedInHierarchy:false;this._isLockedInHierarchy=this._isLocked||e;for(let t of this._children)t._updateHierarchyLock();}_getAABBFromPoints(e){if(e.length===0)return {x:0,y:0,width:0,height:0};let t=1/0,i=1/0,r=-1/0,o=-1/0;for(let s of e)s.x<t&&(t=s.x),s.y<i&&(i=s.y),s.x>r&&(r=s.x),s.y>o&&(o=s.y);return {x:_.toF32(t),y:_.toF32(i),width:_.sub(r,t),height:_.sub(o,i)}}};n(X,"NAME_MAX_LENGTH",256),n(X,"DEFAULT_NODE_NAME","Node");var nt=X;var yr=(i=>(i[i.Inside=0]="Inside",i[i.Center=1]="Center",i[i.Outside=2]="Outside",i))(yr||{});var st=class{constructor(){n(this,"_isVisible");this._isVisible=true;}isVisible(){return this._isVisible}setVisible(e){this._isVisible!==e&&(this._isVisible=e);}};var vr=(i=>(i.Fill="fill",i.Cutout="cutout",i.Inner="inner",i))(vr||{});var re=class re extends st{constructor(){super();n(this,"type");n(this,"_mode");n(this,"_fill");n(this,"_opacity");n(this,"_x");n(this,"_y");n(this,"_blur");n(this,"_spread");this.type="drop-shadow",this._mode="cutout",this._fill=re.DEFAULT_FILL_COLOR,this._opacity=.25,this._x=4,this._y=4,this._blur=4,this._spread=0;}getMode(){return this._mode}setMode(t){this._mode!==t&&(this._mode=t);}getFill(){return culori.formatRgb(this._fill)}setFill(t){let i=typeof t=="string"?culori.parse(t):t;i&&(this._fill&&culori.formatRgb(this._fill)===culori.formatRgb(i)||(this._fill=i));}getOpacity(){return this._opacity}setOpacity(t){let i=Math.max(0,Math.min(1,t));this._opacity!==i&&(this._opacity=i);}getX(){return this._x}setX(t){this._x!==t&&(this._x=t);}getY(){return this._y}setY(t){this._y!==t&&(this._y=t);}setOffset(t,i){this._x===t&&this._y===i||(this._x=t,this._y=i);}getBlur(){return this._blur}setBlur(t){let i=Math.max(0,t);this._blur!==i&&(this._blur=i);}getSpread(){return this._spread}setSpread(t){this._spread!==t&&(this._spread=t);}computeBounds(t,i){let r=this.computeLocalBounds(t,i);return {x:r.x+this._x,y:r.y+this._y,width:r.width,height:r.height}}computeLocalBounds(t,i){let r=Math.max(0,this._spread),o=Math.max(0,this._blur),s=Math.ceil(o*2),a=-r-s,l=-r-s,d=t+r+s,c=i+r+s;return {x:a,y:l,width:Math.max(0,d-a),height:Math.max(0,c-l)}}};n(re,"DEFAULT_FILL_COLOR",{mode:"rgb",r:0,g:0,b:0});var oi=re;var oe=class oe extends st{constructor(){super();n(this,"type");n(this,"_fill");n(this,"_opacity");n(this,"_x");n(this,"_y");n(this,"_blur");n(this,"_spread");this.type="inner-shadow",this._fill=oe.DEFAULT_FILL_COLOR,this._opacity=.25,this._x=4,this._y=4,this._blur=4,this._spread=0;}getFill(){return culori.formatRgb(this._fill)}setFill(t){let i=typeof t=="string"?culori.parse(t):t;i&&(this._fill&&culori.formatRgb(this._fill)===culori.formatRgb(i)||(this._fill=i));}getOpacity(){return this._opacity}setOpacity(t){let i=Math.max(0,Math.min(1,t));this._opacity!==i&&(this._opacity=i);}getX(){return this._x}setX(t){this._x!==t&&(this._x=t);}getY(){return this._y}setY(t){this._y!==t&&(this._y=t);}setOffset(t,i){this._x===t&&this._y===i||(this._x=t,this._y=i);}getBlur(){return this._blur}setBlur(t){let i=Math.max(0,t);this._blur!==i&&(this._blur=i);}getSpread(){return this._spread}setSpread(t){this._spread!==t&&(this._spread=t);}computeBounds(t,i){let r=this.computeLocalBounds(t,i);return {x:r.x+this._x,y:r.y+this._y,width:r.width,height:r.height}}computeLocalBounds(t,i){let r=Math.max(0,this._spread),o=Math.max(0,this._blur),s=Math.ceil(o*2),a=-r-s,l=-r-s,d=t+r+s,c=i+r+s;return {x:a,y:l,width:Math.max(0,d-a),height:Math.max(0,c-l)}}};n(oe,"DEFAULT_FILL_COLOR",{mode:"rgb",r:0,g:0,b:0});var ni=oe;var ne=class{constructor(){n(this,"_effects",new Map);}get(e){return this._effects.get(e)}getAll(){return Array.from(this._effects.values())}has(e){return this._effects.has(e)}add(e){this._effects.set(e.type,e);}remove(e){return this._effects.delete(e)}clear(){this._effects.size!==0&&this._effects.clear();}setAll(e){this._effects.clear();for(let t of e)this._effects.set(t.type,t);}};var lt=class lt extends nt{constructor(t,i,r){super(t,i,r);n(this,"effect");n(this,"_cornerRadius");n(this,"_fill");n(this,"_strokeWidth");n(this,"_strokeFill");n(this,"_strokeAlign");this.setSize(100,100),this._cornerRadius={tl:0,tr:0,br:0,bl:0},this._fill=lt.DEFAULT_FILL_COLOR,this._strokeWidth={t:0,l:0,b:0,r:0},this._strokeFill=lt.DEFAULT_STROKE_FILL_COLOR,this._strokeAlign=1,this.effect=new ne;}getCornerRadius(){return {...this._cornerRadius}}setCornerRadius(t){let i={tl:_.max(0,t.tl),tr:_.max(0,t.tr),br:_.max(0,t.br),bl:_.max(0,t.bl)};i.tl===this._cornerRadius.tl&&i.tr===this._cornerRadius.tr&&i.br===this._cornerRadius.br&&i.bl===this._cornerRadius.bl||(this._cornerRadius=i);}getFill(){return culori.formatRgb(this._fill)}setFill(t){let i=typeof t=="string"?culori.parse(t):t;i&&(this._fill&&culori.formatRgb(this._fill)===culori.formatRgb(i)||(this._fill=i));}getStrokeWidth(){return {...this._strokeWidth}}setStrokeWidth(t){let i={t:_.max(0,t.t),r:_.max(0,t.r),b:_.max(0,t.b),l:_.max(0,t.l)};i.t===this._strokeWidth.t&&i.r===this._strokeWidth.r&&i.b===this._strokeWidth.b&&i.l===this._strokeWidth.l||(this._strokeWidth=i);}getStrokeFill(){return culori.formatRgb(this._strokeFill)}setStrokeFill(t){let i=typeof t=="string"?culori.parse(t):t;i&&(this._strokeFill&&culori.formatRgb(this._strokeFill)===culori.formatRgb(i)||(this._strokeFill=i));}getStrokeAlign(){return this._strokeAlign}setStrokeAlign(t){t!==this._strokeAlign&&(this._strokeAlign=t);}getLocalViewOBB(){let t=this.getLocalOBB(),i=this._getViewStrokeOutset();return {x:_.sub(t.x,i.l),y:_.sub(t.y,i.t),width:_.add(t.width,_.add(i.l,i.r)),height:_.add(t.height,_.add(i.t,i.b))}}getWorldViewCorners(){let t=this.getWorldMatrix(),i=this.getLocalViewOBB(),r=i.x,o=i.y,s=i.width,a=i.height;return [this._applyMatrixToPoint(t,{x:r,y:o}),this._applyMatrixToPoint(t,{x:_.add(r,s),y:o}),this._applyMatrixToPoint(t,{x:_.add(r,s),y:_.add(o,a)}),this._applyMatrixToPoint(t,{x:r,y:_.add(o,a)})]}getWorldViewOBB(){let t=this.getWorldViewCorners(),i={x:_.toF32((t[0].x+t[2].x)/2),y:_.toF32((t[0].y+t[2].y)/2)},r=Math.hypot(t[1].x-t[0].x,t[1].y-t[0].y),o=Math.hypot(t[2].x-t[1].x,t[2].y-t[1].y);return {center:i,width:_.toF32(r),height:_.toF32(o),rotation:this.getWorldRotation()}}getWorldViewAABB(){return this._getAABBFromPoints(this.getWorldViewCorners())}_getViewStrokeOutset(){let t=this.getStrokeWidth();switch(this.getStrokeAlign()){case 0:return {t:0,r:0,b:0,l:0};case 1:return {t:t.t/2,r:t.r/2,b:t.b/2,l:t.l/2};case 2:return {...t};default:return {t:0,r:0,b:0,l:0}}}};n(lt,"DEFAULT_FILL_COLOR",{mode:"rgb",r:.85,g:.85,b:.85}),n(lt,"DEFAULT_STROKE_FILL_COLOR",{mode:"rgb",r:0,g:0,b:0});var N=lt;var gt=class gt extends N{constructor(t,i){super(t,"ellipse-node",i??"Ellipse");n(this,"_innerRatio");n(this,"_startAngle");n(this,"_endAngle");this._innerRatio=0,this._startAngle=0,this._endAngle=Math.PI*2;}getInnerRatio(){return this._innerRatio}setInnerRatio(t){let i=Math.max(0,Math.min(t,.999));i!==this._innerRatio&&(this._innerRatio=i);}getStartAngle(){return this._radToDeg(this._startAngle)}setStartAngle(t){let i=this._degToRad(t);this._startAngle!==i&&(this._startAngle=i);}getEndAngle(){return this._radToDeg(this._endAngle)}setEndAngle(t){let i=this._degToRad(t);this._endAngle!==i&&(this._endAngle=i);}getSweepAngle(){return this._radToDeg(this._endAngle-this._startAngle)}hitTest(t){let i=this.getWorldAABB();if(t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height)return false;try{let r=W(this.getWorldMatrix()),o=this._applyMatrixToPoint(r,t),s=this.getWidth()/2,a=this.getHeight()/2;if(s===0||a===0)return !1;let l=s,d=a,c=(o.x-l)/s,h=(o.y-d)/a,u=c*c+h*h;if(u>1)return !1;if(this._innerRatio>0){let I=this._innerRatio*this._innerRatio;if(u<I)return !1}let m=this._normalizeAngle(this._endAngle-this._startAngle);if(Math.abs(m)<gt.EPSILON||Math.abs(m-Math.PI*2)<gt.EPSILON)return !0;let f=o.x-l,y=o.y-d,x=this._normalizeAngle(Math.atan2(y,f)),v=this._normalizeAngle(this._startAngle),w=this._normalizeAngle(this._endAngle);return this._isAngleBetween(x,v,w)}catch{return false}}_degToRad(t){return t*Math.PI/180}_radToDeg(t){return t*180/Math.PI}_normalizeAngle(t){let i=Math.PI*2;return (t%i+i)%i}_isAngleBetween(t,i,r){return i<=r?t>=i&&t<=r:t>=i||t<=r}};n(gt,"EPSILON",1e-6);var ai=gt;var li=class extends nt{constructor(e,t){super(e,"group-node",t??"Group");}};var wr=(i=>(i.Round="round",i.Square="square",i.Butt="butt",i))(wr||{}),Ir=(s=>(s.None="none",s.LineArrow="line-arrow",s.TriangleArrow="triangle-arrow",s.ReversedTriangle="reversed-triangle",s.CircleArrow="circle-arrow",s.DiamondArrow="diamond-arrow",s))(Ir||{});var di=class extends N{constructor(t,i){super(t,"line-node",i??"Line");n(this,"_start");n(this,"_end");n(this,"_thickness");n(this,"_lineCapStart");n(this,"_lineCapEnd");n(this,"_startEnding");n(this,"_endEnding");this._thickness=1,this._start={x:0,y:0},this._end={x:100,y:0},this._updateBounds(),this._lineCapStart="butt",this._lineCapEnd="butt",this._startEnding="none",this._endEnding="none";}getStart(){return {...this._start}}setStart(t){t.x===this._start.x&&t.y===this._start.y||(this._start=t,this._updateBounds());}getEnd(){return {...this._end}}setEnd(t){t.x===this._end.x&&t.y===this._end.y||(this._end=t,this._updateBounds());}getStrokeThickness(){return this._thickness}setStrokeThickness(t){let i=Math.max(0,t);i!==this._thickness&&(this._thickness=i);}getLineCapStart(){return this._lineCapStart}setLineCapStart(t){this._lineCapStart!==t&&(this._lineCapStart=t);}getLineCapEnd(){return this._lineCapEnd}setLineCapEnd(t){this._lineCapEnd!==t&&(this._lineCapEnd=t);}getStartEnding(){return this._startEnding}setStartEnding(t){this._startEnding!==t&&(this._startEnding=t);}getEndEnding(){return this._endEnding}setEndEnding(t){this._endEnding!==t&&(this._endEnding=t);}setWidth(t){if(this.isLockedInHierarchy())return;let i=Math.max(0,t),r=this.getWidth();if(i===r)return;let o={...this._start},s={...this._end};r>0&&(o.x=o.x/r*i,s.x=s.x/r*i),this._start=o,this._end=s,super.setWidth(i);}setHeight(t){if(this.isLockedInHierarchy())return;let i=Math.max(0,t),r=this.getHeight();if(i===r)return;let o={...this._start},s={...this._end};r>0&&(o.y=o.y/r*i,s.y=s.y/r*i),this._start=o,this._end=s,super.setHeight(i);}setSize(t,i){if(this.isLockedInHierarchy())return;let r=Math.max(0,t),o=Math.max(0,i),s=this.getWidth(),a=this.getHeight();if(r===s&&o===a)return;let l={...this._start},d={...this._end};s>0&&(l.x=l.x/s*r,d.x=d.x/s*r),a>0&&(l.y=l.y/a*o,d.y=d.y/a*o),this._start=l,this._end=d,super.setSize(r,o);}hitTest(t){let i=this.getWorldAABB();if(t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height)return false;try{let r=W(this.getWorldMatrix()),o=this._applyMatrixToPoint(r,t),s=this._start.x,a=this._start.y,l=this._end.x,d=this._end.y,c=this._thickness/2,h=l-s,u=d-a,m=h*h+u*u;if(m===0){let P=o.x-s,D=o.y-a;return P*P+D*D<=c*c}let b=Math.sqrt(m),f=this._lineCapStart==="square"?c:0,y=this._lineCapEnd==="square"?c:0,x=-f/b,v=1+y/b,w=((o.x-s)*h+(o.y-a)*u)/m;w<x?w=x:w>v&&(w=v);let I=s+h*w,C=a+u*w,T=o.x-I,A=o.y-C;if(T*T+A*A<=c*c)return !0;if(this._lineCapStart==="round"){let P=o.x-s,D=o.y-a;if(P*P+D*D<=c*c)return !0}if(this._lineCapEnd==="round"){let P=o.x-l,D=o.y-d;if(P*P+D*D<=c*c)return !0}return !1}catch{return false}}_updateBounds(){let t=Math.min(this._start.x,this._end.x),i=Math.min(this._start.y,this._end.y),r=Math.max(this._start.x,this._end.x),o=Math.max(this._start.y,this._end.y),s=r-t,a=o-i,l=t!==0||i!==0,d=s!==this.getWidth()||a!==this.getHeight();if(!l&&!d)return;let c=this.getPosition(),h=this.getLocalMatrix(),u=h.a*t+h.c*i,m=h.b*t+h.d*i;this._start={x:this._start.x-t,y:this._start.y-i},this._end={x:this._end.x-t,y:this._end.y-i},super.setSize(s,a),this.setPosition(c.x+u,c.y+m);}};var Cr=(o=>(o.MoveTo="move-to",o.LineTo="line-to",o.QuadTo="quad-to",o.CubicTo="cubic-to",o.Close="close",o))(Cr||{});var ci=class g extends N{constructor(t,i){super(t,"path-node",i??"Path");n(this,"_commands");this._commands=[],this.setSize(100,100);}getCommands(){return this._commands.map(t=>structuredClone(t))}setCommands(t){let i=t.map(r=>structuredClone(r));this._commands=i;}moveTo(t){this._commands.push({type:"move-to",to:{...t}});}lineTo(t){this._commands.push({type:"line-to",to:{...t}});}quadTo(t,i){this._commands.push({type:"quad-to",control:{...t},to:{...i}});}cubicTo(t,i,r){this._commands.push({type:"cubic-to",control1:{...t},control2:{...i},to:{...r}});}closePath(){this._commands[this._commands.length-1]?.type!=="close"&&this._commands.push({type:"close"});}clearPath(){this._commands.length!==0&&(this._commands=[]);}isClosed(){return this._commands[this._commands.length-1]?.type==="close"}toString(){let t=[];for(let i of this._commands)switch(i.type){case "move-to":t.push(`M ${i.to.x} ${i.to.y}`);break;case "line-to":t.push(`L ${i.to.x} ${i.to.y}`);break;case "quad-to":t.push(`Q ${i.control.x} ${i.control.y} ${i.to.x} ${i.to.y}`);break;case "cubic-to":t.push(`C ${i.control1.x} ${i.control1.y} ${i.control2.x} ${i.control2.y} ${i.to.x} ${i.to.y}`);break;case "close":t.push("Z");break}return t.join(" ")}static fromString(t,i){let r=new this(t),o=g.parseSvgPathToCommands(i);return r.setCommands(o),r}static parseSvgPathToCommands(t){let i=this._tokenizeSvgPath(t),r=[],o=0,s={x:0,y:0},a={x:0,y:0},l=null,d=null,c=m=>/^[a-zA-Z]$/.test(m),h=()=>{if(o>=i.length)throw new Error("Unexpected end of SVG path");let m=Number(i[o++]);if(!Number.isFinite(m))throw new Error(`Invalid SVG path number: ${i[o-1]}`);return m},u=(m,b)=>({x:b.x*2-m.x,y:b.y*2-m.y});for(;o<i.length;){let m=i[o++];if(!c(m??""))throw new Error(`Expected SVG command, got: ${m}`);let b=m,f=b===b?.toLowerCase();switch(b?.toUpperCase()){case "M":{let y=true;for(;o<i.length&&!c(i[o]);){let x=h(),v=h(),w={x:f?s.x+x:x,y:f?s.y+v:v};y?(r.push({type:"move-to",to:w}),a={...w},y=false):r.push({type:"line-to",to:w}),s=w,l=null,d=null;}break}case "L":{for(;o<i.length&&!c(i[o]);){let y=h(),x=h(),v={x:f?s.x+y:y,y:f?s.y+x:x};r.push({type:"line-to",to:v}),s=v,l=null,d=null;}break}case "H":{for(;o<i.length&&!c(i[o]);){let y=h(),x={x:f?s.x+y:y,y:s.y};r.push({type:"line-to",to:x}),s=x,l=null,d=null;}break}case "V":{for(;o<i.length&&!c(i[o]);){let y=h(),x={x:s.x,y:f?s.y+y:y};r.push({type:"line-to",to:x}),s=x,l=null,d=null;}break}case "Q":{for(;o<i.length&&!c(i[o]);){let y=h(),x=h(),v=h(),w=h(),I={x:f?s.x+y:y,y:f?s.y+x:x},C={x:f?s.x+v:v,y:f?s.y+w:w};r.push({type:"quad-to",control:I,to:C}),s=C,l={...I},d=null;}break}case "T":{for(;o<i.length&&!c(i[o]);){let y=h(),x=h(),v=l?u(l,s):{...s},w={x:f?s.x+y:y,y:f?s.y+x:x};r.push({type:"quad-to",control:v,to:w}),s=w,l={...v},d=null;}break}case "C":{for(;o<i.length&&!c(i[o]);){let y=h(),x=h(),v=h(),w=h(),I=h(),C=h(),T={x:f?s.x+y:y,y:f?s.y+x:x},A={x:f?s.x+v:v,y:f?s.y+w:w},P={x:f?s.x+I:I,y:f?s.y+C:C};r.push({type:"cubic-to",control1:T,control2:A,to:P}),s=P,l=null,d={...A};}break}case "S":{for(;o<i.length&&!c(i[o]);){let y=h(),x=h(),v=h(),w=h(),I=d?u(d,s):{...s},C={x:f?s.x+y:y,y:f?s.y+x:x},T={x:f?s.x+v:v,y:f?s.y+w:w};r.push({type:"cubic-to",control1:I,control2:C,to:T}),s=T,l=null,d={...C};}break}case "Z":{r.push({type:"close"}),s={...a},l=null,d=null;break}case "A":throw new Error("SVG arc commands (A/a) are not supported yet");default:throw new Error(`Unsupported SVG command: ${b}`)}}return r}static _tokenizeSvgPath(t){return t.replace(/,/g," ").replace(/([a-zA-Z])/g," $1 ").trim().split(/\s+/).flatMap(i=>/^[a-zA-Z]$/.test(i)?[i]:i.match(/[+-]?(?:\d*\.\d+|\d+\.?\d*)(?:[eE][+-]?\d+)?/g)??[])}};var q=class q extends N{constructor(t,i,r){super(t,r??"polygon-node",i??"Polygon");n(this,"_sideCount");this._sideCount=q.MIN_SIDE_COUNT;}getSideCount(){return this._sideCount}setSideCount(t){let i=this._clampSideCount(t);i!==this._sideCount&&(this._sideCount=i);}getVertices(){return this._getVertices()}hitTest(t){let i=this.getWorldAABB();if(t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height)return false;try{let r=W(this.getWorldMatrix()),o=this._applyMatrixToPoint(r,t),s=this._getVertices(),a=!1;for(let l=0,d=s.length-1;l<s.length;d=l++){let c=s[l].x,h=s[l].y,u=s[d].x,m=s[d].y;h>o.y!=m>o.y&&o.x<(u-c)*(o.y-h)/(m-h)+c&&(a=!a);}return a}catch{return false}}_clampSideCount(t){return Math.max(q.MIN_SIDE_COUNT,Math.min(q.MAX_SIDE_COUNT,Math.round(t)))}_getVertices(){console.log("herer");let t=this._sideCount,i=this.getWidth()/2,r=this.getHeight()/2,o=i,s=r,a=Math.PI*2/t,l=new Array(t);for(let d=0;d<t;d++){let c=d*a-Math.PI/2;l[d]={x:o+Math.cos(c)*i,y:s+Math.sin(c)*r};}return l}};n(q,"MIN_SIDE_COUNT",3),n(q,"MAX_SIDE_COUNT",60);var se=q;var hi=class extends se{constructor(t,i){super(t,i??"Star","star-node");n(this,"_innerRatio");this._innerRatio=.5,this.setSideCount(5);}getInnerRatio(){return this._innerRatio}setInnerRatio(t){let i=Math.max(0,Math.min(t,.999));i!==this._innerRatio&&(this._innerRatio=i);}_getVertices(){console.log("herererer");let t=this.getSideCount(),i=this.getWidth()/2,r=this.getHeight()/2,o=i,s=r,a=Math.PI*2/t,l=a/2,d=new Array(t*2);for(let c=0;c<t;c++){let h=c*a-Math.PI/2,u=h+l,m=c*2,b=m+1;d[m]={x:o+Math.cos(h)*i,y:s+Math.sin(h)*r},d[b]={x:o+Math.cos(u)*i*this._innerRatio,y:s+Math.sin(u)*r*this._innerRatio};}return d}};var dt=class extends N{constructor(e,t,i){super(e,i??"rect-node",t??"Rect");}};var ui=class extends dt{constructor(t,i){super(t,i??"Frame","frame-node");n(this,"_clipContent");this._clipContent=true;}getClipsContent(){return this._clipContent}setClipsContent(t){t!==this._clipContent&&(this._clipContent=t);}};var Tr=(r=>(r.Fill="fill",r.Contain="contain",r.Cover="cover",r.None="none",r))(Tr||{});var ae=class extends dt{constructor(t,i,r){super(t,i??"Image",r??"image-node");n(this,"_src");n(this,"_alt");n(this,"_fit");this._src="",this._alt="",this._fit="cover";}getSrc(){return this._src}setSrc(t){t!==this._src&&(this._src=t);}getAlt(){return this._alt}setAlt(t){t!==this._alt&&(this._alt=t);}getFit(){return this._fit}setFit(t){t!==this._fit&&(this._fit=t);}};var pi=class extends ae{constructor(t,i){super(t,i??"Video","video-node");n(this,"_poster");n(this,"_isAutoplay");n(this,"_isLooping");n(this,"_isPaused");n(this,"_currentFrame");n(this,"_totalFrames");n(this,"_playbackSpeed");n(this,"_currentTime");n(this,"_duration");n(this,"_volume");n(this,"_cachedVolume");n(this,"_isMuted");n(this,"_metadataLoadToken");this._poster="",this._isAutoplay=false,this._isLooping=false,this._isPaused=true,this._currentFrame=0,this._totalFrames=0,this._playbackSpeed=1,this._currentTime=0,this._duration=0,this._volume=.2,this._cachedVolume=this._volume,this._isMuted=false,this._metadataLoadToken=0;}setSrc(t){let i=this.getSrc();if(super.setSrc(t),i===this.getSrc()||(this._resetPlaybackState(),!t))return;let r=++this._metadataLoadToken;this._loadVideoMetadata(t,r);}getDuration(){return this._duration}getCurrentTime(){return this._currentTime}setCurrentTime(t){let i=Math.max(0,Math.min(this._duration||0,t));i!==this._currentTime&&(this._currentTime=i);}getCurrentFrame(){return this._currentFrame}getTotalFrames(){return this._totalFrames}isAutoplay(){return this._isAutoplay}setAutoplay(t){t!==this._isAutoplay&&(this._isAutoplay=t,t&&this._isPaused&&(this._isPaused=false));}isLooping(){return this._isLooping}setLooping(t){t!==this._isLooping&&(this._isLooping=t);}isPaused(){return this._isPaused}play(){this._isPaused&&(this._isPaused=false);}pause(){this._isPaused||(this._isPaused=true);}getPlaybackSpeed(){return this._playbackSpeed}setPlaybackSpeed(t){let i=Math.max(.1,t);i!==this._playbackSpeed&&(this._playbackSpeed=i);}isMuted(){return this._isMuted}getVolume(){return this._volume}setVolume(t){let i=Math.max(0,Math.min(1,t));i!==this._volume&&(this._volume=i,i>0&&(this._cachedVolume=i),this._isMuted=i===0);}mute(){this._isMuted||(this._isMuted=true,this._volume=0);}unmute(){this._isMuted&&(this._isMuted=false,this._volume=this._cachedVolume>0?this._cachedVolume:.2);}getPoster(){return this._poster}setPoster(t){t!==this._poster&&(this._poster=t);}_resetPlaybackState(){this._isPaused=!this._isAutoplay,this._currentTime=0,this._currentFrame=0,this._totalFrames=0,this._duration=0,this.setSize(0,0);}async _loadVideoMetadata(t,i){if(typeof document>"u")return;let r=document.createElement("video");r.preload="metadata",r.src=t,await new Promise(o=>{let s=()=>{r.onloadedmetadata=null,r.onerror=null;};r.onloadedmetadata=()=>{s(),o();},r.onerror=()=>{s(),o();};}),!(i!==this._metadataLoadToken||this.getSrc()!==t)&&Number.isFinite(r.duration)&&(this._duration=r.duration,this.setSize(r.videoWidth||0,r.videoHeight||0),this._totalFrames=0,this._currentFrame=0);}};var Rr=(r=>(r.Left="left",r.Center="center",r.Right="right",r.Justify="justify",r))(Rr||{}),Mr=(i=>(i.Top="top",i.Center="center",i.Bottom="bottom",i))(Mr||{}),Pr=(i=>(i.None="none",i.Word="word",i.Character="character",i))(Pr||{}),Er=(i=>(i.Normal="normal",i.Italic="italic",i.Oblique="oblique",i))(Er||{}),Ar=(r=>(r.None="none",r.Underline="underline",r.Striketrough="striketrough",r.Overline="overline",r))(Ar||{}),Lr=(i=>(i.Solid="solid",i.Dotted="dotted",i.Wavy="wavy",i))(Lr||{});var B=class B extends N{constructor(t,i){super(t,"text-node",i??"Text");n(this,"_text");n(this,"_fontFamily");n(this,"_fontSize");n(this,"_fontWeight");n(this,"_fontStyle");n(this,"_fontDecoration");n(this,"_underline");n(this,"_textAlign");n(this,"_verticalAlign");n(this,"_lineHeight");n(this,"_letterSpacing");n(this,"_wrapMode");this.setSize(160,48),this._text="Text",this._fontFamily="Inter",this._fontSize=B.TEXT_SCALE.base,this._fontWeight=B.FONT_WEIGHT.REGULAR,this._fontStyle="normal",this._fontDecoration="none",this._underline={style:"solid",skipInk:false,color:B.DEFAULT_TEXT_COLOR,thickness:1,offset:.2},this._textAlign="left",this._verticalAlign="top",this._lineHeight=1.2,this._letterSpacing=0,this._wrapMode="word";}getText(){return this._text}setText(t){t!==this._text&&(this._text=t);}getFontFamily(){return this._fontFamily}setFontFamily(t){t!==this._fontFamily&&(this._fontFamily=t);}getFontSize(){return this._fontSize}setFontSize(t){let i=Math.max(1,t);i!==this._fontSize&&(this._fontSize=i);}getFontWeight(){return this._fontWeight}setFontWeight(t){let i=Math.max(B.MIN_FONT_WEIGHT,Math.min(B.MAX_FONT_WEIGHT,Math.round(t)));i!==this._fontWeight&&(this._fontWeight=i);}getFontStyle(){return this._fontStyle}setFontStyle(t){t!==this._fontStyle&&(this._fontStyle=t);}getTextAlign(){return this._textAlign}setTextAlign(t){t!==this._textAlign&&(this._textAlign=t);}getVerticalAlign(){return this._verticalAlign}setVerticalAlign(t){t!==this._verticalAlign&&(this._verticalAlign=t);}getLineHeight(){return this._lineHeight}setLineHeight(t){let i=Math.max(0,t);i!==this._lineHeight&&(this._lineHeight=i);}getLetterSpacing(){return this._letterSpacing}setLetterSpacing(t){t!==this._letterSpacing&&(this._letterSpacing=t);}getWrapMode(){return this._wrapMode}setWrapMode(t){t!==this._wrapMode&&(this._wrapMode=t);}getFontDecoration(){return this._fontDecoration}setFontDecoration(t){t!==this._fontDecoration&&(this._fontDecoration=t);}getUnderlineStyle(){return this._underline.style}setUnderlineStyle(t){t!==this._underline.style&&(this._underline={...this._underline,style:t});}isUnderlineSkipInk(){return this._underline.skipInk}setUnderlineSkipInk(t){t!==this._underline.skipInk&&(this._underline={...this._underline,skipInk:t});}getUnderlineColor(){return culori.formatHex(this._underline.color)}setUnderlineColor(t){let i=typeof t=="string"?culori.parse(t):t;i&&culori.formatHex(this._underline.color)!==culori.formatHex(i)&&(this._underline={...this._underline,color:i});}getUnderlineThickness(){return this._underline.thickness}setUnderlineThickness(t){let i=Math.max(0,t);i!==this._underline.thickness&&(this._underline={...this._underline,thickness:i});}getUnderlineOffset(){return this._underline.offset}setUnderlineOffset(t){t!==this._underline.offset&&(this._underline={...this._underline,offset:t});}};n(B,"TEXT_SCALE",{xs:12,sm:14,base:16,lg:18,xl:20,"2xl":24,"3xl":30,"4xl":36,"5xl":48,"6xl":60}),n(B,"FONT_WEIGHT",{THIN:100,EXTRA_LIGHT:200,LIGHT:300,REGULAR:400,MEDIUM:500,SEMI_BOLD:600,BOLD:700,EXTRA_BOLD:800,BLACK:900}),n(B,"DEFAULT_TEXT_COLOR",{mode:"rgb",r:0,g:0,b:0}),n(B,"MIN_FONT_WEIGHT",100),n(B,"MAX_FONT_WEIGHT",900);var mi=B;var gi="debug-layer",_i="debug-bounds",fi="debug-pivot",bi="debug-orbit",yi="debug-aabb",Hr="debug-world-layer",vi="debug-view-bounds",L=class L{update(e,t){this._updateIdentity(e,t),this._updateVisibility(e,t),this._updateOpacity(e,t),this._updateTransform(e,t),this._updateDebug(e,t),this.onUpdate(e,t);}_updateIdentity(e,t){t.id(String(e.id));}_updateVisibility(e,t){t.visible(e.isVisible());}_updateOpacity(e,t){t.opacity(e.getOpacity());}_updateTransform(e,t){let i=e.getPosition(),r=e.getScale(),o=e.getPivot(),s=e.getLocalOBB();t.x(i.x),t.y(i.y),t.rotation(e.getRotation()),t.scaleX(r.x),t.scaleY(r.y),t.offsetX(s.x+s.width*o.x),t.offsetY(s.y+s.height*o.y);}_findOneOrThrow(e,t){let i=e.findOne(t);if(!i)throw new Error(`Konva node "${t}" was not found.`);return i}_updateDebug(e,t){let i=this._ensureDebugLayer(t),r=this._ensureWorldDebugLayer(e,t),o=false,s=e.getLocalOBB(),a=e.getPivot(),l=s.x+s.width*a.x,d=s.y+s.height*a.y,c=this._findOneOrThrow(i,`.${_i}`);c.visible(L.DEBUG_OBB),L.DEBUG_OBB&&(c.setAttrs({x:s.x,y:s.y,width:s.width,height:s.height}),o=true);let h=this._findOneOrThrow(i,`.${fi}`);h.visible(L.DEBUG_PIVOT),L.DEBUG_PIVOT&&(h.position({x:l,y:d}),o=true);let u=this._findOneOrThrow(i,`.${bi}`);if(u.visible(L.DEBUG_ORBIT),L.DEBUG_ORBIT){let f=this._getPivotOrbitRadius(s,l,d);u.position({x:l,y:d}),u.radius(f),o=true;}let m=this._findOneOrThrow(r,`.${yi}`);if(m.visible(L.DEBUG_AABB),L.DEBUG_AABB){let f=e.getWorldAABB();m.setAttrs({x:f.x,y:f.y,width:f.width,height:f.height}),o=true;}let b=this._findOneOrThrow(i,`.${vi}`);if(b.visible(L.DEBUG_VIEW_BOUNDS),L.DEBUG_VIEW_BOUNDS){let f=e.getLocalViewOBB();b.setAttrs({x:f.x,y:f.y,width:f.width,height:f.height}),o=true;}i.visible(o),r.visible(L.DEBUG_AABB),o&&i.moveToTop(),L.DEBUG_AABB&&r.moveToTop();}_ensureDebugLayer(e){let t=e.findOne(`.${gi}`);return t||(t=new j__default.default.Group({name:gi,listening:false,visible:false}),t.add(new j__default.default.Rect({name:_i,listening:false,stroke:"#00A3FF",strokeWidth:1,dash:[4,4]}),new j__default.default.Circle({name:fi,listening:false,radius:4,fill:"#34C759"}),new j__default.default.Circle({name:bi,listening:false,stroke:"#FFD60A",strokeWidth:1,dash:[4,4]}),new j__default.default.Rect({name:vi,listening:false,stroke:"#30D158",strokeWidth:1,dash:[4,4]})),e.add(t),t)}_ensureWorldDebugLayer(e,t){let i=t.getParent();if(!i)throw new Error("View has no parent. Cannot create world debug layer.");let r=`${Hr}-${e.id}`,o=i.findOne(`.${r}`);return o||(o=new j__default.default.Group({name:r,listening:false,visible:false}),o.add(new j__default.default.Rect({name:yi,listening:false,stroke:"#FF3B30",strokeWidth:1,dash:[6,4]})),i.add(o),o)}_getPivotOrbitRadius(e,t,i){let r=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}],o=0;for(let s of r){let a=s.x-t,l=s.y-i,d=Math.sqrt(a*a+l*l);d>o&&(o=d);}return o}};n(L,"DEBUG_OBB",false),n(L,"DEBUG_AABB",false),n(L,"DEBUG_ORBIT",false),n(L,"DEBUG_PIVOT",false),n(L,"DEBUG_VIEW_BOUNDS",false);var M=L;var le=class{constructor(){n(this,"_renderers",new Map);}register(e,t){if(this._renderers.has(e))throw new Error(`Renderer for node type "${e}" is already registered.`);this._renderers.set(e,t);}get(e){return this._renderers.get(e)}getOrThrow(e){let t=this.get(e);if(!t)throw new Error(`Renderer for node type "${e}" is not registered.`);return t}has(e){return this._renderers.has(e)}remove(e){return this._renderers.delete(e)}clear(){this._renderers.clear();}};var de=class{constructor(e,t){n(this,"_registry");n(this,"_contentRoot");n(this,"_mounted",new Map);this._registry=e,this._contentRoot=t;}renderNodes(e,t){let i=new Set;for(let r of e)this._renderNode(r,this._contentRoot,i,t);this._cleanupUnmounted(i);}removeNode(e){this._unmountNodeRecursive(e);}clear(){for(let[e,t]of this._mounted)t.destroy(),this._mounted.delete(e);}getMountedView(e){return this._mounted.get(e.id)}_renderNode(e,t,i,r){if(!e.isVisibleInHierarchy()){this._unmountNodeRecursive(e);return}let o=e.getHierarchyWorldAABB();if(!this._intersectsAabb(o,r)){this._unmountNodeRecursive(e);return}i.add(e.id);let s=this._registry.get(e.type),a=t;if(s){let l=this._mounted.get(e.id);l||(l=s.create(e),this._mounted.set(e.id,l)),l.getParent()!==t&&(l.remove(),t.add(l)),s.update(e,l),a=l;}for(let l of e.getChildren())this._renderNode(l,a,i,r);}_cleanupUnmounted(e){for(let[t,i]of this._mounted)e.has(t)||(i.destroy(),this._mounted.delete(t));}_unmountNodeRecursive(e){for(let i of e.getChildren())this._unmountNodeRecursive(i);let t=this._mounted.get(e.id);t&&(t.destroy(),this._mounted.delete(e.id));}_intersectsAabb(e,t){return !(e.x+e.width<t.x||t.x+t.width<e.x||e.y+e.height<t.y||t.y+t.height<e.y)}};var Nr="effect-shadow-group",kr="effect-shadow-shape",Br="effect-shadow-cutout",ce=class{constructor(e,t){n(this,"type");n(this,"_effect");n(this,"_group");n(this,"_shadowShape");n(this,"_cutoutShape");this.type="drop-shadow",this._effect=e,this._group=new j__default.default.Group({name:Nr,listening:false}),this._shadowShape=t.clone(),this._shadowShape.name(kr),this._shadowShape.listening(false),this._cutoutShape=t.clone(),this._cutoutShape.name(Br),this._cutoutShape.listening(false),this._cutoutShape.globalCompositeOperation("destination-out"),this._group.add(this._shadowShape,this._cutoutShape);}getShadowShape(){return this._shadowShape}getView(){return this._group}mount(e){e.add(this._group),this._group.moveToBottom();}update(){if(this._shadowShape.filters([]),this._shadowShape.blurRadius(0),this._shadowShape.clearCache(),this._group.clearCache(),!this._effect.isVisible()){this._group.visible(false);return}let e=Math.max(0,this._effect.getBlur()),t=this._effect.getSpread(),i=this._effect.getOpacity(),r=this._effect.getMode();this._group.visible(true),this._group.opacity(i),this._group.position({x:Math.round(this._effect.getX()),y:Math.round(this._effect.getY())}),this._shadowShape.visible(true),this._shadowShape.fill(this._effect.getFill()),this._shadowShape.setAttr("shadowSpread",t),r==="cutout"?(this._cutoutShape.setAttrs({rectWidth:this._shadowShape.getAttr("rectWidth"),rectHeight:this._shadowShape.getAttr("rectHeight"),strokeTop:this._shadowShape.getAttr("strokeTop"),strokeRight:this._shadowShape.getAttr("strokeRight"),strokeBottom:this._shadowShape.getAttr("strokeBottom"),strokeLeft:this._shadowShape.getAttr("strokeLeft"),strokeAlign:this._shadowShape.getAttr("strokeAlign"),radiusTopLeft:this._shadowShape.getAttr("radiusTopLeft"),radiusTopRight:this._shadowShape.getAttr("radiusTopRight"),radiusBottomRight:this._shadowShape.getAttr("radiusBottomRight"),radiusBottomLeft:this._shadowShape.getAttr("radiusBottomLeft"),shadowSpread:0}),this._cutoutShape.position({x:-Math.round(this._effect.getX()),y:-Math.round(this._effect.getY())}),this._cutoutShape.visible(true),this._cutoutShape.fill("#000")):(this._cutoutShape.visible(false),this._cutoutShape.position({x:0,y:0}));let o=this._getShadowCacheBounds(this._shadowShape,e);if(e>0&&(this._shadowShape.cache(o),this._shadowShape.filters([j__default.default.Filters.Blur]),this._shadowShape.blurRadius(e)),r==="cutout"){let s=this._shadowShape.getAttr("rectWidth")??0,a=this._shadowShape.getAttr("rectHeight")??0,l=Math.max(4,Math.ceil(e*3))+Math.max(0,t);this._group.cache({x:Math.floor(-t-l),y:Math.floor(-t-l),width:Math.max(1,Math.ceil(s+t*2+l*2)),height:Math.max(1,Math.ceil(a+t*2+l*2))});}}clear(){this._group.visible(false),this._shadowShape.visible(false),this._shadowShape.filters([]),this._shadowShape.blurRadius(0),this._shadowShape.clearCache(),this._group.clearCache();}destroy(){this._group.destroy();}_getShadowCacheBounds(e,t){let i=e.getAttr("rectWidth")??0,r=e.getAttr("rectHeight")??0,o=Math.max(0,e.getAttr("shadowSpread")??0),s=Math.max(4,Math.ceil(t*3));return {x:Math.floor(-o-s),y:Math.floor(-o-s),width:Math.max(1,Math.ceil(i+o*2+s*2)),height:Math.max(1,Math.ceil(r+o*2+s*2))}}};var Or="effect-inner-shadow-clip-group",Fr="effect-inner-shadow-group",Wr="effect-inner-shadow-blur-root",Gr="effect-inner-shadow-outer-rect",Vr="effect-inner-shadow-hole",he=class{constructor(e,t){n(this,"type");n(this,"_effect");n(this,"_clipGroup");n(this,"_group");n(this,"_blurRoot");n(this,"_outerRect");n(this,"_holeShape");this.type="inner-shadow",this._effect=e,this._clipGroup=new j__default.default.Group({name:Or,listening:false,visible:false}),this._group=new j__default.default.Group({name:Fr,listening:false}),this._blurRoot=new j__default.default.Group({name:Wr,listening:false}),this._outerRect=new j__default.default.Rect({name:Gr,listening:false}),this._holeShape=t.clone(),this._holeShape.name(Vr),this._holeShape.listening(false),this._holeShape.globalCompositeOperation("destination-out"),this._blurRoot.add(this._outerRect,this._holeShape),this._group.add(this._blurRoot),this._clipGroup.add(this._group);}getHoleShape(){return this._holeShape}getView(){return this._clipGroup}mount(e){e.add(this._clipGroup);}update(){if(this._blurRoot.filters([]),this._blurRoot.blurRadius(0),this._blurRoot.clearCache(),!this._effect.isVisible()){this._clipGroup.visible(false);return}let e=Math.max(0,this._effect.getBlur()),t=Math.max(0,this._effect.getSpread()),i=this._effect.getOpacity(),r=Math.round(this._effect.getX()),o=Math.round(this._effect.getY()),s=this._holeShape.getAttr("rectWidth")??0,a=this._holeShape.getAttr("rectHeight")??0;if(s<=0||a<=0){this._clipGroup.visible(false);return}let l=Math.max(4,Math.ceil(e*3))+t+Math.max(Math.abs(r),Math.abs(o));this._clipGroup.visible(true),this._clipGroup.opacity(i),this._clipGroup.position({x:0,y:0}),this._clipGroup.clipFunc(c=>{c.beginPath(),this._appendOuterShapePath(c,this._holeShape),c.closePath();}),this._outerRect.setAttrs({x:-l,y:-l,width:Math.max(1,Math.ceil(s+l*2)),height:Math.max(1,Math.ceil(a+l*2)),fill:this._effect.getFill()}),this._holeShape.position({x:-r,y:-o}),this._holeShape.setAttr("innerShadowInset",t),this._holeShape.fill("#000"),this._holeShape.visible(true);let d={x:-l,y:-l,width:Math.max(1,Math.ceil(s+l*2)),height:Math.max(1,Math.ceil(a+l*2))};this._blurRoot.cache(d),e>0&&(this._blurRoot.filters([j__default.default.Filters.Blur]),this._blurRoot.blurRadius(e));}clear(){this._clipGroup.visible(false),this._clipGroup.clipFunc(void 0),this._blurRoot.filters([]),this._blurRoot.blurRadius(0),this._blurRoot.clearCache();}destroy(){this._clipGroup.destroy();}_appendOuterShapePath(e,t){let i=t.getAttr("rectWidth")??0,r=t.getAttr("rectHeight")??0,o=t.getAttr("strokeTop")??0,s=t.getAttr("strokeRight")??0,a=t.getAttr("strokeBottom")??0,l=t.getAttr("strokeLeft")??0,d=t.getAttr("strokeAlign")??0,c={tl:t.getAttr("radiusTopLeft")??0,tr:t.getAttr("radiusTopRight")??0,br:t.getAttr("radiusBottomRight")??0,bl:t.getAttr("radiusBottomLeft")??0},h=Math.max(l,o),u=Math.max(s,o),m=Math.max(s,a),b=Math.max(l,a),f=0,y=0,x=i,v=r,w={...c};switch(d){case 0:f=0,y=0,x=i,v=r,w={...c};break;case 1:f=-l/2,y=-o/2,x=i+l/2+s/2,v=r+o/2+a/2,w={tl:this._expandRadius(c.tl,h/2),tr:this._expandRadius(c.tr,u/2),br:this._expandRadius(c.br,m/2),bl:this._expandRadius(c.bl,b/2)};break;case 2:f=-l,y=-o,x=i+l+s,v=r+o+a,w={tl:this._expandRadius(c.tl,h),tr:this._expandRadius(c.tr,u),br:this._expandRadius(c.br,m),bl:this._expandRadius(c.bl,b)};break}this._appendRoundedRectPath(e,f,y,x,v,w);}_appendRoundedRectPath(e,t,i,r,o,s){let a=Math.max(0,r),l=Math.max(0,o);if(a<=0||l<=0)return;let d=this._normalizeCornerRadius(a,l,s);e.moveTo(t+d.tl,i),e.lineTo(t+a-d.tr,i),e.arcTo(t+a,i,t+a,i+d.tr,d.tr),e.lineTo(t+a,i+l-d.br),e.arcTo(t+a,i+l,t+a-d.br,i+l,d.br),e.lineTo(t+d.bl,i+l),e.arcTo(t,i+l,t,i+l-d.bl,d.bl),e.lineTo(t,i+d.tl),e.arcTo(t,i,t+d.tl,i,d.tl),e.closePath();}_normalizeCornerRadius(e,t,i){let r=Math.max(0,i.tl),o=Math.max(0,i.tr),s=Math.max(0,i.br),a=Math.max(0,i.bl),l=r+o;if(l>e&&l>0){let u=e/l;r*=u,o*=u;}let d=a+s;if(d>e&&d>0){let u=e/d;a*=u,s*=u;}let c=r+a;if(c>t&&c>0){let u=t/c;r*=u,a*=u;}let h=o+s;if(h>t&&h>0){let u=t/h;o*=u,s*=u;}return {tl:r,tr:o,br:s,bl:a}}_expandRadius(e,t){return e<=0?0:Math.max(0,e+t)}};var Si="rect-stroke-shape",Kr=`.${Si}`,wi="rect-fill",zr=`.${wi}`,Ii="rect-effect-layer",Ur=`.${Ii}`,ue=class extends M{constructor(){super(...arguments);n(this,"_shadowRenderers",new Map);n(this,"_innerShadowRenderers",new Map);}create(t){let i=new j__default.default.Group({id:String(t.id)}),r=new j__default.default.Group({name:Ii,listening:false}),o=new j__default.default.Rect({name:wi,listening:false}),s=this._createStrokeShape();return r.add(o,s),i.add(r),i}onUpdate(t,i){let r=this._findOneOrThrow(i,zr),o=this._findOneOrThrow(i,Kr),s=this._findOneOrThrow(i,Ur),a=t.getWidth(),l=t.getHeight();r.width(a),r.height(l),r.fill(t.getFill());let{tl:d,tr:c,br:h,bl:u}=t.getCornerRadius();r.cornerRadius([d,c,h,u]);let m=t.getStrokeFill(),{t:b,r:f,b:y,l:x}=t.getStrokeWidth(),v=t.getStrokeAlign();o.fill(m),o.setAttrs({rectWidth:a,rectHeight:l,strokeTop:b,strokeRight:f,strokeBottom:y,strokeLeft:x,strokeAlign:v,radiusTopLeft:d,radiusTopRight:c,radiusBottomRight:h,radiusBottomLeft:u});let w=t.effect.get("drop-shadow"),I=t.effect.get("inner-shadow"),C=this._shadowRenderers.get(String(t.id)),T=this._innerShadowRenderers.get(String(t.id));if(!C&&w){let A=this._createShadowShape();C=new ce(w,A),C.mount(s),this._shadowRenderers.set(String(t.id),C);}if(!T&&I){let A=this._createInnerShadowHoleShape();T=new he(I,A),T.mount(s),this._innerShadowRenderers.set(String(t.id),T);}C&&(C.getShadowShape().setAttrs({rectWidth:a,rectHeight:l,strokeTop:b,strokeRight:f,strokeBottom:y,strokeLeft:x,strokeAlign:v,radiusTopLeft:d,radiusTopRight:c,radiusBottomRight:h,radiusBottomLeft:u}),C.update()),T&&(T.getHoleShape().setAttrs({rectWidth:a,rectHeight:l,strokeTop:b,strokeRight:f,strokeBottom:y,strokeLeft:x,strokeAlign:v,radiusTopLeft:d,radiusTopRight:c,radiusBottomRight:h,radiusBottomLeft:u}),T.update()),T&&(T.getView().moveToTop(),o.moveToTop());}_createStrokeShape(){return new j__default.default.Shape({name:Si,listening:false,sceneFunc:(t,i)=>{let r=i.getAttr("rectWidth")??0,o=i.getAttr("rectHeight")??0,s=i.getAttr("strokeTop")??0,a=i.getAttr("strokeRight")??0,l=i.getAttr("strokeBottom")??0,d=i.getAttr("strokeLeft")??0,c=i.getAttr("strokeAlign")??0,h={tl:i.getAttr("radiusTopLeft")??0,tr:i.getAttr("radiusTopRight")??0,br:i.getAttr("radiusBottomRight")??0,bl:i.getAttr("radiusBottomLeft")??0},u=0,m=0,b=r,f=o,y=0,x=0,v=r,w=o,I={...h},C={...h},T=Math.max(d,s),A=Math.max(a,s),P=Math.max(a,l),D=Math.max(d,l);switch(c){case 0:y=d,x=s,v=r-d-a,w=o-s-l,C={tl:this._shrinkRadius(h.tl,T),tr:this._shrinkRadius(h.tr,A),br:this._shrinkRadius(h.br,P),bl:this._shrinkRadius(h.bl,D)};break;case 1:u=-d/2,m=-s/2,b=r+d/2+a/2,f=o+s/2+l/2,y=d/2,x=s/2,v=r-d/2-a/2,w=o-s/2-l/2,I={tl:this._expandRadius(h.tl,T/2),tr:this._expandRadius(h.tr,A/2),br:this._expandRadius(h.br,P/2),bl:this._expandRadius(h.bl,D/2)},C={tl:this._shrinkRadius(h.tl,T/2),tr:this._shrinkRadius(h.tr,A/2),br:this._shrinkRadius(h.br,P/2),bl:this._shrinkRadius(h.bl,D/2)};break;case 2:u=-d,m=-s,b=r+d+a,f=o+s+l,I={tl:this._expandRadius(h.tl,T),tr:this._expandRadius(h.tr,A),br:this._expandRadius(h.br,P),bl:this._expandRadius(h.bl,D)};break}v=Math.max(0,v),w=Math.max(0,w),t.beginPath(),this._appendRoundedRectPath(t,u,m,b,f,I),v>0&&w>0&&this._appendRoundedRectPath(t,y,x,v,w,C),t.fillStyle=i.fill()||"#000",t.fill("evenodd");}})}_createShadowShape(){return new j__default.default.Shape({listening:false,sceneFunc:(t,i)=>{t.beginPath(),this._appendShadowOuterPath(t,i,true),t.fillStyle=i.fill()||"#000",t.fill();}})}_createInnerShadowHoleShape(){return new j__default.default.Shape({listening:false,sceneFunc:(t,i)=>{t.beginPath(),this._appendInnerShadowHolePath(t,i),t.fillStyle=i.fill()||"#000",t.fill();}})}_appendInnerShadowHolePath(t,i){let r=i.getAttr("rectWidth")??0,o=i.getAttr("rectHeight")??0,s=i.getAttr("strokeTop")??0,a=i.getAttr("strokeRight")??0,l=i.getAttr("strokeBottom")??0,d=i.getAttr("strokeLeft")??0,c=i.getAttr("strokeAlign")??0,h=Math.max(0,i.getAttr("innerShadowInset")??0),u={tl:i.getAttr("radiusTopLeft")??0,tr:i.getAttr("radiusTopRight")??0,br:i.getAttr("radiusBottomRight")??0,bl:i.getAttr("radiusBottomLeft")??0},m=Math.max(d,s),b=Math.max(a,s),f=Math.max(a,l),y=Math.max(d,l),x=0,v=0,w=r,I=o,C={...u};switch(c){case 0:x=0,v=0,w=r,I=o,C={...u};break;case 1:x=-d/2,v=-s/2,w=r+d/2+a/2,I=o+s/2+l/2,C={tl:this._expandRadius(u.tl,m/2),tr:this._expandRadius(u.tr,b/2),br:this._expandRadius(u.br,f/2),bl:this._expandRadius(u.bl,y/2)};break;case 2:x=-d,v=-s,w=r+d+a,I=o+s+l,C={tl:this._expandRadius(u.tl,m),tr:this._expandRadius(u.tr,b),br:this._expandRadius(u.br,f),bl:this._expandRadius(u.bl,y)};break}h>0&&(x+=h,v+=h,w-=h*2,I-=h*2,C={tl:this._shrinkRadius(C.tl,h),tr:this._shrinkRadius(C.tr,h),br:this._shrinkRadius(C.br,h),bl:this._shrinkRadius(C.bl,h)}),!(w<=0||I<=0)&&this._appendRoundedRectPath(t,x,v,w,I,C);}_appendShadowOuterPath(t,i,r){let o=i.getAttr("rectWidth")??0,s=i.getAttr("rectHeight")??0,a=i.getAttr("strokeTop")??0,l=i.getAttr("strokeRight")??0,d=i.getAttr("strokeBottom")??0,c=i.getAttr("strokeLeft")??0,h=i.getAttr("strokeAlign")??0,u=r?Math.max(0,i.getAttr("shadowSpread")??0):0,m={tl:i.getAttr("radiusTopLeft")??0,tr:i.getAttr("radiusTopRight")??0,br:i.getAttr("radiusBottomRight")??0,bl:i.getAttr("radiusBottomLeft")??0},b=Math.max(c,a),f=Math.max(l,a),y=Math.max(l,d),x=Math.max(c,d),v=0,w=0,I=o,C=s,T={...m};switch(h){case 0:v=0,w=0,I=o,C=s,T={...m};break;case 1:v=-c/2,w=-a/2,I=o+c/2+l/2,C=s+a/2+d/2,T={tl:this._expandRadius(m.tl,b/2),tr:this._expandRadius(m.tr,f/2),br:this._expandRadius(m.br,y/2),bl:this._expandRadius(m.bl,x/2)};break;case 2:v=-c,w=-a,I=o+c+l,C=s+a+d,T={tl:this._expandRadius(m.tl,b),tr:this._expandRadius(m.tr,f),br:this._expandRadius(m.br,y),bl:this._expandRadius(m.bl,x)};break}u>0&&(v-=u,w-=u,I+=u*2,C+=u*2,T={tl:this._expandRadius(T.tl,u),tr:this._expandRadius(T.tr,u),br:this._expandRadius(T.br,u),bl:this._expandRadius(T.bl,u)}),this._appendRoundedRectPath(t,v,w,I,C,T);}_appendRoundedRectPath(t,i,r,o,s,a){let l=Math.max(0,o),d=Math.max(0,s);if(l<=0||d<=0)return;let c=this._normalizeCornerRadius(l,d,a);t.moveTo(i+c.tl,r),t.lineTo(i+l-c.tr,r),t.arcTo(i+l,r,i+l,r+c.tr,c.tr),t.lineTo(i+l,r+d-c.br),t.arcTo(i+l,r+d,i+l-c.br,r+d,c.br),t.lineTo(i+c.bl,r+d),t.arcTo(i,r+d,i,r+d-c.bl,c.bl),t.lineTo(i,r+c.tl),t.arcTo(i,r,i+c.tl,r,c.tl),t.closePath();}_normalizeCornerRadius(t,i,r){let o=Math.max(0,r.tl),s=Math.max(0,r.tr),a=Math.max(0,r.br),l=Math.max(0,r.bl),d=o+s;if(d>t&&d>0){let m=t/d;o*=m,s*=m;}let c=l+a;if(c>t&&c>0){let m=t/c;l*=m,a*=m;}let h=o+l;if(h>i&&h>0){let m=i/h;o*=m,l*=m;}let u=s+a;if(u>i&&u>0){let m=i/u;s*=m,a*=m;}return {tl:o,tr:s,br:a,bl:l}}_expandRadius(t,i){return t<=0?0:Math.max(0,t+i)}_shrinkRadius(t,i){return t<=0?0:Math.max(0,t-i)}};var Ri="frame-fill",Yr=`.${Ri}`,Ti=class extends M{create(e){let t=new j__default.default.Group({id:String(e.id)}),i=new j__default.default.Rect({name:Ri,listening:false,x:0,y:0,width:0,height:0});return t.add(i),t}onUpdate(e,t){let i=this._findOneOrThrow(t,Yr),r=Math.max(0,e.getWidth()),o=Math.max(0,e.getHeight());i.width(r),i.height(o),"getFill"in e&&i.fill(e.getFill()),e.getClipsContent();}};var Pi="image-fill",Xr=`.${Pi}`,pe=class extends M{constructor(){super(...arguments);n(this,"_cache",new Map);}create(t){let i=new j__default.default.Group({id:String(t.id)}),r=new j__default.default.Image({name:Pi,listening:false,x:0,y:0,width:0,height:0,image:void 0});return i.add(r),i}onUpdate(t,i){let r=this._findOneOrThrow(i,Xr),o=Math.max(0,t.getWidth()),s=Math.max(0,t.getHeight());r.width(o),r.height(s);let a=t.getSrc();if(!a){r.image(void 0);return}let l=this._cache.get(a);l||(l=new window.Image,l.crossOrigin="anonymous",l.onload=()=>{this._cache.set(a,l),this._applyFit(t,r,l),r.getLayer()?.batchDraw();},l.onerror=()=>{r.image(void 0),r.getLayer()?.batchDraw();},l.src=a),l.complete&&this._applyFit(t,r,l);}_applyFit(t,i,r){let o=Math.max(1,t.getWidth()),s=Math.max(1,t.getHeight()),a=t.getFit(),l=r.width/r.height,d=o/s,c=o,h=s,u=0,m=0;a==="fill"?(c=o,h=s):a==="contain"?l>d?(c=o,h=o/l,m=(s-h)/2):(h=s,c=s*l,u=(o-c)/2):a==="cover"&&(l>d?(h=s,c=s*l,u=(o-c)/2):(c=o,h=o/l,m=(s-h)/2)),i.image(r),i.width(c),i.height(h),i.x(u),i.y(m);}};var Ai="video-fill",$r=`.${Ai}`,me=class extends M{constructor(){super(...arguments);n(this,"_videoCache",new Map);n(this,"_posterCache",new Map);}create(t){let i=new j__default.default.Group({id:String(t.id)}),r=new j__default.default.Image({name:Ai,listening:false,x:0,y:0,width:0,height:0,image:void 0});return i.add(r),i}onUpdate(t,i){let r=this._findOneOrThrow(i,$r),o=Math.max(0,t.getWidth()),s=Math.max(0,t.getHeight());r.width(o),r.height(s);let a=t.getSrc(),l=t.getPoster();if(!a){l?this._applyPoster(t,r,l):r.image(void 0);return}let d=this._videoCache.get(a);if(d||(d=document.createElement("video"),d.src=a,d.crossOrigin="anonymous",d.preload="auto",d.playsInline=true,d.muted=t.isMuted(),d.loop=t.isLooping(),d.autoplay=t.isAutoplay(),d.playbackRate=t.getPlaybackSpeed(),d.volume=t.isMuted()?0:t.getVolume(),d.onloadeddata=()=>{this._applyFit(t,r,d),r.getLayer()?.batchDraw();},d.ontimeupdate=()=>{t.setCurrentTime(d.currentTime),r.getLayer()?.batchDraw();},d.onended=()=>{t.pause(),r.getLayer()?.batchDraw();},d.onerror=()=>{l?this._applyPoster(t,r,l):(r.image(void 0),r.getLayer()?.batchDraw());},this._videoCache.set(a,d)),this._syncVideoState(t,d),d.readyState>=2){this._applyFit(t,r,d),r.image(d);let c=r.getLayer();c&&c.batchDraw();}else l?this._applyPoster(t,r,l):r.image(void 0);}_syncVideoState(t,i){i.loop=t.isLooping(),i.autoplay=t.isAutoplay(),i.playbackRate=t.getPlaybackSpeed(),i.muted=t.isMuted(),i.volume=t.isMuted()?0:t.getVolume();let r=t.getCurrentTime();if(t.isPaused()){if(Number.isFinite(r)&&Math.abs(i.currentTime-r)>.05)try{i.currentTime=r;}catch{}i.paused||i.pause();return}i.paused&&i.play().catch(()=>{}),t.setCurrentTime(i.currentTime);}_applyPoster(t,i,r){let o=this._posterCache.get(r);o||(o=new window.Image,o.crossOrigin="anonymous",o.onload=()=>{this._posterCache.set(r,o),this._applyFit(t,i,o),i.getLayer()?.batchDraw();},o.onerror=()=>{i.image(void 0),i.getLayer()?.batchDraw();},o.src=r),o.complete&&this._applyFit(t,i,o);}_applyFit(t,i,r){let o=Math.max(1,t.getWidth()),s=Math.max(1,t.getHeight()),a=t.getFit(),l="videoWidth"in r&&r.videoWidth?r.videoWidth:r.width??1,d="videoHeight"in r&&r.videoHeight?r.videoHeight:r.height??1,c=l/d,h=o/s,u=o,m=s,b=0,f=0;a==="fill"?(u=o,m=s):a==="contain"?c>h?(u=o,m=o/c,f=(s-m)/2):(m=s,u=s*c,b=(o-u)/2):a==="none"?(u=l,m=d,b=0,f=0):c>h?(m=s,u=s*c,b=(o-u)/2):(u=o,m=o/c,f=(s-m)/2),i.image(r),i.width(u),i.height(m),i.x(b),i.y(f);}};var Di="ellipse-fill",qr=`.${Di}`,ge=class extends M{create(e){let t=new j__default.default.Group({id:String(e.id)}),i=new j__default.default.Shape({name:Di,listening:false,sceneFunc:(r,o)=>{let s=o.getAttr("ellipseWidth")??0,a=o.getAttr("ellipseHeight")??0,l=o.getAttr("innerRatio")??0,d=o.getAttr("startAngle")??0,c=o.getAttr("endAngle")??360;if(s<=0||a<=0)return;let h=s/2,u=a/2,m=h,b=u,f=this._degToRad(d),y=this._degToRad(c),x=y-f,v=this._isFullEllipseSweep(x);if(r.beginPath(),v){r.ellipse(m,b,h,u,0,0,Math.PI*2),l>0?(r.ellipse(m,b,h*l,u*l,0,0,Math.PI*2),r.fillStyle=o.fill()||"#000",r.fill("evenodd")):(r.fillStyle=o.fill()||"#000",r.fill());return}this._appendEllipseArcPath(r,m,b,h,u,f,y,false),l>0?this._appendEllipseArcPath(r,m,b,h*l,u*l,y,f,true):r.lineTo(m,b),r.closePath(),r.fillStyle=o.fill()||"#000",r.fill();}});return t.add(i),t}onUpdate(e,t){let i=this._findOneOrThrow(t,qr);i.setAttrs({ellipseWidth:Math.max(0,e.getWidth()),ellipseHeight:Math.max(0,e.getHeight()),innerRatio:Math.max(0,Math.min(e.getInnerRatio(),.999)),startAngle:e.getStartAngle(),endAngle:e.getEndAngle()}),i.fill(e.getFill());}_appendEllipseArcPath(e,t,i,r,o,s,a,l){let d=a-s,c=Math.max(1,Math.ceil(Math.abs(d)/(Math.PI/32)));for(let h=0;h<=c;h++){let u=h/c,m=s+d*u,b=t+Math.cos(m)*r,f=i+Math.sin(m)*o;h===0?l?e.lineTo(b,f):e.moveTo(b,f):e.lineTo(b,f);}}_isFullEllipseSweep(e){return Math.abs(Math.abs(e)-Math.PI*2)<1e-4}_degToRad(e){return e*Math.PI/180}};var Ni="polygon-fill",jr=`.${Ni}`,_e=class extends M{create(e){let t=new j__default.default.Group({id:String(e.id)}),i=new j__default.default.Shape({name:Ni,listening:false,sceneFunc:(r,o)=>{let s=o.getAttr("polygonWidth")??0,a=o.getAttr("polygonHeight")??0,l=Math.max(3,o.getAttr("sideCount")??3);if(s<=0||a<=0)return;let d=s/2,c=a/2,h=Math.min(s,a)/2,u=-Math.PI/2,m=Math.PI*2/l;r.beginPath();for(let b=0;b<l;b++){let f=u+b*m,y=d+Math.cos(f)*h,x=c+Math.sin(f)*h;b===0?r.moveTo(y,x):r.lineTo(y,x);}r.closePath(),r.fillStyle=o.fill()||"#000",r.fill();}});return t.add(i),t}onUpdate(e,t){let i=this._findOneOrThrow(t,jr);i.setAttrs({polygonWidth:Math.max(0,e.getWidth()),polygonHeight:Math.max(0,e.getHeight()),sideCount:Math.max(3,e.getSideCount())}),i.fill(e.getFill());}};var Bi="star-fill",Zr=`.${Bi}`,fe=class extends M{create(e){let t=new j__default.default.Group({id:String(e.id)}),i=new j__default.default.Shape({name:Bi,listening:false,sceneFunc:(r,o)=>{let s=o.getAttr("vertices");if(!(!s||s.length===0)){r.beginPath();for(let a=0;a<s.length;a++){let l=s[a];a===0?r.moveTo(l.x,l.y):r.lineTo(l.x,l.y);}r.closePath(),r.fillStyle=o.fill()||"#000",r.fill();}}});return t.add(i),t}onUpdate(e,t){let i=this._findOneOrThrow(t,Zr);i.setAttrs({vertices:e.getVertices()}),i.fill(e.getFill()),i.getLayer()?.batchDraw();}};var Fi="line-stroke",Qr=`.${Fi}`,be=class extends M{create(e){let t=new j__default.default.Group({id:String(e.id)}),i=new j__default.default.Shape({name:Fi,listening:false,sceneFunc:(r,o)=>{let s=o.getAttr("startX")??0,a=o.getAttr("startY")??0,l=o.getAttr("endX")??0,d=o.getAttr("endY")??0,c=Math.max(0,o.getAttr("thickness")??0),h=o.getAttr("lineCapStart")??"butt",u=o.getAttr("lineCapEnd")??"butt";if(c<=0)return;let m=l-s,b=d-a,f=Math.sqrt(m*m+b*b);if(f<=1e-6){this._drawDegenerateLine(r,s,a,c,h,u,o);return}let y=m/f,x=b/f,v=-x,w=y,I=c/2,C=h==="square"?I:0,T=u==="square"?I:0,A=s-y*C,P=a-x*C,D=l+y*T,bt=d+x*T,yt=A+v*I,er=P+w*I,ir=D+v*I,rr=bt+w*I,or=D-v*I,nr=bt-w*I,sr=A-v*I,ar=P-w*I;r.fillStyle=o.fill()||"#000",r.beginPath(),r.moveTo(yt,er),r.lineTo(ir,rr),r.lineTo(or,nr),r.lineTo(sr,ar),r.closePath(),r.fill(),h==="round"&&(r.beginPath(),r.arc(s,a,I,0,Math.PI*2),r.fill()),u==="round"&&(r.beginPath(),r.arc(l,d,I,0,Math.PI*2),r.fill());}});return t.add(i),t}onUpdate(e,t){let i=this._findOneOrThrow(t,Qr),r=e.getStart(),o=e.getEnd();i.setAttrs({startX:r.x,startY:r.y,endX:o.x,endY:o.y,thickness:e.getStrokeThickness(),lineCapStart:e.getLineCapStart(),lineCapEnd:e.getLineCapEnd()}),i.fill(e.getStrokeFill());}_drawDegenerateLine(e,t,i,r,o,s,a){let l=r/2;if(o==="round"||s==="round"){e.beginPath(),e.arc(t,i,l,0,Math.PI*2),e.fillStyle=a.fill()||"#000",e.fill();return}e.beginPath(),e.rect(t-l,i-l,r,r),e.fillStyle=a.fill()||"#000",e.fill();}};var Gi="text-fill",Jr=`.${Gi}`,ye=class extends M{create(e){let t=new j__default.default.Group({id:String(e.id)}),i=new j__default.default.Text({name:Gi,listening:false,text:"",width:0,height:0,fontFamily:"Inter",fontSize:16,fontStyle:"normal",fontVariant:"normal",align:"left",verticalAlign:"top",wrap:"word",lineHeight:1.2,padding:0,fill:"#000000"});return t.add(i),t}onUpdate(e,t){let i=this._findOneOrThrow(t,Jr);i.text(e.getText()),i.fontFamily(e.getFontFamily()),i.fontSize(e.getFontSize()),i.fontStyle(this._resolveFontStyle(e)),i.align(this._resolveTextAlign(e)),i.verticalAlign(this._resolveVerticalAlign(e)),i.wrap(this._resolveWrapMode(e)),i.lineHeight(e.getLineHeight()),i.fill(e.getFill()),"letterSpacing"in i&&typeof i.letterSpacing=="function"&&i.letterSpacing(e.getLetterSpacing()),i.width(Math.max(1,e.getWidth())),i.height(void 0);let r=i.getClientRect({skipTransform:true,skipShadow:true,skipStroke:true});i.height(Math.max(1,r.height));}_resolveFontStyle(e){let t=e.getFontWeight(),r=e.getFontStyle()==="italic"?"italic":"normal",o=String(t);return `${r} ${o}`}_resolveTextAlign(e){switch(e.getTextAlign()){case "center":return "center";case "right":return "right";case "justify":return "justify";case "left":default:return "left"}}_resolveVerticalAlign(e){switch(e.getVerticalAlign()){case "center":return "middle";case "bottom":return "bottom";case "top":default:return "top"}}_resolveWrapMode(e){switch(e.getWrapMode()){case "character":return "char";case "none":return "none";case "word":default:return "word"}}};var Ki="path-fill",to=`.${Ki}`,ve=class extends M{create(e){let t=new j__default.default.Group({id:String(e.id)}),i=new j__default.default.Shape({name:Ki,listening:false,sceneFunc:(r,o)=>{let s=o.getAttr("commands")??[];if(!s.length)return;r.beginPath(),this._appendPathCommands(r,s);let a=o.fill();a&&(r.fillStyle=a,r.fill());let l=o.getAttr("strokeColor"),d=o.getAttr("strokeWidth")??0;l&&d>0&&(r.strokeStyle=l,r.lineWidth=d,r.stroke());}});return t.add(i),t}onUpdate(e,t){let i=this._findOneOrThrow(t,to);i.setAttrs({commands:e.getCommands(),strokeColor:"getStrokeFill"in e?e.getStrokeFill():void 0,strokeWidth:"getStrokeWidth"in e?e.getStrokeWidth():0}),i.fill(e.getFill());}_appendPathCommands(e,t){for(let i of t)switch(i.type){case "move-to":e.moveTo(i.to.x,i.to.y);break;case "line-to":e.lineTo(i.to.x,i.to.y);break;case "quad-to":e.quadraticCurveTo(i.control.x,i.control.y,i.to.x,i.to.y);break;case "cubic-to":e.bezierCurveTo(i.control1.x,i.control1.y,i.control2.x,i.control2.y,i.to.x,i.to.y);break;case "close":e.closePath();break}}};var zi=class{constructor(){n(this,"type");n(this,"id");n(this,"_layer");n(this,"_fillRect");n(this,"_imageNode");n(this,"_background",null);n(this,"_imageElement",null);n(this,"_imageSrc","");this.id=0,this.type="canvas",this._layer=new j__default.default.Layer({listening:false}),this._fillRect=new j__default.default.Rect({listening:false}),this._imageNode=new j__default.default.Image,this._imageNode.listening(false),this._imageNode.visible(false),this._layer.add(this._fillRect),this._layer.add(this._imageNode);}getLayer(){return this._layer}getRenderNode(){return this._layer}attach(e){this._background=e;}detach(){this._background=null,this._imageElement=null,this._imageSrc="",this._imageNode.image(null),this._imageNode.visible(false);}render(){this._layer.draw();}update(){if(!this._background)return;let e=this._background.getWidth(),t=this._background.getHeight();this._fillRect.setAttrs({x:0,y:0,width:e,height:t,fill:this._background.getFill()});let i=this._background.getImage();if(!i){this._imageSrc="",this._imageElement=null,this._imageNode.image(null),this._imageNode.visible(false);return}if(i!==this._imageSrc){this._loadImage(i);return}this._imageElement&&this._applyImageAttrs();}destroy(){this.detach(),this._layer.destroy();}_loadImage(e){this._imageSrc=e,this._imageElement=null,this._imageNode.visible(false);let t=new Image;t.onload=()=>{e===this._imageSrc&&(this._imageElement=t,this._imageNode.image(t),this._applyImageAttrs(),this._layer.draw());},t.onerror=()=>{e===this._imageSrc&&(this._imageElement=null,this._imageNode.image(null),this._imageNode.visible(false),this._layer.draw());},t.src=e;}_applyImageAttrs(){if(!this._background||!this._imageElement){this._imageNode.visible(false);return}this._imageNode.setAttrs({x:this._background.getImageX(),y:this._background.getImageY(),opacity:this._background.getImageOpacity(),width:this._background.getImageWidth(),height:this._background.getImageHeight(),offsetX:this._background.getImageOffsetX(),offsetY:this._background.getImageOffsetY(),image:this._imageElement,visible:true});}};var G=class G{constructor(){n(this,"_root");n(this,"_handle",null);n(this,"_camera",null);n(this,"_view",null);n(this,"_nodeId",null);n(this,"_nodeType",null);this._root=new j__default.default.Group({listening:false});}getRoot(){return this._root}attach(e){this._handle=e.getHandle(),this._camera=e.getCamera();}detach(){this._handle=null,this._camera=null,this._destroyView();}update(){if(!this._handle||!this._camera||!this._handle.isEnabled()||!this._handle.hasNode()){this._destroyView();return}let e=this._handle.getNode();if(!e){this._destroyView();return}let t=this._nodeType!==e.type,i=this._nodeId!==e.id;(!this._view||t||i)&&this._recreateView(e),this._view&&this._updateView(e,this._view);}render(){}destroy(){this.detach(),this._root.destroy();}_recreateView(e){this._destroyView();let t=this._createView(e);t&&(this._view=t,this._nodeId=e.id.toString(),this._nodeType=e.type,this._root.add(t));}_destroyView(){this._view&&this._view.destroy(),this._view=null,this._nodeId=null,this._nodeType=null;}_createView(e){switch(e.type){case "rect-node":case "image-node":case "video-node":case "text-node":return new j__default.default.Rect({fillEnabled:false,stroke:G.STROKE,strokeWidth:G.STROKE_WIDTH,listening:false});case "ellipse-node":return new j__default.default.Ellipse({fillEnabled:false,stroke:G.STROKE,strokeWidth:G.STROKE_WIDTH,listening:false});case "line-node":case "polygon-node":case "star-node":case "path-node":return new j__default.default.Line({closed:true,fillEnabled:false,stroke:G.STROKE,strokeWidth:G.STROKE_WIDTH,listening:false});default:return null}}_updateView(e,t){switch(e.type){case "rect-node":case "image-node":case "video-node":case "text-node":this._updateRectLike(e,t);return;case "ellipse-node":this._updateEllipse(e,t);return;case "line-node":case "polygon-node":case "star-node":case "path-node":this._updatePolyLike(e,t);return}}_updateRectLike(e,t){let i=this._toScreenPoints(e.getWorldViewCorners()),r=Math.hypot(i[1].x-i[0].x,i[1].y-i[0].y),o=Math.hypot(i[2].x-i[1].x,i[2].y-i[1].y),s=(i[0].x+i[2].x)/2,a=(i[0].y+i[2].y)/2,l=Math.atan2(i[1].y-i[0].y,i[1].x-i[0].x)*180/Math.PI;t.setAttrs({x:s,y:a,width:r,height:o,offsetX:r/2,offsetY:o/2,rotation:l,visible:true});}_updateEllipse(e,t){let i=this._toScreenPoints(e.getWorldViewCorners()),r=Math.hypot(i[1].x-i[0].x,i[1].y-i[0].y),o=Math.hypot(i[2].x-i[1].x,i[2].y-i[1].y),s=(i[0].x+i[2].x)/2,a=(i[0].y+i[2].y)/2,l=Math.atan2(i[1].y-i[0].y,i[1].x-i[0].x)*180/Math.PI;t.setAttrs({x:s,y:a,radiusX:r/2,radiusY:o/2,rotation:l,visible:true});}_updatePolyLike(e,t){let i=this._toScreenPoints(e.getWorldViewCorners());t.points([i[0].x,i[0].y,i[1].x,i[1].y,i[2].x,i[2].y,i[3].x,i[3].y]),t.visible(true);}_toScreenPoint(e){return this._camera?this._camera.worldToScreen(e):e}_toScreenPoints(e){return e.map(t=>this._toScreenPoint(t))}};n(G,"STROKE","#4DA3FF"),n(G,"STROKE_WIDTH",3);var Se=G;var we=class{constructor(e,t){n(this,"_handle");n(this,"_camera");this._handle=e,this._camera=t;}getHandle(){return this._handle}getCamera(){return this._camera}};var Ie=class{constructor(e,t){n(this,"_handle");n(this,"_camera");this._handle=e,this._camera=t;}getHandle(){return this._handle}getCamera(){return this._camera}};var eo="transform-outline",Ce=class{constructor(){n(this,"_target",null);n(this,"_group");n(this,"_outline",null);this._group=new j__default.default.Group({listening:false,visible:true});}attach(e){this._target=e;}detach(){this._target=null,this._destroyOutline();}getRoot(){return this._group}render(){}update(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t||!e.isEnabled()||!e.hasNode()){this._destroyOutline();return}let i=e.getObbCorners();if(i.length<4){this._destroyOutline();return}let r=this._getOrCreateOutline(),o=t.worldToScreen(i[0]),s=t.worldToScreen(i[1]),a=t.worldToScreen(i[2]),l=t.worldToScreen(i[3]);r.points([o.x,o.y,s.x,s.y,a.x,a.y,l.x,l.y,o.x,o.y]),r.visible(true);}destroy(){this.detach(),this._group.destroy(),this._outline=null;}_getOrCreateOutline(){return this._outline?this._outline:(this._outline=new j__default.default.Line({name:eo,listening:false,stroke:"#4C8DFF",strokeWidth:1,perfectDrawEnabled:false}),this._group.add(this._outline),this._outline)}_destroyOutline(){this._outline&&(this._outline.destroy(),this._outline=null);}};var io=6,ro="#FFFFFF",oo="#4C8DFF",no=1,Te=class{constructor(){n(this,"_target",null);n(this,"_group");n(this,"_handle",null);this._group=new j__default.default.Group({listening:false,visible:true});}attach(e){this._target=e;}detach(){this._target=null,this._destroyHandle();}getRoot(){return this._group}render(){}update(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t||!e.isEnabled()||!e.hasNode()){this._destroyHandle();return}let i=e.getPivotWorldPoint();if(!i){this._destroyHandle();return}let r=t.worldToScreen(i),o=this._getOrCreateHandle();o.position({x:r.x,y:r.y}),o.visible(true);}destroy(){this.detach(),this._group.destroy(),this._handle=null;}_getOrCreateHandle(){return this._handle?this._handle:(this._handle=new j__default.default.Circle({name:"transform-pivot-handle",listening:false,radius:io,fill:ro,stroke:oo,strokeWidth:no,perfectDrawEnabled:false,visible:true}),this._group.add(this._handle),this._handle)}_destroyHandle(){this._handle&&(this._handle.destroy(),this._handle=null);}};var Re=class{constructor(e,t){n(this,"_handle");n(this,"_camera");this._handle=e,this._camera=t;}getHandle(){return this._handle}getCamera(){return this._camera}};var Me=class{constructor(e,t){n(this,"_handle");n(this,"_camera");this._handle=e,this._camera=t;}getHandle(){return this._handle}getCamera(){return this._camera}};var so=["n","e","s","w"],ao=["ne","nw","se","sw"],Pe=8,lo="#4C8DFF",co=2,ho="#FFFFFF",uo="#4C8DFF",po=1,Ee=class{constructor(){n(this,"_target",null);n(this,"_group");n(this,"_edgesGroup");n(this,"_handlesGroup");n(this,"_edges");n(this,"_handles");this._group=new j__default.default.Group({listening:false,visible:true}),this._edgesGroup=new j__default.default.Group({listening:false,visible:true}),this._handlesGroup=new j__default.default.Group({listening:false,visible:true}),this._edges=new Map,this._handles=new Map,this._group.add(this._edgesGroup),this._group.add(this._handlesGroup);}attach(e){this._target=e;}detach(){this._target=null,this._destroyView();}getRoot(){return this._group}render(){}update(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t||!e.isEnabled()||!e.hasNode()){this._destroyView();return}this._updateEdges(),this._updateHandles();}destroy(){this.detach(),this._group.destroy(),this._edges.clear(),this._handles.clear();}_updateEdges(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t){this._destroyEdges();return}for(let i of so){let r=e.getEdgeWorldPoints(i);if(!r){this._destroyEdge(i);continue}let o=t.worldToScreen(r[0]),s=t.worldToScreen(r[1]),a=this._getOrCreateEdge(i);a.points([o.x,o.y,s.x,s.y]),a.visible(true);}}_updateHandles(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t){this._destroyHandles();return}let i=e.getEdgeWorldPoints("n");if(!i){this._destroyHandles();return}let r=t.worldToScreen(i[0]),o=t.worldToScreen(i[1]),a=Math.atan2(o.y-r.y,o.x-r.x)*180/Math.PI;for(let l of ao){let d=e.getHandleWorldPoint(l);if(!d){this._destroyHandle(l);continue}let c=t.worldToScreen(d),h=this._getOrCreateHandle(l);h.position({x:c.x,y:c.y}),h.rotation(a),h.visible(true);}}_getOrCreateEdge(e){let t=this._edges.get(e);if(t)return t;let i=new j__default.default.Line({name:`transform-resize-edge-${e}`,listening:false,stroke:lo,strokeWidth:co,perfectDrawEnabled:false});return this._edges.set(e,i),this._edgesGroup.add(i),i}_getOrCreateHandle(e){let t=this._handles.get(e);if(t)return t;let i=new j__default.default.Rect({name:`transform-resize-handle-${e}`,listening:false,fill:ho,stroke:uo,strokeWidth:po,width:Pe,height:Pe,offsetX:Pe*.5,offsetY:Pe*.5,perfectDrawEnabled:false,visible:true});return this._handles.set(e,i),this._handlesGroup.add(i),i}_destroyEdge(e){let t=this._edges.get(e);t&&(t.destroy(),this._edges.delete(e));}_destroyHandle(e){let t=this._handles.get(e);t&&(t.destroy(),this._handles.delete(e));}_destroyEdges(){for(let e of Array.from(this._edges.keys()))this._destroyEdge(e);}_destroyHandles(){for(let e of Array.from(this._handles.keys()))this._destroyHandle(e);}_destroyView(){this._destroyEdges(),this._destroyHandles();}};var mo=["ne","nw","se","sw"],go=18,Ae=class{constructor(){n(this,"_target",null);n(this,"_group");n(this,"_handles");this._group=new j__default.default.Group({listening:false,visible:true}),this._handles=new Map;}attach(e){this._target=e;}detach(){this._target=null,this._destroyView();}getRoot(){return this._group}render(){}update(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t||!e.isEnabled()||!e.hasNode()){this._destroyView();return}for(let i of mo){let r=e.getHandleWorldPoint(i);if(!r){this._destroyHandle(i);continue}let o=t.worldToScreen(r),s=this._getOrCreateHandle(i);s.position({x:o.x,y:o.y}),s.visible(true);}}destroy(){this.detach(),this._group.destroy(),this._handles.clear();}_getOrCreateHandle(e){let t=this._handles.get(e);if(t)return t;let i=new j__default.default.Circle({name:`transform-rotate-handle-${e}`,listening:false,radius:go,perfectDrawEnabled:false,visible:true});return this._handles.set(e,i),this._group.add(i),i}_destroyHandle(e){let t=this._handles.get(e);t&&(t.destroy(),this._handles.delete(e));}_destroyView(){for(let e of Array.from(this._handles.keys()))this._destroyHandle(e);}};var Le=class{constructor(e,t){n(this,"_handle");n(this,"_camera");this._handle=e,this._camera=t;}getHandle(){return this._handle}getCamera(){return this._camera}};var De=class{constructor(e,t){n(this,"_handle");n(this,"_camera");this._handle=e,this._camera=t;}getHandle(){return this._handle}getCamera(){return this._camera}};var Ue=["tl","tr","br","bl"],_o=4,fo="#FFFFFF",bo="#4C8DFF",yo=1,vo="#FF9F0A",xo=1,So=.9,wo="#FF2D55",Io=1,Co=2.5,To="#FF2D55",He=class{constructor(){n(this,"_target",null);n(this,"_group");n(this,"_debugGroup");n(this,"_handlesGroup");n(this,"_handles");n(this,"_debugSections");n(this,"_debugDiagonals");n(this,"_debugOrigins");this._group=new j__default.default.Group({listening:false,visible:true}),this._debugGroup=new j__default.default.Group({listening:false,visible:false}),this._handlesGroup=new j__default.default.Group({listening:false,visible:true}),this._handles=new Map,this._debugSections=new Map,this._debugDiagonals=new Map,this._debugOrigins=new Map,this._group.add(this._debugGroup),this._group.add(this._handlesGroup);}attach(e){this._target=e;}detach(){this._target=null,this._destroyView();}getRoot(){return this._group}render(){}update(){let e=this._target?.getHandle();if(!e||!e.isEnabled()||!e.hasNode()){this._destroyView();return}this._updateHandles(),e.isDebugEnabled()?this._updateDebugSections():this._destroyDebug();}destroy(){this.detach(),this._group.destroy(),this._handles.clear(),this._debugSections.clear(),this._debugDiagonals.clear(),this._debugOrigins.clear();}_updateHandles(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t){this._destroyHandles();return}for(let i of Ue){let r=e.getHandleWorldPoint(i);if(!r){this._destroyHandle(i);continue}let o=t.worldToScreen(r),s=this._getOrCreateHandle(i);s.position({x:o.x,y:o.y}),s.visible(true);}}_updateDebugSections(){let e=this._target?.getHandle(),t=this._target?.getCamera();if(!e||!t){this._destroyDebug();return}for(let i of Ue){let r=e.getSection(i);if(!r){this._destroyDebugAxis(i);continue}this._updateDebugSection(i,r,t),this._updateDebugDiagonal(i,r,t),this._updateDebugOrigin(i,r,t);}}_updateDebugSection(e,t,i){let r=this._getOrCreateDebugSection(e),o=i.worldToScreen(t.origin),s=i.worldToScreen(t.xAxisPoint),a=i.worldToScreen(this._getSectionDiagonalPoint(t)),l=i.worldToScreen(t.yAxisPoint);r.points([o.x,o.y,s.x,s.y,a.x,a.y,l.x,l.y]),r.closed(true),r.visible(true);}_updateDebugDiagonal(e,t,i){let r=this._getOrCreateDebugDiagonal(e),o=i.worldToScreen(t.origin),s=i.worldToScreen(this._getSectionDiagonalPoint(t));r.points([o.x,o.y,s.x,s.y]),r.visible(true);}_updateDebugOrigin(e,t,i){let r=this._getOrCreateDebugOrigin(e),o=i.worldToScreen(t.origin);r.position({x:o.x,y:o.y}),r.visible(true);}_getOrCreateHandle(e){let t=this._handles.get(e);if(t)return t;let i=new j__default.default.Circle({name:`corner-radius-handle-${e}`,listening:false,radius:_o,fill:fo,stroke:bo,strokeWidth:yo,perfectDrawEnabled:false,visible:true});return this._handles.set(e,i),this._handlesGroup.add(i),i}_getOrCreateDebugSection(e){let t=this._debugSections.get(e);if(t)return t;let i=new j__default.default.Line({name:`corner-radius-debug-section-${e}`,listening:false,stroke:vo,strokeWidth:xo,opacity:So,perfectDrawEnabled:false,closed:true,visible:true});return this._debugSections.set(e,i),this._debugGroup.add(i),i}_getOrCreateDebugDiagonal(e){let t=this._debugDiagonals.get(e);if(t)return t;let i=new j__default.default.Line({name:`corner-radius-debug-diagonal-${e}`,listening:false,stroke:wo,strokeWidth:Io,perfectDrawEnabled:false,visible:true});return this._debugDiagonals.set(e,i),this._debugGroup.add(i),i}_getOrCreateDebugOrigin(e){let t=this._debugOrigins.get(e);if(t)return t;let i=new j__default.default.Circle({name:`corner-radius-debug-origin-${e}`,listening:false,radius:Co,fill:To,perfectDrawEnabled:false,visible:true});return this._debugOrigins.set(e,i),this._debugGroup.add(i),i}_destroyHandle(e){let t=this._handles.get(e);t&&(t.destroy(),this._handles.delete(e));}_destroyHandles(){for(let e of Array.from(this._handles.keys()))this._destroyHandle(e);}_destroyDebugAxis(e){let t=this._debugSections.get(e);t&&(t.destroy(),this._debugSections.delete(e));let i=this._debugDiagonals.get(e);i&&(i.destroy(),this._debugDiagonals.delete(e));let r=this._debugOrigins.get(e);r&&(r.destroy(),this._debugOrigins.delete(e));}_destroyDebug(){for(let e of Ue)this._destroyDebugAxis(e);}_destroyView(){this._destroyHandles(),this._destroyDebug();}_getSectionDiagonalPoint(e){return {x:e.xAxisPoint.x+e.yAxisPoint.x-e.origin.x,y:e.xAxisPoint.y+e.yAxisPoint.y-e.origin.y}}};var qi=class{constructor(){n(this,"id");n(this,"type");n(this,"_layer");n(this,"_root");n(this,"_overlay",null);n(this,"_camera",null);n(this,"_hoverRenderer");n(this,"_handleTransformRenderer");n(this,"_handleTransformResizeRenderer");n(this,"_handleTransformRotateRenderer");n(this,"_handleTransformPivotRenderer");n(this,"_handleCornerRadiusRenderer");this.id=2,this.type="canvas",this._layer=new j__default.default.Layer({listening:false}),this._root=new j__default.default.Group({listening:false}),this._hoverRenderer=new Se,this._handleTransformRenderer=new Ce,this._handleTransformResizeRenderer=new Ee,this._handleTransformRotateRenderer=new Ae,this._handleTransformPivotRenderer=new Te,this._handleCornerRadiusRenderer=new He,this._root.add(this._hoverRenderer.getRoot()),this._root.add(this._handleTransformRotateRenderer.getRoot()),this._root.add(this._handleTransformRenderer.getRoot()),this._root.add(this._handleTransformResizeRenderer.getRoot()),this._root.add(this._handleTransformPivotRenderer.getRoot()),this._root.add(this._handleCornerRadiusRenderer.getRoot()),this._layer.add(this._root);}getLayer(){return this._layer}getRenderNode(){return this._layer}attach(e){this._overlay=e.getOverlay(),this._camera=e.getCamera();let t=this._overlay.getHandlerManager().get("hover");if(!t)throw new Error("Hover handle is not registered.");let i=new we(t,this._camera);this._hoverRenderer.attach(i);let r=this._overlay.getHandlerManager().get(ot.TYPE);this._handleTransformRenderer.attach(new Ie(r,this._camera));let o=this._overlay.getHandlerManager().get(z.TYPE);this._handleTransformResizeRenderer.attach(new Me(o,this._camera));let s=this._overlay.getHandlerManager().get(U.TYPE);this._handleTransformRotateRenderer.attach(new Le(s,this._camera));let a=this._overlay.getHandlerManager().get(V.TYPE);this._handleTransformPivotRenderer.attach(new Re(a,this._camera));let l=this._overlay.getHandlerManager().get(Y.TYPE);this._handleCornerRadiusRenderer.attach(new De(l,this._camera));}detach(){this._hoverRenderer.detach(),this._handleTransformRenderer.detach(),this._handleTransformResizeRenderer.detach(),this._handleTransformRotateRenderer.detach(),this._handleTransformPivotRenderer.detach(),this._handleCornerRadiusRenderer.detach(),this._overlay=null,this._camera=null;}render(){this._layer.draw();}update(){if(!this._overlay||!this._overlay.isEnabled())return;let e=this._overlay.getWidth(),t=this._overlay.getHeight();this._layer.size({width:e,height:t}),this._hoverRenderer.update(),this._handleTransformRenderer.update(),this._handleTransformResizeRenderer.update(),this._handleTransformRotateRenderer.update(),this._handleTransformPivotRenderer.update(),this._handleCornerRadiusRenderer.update();}destroy(){this.detach(),this._hoverRenderer.destroy(),this._handleTransformRenderer.destroy(),this._handleTransformResizeRenderer.destroy(),this._handleTransformRotateRenderer.destroy(),this._handleTransformPivotRenderer.destroy(),this._handleCornerRadiusRenderer.destroy(),this._root.destroyChildren(),this._layer.destroy();}};var ji=class{constructor(e,t){n(this,"_layer");n(this,"_camera");this._layer=e,this._camera=t;}getOverlay(){return this._layer}getCamera(){return this._camera}};var Zi=class{constructor(){n(this,"id");n(this,"type");n(this,"_layer");n(this,"_content");n(this,"_gridContent");n(this,"_registry");n(this,"_manager");n(this,"_world",null);n(this,"_gridView");this.id=1,this.type="canvas",this._layer=new j__default.default.Layer({listening:false}),this._content=new j__default.default.Group({listening:false}),this._gridContent=new j__default.default.Group({listening:false}),this._registry=new le,this._manager=new de(this._registry,this._content);let e=new Ct;this._gridView=new It({renderer:e,getDrawInput:()=>this._world?{camera:this._world.getCamera().getState(),viewportAabbWorld:this._world.getViewportWorldAABB()}:{camera:{x:0,y:0,scale:1,rotation:0},viewportAabbWorld:{x:0,y:0,width:0,height:0}}}),this._gridContent.add(this._content),this._gridContent.add(this._gridView.getRoot()),this._layer.add(this._gridContent),this._registerDefaultRenderers();}getLayer(){return this._layer}getRenderNode(){return this._layer}attach(e){this._world=e,this._gridView.setOptions({enabled:true,size:1,majorEvery:10,maxLines:1e3,minorAlpha:.2,majorAlpha:.2});}detach(){this._world=null,this._manager.clear(),this._content.destroyChildren(),this._gridContent.setAttrs({x:0,y:0,scaleX:1,scaleY:1,rotation:0,offsetX:0,offsetY:0});}update(){if(!this._world)return;this._applyCamera(this._world.getCamera().getState());let e=this._world.getViewportWorldAABB();this._manager.renderNodes(this._world.getNodes(),e);}render(){this._layer.draw();}destroy(){this.detach(),this._gridView.destroy(),this._layer.destroy();}_registerDefaultRenderers(){this._registry.register("rect-node",new ue),this._registry.register("ellipse-node",new ge),this._registry.register("polygon-node",new _e),this._registry.register("star-node",new fe),this._registry.register("line-node",new be),this._registry.register("text-node",new ye),this._registry.register("image-node",new pe),this._registry.register("video-node",new me),this._registry.register("path-node",new ve);}_applyCamera(e){if(!this._world)return;let{width:t,height:i}=this._world.getSize(),{x:r,y:o,scale:s,rotation:a}=e,l=t/2,d=i/2;this._gridContent.position({x:l,y:d}),this._gridContent.offset({x:r,y:o}),this._gridContent.scale({x:s,y:s}),this._gridContent.rotation(-a*180/Math.PI);}};var Ne=class{constructor(e=-1,t=null){n(this,"type");n(this,"id");n(this,"_scene");this.id=_.clamp(e,-1,$),this.type=t,this._scene=null;}detach(){this._scene&&(this._scene.layerManager.getAll().forEach(e=>{e.renderer.detach();}),this._onDetach(this._scene),this._scene=null);}render(){this._scene&&(this._scene.layerManager.getAll().forEach(e=>{e.renderer.render();}),this._onRender(this._scene));}update(){this._scene&&(this._onUpdate(this._scene),this._scene.layerManager.getAll().forEach(e=>{e.renderer.update();}));}destroy(){this._scene&&(this._scene.layerManager.getAll().forEach(e=>{e.renderer.destroy();}),this._onDestroy(this._scene),this.detach());}_onAttachBindings(e,t){this._scene&&this.detach(),e.layerManager.getAll().forEach(i=>{let r=i.renderer,o=this.type===null||r.type===this.type,s=this.id===-1||r.id===this.id;o&&s&&t(i);}),this._scene=e,this.update();}};var Qi=class extends Ne{constructor(t,i=-1){super(i,"canvas");n(this,"_stage");this._stage=new j__default.default.Stage({container:t,width:1,height:1,draggable:false});}getSurface(){return this._stage.container()}getRenderNode(){return this._stage}attach(t){this._onAttachBindings(t,i=>{let r=i.renderer;this._stage.add(r.getRenderNode());});}_onUpdate(t){let i=t.getWidth(),r=t.getHeight();this._stage.width(i),this._stage.height(r);}_onRender(t){}_onDetach(t){}_onDestroy(t){this._stage.destroy();}};var Ji=class{constructor(e){n(this,"type");n(this,"id");n(this,"_container");n(this,"_layer",null);n(this,"_root",null);this.id=3,this.type="html",this._container=e;}getRenderNode(){return this._root}attach(e){if(this._layer===e)return;this.detach(),this._layer=e;let t=document.createElement("div");t.className="flowscape-layer-ui",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.overflow="hidden",this._root=t,this._container.appendChild(t),t.addEventListener("wheel",i=>{i.preventDefault();},{passive:false});for(let i of this._layer.getManager().getAll())i.attach(t);}detach(){if(this._layer){for(let e of this._layer.getManager().getAll())e.detach();this._root&&this._root.remove(),this._root=null,this._layer=null;}}update(){if(!this._layer||!this._root)return;let{width:e,height:t}=this._layer.getSize();this._root.style.width=`${e}px`,this._root.style.height=`${t}px`,this._root.style.display=this._layer.isEnabled()?"block":"none";for(let i of this._getModules())i.isEnabled()&&i.update();}render(){}destroy(){this.detach();}getRoot(){return this._root}_getModules(){return this._layer?this._layer.getManager().getAll():[]}};var ke=class{constructor(){n(this,"_bindings",new Map);}add(e,t,i){let r=String(t.id),o=this._bindings.get(r);o&&(o.controller.detach(),o.controller.destroy()),t.attach(i),this._bindings.set(r,{layer:e,controller:t});}remove(e){let t=String(e),i=this._bindings.get(t);return i?(i.controller.detach(),i.controller.destroy(),this._bindings.delete(t),true):false}update(){this._bindings.forEach(e=>{e.controller.update();});}getAll(){return Array.from(this._bindings.values())}getById(e){return this._bindings.get(String(e))??null}destroy(){this._bindings.forEach(e=>{e.controller.detach(),e.controller.destroy();}),this._bindings.clear();}};var Be=class{constructor(){n(this,"_bindings",new Map);}add(e,t,i){let r=String(e.id),o=this._bindings.get(r);o&&(o.layer.destroy(),o.renderer.detach(),o.renderer.destroy()),t.attach(i),this._bindings.set(r,{layer:e,renderer:t});}remove(e){let t=String(e),i=this._bindings.get(t);return i?(i.layer.destroy(),i.renderer.detach(),i.renderer.destroy(),this._bindings.delete(t),true):false}getAll(){return Array.from(this._bindings.values())}getById(e){return this._bindings.get(String(e))??null}};var Oe=class{constructor(e){n(this,"_hosts",[]);n(this,"_hostsById",new Map);n(this,"_scene");this._scene=e;}add(e){this.detach();let t=Number(e.id);if(this._hostsById.has(t))throw new Error(`Render host "${t}" already exists.`);S._registerSurface(e.getSurface()),this._hosts.push(e),this._hostsById.set(t,e),this.attach();}remove(e){let t=this._hostsById.get(e);if(!t)return false;this._hostsById.delete(e);let i=this._hosts.indexOf(t);return i!==-1&&this._hosts.splice(i,1),S._unregisterSurface(t.getSurface()),t.detach(),t.destroy(),true}getAll(){return this._hosts}getById(e){return this._hostsById.get(e)??null}attach(){this.detach();for(let e of this._hosts)e.attach(this._scene);}detach(){for(let e of this._hosts)e.detach();}update(){for(let e of this._hosts)e.update();}render(){for(let e of this._hosts)e.render();}destroy(){for(let e of this._hosts)e.detach(),e.destroy();this._hosts.length=0,this._hostsById.clear();}};var tr=class{constructor(e,t){n(this,"layerBackground");n(this,"layerWorld");n(this,"layerOverlay");n(this,"layerUI");n(this,"layerManager");n(this,"hostManager");n(this,"inputManager");n(this,"_isFrameScheduled",false);n(this,"_width");n(this,"_height");this.layerBackground=new Nt(e,t),this.layerWorld=new kt(e,t),this.layerOverlay=new Ut(e,t),this.layerUI=new jt(this.layerWorld,e,t),this.layerManager=new Be,this.hostManager=new Oe(this),this.inputManager=new ke,this._width=e,this._height=t,S._initialize(),S.onInput(()=>{this.invalidate();});}getWidth(){return this._width}getHeight(){return this._height}setSize(e,t){this._width=e,this._height=t,this.layerManager.getAll().forEach(i=>{i.layer.setSize(e,t),i.renderer.update();}),this.invalidate();}update(){this.inputManager.update(),this.layerManager.getAll().forEach(e=>{e.renderer.update();}),this.hostManager?.update();}render(){this.layerManager.getAll().forEach(e=>{e.renderer.render();}),this.hostManager?.render(),S._endFrame();}invalidate(){this._isFrameScheduled||(this._isFrameScheduled=true,requestAnimationFrame(()=>{this._isFrameScheduled=false,this.update(),this.render();}));}};exports.BROWSER_KEY_CODE_MAP=Ze;exports.BaseGradient=Pt;exports.BaseRendererHost=Ne;exports.BoxPosition=cr;exports.Camera=xt;exports.CanvasRendererHost=Qi;exports.Color=E;exports.ConicGradient=Et;exports.ConicGradientPosition=hr;exports.DEG_TO_RAD=Xe;exports.DiamondGradient=At;exports.EPSILON=qe;exports.EPSILON_STRICT=Ho;exports.EffectBase=st;exports.EffectInnerShadow=ni;exports.EffectShadow=oi;exports.Enableable=St;exports.EventEmitter=Q;exports.FLOAT32_EPSILON=No;exports.FLOAT32_MAX=$;exports.FLOAT32_MIN=ht;exports.FontDecoration=Ar;exports.FontDecorationUnderlineStyle=Lr;exports.FontStyle=Er;exports.GridRenderer=Ct;exports.HALF_PI=Lo;exports.HandleCornerRadius=Y;exports.HandleHover=rt;exports.HandleTransform=ot;exports.HandleTransformPivot=V;exports.HandleTransformPosition=K;exports.HandleTransformResize=z;exports.HandleTransformRotate=U;exports.ImageFit=Tr;exports.Input=S;exports.InputControllerBase=et;exports.InputManager=ke;exports.KonvaGridView=It;exports.LayerBackground=Nt;exports.LayerBase=O;exports.LayerManager=Be;exports.LayerOverlay=Ut;exports.LayerOverlayHandleManager=Bt;exports.LayerOverlayInputController=ei;exports.LayerType=ut;exports.LayerUI=jt;exports.LayerWorld=kt;exports.LayerWorldInputController=Qe;exports.LineCap=wr;exports.LineEnding=Ir;exports.LinearGradient=Lt;exports.ManagerLayerUI=Yt;exports.ManagerRenderHost=Oe;exports.MathF32=_;exports.MeshGradient=Dt;exports.ModuleBaseLayerUI=Xt;exports.ModuleManager=tt;exports.ModuleOverlayCornerRadius=ie;exports.ModuleOverlayHover=Mt;exports.ModuleOverlayTransform=ee;exports.ModuleOverlayTransformMove=Zt;exports.ModuleOverlayTransformPivot=Qt;exports.ModuleOverlayTransformResize=Jt;exports.ModuleOverlayTransformRotate=te;exports.ModuleRulerUI=qt;exports.ModuleWorldPan=Rt;exports.ModuleWorldZoom=Tt;exports.NodeBase=nt;exports.NodeEllipse=ai;exports.NodeFrame=ui;exports.NodeGroup=li;exports.NodeImage=ae;exports.NodeLine=di;exports.NodePath=ci;exports.NodePolygon=se;exports.NodeRect=dt;exports.NodeStar=hi;exports.NodeText=mi;exports.NodeType=ri;exports.NodeVideo=pi;exports.PI=vt;exports.PathCommandType=Cr;exports.QUARTER_PI=Do;exports.RAD_TO_DEG=$e;exports.RadialGradient=Ht;exports.RadialGradientPosition=ur;exports.RendererCanvasBase=M;exports.RendererCanvasEllipse=ge;exports.RendererCanvasFrame=Ti;exports.RendererCanvasImage=pe;exports.RendererCanvasLine=be;exports.RendererCanvasManager=de;exports.RendererCanvasPath=ve;exports.RendererCanvasPolygon=_e;exports.RendererCanvasRect=ue;exports.RendererCanvasRegistry=le;exports.RendererCanvasStar=fe;exports.RendererCanvasText=ye;exports.RendererCanvasVideo=me;exports.RendererHandleCornerRadiusCanvas=He;exports.RendererHandleCornerRadiusTarget=De;exports.RendererHandleHoverCanvas=Se;exports.RendererHandleHoverTarget=we;exports.RendererHandleTransformCanvas=Ce;exports.RendererHandleTransformPivotCanvas=Te;exports.RendererHandleTransformPivotTarget=Re;exports.RendererHandleTransformResizeCanvas=Ee;exports.RendererHandleTransformResizeTarget=Me;exports.RendererHandleTransformRotateCanvas=Ae;exports.RendererHandleTransformRotateTarget=Le;exports.RendererHandleTransformTarget=Ie;exports.RendererLayerBackgroundCanvas=zi;exports.RendererLayerOverlayCanvas=qi;exports.RendererLayerOverlayTarget=ji;exports.RendererLayerUI=Ji;exports.RendererLayerWorldCanvas=Zi;exports.RulerGuideLine=$t;exports.Scene=tr;exports.ShadowMode=vr;exports.ShapeBase=N;exports.StrokeAlign=yr;exports.TAU=Ao;exports.TextAlign=Rr;exports.TextVerticalAlign=Mr;exports.TextWrapMode=Pr;exports.Transform=wt;exports.clamp01=H;exports.clamp255=F;exports.getBrowserKeyCode=Fe;exports.isBrowserKeyCode=tn;exports.replaceMarkersFromInputString=ti;
|