@linker-design-plus/timeline-track 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Ln=Object.defineProperty;var Dn=(a,t,e)=>t in a?Ln(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e;var g=(a,t,e)=>Dn(a,typeof t!="symbol"?t+"":t,e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Rs={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},$e={background:"#000000",border:"#333333",timeTick:"#666666",timeText:"#aaaaaa",trackBackground:"#000000",trackSelectedBackground:"#292929",trackBorder:"#444444",clipBackground:"#2e2e2e",clipBorder:"#000000",clipName:"#ffffff",clipDuration:"#cccccc",clipHandle:"#ffffff",clipSelectedBackground:"#b5baff",clipSelectedBorder:"#50e3c2",clipSelectedName:"#ffffff",clipSelectedDuration:"#ffffff",clipSelectedHandle:"#ffffff",clipSelectedCoverBackground:"#444444",clipCoverBackground:"#333333",audioClipBackground:"#252525",audioClipText:"#d0d0d0",audioClipAccent:"#b8b8c0",playhead:"#ffffff",grid:"#333333",snapGuideLineColor:"#50e3c2",snapGuideLineWidth:1,scrollbarBackground:"#333333",scrollbarBorder:"#555555",scrollbarThumb:"#444444"};function be(a){return a?{...$e,...a}:{...$e}}const vt={mode:"auto-first-added-video",width:16,height:9},Rn=[{key:"default",label:"默认",aspectRatio:{...vt}},{key:"9:16",label:"9:16",aspectRatio:{mode:"manual",width:9,height:16}},{key:"16:9",label:"16:9",aspectRatio:{mode:"manual",width:16,height:9}},{key:"3:4",label:"3:4",aspectRatio:{mode:"manual",width:3,height:4}},{key:"4:3",label:"4:3",aspectRatio:{mode:"manual",width:4,height:3}}];function Ai(a){return a==="manual"?"manual":"auto-first-added-video"}function Qt(a){return Ai(a)==="auto-first-added-video"}function Dt(a){return{mode:Ai(a==null?void 0:a.mode),width:typeof(a==null?void 0:a.width)=="number"&&a.width>0?a.width:vt.width,height:typeof(a==null?void 0:a.height)=="number"&&a.height>0?a.height:vt.height}}const On={DEFAULT:1,ACTIVE:2},ct={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Os={DURATION:300,EASING:"easeOutCubic"},Gn={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},ot=15,ke=6,_t={VIDEO:64,AUDIO:48};function Gs(a={}){const t=Object.fromEntries(Object.entries(a).filter(([,e])=>e!==void 0));return{...Rs,...t}}function Ei(a,t={}){return{...a,...Gs(t)}}class z{static msToSeconds(t){return t/1e3}static secondsToMs(t){return t*1e3}static timeToPixels(t,e){return this.msToSeconds(t)*e}static pixelsToTime(t,e){return this.secondsToMs(t/e)}static formatTime(t){const e=t/1e3,i=Math.floor(e/60),s=Math.floor(e%60),n=Math.floor(t%1e3/10);return`${i.toString().padStart(2,"0")}:${s.toString().padStart(2,"0")}.${n.toString().padStart(2,"0")}`}static formatDuration(t){const e=Math.floor(t/1e3),i=Math.floor(t%1e3/10);return`${e}.${i.toString().padStart(2,"0")}s`}static diffTime(t,e){return Math.abs(t-e)}static isTimeInRange(t,e,i){return t>=e&&t<=i}static clampTime(t,e,i){return Math.max(e,Math.min(i,t))}static calculateEndTime(t,e){return t+e}static getTickConfig(t){let e,i;return t>=1e3?(e=1,i=.1):t>=500?(e=1,i=.5):t>=100?(e=1,i=1):t>=50?(e=5,i=1):t>=10?(e=10,i=2):t>=5?(e=60,i=10):(e=300,i=60),{majorStep:e,minorStep:i}}static generateTimeTicks(t,e=1){const i=[],s=this.msToSeconds(t);for(let n=0;n<=s;n+=e)i.push(this.secondsToMs(n));return i}static generateVisibleTicks(t,e,i,s){const n=[],r=Math.max(0,t);let o=Math.floor(r/i)*i,l=0;const h=100;for(let p=o;p<=e&&(n.push({time:this.secondsToMs(p),type:this.TICK_TYPE_MAJOR}),l++,!(l>=h));p+=i);let c=0;const d=400;let u=Math.floor(r/s)*s;for(let p=u;p<=e&&!(Math.abs(p-Math.round(p/i)*i)>.001&&(n.push({time:this.secondsToMs(p),type:this.TICK_TYPE_MINOR}),c++,c>=d));p+=s);return n.sort((p,f)=>p.time-f.time)}static getVideoDuration(t){return new Promise(e=>{const i=document.createElement("video");i.preload="metadata",i.onloadedmetadata=()=>{i.onloadedmetadata=null,i.onerror=null,e(i.duration*1e3)},i.onerror=()=>{i.onloadedmetadata=null,i.onerror=null,e(0)},i.src=t})}}g(z,"TICK_TYPE_MAJOR","major"),g(z,"TICK_TYPE_MINOR","minor");const Bn=Math.PI/180;function Hn(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const Ft=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},E={_global:Ft,version:"10.2.0",isBrowser:Hn(),isUnminified:/param/.test((function(a){}).toString()),dblClickWindow:400,getAngle(a){return E.angleDeg?a*Bn:a},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return E.DD.isDragging},isTransforming(){var a,t;return(t=(a=E.Transformer)===null||a===void 0?void 0:a.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!E.DD.node},releaseCanvasOnDestroy:!0,document:Ft.document,_injectGlobal(a){typeof Ft.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),Ft.Konva=a}},st=a=>{E[a.prototype.getClassName()]=a};E._injectGlobal(E);const zn=`Konva.js unsupported environment.
1
+ "use strict";var Ws=Object.defineProperty;var Ys=(a,e,t)=>e in a?Ws(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var g=(a,e,t)=>Ys(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Yn={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},Jt={background:"#000000",border:"#333333",timeTick:"#666666",timeText:"#aaaaaa",trackBackground:"#000000",trackSelectedBackground:"#292929",trackBorder:"#444444",clipBackground:"#2e2e2e",clipBorder:"#000000",clipName:"#ffffff",clipDuration:"#cccccc",clipHandle:"#ffffff",clipSelectedBackground:"#b5baff",clipSelectedBorder:"#50e3c2",clipSelectedName:"#ffffff",clipSelectedDuration:"#ffffff",clipSelectedHandle:"#ffffff",clipSelectedCoverBackground:"#444444",clipCoverBackground:"#333333",audioClipBackground:"#252525",audioClipText:"#d0d0d0",audioClipAccent:"#b8b8c0",playhead:"#ffffff",grid:"#333333",snapGuideLineColor:"#50e3c2",snapGuideLineWidth:1,scrollbarBackground:"#333333",scrollbarBorder:"#555555",scrollbarThumb:"#444444"};function xt(a){return a?{...Jt,...a}:{...Jt}}const be={mode:"auto-first-added-video",width:16,height:9},Xs=[{key:"default",label:"默认",aspectRatio:{...be}},{key:"9:16",label:"9:16",aspectRatio:{mode:"manual",width:9,height:16}},{key:"16:9",label:"16:9",aspectRatio:{mode:"manual",width:16,height:9}},{key:"3:4",label:"3:4",aspectRatio:{mode:"manual",width:3,height:4}},{key:"4:3",label:"4:3",aspectRatio:{mode:"manual",width:4,height:3}}];function Di(a){return a==="manual"?"manual":"auto-first-added-video"}function st(a){return Di(a)==="auto-first-added-video"}function De(a){return{mode:Di(a==null?void 0:a.mode),width:typeof(a==null?void 0:a.width)=="number"&&a.width>0?a.width:be.width,height:typeof(a==null?void 0:a.height)=="number"&&a.height>0?a.height:be.height}}const Us={DEFAULT:1,ACTIVE:2},de={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Xn={DURATION:300,EASING:"easeOutCubic"},$s={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},le=15,It=6,_e={VIDEO:64,AUDIO:48};function Un(a={}){const e=Object.fromEntries(Object.entries(a).filter(([,t])=>t!==void 0));return{...Yn,...e}}function Oi(a,e={}){return{...a,...Un(e)}}class N{static msToSeconds(e){return e/1e3}static secondsToMs(e){return e*1e3}static timeToPixels(e,t){return this.msToSeconds(e)*t}static pixelsToTime(e,t){return this.secondsToMs(e/t)}static formatTime(e){const t=e/1e3,i=Math.floor(t/60),n=Math.floor(t%60),s=Math.floor(e%1e3/10);return`${i.toString().padStart(2,"0")}:${n.toString().padStart(2,"0")}.${s.toString().padStart(2,"0")}`}static formatDuration(e){const t=Math.floor(e/1e3),i=Math.floor(e%1e3/10);return`${t}.${i.toString().padStart(2,"0")}s`}static diffTime(e,t){return Math.abs(e-t)}static isTimeInRange(e,t,i){return e>=t&&e<=i}static clampTime(e,t,i){return Math.max(t,Math.min(i,e))}static calculateEndTime(e,t){return e+t}static getTickConfig(e){let t,i;return e>=1e3?(t=1,i=.1):e>=500?(t=1,i=.5):e>=100?(t=1,i=1):e>=50?(t=5,i=1):e>=10?(t=10,i=2):e>=5?(t=60,i=10):(t=300,i=60),{majorStep:t,minorStep:i}}static generateTimeTicks(e,t=1){const i=[],n=this.msToSeconds(e);for(let s=0;s<=n;s+=t)i.push(this.secondsToMs(s));return i}static generateVisibleTicks(e,t,i,n){const s=[],r=Math.max(0,e);let o=Math.floor(r/i)*i,l=0;const h=100;for(let f=o;f<=t&&(s.push({time:this.secondsToMs(f),type:this.TICK_TYPE_MAJOR}),l++,!(l>=h));f+=i);let c=0;const d=400;let u=Math.floor(r/n)*n;for(let f=u;f<=t&&!(Math.abs(f-Math.round(f/i)*i)>.001&&(s.push({time:this.secondsToMs(f),type:this.TICK_TYPE_MINOR}),c++,c>=d));f+=n);return s.sort((f,p)=>f.time-p.time)}static getVideoDuration(e){return new Promise(t=>{const i=document.createElement("video");i.preload="metadata",i.onloadedmetadata=()=>{i.onloadedmetadata=null,i.onerror=null,t(i.duration*1e3)},i.onerror=()=>{i.onloadedmetadata=null,i.onerror=null,t(0)},i.src=e})}}g(N,"TICK_TYPE_MAJOR","major"),g(N,"TICK_TYPE_MINOR","minor");const qs=Math.PI/180;function Ks(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const We=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},E={_global:We,version:"10.2.0",isBrowser:Ks(),isUnminified:/param/.test((function(a){}).toString()),dblClickWindow:400,getAngle(a){return E.angleDeg?a*qs:a},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return E.DD.isDragging},isTransforming(){var a,e;return(e=(a=E.Transformer)===null||a===void 0?void 0:a.isTransforming())!==null&&e!==void 0?e:!1},isDragReady(){return!!E.DD.node},releaseCanvasOnDestroy:!0,document:We.document,_injectGlobal(a){typeof We.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),We.Konva=a}},ne=a=>{E[a.prototype.getClassName()]=a};E._injectGlobal(E);const js=`Konva.js unsupported environment.
2
2
 
3
3
  Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined.
4
4
 
@@ -11,8 +11,8 @@ or
11
11
 
12
12
  bash: npm install skia-canvas
13
13
  js: import "konva/skia-backend";
14
- `,Hi=()=>{if(typeof document>"u")throw new Error(zn)};class dt{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new dt(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const e=this.m;return{x:e[0]*t.x+e[2]*t.y+e[4],y:e[1]*t.x+e[3]*t.y+e[5]}}translate(t,e){return this.m[4]+=this.m[0]*t+this.m[2]*e,this.m[5]+=this.m[1]*t+this.m[3]*e,this}scale(t,e){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=e,this.m[3]*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),s=this.m[0]*e+this.m[2]*i,n=this.m[1]*e+this.m[3]*i,r=this.m[0]*-i+this.m[2]*e,o=this.m[1]*-i+this.m[3]*e;return this.m[0]=s,this.m[1]=n,this.m[2]=r,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,e){const i=this.m[0]+this.m[2]*e,s=this.m[1]+this.m[3]*e,n=this.m[2]+this.m[0]*t,r=this.m[3]+this.m[1]*t;return this.m[0]=i,this.m[1]=s,this.m[2]=n,this.m[3]=r,this}multiply(t){const e=this.m[0]*t.m[0]+this.m[2]*t.m[1],i=this.m[1]*t.m[0]+this.m[3]*t.m[1],s=this.m[0]*t.m[2]+this.m[2]*t.m[3],n=this.m[1]*t.m[2]+this.m[3]*t.m[3],r=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],o=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=e,this.m[1]=i,this.m[2]=s,this.m[3]=n,this.m[4]=r,this.m[5]=o,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),e=this.m[3]*t,i=-this.m[1]*t,s=-this.m[2]*t,n=this.m[0]*t,r=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=e,this.m[1]=i,this.m[2]=s,this.m[3]=n,this.m[4]=r,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],e=this.m[1],i=this.m[2],s=this.m[3],n=this.m[4],r=this.m[5],o=t*s-e*i,l={x:n,y:r,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||e!=0){const h=Math.sqrt(t*t+e*e);l.rotation=e>0?Math.acos(t/h):-Math.acos(t/h),l.scaleX=h,l.scaleY=o/h,l.skewX=(t*i+e*s)/o,l.skewY=0}else if(i!=0||s!=0){const h=Math.sqrt(i*i+s*s);l.rotation=Math.PI/2-(s>0?Math.acos(-i/h):-Math.acos(i/h)),l.scaleX=o/h,l.scaleY=h,l.skewX=0,l.skewY=(t*i+e*s)/o}return l.rotation=C._getRotation(l.rotation),l}}const Nn="[object Array]",Fn="[object Number]",Vn="[object String]",Wn="[object Boolean]",Yn=Math.PI/180,Xn=180/Math.PI,ie="#",Un="",$n="0",Kn="Konva warning: ",zi="Konva error: ",jn="rgb(",ti={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},Zn=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let Ae=[],se=null;const qn=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(a){setTimeout(a,16)},C={_isElement(a){return!!(a&&a.nodeType==1)},_isFunction(a){return!!(a&&a.constructor&&a.call&&a.apply)},_isPlainObject(a){return!!a&&a.constructor===Object},_isArray(a){return Object.prototype.toString.call(a)===Nn},_isNumber(a){return Object.prototype.toString.call(a)===Fn&&!isNaN(a)&&isFinite(a)},_isString(a){return Object.prototype.toString.call(a)===Vn},_isBoolean(a){return Object.prototype.toString.call(a)===Wn},isObject(a){return a instanceof Object},isValidSelector(a){if(typeof a!="string")return!1;const t=a[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(a){return a===0||a>0?1:-1},requestAnimFrame(a){Ae.push(a),Ae.length===1&&qn(function(){const t=Ae;Ae=[],t.forEach(function(e){e()})})},createCanvasElement(){Hi();const a=document.createElement("canvas");try{a.style=a.style||{}}catch{}return a},createImageElement(){return Hi(),document.createElement("img")},_isInDocument(a){for(;a=a.parentNode;)if(a==document)return!0;return!1},_urlToImage(a,t){const e=C.createImageElement();e.onload=function(){t(e)},e.src=a},_rgbToHex(a,t,e){return((1<<24)+(a<<16)+(t<<8)+e).toString(16).slice(1)},_hexToRgb(a){a=a.replace(ie,Un);const t=parseInt(a,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let a=(Math.random()*16777215<<0).toString(16);for(;a.length<6;)a=$n+a;return ie+a},isCanvasFarblingActive(){if(se!==null)return se;if(typeof document>"u")return se=!1,!1;const a=this.createCanvasElement();a.width=10,a.height=10;const t=a.getContext("2d",{willReadFrequently:!0});t.clearRect(0,0,10,10),t.fillStyle="#282828",t.fillRect(0,0,10,10);const e=t.getImageData(0,0,10,10).data;let i=!1;for(let s=0;s<100;s++)if(e[s*4]!==40||e[s*4+1]!==40||e[s*4+2]!==40||e[s*4+3]!==255){i=!0;break}return se=i,this.releaseCanvas(a),se},getHitColor(){const a=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(a):a},getHitColorKey(a,t,e){return this.isCanvasFarblingActive()&&(a=Math.round(a/5)*5,t=Math.round(t/5)*5,e=Math.round(e/5)*5),ie+this._rgbToHex(a,t,e)},getSnappedHexColor(a){const t=this._hexToRgb(a);return ie+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(a){let t;return a in ti?(t=ti[a],{r:t[0],g:t[1],b:t[2]}):a[0]===ie?this._hexToRgb(a.substring(1)):a.substr(0,4)===jn?(t=Zn.exec(a.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(a){return a=a||"black",C._namedColorToRBA(a)||C._hex3ColorToRGBA(a)||C._hex4ColorToRGBA(a)||C._hex6ColorToRGBA(a)||C._hex8ColorToRGBA(a)||C._rgbColorToRGBA(a)||C._rgbaColorToRGBA(a)||C._hslColorToRGBA(a)},_namedColorToRBA(a){const t=ti[a.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(a){if(a.indexOf("rgb(")===0){a=a.match(/rgb\(([^)]+)\)/)[1];const t=a.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(a){if(a.indexOf("rgba(")===0){a=a.match(/rgba\(([^)]+)\)/)[1];const t=a.split(/ *, */).map((e,i)=>e.slice(-1)==="%"?i===3?parseInt(e)/100:parseInt(e)/100*255:Number(e));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(a){if(a[0]==="#"&&a.length===9)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:parseInt(a.slice(7,9),16)/255}},_hex6ColorToRGBA(a){if(a[0]==="#"&&a.length===7)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:1}},_hex4ColorToRGBA(a){if(a[0]==="#"&&a.length===5)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:parseInt(a[4]+a[4],16)/255}},_hex3ColorToRGBA(a){if(a[0]==="#"&&a.length===4)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:1}},_hslColorToRGBA(a){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(a)){const[t,...e]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a),i=Number(e[0])/360,s=Number(e[1])/100,n=Number(e[2])/100;let r,o,l;if(s===0)return l=n*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};n<.5?r=n*(1+s):r=n+s-n*s;const h=2*n-r,c=[0,0,0];for(let d=0;d<3;d++)o=i+1/3*-(d-1),o<0&&o++,o>1&&o--,6*o<1?l=h+(r-h)*6*o:2*o<1?l=r:3*o<2?l=h+(r-h)*(2/3-o)*6:l=h,c[d]=l*255;return{r:Math.round(c[0]),g:Math.round(c[1]),b:Math.round(c[2]),a:1}}},haveIntersection(a,t){return!(t.x>a.x+a.width||t.x+t.width<a.x||t.y>a.y+a.height||t.y+t.height<a.y)},cloneObject(a){const t={};for(const e in a)this._isPlainObject(a[e])?t[e]=this.cloneObject(a[e]):this._isArray(a[e])?t[e]=this.cloneArray(a[e]):t[e]=a[e];return t},cloneArray(a){return a.slice(0)},degToRad(a){return a*Yn},radToDeg(a){return a*Xn},_degToRad(a){return C.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),C.degToRad(a)},_radToDeg(a){return C.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),C.radToDeg(a)},_getRotation(a){return E.angleDeg?C.radToDeg(a):a},_capitalize(a){return a.charAt(0).toUpperCase()+a.slice(1)},throw(a){throw new Error(zi+a)},error(a){console.error(zi+a)},warn(a){E.showWarnings&&console.warn(Kn+a)},each(a,t){for(const e in a)t(e,a[e])},_inRange(a,t,e){return t<=a&&a<e},_getProjectionToSegment(a,t,e,i,s,n){let r,o,l;const h=(a-e)*(a-e)+(t-i)*(t-i);if(h==0)r=a,o=t,l=(s-e)*(s-e)+(n-i)*(n-i);else{const c=((s-a)*(e-a)+(n-t)*(i-t))/h;c<0?(r=a,o=t,l=(a-s)*(a-s)+(t-n)*(t-n)):c>1?(r=e,o=i,l=(e-s)*(e-s)+(i-n)*(i-n)):(r=a+c*(e-a),o=t+c*(i-t),l=(r-s)*(r-s)+(o-n)*(o-n))}return[r,o,l]},_getProjectionToLine(a,t,e){const i=C.cloneObject(a);let s=Number.MAX_VALUE;return t.forEach(function(n,r){if(!e&&r===t.length-1)return;const o=t[(r+1)%t.length],l=C._getProjectionToSegment(n.x,n.y,o.x,o.y,a.x,a.y),h=l[0],c=l[1],d=l[2];d<s&&(i.x=h,i.y=c,s=d)}),i},_prepareArrayForTween(a,t,e){const i=[],s=[];if(a.length>t.length){const r=t;t=a,a=r}for(let r=0;r<a.length;r+=2)i.push({x:a[r],y:a[r+1]});for(let r=0;r<t.length;r+=2)s.push({x:t[r],y:t[r+1]});const n=[];return s.forEach(function(r){const o=C._getProjectionToLine(r,i,e);n.push(o.x),n.push(o.y)}),n},_prepareToStringify(a){let t;a.visitedByCircularReferenceRemoval=!0;for(const e in a)if(a.hasOwnProperty(e)&&a[e]&&typeof a[e]=="object"){if(t=Object.getOwnPropertyDescriptor(a,e),a[e].visitedByCircularReferenceRemoval||C._isElement(a[e]))if(t.configurable)delete a[e];else return null;else if(C._prepareToStringify(a[e])===null)if(t.configurable)delete a[e];else return null}return delete a.visitedByCircularReferenceRemoval,a},_assign(a,t){for(const e in t)a[e]=t[e];return a},_getFirstPointerId(a){return a.touches?a.changedTouches[0].identifier:a.pointerId||999},releaseCanvas(...a){E.releaseCanvasOnDestroy&&a.forEach(t=>{t.width=0,t.height=0})},drawRoundedRectPath(a,t,e,i){let s=t<0?t:0,n=e<0?e:0;t=Math.abs(t),e=Math.abs(e);let r=0,o=0,l=0,h=0;typeof i=="number"?r=o=l=h=Math.min(i,t/2,e/2):(r=Math.min(i[0]||0,t/2,e/2),o=Math.min(i[1]||0,t/2,e/2),h=Math.min(i[2]||0,t/2,e/2),l=Math.min(i[3]||0,t/2,e/2)),a.moveTo(s+r,n),a.lineTo(s+t-o,n),a.arc(s+t-o,n+o,o,Math.PI*3/2,0,!1),a.lineTo(s+t,n+e-h),a.arc(s+t-h,n+e-h,h,0,Math.PI/2,!1),a.lineTo(s+l,n+e),a.arc(s+l,n+e-l,l,Math.PI/2,Math.PI,!1),a.lineTo(s,n+r),a.arc(s+r,n+r,r,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(a,t,e,i,s){i=Math.abs(i);for(let n=0;n<e;n++){const r=t[(n-1+e)%e],o=t[n],l=t[(n+1)%e],h={x:o.x-r.x,y:o.y-r.y},c={x:l.x-o.x,y:l.y-o.y},d=Math.hypot(h.x,h.y),u=Math.hypot(c.x,c.y);let p;typeof s=="number"?p=s:p=n<s.length?s[n]:0,p=i*Math.cos(Math.PI/e)*Math.min(1,p/i*2);const y={x:h.x/d,y:h.y/d},T={x:c.x/u,y:c.y/u},S={x:o.x-y.x*p,y:o.y-y.y*p},v={x:o.x+T.x*p,y:o.y+T.y*p};n===0?a.moveTo(S.x,S.y):a.lineTo(S.x,S.y),a.arcTo(o.x,o.y,v.x,v.y,p)}}};function Jn(a){const t=[],e=a.length,i=C;for(let s=0;s<e;s++){let n=a[s];i._isNumber(n)?n=Math.round(n*1e3)/1e3:i._isString(n)||(n=n+""),t.push(n)}return t}const Ni=",",Qn="(",tr=")",er="([",ir="])",sr=";",nr="()",rr="=",Fi=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],ar=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],or=100;let Ee=null;function Vi(){if(Ee!==null)return Ee;try{const t=C.createCanvasElement().getContext("2d");return t?!!t&&"filter"in t:(Ee=!1,!1)}catch{return Ee=!1,!1}}class qe{constructor(t){this.canvas=t,E.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(t){t.fillEnabled()&&this._fill(t)}_fill(t){}strokeShape(t){t.hasStroke()&&this._stroke(t)}_stroke(t){}fillStrokeShape(t){t.attrs.fillAfterStrokeEnabled?(this.strokeShape(t),this.fillShape(t)):(this.fillShape(t),this.strokeShape(t))}getTrace(t,e){let i=this.traceArr,s=i.length,n="",r,o,l,h;for(r=0;r<s;r++)o=i[r],l=o.method,l?(h=o.args,n+=l,t?n+=nr:C._isArray(h[0])?n+=er+h.join(Ni)+ir:(e&&(h=h.map(c=>typeof c=="number"?Math.floor(c):c)),n+=Qn+h.join(Ni)+tr)):(n+=o.property,t||(n+=rr+o.val)),n+=sr;return n}clearTrace(){this.traceArr=[]}_trace(t){let e=this.traceArr,i;e.push(t),i=e.length,i>=or&&e.shift()}reset(){const t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){const e=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,e.getWidth()/e.pixelRatio,e.getHeight()/e.pixelRatio)}_applyLineCap(t){const e=t.attrs.lineCap;e&&this.setAttr("lineCap",e)}_applyOpacity(t){const e=t.getAbsoluteOpacity();e!==1&&this.setAttr("globalAlpha",e)}_applyLineJoin(t){const e=t.attrs.lineJoin;e&&this.setAttr("lineJoin",e)}_applyMiterLimit(t){const e=t.attrs.miterLimit;e!=null&&this.setAttr("miterLimit",e)}setAttr(t,e){this._context[t]=e}arc(t,e,i,s,n,r){this._context.arc(t,e,i,s,n,r)}arcTo(t,e,i,s,n){this._context.arcTo(t,e,i,s,n)}beginPath(){this._context.beginPath()}bezierCurveTo(t,e,i,s,n,r){this._context.bezierCurveTo(t,e,i,s,n,r)}clearRect(t,e,i,s){this._context.clearRect(t,e,i,s)}clip(...t){this._context.clip.apply(this._context,t)}closePath(){this._context.closePath()}createImageData(t,e){const i=arguments;if(i.length===2)return this._context.createImageData(t,e);if(i.length===1)return this._context.createImageData(t)}createLinearGradient(t,e,i,s){return this._context.createLinearGradient(t,e,i,s)}createPattern(t,e){return this._context.createPattern(t,e)}createRadialGradient(t,e,i,s,n,r){return this._context.createRadialGradient(t,e,i,s,n,r)}drawImage(t,e,i,s,n,r,o,l,h){const c=arguments,d=this._context;c.length===3?d.drawImage(t,e,i):c.length===5?d.drawImage(t,e,i,s,n):c.length===9&&d.drawImage(t,e,i,s,n,r,o,l,h)}ellipse(t,e,i,s,n,r,o,l){this._context.ellipse(t,e,i,s,n,r,o,l)}isPointInPath(t,e,i,s){return i?this._context.isPointInPath(i,t,e,s):this._context.isPointInPath(t,e,s)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,e,i,s){this._context.fillRect(t,e,i,s)}strokeRect(t,e,i,s){this._context.strokeRect(t,e,i,s)}fillText(t,e,i,s){s?this._context.fillText(t,e,i,s):this._context.fillText(t,e,i)}measureText(t){return this._context.measureText(t)}getImageData(t,e,i,s){return this._context.getImageData(t,e,i,s)}lineTo(t,e){this._context.lineTo(t,e)}moveTo(t,e){this._context.moveTo(t,e)}rect(t,e,i,s){this._context.rect(t,e,i,s)}roundRect(t,e,i,s,n){this._context.roundRect(t,e,i,s,n)}putImageData(t,e,i){this._context.putImageData(t,e,i)}quadraticCurveTo(t,e,i,s){this._context.quadraticCurveTo(t,e,i,s)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,e){this._context.scale(t,e)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,e,i,s,n,r){this._context.setTransform(t,e,i,s,n,r)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,e,i,s){this._context.strokeText(t,e,i,s)}transform(t,e,i,s,n,r){this._context.transform(t,e,i,s,n,r)}translate(t,e){this._context.translate(t,e)}_enableTrace(){let t=this,e=Fi.length,i=this.setAttr,s,n;const r=function(o){let l=t[o],h;t[o]=function(){return n=Jn(Array.prototype.slice.call(arguments,0)),h=l.apply(t,arguments),t._trace({method:o,args:n}),h}};for(s=0;s<e;s++)r(Fi[s]);t.setAttr=function(){i.apply(t,arguments);const o=arguments[0];let l=arguments[1];(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")&&(l=l/this.canvas.getPixelRatio()),t._trace({property:o,val:l})}}_applyGlobalCompositeOperation(t){const e=t.attrs.globalCompositeOperation;!e||e==="source-over"||this.setAttr("globalCompositeOperation",e)}}ar.forEach(function(a){Object.defineProperty(qe.prototype,a,{get(){return this._context[a]},set(t){this._context[a]=t}})});class lr extends qe{constructor(t,{willReadFrequently:e=!1}={}){super(t),this._context=t._canvas.getContext("2d",{willReadFrequently:e})}_fillColor(t){const e=t.fill();this.setAttr("fillStyle",e),t._fillFunc(this)}_fillPattern(t){this.setAttr("fillStyle",t._getFillPattern()),t._fillFunc(this)}_fillLinearGradient(t){const e=t._getLinearGradient();e&&(this.setAttr("fillStyle",e),t._fillFunc(this))}_fillRadialGradient(t){const e=t._getRadialGradient();e&&(this.setAttr("fillStyle",e),t._fillFunc(this))}_fill(t){const e=t.fill(),i=t.getFillPriority();if(e&&i==="color"){this._fillColor(t);return}const s=t.getFillPatternImage();if(s&&i==="pattern"){this._fillPattern(t);return}const n=t.getFillLinearGradientColorStops();if(n&&i==="linear-gradient"){this._fillLinearGradient(t);return}const r=t.getFillRadialGradientColorStops();if(r&&i==="radial-gradient"){this._fillRadialGradient(t);return}e?this._fillColor(t):s?this._fillPattern(t):n?this._fillLinearGradient(t):r&&this._fillRadialGradient(t)}_strokeLinearGradient(t){const e=t.getStrokeLinearGradientStartPoint(),i=t.getStrokeLinearGradientEndPoint(),s=t.getStrokeLinearGradientColorStops(),n=this.createLinearGradient(e.x,e.y,i.x,i.y);if(s){for(let r=0;r<s.length;r+=2)n.addColorStop(s[r],s[r+1]);this.setAttr("strokeStyle",n)}}_stroke(t){const e=t.dash(),i=t.getStrokeScaleEnabled();if(t.hasStroke()){if(!i){this.save();const n=this.getCanvas().getPixelRatio();this.setTransform(n,0,0,n,0,0)}this._applyLineCap(t),e&&t.dashEnabled()&&(this.setLineDash(e),this.setAttr("lineDashOffset",t.dashOffset())),this.setAttr("lineWidth",t.strokeWidth()),t.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),t.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(t):this.setAttr("strokeStyle",t.stroke()),t._strokeFunc(this),i||this.restore()}}_applyShadow(t){var e,i,s;const n=(e=t.getShadowRGBA())!==null&&e!==void 0?e:"black",r=(i=t.getShadowBlur())!==null&&i!==void 0?i:5,o=(s=t.getShadowOffset())!==null&&s!==void 0?s:{x:0,y:0},l=t.getAbsoluteScale(),h=this.canvas.getPixelRatio(),c=l.x*h,d=l.y*h;this.setAttr("shadowColor",n),this.setAttr("shadowBlur",r*Math.min(Math.abs(c),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*c),this.setAttr("shadowOffsetY",o.y*d)}}class hr extends qe{constructor(t){super(t),this._context=t._canvas.getContext("2d",{willReadFrequently:!0})}_fill(t){this.save(),this.setAttr("fillStyle",t.colorKey),t._fillFuncHit(this),this.restore()}strokeShape(t){t.hasHitStroke()&&this._stroke(t)}_stroke(t){if(t.hasHitStroke()){const e=t.getStrokeScaleEnabled();if(!e){this.save();const n=this.getCanvas().getPixelRatio();this.setTransform(n,0,0,n,0,0)}this._applyLineCap(t);const i=t.hitStrokeWidth(),s=i==="auto"?t.strokeWidth():i;this.setAttr("lineWidth",s),this.setAttr("strokeStyle",t.colorKey),t._strokeFuncHit(this),e||this.restore()}}}let Ie;function cr(){if(Ie)return Ie;const a=C.createCanvasElement(),t=a.getContext("2d");return Ie=function(){const e=E._global.devicePixelRatio||1,i=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1;return e/i}(),C.releaseCanvas(a),Ie}class Ii{constructor(t){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(t||{}).pixelRatio||E.pixelRatio||cr();this.pixelRatio=i,this._canvas=C.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(t){const e=this.pixelRatio;this.pixelRatio=t,this.setSize(this.getWidth()/e,this.getHeight()/e)}setWidth(t){this.width=this._canvas.width=t*this.pixelRatio,this._canvas.style.width=t+"px";const e=this.pixelRatio;this.getContext()._context.scale(e,e)}setHeight(t){this.height=this._canvas.height=t*this.pixelRatio,this._canvas.style.height=t+"px";const e=this.pixelRatio;this.getContext()._context.scale(e,e)}getWidth(){return this.width}getHeight(){return this.height}setSize(t,e){this.setWidth(t||0),this.setHeight(e||0)}toDataURL(t,e){try{return this._canvas.toDataURL(t,e)}catch{try{return this._canvas.toDataURL()}catch(s){return C.error("Unable to get data URL. "+s.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class Rt extends Ii{constructor(t={width:0,height:0,willReadFrequently:!1}){super(t),this.context=new lr(this,{willReadFrequently:t.willReadFrequently}),this.setSize(t.width,t.height)}}class Mi extends Ii{constructor(t={width:0,height:0}){super(t),this.hitCanvas=!0,this.context=new hr(this),this.setSize(t.width,t.height)}}const $={get isDragging(){let a=!1;return $._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(a=!0)}),a},justDragged:!1,get node(){let a;return $._dragElements.forEach(t=>{a=t.node}),a},_dragElements:new Map,_drag(a){const t=[];$._dragElements.forEach((e,i)=>{const{node:s}=e,n=s.getStage();n.setPointersPositions(a),e.pointerId===void 0&&(e.pointerId=C._getFirstPointerId(a));const r=n._changedPointerPositions.find(o=>o.id===e.pointerId);if(r){if(e.dragStatus!=="dragging"){const o=s.dragDistance();if(Math.max(Math.abs(r.x-e.startPointerPos.x),Math.abs(r.y-e.startPointerPos.y))<o||(s.startDrag({evt:a}),!s.isDragging()))return}s._setDragPosition(a,e),t.push(s)}}),t.forEach(e=>{e.fire("dragmove",{type:"dragmove",target:e,evt:a},!0)})},_endDragBefore(a){const t=[];$._dragElements.forEach(e=>{const{node:i}=e,s=i.getStage();if(a&&s.setPointersPositions(a),!s._changedPointerPositions.find(o=>o.id===e.pointerId))return;(e.dragStatus==="dragging"||e.dragStatus==="stopped")&&($.justDragged=!0,E._mouseListenClick=!1,E._touchListenClick=!1,E._pointerListenClick=!1,e.dragStatus="stopped");const r=e.node.getLayer()||e.node instanceof E.Stage&&e.node;r&&t.indexOf(r)===-1&&t.push(r)}),t.forEach(e=>{e.draw()})},_endDragAfter(a){$._dragElements.forEach((t,e)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:a},!0),t.dragStatus!=="dragging"&&$._dragElements.delete(e)})}};E.isBrowser&&(window.addEventListener("mouseup",$._endDragBefore,!0),window.addEventListener("touchend",$._endDragBefore,!0),window.addEventListener("touchcancel",$._endDragBefore,!0),window.addEventListener("mousemove",$._drag),window.addEventListener("touchmove",$._drag),window.addEventListener("mouseup",$._endDragAfter,!1),window.addEventListener("touchend",$._endDragAfter,!1),window.addEventListener("touchcancel",$._endDragAfter,!1));function Ot(a){return C._isString(a)?'"'+a+'"':Object.prototype.toString.call(a)==="[object Number]"||C._isBoolean(a)?a:Object.prototype.toString.call(a)}function Bs(a){return a>255?255:a<0?0:Math.round(a)}function x(){if(E.isUnminified)return function(a,t){return C._isNumber(a)||C.warn(Ot(a)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),a}}function Je(a){if(E.isUnminified)return function(t,e){let i=C._isNumber(t),s=C._isArray(t)&&t.length==a;return!i&&!s&&C.warn(Ot(t)+' is a not valid value for "'+e+'" attribute. The value should be a number or Array<number>('+a+")"),t}}function Li(){if(E.isUnminified)return function(a,t){return C._isNumber(a)||a==="auto"||C.warn(Ot(a)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),a}}function Wt(){if(E.isUnminified)return function(a,t){return C._isString(a)||C.warn(Ot(a)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),a}}function Hs(){if(E.isUnminified)return function(a,t){const e=C._isString(a),i=Object.prototype.toString.call(a)==="[object CanvasGradient]"||a&&a.addColorStop;return e||i||C.warn(Ot(a)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),a}}function dr(){if(E.isUnminified)return function(a,t){const e=Int8Array?Object.getPrototypeOf(Int8Array):null;return e&&a instanceof e||(C._isArray(a)?a.forEach(function(i){C._isNumber(i)||C.warn('"'+t+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):C.warn(Ot(a)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),a}}function pt(){if(E.isUnminified)return function(a,t){return a===!0||a===!1||C.warn(Ot(a)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),a}}function ur(a){if(E.isUnminified)return function(t,e){return t==null||C.isObject(t)||C.warn(Ot(t)+' is a not valid value for "'+e+'" attribute. The value should be an object with properties '+a),t}}const ne="get",re="set",m={addGetterSetter(a,t,e,i,s){m.addGetter(a,t,e),m.addSetter(a,t,i,s),m.addOverloadedGetterSetter(a,t)},addGetter(a,t,e){const i=ne+C._capitalize(t);a.prototype[i]=a.prototype[i]||function(){const s=this.attrs[t];return s===void 0?e:s}},addSetter(a,t,e,i){const s=re+C._capitalize(t);a.prototype[s]||m.overWriteSetter(a,t,e,i)},overWriteSetter(a,t,e,i){const s=re+C._capitalize(t);a.prototype[s]=function(n){return e&&n!==void 0&&n!==null&&(n=e.call(this,n,t)),this._setAttr(t,n),i&&i.call(this),this}},addComponentsGetterSetter(a,t,e,i,s){const n=e.length,r=C._capitalize,o=ne+r(t),l=re+r(t);a.prototype[o]=function(){const c={};for(let d=0;d<n;d++){const u=e[d];c[u]=this.getAttr(t+r(u))}return c};const h=ur(e);a.prototype[l]=function(c){const d=this.attrs[t];i&&(c=i.call(this,c,t)),h&&h.call(this,c,t);for(const u in c)c.hasOwnProperty(u)&&this._setAttr(t+r(u),c[u]);return c||e.forEach(u=>{this._setAttr(t+r(u),void 0)}),this._fireChangeEvent(t,d,c),s&&s.call(this),this},m.addOverloadedGetterSetter(a,t)},addOverloadedGetterSetter(a,t){const e=C._capitalize(t),i=re+e,s=ne+e;a.prototype[t]=function(){return arguments.length?(this[i](arguments[0]),this):this[s]()}},addDeprecatedGetterSetter(a,t,e,i){C.error("Adding deprecated "+t);const s=ne+C._capitalize(t),n=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";a.prototype[s]=function(){C.error(n);const r=this.attrs[t];return r===void 0?e:r},m.addSetter(a,t,i,function(){C.error(n)}),m.addOverloadedGetterSetter(a,t)},backCompat(a,t){C.each(t,function(e,i){const s=a.prototype[i],n=ne+C._capitalize(e),r=re+C._capitalize(e);function o(){s.apply(this,arguments),C.error('"'+e+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}a.prototype[e]=o,a.prototype[n]=o,a.prototype[r]=o})},afterSetFilter(){this._filterUpToDate=!1}};function gr(a){const t=/(\w+)\(([^)]+)\)/g;let e;for(;(e=t.exec(a))!==null;){const[,i,s]=e;switch(i){case"blur":{const n=parseFloat(s.replace("px",""));return function(r){this.blurRadius(n*.5);const o=E.Filters;o&&o.Blur&&o.Blur.call(this,r)}}case"brightness":{const n=s.includes("%")?parseFloat(s)/100:parseFloat(s);return function(r){this.brightness(n);const o=E.Filters;o&&o.Brightness&&o.Brightness.call(this,r)}}case"contrast":{const n=parseFloat(s);return function(r){const o=100*(Math.sqrt(n)-1);this.contrast(o);const l=E.Filters;l&&l.Contrast&&l.Contrast.call(this,r)}}case"grayscale":return function(n){const r=E.Filters;r&&r.Grayscale&&r.Grayscale.call(this,n)};case"sepia":return function(n){const r=E.Filters;r&&r.Sepia&&r.Sepia.call(this,n)};case"invert":return function(n){const r=E.Filters;r&&r.Invert&&r.Invert.call(this,n)};default:C.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const We="absoluteOpacity",Wi="allEventListeners",wt="absoluteTransform",Yi="absoluteScale",zt="canvas",fr="Change",pr="children",mr="konva",gi="listening",yr="mouseenter",Cr="mouseleave",Sr="pointerenter",Tr="pointerleave",vr="touchenter",br="touchleave",Xi="set",Ui="Shape",Ye=" ",$i="stage",Mt="transform",kr="Stage",fi="visible",wr=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Ye);let _r=1;class P{constructor(t){this._id=_r++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===Mt||t===wt)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,e){let i=this._cache.get(t);return(i===void 0||(t===Mt||t===wt)&&i.dirty===!0)&&(i=e.call(this),this._cache.set(t,i)),i}_calculate(t,e,i){if(!this._attachedDepsListeners.get(t)){const s=e.map(n=>n+"Change.konva").join(Ye);this.on(s,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,i)}_getCanvasCache(){return this._cache.get(zt)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===wt&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(zt)){const{scene:t,filter:e,hit:i}=this._cache.get(zt);C.releaseCanvas(t._canvas,e._canvas,i._canvas),this._cache.delete(zt)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const e=t||{};let i={};(e.x===void 0||e.y===void 0||e.width===void 0||e.height===void 0)&&(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let s=Math.ceil(e.width||i.width),n=Math.ceil(e.height||i.height),r=e.pixelRatio,o=e.x===void 0?Math.floor(i.x):e.x,l=e.y===void 0?Math.floor(i.y):e.y,h=e.offset||0,c=e.drawBorder||!1,d=e.hitCanvasPixelRatio||1;if(!s||!n){C.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const u=Math.abs(Math.round(i.x)-o)>.5?1:0,p=Math.abs(Math.round(i.y)-l)>.5?1:0;s+=h*2+u,n+=h*2+p,o-=h,l-=h;const f=new Rt({pixelRatio:r,width:s,height:n}),y=new Rt({pixelRatio:r,width:0,height:0,willReadFrequently:!0}),T=new Mi({pixelRatio:d,width:s,height:n}),S=f.getContext(),v=T.getContext(),b=new Rt({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(l),pixelRatio:f.pixelRatio}),k=b.getContext();return T.isCache=!0,f.isCache=!0,this._cache.delete(zt),this._filterUpToDate=!1,e.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),S.save(),v.save(),k.save(),S.translate(-o,-l),v.translate(-o,-l),k.translate(-o,-l),b.x=o,b.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(We),this._clearSelfAndDescendantCache(Yi),this.drawScene(f,this,b),this.drawHit(T,this),this._isUnderCache=!1,S.restore(),v.restore(),c&&(S.save(),S.beginPath(),S.rect(0,0,s,n),S.closePath(),S.setAttr("strokeStyle","red"),S.setAttr("lineWidth",5),S.stroke(),S.restore()),C.releaseCanvas(b._canvas),this._cache.set(zt,{scene:f,filter:y,hit:T,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(zt)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,e){const i=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let s=1/0,n=1/0,r=-1/0,o=-1/0;const l=this.getAbsoluteTransform(e);return i.forEach(function(h){const c=l.point(h);s===void 0&&(s=r=c.x,n=o=c.y),s=Math.min(s,c.x),n=Math.min(n,c.y),r=Math.max(r,c.x),o=Math.max(o,c.y)}),{x:s,y:n,width:r-s,height:o-n}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const e=this._getCanvasCache();t.translate(e.x,e.y);const i=this._getCachedSceneCanvas(),s=i.pixelRatio;t.drawImage(i._canvas,0,0,i.width/s,i.height/s),t.restore()}_drawCachedHitCanvas(t){const e=this._getCanvasCache(),i=e.hit;t.save(),t.translate(e.x,e.y),t.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),e=this._getCanvasCache(),i=e.scene,s=e.filter,n=s.getContext(),r,o,l,h;if(!t||t.length===0)return i;if(this._filterUpToDate)return s;let c=!0;for(let u=0;u<t.length;u++)if(typeof t[u]=="string"&&Vi(),typeof t[u]!="string"||!Vi()){c=!1;break}const d=i.pixelRatio;if(s.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),c){const u=t.join(" ");return n.save(),n.setAttr("filter",u),n.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),n.restore(),this._filterUpToDate=!0,s}try{for(r=t.length,n.clear(),n.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),o=n.getImageData(0,0,s.getWidth(),s.getHeight()),l=0;l<r;l++)h=t[l],typeof h=="string"&&(h=gr(h)),h.call(this,o),n.putImageData(o,0,0)}catch(u){C.error("Unable to apply filter. "+u.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,s}on(t,e){if(this._cache&&this._cache.delete(Wi),arguments.length===3)return this._delegate.apply(this,arguments);const i=t.split(Ye);for(let s=0;s<i.length;s++){const r=i[s].split("."),o=r[0],l=r[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:e})}return this}off(t,e){let i=(t||"").split(Ye),s=i.length,n,r,o,l,h,c;if(this._cache&&this._cache.delete(Wi),!t)for(r in this.eventListeners)this._off(r);for(n=0;n<s;n++)if(o=i[n],l=o.split("."),h=l[0],c=l[1],h)this.eventListeners[h]&&this._off(h,c,e);else for(r in this.eventListeners)this._off(r,c,e);return this}dispatchEvent(t){const e={target:this,type:t.type,evt:t};return this.fire(t.type,e),this}addEventListener(t,e){return this.on(t,function(i){e.call(this,i.evt)}),this}removeEventListener(t){return this.off(t),this}_delegate(t,e,i){const s=this;this.on(t,function(n){const r=n.target.findAncestors(e,!0,s);for(let o=0;o<r.length;o++)n=C.cloneObject(n),n.currentTarget=r[o],i.call(r[o],n)})}remove(){return this.isDragging()&&this.stopDrag(),$._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(wt),this._clearSelfAndDescendantCache(We),this._clearSelfAndDescendantCache(Yi),this._clearSelfAndDescendantCache($i),this._clearSelfAndDescendantCache(fi),this._clearSelfAndDescendantCache(gi)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const e="get"+C._capitalize(t);return C._isFunction(this[e])?this[e]():this.attrs[t]}getAncestors(){let t=this.getParent(),e=[];for(;t;)e.push(t),t=t.getParent();return e}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let e,i;if(!t)return this;for(e in t)e!==pr&&(i=Xi+C._capitalize(e),C._isFunction(this[i])?this[i](t[e]):this._setAttr(e,t[e]))}),this}isListening(){return this._getCache(gi,this._isListening)}_isListening(t){if(!this.listening())return!1;const i=this.getParent();return i&&i!==t&&this!==t?i._isListening(t):!0}isVisible(){return this._getCache(fi,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const i=this.getParent();return i&&i!==t&&this!==t?i._isVisible(t):!0}shouldDrawHit(t,e=!1){if(t)return this._isVisible(t)&&this._isListening(t);const i=this.getLayer();let s=!1;$._dragElements.forEach(r=>{r.dragStatus==="dragging"&&(r.node.nodeType==="Stage"||r.node.getLayer()===i)&&(s=!0)});const n=!e&&!E.hitOnDragEnabled&&(s||E.isTransforming());return this.isListening()&&this.isVisible()&&!n}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),e=this,i=0,s,n,r,o;function l(c){for(s=[],n=c.length,r=0;r<n;r++)o=c[r],i++,o.nodeType!==Ui&&(s=s.concat(o.getChildren().slice())),o._id===e._id&&(r=n);s.length>0&&s[0].getDepth()<=t&&l(s)}const h=this.getStage();return e.nodeType!==kr&&h&&l(h.getChildren()),i}getDepth(){let t=0,e=this.parent;for(;e;)t++,e=e.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(Mt),this._clearSelfAndDescendantCache(wt)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const e=t.getPointerPosition();if(!e)return null;const i=this.getAbsoluteTransform().copy();return i.invert(),i.point(e)}getAbsolutePosition(t){let e=!1,i=this.parent;for(;i;){if(i.isCached()){e=!0;break}i=i.parent}e&&!t&&(t=!0);const s=this.getAbsoluteTransform(t).getMatrix(),n=new dt,r=this.offset();return n.m=s.slice(),n.translate(r.x,r.y),n.getTranslation()}setAbsolutePosition(t){const{x:e,y:i,...s}=this._clearTransform();this.attrs.x=e,this.attrs.y=i,this._clearCache(Mt);const n=this._getAbsoluteTransform().copy();return n.invert(),n.translate(t.x,t.y),t={x:this.attrs.x+n.getTranslation().x,y:this.attrs.y+n.getTranslation().y},this._setTransform(s),this.setPosition({x:t.x,y:t.y}),this._clearCache(Mt),this._clearSelfAndDescendantCache(wt),this}_setTransform(t){let e;for(e in t)this.attrs[e]=t[e]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let e=t.x,i=t.y,s=this.x(),n=this.y();return e!==void 0&&(s+=e),i!==void 0&&(n+=i),this.setPosition({x:s,y:n}),this}_eachAncestorReverse(t,e){let i=[],s=this.getParent(),n,r;if(!(e&&e._id===this._id)){for(i.unshift(this);s&&(!e||s._id!==e._id);)i.unshift(s),s=s.parent;for(n=i.length,r=0;r<n;r++)t(i[r])}}rotate(t){return this.rotation(this.rotation()+t),this}moveToTop(){if(!this.parent)return C.warn("Node has no parent. moveToTop function is ignored."),!1;const t=this.index,e=this.parent.getChildren().length;return t<e-1?(this.parent.children.splice(t,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return C.warn("Node has no parent. moveUp function is ignored."),!1;const t=this.index,e=this.parent.getChildren().length;return t<e-1?(this.parent.children.splice(t,1),this.parent.children.splice(t+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return C.warn("Node has no parent. moveDown function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return C.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return C.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&C.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(We,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const e=this.getParent();return e&&!e._isUnderCache&&(t*=e.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),e,i,s,n,r;const o={attrs:{},className:this.getClassName()};for(e in t)i=t[e],r=C.isObject(i)&&!C._isPlainObject(i)&&!C._isArray(i),!r&&(s=typeof this[e]=="function"&&this[e],delete t[e],n=s?s.call(this):null,t[e]=i,n!==i&&(o.attrs[e]=i));return C._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,e,i){const s=[];e&&this._isMatch(t)&&s.push(this);let n=this.parent;for(;n;){if(n===i)return s;n._isMatch(t)&&s.push(n),n=n.parent}return s}isAncestorOf(t){return!1}findAncestor(t,e,i){return this.findAncestors(t,e,i)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let e=t.replace(/ /g,"").split(","),i=e.length,s,n;for(s=0;s<i;s++)if(n=e[s],C.isValidSelector(n)||(C.warn('Selector "'+n+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),C.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),C.warn("Konva is awesome, right?")),n.charAt(0)==="#"){if(this.id()===n.slice(1))return!0}else if(n.charAt(0)==="."){if(this.hasName(n.slice(1)))return!0}else if(this.className===n||this.nodeType===n)return!0;return!1}getLayer(){const t=this.getParent();return t?t.getLayer():null}getStage(){return this._getCache($i,this._getStage)}_getStage(){const t=this.getParent();return t?t.getStage():null}fire(t,e={},i){return e.target=e.target||this,i?this._fireAndBubble(t,e):this._fire(t,e),this}getAbsoluteTransform(t){return t?this._getAbsoluteTransform(t):this._getCache(wt,this._getAbsoluteTransform)}_getAbsoluteTransform(t){let e;if(t)return e=new dt,this._eachAncestorReverse(function(i){const s=i.transformsEnabled();s==="all"?e.multiply(i.getTransform()):s==="position"&&e.translate(i.x()-i.offsetX(),i.y()-i.offsetY())},t),e;{e=this._cache.get(wt)||new dt,this.parent?this.parent.getAbsoluteTransform().copyInto(e):e.reset();const i=this.transformsEnabled();if(i==="all")e.multiply(this.getTransform());else if(i==="position"){const s=this.attrs.x||0,n=this.attrs.y||0,r=this.attrs.offsetX||0,o=this.attrs.offsetY||0;e.translate(s-r,n-o)}return e.dirty=!1,e}}getAbsoluteScale(t){let e=this;for(;e;)e._isUnderCache&&(t=e),e=e.getParent();const s=this.getAbsoluteTransform(t).decompose();return{x:s.scaleX,y:s.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(Mt,this._getTransform)}_getTransform(){var t,e;const i=this._cache.get(Mt)||new dt;i.reset();const s=this.x(),n=this.y(),r=E.getAngle(this.rotation()),o=(t=this.attrs.scaleX)!==null&&t!==void 0?t:1,l=(e=this.attrs.scaleY)!==null&&e!==void 0?e:1,h=this.attrs.skewX||0,c=this.attrs.skewY||0,d=this.attrs.offsetX||0,u=this.attrs.offsetY||0;return(s!==0||n!==0)&&i.translate(s,n),r!==0&&i.rotate(r),(h!==0||c!==0)&&i.skew(h,c),(o!==1||l!==1)&&i.scale(o,l),(d!==0||u!==0)&&i.translate(-1*d,-1*u),i.dirty=!1,i}clone(t){let e=C.cloneObject(this.attrs),i,s,n,r,o;for(i in t)e[i]=t[i];const l=new this.constructor(e);for(i in this.eventListeners)for(s=this.eventListeners[i],n=s.length,r=0;r<n;r++)o=s[r],o.name.indexOf(mr)<0&&(l.eventListeners[i]||(l.eventListeners[i]=[]),l.eventListeners[i].push(o));return l}_toKonvaCanvas(t){t=t||{};const e=this.getClientRect(),i=this.getStage(),s=t.x!==void 0?t.x:Math.floor(e.x),n=t.y!==void 0?t.y:Math.floor(e.y),r=t.pixelRatio||1,o=new Rt({width:t.width||Math.ceil(e.width)||(i?i.width():0),height:t.height||Math.ceil(e.height)||(i?i.height():0),pixelRatio:r}),l=o.getContext(),h=new Rt({width:o.width/o.pixelRatio+Math.abs(s),height:o.height/o.pixelRatio+Math.abs(n),pixelRatio:o.pixelRatio});return t.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(s||n)&&l.translate(-1*s,-1*n),this.drawScene(o,void 0,h),l.restore(),o}toCanvas(t){return this._toKonvaCanvas(t)._canvas}toDataURL(t){t=t||{};const e=t.mimeType||null,i=t.quality||null,s=this._toKonvaCanvas(t).toDataURL(e,i);return t.callback&&t.callback(s),s}toImage(t){return new Promise((e,i)=>{try{const s=t==null?void 0:t.callback;s&&delete t.callback,C._urlToImage(this.toDataURL(t),function(n){e(n),s==null||s(n)})}catch(s){i(s)}})}toBlob(t){return new Promise((e,i)=>{try{const s=t==null?void 0:t.callback;s&&delete t.callback,this.toCanvas(t).toBlob(n=>{e(n),s==null||s(n)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(s){i(s)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():E.dragDistance}_off(t,e,i){let s=this.eventListeners[t],n,r,o;for(n=0;n<s.length;n++)if(r=s[n].name,o=s[n].handler,(r!=="konva"||e==="konva")&&(!e||r===e)&&(!i||i===o)){if(s.splice(n,1),s.length===0){delete this.eventListeners[t];break}n--}}_fireChangeEvent(t,e,i){this._fire(t+fr,{oldVal:e,newVal:i})}addName(t){if(!this.hasName(t)){const e=this.name(),i=e?e+" "+t:t;this.name(i)}return this}hasName(t){if(!t)return!1;const e=this.name();return e?(e||"").split(/\s/g).indexOf(t)!==-1:!1}removeName(t){const e=(this.name()||"").split(/\s/g),i=e.indexOf(t);return i!==-1&&(e.splice(i,1),this.name(e.join(" "))),this}setAttr(t,e){const i=this[Xi+C._capitalize(t)];return C._isFunction(i)?i.call(this,e):this._setAttr(t,e),this}_requestDraw(){if(E.autoDrawEnabled){const t=this.getLayer()||this.getStage();t==null||t.batchDraw()}}_setAttr(t,e){const i=this.attrs[t];i===e&&!C.isObject(e)||(e==null?delete this.attrs[t]:this.attrs[t]=e,this._shouldFireChangeEvents&&this._fireChangeEvent(t,i,e),this._requestDraw())}_setComponentAttr(t,e,i){let s;i!==void 0&&(s=this.attrs[t],s||(this.attrs[t]=this.getAttr(t)),this.attrs[t][e]=i,this._fireChangeEvent(t,s,i))}_fireAndBubble(t,e,i){e&&this.nodeType===Ui&&(e.target=this);const s=[yr,Cr,Sr,Tr,vr,br];if(!(s.indexOf(t)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(t,e);const r=s.indexOf(t)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(e&&!e.cancelBubble||!e)&&this.parent&&this.parent.isListening()&&!r&&(i&&i.parent?this._fireAndBubble.call(this.parent,t,e,i):this._fireAndBubble.call(this.parent,t,e))}}_getProtoListeners(t){var e,i;const{nodeType:s}=this,n=P.protoListenerMap.get(s)||{};let r=n==null?void 0:n[t];if(r===void 0){r=[];let o=Object.getPrototypeOf(this);for(;o;){const l=(i=(e=o.eventListeners)===null||e===void 0?void 0:e[t])!==null&&i!==void 0?i:[];r.push(...l),o=Object.getPrototypeOf(o)}n[t]=r,P.protoListenerMap.set(s,n)}return r}_fire(t,e){e=e||{},e.currentTarget=this,e.type=t;const i=this._getProtoListeners(t);if(i)for(let n=0;n<i.length;n++)i[n].handler.call(this,e);const s=this.eventListeners[t];if(s)for(let n=0;n<s.length;n++)s[n].handler.call(this,e)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(t){const e=t?t.pointerId:void 0,i=this.getStage(),s=this.getAbsolutePosition();if(!i)return;const n=i._getPointerById(e)||i._changedPointerPositions[0]||s;$._dragElements.set(this._id,{node:this,startPointerPos:n,offset:{x:n.x-s.x,y:n.y-s.y},dragStatus:"ready",pointerId:e})}startDrag(t,e=!0){$._dragElements.has(this._id)||this._createDragElement(t);const i=$._dragElements.get(this._id);i.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:t&&t.evt},e)}_setDragPosition(t,e){const i=this.getStage()._getPointerById(e.pointerId);if(!i)return;let s={x:i.x-e.offset.x,y:i.y-e.offset.y};const n=this.dragBoundFunc();if(n!==void 0){const r=n.call(this,s,t);r?s=r:C.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==s.x||this._lastPos.y!==s.y)&&(this.setAbsolutePosition(s),this._requestDraw()),this._lastPos=s}stopDrag(t){const e=$._dragElements.get(this._id);e&&(e.dragStatus="stopped"),$._endDragBefore(t),$._endDragAfter(t)}setDraggable(t){this._setAttr("draggable",t),this._dragChange()}isDragging(){const t=$._dragElements.get(this._id);return t?t.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(t){if(!(!(t.evt.button!==void 0)||E.dragButtons.indexOf(t.evt.button)>=0)||this.isDragging())return;let s=!1;$._dragElements.forEach(n=>{this.isAncestorOf(n.node)&&(s=!0)}),s||this._createDragElement(t)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const e=$._dragElements.get(this._id),i=e&&e.dragStatus==="dragging",s=e&&e.dragStatus==="ready";i?this.stopDrag():s&&$._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const e=this.getStage();if(!e)return!1;const i={x:-t.x,y:-t.y,width:e.width()+2*t.x,height:e.height()+2*t.y};return C.haveIntersection(i,this.getClientRect())}static create(t,e){return C._isString(t)&&(t=JSON.parse(t)),this._createNode(t,e)}static _createNode(t,e){let i=P.prototype.getClassName.call(t),s=t.children,n,r,o;e&&(t.attrs.container=e),E[i]||(C.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=E[i];if(n=new l(t.attrs),s)for(r=s.length,o=0;o<r;o++)n.add(P._createNode(s[o]));return n}}P.protoListenerMap=new Map;P.prototype.nodeType="Node";P.prototype._attrsAffectingSize=[];P.prototype.eventListeners={};P.prototype.on.call(P.prototype,wr,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(Mt),this._clearSelfAndDescendantCache(wt)});P.prototype.on.call(P.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(fi)});P.prototype.on.call(P.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(gi)});P.prototype.on.call(P.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(We)});const J=m.addGetterSetter;J(P,"zIndex");J(P,"absolutePosition");J(P,"position");J(P,"x",0,x());J(P,"y",0,x());J(P,"globalCompositeOperation","source-over",Wt());J(P,"opacity",1,x());J(P,"name","",Wt());J(P,"id","",Wt());J(P,"rotation",0,x());m.addComponentsGetterSetter(P,"scale",["x","y"]);J(P,"scaleX",1,x());J(P,"scaleY",1,x());m.addComponentsGetterSetter(P,"skew",["x","y"]);J(P,"skewX",0,x());J(P,"skewY",0,x());m.addComponentsGetterSetter(P,"offset",["x","y"]);J(P,"offsetX",0,x());J(P,"offsetY",0,x());J(P,"dragDistance",void 0,x());J(P,"width",0,x());J(P,"height",0,x());J(P,"listening",!0,pt());J(P,"preventDefault",!0,pt());J(P,"filters",void 0,function(a){return this._filterUpToDate=!1,a});J(P,"visible",!0,pt());J(P,"transformsEnabled","all",Wt());J(P,"size");J(P,"dragBoundFunc");J(P,"draggable",!1,pt());m.backCompat(P,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class ut extends P{constructor(){super(...arguments),this.children=[]}getChildren(t){const e=this.children||[];return t?e.filter(t):e}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this._requestDraw(),this}add(...t){if(t.length===0)return this;if(t.length>1){for(let i=0;i<t.length;i++)this.add(t[i]);return this}const e=t[0];return e.getParent()?(e.moveTo(this),this):(this._validateAdd(e),e.index=this.getChildren().length,e.parent=this,e._clearCaches(),this.getChildren().push(e),this._fire("add",{child:e}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(t){return this._generalFind(t,!1)}findOne(t){const e=this._generalFind(t,!0);return e.length>0?e[0]:void 0}_generalFind(t,e){const i=[];return this._descendants(s=>{const n=s._isMatch(t);return n&&i.push(s),!!(n&&e)}),i}_descendants(t){let e=!1;const i=this.getChildren();for(const s of i){if(e=t(s),e)return!0;if(s.hasChildren()&&(e=s._descendants(t),e))return!0}return!1}toObject(){const t=P.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(e=>{t.children.push(e.toObject())}),t}isAncestorOf(t){let e=t.getParent();for(;e;){if(e._id===this._id)return!0;e=e.getParent()}return!1}clone(t){const e=P.prototype.clone.call(this,t);return this.getChildren().forEach(function(i){e.add(i.clone())}),e}getAllIntersections(t){const e=[];return this.find("Shape").forEach(i=>{i.isVisible()&&i.intersects(t)&&e.push(i)}),e}_clearSelfAndDescendantCache(t){var e;super._clearSelfAndDescendantCache(t),!this.isCached()&&((e=this.children)===null||e===void 0||e.forEach(function(i){i._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(e,i){e.index=i}),this._requestDraw()}drawScene(t,e,i){const s=this.getLayer(),n=t||s&&s.getCanvas(),r=n&&n.getContext(),o=this._getCanvasCache(),l=o&&o.scene,h=n&&n.isCache;if(!this.isVisible()&&!h)return this;if(l){r.save();const c=this.getAbsoluteTransform(e).getMatrix();r.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedSceneCanvas(r),r.restore()}else this._drawChildren("drawScene",n,e,i);return this}drawHit(t,e){if(!this.shouldDrawHit(e))return this;const i=this.getLayer(),s=t||i&&i.hitCanvas,n=s&&s.getContext(),r=this._getCanvasCache();if(r&&r.hit){n.save();const l=this.getAbsoluteTransform(e).getMatrix();n.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(n),n.restore()}else this._drawChildren("drawHit",s,e);return this}_drawChildren(t,e,i,s){var n;const r=e&&e.getContext(),o=this.clipWidth(),l=this.clipHeight(),h=this.clipFunc(),c=typeof o=="number"&&typeof l=="number"||h,d=i===this;if(c){r.save();const p=this.getAbsoluteTransform(i);let f=p.getMatrix();r.transform(f[0],f[1],f[2],f[3],f[4],f[5]),r.beginPath();let y;if(h)y=h.call(this,r,this);else{const T=this.clipX(),S=this.clipY();r.rect(T||0,S||0,o,l)}r.clip.apply(r,y),f=p.copy().invert().getMatrix(),r.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";u&&(r.save(),r._applyGlobalCompositeOperation(this)),(n=this.children)===null||n===void 0||n.forEach(function(p){p[t](e,i,s)}),u&&r.restore(),c&&r.restore()}getClientRect(t={}){var e;const i=t.skipTransform,s=t.relativeTo;let n,r,o,l,h={x:1/0,y:1/0,width:0,height:0};const c=this;(e=this.children)===null||e===void 0||e.forEach(function(p){if(!p.visible())return;const f=p.getClientRect({relativeTo:c,skipShadow:t.skipShadow,skipStroke:t.skipStroke});f.width===0&&f.height===0||(n===void 0?(n=f.x,r=f.y,o=f.x+f.width,l=f.y+f.height):(n=Math.min(n,f.x),r=Math.min(r,f.y),o=Math.max(o,f.x+f.width),l=Math.max(l,f.y+f.height)))});const d=this.find("Shape");let u=!1;for(let p=0;p<d.length;p++)if(d[p]._isVisible(this)){u=!0;break}return u&&n!==void 0?h={x:n,y:r,width:o-n,height:l-r}:h={x:0,y:0,width:0,height:0},i?h:this._transformedRect(h,s)}}m.addComponentsGetterSetter(ut,"clip",["x","y","width","height"]);m.addGetterSetter(ut,"clipX",void 0,x());m.addGetterSetter(ut,"clipY",void 0,x());m.addGetterSetter(ut,"clipWidth",void 0,x());m.addGetterSetter(ut,"clipHeight",void 0,x());m.addGetterSetter(ut,"clipFunc");const we=new Map,zs=E._global.PointerEvent!==void 0;function ei(a){return we.get(a)}function Di(a){return{evt:a,pointerId:a.pointerId}}function Ns(a,t){return we.get(a)===t}function Fs(a,t){me(a),t.getStage()&&(we.set(a,t),zs&&t._fire("gotpointercapture",Di(new PointerEvent("gotpointercapture"))))}function me(a,t){const e=we.get(a);if(!e)return;const i=e.getStage();i&&i.content,we.delete(a),zs&&e._fire("lostpointercapture",Di(new PointerEvent("lostpointercapture")))}const Pr="Stage",xr="string",Ki="px",Ar="mouseout",Vs="mouseleave",Ws="mouseover",Ys="mouseenter",Xs="mousemove",Us="mousedown",$s="mouseup",ce="pointermove",de="pointerdown",Jt="pointerup",ue="pointercancel",Er="lostpointercapture",Me="pointerout",ge="pointerleave",Le="pointerover",De="pointerenter",pi="contextmenu",Ks="touchstart",js="touchend",Zs="touchmove",qs="touchcancel",mi="wheel",Ir=5,Mr=[[Ys,"_pointerenter"],[Us,"_pointerdown"],[Xs,"_pointermove"],[$s,"_pointerup"],[Vs,"_pointerleave"],[Ks,"_pointerdown"],[Zs,"_pointermove"],[js,"_pointerup"],[qs,"_pointercancel"],[Ws,"_pointerover"],[mi,"_wheel"],[pi,"_contextmenu"],[de,"_pointerdown"],[ce,"_pointermove"],[Jt,"_pointerup"],[ue,"_pointercancel"],[ge,"_pointerleave"],[Er,"_lostpointercapture"]],ii={mouse:{[Me]:Ar,[ge]:Vs,[Le]:Ws,[De]:Ys,[ce]:Xs,[de]:Us,[Jt]:$s,[ue]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Me]:"touchout",[ge]:"touchleave",[Le]:"touchover",[De]:"touchenter",[ce]:Zs,[de]:Ks,[Jt]:js,[ue]:qs,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Me]:Me,[ge]:ge,[Le]:Le,[De]:De,[ce]:ce,[de]:de,[Jt]:Jt,[ue]:ue,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},fe=a=>a.indexOf("pointer")>=0?"pointer":a.indexOf("touch")>=0?"touch":"mouse",Kt=a=>{const t=fe(a);if(t==="pointer")return E.pointerEventsEnabled&&ii.pointer;if(t==="touch")return ii.touch;if(t==="mouse")return ii.mouse};function ji(a={}){return(a.clipFunc||a.clipWidth||a.clipHeight)&&C.warn("Stage does not support clipping. Please use clip for Layers or Groups."),a}const Lr="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",ye=[];class Qe extends ut{constructor(t){super(ji(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),ye.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{ji(this.attrs)}),this._checkVisibility()}_validateAdd(t){const e=t.getType()==="Layer",i=t.getType()==="FastLayer";e||i||C.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if(typeof t===xr){let e;if(t.charAt(0)==="."){const i=t.slice(1);t=document.getElementsByClassName(i)[0]}else t.charAt(0)!=="#"?e=t:e=t.slice(1),t=document.getElementById(e);if(!t)throw"Can not find container in document with id "+e}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const t=this.children,e=t.length;for(let i=0;i<e;i++)t[i].clear();return this}clone(t){return t||(t={}),t.container=typeof document<"u"&&document.createElement("div"),ut.prototype.clone.call(this,t)}destroy(){super.destroy();const t=this.content;t&&C._isInDocument(t)&&this.container().removeChild(t);const e=ye.indexOf(this);return e>-1&&ye.splice(e,1),C.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(C.warn(Lr),null)}_getPointerById(t){return this._pointerPositions.find(e=>e.id===t)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(t){t={...t},t.x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();const e=new Rt({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),i=e.getContext()._context,s=this.children;return(t.x||t.y)&&i.translate(-1*t.x,-1*t.y),s.forEach(function(n){if(!n.isVisible())return;const r=n._toKonvaCanvas(t);i.drawImage(r._canvas,t.x,t.y,r.getWidth()/r.getPixelRatio(),r.getHeight()/r.getPixelRatio())}),e}getIntersection(t){if(!t)return null;const e=this.children,i=e.length,s=i-1;for(let n=s;n>=0;n--){const r=e[n].getIntersection(t);if(r)return r}return null}_resizeDOM(){const t=this.width(),e=this.height();this.content&&(this.content.style.width=t+Ki,this.content.style.height=e+Ki),this.bufferCanvas.setSize(t,e),this.bufferHitCanvas.setSize(t,e),this.children.forEach(i=>{i.setSize({width:t,height:e}),i.draw()})}add(t,...e){if(arguments.length>1){for(let s=0;s<arguments.length;s++)this.add(arguments[s]);return this}super.add(t);const i=this.children.length;return i>Ir&&C.warn("The stage has "+i+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),E.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return Ns(t,this)}setPointerCapture(t){Fs(t,this)}releaseCapture(t){me(t)}getLayers(){return this.children}_bindContentEvents(){E.isBrowser&&Mr.forEach(([t,e])=>{this.content.addEventListener(t,i=>{this[e](i)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const e=Kt(t.type);e&&this._fire(e.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const e=Kt(t.type);e&&this._fire(e.pointerover,{evt:t,target:this,currentTarget:this})}_getTargetShape(t){let e=this[t+"targetShape"];return e&&!e.getStage()&&(e=null),e}_pointerleave(t){const e=Kt(t.type),i=fe(t.type);if(!e)return;this.setPointersPositions(t);const s=this._getTargetShape(i),n=!(E.isDragging()||E.isTransforming())||E.hitOnDragEnabled;s&&n?(s._fireAndBubble(e.pointerout,{evt:t}),s._fireAndBubble(e.pointerleave,{evt:t}),this._fire(e.pointerleave,{evt:t,target:this,currentTarget:this}),this[i+"targetShape"]=null):n&&(this._fire(e.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(e.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(t){const e=Kt(t.type),i=fe(t.type);if(!e)return;this.setPointersPositions(t);let s=!1;this._changedPointerPositions.forEach(n=>{const r=this.getIntersection(n);if($.justDragged=!1,E["_"+i+"ListenClick"]=!0,!r||!r.isListening()){this[i+"ClickStartShape"]=void 0;return}E.capturePointerEventsEnabled&&r.setPointerCapture(n.id),this[i+"ClickStartShape"]=r,r._fireAndBubble(e.pointerdown,{evt:t,pointerId:n.id}),s=!0;const o=t.type.indexOf("touch")>=0;r.preventDefault()&&t.cancelable&&o&&t.preventDefault()}),s||this._fire(e.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(t){const e=Kt(t.type),i=fe(t.type);if(!e)return;const s=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(E.isDragging()&&$.node.preventDefault()&&t.cancelable&&s&&t.preventDefault(),this.setPointersPositions(t),!(!(E.isDragging()||E.isTransforming())||E.hitOnDragEnabled))return;const r={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(h=>{const c=ei(h.id)||this.getIntersection(h),d=h.id,u={evt:t,pointerId:d},p=l!==c;if(p&&l&&(l._fireAndBubble(e.pointerout,{...u},c),l._fireAndBubble(e.pointerleave,{...u},c)),c){if(r[c._id])return;r[c._id]=!0}c&&c.isListening()?(o=!0,p&&(c._fireAndBubble(e.pointerover,{...u},l),c._fireAndBubble(e.pointerenter,{...u},l),this[i+"targetShape"]=c),c._fireAndBubble(e.pointermove,{...u})):l&&(this._fire(e.pointerover,{evt:t,target:this,currentTarget:this,pointerId:d}),this[i+"targetShape"]=null)}),o||this._fire(e.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const e=Kt(t.type),i=fe(t.type);if(!e)return;this.setPointersPositions(t);const s=this[i+"ClickStartShape"],n=this[i+"ClickEndShape"],r={};let o=!1;this._changedPointerPositions.forEach(l=>{const h=ei(l.id)||this.getIntersection(l);if(h){if(h.releaseCapture(l.id),r[h._id])return;r[h._id]=!0}const c=l.id,d={evt:t,pointerId:c};let u=!1;E["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):$.justDragged||(E["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){E["_"+i+"InDblClickWindow"]=!1},E.dblClickWindow),h&&h.isListening()?(o=!0,this[i+"ClickEndShape"]=h,h._fireAndBubble(e.pointerup,{...d}),E["_"+i+"ListenClick"]&&s&&s===h&&(h._fireAndBubble(e.pointerclick,{...d}),u&&n&&n===h&&h._fireAndBubble(e.pointerdblclick,{...d}))):(this[i+"ClickEndShape"]=null,o||(this._fire(e.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),E["_"+i+"ListenClick"]&&this._fire(e.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:c}),u&&this._fire(e.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:c}))}),o||this._fire(e.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),E["_"+i+"ListenClick"]=!1,t.cancelable&&i!=="touch"&&i!=="pointer"&&t.preventDefault()}_contextmenu(t){this.setPointersPositions(t);const e=this.getIntersection(this.getPointerPosition());e&&e.isListening()?e._fireAndBubble(pi,{evt:t}):this._fire(pi,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const e=this.getIntersection(this.getPointerPosition());e&&e.isListening()?e._fireAndBubble(mi,{evt:t}):this._fire(mi,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const e=ei(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble(Jt,Di(t)),me(t.pointerId)}_lostpointercapture(t){me(t.pointerId)}setPointersPositions(t){const e=this._getContentPosition();let i=null,s=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,n=>{this._pointerPositions.push({id:n.identifier,x:(n.clientX-e.left)/e.scaleX,y:(n.clientY-e.top)/e.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,n=>{this._changedPointerPositions.push({id:n.identifier,x:(n.clientX-e.left)/e.scaleX,y:(n.clientY-e.top)/e.scaleY})})):(i=(t.clientX-e.left)/e.scaleX,s=(t.clientY-e.top)/e.scaleY,this.pointerPos={x:i,y:s},this._pointerPositions=[{x:i,y:s,id:C._getFirstPointerId(t)}],this._changedPointerPositions=[{x:i,y:s,id:C._getFirstPointerId(t)}])}_setPointerPosition(t){C.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new Rt({width:this.width(),height:this.height()}),this.bufferHitCanvas=new Mi({pixelRatio:1,width:this.width(),height:this.height()}),!E.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}cache(){return C.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(t){t.batchDraw()}),this}}Qe.prototype.nodeType=Pr;st(Qe);m.addGetterSetter(Qe,"container");E.isBrowser&&document.addEventListener("visibilitychange",()=>{ye.forEach(a=>{a.batchDraw()})});const Js="hasShadow",Qs="shadowRGBA",tn="patternImage",en="linearGradient",sn="radialGradient";let Re;function si(){return Re||(Re=C.createCanvasElement().getContext("2d"),Re)}const Ce={};function Dr(a){const t=this.attrs.fillRule;t?a.fill(t):a.fill()}function Rr(a){a.stroke()}function Or(a){const t=this.attrs.fillRule;t?a.fill(t):a.fill()}function Gr(a){a.stroke()}function Br(){this._clearCache(Js)}function Hr(){this._clearCache(Qs)}function zr(){this._clearCache(tn)}function Nr(){this._clearCache(en)}function Fr(){this._clearCache(sn)}class w extends P{constructor(t){super(t);let e,i=0;for(;e=C.getHitColor(),!(e&&!(e in Ce));)if(i++,i>=1e4){C.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),e=C.getRandomColor();break}this.colorKey=e,Ce[e]=this}getContext(){return C.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return C.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(Js,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(tn,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const e=si().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(e&&e.setTransform){const i=new dt;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(E.getAngle(this.fillPatternRotation())),i.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),i.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const s=i.getMatrix(),n=typeof DOMMatrix>"u"?{a:s[0],b:s[1],c:s[2],d:s[3],e:s[4],f:s[5]}:new DOMMatrix(s);e.setTransform(n)}return e}}_getLinearGradient(){return this._getCache(en,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const e=si(),i=this.fillLinearGradientStartPoint(),s=this.fillLinearGradientEndPoint(),n=e.createLinearGradient(i.x,i.y,s.x,s.y);for(let r=0;r<t.length;r+=2)n.addColorStop(t[r],t[r+1]);return n}}_getRadialGradient(){return this._getCache(sn,this.__getRadialGradient)}__getRadialGradient(){const t=this.fillRadialGradientColorStops();if(t){const e=si(),i=this.fillRadialGradientStartPoint(),s=this.fillRadialGradientEndPoint(),n=e.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),s.x,s.y,this.fillRadialGradientEndRadius());for(let r=0;r<t.length;r+=2)n.addColorStop(t[r],t[r+1]);return n}}getShadowRGBA(){return this._getCache(Qs,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const t=C.colorToRGBA(this.shadowColor());if(t)return"rgba("+t.r+","+t.g+","+t.b+","+t.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return t==="auto"?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){const e=this.getStage();if(!e)return!1;const i=e.bufferHitCanvas;return i.getContext().clear(),this.drawHit(i,void 0,!0),i.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return P.prototype.destroy.call(this),delete Ce[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var e;if(!((e=this.attrs.perfectDrawEnabled)!==null&&e!==void 0?e:!0))return!1;const s=t||this.hasFill(),n=this.hasStroke(),r=this.getAbsoluteOpacity()!==1;if(s&&n&&r)return!0;const o=this.hasShadow(),l=this.shadowForStrokeEnabled();return!!(s&&n&&o&&l)}setStrokeHitEnabled(t){C.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let e=!1,i=this.getParent();for(;i;){if(i.isCached()){e=!0;break}i=i.getParent()}const s=t.skipTransform,n=t.relativeTo||e&&this.getStage()||void 0,r=this.getSelfRect(),l=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,h=r.width+l,c=r.height+l,d=!t.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,p=d?this.shadowOffsetY():0,f=h+Math.abs(u),y=c+Math.abs(p),T=d&&this.shadowBlur()||0,S=f+T*2,v=y+T*2,b={width:S,height:v,x:-(l/2+T)+Math.min(u,0)+r.x,y:-(l/2+T)+Math.min(p,0)+r.y};return s?b:this._transformedRect(b,n)}drawScene(t,e,i){const s=this.getLayer(),n=t||s.getCanvas(),r=n.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),h=this.hasShadow();let c;const d=e===this;if(!this.isVisible()&&!d)return this;if(o){r.save();const u=this.getAbsoluteTransform(e).getMatrix();return r.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(r),r.restore(),this}if(!l)return this;if(r.save(),this._useBufferCanvas()){c=this.getStage();const u=i||c.bufferCanvas,p=u.getContext();i?(p.save(),p.setTransform(1,0,0,1,0,0),p.clearRect(0,0,u.width,u.height),p.restore()):p.clear(),p.save(),p._applyLineJoin(this),p._applyMiterLimit(this);const f=this.getAbsoluteTransform(e).getMatrix();p.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.call(this,p,this),p.restore();const y=u.pixelRatio;h&&r._applyShadow(this),d||(r._applyOpacity(this),r._applyGlobalCompositeOperation(this)),r.drawImage(u._canvas,u.x||0,u.y||0,u.width/y,u.height/y)}else{if(r._applyLineJoin(this),r._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(e).getMatrix();r.transform(u[0],u[1],u[2],u[3],u[4],u[5]),r._applyOpacity(this),r._applyGlobalCompositeOperation(this)}h&&r._applyShadow(this),l.call(this,r,this)}return r.restore(),this}drawHit(t,e,i=!1){if(!this.shouldDrawHit(e,i))return this;const s=this.getLayer(),n=t||s.hitCanvas,r=n&&n.getContext(),o=this.hitFunc()||this.sceneFunc(),l=this._getCanvasCache(),h=l&&l.hit;if(this.colorKey||C.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),h){r.save();const d=this.getAbsoluteTransform(e).getMatrix();return r.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(r),r.restore(),this}if(!o)return this;if(r.save(),r._applyLineJoin(this),r._applyMiterLimit(this),!(this===e)){const d=this.getAbsoluteTransform(e).getMatrix();r.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,r,this),r.restore(),this}drawHitFromCache(t=0){const e=this._getCanvasCache(),i=this._getCachedSceneCanvas(),s=e.hit,n=s.getContext(),r=s.getWidth(),o=s.getHeight();n.clear(),n.drawImage(i._canvas,0,0,r,o);try{const l=n.getImageData(0,0,r,o),h=l.data,c=h.length,d=C._hexToRgb(this.colorKey);for(let u=0;u<c;u+=4)h[u+3]>t?(h[u]=d.r,h[u+1]=d.g,h[u+2]=d.b,h[u+3]=255):h[u+3]=0;n.putImageData(l,0,0)}catch(l){C.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(t){return Ns(t,this)}setPointerCapture(t){Fs(t,this)}releaseCapture(t){me(t)}}w.prototype._fillFunc=Dr;w.prototype._strokeFunc=Rr;w.prototype._fillFuncHit=Or;w.prototype._strokeFuncHit=Gr;w.prototype._centroid=!1;w.prototype.nodeType="Shape";st(w);w.prototype.eventListeners={};w.prototype.on.call(w.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Br);w.prototype.on.call(w.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Hr);w.prototype.on.call(w.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",zr);w.prototype.on.call(w.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Nr);w.prototype.on.call(w.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Fr);m.addGetterSetter(w,"stroke",void 0,Hs());m.addGetterSetter(w,"strokeWidth",2,x());m.addGetterSetter(w,"fillAfterStrokeEnabled",!1);m.addGetterSetter(w,"hitStrokeWidth","auto",Li());m.addGetterSetter(w,"strokeHitEnabled",!0,pt());m.addGetterSetter(w,"perfectDrawEnabled",!0,pt());m.addGetterSetter(w,"shadowForStrokeEnabled",!0,pt());m.addGetterSetter(w,"lineJoin");m.addGetterSetter(w,"lineCap");m.addGetterSetter(w,"miterLimit");m.addGetterSetter(w,"sceneFunc");m.addGetterSetter(w,"hitFunc");m.addGetterSetter(w,"dash");m.addGetterSetter(w,"dashOffset",0,x());m.addGetterSetter(w,"shadowColor",void 0,Wt());m.addGetterSetter(w,"shadowBlur",0,x());m.addGetterSetter(w,"shadowOpacity",1,x());m.addComponentsGetterSetter(w,"shadowOffset",["x","y"]);m.addGetterSetter(w,"shadowOffsetX",0,x());m.addGetterSetter(w,"shadowOffsetY",0,x());m.addGetterSetter(w,"fillPatternImage");m.addGetterSetter(w,"fill",void 0,Hs());m.addGetterSetter(w,"fillPatternX",0,x());m.addGetterSetter(w,"fillPatternY",0,x());m.addGetterSetter(w,"fillLinearGradientColorStops");m.addGetterSetter(w,"strokeLinearGradientColorStops");m.addGetterSetter(w,"fillRadialGradientStartRadius",0);m.addGetterSetter(w,"fillRadialGradientEndRadius",0);m.addGetterSetter(w,"fillRadialGradientColorStops");m.addGetterSetter(w,"fillPatternRepeat","repeat");m.addGetterSetter(w,"fillEnabled",!0);m.addGetterSetter(w,"strokeEnabled",!0);m.addGetterSetter(w,"shadowEnabled",!0);m.addGetterSetter(w,"dashEnabled",!0);m.addGetterSetter(w,"strokeScaleEnabled",!0);m.addGetterSetter(w,"fillPriority","color");m.addComponentsGetterSetter(w,"fillPatternOffset",["x","y"]);m.addGetterSetter(w,"fillPatternOffsetX",0,x());m.addGetterSetter(w,"fillPatternOffsetY",0,x());m.addComponentsGetterSetter(w,"fillPatternScale",["x","y"]);m.addGetterSetter(w,"fillPatternScaleX",1,x());m.addGetterSetter(w,"fillPatternScaleY",1,x());m.addComponentsGetterSetter(w,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(w,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(w,"fillLinearGradientStartPointX",0);m.addGetterSetter(w,"strokeLinearGradientStartPointX",0);m.addGetterSetter(w,"fillLinearGradientStartPointY",0);m.addGetterSetter(w,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(w,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(w,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(w,"fillLinearGradientEndPointX",0);m.addGetterSetter(w,"strokeLinearGradientEndPointX",0);m.addGetterSetter(w,"fillLinearGradientEndPointY",0);m.addGetterSetter(w,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(w,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(w,"fillRadialGradientStartPointX",0);m.addGetterSetter(w,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(w,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(w,"fillRadialGradientEndPointX",0);m.addGetterSetter(w,"fillRadialGradientEndPointY",0);m.addGetterSetter(w,"fillPatternRotation",0);m.addGetterSetter(w,"fillRule",void 0,Wt());m.backCompat(w,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Vr="beforeDraw",Wr="draw",nn=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Yr=nn.length;class Yt extends ut{constructor(t){super(t),this.canvas=new Rt,this.hitCanvas=new Mi({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),t<e.children.length-1?e.content.insertBefore(this.getNativeCanvasElement(),e.children[t+1].getCanvas()._canvas):e.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){P.prototype.moveToTop.call(this);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),t.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!P.prototype.moveUp.call(this))return!1;const e=this.getStage();return!e||!e.content?!1:(e.content.removeChild(this.getNativeCanvasElement()),this.index<e.children.length-1?e.content.insertBefore(this.getNativeCanvasElement(),e.children[this.index+1].getCanvas()._canvas):e.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(P.prototype.moveDown.call(this)){const t=this.getStage();if(t){const e=t.children;t.content&&(t.content.removeChild(this.getNativeCanvasElement()),t.content.insertBefore(this.getNativeCanvasElement(),e[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(P.prototype.moveToBottom.call(this)){const t=this.getStage();if(t){const e=t.children;t.content&&(t.content.removeChild(this.getNativeCanvasElement()),t.content.insertBefore(this.getNativeCanvasElement(),e[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const t=this.getNativeCanvasElement();return P.prototype.remove.call(this),t&&t.parentNode&&C._isInDocument(t)&&t.parentNode.removeChild(t),this}getStage(){return this.parent}setSize({width:t,height:e}){return this.canvas.setSize(t,e),this.hitCanvas.setSize(t,e),this._setSmoothEnabled(),this}_validateAdd(t){const e=t.getType();e!=="Group"&&e!=="Shape"&&C.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(t){return t={...t},t.width=t.width||this.getWidth(),t.height=t.height||this.getHeight(),t.x=t.x!==void 0?t.x:this.x(),t.y=t.y!==void 0?t.y:this.y(),P.prototype._toKonvaCanvas.call(this,t)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){C.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){C.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,C.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;let e=1,i=!1;for(;;){for(let s=0;s<Yr;s++){const n=nn[s],r=this._getIntersection({x:t.x+n.x*e,y:t.y+n.y*e}),o=r.shape;if(o)return o;if(i=!!r.antialiased,!r.antialiased)break}if(i)e+=1;else return null}}_getIntersection(t){const e=this.hitCanvas.pixelRatio,i=this.hitCanvas.context.getImageData(Math.round(t.x*e),Math.round(t.y*e),1,1).data,s=i[3];if(s===255){const n=C.getHitColorKey(i[0],i[1],i[2]),r=Ce[n];return r?{shape:r}:{antialiased:!0}}else if(s>0)return{antialiased:!0};return{}}drawScene(t,e,i){const s=this.getLayer(),n=t||s&&s.getCanvas();return this._fire(Vr,{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),ut.prototype.drawScene.call(this,n,e,i),this._fire(Wr,{node:this}),this}drawHit(t,e){const i=this.getLayer(),s=t||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),ut.prototype.drawHit.call(this,s,e),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){C.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return C.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}destroy(){return C.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}Yt.prototype.nodeType="Layer";st(Yt);m.addGetterSetter(Yt,"imageSmoothingEnabled",!0);m.addGetterSetter(Yt,"clearBeforeDraw",!0);m.addGetterSetter(Yt,"hitGraphEnabled",!0,pt());class Ri extends Yt{constructor(t){super(t),this.listening(!1),C.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}Ri.prototype.nodeType="FastLayer";st(Ri);class te extends ut{_validateAdd(t){const e=t.getType();e!=="Group"&&e!=="Shape"&&C.throw("You may only add groups and shapes to groups.")}}te.prototype.nodeType="Group";st(te);const ni=function(){return Ft.performance&&Ft.performance.now?function(){return Ft.performance.now()}:function(){return new Date().getTime()}}();class gt{constructor(t,e){this.id=gt.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:ni(),frameRate:0},this.func=t,this.setLayers(e)}setLayers(t){let e=[];return t&&(e=Array.isArray(t)?t:[t]),this.layers=e,this}getLayers(){return this.layers}addLayer(t){const e=this.layers,i=e.length;for(let s=0;s<i;s++)if(e[s]._id===t._id)return!1;return this.layers.push(t),!0}isRunning(){const e=gt.animations,i=e.length;for(let s=0;s<i;s++)if(e[s].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=ni(),gt._addAnimation(this),this}stop(){return gt._removeAnimation(this),this}_updateFrameObject(t){this.frame.timeDiff=t-this.frame.lastTime,this.frame.lastTime=t,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(t){this.animations.push(t),this._handleAnimation()}static _removeAnimation(t){const e=t.id,i=this.animations,s=i.length;for(let n=0;n<s;n++)if(i[n].id===e){this.animations.splice(n,1);break}}static _runFrames(){const t={},e=this.animations;for(let i=0;i<e.length;i++){const s=e[i],n=s.layers,r=s.func;s._updateFrameObject(ni());const o=n.length;let l;if(r?l=r.call(s,s.frame)!==!1:l=!0,!!l)for(let h=0;h<o;h++){const c=n[h];c._id!==void 0&&(t[c._id]=c)}}for(const i in t)t.hasOwnProperty(i)&&t[i].batchDraw()}static _animationLoop(){const t=gt;t.animations.length?(t._runFrames(),C.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,C.requestAnimFrame(this._animationLoop))}}gt.animations=[];gt.animIdCounter=0;gt.animRunning=!1;const Xr={node:1,duration:1,easing:1,onFinish:1,yoyo:1},Ur=1,Zi=2,qi=3,Ji=["fill","stroke","shadowColor"];let $r=0;class Kr{constructor(t,e,i,s,n,r,o){this.prop=t,this.propFunc=e,this.begin=s,this._pos=s,this.duration=r,this._change=0,this.prevPos=0,this.yoyo=o,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=i,this._change=n-this.begin,this.pause()}fire(t){const e=this[t];e&&e()}setTime(t){t>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return t===void 0&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=Zi,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=qi,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const t=this.getTimer()-this._startTime;this.state===Zi?this.setTime(t):this.state===qi&&this.setTime(this.duration-t)}pause(){this.state=Ur,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Q{constructor(t){const e=this,i=t.node,s=i._id,n=t.easing||Se.Linear,r=!!t.yoyo;let o,l;typeof t.duration>"u"?o=.3:t.duration===0?o=.001:o=t.duration,this.node=i,this._id=$r++;const h=i.getLayer()||(i instanceof E.Stage?i.getLayers():null);h||C.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new gt(function(){e.tween.onEnterFrame()},h),this.tween=new Kr(l,function(c){e._tweenFunc(c)},n,0,1,o*1e3,r),this._addListeners(),Q.attrs[s]||(Q.attrs[s]={}),Q.attrs[s][this._id]||(Q.attrs[s][this._id]={}),Q.tweens[s]||(Q.tweens[s]={});for(l in t)Xr[l]===void 0&&this._addAttr(l,t[l]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,e){const i=this.node,s=i._id;let n,r,o,l,h;const c=Q.tweens[s][t];c&&delete Q.attrs[s][c][t];let d=i.getAttr(t);if(C._isArray(e))if(n=[],r=Math.max(e.length,d.length),t==="points"&&e.length!==d.length&&(e.length>d.length?(l=d,d=C._prepareArrayForTween(d,e,i.closed())):(o=e,e=C._prepareArrayForTween(e,d,i.closed()))),t.indexOf("fill")===0)for(let u=0;u<r;u++)if(u%2===0)n.push(e[u]-d[u]);else{const p=C.colorToRGBA(d[u]);h=C.colorToRGBA(e[u]),d[u]=p,n.push({r:h.r-p.r,g:h.g-p.g,b:h.b-p.b,a:h.a-p.a})}else for(let u=0;u<r;u++)n.push(e[u]-d[u]);else Ji.indexOf(t)!==-1?(d=C.colorToRGBA(d),h=C.colorToRGBA(e),n={r:h.r-d.r,g:h.g-d.g,b:h.b-d.b,a:h.a-d.a}):n=e-d;Q.attrs[s][this._id][t]={start:d,diff:n,end:e,trueEnd:o,trueStart:l},Q.tweens[s][t]=this._id}_tweenFunc(t){const e=this.node,i=Q.attrs[e._id][this._id];let s,n,r,o,l,h,c,d;for(s in i){if(n=i[s],r=n.start,o=n.diff,d=n.end,C._isArray(r))if(l=[],c=Math.max(r.length,d.length),s.indexOf("fill")===0)for(h=0;h<c;h++)h%2===0?l.push((r[h]||0)+o[h]*t):l.push("rgba("+Math.round(r[h].r+o[h].r*t)+","+Math.round(r[h].g+o[h].g*t)+","+Math.round(r[h].b+o[h].b*t)+","+(r[h].a+o[h].a*t)+")");else for(h=0;h<c;h++)l.push((r[h]||0)+o[h]*t);else Ji.indexOf(s)!==-1?l="rgba("+Math.round(r.r+o.r*t)+","+Math.round(r.g+o.g*t)+","+Math.round(r.b+o.b*t)+","+(r.a+o.a*t)+")":l=r+o*t;e.setAttr(s,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,e=Q.attrs[t._id][this._id];e.points&&e.points.trueEnd&&t.setAttr("points",e.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,e=Q.attrs[t._id][this._id];e.points&&e.points.trueStart&&t.points(e.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const t=this.node._id,e=this._id,i=Q.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const s in i)delete Q.tweens[t][s];delete Q.attrs[t][e],Q.tweens[t]&&(Object.keys(Q.tweens[t]).length===0&&delete Q.tweens[t],Object.keys(Q.attrs[t]).length===0&&delete Q.attrs[t])}}Q.attrs={};Q.tweens={};P.prototype.to=function(a){const t=a.onFinish;a.node=this,a.onFinish=function(){this.destroy(),t&&t()},new Q(a).play()};const Se={BackEaseIn(a,t,e,i){return e*(a/=i)*a*((1.70158+1)*a-1.70158)+t},BackEaseOut(a,t,e,i){return e*((a=a/i-1)*a*((1.70158+1)*a+1.70158)+1)+t},BackEaseInOut(a,t,e,i){let s=1.70158;return(a/=i/2)<1?e/2*(a*a*(((s*=1.525)+1)*a-s))+t:e/2*((a-=2)*a*(((s*=1.525)+1)*a+s)+2)+t},ElasticEaseIn(a,t,e,i,s,n){let r=0;return a===0?t:(a/=i)===1?t+e:(n||(n=i*.3),!s||s<Math.abs(e)?(s=e,r=n/4):r=n/(2*Math.PI)*Math.asin(e/s),-(s*Math.pow(2,10*(a-=1))*Math.sin((a*i-r)*(2*Math.PI)/n))+t)},ElasticEaseOut(a,t,e,i,s,n){let r=0;return a===0?t:(a/=i)===1?t+e:(n||(n=i*.3),!s||s<Math.abs(e)?(s=e,r=n/4):r=n/(2*Math.PI)*Math.asin(e/s),s*Math.pow(2,-10*a)*Math.sin((a*i-r)*(2*Math.PI)/n)+e+t)},ElasticEaseInOut(a,t,e,i,s,n){let r=0;return a===0?t:(a/=i/2)===2?t+e:(n||(n=i*(.3*1.5)),!s||s<Math.abs(e)?(s=e,r=n/4):r=n/(2*Math.PI)*Math.asin(e/s),a<1?-.5*(s*Math.pow(2,10*(a-=1))*Math.sin((a*i-r)*(2*Math.PI)/n))+t:s*Math.pow(2,-10*(a-=1))*Math.sin((a*i-r)*(2*Math.PI)/n)*.5+e+t)},BounceEaseOut(a,t,e,i){return(a/=i)<1/2.75?e*(7.5625*a*a)+t:a<2/2.75?e*(7.5625*(a-=1.5/2.75)*a+.75)+t:a<2.5/2.75?e*(7.5625*(a-=2.25/2.75)*a+.9375)+t:e*(7.5625*(a-=2.625/2.75)*a+.984375)+t},BounceEaseIn(a,t,e,i){return e-Se.BounceEaseOut(i-a,0,e,i)+t},BounceEaseInOut(a,t,e,i){return a<i/2?Se.BounceEaseIn(a*2,0,e,i)*.5+t:Se.BounceEaseOut(a*2-i,0,e,i)*.5+e*.5+t},EaseIn(a,t,e,i){return e*(a/=i)*a+t},EaseOut(a,t,e,i){return-e*(a/=i)*(a-2)+t},EaseInOut(a,t,e,i){return(a/=i/2)<1?e/2*a*a+t:-e/2*(--a*(a-2)-1)+t},StrongEaseIn(a,t,e,i){return e*(a/=i)*a*a*a*a+t},StrongEaseOut(a,t,e,i){return e*((a=a/i-1)*a*a*a*a+1)+t},StrongEaseInOut(a,t,e,i){return(a/=i/2)<1?e/2*a*a*a*a*a+t:e/2*((a-=2)*a*a*a*a+2)+t},Linear(a,t,e,i){return e*a/i+t}},Qi=C._assign(E,{Util:C,Transform:dt,Node:P,Container:ut,Stage:Qe,stages:ye,Layer:Yt,FastLayer:Ri,Group:te,DD:$,Shape:w,shapes:Ce,Animation:gt,Tween:Q,Easings:Se,Context:qe,Canvas:Ii});class xt extends w{_sceneFunc(t){const e=E.getAngle(this.angle()),i=this.clockwise();t.beginPath(),t.arc(0,0,this.outerRadius(),0,e,i),t.arc(0,0,this.innerRadius(),e,0,!i),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}getSelfRect(){const t=this.innerRadius(),e=this.outerRadius(),i=this.clockwise(),s=E.getAngle(i?360-this.angle():this.angle()),n=Math.cos(Math.min(s,Math.PI)),r=1,o=Math.sin(Math.min(Math.max(Math.PI,s),3*Math.PI/2)),l=Math.sin(Math.min(s,Math.PI/2)),h=n*(n>0?t:e),c=r*e,d=o*(o>0?t:e),u=l*(l>0?e:t);return{x:h,y:i?-1*u:d,width:c-h,height:u-d}}}xt.prototype._centroid=!0;xt.prototype.className="Arc";xt.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];st(xt);m.addGetterSetter(xt,"innerRadius",0,x());m.addGetterSetter(xt,"outerRadius",0,x());m.addGetterSetter(xt,"angle",0,x());m.addGetterSetter(xt,"clockwise",!1,pt());function yi(a,t,e,i,s,n,r){const o=Math.sqrt(Math.pow(e-a,2)+Math.pow(i-t,2)),l=Math.sqrt(Math.pow(s-e,2)+Math.pow(n-i,2)),h=r*o/(o+l),c=r*l/(o+l),d=e-h*(s-a),u=i-h*(n-t),p=e+c*(s-a),f=i+c*(n-t);return[d,u,p,f]}function ts(a,t){const e=a.length,i=[];for(let s=2;s<e-2;s+=2){const n=yi(a[s-2],a[s-1],a[s],a[s+1],a[s+2],a[s+3],t);isNaN(n[0])||(i.push(n[0]),i.push(n[1]),i.push(a[s]),i.push(a[s+1]),i.push(n[2]),i.push(n[3]))}return i}function jr(a){const t=[[a[0],a[2],a[4],a[6]],[a[1],a[3],a[5],a[7]]],e=[];for(const i of t){const s=-3*i[0]+9*i[1]-9*i[2]+3*i[3];if(s!==0){const n=6*i[0]-12*i[1]+6*i[2],r=-3*i[0]+3*i[1],o=n*n-4*s*r;if(o>=0){const l=Math.sqrt(o);e.push((-n+l)/(2*s)),e.push((-n-l)/(2*s))}}}return e.filter(i=>i>0&&i<1).flatMap(i=>t.map(s=>{const n=1-i;return n*n*n*s[0]+3*n*n*i*s[1]+3*n*i*i*s[2]+i*i*i*s[3]}))}class At extends w{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(t){const e=this.points(),i=e.length,s=this.tension(),n=this.closed(),r=this.bezier();if(!i)return;let o=0;if(t.beginPath(),t.moveTo(e[0],e[1]),s!==0&&i>4){const l=this.getTensionPoints(),h=l.length;for(o=n?0:4,n||t.quadraticCurveTo(l[0],l[1],l[2],l[3]);o<h-2;)t.bezierCurveTo(l[o++],l[o++],l[o++],l[o++],l[o++],l[o++]);n||t.quadraticCurveTo(l[h-2],l[h-1],e[i-2],e[i-1])}else if(r)for(o=2;o<i;)t.bezierCurveTo(e[o++],e[o++],e[o++],e[o++],e[o++],e[o++]);else for(o=2;o<i;o+=2)t.lineTo(e[o],e[o+1]);n?(t.closePath(),t.fillStrokeShape(this)):t.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():ts(this.points(),this.tension())}_getTensionPointsClosed(){const t=this.points(),e=t.length,i=this.tension(),s=yi(t[e-2],t[e-1],t[0],t[1],t[2],t[3],i),n=yi(t[e-4],t[e-3],t[e-2],t[e-1],t[0],t[1],i),r=ts(t,i);return[s[2],s[3]].concat(r).concat([n[0],n[1],t[e-2],t[e-1],n[2],n[3],s[0],s[1],t[0],t[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let t=this.points();if(t.length<4)return{x:t[0]||0,y:t[1]||0,width:0,height:0};this.tension()!==0?t=[t[0],t[1],...this._getTensionPoints(),t[t.length-2],t[t.length-1]]:this.bezier()?t=[t[0],t[1],...jr(this.points()),t[t.length-2],t[t.length-1]]:t=this.points();let e=t[0],i=t[0],s=t[1],n=t[1],r,o;for(let l=0;l<t.length/2;l++)r=t[l*2],o=t[l*2+1],e=Math.min(e,r),i=Math.max(i,r),s=Math.min(s,o),n=Math.max(n,o);return{x:e,y:s,width:i-e,height:n-s}}}At.prototype.className="Line";At.prototype._attrsAffectingSize=["points","bezier","tension"];st(At);m.addGetterSetter(At,"closed",!1);m.addGetterSetter(At,"bezier",!1);m.addGetterSetter(At,"tension",0,x());m.addGetterSetter(At,"points",[],dr());const Zr=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],qr=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],Jr=[[1],[1,1],[1,2,1],[1,3,3,1]],es=(a,t,e)=>{let i,s;const r=e/2;i=0;for(let o=0;o<20;o++)s=r*Zr[20][o]+r,i+=qr[20][o]*Qr(a,t,s);return r*i},is=(a,t,e)=>{e===void 0&&(e=1);const i=a[0]-2*a[1]+a[2],s=t[0]-2*t[1]+t[2],n=2*a[1]-2*a[0],r=2*t[1]-2*t[0],o=4*(i*i+s*s),l=4*(i*n+s*r),h=n*n+r*r;if(o===0)return e*Math.sqrt(Math.pow(a[2]-a[0],2)+Math.pow(t[2]-t[0],2));const c=l/(2*o),d=h/o,u=e+c,p=d-c*c,f=u*u+p>0?Math.sqrt(u*u+p):0,y=c*c+p>0?Math.sqrt(c*c+p):0,T=c+Math.sqrt(c*c+p)!==0?p*Math.log(Math.abs((u+f)/(c+y))):0;return Math.sqrt(o)/2*(u*f-c*y+T)};function Qr(a,t,e){const i=Ci(1,e,a),s=Ci(1,e,t),n=i*i+s*s;return Math.sqrt(n)}const Ci=(a,t,e)=>{const i=e.length-1;let s,n;if(i===0)return 0;if(a===0){n=0;for(let r=0;r<=i;r++)n+=Jr[i][r]*Math.pow(1-t,i-r)*Math.pow(t,r)*e[r];return n}else{s=new Array(i);for(let r=0;r<i;r++)s[r]=i*(e[r+1]-e[r]);return Ci(a-1,t,s)}},ss=(a,t,e)=>{let i=1,s=a/t,n=(a-e(s))/t,r=0;for(;i>.001;){const o=e(s+n),l=Math.abs(a-o)/t;if(l<i)i=l,s+=n;else{const h=e(s-n),c=Math.abs(a-h)/t;c<i?(i=c,s-=n):n/=2}if(r++,r>500)break}return s};class tt extends w{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=tt.parsePathData(this.data()),this.pathLength=tt.getPathLength(this.dataArray)}_sceneFunc(t){const e=this.dataArray;t.beginPath();let i=!1;for(let s=0;s<e.length;s++){const n=e[s].command,r=e[s].points;switch(n){case"L":t.lineTo(r[0],r[1]);break;case"M":t.moveTo(r[0],r[1]);break;case"C":t.bezierCurveTo(r[0],r[1],r[2],r[3],r[4],r[5]);break;case"Q":t.quadraticCurveTo(r[0],r[1],r[2],r[3]);break;case"A":const o=r[0],l=r[1],h=r[2],c=r[3],d=r[4],u=r[5],p=r[6],f=r[7],y=h>c?h:c,T=h>c?1:h/c,S=h>c?c/h:1;t.translate(o,l),t.rotate(p),t.scale(T,S),t.arc(0,0,y,d,d+u,1-f),t.scale(1/T,1/S),t.rotate(-p),t.translate(-o,-l);break;case"z":i=!0,t.closePath();break}}!i&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(l){if(l.command==="A"){const h=l.points[4],c=l.points[5],d=l.points[4]+c;let u=Math.PI/180;if(Math.abs(h-d)<u&&(u=Math.abs(h-d)),c<0)for(let p=h-u;p>d;p-=u){const f=tt.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);t.push(f.x,f.y)}else for(let p=h+u;p<d;p+=u){const f=tt.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);t.push(f.x,f.y)}}else if(l.command==="C")for(let h=0;h<=1;h+=.01){const c=tt.getPointOnCubicBezier(h,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);t.push(c.x,c.y)}else t=t.concat(l.points)});let e=t[0],i=t[0],s=t[1],n=t[1],r,o;for(let l=0;l<t.length/2;l++)r=t[l*2],o=t[l*2+1],isNaN(r)||(e=Math.min(e,r),i=Math.max(i,r)),isNaN(o)||(s=Math.min(s,o),n=Math.max(n,o));return{x:e,y:s,width:i-e,height:n-s}}getLength(){return this.pathLength}getPointAtLength(t){return tt.getPointAtLengthOfDataArray(t,this.dataArray)}static getLineLength(t,e,i,s){return Math.sqrt((i-t)*(i-t)+(s-e)*(s-e))}static getPathLength(t){let e=0;for(let i=0;i<t.length;++i)e+=t[i].pathLength;return e}static getPointAtLengthOfDataArray(t,e){let i,s=0,n=e.length;if(!n)return null;for(;s<n&&t>e[s].pathLength;)t-=e[s].pathLength,++s;if(s===n)return i=e[s-1].points.slice(-2),{x:i[0],y:i[1]};if(t<.01)return e[s].command==="M"?(i=e[s].points.slice(0,2),{x:i[0],y:i[1]}):{x:e[s].start.x,y:e[s].start.y};const r=e[s],o=r.points;switch(r.command){case"L":return tt.getPointOnLine(t,r.start.x,r.start.y,o[0],o[1]);case"C":return tt.getPointOnCubicBezier(ss(t,tt.getPathLength(e),y=>es([r.start.x,o[0],o[2],o[4]],[r.start.y,o[1],o[3],o[5]],y)),r.start.x,r.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return tt.getPointOnQuadraticBezier(ss(t,tt.getPathLength(e),y=>is([r.start.x,o[0],o[2]],[r.start.y,o[1],o[3]],y)),r.start.x,r.start.y,o[0],o[1],o[2],o[3]);case"A":const l=o[0],h=o[1],c=o[2],d=o[3],u=o[5],p=o[6];let f=o[4];return f+=u*t/r.pathLength,tt.getPointOnEllipticalArc(l,h,c,d,f,p)}return null}static getPointOnLine(t,e,i,s,n,r,o){r=r??e,o=o??i;const l=this.getLineLength(e,i,s,n);if(l<1e-10)return{x:e,y:i};if(s===e)return{x:r,y:o+(n>i?t:-t)};const h=(n-i)/(s-e),c=Math.sqrt(t*t/(1+h*h))*(s<e?-1:1),d=h*c;if(Math.abs(o-i-h*(r-e))<1e-10)return{x:r+c,y:o+d};const u=((r-e)*(s-e)+(o-i)*(n-i))/(l*l),p=e+u*(s-e),f=i+u*(n-i),y=this.getLineLength(r,o,p,f),T=Math.sqrt(t*t-y*y),S=Math.sqrt(T*T/(1+h*h))*(s<e?-1:1),v=h*S;return{x:p+S,y:f+v}}static getPointOnCubicBezier(t,e,i,s,n,r,o,l,h){function c(T){return T*T*T}function d(T){return 3*T*T*(1-T)}function u(T){return 3*T*(1-T)*(1-T)}function p(T){return(1-T)*(1-T)*(1-T)}const f=l*c(t)+r*d(t)+s*u(t)+e*p(t),y=h*c(t)+o*d(t)+n*u(t)+i*p(t);return{x:f,y}}static getPointOnQuadraticBezier(t,e,i,s,n,r,o){function l(p){return p*p}function h(p){return 2*p*(1-p)}function c(p){return(1-p)*(1-p)}const d=r*l(t)+s*h(t)+e*c(t),u=o*l(t)+n*h(t)+i*c(t);return{x:d,y:u}}static getPointOnEllipticalArc(t,e,i,s,n,r){const o=Math.cos(r),l=Math.sin(r),h={x:i*Math.cos(n),y:s*Math.sin(n)};return{x:t+(h.x*o-h.y*l),y:e+(h.x*l+h.y*o)}}static parsePathData(t){if(!t)return[];let e=t;const i=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];e=e.replace(new RegExp(" ","g"),",");for(let d=0;d<i.length;d++)e=e.replace(new RegExp(i[d],"g"),"|"+i[d]);const s=e.split("|"),n=[],r=[];let o=0,l=0;const h=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let c;for(let d=1;d<s.length;d++){let u=s[d],p=u.charAt(0);for(u=u.slice(1),r.length=0;c=h.exec(u);)r.push(c[0]);let f=[],y=p==="A"||p==="a"?0:-1;for(let T=0,S=r.length;T<S;T++){const v=r[T];if(v==="00"){f.push(0,0),y>=0&&(y+=2,y>=7&&(y-=7));continue}if(y>=0){if(y===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(v)){f.push(parseInt(v[0],10)),f.push(parseInt(v[1],10)),f.push(parseFloat(v.slice(2))),y+=3,y>=7&&(y-=7);continue}if(v==="11"||v==="10"||v==="01"){f.push(parseInt(v[0],10)),f.push(parseInt(v[1],10)),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){f.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(v)){f.push(parseInt(v[0],10)),f.push(parseFloat(v.slice(1))),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){f.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}const b=parseFloat(v);isNaN(b)?f.push(0):f.push(b),y+=1,y>=7&&(y-=7)}else{const b=parseFloat(v);isNaN(b)?f.push(0):f.push(b)}}for(;f.length>0&&!isNaN(f[0]);){let T="",S=[];const v=o,b=l;let k,M,_,R,A,I,D,N,G,W;switch(p){case"l":o+=f.shift(),l+=f.shift(),T="L",S.push(o,l);break;case"L":o=f.shift(),l=f.shift(),S.push(o,l);break;case"m":const F=f.shift(),H=f.shift();if(o+=F,l+=H,T="M",n.length>2&&n[n.length-1].command==="z"){for(let L=n.length-2;L>=0;L--)if(n[L].command==="M"){o=n[L].points[0]+F,l=n[L].points[1]+H;break}}S.push(o,l),p="l";break;case"M":o=f.shift(),l=f.shift(),T="M",S.push(o,l),p="L";break;case"h":o+=f.shift(),T="L",S.push(o,l);break;case"H":o=f.shift(),T="L",S.push(o,l);break;case"v":l+=f.shift(),T="L",S.push(o,l);break;case"V":l=f.shift(),T="L",S.push(o,l);break;case"C":S.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),l=f.shift(),S.push(o,l);break;case"c":S.push(o+f.shift(),l+f.shift(),o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),T="C",S.push(o,l);break;case"S":M=o,_=l,k=n[n.length-1],k.command==="C"&&(M=o+(o-k.points[2]),_=l+(l-k.points[3])),S.push(M,_,f.shift(),f.shift()),o=f.shift(),l=f.shift(),T="C",S.push(o,l);break;case"s":M=o,_=l,k=n[n.length-1],k.command==="C"&&(M=o+(o-k.points[2]),_=l+(l-k.points[3])),S.push(M,_,o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),T="C",S.push(o,l);break;case"Q":S.push(f.shift(),f.shift()),o=f.shift(),l=f.shift(),S.push(o,l);break;case"q":S.push(o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),T="Q",S.push(o,l);break;case"T":M=o,_=l,k=n[n.length-1],k.command==="Q"&&(M=o+(o-k.points[0]),_=l+(l-k.points[1])),o=f.shift(),l=f.shift(),T="Q",S.push(M,_,o,l);break;case"t":M=o,_=l,k=n[n.length-1],k.command==="Q"&&(M=o+(o-k.points[0]),_=l+(l-k.points[1])),o+=f.shift(),l+=f.shift(),T="Q",S.push(M,_,o,l);break;case"A":R=f.shift(),A=f.shift(),I=f.shift(),D=f.shift(),N=f.shift(),G=o,W=l,o=f.shift(),l=f.shift(),T="A",S=this.convertEndpointToCenterParameterization(G,W,o,l,D,N,R,A,I);break;case"a":R=f.shift(),A=f.shift(),I=f.shift(),D=f.shift(),N=f.shift(),G=o,W=l,o+=f.shift(),l+=f.shift(),T="A",S=this.convertEndpointToCenterParameterization(G,W,o,l,D,N,R,A,I);break}n.push({command:T||p,points:S,start:{x:v,y:b},pathLength:this.calcLength(v,b,T||p,S)})}(p==="z"||p==="Z")&&n.push({command:"z",points:[],start:void 0,pathLength:0})}return n}static calcLength(t,e,i,s){let n,r,o,l;const h=tt;switch(i){case"L":return h.getLineLength(t,e,s[0],s[1]);case"C":return es([t,s[0],s[2],s[4]],[e,s[1],s[3],s[5]],1);case"Q":return is([t,s[0],s[2]],[e,s[1],s[3]],1);case"A":n=0;const c=s[4],d=s[5],u=s[4]+d;let p=Math.PI/180;if(Math.abs(c-u)<p&&(p=Math.abs(c-u)),r=h.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],c,0),d<0)for(l=c-p;l>u;l-=p)o=h.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],l,0),n+=h.getLineLength(r.x,r.y,o.x,o.y),r=o;else for(l=c+p;l<u;l+=p)o=h.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],l,0),n+=h.getLineLength(r.x,r.y,o.x,o.y),r=o;return o=h.getPointOnEllipticalArc(s[0],s[1],s[2],s[3],u,0),n+=h.getLineLength(r.x,r.y,o.x,o.y),n}return 0}static convertEndpointToCenterParameterization(t,e,i,s,n,r,o,l,h){const c=h*(Math.PI/180),d=Math.cos(c)*(t-i)/2+Math.sin(c)*(e-s)/2,u=-1*Math.sin(c)*(t-i)/2+Math.cos(c)*(e-s)/2,p=d*d/(o*o)+u*u/(l*l);p>1&&(o*=Math.sqrt(p),l*=Math.sqrt(p));let f=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));n===r&&(f*=-1),isNaN(f)&&(f=0);const y=f*o*u/l,T=f*-l*d/o,S=(t+i)/2+Math.cos(c)*y-Math.sin(c)*T,v=(e+s)/2+Math.sin(c)*y+Math.cos(c)*T,b=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},k=function(D,N){return(D[0]*N[0]+D[1]*N[1])/(b(D)*b(N))},M=function(D,N){return(D[0]*N[1]<D[1]*N[0]?-1:1)*Math.acos(k(D,N))},_=M([1,0],[(d-y)/o,(u-T)/l]),R=[(d-y)/o,(u-T)/l],A=[(-1*d-y)/o,(-1*u-T)/l];let I=M(R,A);return k(R,A)<=-1&&(I=Math.PI),k(R,A)>=1&&(I=0),r===0&&I>0&&(I=I-2*Math.PI),r===1&&I<0&&(I=I+2*Math.PI),[S,v,o,l,_,I,c,r]}}tt.prototype.className="Path";tt.prototype._attrsAffectingSize=["data"];st(tt);m.addGetterSetter(tt,"data");class Xt extends At{_sceneFunc(t){super._sceneFunc(t);const e=Math.PI*2,i=this.points();let s=i;const n=this.tension()!==0&&i.length>4;n&&(s=this.getTensionPoints());const r=this.pointerLength(),o=i.length;let l,h;if(n){const u=[s[s.length-4],s[s.length-3],s[s.length-2],s[s.length-1],i[o-2],i[o-1]],p=tt.calcLength(s[s.length-4],s[s.length-3],"C",u),f=tt.getPointOnQuadraticBezier(Math.min(1,1-r/p),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-f.x,h=i[o-1]-f.y}else l=i[o-2]-i[o-4],h=i[o-1]-i[o-3];const c=(Math.atan2(h,l)+e)%e,d=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(i[o-2],i[o-1]),t.rotate(c),t.moveTo(0,0),t.lineTo(-r,d/2),t.lineTo(-r,-d/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(i[0],i[1]),n?(l=(s[0]+s[2])/2-i[0],h=(s[1]+s[3])/2-i[1]):(l=i[2]-i[0],h=i[3]-i[1]),t.rotate((Math.atan2(-h,-l)+e)%e),t.moveTo(0,0),t.lineTo(-r,d/2),t.lineTo(-r,-d/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const e=this.dashEnabled();e&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),e&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),e=this.pointerWidth()/2;return{x:t.x,y:t.y-e,width:t.width,height:t.height+e*2}}}Xt.prototype.className="Arrow";st(Xt);m.addGetterSetter(Xt,"pointerLength",10,x());m.addGetterSetter(Xt,"pointerWidth",10,x());m.addGetterSetter(Xt,"pointerAtBeginning",!1);m.addGetterSetter(Xt,"pointerAtEnding",!0);class ee extends w{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}ee.prototype._centroid=!0;ee.prototype.className="Circle";ee.prototype._attrsAffectingSize=["radius"];st(ee);m.addGetterSetter(ee,"radius",0,x());class Gt extends w{_sceneFunc(t){const e=this.radiusX(),i=this.radiusY();t.beginPath(),t.save(),e!==i&&t.scale(1,i/e),t.arc(0,0,e,0,Math.PI*2,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}Gt.prototype.className="Ellipse";Gt.prototype._centroid=!0;Gt.prototype._attrsAffectingSize=["radiusX","radiusY"];st(Gt);m.addComponentsGetterSetter(Gt,"radius",["x","y"]);m.addGetterSetter(Gt,"radiusX",0,x());m.addGetterSetter(Gt,"radiusY",0,x());let mt=class rn extends w{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",e=>{this._removeImageLoad(e.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),e=this.hasShadow();return t&&e?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const e=this.getWidth(),i=this.getHeight(),s=this.cornerRadius(),n=this.attrs.image;let r;if(n){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?r=[n,this.cropX(),this.cropY(),o,l,0,0,e,i]:r=[n,0,0,e,i]}(this.hasFill()||this.hasStroke()||s)&&(t.beginPath(),s?C.drawRoundedRectPath(t,e,i,s):t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)),n&&(s&&t.clip(),t.drawImage.apply(t,r))}_hitFunc(t){const e=this.width(),i=this.height(),s=this.cornerRadius();t.beginPath(),s?C.drawRoundedRectPath(t,e,i,s):t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,e,i;return(i=(t=this.attrs.width)!==null&&t!==void 0?t:(e=this.image())===null||e===void 0?void 0:e.width)!==null&&i!==void 0?i:0}getHeight(){var t,e,i;return(i=(t=this.attrs.height)!==null&&t!==void 0?t:(e=this.image())===null||e===void 0?void 0:e.height)!==null&&i!==void 0?i:0}static fromURL(t,e,i=null){const s=C.createImageElement();s.onload=function(){const n=new rn({image:s});e(n)},s.onerror=i,s.crossOrigin="Anonymous",s.src=t}};mt.prototype.className="Image";mt.prototype._attrsAffectingSize=["image"];st(mt);m.addGetterSetter(mt,"cornerRadius",0,Je(4));m.addGetterSetter(mt,"image");m.addComponentsGetterSetter(mt,"crop",["x","y","width","height"]);m.addGetterSetter(mt,"cropX",0,x());m.addGetterSetter(mt,"cropY",0,x());m.addGetterSetter(mt,"cropWidth",0,x());m.addGetterSetter(mt,"cropHeight",0,x());const an=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],ta="Change.konva",ea="none",Si="up",Ti="right",vi="down",bi="left",ia=an.length;class Oi extends te{constructor(t){super(t),this.on("add.konva",function(e){this._addListeners(e.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){let e=this,i;const s=function(){e._sync()};for(i=0;i<ia;i++)t.on(an[i]+ta,s)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let t=this.getText(),e=this.getTag(),i,s,n,r,o,l,h;if(t&&e){switch(i=t.width(),s=t.height(),n=e.pointerDirection(),r=e.pointerWidth(),h=e.pointerHeight(),o=0,l=0,n){case Si:o=i/2,l=-1*h;break;case Ti:o=i+r,l=s/2;break;case vi:o=i/2,l=s+h;break;case bi:o=-1*r,l=s/2;break}e.setAttrs({x:-1*o,y:-1*l,width:i,height:s}),t.setAttrs({x:-1*o,y:-1*l})}}}Oi.prototype.className="Label";st(Oi);class Ut extends w{_sceneFunc(t){const e=this.width(),i=this.height(),s=this.pointerDirection(),n=this.pointerWidth(),r=this.pointerHeight(),o=this.cornerRadius();let l=0,h=0,c=0,d=0;typeof o=="number"?l=h=c=d=Math.min(o,e/2,i/2):(l=Math.min(o[0]||0,e/2,i/2),h=Math.min(o[1]||0,e/2,i/2),d=Math.min(o[2]||0,e/2,i/2),c=Math.min(o[3]||0,e/2,i/2)),t.beginPath(),t.moveTo(l,0),s===Si&&(t.lineTo((e-n)/2,0),t.lineTo(e/2,-1*r),t.lineTo((e+n)/2,0)),t.lineTo(e-h,0),t.arc(e-h,h,h,Math.PI*3/2,0,!1),s===Ti&&(t.lineTo(e,(i-r)/2),t.lineTo(e+n,i/2),t.lineTo(e,(i+r)/2)),t.lineTo(e,i-d),t.arc(e-d,i-d,d,0,Math.PI/2,!1),s===vi&&(t.lineTo((e+n)/2,i),t.lineTo(e/2,i+r),t.lineTo((e-n)/2,i)),t.lineTo(c,i),t.arc(c,i-c,c,Math.PI/2,Math.PI,!1),s===bi&&(t.lineTo(0,(i+r)/2),t.lineTo(-1*n,i/2),t.lineTo(0,(i-r)/2)),t.lineTo(0,l),t.arc(l,l,l,Math.PI,Math.PI*3/2,!1),t.closePath(),t.fillStrokeShape(this)}getSelfRect(){let t=0,e=0,i=this.pointerWidth(),s=this.pointerHeight(),n=this.pointerDirection(),r=this.width(),o=this.height();return n===Si?(e-=s,o+=s):n===vi?o+=s:n===bi?(t-=i*1.5,r+=i):n===Ti&&(r+=i*1.5),{x:t,y:e,width:r,height:o}}}Ut.prototype.className="Tag";st(Ut);m.addGetterSetter(Ut,"pointerDirection",ea);m.addGetterSetter(Ut,"pointerWidth",0,x());m.addGetterSetter(Ut,"pointerHeight",0,x());m.addGetterSetter(Ut,"cornerRadius",0,Je(4));class _e extends w{_sceneFunc(t){const e=this.cornerRadius(),i=this.width(),s=this.height();t.beginPath(),e?C.drawRoundedRectPath(t,i,s,e):t.rect(0,0,i,s),t.closePath(),t.fillStrokeShape(this)}}_e.prototype.className="Rect";st(_e);m.addGetterSetter(_e,"cornerRadius",0,Je(4));class Bt extends w{_sceneFunc(t){const e=this._getPoints(),i=this.radius(),s=this.sides(),n=this.cornerRadius();if(t.beginPath(),n)C.drawRoundedPolygonPath(t,e,s,i,n);else{t.moveTo(e[0].x,e[0].y);for(let r=1;r<e.length;r++)t.lineTo(e[r].x,e[r].y)}t.closePath(),t.fillStrokeShape(this)}_getPoints(){const t=this.attrs.sides,e=this.attrs.radius||0,i=[];for(let s=0;s<t;s++)i.push({x:e*Math.sin(s*2*Math.PI/t),y:-1*e*Math.cos(s*2*Math.PI/t)});return i}getSelfRect(){const t=this._getPoints();let e=t[0].x,i=t[0].x,s=t[0].y,n=t[0].y;return t.forEach(r=>{e=Math.min(e,r.x),i=Math.max(i,r.x),s=Math.min(s,r.y),n=Math.max(n,r.y)}),{x:e,y:s,width:i-e,height:n-s}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}Bt.prototype.className="RegularPolygon";Bt.prototype._centroid=!0;Bt.prototype._attrsAffectingSize=["radius"];st(Bt);m.addGetterSetter(Bt,"radius",0,x());m.addGetterSetter(Bt,"sides",0,x());m.addGetterSetter(Bt,"cornerRadius",0,Je(4));const ns=Math.PI*2;class $t extends w{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,ns,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),ns,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}$t.prototype.className="Ring";$t.prototype._centroid=!0;$t.prototype._attrsAffectingSize=["innerRadius","outerRadius"];st($t);m.addGetterSetter($t,"innerRadius",0,x());m.addGetterSetter($t,"outerRadius",0,x());class bt extends w{constructor(t){super(t),this._updated=!0,this.anim=new gt(()=>{const e=this._updated;return this._updated=!1,e}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){const e=this.animation(),i=this.frameIndex(),s=i*4,n=this.animations()[e],r=this.frameOffsets(),o=n[s+0],l=n[s+1],h=n[s+2],c=n[s+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,h,c),t.closePath(),t.fillStrokeShape(this)),d)if(r){const u=r[e],p=i*2;t.drawImage(d,o,l,h,c,u[p+0],u[p+1],h,c)}else t.drawImage(d,o,l,h,c,0,0,h,c)}_hitFunc(t){const e=this.animation(),i=this.frameIndex(),s=i*4,n=this.animations()[e],r=this.frameOffsets(),o=n[s+2],l=n[s+3];if(t.beginPath(),r){const h=r[e],c=i*2;t.rect(h[c+0],h[c+1],o,l)}else t.rect(0,0,o,l);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),e=this.animation(),i=this.animations(),s=i[e],n=s.length/4;t<n-1?this.frameIndex(t+1):this.frameIndex(0)}}bt.prototype.className="Sprite";st(bt);m.addGetterSetter(bt,"animation");m.addGetterSetter(bt,"animations");m.addGetterSetter(bt,"frameOffsets");m.addGetterSetter(bt,"image");m.addGetterSetter(bt,"frameIndex",0,x());m.addGetterSetter(bt,"frameRate",17,x());m.backCompat(bt,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Ht extends w{_sceneFunc(t){const e=this.innerRadius(),i=this.outerRadius(),s=this.numPoints();t.beginPath(),t.moveTo(0,0-i);for(let n=1;n<s*2;n++){const r=n%2===0?i:e,o=r*Math.sin(n*Math.PI/s),l=-1*r*Math.cos(n*Math.PI/s);t.lineTo(o,l)}t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}Ht.prototype.className="Star";Ht.prototype._centroid=!0;Ht.prototype._attrsAffectingSize=["innerRadius","outerRadius"];st(Ht);m.addGetterSetter(Ht,"numPoints",5,x());m.addGetterSetter(Ht,"innerRadius",0,x());m.addGetterSetter(Ht,"outerRadius",0,x());function Lt(a){return[...a].reduce((t,e,i,s)=>{if(new RegExp("\\p{Emoji}","u").test(e)){const n=s[i+1];n&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(n)?(t.push(e+n),s[i+1]=""):t.push(e)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(e+(s[i+1]||""))?t.push(e+s[i+1]):i>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(e)?t[t.length-1]+=e:e&&t.push(e);return t},[])}const jt="auto",sa="center",on="inherit",ae="justify",na="Change.konva",ra="2d",rs="-",ln="left",aa="text",oa="Text",la="top",ha="bottom",as="middle",hn="normal",ca="px ",Oe=" ",da="right",os="rtl",ua="word",ga="char",ls="none",ri="…",cn=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],fa=cn.length;function pa(a){return a.split(",").map(t=>{t=t.trim();const e=t.indexOf(" ")>=0,i=t.indexOf('"')>=0||t.indexOf("'")>=0;return e&&!i&&(t=`"${t}"`),t}).join(", ")}let Ge;function ai(){return Ge||(Ge=C.createCanvasElement().getContext(ra),Ge)}function ma(a){a.fillText(this._partialText,this._partialTextX,this._partialTextY)}function ya(a){a.setAttr("miterLimit",2),a.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Ca(a){return a=a||{},!a.fillLinearGradientColorStops&&!a.fillRadialGradientColorStops&&!a.fillPatternImage&&(a.fill=a.fill||"black"),a}class et extends w{constructor(t){super(Ca(t)),this._partialTextX=0,this._partialTextY=0;for(let e=0;e<fa;e++)this.on(cn[e]+na,this._setTextData);this._setTextData()}_sceneFunc(t){var e,i;const s=this.textArr,n=s.length;if(!this.text())return;let r=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,h=this.verticalAlign(),c=this.direction(),d=0,u=this.align(),p=this.getWidth(),f=this.letterSpacing(),y=this.charRenderFunc(),T=this.fill(),S=this.textDecoration(),v=this.underlineOffset(),b=S.indexOf("underline")!==-1,k=S.indexOf("line-through")!==-1,M;c=c===on?t.direction:c;let _=l/2,R=as;if(!E.legacyTextRendering){const A=this.measureSize("M");R="alphabetic";const I=(e=A.fontBoundingBoxAscent)!==null&&e!==void 0?e:A.actualBoundingBoxAscent,D=(i=A.fontBoundingBoxDescent)!==null&&i!==void 0?i:A.actualBoundingBoxDescent;_=(I-D)/2+l/2}for(c===os&&t.setAttr("direction",c),t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",R),t.setAttr("textAlign",ln),h===as?d=(this.getHeight()-n*l-r*2)/2:h===ha&&(d=this.getHeight()-n*l-r*2),t.translate(r,d+r),M=0;M<n;M++){let A=0,I=0;const D=s[M],N=D.text,G=D.width,W=D.lastInParagraph;if(t.save(),u===da?A+=p-G-r*2:u===sa&&(A+=(p-G-r*2)/2),b){t.save(),t.beginPath();const H=v??(E.legacyTextRendering?Math.round(o/2):Math.round(o/4)),L=A,j=_+I+H;t.moveTo(L,j);const B=u===ae&&!W?p-r*2:G;t.lineTo(L+Math.round(B),j),t.lineWidth=o/15;const U=this._getLinearGradient();t.strokeStyle=U||T,t.stroke(),t.restore()}const F=A;if(c!==os&&(f!==0||u===ae||y)){const H=N.split(" ").length-1,L=Lt(N);for(let j=0;j<L.length;j++){const B=L[j];if(B===" "&&!W&&u===ae&&(A+=(p-r*2-G)/H),this._partialTextX=A,this._partialTextY=_+I,this._partialText=B,y){t.save();const q=s.slice(0,M).reduce((nt,lt)=>nt+Lt(lt.text).length,0),K=j+q;y({char:B,index:K,x:A,y:_+I,lineIndex:M,column:j,isLastInLine:W,width:this.measureSize(B).width,context:t})}t.fillStrokeShape(this),y&&t.restore(),A+=this.measureSize(B).width+f}}else f!==0&&t.setAttr("letterSpacing",`${f}px`),this._partialTextX=A,this._partialTextY=_+I,this._partialText=N,t.fillStrokeShape(this);if(k){t.save(),t.beginPath();const H=E.legacyTextRendering?0:-Math.round(o/4),L=F;t.moveTo(L,_+I+H);const j=u===ae&&!W?p-r*2:G;t.lineTo(L+Math.round(j),_+I+H),t.lineWidth=o/15;const B=this._getLinearGradient();t.strokeStyle=B||T,t.stroke(),t.restore()}t.restore(),n>1&&(_+=l)}}_hitFunc(t){const e=this.getWidth(),i=this.getHeight();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}setText(t){const e=C._isString(t)?t:t==null?"":t+"";return this._setAttr(aa,e),this}getWidth(){return this.attrs.width===jt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===jt||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return C.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var e,i,s,n,r,o,l,h,c,d,u;let p=ai(),f=this.fontSize(),y;p.save(),p.font=this._getContextFont(),y=p.measureText(t),p.restore();const T=f/100;return{actualBoundingBoxAscent:(e=y.actualBoundingBoxAscent)!==null&&e!==void 0?e:71.58203125*T,actualBoundingBoxDescent:(i=y.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(s=y.actualBoundingBoxLeft)!==null&&s!==void 0?s:-7.421875*T,actualBoundingBoxRight:(n=y.actualBoundingBoxRight)!==null&&n!==void 0?n:75.732421875*T,alphabeticBaseline:(r=y.alphabeticBaseline)!==null&&r!==void 0?r:0,emHeightAscent:(o=y.emHeightAscent)!==null&&o!==void 0?o:100*T,emHeightDescent:(l=y.emHeightDescent)!==null&&l!==void 0?l:-20*T,fontBoundingBoxAscent:(h=y.fontBoundingBoxAscent)!==null&&h!==void 0?h:91*T,fontBoundingBoxDescent:(c=y.fontBoundingBoxDescent)!==null&&c!==void 0?c:21*T,hangingBaseline:(d=y.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*T,ideographicBaseline:(u=y.ideographicBaseline)!==null&&u!==void 0?u:-21*T,width:y.width,height:f}}_getContextFont(){return this.fontStyle()+Oe+this.fontVariant()+Oe+(this.fontSize()+ca)+pa(this.fontFamily())}_addTextLine(t){this.align()===ae&&(t=t.trim());const i=this._getTextWidth(t);return this.textArr.push({text:t,width:i,lastInParagraph:!1})}_getTextWidth(t){const e=this.letterSpacing(),i=t.length;return ai().measureText(t).width+e*i}_setTextData(){let t=this.text().split(`
15
- `),e=+this.fontSize(),i=0,s=this.lineHeight()*e,n=this.attrs.width,r=this.attrs.height,o=n!==jt&&n!==void 0,l=r!==jt&&r!==void 0,h=this.padding(),c=n-h*2,d=r-h*2,u=0,p=this.wrap(),f=p!==ls,y=p!==ga&&f,T=this.ellipsis();this.textArr=[],ai().font=this._getContextFont();const S=T?this._getTextWidth(ri):0;for(let v=0,b=t.length;v<b;++v){let k=t[v],M=this._getTextWidth(k);if(o&&M>c)for(;k.length>0;){let _=0,R=Lt(k).length,A="",I=0;for(;_<R;){const D=_+R>>>1,N=Lt(k),G=N.slice(0,D+1).join(""),W=this._getTextWidth(G);(T&&l&&u+s>d?W+S:W)<=c?(_=D+1,A=G,I=W):R=D}if(A){if(y){const G=Lt(k),W=Lt(A),F=G[W.length],H=F===Oe||F===rs;let L;if(H&&I<=c)L=W.length;else{const j=W.lastIndexOf(Oe),B=W.lastIndexOf(rs);L=Math.max(j,B)+1}L>0&&(_=L,A=G.slice(0,_).join(""),I=this._getTextWidth(A))}if(A=A.trimRight(),this._addTextLine(A),i=Math.max(i,I),u+=s,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(k=Lt(k).slice(_).join("").trimLeft(),k.length>0&&(M=this._getTextWidth(k),M<=c)){this._addTextLine(k),u+=s,i=Math.max(i,M);break}}else break}else this._addTextLine(k),u+=s,i=Math.max(i,M),this._shouldHandleEllipsis(u)&&v<b-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),l&&u+s>d)break}this.textHeight=e,this.textWidth=i}_shouldHandleEllipsis(t){const e=+this.fontSize(),i=this.lineHeight()*e,s=this.attrs.height,n=s!==jt&&s!==void 0,r=this.padding(),o=s-r*2;return!(this.wrap()!==ls)||n&&t+i>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,e=t!==jt&&t!==void 0,i=this.padding(),s=t-i*2,n=this.ellipsis(),r=this.textArr[this.textArr.length-1];!r||!n||(e&&(this._getTextWidth(r.text+ri)<s||(r.text=r.text.slice(0,r.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(r.text+ri))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const t=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,e=this.hasShadow();return t&&e?!0:super._useBufferCanvas()}}et.prototype._fillFunc=ma;et.prototype._strokeFunc=ya;et.prototype.className=oa;et.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];st(et);m.overWriteSetter(et,"width",Li());m.overWriteSetter(et,"height",Li());m.addGetterSetter(et,"direction",on);m.addGetterSetter(et,"fontFamily","Arial");m.addGetterSetter(et,"fontSize",12,x());m.addGetterSetter(et,"fontStyle",hn);m.addGetterSetter(et,"fontVariant",hn);m.addGetterSetter(et,"padding",0,x());m.addGetterSetter(et,"align",ln);m.addGetterSetter(et,"verticalAlign",la);m.addGetterSetter(et,"lineHeight",1,x());m.addGetterSetter(et,"wrap",ua);m.addGetterSetter(et,"ellipsis",!1,pt());m.addGetterSetter(et,"letterSpacing",0,x());m.addGetterSetter(et,"text","",Wt());m.addGetterSetter(et,"textDecoration","");m.addGetterSetter(et,"underlineOffset",void 0,x());m.addGetterSetter(et,"charRenderFunc",void 0);const Sa="",dn="normal";function un(a){a.fillText(this.partialText,0,0)}function gn(a){a.strokeText(this.partialText,0,0)}class rt extends w{constructor(t){super(t),this.dummyCanvas=C.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return tt.getPathLength(this.dataArray)}_getPointAtLength(t){if(!this.attrs.data)return null;const e=this.pathLength;return t>e?null:tt.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=tt.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();const e=this.textDecoration(),i=this.fill(),s=this.fontSize(),n=this.glyphInfo,r=e.indexOf("underline")!==-1,o=e.indexOf("line-through")!==-1;r&&t.beginPath();for(let l=0;l<n.length;l++){t.save();const h=n[l].p0;t.translate(h.x,h.y),t.rotate(n[l].rotation),this.partialText=n[l].text,t.fillStrokeShape(this),r&&(l===0&&t.moveTo(0,s/2+1),t.lineTo(n[l].width,s/2+1)),t.restore()}if(r&&(t.strokeStyle=i,t.lineWidth=s/20,t.stroke()),o){t.beginPath();for(let l=0;l<n.length;l++){t.save();const h=n[l].p0;t.translate(h.x,h.y),t.rotate(n[l].rotation),l===0&&t.moveTo(0,0),t.lineTo(n[l].width,0),t.restore()}t.strokeStyle=i,t.lineWidth=s/20,t.stroke()}t.restore()}_hitFunc(t){t.beginPath();const e=this.glyphInfo;if(e.length>=1){const i=e[0].p0;t.moveTo(i.x,i.y)}for(let i=0;i<e.length;i++){const s=e[i].p1;t.lineTo(s.x,s.y)}t.setAttr("lineWidth",this.fontSize()),t.setAttr("strokeStyle",this.colorKey),t.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return C.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(t){return et.prototype.setText.call(this,t)}_getContextFont(){return et.prototype._getContextFont.call(this)}_getTextSize(t){const i=this.dummyCanvas.getContext("2d");i.save(),i.font=this._getContextFont();const s=i.measureText(t);return i.restore(),{width:s.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const t=Lt(this.text()),e=[];let i=0;for(let d=0;d<t.length;d++)e.push({char:t[d],width:this._getTextSize(t[d]).width}),i+=e[d].width;const{height:s}=this._getTextSize(this.attrs.text);if(this.textWidth=i,this.textHeight=s,this.glyphInfo=[],!this.attrs.data)return null;const n=this.letterSpacing(),r=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*n,0);let h=0;r==="center"&&(h=Math.max(0,this.pathLength/2-l/2)),r==="right"&&(h=Math.max(0,this.pathLength-l));let c=h;for(let d=0;d<e.length;d++){const u=this._getPointAtLength(c);if(!u)return;const p=e[d].char;let f=e[d].width+n;if(p===" "&&r==="justify"){const k=this.text().split(" ").length-1;f+=(this.pathLength-l)/k}const y=this._getPointAtLength(c+f);if(!y)return;const T=tt.getLineLength(u.x,u.y,y.x,y.y);let S=0;if(o)try{S=o(e[d-1].char,p)*this.fontSize()}catch{S=0}u.x+=S,y.x+=S,this.textWidth+=S;const v=tt.getPointOnLine(S+T/2,u.x,u.y,y.x,y.y),b=Math.atan2(y.y-u.y,y.x-u.x);this.glyphInfo.push({transposeX:v.x,transposeY:v.y,text:t[d],rotation:b,p0:u,p1:y,width:T}),c+=f}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(h){t.push(h.p0.x),t.push(h.p0.y),t.push(h.p1.x),t.push(h.p1.y)});let e=t[0]||0,i=t[0]||0,s=t[1]||0,n=t[1]||0,r,o;for(let h=0;h<t.length/2;h++)r=t[h*2],o=t[h*2+1],e=Math.min(e,r),i=Math.max(i,r),s=Math.min(s,o),n=Math.max(n,o);const l=this.fontSize();return{x:e-l/2,y:s-l/2,width:i-e+l,height:n-s+l}}destroy(){return C.releaseCanvas(this.dummyCanvas),super.destroy()}}rt.prototype._fillFunc=un;rt.prototype._strokeFunc=gn;rt.prototype._fillFuncHit=un;rt.prototype._strokeFuncHit=gn;rt.prototype.className="TextPath";rt.prototype._attrsAffectingSize=["text","fontSize","data"];st(rt);m.addGetterSetter(rt,"data");m.addGetterSetter(rt,"fontFamily","Arial");m.addGetterSetter(rt,"fontSize",12,x());m.addGetterSetter(rt,"fontStyle",dn);m.addGetterSetter(rt,"align","left");m.addGetterSetter(rt,"letterSpacing",0,x());m.addGetterSetter(rt,"textBaseline","middle");m.addGetterSetter(rt,"fontVariant",dn);m.addGetterSetter(rt,"text",Sa);m.addGetterSetter(rt,"textDecoration","");m.addGetterSetter(rt,"kerningFunc",void 0);const fn="tr-konva",Ta=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(a=>a+`.${fn}`).join(" "),hs="nodesRect",va=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],ba={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},ka="ontouchstart"in E._global;function wa(a,t,e){if(a==="rotater")return e;t+=C.degToRad(ba[a]||0);const i=(C.radToDeg(t)%360+360)%360;return C._inRange(i,315+22.5,360)||C._inRange(i,0,22.5)?"ns-resize":C._inRange(i,45-22.5,45+22.5)?"nesw-resize":C._inRange(i,90-22.5,90+22.5)?"ew-resize":C._inRange(i,135-22.5,135+22.5)?"nwse-resize":C._inRange(i,180-22.5,180+22.5)?"ns-resize":C._inRange(i,225-22.5,225+22.5)?"nesw-resize":C._inRange(i,270-22.5,270+22.5)?"ew-resize":C._inRange(i,315-22.5,315+22.5)?"nwse-resize":(C.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}const Ke=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function _a(a){return{x:a.x+a.width/2*Math.cos(a.rotation)+a.height/2*Math.sin(-a.rotation),y:a.y+a.height/2*Math.cos(a.rotation)+a.width/2*Math.sin(a.rotation)}}function pn(a,t,e){const i=e.x+(a.x-e.x)*Math.cos(t)-(a.y-e.y)*Math.sin(t),s=e.y+(a.x-e.x)*Math.sin(t)+(a.y-e.y)*Math.cos(t);return{...a,rotation:a.rotation+t,x:i,y:s}}function Pa(a,t){const e=_a(a);return pn(a,t,e)}function xa(a,t,e){let i=t;for(let s=0;s<a.length;s++){const n=E.getAngle(a[s]),r=Math.abs(n-t)%(Math.PI*2);Math.min(r,Math.PI*2-r)<e&&(i=n)}return i}let ki=0;class Y extends te{constructor(t){super(t),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(Ta,this.update),this.getNode()&&this.update()}attachTo(t){return this.setNode(t),this}setNode(t){return C.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([t])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return fn+this._id}setNodes(t=[]){this._nodes&&this._nodes.length&&this.detach();const e=t.filter(s=>s.isAncestorOf(this)?(C.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=e,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(s=>{const n=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(s._attrsAffectingSize.length){const r=s._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");s.on(r,n)}s.on(va.map(r=>r+`.${this._getEventNamespace()}`).join(" "),n),s.on(`absoluteTransformChange.${this._getEventNamespace()}`,n),this._proxyDrag(s)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let e;t.on(`dragstart.${this._getEventNamespace()}`,i=>{e=t.getAbsolutePosition(),!this.isDragging()&&t!==this.findOne(".back")&&this.startDrag(i,!1)}),t.on(`dragmove.${this._getEventNamespace()}`,i=>{if(!e)return;const s=t.getAbsolutePosition(),n=s.x-e.x,r=s.y-e.y;this.nodes().forEach(o=>{if(o===t||o.isDragging())return;const l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+n,y:l.y+r}),o.startDrag(i)}),e=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(hs),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(hs,this.__getNodeRect)}__getNodeShape(t,e=this.rotation(),i){const s=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),n=t.getAbsoluteScale(i),r=t.getAbsolutePosition(i),o=s.x*n.x-t.offsetX()*n.x,l=s.y*n.y-t.offsetY()*n.y,h=(E.getAngle(t.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),c={x:r.x+o*Math.cos(h)+l*Math.sin(-h),y:r.y+l*Math.cos(h)+o*Math.sin(h),width:s.width*n.x,height:s.height*n.y,rotation:h};return pn(c,-E.getAngle(e),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const e=[];this.nodes().map(h=>{const c=h.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:c.x,y:c.y},{x:c.x+c.width,y:c.y},{x:c.x+c.width,y:c.y+c.height},{x:c.x,y:c.y+c.height}],u=h.getAbsoluteTransform();d.forEach(function(p){const f=u.point(p);e.push(f)})});const i=new dt;i.rotate(-E.getAngle(this.rotation()));let s=1/0,n=1/0,r=-1/0,o=-1/0;e.forEach(function(h){const c=i.point(h);s===void 0&&(s=r=c.x,n=o=c.y),s=Math.min(s,c.x),n=Math.min(n,c.y),r=Math.max(r,c.x),o=Math.max(o,c.y)}),i.invert();const l=i.point({x:s,y:n});return{x:l.x,y:l.y,width:r-s,height:o-n,rotation:E.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Ke.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater")}_createAnchor(t){const e=new _e({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:ka?10:"auto"}),i=this;e.on("mousedown touchstart",function(s){i._handleMouseDown(s)}),e.on("dragstart",s=>{e.stopDrag(),s.cancelBubble=!0}),e.on("dragend",s=>{s.cancelBubble=!0}),e.on("mouseenter",()=>{const s=E.getAngle(this.rotation()),n=this.rotateAnchorCursor(),r=wa(t,s,n);e.getStage().content&&(e.getStage().content.style.cursor=r),this._cursorChange=!0}),e.on("mouseout",()=>{e.getStage().content&&(e.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(e)}_createBack(){const t=new w({name:"back",width:0,height:0,sceneFunc(e,i){const s=i.getParent(),n=s.padding(),r=i.width(),o=i.height();if(e.beginPath(),e.rect(-n,-n,r+n*2,o+n*2),s.rotateEnabled()&&s.rotateLineVisible()){const l=s.rotateAnchorAngle(),h=s.rotateAnchorOffset(),c=C.degToRad(l),d=Math.sin(c),u=-Math.cos(c),p=r/2,f=o/2;let y=1/0;u<0?y=Math.min(y,-f/u):u>0&&(y=Math.min(y,(o-f)/u)),d<0?y=Math.min(y,-p/d):d>0&&(y=Math.min(y,(r-p)/d));const T=p+d*y,S=f+u*y,v=C._sign(o),b=T+d*h*v,k=S+u*h*v;e.moveTo(T,S),e.lineTo(b,k)}e.fillStrokeShape(i)},hitFunc:(e,i)=>{if(!this.shouldOverdrawWholeArea())return;const s=this.padding();e.beginPath(),e.rect(-s,-s,i.width()+s*2,i.height()+s*2),e.fillStrokeShape(i)}});this.add(t),this._proxyDrag(t),t.on("dragstart",e=>{e.cancelBubble=!0}),t.on("dragmove",e=>{e.cancelBubble=!0}),t.on("dragend",e=>{e.cancelBubble=!0}),this.on("dragmove",e=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const e=this._getNodeRect(),i=e.width,s=e.height,n=Math.sqrt(Math.pow(i,2)+Math.pow(s,2));this.sin=Math.abs(s/n),this.cos=Math.abs(i/n),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const r=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-r.x,y:o.y-r.y},ki++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(l=>{l._fire("transformstart",{evt:t.evt,target:l})})}_handleMouseMove(t){let e,i,s;const n=this.findOne("."+this._movingAnchorName),r=n.getStage();r.setPointersPositions(t);const o=r.getPointerPosition();let l={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const h=n.getAbsolutePosition();this.anchorDragBoundFunc()&&(l=this.anchorDragBoundFunc()(h,l,t)),n.setAbsolutePosition(l);const c=n.getAbsolutePosition();if(h.x===c.x&&h.y===c.y)return;if(this._movingAnchorName==="rotater"){const v=this._getNodeRect();e=n.x()-v.width/2,i=-n.y()+v.height/2;const b=E.getAngle(this.rotateAnchorAngle());let k=Math.atan2(-i,e)+Math.PI/2-b;v.height<0&&(k-=Math.PI);const _=E.getAngle(this.rotation())+k,R=E.getAngle(this.rotationSnapTolerance()),I=xa(this.rotationSnaps(),_,R)-v.rotation,D=Pa(v,I);this._fitNodesInto(D,t);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!t.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||t.shiftKey;let p=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(u){const v=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};s=Math.sqrt(Math.pow(v.x-n.x(),2)+Math.pow(v.y-n.y(),2));const b=this.findOne(".top-left").x()>v.x?-1:1,k=this.findOne(".top-left").y()>v.y?-1:1;e=s*this.cos*b,i=s*this.sin*k,this.findOne(".top-left").x(v.x-e),this.findOne(".top-left").y(v.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(n.y());else if(this._movingAnchorName==="top-right"){if(u){const v=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};s=Math.sqrt(Math.pow(n.x()-v.x,2)+Math.pow(v.y-n.y(),2));const b=this.findOne(".top-right").x()<v.x?-1:1,k=this.findOne(".top-right").y()>v.y?-1:1;e=s*this.cos*b,i=s*this.sin*k,this.findOne(".top-right").x(v.x+e),this.findOne(".top-right").y(v.y-i)}var f=n.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(n.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(n.x());else if(this._movingAnchorName==="bottom-left"){if(u){const v=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};s=Math.sqrt(Math.pow(v.x-n.x(),2)+Math.pow(n.y()-v.y,2));const b=v.x<n.x()?-1:1,k=n.y()<v.y?-1:1;e=s*this.cos*b,i=s*this.sin*k,n.x(v.x-e),n.y(v.y+i)}f=n.position(),this.findOne(".top-left").x(f.x),this.findOne(".bottom-right").y(f.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(n.y());else if(this._movingAnchorName==="bottom-right"){if(u){const v=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};s=Math.sqrt(Math.pow(n.x()-v.x,2)+Math.pow(n.y()-v.y,2));const b=this.findOne(".bottom-right").x()<v.x?-1:1,k=this.findOne(".bottom-right").y()<v.y?-1:1;e=s*this.cos*b,i=s*this.sin*k,this.findOne(".bottom-right").x(v.x+e),this.findOne(".bottom-right").y(v.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(p=this.centeredScaling()||t.altKey,p){const v=this.findOne(".top-left"),b=this.findOne(".bottom-right"),k=v.x(),M=v.y(),_=this.getWidth()-b.x(),R=this.getHeight()-b.y();b.move({x:-k,y:-M}),v.move({x:_,y:R})}const y=this.findOne(".top-left").getAbsolutePosition();e=y.x,i=y.y;const T=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),S=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:e,y:i,width:T,height:S,rotation:E.getAngle(this.rotation())},t)}_handleMouseUp(t){this._removeEvents(t)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(t){var e;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const i=this.getNode();ki--,this._fire("transformend",{evt:t,target:i}),(e=this.getLayer())===null||e===void 0||e.batchDraw(),i&&this._nodes.forEach(s=>{var n;s._fire("transformend",{evt:t,target:s}),(n=s.getLayer())===null||n===void 0||n.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,e){const i=this._getNodeRect(),s=1;if(C._inRange(t.width,-this.padding()*2-s,s)){this.update();return}if(C._inRange(t.height,-this.padding()*2-s,s)){this.update();return}const n=new dt;if(n.rotate(E.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const u=n.point({x:-this.padding()*2,y:0});t.x+=u.x,t.y+=u.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const u=n.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const u=n.point({x:0,y:-this.padding()*2});t.x+=u.x,t.y+=u.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const u=n.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const u=this.boundBoxFunc()(i,t);u?t=u:C.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const r=1e7,o=new dt;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/r,i.height/r);const l=new dt,h=t.width/r,c=t.height/r;this.flipEnabled()===!1?(l.translate(t.x,t.y),l.rotate(t.rotation),l.translate(t.width<0?t.width:0,t.height<0?t.height:0),l.scale(Math.abs(h),Math.abs(c))):(l.translate(t.x,t.y),l.rotate(t.rotation),l.scale(h,c));const d=l.multiply(o.invert());this._nodes.forEach(u=>{var p;if(!u.getStage())return;const f=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const T=new dt;T.multiply(f.copy().invert()).multiply(d).multiply(f).multiply(y);const S=T.decompose();u.setAttrs(S),(p=u.getLayer())===null||p===void 0||p.batchDraw()}),this.rotation(C._getRotation(t.rotation)),this._nodes.forEach(u=>{this._fire("transform",{evt:e,target:u}),u._fire("transform",{evt:e,target:u})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,e){this.findOne(t).setAttrs(e)}update(){var t;const e=this._getNodeRect();this.rotation(C._getRotation(e.rotation));const i=e.width,s=e.height,n=this.enabledAnchors(),r=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),h=this.find("._anchor");h.forEach(_=>{_.setAttrs({width:l,height:l,offsetX:l/2,offsetY:l/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:l/2+o,offsetY:l/2+o,visible:r&&n.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:r&&n.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:r&&n.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:s/2,offsetX:l/2+o,visible:r&&n.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:s/2,offsetX:l/2-o,visible:r&&n.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:s,offsetX:l/2+o,offsetY:l/2-o,visible:r&&n.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:s,offsetY:l/2-o,visible:r&&n.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:s,offsetX:l/2-o,offsetY:l/2-o,visible:r&&n.indexOf("bottom-right")>=0});const c=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=C.degToRad(c),p=Math.sin(u),f=-Math.cos(u),y=i/2,T=s/2;let S=1/0;f<0?S=Math.min(S,-T/f):f>0&&(S=Math.min(S,(s-T)/f)),p<0?S=Math.min(S,-y/p):p>0&&(S=Math.min(S,(i-y)/p));const v=y+p*S,b=T+f*S,k=C._sign(s);this._batchChangeChild(".rotater",{x:v+p*d*k,y:b+f*d*k-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:s,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(_=>_.draggable()),x:0,y:0});const M=this.anchorStyleFunc();M&&h.forEach(_=>{M(_)}),(t=this.getLayer())===null||t===void 0||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),te.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return P.prototype.toObject.call(this)}clone(t){return P.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}Y.isTransforming=()=>ki>0;function Aa(a){return a instanceof Array||C.warn("enabledAnchors value should be an array"),a instanceof Array&&a.forEach(function(t){Ke.indexOf(t)===-1&&C.warn("Unknown anchor name: "+t+". Available names are: "+Ke.join(", "))}),a||[]}Y.prototype.className="Transformer";st(Y);m.addGetterSetter(Y,"enabledAnchors",Ke,Aa);m.addGetterSetter(Y,"flipEnabled",!0,pt());m.addGetterSetter(Y,"resizeEnabled",!0);m.addGetterSetter(Y,"anchorSize",10,x());m.addGetterSetter(Y,"rotateEnabled",!0);m.addGetterSetter(Y,"rotateLineVisible",!0);m.addGetterSetter(Y,"rotationSnaps",[]);m.addGetterSetter(Y,"rotateAnchorOffset",50,x());m.addGetterSetter(Y,"rotateAnchorAngle",0,x());m.addGetterSetter(Y,"rotateAnchorCursor","crosshair");m.addGetterSetter(Y,"rotationSnapTolerance",5,x());m.addGetterSetter(Y,"borderEnabled",!0);m.addGetterSetter(Y,"anchorStroke","rgb(0, 161, 255)");m.addGetterSetter(Y,"anchorStrokeWidth",1,x());m.addGetterSetter(Y,"anchorFill","white");m.addGetterSetter(Y,"anchorCornerRadius",0,x());m.addGetterSetter(Y,"borderStroke","rgb(0, 161, 255)");m.addGetterSetter(Y,"borderStrokeWidth",1,x());m.addGetterSetter(Y,"borderDash");m.addGetterSetter(Y,"keepRatio",!0);m.addGetterSetter(Y,"shiftBehavior","default");m.addGetterSetter(Y,"centeredScaling",!1);m.addGetterSetter(Y,"ignoreStroke",!1);m.addGetterSetter(Y,"padding",0,x());m.addGetterSetter(Y,"nodes");m.addGetterSetter(Y,"node");m.addGetterSetter(Y,"boundBoxFunc");m.addGetterSetter(Y,"anchorDragBoundFunc");m.addGetterSetter(Y,"anchorStyleFunc");m.addGetterSetter(Y,"shouldOverdrawWholeArea",!1);m.addGetterSetter(Y,"useSingleNodeRotation",!0);m.backCompat(Y,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Et extends w{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,E.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}Et.prototype.className="Wedge";Et.prototype._centroid=!0;Et.prototype._attrsAffectingSize=["radius"];st(Et);m.addGetterSetter(Et,"radius",0,x());m.addGetterSetter(Et,"angle",0,x());m.addGetterSetter(Et,"clockwise",!1);m.backCompat(Et,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function cs(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Ea=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],Ia=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function Ma(a,t){const e=a.data,i=a.width,s=a.height;let n,r,o,l,h,c,d,u,p,f,y,T,S,v,b,k,M,_,R,A;const I=t+t+1,D=i-1,N=s-1,G=t+1,W=G*(G+1)/2,F=new cs,H=Ea[t],L=Ia[t];let j=null,B=F,U=null,q=null;for(let K=1;K<I;K++)B=B.next=new cs,K===G&&(j=B);B.next=F,o=r=0;for(let K=0;K<s;K++){T=S=v=b=l=h=c=d=0,u=G*(k=e[r]),p=G*(M=e[r+1]),f=G*(_=e[r+2]),y=G*(R=e[r+3]),l+=W*k,h+=W*M,c+=W*_,d+=W*R,B=F;for(let nt=0;nt<G;nt++)B.r=k,B.g=M,B.b=_,B.a=R,B=B.next;for(let nt=1;nt<G;nt++)n=r+((D<nt?D:nt)<<2),l+=(B.r=k=e[n])*(A=G-nt),h+=(B.g=M=e[n+1])*A,c+=(B.b=_=e[n+2])*A,d+=(B.a=R=e[n+3])*A,T+=k,S+=M,v+=_,b+=R,B=B.next;U=F,q=j;for(let nt=0;nt<i;nt++)e[r+3]=R=d*H>>L,R!==0?(R=255/R,e[r]=(l*H>>L)*R,e[r+1]=(h*H>>L)*R,e[r+2]=(c*H>>L)*R):e[r]=e[r+1]=e[r+2]=0,l-=u,h-=p,c-=f,d-=y,u-=U.r,p-=U.g,f-=U.b,y-=U.a,n=o+((n=nt+t+1)<D?n:D)<<2,T+=U.r=e[n],S+=U.g=e[n+1],v+=U.b=e[n+2],b+=U.a=e[n+3],l+=T,h+=S,c+=v,d+=b,U=U.next,u+=k=q.r,p+=M=q.g,f+=_=q.b,y+=R=q.a,T-=k,S-=M,v-=_,b-=R,q=q.next,r+=4;o+=i}for(let K=0;K<i;K++){S=v=b=T=h=c=d=l=0,r=K<<2,u=G*(k=e[r]),p=G*(M=e[r+1]),f=G*(_=e[r+2]),y=G*(R=e[r+3]),l+=W*k,h+=W*M,c+=W*_,d+=W*R,B=F;for(let lt=0;lt<G;lt++)B.r=k,B.g=M,B.b=_,B.a=R,B=B.next;let nt=i;for(let lt=1;lt<=t;lt++)r=nt+K<<2,l+=(B.r=k=e[r])*(A=G-lt),h+=(B.g=M=e[r+1])*A,c+=(B.b=_=e[r+2])*A,d+=(B.a=R=e[r+3])*A,T+=k,S+=M,v+=_,b+=R,B=B.next,lt<N&&(nt+=i);r=K,U=F,q=j;for(let lt=0;lt<s;lt++)n=r<<2,e[n+3]=R=d*H>>L,R>0?(R=255/R,e[n]=(l*H>>L)*R,e[n+1]=(h*H>>L)*R,e[n+2]=(c*H>>L)*R):e[n]=e[n+1]=e[n+2]=0,l-=u,h-=p,c-=f,d-=y,u-=U.r,p-=U.g,f-=U.b,y-=U.a,n=K+((n=lt+G)<N?n:N)*i<<2,l+=T+=U.r=e[n],h+=S+=U.g=e[n+1],c+=v+=U.b=e[n+2],d+=b+=U.a=e[n+3],U=U.next,u+=k=q.r,p+=M=q.g,f+=_=q.b,y+=R=q.a,T-=k,S-=M,v-=_,b-=R,q=q.next,r+=i}}const La=function(t){const e=Math.round(this.blurRadius());e>0&&Ma(t,e)};m.addGetterSetter(P,"blurRadius",0,x(),m.afterSetFilter);const Da=function(a){const t=this.brightness()*255,e=a.data,i=e.length;for(let s=0;s<i;s+=4)e[s]+=t,e[s+1]+=t,e[s+2]+=t};m.addGetterSetter(P,"brightness",0,x(),m.afterSetFilter);const Ra=function(a){const t=this.brightness(),e=a.data,i=e.length;for(let s=0;s<i;s+=4)e[s]=Math.min(255,e[s]*t),e[s+1]=Math.min(255,e[s+1]*t),e[s+2]=Math.min(255,e[s+2]*t)},Oa=function(a){const t=Math.pow((this.contrast()+100)/100,2),e=a.data,i=e.length;let s=150,n=150,r=150;for(let o=0;o<i;o+=4)s=e[o],n=e[o+1],r=e[o+2],s/=255,s-=.5,s*=t,s+=.5,s*=255,n/=255,n-=.5,n*=t,n+=.5,n*=255,r/=255,r-=.5,r*=t,r+=.5,r*=255,s=s<0?0:s>255?255:s,n=n<0?0:n>255?255:n,r=r<0?0:r>255?255:r,e[o]=s,e[o+1]=n,e[o+2]=r};m.addGetterSetter(P,"contrast",0,x(),m.afterSetFilter);const Ga=function(a){var t,e,i,s,n,r,o,l,h;const c=a.data,d=a.width,u=a.height,p=Math.min(1,Math.max(0,(e=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&e!==void 0?e:.5)),f=Math.min(1,Math.max(0,(s=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&s!==void 0?s:.5)),T=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(r=(n=this.embossDirection)===null||n===void 0?void 0:n.call(this))!==null&&r!==void 0?r:"top-left"])!==null&&o!==void 0?o:315,S=!!((h=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&h!==void 0&&h),v=p*10,b=f*255,k=T*Math.PI/180,M=Math.cos(k),_=Math.sin(k),R=128/1020*v,A=new Uint8ClampedArray(c),I=new Float32Array(d*u);for(let F=0,H=0;H<c.length;H+=4,F++)I[F]=.2126*A[H]+.7152*A[H+1]+.0722*A[H+2];const D=[-1,0,1,-2,0,2,-1,0,1],N=[-1,-2,-1,0,0,0,1,2,1],G=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],W=F=>F<0?0:F>255?255:F;for(let F=1;F<u-1;F++)for(let H=1;H<d-1;H++){const L=F*d+H;let j=0,B=0;j+=I[L+G[0]]*D[0],B+=I[L+G[0]]*N[0],j+=I[L+G[1]]*D[1],B+=I[L+G[1]]*N[1],j+=I[L+G[2]]*D[2],B+=I[L+G[2]]*N[2],j+=I[L+G[3]]*D[3],B+=I[L+G[3]]*N[3],j+=I[L+G[5]]*D[5],B+=I[L+G[5]]*N[5],j+=I[L+G[6]]*D[6],B+=I[L+G[6]]*N[6],j+=I[L+G[7]]*D[7],B+=I[L+G[7]]*N[7],j+=I[L+G[8]]*D[8],B+=I[L+G[8]]*N[8];const U=M*j+_*B,q=W(b+U*R),K=L*4;if(S){const nt=q-b;c[K]=W(A[K]+nt),c[K+1]=W(A[K+1]+nt),c[K+2]=W(A[K+2]+nt),c[K+3]=A[K+3]}else c[K]=c[K+1]=c[K+2]=q,c[K+3]=A[K+3]}for(let F=0;F<d;F++){let H=F*4,L=((u-1)*d+F)*4;c[H]=A[H],c[H+1]=A[H+1],c[H+2]=A[H+2],c[H+3]=A[H+3],c[L]=A[L],c[L+1]=A[L+1],c[L+2]=A[L+2],c[L+3]=A[L+3]}for(let F=1;F<u-1;F++){let H=F*d*4,L=(F*d+(d-1))*4;c[H]=A[H],c[H+1]=A[H+1],c[H+2]=A[H+2],c[H+3]=A[H+3],c[L]=A[L],c[L+1]=A[L+1],c[L+2]=A[L+2],c[L+3]=A[L+3]}return a};m.addGetterSetter(P,"embossStrength",.5,x(),m.afterSetFilter);m.addGetterSetter(P,"embossWhiteLevel",.5,x(),m.afterSetFilter);m.addGetterSetter(P,"embossDirection","top-left",void 0,m.afterSetFilter);m.addGetterSetter(P,"embossBlend",!1,void 0,m.afterSetFilter);function oi(a,t,e,i,s){const n=e-t,r=s-i;if(n===0)return i+r/2;if(r===0)return i;let o=(a-t)/n;return o=r*o+i,o}const Ba=function(a){const t=a.data,e=t.length;let i=t[0],s=i,n,r=t[1],o=r,l,h=t[2],c=h,d;const u=this.enhance();if(u===0)return;for(let b=0;b<e;b+=4)n=t[b+0],n<i?i=n:n>s&&(s=n),l=t[b+1],l<r?r=l:l>o&&(o=l),d=t[b+2],d<h?h=d:d>c&&(c=d);s===i&&(s=255,i=0),o===r&&(o=255,r=0),c===h&&(c=255,h=0);let p,f,y,T,S,v;if(u>0)p=s+u*(255-s),f=i-u*(i-0),y=o+u*(255-o),T=r-u*(r-0),S=c+u*(255-c),v=h-u*(h-0);else{const b=(s+i)*.5;p=s+u*(s-b),f=i+u*(i-b);const k=(o+r)*.5;y=o+u*(o-k),T=r+u*(r-k);const M=(c+h)*.5;S=c+u*(c-M),v=h+u*(h-M)}for(let b=0;b<e;b+=4)t[b+0]=oi(t[b+0],i,s,f,p),t[b+1]=oi(t[b+1],r,o,T,y),t[b+2]=oi(t[b+2],h,c,v,S)};m.addGetterSetter(P,"enhance",0,x(),m.afterSetFilter);const Ha=function(a){const t=a.data,e=t.length;for(let i=0;i<e;i+=4){const s=.34*t[i]+.5*t[i+1]+.16*t[i+2];t[i]=s,t[i+1]=s,t[i+2]=s}};m.addGetterSetter(P,"hue",0,x(),m.afterSetFilter);m.addGetterSetter(P,"saturation",0,x(),m.afterSetFilter);m.addGetterSetter(P,"luminance",0,x(),m.afterSetFilter);const za=function(a){const t=a.data,e=t.length,i=1,s=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,r=this.luminance()*127,o=i*s*Math.cos(n*Math.PI/180),l=i*s*Math.sin(n*Math.PI/180),h=.299*i+.701*o+.167*l,c=.587*i-.587*o+.33*l,d=.114*i-.114*o-.497*l,u=.299*i-.299*o-.328*l,p=.587*i+.413*o+.035*l,f=.114*i-.114*o+.293*l,y=.299*i-.3*o+1.25*l,T=.587*i-.586*o-1.05*l,S=.114*i+.886*o-.2*l;let v,b,k,M;for(let _=0;_<e;_+=4)v=t[_+0],b=t[_+1],k=t[_+2],M=t[_+3],t[_+0]=h*v+c*b+d*k+r,t[_+1]=u*v+p*b+f*k+r,t[_+2]=y*v+T*b+S*k+r,t[_+3]=M},Na=function(a){const t=a.data,e=t.length,i=Math.pow(2,this.value()),s=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,r=i*s*Math.cos(n*Math.PI/180),o=i*s*Math.sin(n*Math.PI/180),l=.299*i+.701*r+.167*o,h=.587*i-.587*r+.33*o,c=.114*i-.114*r-.497*o,d=.299*i-.299*r-.328*o,u=.587*i+.413*r+.035*o,p=.114*i-.114*r+.293*o,f=.299*i-.3*r+1.25*o,y=.587*i-.586*r-1.05*o,T=.114*i+.886*r-.2*o;for(let S=0;S<e;S+=4){const v=t[S+0],b=t[S+1],k=t[S+2],M=t[S+3];t[S+0]=l*v+h*b+c*k,t[S+1]=d*v+u*b+p*k,t[S+2]=f*v+y*b+T*k,t[S+3]=M}};m.addGetterSetter(P,"hue",0,x(),m.afterSetFilter);m.addGetterSetter(P,"saturation",0,x(),m.afterSetFilter);m.addGetterSetter(P,"value",0,x(),m.afterSetFilter);const Fa=function(a){const t=a.data,e=t.length;for(let i=0;i<e;i+=4)t[i]=255-t[i],t[i+1]=255-t[i+1],t[i+2]=255-t[i+2]},Va=function(a,t,e){const i=a.data,s=t.data,n=a.width,r=a.height,o=e.polarCenterX||n/2,l=e.polarCenterY||r/2;let h=Math.sqrt(o*o+l*l),c=n-o,d=r-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const p=r,f=n,y=360/f*Math.PI/180;for(let T=0;T<f;T+=1){const S=Math.sin(T*y),v=Math.cos(T*y);for(let b=0;b<p;b+=1){c=Math.floor(o+h*b/p*v),d=Math.floor(l+h*b/p*S);let k=(d*n+c)*4;const M=i[k+0],_=i[k+1],R=i[k+2],A=i[k+3];k=(T+b*n)*4,s[k+0]=M,s[k+1]=_,s[k+2]=R,s[k+3]=A}}},Wa=function(a,t,e){const i=a.data,s=t.data,n=a.width,r=a.height,o=e.polarCenterX||n/2,l=e.polarCenterY||r/2;let h=Math.sqrt(o*o+l*l),c=n-o,d=r-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const p=r,f=n,y=0;let T,S;for(c=0;c<n;c+=1)for(d=0;d<r;d+=1){const v=c-o,b=d-l,k=Math.sqrt(v*v+b*b)*p/h;let M=(Math.atan2(b,v)*180/Math.PI+360+y)%360;M=M*f/360,T=Math.floor(M),S=Math.floor(k);let _=(S*n+T)*4;const R=i[_+0],A=i[_+1],I=i[_+2],D=i[_+3];_=(d*n+c)*4,s[_+0]=R,s[_+1]=A,s[_+2]=I,s[_+3]=D}},Ya=function(a){const t=a.width,e=a.height;let i,s,n,r,o,l,h,c,d,u,p=Math.round(this.kaleidoscopePower());const f=Math.round(this.kaleidoscopeAngle()),y=Math.floor(t*(f%360)/360);if(p<1)return;const T=C.createCanvasElement();T.width=t,T.height=e;const S=T.getContext("2d").getImageData(0,0,t,e);C.releaseCanvas(T),Va(a,S,{polarCenterX:t/2,polarCenterY:e/2});let v=t/Math.pow(2,p);for(;v<=8;)v=v*2,p-=1;v=Math.ceil(v);let b=v,k=0,M=b,_=1;for(y+v>t&&(k=b,M=0,_=-1),s=0;s<e;s+=1)for(i=k;i!==M;i+=_)n=Math.round(i+y)%t,d=(t*s+n)*4,o=S.data[d+0],l=S.data[d+1],h=S.data[d+2],c=S.data[d+3],u=(t*s+i)*4,S.data[u+0]=o,S.data[u+1]=l,S.data[u+2]=h,S.data[u+3]=c;for(s=0;s<e;s+=1)for(b=Math.floor(v),r=0;r<p;r+=1){for(i=0;i<b+1;i+=1)d=(t*s+i)*4,o=S.data[d+0],l=S.data[d+1],h=S.data[d+2],c=S.data[d+3],u=(t*s+b*2-i-1)*4,S.data[u+0]=o,S.data[u+1]=l,S.data[u+2]=h,S.data[u+3]=c;b*=2}Wa(S,a,{})};m.addGetterSetter(P,"kaleidoscopePower",2,x(),m.afterSetFilter);m.addGetterSetter(P,"kaleidoscopeAngle",0,x(),m.afterSetFilter);function Be(a,t,e){let i=(e*a.width+t)*4;const s=[];return s.push(a.data[i++],a.data[i++],a.data[i++],a.data[i++]),s}function oe(a,t){return Math.sqrt(Math.pow(a[0]-t[0],2)+Math.pow(a[1]-t[1],2)+Math.pow(a[2]-t[2],2))}function Xa(a){const t=[0,0,0];for(let e=0;e<a.length;e++)t[0]+=a[e][0],t[1]+=a[e][1],t[2]+=a[e][2];return t[0]/=a.length,t[1]/=a.length,t[2]/=a.length,t}function Ua(a,t){const e=Be(a,0,0),i=Be(a,a.width-1,0),s=Be(a,0,a.height-1),n=Be(a,a.width-1,a.height-1),r=t||10;if(oe(e,i)<r&&oe(i,n)<r&&oe(n,s)<r&&oe(s,e)<r){const o=Xa([i,e,n,s]),l=[];for(let h=0;h<a.width*a.height;h++){const c=oe(o,[a.data[h*4],a.data[h*4+1],a.data[h*4+2]]);l[h]=c<r?0:255}return l}}function $a(a,t){for(let e=0;e<a.width*a.height;e++)a.data[4*e+3]=t[e]}function Ka(a,t,e){const i=[1,1,1,1,0,1,1,1,1],s=Math.round(Math.sqrt(i.length)),n=Math.floor(s/2),r=[];for(let o=0;o<e;o++)for(let l=0;l<t;l++){const h=o*t+l;let c=0;for(let d=0;d<s;d++)for(let u=0;u<s;u++){const p=o+d-n,f=l+u-n;if(p>=0&&p<e&&f>=0&&f<t){const y=p*t+f,T=i[d*s+u];c+=a[y]*T}}r[h]=c===255*8?255:0}return r}function ja(a,t,e){const i=[1,1,1,1,1,1,1,1,1],s=Math.round(Math.sqrt(i.length)),n=Math.floor(s/2),r=[];for(let o=0;o<e;o++)for(let l=0;l<t;l++){const h=o*t+l;let c=0;for(let d=0;d<s;d++)for(let u=0;u<s;u++){const p=o+d-n,f=l+u-n;if(p>=0&&p<e&&f>=0&&f<t){const y=p*t+f,T=i[d*s+u];c+=a[y]*T}}r[h]=c>=255*4?255:0}return r}function Za(a,t,e){const i=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],s=Math.round(Math.sqrt(i.length)),n=Math.floor(s/2),r=[];for(let o=0;o<e;o++)for(let l=0;l<t;l++){const h=o*t+l;let c=0;for(let d=0;d<s;d++)for(let u=0;u<s;u++){const p=o+d-n,f=l+u-n;if(p>=0&&p<e&&f>=0&&f<t){const y=p*t+f,T=i[d*s+u];c+=a[y]*T}}r[h]=c}return r}const qa=function(a){const t=this.threshold();let e=Ua(a,t);return e&&(e=Ka(e,a.width,a.height),e=ja(e,a.width,a.height),e=Za(e,a.width,a.height),$a(a,e)),a};m.addGetterSetter(P,"threshold",0,x(),m.afterSetFilter);const Ja=function(a){const t=this.noise()*255,e=a.data,i=e.length,s=t/2;for(let n=0;n<i;n+=4)e[n+0]+=s-2*s*Math.random(),e[n+1]+=s-2*s*Math.random(),e[n+2]+=s-2*s*Math.random()};m.addGetterSetter(P,"noise",.2,x(),m.afterSetFilter);const Qa=function(a){let t=Math.ceil(this.pixelSize()),e=a.width,i=a.height,s=Math.ceil(e/t),n=Math.ceil(i/t),r=a.data;if(t<=0){C.error("pixelSize value can not be <= 0");return}for(let o=0;o<s;o+=1)for(let l=0;l<n;l+=1){let h=0,c=0,d=0,u=0;const p=o*t,f=p+t,y=l*t,T=y+t;let S=0;for(let v=p;v<f;v+=1)if(!(v>=e))for(let b=y;b<T;b+=1){if(b>=i)continue;const k=(e*b+v)*4;h+=r[k+0],c+=r[k+1],d+=r[k+2],u+=r[k+3],S+=1}h=h/S,c=c/S,d=d/S,u=u/S;for(let v=p;v<f;v+=1)if(!(v>=e))for(let b=y;b<T;b+=1){if(b>=i)continue;const k=(e*b+v)*4;r[k+0]=h,r[k+1]=c,r[k+2]=d,r[k+3]=u}}};m.addGetterSetter(P,"pixelSize",8,x(),m.afterSetFilter);const to=function(a){const t=Math.round(this.levels()*254)+1,e=a.data,i=e.length,s=255/t;for(let n=0;n<i;n+=1)e[n]=Math.floor(e[n]/s)*s};m.addGetterSetter(P,"levels",.5,x(),m.afterSetFilter);const eo=function(a){const t=a.data,e=t.length,i=this.red(),s=this.green(),n=this.blue();for(let r=0;r<e;r+=4){const o=(.34*t[r]+.5*t[r+1]+.16*t[r+2])/255;t[r]=o*i,t[r+1]=o*s,t[r+2]=o*n,t[r+3]=t[r+3]}};m.addGetterSetter(P,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(P,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(P,"blue",0,Bs,m.afterSetFilter);const io=function(a){const t=a.data,e=t.length,i=this.red(),s=this.green(),n=this.blue(),r=this.alpha();for(let o=0;o<e;o+=4){const l=1-r;t[o]=i*r+t[o]*l,t[o+1]=s*r+t[o+1]*l,t[o+2]=n*r+t[o+2]*l}};m.addGetterSetter(P,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(P,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(P,"blue",0,Bs,m.afterSetFilter);m.addGetterSetter(P,"alpha",1,function(a){return this._filterUpToDate=!1,a>1?1:a<0?0:a});const so=function(a){const t=a.data,e=t.length;for(let i=0;i<e;i+=4){const s=t[i+0],n=t[i+1],r=t[i+2];t[i+0]=Math.min(255,s*.393+n*.769+r*.189),t[i+1]=Math.min(255,s*.349+n*.686+r*.168),t[i+2]=Math.min(255,s*.272+n*.534+r*.131)}},no=function(a){const e=a.data;for(let i=0;i<e.length;i+=4){const s=e[i],n=e[i+1],r=e[i+2];.2126*s+.7152*n+.0722*r>=128&&(e[i]=255-s,e[i+1]=255-n,e[i+2]=255-r)}return a},ro=function(a){const t=this.threshold()*255,e=a.data,i=e.length;for(let s=0;s<i;s+=1)e[s]=e[s]<t?0:255};m.addGetterSetter(P,"threshold",.5,x(),m.afterSetFilter);const X=Qi.Util._assign(Qi,{Arc:xt,Arrow:Xt,Circle:ee,Ellipse:Gt,Image:mt,Label:Oi,Tag:Ut,Line:At,Path:tt,Rect:_e,RegularPolygon:Bt,Ring:$t,Sprite:bt,Star:Ht,Text:et,TextPath:rt,Transformer:Y,Wedge:Et,Filters:{Blur:La,Brightness:Ra,Brighten:Da,Contrast:Oa,Emboss:Ga,Enhance:Ba,Grayscale:Ha,HSL:za,HSV:Na,Invert:Fa,Kaleidoscope:Ya,Mask:qa,Noise:Ja,Pixelate:Qa,Posterize:to,RGB:eo,RGBA:io,Sepia:so,Solarize:no,Threshold:ro}}),ds={debug:10,info:20,warn:30,error:40},He={enabled:!0,level:"warn",moduleLevels:{}},us=400;function ao(a,t){return a.moduleLevels[t]??a.level}function Nt(a,t,e){if(!a.enabled)return!1;const i=ao(a,e);return ds[t]>=ds[i]}function gs(a){if(!a||typeof a!="object")return null;const t="clientX"in a||"clientY"in a,e="deltaX"in a||"deltaY"in a,i="shiftKey"in a||"metaKey"in a||"ctrlKey"in a||"altKey"in a;return!t&&!e&&!i?null:{type:typeof a.type=="string"?a.type:void 0,clientX:typeof a.clientX=="number"?a.clientX:void 0,clientY:typeof a.clientY=="number"?a.clientY:void 0,button:typeof a.button=="number"?a.button:void 0,buttons:typeof a.buttons=="number"?a.buttons:void 0,deltaX:typeof a.deltaX=="number"?a.deltaX:void 0,deltaY:typeof a.deltaY=="number"?a.deltaY:void 0,shiftKey:!!a.shiftKey,metaKey:!!a.metaKey,ctrlKey:!!a.ctrlKey,altKey:!!a.altKey}}function oo(a){if(a===void 0)return;const t=gs(a);if(t)return t;if(a&&typeof a=="object"&&"evt"in a){const e=gs(a.evt);if(e)return{...a,evt:e}}return a}function lo(a,t,e,i){const s=oo(i);s===void 0?a(`${t} ${e}`):a(`${t} ${e}`,s)}class O{static setConfig(t){if(!t){this.config={...He};return}this.config={enabled:t.enabled??He.enabled,level:t.level??He.level,moduleLevels:t.moduleLevels??{}}}static debug(t,e,i){Nt(this.config,"debug",t)&&this.emit("debug",t,e,i)}static debugLazy(t,e,i){if(!Nt(this.config,"debug",t))return;const s=e(),n=i?i():void 0;this.emit("debug",t,s,n)}static info(t,e,i){Nt(this.config,"info",t)&&this.emit("info",t,e,i)}static infoLazy(t,e,i){if(!Nt(this.config,"info",t))return;const s=e(),n=i?i():void 0;this.emit("info",t,s,n)}static warn(t,e,i){Nt(this.config,"warn",t)&&this.emit("warn",t,e,i)}static warnLazy(t,e,i){if(!Nt(this.config,"warn",t))return;const s=e(),n=i?i():void 0;this.emit("warn",t,s,n)}static error(t,e,i){Nt(this.config,"error",t)&&this.emit("error",t,e,i)}static setDedupeWindowMs(t){this.dedupeWindowMs=Number.isFinite(t)&&t>=0?t:us}static emit(t,e,i,s){const n=Date.now(),r=`${t}:${e}:${i}`,o=this.dedupeState.get(r);if(o&&n-o.lastPrintedAt<this.dedupeWindowMs){o.suppressed+=1;return}const l=(o==null?void 0:o.suppressed)??0,h=l>0?`${i} (+${l} repeats)`:i;this.dedupeState.set(r,{lastPrintedAt:n,suppressed:0});const c=`[${t.toUpperCase()}] [${e}]`,d=this.resolveConsoleMethod(t);lo(d,c,h,s)}static resolveConsoleMethod(t){return t==="debug"?console.log.bind(console):t==="info"?console.info.bind(console):t==="warn"?console.warn.bind(console):console.error.bind(console)}}g(O,"config",{...He}),g(O,"dedupeWindowMs",us),g(O,"dedupeState",new Map);class Ct{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={}}static renderClipCovers(t,e,i,s,n,r=!1){O.debugLazy("ClipCoverRenderer",()=>"renderClipCovers",()=>({videoSrc:n,coverCount:(e==null?void 0:e.length)??0,coverWidth:i,coverHeight:s}));const o=(t.getAttr(this.COVER_RENDER_VERSION_KEY)||0)+1;if(t.setAttr(this.COVER_RENDER_VERSION_KEY,o),!e||e.length===0){t.destroyChildren(),r||this.requestRender(t);return}const l=this.buildSegmentsDataSync(e,i,s,n);if(l){this.renderSegments(t,l,i,s),r||this.requestRender(t);return}r||(t.destroyChildren(),this.requestRender(t)),this.startRenderJob({coversGroup:t,coverSource:e,coverWidth:i,coverHeight:s,videoSrc:n,version:o})}static async startRenderJob(t){const{coversGroup:e,coverSource:i,coverWidth:s,coverHeight:n,videoSrc:r,version:o}=t,l=await this.buildSegmentsData(i,s,n,r);if(this.isRenderJobCurrent(e,o)){if(this.renderSegments(e,l,s,n),!this.isRenderJobCurrent(e,o)){e.destroyChildren();return}this.requestRender(e)}}static async buildSegmentsData(t,e,i,s){const n=t.length,r=s||t[0]||"",o=await this.getSafeKeyframeDimensions(r,t[0]),l=o.width/o.height,h=i*l,c=l>=1;let d;c?d=Math.min(n,Math.max(1,Math.floor(e/h))):d=Math.min(n,Math.max(1,Math.floor(e/this.MIN_IMAGE_DISPLAY_WIDTH)));const u=e/d,p=[];if(d===1)p.push(0);else for(let y=0;y<d;y++)p.push(Math.round(y*(n-1)/(d-1)));const f=[];for(let y=0;y<d;y++){const T=t[p[y]],S=await this.getSafeKeyframeDimensions(r,T),v=S.width/S.height;f.push({coverUrl:T,singleImageWidth:i*v,segmentStartX:y*u,segmentWidth:u})}return f}static buildSegmentsDataSync(t,e,i,s){const n=t.length,r=s||t[0]||"",o=this.getCachedKeyframeDimensions(r,t[0]);if(!o)return null;const l=o.width/o.height,h=i*l,c=l>=1;let d;c?d=Math.min(n,Math.max(1,Math.floor(e/h))):d=Math.min(n,Math.max(1,Math.floor(e/this.MIN_IMAGE_DISPLAY_WIDTH)));const u=e/d,p=[];if(d===1)p.push(0);else for(let y=0;y<d;y++)p.push(Math.round(y*(n-1)/(d-1)));const f=[];for(let y=0;y<d;y++){const T=t[p[y]],S=this.getCachedKeyframeDimensions(r,T);if(!S)return null;const v=S.width/S.height;f.push({coverUrl:T,singleImageWidth:i*v,segmentStartX:y*u,segmentWidth:u})}return f}static requestRender(t){var i,s;const e=(i=t.getLayer)==null?void 0:i.call(t);if((s=e==null?void 0:e.getStage)!=null&&s.call(e))try{t.draw(),e.batchDraw()}catch{}}static isRenderJobCurrent(t,e){return t.getAttr(this.COVER_RENDER_VERSION_KEY)===e}static renderSegments(t,e,i,s){t.destroyChildren(),t.clip({x:0,y:0,width:i,height:s});for(const{coverUrl:n,singleImageWidth:r,segmentStartX:o,segmentWidth:l}of e){const h=Math.max(r,.01),c=Math.max(1,Math.ceil(l/h)),d=Math.max(r,.01),u=this.getCachedImage(n),p=new X.Group({x:o,y:0,clip:{x:0,y:0,width:l,height:s},name:"cover-segment"});u.src||(u.src=n);for(let f=0;f<c;f++){const y=f*d,T=l-y,S=i-o-y,v=Math.min(d,T,S);if(v<=0)continue;const b=new X.Image({image:u,cornerRadius:2,name:"cover-image"});b.x(y),b.y(0),b.width(v),b.height(s),p.add(b)}t.add(p)}}static async getSafeKeyframeDimensions(t,e){try{const i=await this.getKeyframeDimensions(t,e);if(i!=null&&i.width&&(i!=null&&i.height))return i}catch{}return this.DEFAULT_DIMENSIONS}static getKeyframeDimensions(t,e){const i=e||t;if(this.keyframeDimensionsCache[i])return Promise.resolve(this.keyframeDimensionsCache[i]);if(this.keyframeDimensionsPromiseCache[i])return this.keyframeDimensionsPromiseCache[i];const s=new Promise(n=>{const r=this.getCachedImage(e);if(r.complete&&r.width>0){const l={width:r.width,height:r.height};this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],n(l);return}const o=l=>{this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],n(l)};r.onload=()=>{const l={width:r.width,height:r.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},r.onerror=()=>{o(this.DEFAULT_DIMENSIONS)},r.src||(r.src=e)});return this.keyframeDimensionsPromiseCache[i]=s,s}static getCachedKeyframeDimensions(t,e){const i=e||t,s=this.keyframeDimensionsCache[i];if(s!=null&&s.width&&(s!=null&&s.height))return s;const n=this.imageCache[e];if(n!=null&&n.complete&&n.width>0&&n.height>0){const r={width:n.width,height:n.height};return this.keyframeDimensionsCache[i]=r,r}return null}static getCachedImage(t){const e=this.imageCache[t];if(e)return e;const i=new Image;return this.imageCache[t]=i,this.checkAndTrimCache(),i}static checkAndTrimCache(){const t=Object.keys(this.imageCache);if(t.length<=this.MAX_CACHE_SIZE)return;const e=t.length-this.MAX_CACHE_SIZE,i=t.filter(r=>{const o=this.imageCache[r];return o&&!o.complete}),s=t.filter(r=>!i.includes(r));let n=0;for(const r of i){if(n>=e)break;delete this.imageCache[r],n++}for(const r of s){if(n>=e)break;delete this.imageCache[r],n++}}}g(Ct,"MIN_IMAGE_DISPLAY_WIDTH",24),g(Ct,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),g(Ct,"MAX_CACHE_SIZE",1e3),g(Ct,"DEFAULT_DIMENSIONS",{width:160,height:90}),g(Ct,"keyframeDimensionsCache",{}),g(Ct,"keyframeDimensionsPromiseCache",{}),g(Ct,"imageCache",{});const at=3,fs=10,ho=8,co=8,uo=10,li=4,ps=14,go=[4,10,14,10,4],ms=[3,7,11,15,11,7,3],Gi=28,fo=14,mn=8,po=[4,9,14,9,4];function Tt(a,t,e,i,s="#ffffff",n="#000000",r=1){return new X.Rect({x:a,y:t,width:e,height:i,fill:s,stroke:n,strokeWidth:r})}function yn(a,t,e,i=12,s="Arial",n="#000000",r="left",o="top"){return new X.Text({text:a,x:t,y:e,fontSize:i,fontFamily:s,fill:n,align:r,verticalAlign:o})}function Pt(a=0,t=0){return new X.Group({x:a,y:t})}function Bi(a,t,e,i){if(i){a.add(new X.Rect({x:0,y:0,width:t,height:e,name:"clip-resize-left",listening:!0})),a.add(new X.Rect({x:0,y:0,width:t,height:e,name:"clip-resize-right",listening:!0}));return}a.add(new X.Rect({x:0,y:0,width:at,height:e,name:"clip-resize-left"})),a.add(new X.Rect({x:t-at,y:0,width:at,height:e,name:"clip-resize-right"}))}function mo(a,t,e,i){const s=a.findOne(".clip-resize-left"),n=a.findOne(".clip-resize-right");return!s||!n?!1:(s.x(0),s.y(0),s.width(at),s.height(e),n.x(t-at),n.y(0),n.width(at),n.height(e),!0)}function Cn(a,t,e){return e==="audio"?{background:t?a.clipSelectedBackground||a.audioClipBackground||a.clipBackground:a.audioClipBackground||a.clipBackground,label:t?a.clipSelectedName||a.audioClipText||a.clipName:a.audioClipText||a.clipName,accent:t?a.clipSelectedHandle||a.audioClipAccent||a.clipHandle:a.audioClipAccent||a.clipHandle,coverBackground:a.clipCoverBackground||"#333333"}:{background:t&&a.clipSelectedBackground||a.clipBackground,label:t&&a.clipSelectedName||a.clipName,accent:t&&a.clipSelectedHandle||a.clipHandle,coverBackground:t?a.clipSelectedCoverBackground||a.clipCoverBackground||"#FFF2A0":a.clipCoverBackground||"#FFF2A0"}}function yo(a,t,e,i){const s=Tt(0,0,t,e,i.background,"transparent",0);s.cornerRadius(Math.min(4,Math.floor(t/2))),s.name("clip-background"),a.add(s),Bi(a,t,e,!0)}function Co(a,t,e){const i=Tt(0,0,t.width,t.height,e.background,"transparent",0);i.cornerRadius(4),i.name("clip-background"),a.add(i),Bi(a,t.width,t.height,!1);const s=15,n=t.height-s-4,r=t.width-at*2,o=Pt(at,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:r,height:n}),a.add(o);const l=Tt(0,0,r,n,e.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const h=Pt(0,0);h.name("clip-covers-group"),o.add(h),Ct.renderClipCovers(h,t.thumbnails??[],r,n,t.videoSrc,t.deferCoverRender);const c=r>=120?Gi+mn:0,d=yn(`${t.clipName} ${z.formatDuration(t.duration)}`,at,t.height-s,10,"Arial",e.label,"left","middle");d.ellipsis(!0),d.width(Math.max(0,r-c)),d.height(s),d.name("clip-label"),a.add(d),c>0&&Sn(a,t.width,t.height,e.label,t.hasSeparatedAudio)}function So(a,t,e){const i=a.findOne(".clip-background"),s=a.findOne(".clip-cover-container"),n=a.findOne(".clip-cover-background"),r=a.findOne(".clip-covers-group"),o=a.findOne(".clip-label");if(!i||!s||!n||!r||!o||(i.width(t.width),i.height(t.height),i.fill(e.background),i.stroke("transparent"),i.strokeWidth(0),i.cornerRadius(4),!mo(a,t.width,t.height)))return!1;const l=15,h=t.height-l-4,c=t.width-at*2;s.x(at),s.y(2),s.clip({x:0,y:0,width:c,height:h}),n.width(c),n.height(h),n.fill(e.coverBackground),n.cornerRadius(2),Ct.renderClipCovers(r,t.thumbnails??[],c,h,t.videoSrc,t.deferCoverRender);const d=c>=120?Gi+mn:0;o.text(`${t.clipName} ${z.formatDuration(t.duration)}`),o.x(at),o.y(t.height-l),o.fill(e.label),o.width(Math.max(0,c-d)),o.height(l),o.ellipsis(!0);const u=a.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&Sn(a,t.width,t.height,e.label,t.hasSeparatedAudio),!0}function wi(a,t,e,i,s,n,r){return a.name(s),t.forEach((o,l)=>{const h=Tt(l*(n+r),Math.max(0,(e-o)/2),n,o,i,"transparent",0);h.cornerRadius(1),h.name(`${s}-bar-${l}`),a.add(h)}),t.length*n+Math.max(0,t.length-1)*r}function Sn(a,t,e,i,s){const n=Pt(Math.max(at,t-at-Gi),Math.max(0,e-15));if(n.name("video-audio-status"),s){const c=Pt(0,0);c.name("video-audio-status-separated");const d=Tt(0,5,3,3,i,"transparent",0);d.cornerRadius(1.5),d.name("video-audio-status-separated-left-dot"),c.add(d);const u=Tt(6,6,16,2,i,"transparent",0);u.cornerRadius(1),u.name("video-audio-status-separated-line"),c.add(u);const p=Tt(25,5,3,3,i,"transparent",0);p.cornerRadius(1.5),p.name("video-audio-status-separated-right-dot"),c.add(p),n.add(c),a.add(n);return}const r=Pt(2,0);r.name("video-audio-status-active");const o=Tt(0,5,3,3,i,"transparent",0);o.cornerRadius(1.5),o.name("video-audio-status-active-left-dot"),r.add(o);const l=Pt(5,0);wi(l,po,fo,i,"video-audio-status-active-bars",2,2),r.add(l);const h=Tt(25,5,3,3,i,"transparent",0);h.cornerRadius(1.5),h.name("video-audio-status-active-right-dot"),r.add(h),n.add(r),a.add(n)}function To(a,t,e){const i=Tt(0,0,t.width,t.height,e.background,"transparent",0);i.cornerRadius(6),i.name("clip-background"),a.add(i),Bi(a,t.width,t.height,!1);const s=at+fs,n=Math.max(0,t.width-at*2-fs*2),r=ho,o=Pt(s,r),l=wi(o,go,14,e.accent,"audio-clip-icon",2,2);a.add(o);const h=s+l+uo,c=Math.max(0,s+n-h),d=3+li,u=Math.min(ms.length,Math.floor((c+li)/d));if(u>0){const f=Pt(h,r);wi(f,ms.slice(0,u),15,e.accent,"audio-clip-waveform",3,li),a.add(f)}const p=yn(t.clipName,s,t.height-co-ps,12,"Arial",e.label,"left","middle");p.ellipsis(!0),p.width(n),p.height(ps),p.name("clip-label"),a.add(p)}function Tn(a,t){const e=t.width<=ke,i=Cn(t.theme,t.isSelected,t.clipType);if(a.destroyChildren(),e){yo(a,t.width,t.height,i);return}if(t.clipType==="audio"){To(a,t,i);return}Co(a,t,i)}function vo(a,t){if(t.width<=ke||t.clipType!=="video")return!1;const i=Cn(t.theme,t.isSelected,t.clipType);return So(a,t,i)}function bo(a,t,e,i,s,n,r,o=!1,l,h,c="video",d=!1,u=!1){const p=Pt(a,t);return p.clip({x:0,y:0,width:e,height:i}),Tn(p,{width:e,height:i,clipName:s,duration:n,theme:r,isSelected:o,thumbnails:l,videoSrc:h,clipType:c,hasSeparatedAudio:d,deferCoverRender:u}),p}function ko(a,t,e,i,s,n,r=!1,o,l,h="video",c=!1,d=!1){a.clip({x:0,y:0,width:t,height:e});const u={width:t,height:e,clipName:i,duration:s,theme:n??$e,isSelected:r,thumbnails:o,videoSrc:l,clipType:h,hasSeparatedAudio:c,deferCoverRender:d};vo(a,u)||Tn(a,u)}function wo(a,t,e,i){return new X.Rect({x:a,y:t,width:e,height:i,stroke:"#50E3C2",strokeWidth:2,dash:[5,5],fillEnabled:!1})}function _i(a,t="#000000",e=1){return new X.Line({points:a,stroke:t,strokeWidth:e,lineCap:"round",lineJoin:"round"})}function _o(a,t,e,i=12,s="Arial",n="#000000",r="left",o="top"){return new X.Text({text:a,x:t,y:e,fontSize:i,fontFamily:s,fill:n,align:r,verticalAlign:o})}function Po(a=0,t=0){return new X.Group({x:a,y:t})}function xo(a,t,e,i,s,n,r,o){const l=o||i,h=r==="major"?l*.6:l*.3,c=_i([t,e,t,e+h],n.timeTick,r==="major"?1:.5);if(c.name("time-tick-line"),a.add(c),r==="major"){const d=e+h+5,u=_o(z.formatTime(s),t,d,10,"Arial",n.timeText,"center");u.name("time-tick-text"),a.add(u)}}function Ao(a,t,e,i,s,n){const r=Po(t,e);for(let o=0;o<=i;o+=n)r.add(_i([o,0,o,s],"#E0E0E0",.5));for(let o=0;o<=s;o+=n)r.add(_i([0,o,i,o],"#E0E0E0",.5));a.add(r)}class it{static createStage(t,e,i){return new X.Stage({container:t,width:e,height:i})}static createLayer(t){const e=new X.Layer;return e.name(t),e}static createRect(t,e,i,s,n="#ffffff",r="#000000",o=1){return new X.Rect({x:t,y:e,width:i,height:s,fill:n,stroke:r,strokeWidth:o})}static createText(t,e,i,s=12,n="Arial",r="#000000",o="left",l="top"){return new X.Text({text:t,x:e,y:i,fontSize:s,fontFamily:n,fill:r,align:o,verticalAlign:l})}static createLine(t,e="#000000",i=1){return new X.Line({points:t,stroke:e,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(t=0,e=0){return new X.Group({x:t,y:e})}static createPlayhead(t,e,i){const s=new X.Group({x:t,y:e}),n=this.createLine([0,0,0,i],"#FF0000",2),r=new X.RegularPolygon({x:0,y:-10,sides:3,radius:5,fill:"#FF0000",rotation:180});return s.add(n),s.add(r),s}static drawTimeTick(t,e,i,s,n,r,o,l){xo(t,e,i,s,n,r,o,l)}static drawGrid(t,e,i,s,n,r){Ao(t,e,i,s,n,r)}static clearImageCache(){Ct.clearImageCache()}static createClipGroup(t,e,i,s,n,r,o,l=!1,h,c,d="video",u=!1,p=!1){return bo(t,e,i,s,n,r,o,l,h,c,d,u,p)}static updateClipGroup(t,e,i,s,n,r,o=!1,l,h,c="video",d=!1,u=!1){ko(t,e,i,s,n,r,o,l,h,c,d,u)}static createSelectionEffect(t,e,i,s){return wo(t,e,i,s)}static timeToPixels(t,e){return t/1e3*e}static pixelsToTime(t,e){return t/e*1e3}}g(it,"RESIZE_AREA_WIDTH",3);function Pe(a){let t=!1;return typeof window<"u"&&(window.addEventListener("mousemove",a.onPointerMove),window.addEventListener("mouseup",a.onPointerEnd),window.addEventListener("blur",a.onWindowBlur||a.onPointerEnd),t=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",a.onVisibilityChange),t=!0),t}function xe(a){typeof window<"u"&&(window.removeEventListener("mousemove",a.onPointerMove),window.removeEventListener("mouseup",a.onPointerEnd),window.removeEventListener("blur",a.onWindowBlur||a.onPointerEnd)),typeof document<"u"&&document.removeEventListener("visibilitychange",a.onVisibilityChange)}class Eo{constructor(t,e,i,s,n,r){g(this,"stage");g(this,"gridLayer");g(this,"config");g(this,"theme");g(this,"isDragging",!1);g(this,"startDragX",0);g(this,"scrollLeft",0);g(this,"timeScaleHeight",40);g(this,"onTimeChange");g(this,"onZoomChange");g(this,"onScrollChange");g(this,"animationFrameId",null);g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"isScrollbarDragging",!1);g(this,"scrollbarDragStartX",0);g(this,"scrollbarDragStartScrollLeft",0);g(this,"isPointerInsideTimeline",!1);g(this,"lastPointerXInTimeline",null);g(this,"scrollbarHeight",12);g(this,"scrollbarMargin",4);g(this,"handleGlobalPointerMove",t=>{this.isPointerSessionActive()&&this.handlePointerMove(t)});g(this,"handleGlobalPointerEnd",()=>{this.finalizePointerInteraction()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finalizePointerInteraction()});g(this,"leftPadding",ot);this.stage=t,this.gridLayer=e,this.onTimeChange=s,this.onZoomChange=n,this.onScrollChange=r,this.config={duration:i.duration||36e5,zoom:i.zoom||ct.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:be(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,i.timeScaleHeight&&(this.timeScaleHeight=i.timeScaleHeight),this.initEventListeners(),this.render()}initEventListeners(){this.stage.on("wheel",t=>{t.evt.preventDefault(),this.updatePointerPosition(t.evt.offsetX),this.isPointerInsideTimeline=!0;const{deltaX:e,deltaY:i,shiftKey:s}=t.evt,n=Math.abs(e)>0;if(s||n){const l=(n?e:i)*1.5,h=this.stage.width(),c=z.timeToPixels(this.config.duration,this.config.zoom),d=Math.max(0,c-h),u=Math.max(0,Math.min(d,this.scrollLeft+l));u!==this.scrollLeft&&this.animateHorizontalScroll(u)}else Math.abs(i)>0&&this.handleZoom(t)}),this.stage.on("click",t=>{let e=t.target.getLayer();const i=t.target.name()==="scrollbar-background"||t.target.name()==="scrollbar-thumb";e===this.gridLayer&&!i&&this.handleClick(t.evt.offsetX)}),this.stage.on("mousedown",t=>{this.updatePointerPosition(t.evt.offsetX),this.isPointerInsideTimeline=!0;let e=t.target.getLayer(),i=t.target.name()==="scrollbar-background"||t.target.name()==="scrollbar-thumb";e===this.gridLayer&&t.target.name()==="scrollbar-thumb"?(this.isScrollbarDragging=!0,this.scrollbarDragStartX=t.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):e===this.gridLayer&&t.target.name()==="scrollbar-background"?(this.jumpScrollbarToPointer(t.evt.offsetX),this.isScrollbarDragging=!0,this.scrollbarDragStartX=t.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):e===this.gridLayer&&!i&&(this.isDragging=!0,this.startDragX=t.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",t=>{this.updatePointerPosition(t.evt.offsetX),this.isPointerInsideTimeline=!0,this.isPointerSessionActive()&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(t.evt)}),this.stage.on("mouseup",()=>{this.finalizePointerInteraction()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(t){if(!Number.isFinite(t))return;const e=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(e,t))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Pe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(xe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}isPointerSessionActive(){return this.isDragging||this.isScrollbarDragging}finalizePointerInteraction(){this.isDragging=!1,this.isScrollbarDragging=!1,this.unbindGlobalPointerListenersForDrag()}handlePointerMove(t){if(this.isScrollbarDragging){const e=this.stage.width(),i=this.getTotalDurationPixels(),s=Math.max(0,i-e);if(s<=0)return;const n=this.getScrollbarThumbWidth(),r=Math.max(1,e-n),o=t.clientX-this.scrollbarDragStartX,l=this.scrollLeft,h=this.scrollbarDragStartScrollLeft+o/r*s;this.scrollLeft=Math.max(0,Math.min(s,h)),this.render(),this.scrollLeft!==l&&this.onScrollChange(this.scrollLeft)}else if(this.isDragging){const e=t.clientX-this.startDragX,i=this.scrollLeft;this.scrollLeft-=e;const s=this.stage.width(),n=z.timeToPixels(this.config.duration,this.config.zoom);this.scrollLeft=Math.max(0,Math.min(n-s,this.scrollLeft)),this.startDragX=t.clientX,this.render(),this.scrollLeft!==i&&this.onScrollChange(this.scrollLeft)}}handleZoom(t){const e=t.evt.deltaY;if(e===0)return;const i=e>0?.5:1.5,s=Math.max(ct.MIN,Math.min(ct.MAX,this.config.zoom*i));if(s!==this.config.zoom){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const n=t.evt.offsetX;this.animateZoom(s,n)}}animateZoom(t,e){const i=this.config.zoom,s=Os.DURATION,n=Date.now(),r=this.pixelToTime(e),o=()=>{const l=Date.now()-n,h=Math.min(l/s,1),c=this.easeOutCubic(h),d=i+(t-i)*c,u=z.timeToPixels(r,d),p=Math.max(0,u-(e-this.leftPadding));if(this.scrollLeft=p,this.config.zoom=d,this.onZoomChange(d),this.onScrollChange(p),this.render(),h<1)this.animationFrameId=requestAnimationFrame(o);else{const f=z.timeToPixels(r,t),y=Math.max(0,f-(e-this.leftPadding));this.config.zoom=t,this.scrollLeft=y,this.onZoomChange(t),this.onScrollChange(y),this.render()}};this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),o()}animateHorizontalScroll(t){const e=this.scrollLeft,i=300,s=Date.now(),n=this.stage.width(),r=z.timeToPixels(this.config.duration,this.config.zoom);this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const o=()=>{const l=Date.now()-s,h=Math.min(l/i,1),c=this.easeOutCubic(h),d=e+(t-e)*c;this.scrollLeft=Math.max(0,Math.min(r-n,d)),this.onScrollChange(this.scrollLeft),this.render(),h<1?this.animationFrameId=requestAnimationFrame(o):(this.scrollLeft=Math.max(0,Math.min(r-n,t)),this.onScrollChange(this.scrollLeft),this.render())};o()}easeOutCubic(t){return 1-Math.pow(1-t,3)}handleClick(t){const e=this.pixelToTime(t);this.setCurrentTime(e)}pixelToTime(t){return z.pixelsToTime(t-this.leftPadding+this.scrollLeft,this.config.zoom)}timeToPixel(t){return z.timeToPixels(t,this.config.zoom)-this.scrollLeft+this.leftPadding}setCurrentTime(t){this.config.currentTime=Math.max(0,t),this.onTimeChange(this.config.currentTime)}setZoom(t){this.config.zoom=t,this.render()}setDuration(t){this.config.duration=t,this.render()}setPlayState(t){this.config.playState=t,this.render()}update(){this.render()}render(){const t=this.stage.width(),e=this.stage.height(),i=this.gridLayer.findOne(".timeline-background");if(i)i.width(t),i.height(e),i.fill(this.theme.background),i.stroke(this.theme.border);else{const s=it.createRect(0,0,t,e,this.theme.background,this.theme.border,1);s.name("timeline-background"),this.gridLayer.add(s)}this.gridLayer.find(".grid-line").forEach(s=>s.remove()),this.gridLayer.find(".time-tick-line").forEach(s=>s.remove()),this.gridLayer.find(".time-tick-text").forEach(s=>s.remove()),this.renderTimeTicks(),this.renderScrollbar(),this.gridLayer.batchDraw()}renderScrollbar(){const t=this.stage.width(),e=this.stage.height(),i=Math.max(this.timeScaleHeight,e-this.scrollbarHeight-this.scrollbarMargin),s=this.getScrollbarThumbWidth(),n=this.getScrollbarThumbX(s),r=this.gridLayer.findOne(".scrollbar-background");if(r)r.x(0),r.y(i),r.width(t),r.height(this.scrollbarHeight),r.fill(this.theme.scrollbarBackground||"#333333"),r.stroke(this.theme.scrollbarBorder||"#555555"),r.visible(!0);else{const l=it.createRect(0,i,t,this.scrollbarHeight,this.theme.scrollbarBackground||"#333333",this.theme.scrollbarBorder||"#555555",1);l.name("scrollbar-background"),this.gridLayer.add(l)}const o=this.gridLayer.findOne(".scrollbar-thumb");if(o)o.x(n),o.y(i),o.width(s),o.height(this.scrollbarHeight),o.fill(this.theme.scrollbarThumb||"#444444"),o.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555"),o.visible(s<t);else{const l=it.createRect(n,i,s,this.scrollbarHeight,this.theme.scrollbarThumb||"#444444",this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555",1);l.name("scrollbar-thumb"),l.visible(s<t),this.gridLayer.add(l)}}renderTimeTicks(){const t=this.stage.width(),e=this.scrollLeft,i=this.scrollLeft+t,s=z.pixelsToTime(e,this.config.zoom),n=z.pixelsToTime(i,this.config.zoom),r=z.msToSeconds(s),o=z.msToSeconds(n),l=10,h=r-l,c=o+l,{majorStep:d,minorStep:u}=z.getTickConfig(this.config.zoom),p=z.generateVisibleTicks(h,c,d,u);let f=0;const y=20;for(const T of p){const S=this.timeToPixel(T.time);S>=-y&&S<=t+y&&(it.drawTimeTick(this.gridLayer,S,0,this.timeScaleHeight,T.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},T.type,this.timeScaleHeight),f++)}O.debugLazy("Timeline",()=>`Timeline - scrollLeft: ${this.scrollLeft}px, zoom: ${this.config.zoom}px/s, visible time: ${Math.round(r)}s to ${Math.round(o)}s, ticks: ${p.length} generated, ${f} drawn`)}getConfig(){return{...this.config}}getScrollLeft(){return this.scrollLeft}setScrollLeft(t){const e=this.stage.width(),i=this.getTotalDurationPixels();this.scrollLeft=Math.max(0,Math.min(i-e,t)),this.render()}getTotalDurationPixels(){return z.timeToPixels(this.config.duration,this.config.zoom)}getScrollbarThumbWidth(){const t=this.stage.width(),e=this.getTotalDurationPixels();return e<=0||e<=t?t:Math.max(40,t/e*t)}getScrollbarThumbX(t){const e=this.stage.width(),i=this.getTotalDurationPixels(),s=Math.max(0,i-e);if(s<=0||t>=e)return 0;const n=e-t;return this.scrollLeft/s*n}jumpScrollbarToPointer(t){const e=this.stage.width(),i=this.getTotalDurationPixels(),s=Math.max(0,i-e);if(s<=0)return;const n=this.getScrollbarThumbWidth(),r=Math.max(1,e-n),l=Math.max(n/2,Math.min(e-n/2,t))-n/2,h=this.scrollLeft;this.scrollLeft=l/r*s,this.render(),this.scrollLeft!==h&&this.onScrollChange(this.scrollLeft)}scrollToTime(t){const e=z.timeToPixels(t,this.config.zoom),i=this.stage.width(),s=Math.max(0,e-i/2);this.setScrollLeft(s),this.onScrollChange(s)}scrollToClip(t){const e=z.timeToPixels(t.startTime,this.config.zoom),s=z.timeToPixels(t.startTime+t.duration,this.config.zoom)-e,n=this.stage.width();let r;s<=n?r=Math.max(0,e-(n-s)/2):r=Math.max(0,e),this.setScrollLeft(r),this.onScrollChange(r)}getStage(){return this.stage}getGridLayer(){return this.gridLayer}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}resize(t,e){this.render()}}const pe=8;function ht(a,t,e){return it.timeToPixels(a,t)-e+ot}function St(a,t){const e=it.timeToPixels(a,t);return a<=1e3||e<=ke?ke:e}function ys(a,t){const e=ht(a.startTime,a.zoom,a.scrollLeft),i=St(a.duration,a.zoom);return e+i>0&&e<t}function Io(a){for(const t of a.clips){const e=ht(t.startTime,a.zoom,a.scrollLeft),i=St(t.duration,a.zoom),s=a.y>=a.trackY&&a.y<=a.trackY+a.trackHeight;if(a.x>=e&&a.x<=e+pe&&s||a.x>=e+i-pe&&a.x<=e+i&&s)return"ew-resize";if(a.x>e+pe&&a.x<e+i-pe&&s)return"pointer"}return"default"}class Xe{constructor(t,e,i){g(this,"clip");g(this,"onUpdate");g(this,"onSplit");this.clip=Ei({...t,endTime:z.calculateEndTime(t.startTime,t.duration)},{isDragging:t.isDragging,isResizingLeft:t.isResizingLeft,isResizingRight:t.isResizingRight,isSelected:t.isSelected,isResizing:t.isResizing,zIndex:t.zIndex,opacity:t.opacity}),this.onUpdate=e,this.onSplit=i}getClip(){return{...this.clip}}applyPreviewState(t){this.clip={...this.clip,...t,endTime:z.calculateEndTime(t.startTime,t.duration)}}setSelected(t){this.clip={...this.clip,isSelected:t},this.onUpdate(this.clip)}isPointInResizeHandle(t,e,i,s,n,r){const o=ht(this.clip.startTime,i,r),l=St(this.clip.duration,i),h=pe;return e<s||e>s+n?(this.setResizeHandleState(!1,!1),!1):t>=o&&t<=o+h?(this.setResizeHandleState(!0,!1),!0):t>=o+l-h&&t<=o+l?(this.setResizeHandleState(!1,!0),!0):(this.setResizeHandleState(!1,!1),!1)}startDrag(t){this.clip={...this.clip,isDragging:!0,isResizing:!1,isResizingLeft:!1,isResizingRight:!1},this.onUpdate(this.clip)}startResize(t){this.clip={...this.clip,isDragging:!0,isResizing:!0},this.onUpdate(this.clip)}endDrag(){this.clip={...this.clip,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1}}split(t){t>this.clip.startTime+1&&t<this.clip.endTime-1&&this.onSplit(this.clip,t)}setResizeHandleState(t,e){this.clip={...this.clip,isResizingLeft:t,isResizingRight:e}}}function je(){return{kind:"idle"}}function hi(a){return!!a&&a.kind!=="idle"}function Te(a){return(a==null?void 0:a.kind)==="draggingMove"||(a==null?void 0:a.kind)==="draggingResizeLeft"||(a==null?void 0:a.kind)==="draggingResizeRight"}function Zt(a){return!a||a.kind==="idle"||a.kind==="boxSelecting"?null:a.context}function ve(a){return!a||a.kind==="idle"||a.kind==="boxSelecting"?null:a.kind==="pressed"?a.operation:a.kind==="draggingResizeLeft"?"resize-left":a.kind==="draggingResizeRight"?"resize-right":"move"}function Mo(a){const t=ve(a);return t?t==="move"?"grabbing":"ew-resize":null}function ze(a,t){if(t.type==="POINTER_DOWN")return{state:{kind:"pressed",operation:t.operation,context:{clipId:t.clipId,originalClipsState:t.originalClipsState,nonDraggedClips:t.nonDraggedClips,snapCandidateClips:t.snapCandidateClips,pointerStartClientX:t.clientX,pointerStartClientY:t.clientY,pointerStartX:t.localX,pointerStartY:t.localY,dragStartScrollLeft:t.scrollLeft,lastPointerClientX:t.clientX,lastPointerClientY:t.clientY,dragTargetTrackY:t.localY,crossTrackDragOffsetY:0}},effects:{bindGlobalListeners:!0}};if(t.type==="BOX_SELECT_START")return{state:{kind:"boxSelecting",context:{startClientX:t.clientX,startClientY:t.clientY,startLocalX:t.localX,startLocalY:t.localY,currentClientX:t.clientX,currentClientY:t.clientY,currentLocalX:t.localX,currentLocalY:t.localY,additive:t.additive}},effects:{bindGlobalListeners:!0}};if(a.kind==="idle")return{state:a,effects:{}};if(a.kind==="boxSelecting")return t.type==="BOX_SELECT_MOVE"?{state:{kind:"boxSelecting",context:{...a.context,currentClientX:t.clientX,currentClientY:t.clientY,currentLocalX:t.localX,currentLocalY:t.localY}},effects:{updatePreview:!0}}:t.type==="BOX_SELECT_END"||t.type==="POINTER_UP"||t.type==="CANCEL"||t.type==="VISIBILITY_HIDDEN"||t.type==="WINDOW_BLUR"?{state:je(),effects:{unbindGlobalListeners:!0,commit:t.type==="BOX_SELECT_END"||t.type==="POINTER_UP",cleanup:!0}}:{state:a,effects:{}};if(t.type==="POINTER_MOVE"){const i=Do(a.context,t,ve(a)||"move");return a.kind==="pressed"?Ro(a.context,t.activationThreshold,t.clientX,t.clientY)?{state:Lo(a.operation,i),effects:{updatePreview:!0}}:{state:{...a,context:i},effects:{}}:{state:{...a,context:i},effects:{updatePreview:!0}}}if(t.type==="SCROLL_LEFT_CHANGED")return{state:a,effects:{updatePreview:Te(a)}};const e=t.type==="POINTER_UP"&&Te(a);return{state:je(),effects:{unbindGlobalListeners:!0,commit:e,cleanup:!0}}}function Lo(a,t){return a==="resize-left"?{kind:"draggingResizeLeft",context:t}:a==="resize-right"?{kind:"draggingResizeRight",context:t}:{kind:"draggingMove",context:t}}function Do(a,t,e){const i=e==="move";return{...a,lastPointerClientX:t.clientX,lastPointerClientY:t.clientY,dragTargetTrackY:i?t.localY:a.pointerStartY,crossTrackDragOffsetY:i?t.localY-a.pointerStartY:0}}function Ro(a,t,e,i){const s=e-a.pointerStartClientX,n=i-a.pointerStartClientY;return Math.hypot(s,n)>=Math.max(0,t)}const yt=class yt{constructor(t,e,i,s,n,r,o,l,h,c,d,u,p,f,y,T,S,v,b,k,M,_,R,A,I,D=yt.DEFAULT_DRAG_ACTIVATION_THRESHOLD,N=!1,G=yt.DEFAULT_CLIP_SNAP_THRESHOLD){g(this,"layer");g(this,"trackGroup");g(this,"dragOverlayLayer",null);g(this,"dropPreviewGroup",null);g(this,"dropPreviewClips",[]);g(this,"config");g(this,"theme");g(this,"trackType");g(this,"clips",[]);g(this,"clipGroups",new Map);g(this,"zoom",100);g(this,"scrollLeft",0);g(this,"trackY",0);g(this,"trackHeight",64);g(this,"selectedClip",null);g(this,"hasSelectedClip",!1);g(this,"selectedClipIds",new Set);g(this,"multiDragOriginalPositions",new Map);g(this,"promotedClipParents",new Map);g(this,"interactionState",je());g(this,"isVisualUpdate",!1);g(this,"onClipUpdate");g(this,"onClipAdd");g(this,"onClipRemove");g(this,"onClipSplit");g(this,"onClipSelect");g(this,"onTimeJump");g(this,"onClipOverlap");g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"hasLockedGlobalCursor",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"onHorizontalDragAutoScroll");g(this,"onClipCrossTrackPreview");g(this,"onClipCrossTrack");g(this,"onClearDropPreview");g(this,"onClearSelection");g(this,"onSnapGuideChange");g(this,"onClipToggleSelection");g(this,"onSetSingleSelection");g(this,"getMultiDragClipIds");g(this,"onMultiDragMove");g(this,"onMultiDragInteractionEnd");g(this,"resolveSnapTargetClips");g(this,"dragActivationThreshold");g(this,"enableClipSnap");g(this,"clipSnapThreshold");g(this,"handleGlobalPointerMove",t=>{hi(this.interactionState)&&this.handleDragMove(t)});g(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});g(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});g(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const t=this.resolveInteractionState();if(!Te(t)||!this.onHorizontalDragAutoScroll)return;const e=this.layer.getStage(),i=e==null?void 0:e.container(),s=Zt(t);if(!i||!s){this.stopEdgeAutoScroll();return}const n=i.getBoundingClientRect(),r=s.lastPointerClientX-n.left,o=this.calculateHorizontalAutoScrollVelocity(r,n.width);if(o===0){this.stopEdgeAutoScroll();return}const l=this.scrollLeft,h=this.onHorizontalDragAutoScroll(this.scrollLeft+o),c=typeof h=="number"?h:this.scrollLeft;if(Math.abs(c-l)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.layer=t,this.config=e,this.theme=o,this.trackType=i,this.zoom=s,this.trackY=n,this.trackHeight=r,this.onClipUpdate=l,this.onClipAdd=h,this.onClipRemove=c,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=p,this.onHorizontalDragAutoScroll=f,this.onClipOverlap=y,this.onClipCrossTrackPreview=T,this.onClipCrossTrack=S,this.onClearDropPreview=v,this.onClearSelection=b,this.onSnapGuideChange=k,this.onClipToggleSelection=M,this.onSetSingleSelection=_,this.getMultiDragClipIds=R,this.onMultiDragMove=A,this.onMultiDragInteractionEnd=I,this.dragActivationThreshold=Math.max(0,D),this.enableClipSnap=N,this.clipSnapThreshold=Math.max(0,G),this.trackGroup=it.createGroup(0,n),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}initClips(){this.clips=this.config.clips.map(t=>{const e=new Xe(t,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));return this.createClipGroup(t),e})}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const t=it.createGroup(0,0);return t.name("clip-drop-preview"),t.visible(!1),t.listening(!1),this.trackGroup.add(t),this.dropPreviewGroup=t,t}createDropPreviewRect(t){const e=this.trackType==="video"?"rgba(80, 227, 194, 0.18)":"rgba(181, 186, 255, 0.18)",i=this.trackType==="video"?"#50e3c2":"#b5baff",s=ht(t.startTime,this.zoom,this.scrollLeft),n=St(t.duration,this.zoom),r=it.createRect(s,2,Math.max(n,1),Math.max(this.trackHeight-4,1),e,i,1);return r.dash([6,4]),r.cornerRadius(4),r.listening(!1),r.visible(s+n>0&&s<this.layer.width()),r}showDropPreview(t){const e=this.ensureDropPreviewGroup(),i=Array.isArray(t)?t:[t];this.dropPreviewClips=i.map(n=>({...n})),e.destroyChildren();let s=!1;for(const n of this.dropPreviewClips){const r=this.createDropPreviewRect(n);s=s||r.visible(),e.add(r)}e.x(0),e.y(0),e.visible(s),e.moveToTop()}hideDropPreview(){var t;this.dropPreviewClips=[],(t=this.dropPreviewGroup)==null||t.visible(!1)}initEventListeners(){const t=this.layer.getStage();t&&t.on("mouseup",()=>{this.handleClipMouseUp()})}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Pe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(xe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}),this.hasBoundGlobalPointerListenersForDrag=!1)}handleTrackBackgroundClick(t){const e=this.layer.getStage();if(!e)return;const i=e.container();if(!i)return;const s=i.getBoundingClientRect(),n=t.clientX-s.left,r=Math.max(0,z.pixelsToTime(n-ot+this.scrollLeft,this.zoom));this.onTimeJump(r),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(t){}updateClipSelection(t,e){var s;const i=this.clips.find(n=>n.getClip().id===t);i&&(this.isVisualUpdate=!0,i.setSelected(e),this.isVisualUpdate=!1,e?(this.selectedClipIds.add(t),this.selectedClip=i,this.hasSelectedClip=!0):(this.selectedClipIds.delete(t),((s=this.selectedClip)==null?void 0:s.getClip().id)===t&&(this.selectedClip=null,this.hasSelectedClip=!1)),this.updateClipGroup(i.getClip()),this.layer.batchDraw())}createClipGroup(t){const e=ht(t.startTime,this.zoom,this.scrollLeft),i=St(t.duration,this.zoom),s=2,n=this.trackHeight-4,r=it.createClipGroup(e,s,i,n,t.name,t.duration,this.theme,!1,t.thumbnails,t.src,t.type,!!t.separatedAudioClipId);r.name(`clip-${t.id}`),r.on("click",o=>{this.handleClipClick(t.id,o.evt)}),r.on("mousedown",o=>{this.handleClipMouseDown(t.id,o.evt)}),r.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),r.on("mouseleave",()=>{this.handleClipMouseLeave()}),r.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(r),this.clipGroups.set(t.id,r)}handleClipClick(t,e){if(e.button!==0)return;this.clips.find(s=>s.getClip().id===t)&&this.render()}handleClipMouseDown(t,e){var c;if(e.button!==0)return;if(e.ctrlKey||e.metaKey){this.onClipToggleSelection&&this.onClipToggleSelection(t);return}const i=(c=this.getMultiDragClipIds)==null?void 0:c.call(this,t),s=i!=null&&i.length>1;if(!s)this.selectedClipIds.clear(),this.selectedClipIds.add(t),this.onSetSingleSelection&&this.onSetSingleSelection(t);else{this.selectedClipIds.clear();for(const d of i)this.selectedClipIds.add(d)}this.clips.sort((d,u)=>d.getClip().startTime-u.getClip().startTime);const n=this.clips.map(d=>({...d.getClip()})),r=this.clips.filter(d=>d.getClip().id!==t).map(d=>({...d.getClip()})),l=(this.resolveSnapTargetClips?this.resolveSnapTargetClips():this.clips.map(d=>d.getClip())).filter(d=>d.id!==t).map(d=>({...d})),h=this.clips.find(d=>d.getClip().id===t);if(h){s||(this.applySelectionVisual(t),this.onClipSelect(h.getClip())),this.selectedClip=h;const d=this.layer.getStage();if(!d)return;const u=d.container();if(!u)return;const p=u.getBoundingClientRect(),f=e.clientX-p.left,y=e.clientY-p.top;if(s){this.multiDragOriginalPositions.clear();for(const S of this.selectedClipIds){const v=this.clips.find(b=>b.getClip().id===S);if(v){const b=v.getClip();this.multiDragOriginalPositions.set(S,{startTime:b.startTime,duration:b.duration})}}}let T;h.isPointInResizeHandle(f,y,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(T=h.getClip().isResizingLeft?"resize-left":"resize-right",h.startResize({x:f,y})):(T="move",h.startDrag({x:f,y}),this.trackGroup.moveToTop()),this.applyInteractionTransition(ze(this.interactionState,{type:"POINTER_DOWN",operation:T,clipId:t,originalClipsState:n,nonDraggedClips:r,snapCandidateClips:l,clientX:e.clientX,clientY:e.clientY,localX:f,localY:y,scrollLeft:this.scrollLeft})),this.render()}}handleClipMouseMove(t){this.updateHoverCursor(t.clientX,t.clientY)}handleTrackBackgroundMouseMove(){if(this.isDragSessionActive())return;const t=this.layer.getStage(),e=t==null?void 0:t.container();e&&(e.style.cursor="default")}handleClipMouseUp(){this.finishPointerInteraction("POINTER_UP")}finishPointerInteraction(t){const e=this.interactionState;try{if(!this.selectedClip)return;const i=this.selectedClip.getClip();if(!i.isDragging)return;const s=i;this.selectedClip.endDrag();const n=ze(e,{type:t});this.interactionState=n.state,n.effects.commit&&this.handleClipMoveEnd(s,e),this.layer.batchDraw()}finally{this.interactionState=je(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}applyInteractionTransition(t){var i,s;this.interactionState=t.state,this.syncLegacyInteractionMirror(t.state),t.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const e=Mo(t.state);e&&this.lockPointerCursor(e),t.effects.cleanup&&(this.releasePointerCursor(),this.hideDropPreview(),(i=this.onClearDropPreview)==null||i.call(this),this.updateSnapGuideLine(null),this.stopEdgeAutoScroll(),this.clearClipDragOverlay(),this.multiDragOriginalPositions.size>0&&((s=this.onMultiDragInteractionEnd)==null||s.call(this),this.multiDragOriginalPositions.clear())),t.effects.unbindGlobalListeners&&this.unbindGlobalPointerListenersForDrag()}resolveInteractionState(t=this.interactionState){var r;if(hi(t))return t;const e=this,i=(r=this.selectedClip)==null?void 0:r.getClip();if(!(i!=null&&i.id)||!i.isDragging)return t;const s=e.activePointerOperation||(i.isResizingLeft?"resize-left":i.isResizingRight?"resize-right":"move"),n={clipId:i.id,originalClipsState:Array.isArray(e.originalClipsState)?e.originalClipsState:[],nonDraggedClips:Array.isArray(e.nonDraggedClips)?e.nonDraggedClips:[],snapCandidateClips:Array.isArray(e.snapCandidateClips)?e.snapCandidateClips:[],pointerStartClientX:typeof e.dragGestureStartClientX=="number"?e.dragGestureStartClientX:0,pointerStartClientY:typeof e.dragGestureStartClientY=="number"?e.dragGestureStartClientY:0,pointerStartX:typeof e.crossTrackDragStartX=="number"?e.crossTrackDragStartX:0,pointerStartY:typeof e.dragStartY=="number"?e.dragStartY:0,dragStartScrollLeft:typeof e.dragStartScrollLeft=="number"?e.dragStartScrollLeft:this.scrollLeft,lastPointerClientX:typeof e.lastDragClientX=="number"?e.lastDragClientX:0,lastPointerClientY:typeof e.lastDragClientY=="number"?e.lastDragClientY:0,dragTargetTrackY:typeof e.dragTargetTrackY=="number"?e.dragTargetTrackY:0,crossTrackDragOffsetY:typeof e.crossTrackDragOffsetY=="number"?e.crossTrackDragOffsetY:0};return e.hasDragMoved?s==="resize-left"?{kind:"draggingResizeLeft",context:n}:s==="resize-right"?{kind:"draggingResizeRight",context:n}:{kind:"draggingMove",context:n}:{kind:"pressed",operation:s,context:n}}syncLegacyInteractionMirror(t=this.interactionState){const e=this,i=Zt(t);e.hasDragMoved=Te(t),e.activePointerOperation=ve(t),e.originalClipsState=(i==null?void 0:i.originalClipsState)??[],e.nonDraggedClips=(i==null?void 0:i.nonDraggedClips)??[],e.snapCandidateClips=(i==null?void 0:i.snapCandidateClips)??[],e.dragStartY=(i==null?void 0:i.pointerStartY)??0,e.dragTargetTrackY=(i==null?void 0:i.dragTargetTrackY)??0,e.crossTrackDragOffsetY=(i==null?void 0:i.crossTrackDragOffsetY)??0,e.crossTrackDragStartX=(i==null?void 0:i.pointerStartX)??0,e.dragStartScrollLeft=(i==null?void 0:i.dragStartScrollLeft)??0,e.dragGestureStartClientX=(i==null?void 0:i.pointerStartClientX)??null,e.dragGestureStartClientY=(i==null?void 0:i.pointerStartClientY)??null,e.lastDragClientX=(i==null?void 0:i.lastPointerClientX)??null,e.lastDragClientY=(i==null?void 0:i.lastPointerClientY)??null}handleClipMoveEnd(t,e){var T,S,v;const i=this.resolveInteractionState(e),s=this,n=Zt(i)||{clipId:t.id,originalClipsState:Array.isArray(s.originalClipsState)?s.originalClipsState:[t],nonDraggedClips:Array.isArray(s.nonDraggedClips)?s.nonDraggedClips:[],snapCandidateClips:Array.isArray(s.snapCandidateClips)?s.snapCandidateClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:typeof s.dragTargetTrackY=="number"?s.dragTargetTrackY:0,crossTrackDragOffsetY:typeof s.crossTrackDragOffsetY=="number"?s.crossTrackDragOffsetY:0},o=(ve(i)||s.activePointerOperation||"move")==="move",l=o&&this.multiDragOriginalPositions.size>0,h=(T=this.clipGroups)==null?void 0:T.get(t.id);if(h&&h.y(2),l){const b=this.multiDragOriginalPositions.get(t.id),k=b?t.startTime-b.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:t.id,deltaTime:k,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!0})){for(const D of this.selectedClipIds){const N=(S=this.clipGroups)==null?void 0:S.get(D);N==null||N.y(2)}this.multiDragOriginalPositions.clear();return}const M=[],_=[];for(const[I,D]of this.multiDragOriginalPositions){const N=this.clips.find(L=>L.getClip().id===I);if(!N)continue;const G=Math.max(0,D.startTime+k),W={...N.getClip(),startTime:G,endTime:G+D.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(I)};M.push(W);const F=n.originalClipsState.find(L=>L.id===I);F&&_.push(F);const H=(v=this.clipGroups)==null?void 0:v.get(I);H&&H.y(2)}const R=[];for(const I of this.clips){const D=I.getClip(),N=M.find(G=>G.id===D.id);N?R.push(N):R.push({...D,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}R.sort((I,D)=>I.startTime-D.startTime),this.isVisualUpdate=!0;for(const I of R)this.clips.find(N=>N.getClip().id===I.id)&&this.handleClipUpdate(I);this.isVisualUpdate=!1;const A=_.map(I=>{const D=M.find(N=>N.id===I.id);return D&&(I.startTime!==D.startTime||I.duration!==D.duration)?{clipId:I.id,previousState:I,newState:D}:null}).filter(I=>I!==null);A.length>0&&this.onClipUpdate(t,_.find(I=>I.id===t.id),A),this.multiDragOriginalPositions.clear();return}if(o&&this.onClipCrossTrack&&this.config.id){const b=n.originalClipsState.find(M=>M.id===t.id)??null;if(this.onClipCrossTrack(t,b,n.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}const c=o?[...n.nonDraggedClips]:[];let d=!1;const u=t.startTime+t.duration;for(const b of c){const k=b.startTime+b.duration;if(t.startTime<k&&u>b.startTime){d=!0;break}}if(o&&d&&this.onClipOverlap&&this.config.id){this.onClipOverlap(t,this.config.id);return}const p=[...n.nonDraggedClips];let f=p.findIndex(b=>b.startTime>=t.startTime);f===-1&&(f=p.length),n.nonDraggedClips.forEach(b=>{b.isSelected=!1});const y={...t,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};p.splice(f,0,y),this.updateAllClips(p),this.buildAndSendUpdates(y,p,n.originalClipsState)}updateAllClips(t){const e=this.clips??[];this.isVisualUpdate=!0,t.forEach(i=>{e.find(n=>n.getClip().id===i.id)&&this.handleClipUpdate(i)}),this.isVisualUpdate=!1,e.sort((i,s)=>i.getClip().startTime-s.getClip().startTime),this.clips=e}buildAndSendUpdates(t,e,i){const s=i.map(n=>{const r=e.find(o=>o.id===n.id);return r&&(n.startTime!==r.startTime||n.duration!==r.duration||n.opacity!==r.opacity)?{clipId:n.id,previousState:n,newState:r}:null}).filter(n=>n!==null);s.length>0&&this.onClipUpdate(t,i.find(n=>n.id===t.id),s)}updateHoverCursor(t,e){const i=this.layer.getStage();if(!i)return;const s=i.container();if(!s||this.isDragSessionActive())return;const n=s.getBoundingClientRect(),r=t-n.left,o=e-n.top;s.style.cursor=Io({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:r,y:o})}isDragSessionActive(){return hi(this.resolveInteractionState())}handleDragMove(t){const e=this.resolveInteractionState(),i=this.layer.getStage(),s=i==null?void 0:i.container();if(!s)return;const n=s.getBoundingClientRect(),r=ze(e,{type:"POINTER_MOVE",clientX:t.clientX,clientY:t.clientY,localY:t.clientY-n.top,activationThreshold:this.dragActivationThreshold});this.interactionState=r.state,this.syncLegacyInteractionMirror(r.state),r.effects.updatePreview&&this.updateDraggedClipFromPointer(t.clientX,t.clientY,!0)}handleClipMouseLeave(){if(this.isDragSessionActive())return;const t=this.layer.getStage();t&&t.container()&&(t.container().style.cursor="default")}lockPointerCursor(t){const e=typeof this.layer.getStage=="function"?this.layer.getStage():null,i=e==null?void 0:e.container();i&&(i.style.cursor=t),typeof document<"u"&&document.body&&(document.body.style.cursor=t,this.hasLockedGlobalCursor=!0)}releasePointerCursor(){const t=typeof this.layer.getStage=="function"?this.layer.getStage():null,e=t==null?void 0:t.container();e&&(e.style.cursor="default"),this.hasLockedGlobalCursor&&typeof document<"u"&&document.body&&(document.body.style.cursor="",this.hasLockedGlobalCursor=!1)}updateClipGroup(t,e=!1){const i=this.clipGroups.get(t.id);if(i){const s=ht(t.startTime,this.zoom,this.scrollLeft),n=St(t.duration,this.zoom);i.x(s),i.visible(ys({startTime:t.startTime,duration:t.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width()));const r=t.isSelected;(t.isDragging||r)&&i.moveToTop(),i.opacity(t.opacity),it.updateClipGroup(i,n,this.trackHeight-4,t.name,t.duration,this.theme,r,t.thumbnails,t.src,t.type,!!t.separatedAudioClipId,e)}}handleClipUpdate(t){var i,s;const e=this.clips.findIndex(n=>n.getClip().id===t.id);if(e!==-1){const n=this.clips[e].getClip(),r={...t,isSelected:this.isVisualUpdate||((i=this.selectedClip)==null?void 0:i.getClip().id)===t.id?t.isSelected:!1};this.clips[e]=new Xe(r,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this)),((s=this.selectedClip)==null?void 0:s.getClip().id)===t.id&&(this.selectedClip=this.clips[e]),this.updateClipGroup(r);const o=this.clipGroups.get(t.id);o&&o.opacity(r.opacity),this.isVisualUpdate||this.onClipUpdate(r,n),this.layer.batchDraw()}}handleClipSplit(t,e){const i=e-t.startTime,s=t.duration-i,n=t.startTimeAtSource+i,r={...t,duration:i,endTime:e,endTimeAtSource:n},o={...t,id:`${t.id}_split_${Date.now()}`,startTime:e,duration:s,endTime:z.calculateEndTime(e,s),startTimeAtSource:n,endTimeAtSource:t.endTimeAtSource};this.removeClip(t.id),this.addClip(r),this.addClip(o),this.onClipSplit(r,o),this.layer.batchDraw()}addClip(t){if(t.type!==this.trackType){O.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${t.type}`);return}const e={...t,isSelected:!1},i=new Xe(e,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));this.clips.push(i),this.createClipGroup(e),this.onClipAdd(e),this.layer.batchDraw()}removeClip(t){var i;const e=this.clips.findIndex(s=>s.getClip().id===t);if(e!==-1){this.clips.splice(e,1),((i=this.selectedClip)==null?void 0:i.getClip().id)===t&&(this.selectedClip=null);const s=this.clipGroups.get(t);s&&(this.getPromotedClipParents().delete(t),s.remove(),this.clipGroups.delete(t)),this.onClipRemove(t),this.hideDropPreview(),this.layer.batchDraw()}}updateClip(t,e){const i=this.clips.find(s=>s.getClip().id===t);if(i){const n={...i.getClip(),...e};(e.startTime!==void 0||e.duration!==void 0)&&(n.endTime=n.startTime+n.duration),this.handleClipUpdate(n)}}setZoom(t){this.zoom=t,this.clips.forEach(e=>{this.updateClipGroup(e.getClip())}),this.layer.batchDraw()}setCurrentTime(t){this.layer.batchDraw()}setScrollLeft(t){this.scrollLeft=t,this.clips.forEach(n=>{const r=n.getClip();this.updateClipGroup(r),this.updateClipVisibility(r)});const e=this.resolveInteractionState(),i=Zt(e),s=ze(e,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=s.state,this.syncLegacyInteractionMirror(s.state),s.effects.updatePreview&&i&&this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1),this.layer.batchDraw()}updateClipVisibility(t){const e=this.clipGroups.get(t.id);if(e){const i=ys({startTime:t.startTime,duration:t.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width());e.visible(i)}}setTrackY(t){const e=t-this.trackY;this.trackY=t,this.trackGroup.y(t),this.getPromotedClipParents().forEach((i,s)=>{i.baseY=t;const n=this.clipGroups.get(s);n&&n.y(n.y()+e)})}setTrackStackOrder(t){this.trackGroup.zIndex(t)}setDragOverlayLayer(t){this.dragOverlayLayer=t}setClipsDragOverlayActive(t,e){t.forEach(i=>{this.setClipDragOverlayActive(i,e)})}clearClipDragOverlay(){Array.from(this.getPromotedClipParents().keys()).forEach(t=>{this.setClipDragOverlayActive(t,!1)})}getTrackType(){return this.trackType}render(t=!0){const e=this.getTrackBackgroundFill();if(this.trackGroup.children.length===0){const i=it.createRect(0,0,this.layer.width(),this.trackHeight,e,this.theme.trackBorder,1);i.name("track-background"),i.on("click",s=>{this.handleTrackBackgroundClick(s.evt)}),i.on("mousedown",s=>{this.handleTrackBackgroundMouseDown(s.evt)}),i.on("mousemove",()=>{this.handleTrackBackgroundMouseMove()}),i.on("mouseleave",()=>{this.handleClipMouseLeave()}),this.trackGroup.add(i)}else{const i=this.trackGroup.findOne(".track-background");i&&(i.width(this.layer.width()),typeof i.height=="function"&&i.height(this.trackHeight),i.fill(e),i.stroke(this.theme.trackBorder),i.listening()||i.listening(!0))}t&&this.layer.batchDraw()}getTrackBackgroundFill(){return this.hasSelectedClip?this.theme.trackSelectedBackground||"#292929":this.theme.trackBackground}getClips(){return this.clips.map(t=>t.getClip())}getSelectedClip(){return this.selectedClip?this.selectedClip.getClip():null}clearSelection(){this.selectedClipIds.clear(),this.updateSelectionVisual(null)}updateSelectionVisual(t){if(this.applySelectionVisual(t),t){const e=this.clips.find(i=>i.getClip().id===t);this.selectedClip=e||null,this.hasSelectedClip=!!e}else this.selectedClip=null,this.hasSelectedClip=!1;this.render()}selectClip(t){const e=this.clips.find(i=>i.getClip().id===t);e&&this.onClipSelect(e.getClip())}applySelectionVisual(t){this.isVisualUpdate=!0;try{this.clips.forEach(e=>{const i=e.getClip().id,s=t!==null&&i===t;e.setSelected(s)})}finally{this.isVisualUpdate=!1}}splitSelectedClip(t){const e=this.clips.find(i=>{const s=i.getClip();return t>=s.startTime&&t<s.endTime});e&&e.split(t)}removeClipGaps(){O.debugLazy("Track",()=>"Removing clip gaps");const t=this.clips.map(i=>i.getClip()).sort((i,s)=>i.startTime-s.startTime);if(t.length===0)return;let e=0;for(let i=0;i<t.length;i++){const s=t[i];if(e-s.startTime<0||i===0){const r=e,o=r+s.duration;this.handleClipUpdate({...s,startTime:r,endTime:o}),e=o}else e=s.startTime+s.duration}}getTrackGroup(){return this.trackGroup}getId(){return this.config.id||"default"}updateClipPosition(t,e,i,s=0){var l;const n=this.clips.find(h=>h.getClip().id===t);if(!n)return;const r=n.getClip(),o=this.clipGroups.get(t);if(i)this.setClipDragOverlayActive(t,!1),this.updateClipPositionFinal(t,e);else if(o){const h=ht(e,this.zoom,this.scrollLeft);o.x(h),o.y(this.resolveClipRenderY(t,s)),o.moveToTop(),it.updateClipGroup(o,St(r.duration,this.zoom),this.trackHeight-4,r.name,r.duration,this.theme,!0,r.thumbnails,r.src,r.type,!!r.separatedAudioClipId,!0),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw()}}updateClipPositionFinal(t,e){const i=this.clips.find(r=>r.getClip().id===t);if(!i)return;const s=i.getClip(),n=this.clipGroups.get(t);this.setClipDragOverlayActive(t,!1),n==null||n.y(2),this.isVisualUpdate=!0,this.handleClipUpdate({...s,startTime:e,endTime:e+s.duration}),this.isVisualUpdate=!1}setTrackHeight(t){var e,i;if(this.trackHeight=t,(e=this.dropPreviewGroup)!=null&&e.visible()&&Array.isArray(this.dropPreviewClips)&&this.dropPreviewClips.length>0)this.showDropPreview(this.dropPreviewClips);else if((i=this.dropPreviewGroup)!=null&&i.visible()){const s=this.dropPreviewGroup.children[0];s==null||s.height(Math.max(this.trackHeight-4,1))}this.clips.forEach(s=>{this.updateClipGroup(s.getClip(),!0)}),this.render(!1)}showClipDropPreview(t){this.showDropPreview(t),this.layer.batchDraw()}showClipDropPreviews(t){this.showDropPreview(t),this.layer.batchDraw()}clearClipDropPreview(){this.hideDropPreview(),this.layer.batchDraw()}getRole(){return this.config.role||"normal"}setClipSnapEnabled(t){this.enableClipSnap=t,t||this.updateSnapGuideLine(null);const e=this.resolveInteractionState(),i=Zt(e);if(Te(e)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(t){this.resolveSnapTargetClips=t}updateDraggedClipFromPointer(t,e,i){var T,S,v,b,k;const s=this.resolveInteractionState(),n=Zt(s),r=ve(s),o=this.layer.getStage();if(!o||!this.selectedClip||!n||!r)return;const l=o.container();if(!l)return;const h=l.getBoundingClientRect(),c=t-h.left,d=e-h.top,u=r==="move",p=u&&this.multiDragOriginalPositions.size>0;u&&O.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:d,currentTrackId:this.config.id,offsetY:n.crossTrackDragOffsetY}));const f=this.selectedClip.getClip(),y=(T=this.clipGroups)==null?void 0:T.get(f.id);if(y){const M=u&&n.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(f.id,M);const _=n.originalClipsState.find(F=>F.id===f.id);if(!_)return;const R=this.buildPreviewClip(f,_,c,n,r);if(!R){this.hideDropPreview(),(S=this.onClearDropPreview)==null||S.call(this),this.updateSnapGuideLine(null);return}const A=R.clip,I=A.startTime-_.startTime,D=this.applyPreviewClipState(A),N=ht(A.startTime,this.zoom,this.scrollLeft),G=St(A.duration,this.zoom);y.x(N),y.y(this.resolveClipRenderY(f.id,n.crossTrackDragOffsetY)),y.visible(N+G>0&&N<this.layer.width()),D&&(this.updateClipGroup(A),y.y(this.resolveClipRenderY(f.id,n.crossTrackDragOffsetY)));let W=!1;if(p){this.onMultiDragMove&&this.config.id&&(W=this.onMultiDragMove({draggedClipId:f.id,deltaTime:I,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[F,H]of this.multiDragOriginalPositions){if(F===f.id)continue;const L=this.clips.find(U=>U.getClip().id===F);if(!L)continue;const j=Math.max(0,H.startTime+I),B=(v=this.clipGroups)==null?void 0:v.get(F);if(B){const U=ht(j,this.zoom,this.scrollLeft);B.x(U),B.y(this.resolveClipRenderY(F,n.crossTrackDragOffsetY)),B.visible(U+St(H.duration,this.zoom)>0&&U<this.layer.width());const q=L.getClip();it.updateClipGroup(B,St(q.duration,this.zoom),this.trackHeight-4,q.name,q.duration,this.theme,!0,q.thumbnails,q.src,q.type,!!q.separatedAudioClipId,!0)}}}u&&this.onClipCrossTrackPreview&&this.config.id&&!W?this.onClipCrossTrackPreview(A,n.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():W?this.hideDropPreview():this.showDropPreview(A),this.updateSnapGuideLine(R.guideTime)}else this.hideDropPreview(),(b=this.onClearDropPreview)==null||b.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(c,h.width),this.layer.batchDraw(),(k=this.dragOverlayLayer)==null||k.batchDraw()}buildPreviewClip(t,e,i,s,n){const r=i-s.pointerStartX+(this.scrollLeft-s.dragStartScrollLeft),o=z.pixelsToTime(r,this.zoom);let l;return n==="resize-left"||t.isResizingLeft?l=this.buildResizeLeftPreviewClip(t,e,o):n==="resize-right"||t.isResizingRight?l=this.buildResizeRightPreviewClip(t,e,o):l={...t,startTime:Math.max(0,e.startTime+o),endTime:Math.max(0,e.startTime+o)+t.duration},this.constrainResizePreviewToTrackBounds(this.applyClipSnap(l,e,s.snapCandidateClips),e,s.nonDraggedClips)}constrainResizePreviewToTrackBounds(t,e,i){if(t.clip.isResizingLeft){const s=this.getResizeLeftBoundaryStart(e,i);if(t.clip.startTime>=s)return t;const n=t.clip.endTime,r=n-s;return{clip:{...t.clip,startTime:s,duration:r,endTime:n,startTimeAtSource:e.endTimeAtSource-r,endTimeAtSource:e.endTimeAtSource},guideTime:t.guideTime===s?t.guideTime:null}}if(t.clip.isResizingRight){const s=this.getResizeRightBoundaryEnd(e,i);if(t.clip.startTime+t.clip.duration<=s)return t;const r=s-t.clip.startTime;return{clip:{...t.clip,duration:r,endTime:s,endTimeAtSource:e.startTimeAtSource+r},guideTime:t.guideTime===s?t.guideTime:null}}return t}getResizeLeftBoundaryStart(t,e){let i=0;for(const s of e){if(s.startTime>=t.startTime)continue;const n=s.startTime+s.duration;i=Math.max(i,n)}return i}getResizeRightBoundaryEnd(t,e){let i=Number.POSITIVE_INFINITY;for(const s of e)s.startTime<t.endTime||(i=Math.min(i,s.startTime));return Number.isFinite(i)?i:Number.POSITIVE_INFINITY}buildResizeLeftPreviewClip(t,e,i){const n=Math.max(0,e.startTime+i)-e.startTime,o=Math.max(0,e.startTimeAtSource+i)-e.startTimeAtSource,l=Math.abs(n)<Math.abs(o)?n:o,h=z.calculateEndTime(e.startTime,e.duration);let c=e.startTime+l,d=e.duration-l,u;return d<1e3?(d=1e3,c=h-d,u=e.endTimeAtSource-d):u=e.startTimeAtSource+l,{...t,startTime:c,duration:d,endTime:c+d,startTimeAtSource:u,endTimeAtSource:e.endTimeAtSource}}buildResizeRightPreviewClip(t,e,i){let s=Math.max(1e3,e.duration+i);const n=e.startTimeAtSource,r=Math.min(e.sourceDuration,n+s);return s=r-n,{...t,startTime:e.startTime,duration:s,endTime:e.startTime+s,startTimeAtSource:n,endTimeAtSource:r}}applyClipSnap(t,e,i){if(!this.enableClipSnap||i.length===0)return{clip:t,guideTime:null};const s=i.flatMap(h=>[h.startTime,h.startTime+h.duration]);if(s.length===0)return{clip:t,guideTime:null};const n=z.pixelsToTime(this.clipSnapThreshold,this.zoom),r=t.startTime+t.duration,o=[];if(t.isResizingLeft)for(const h of s){const c=r-h,d=e.endTimeAtSource-c,u=Math.abs(h-t.startTime);u>n||c<1e3||d<0||o.push({clip:{...t,startTime:h,duration:c,endTime:r,startTimeAtSource:d,endTimeAtSource:e.endTimeAtSource},guideTime:h,distance:u})}else if(t.isResizingRight)for(const h of s){const c=h-t.startTime,d=e.startTimeAtSource+c,u=Math.abs(h-r);u>n||c<1e3||d>e.sourceDuration||o.push({clip:{...t,duration:c,endTime:t.startTime+c,endTimeAtSource:d},guideTime:h,distance:u})}else for(const h of s){const c=Math.abs(h-t.startTime);c<=n&&h>=0&&o.push({clip:{...t,startTime:h,endTime:h+t.duration},guideTime:h,distance:c});const d=h-t.duration,u=Math.abs(h-r);u<=n&&d>=0&&o.push({clip:{...t,startTime:d,endTime:d+t.duration},guideTime:h,distance:u})}if(o.length===0)return{clip:t,guideTime:null};o.sort((h,c)=>h.distance-c.distance);const l=o[0];return{clip:l.clip,guideTime:l.guideTime}}applyPreviewClipState(t){return this.selectedClip&&typeof this.selectedClip.applyPreviewState=="function"?(this.selectedClip.applyPreviewState(t),!0):(this.isVisualUpdate=!0,this.handleClipUpdate(t),this.isVisualUpdate=!1,!1)}setClipDragOverlayActive(t,e){var o,l;const i=this.getPromotedClipParents(),s=this.clipGroups.get(t);if(!s){i.delete(t);return}if(!e){const h=i.get(t);if(!h)return;s.remove(),h.parent.add(s);const c=(o=this.clips.find(d=>d.getClip().id===t))==null?void 0:o.getClip();c&&s.x(ht(c.startTime,this.zoom,this.scrollLeft)),s.y(2),i.delete(t),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw();return}if(i.has(t)||!this.dragOverlayLayer)return;const n=s.getParent();if(!n)return;const r=s.getAbsolutePosition();i.set(t,{parent:n,baseY:this.trackY}),s.remove(),this.dragOverlayLayer.add(s),s.position(r),s.moveToTop(),this.layer.batchDraw(),this.dragOverlayLayer.batchDraw()}resolveClipRenderY(t,e){const i=this.getPromotedClipParents().get(t);return((i==null?void 0:i.baseY)??0)+2+e}getPromotedClipParents(){return this.promotedClipParents instanceof Map||(this.promotedClipParents=new Map),this.promotedClipParents}updateSnapGuideLine(t){var e;(e=this.onSnapGuideChange)==null||e.call(this,this.enableClipSnap?t:null)}updateEdgeAutoScrollState(t,e){if(this.calculateHorizontalAutoScrollVelocity(t,e)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(t,e){if(e<=0)return 0;const i=Math.min(yt.AUTO_SCROLL_EDGE_THRESHOLD,e/2),s=yt.AUTO_SCROLL_MAX_SPEED;if(t<=0)return-s;if(t>=e)return s;if(t<i){const n=(i-t)/i;return-Math.max(1,Math.round(n*s))}if(t>e-i){const n=(t-(e-i))/i;return Math.max(1,Math.round(n*s))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}};g(yt,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),g(yt,"DEFAULT_CLIP_SNAP_THRESHOLD",8),g(yt,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(yt,"AUTO_SCROLL_MAX_SPEED",18);let Ze=yt;class Oo{constructor(t,e,i,s,n,r){g(this,"layer");g(this,"playheadGroup");g(this,"playheadLine");g(this,"playheadTriangle");g(this,"theme");g(this,"currentTime",0);g(this,"zoom",100);g(this,"scrollLeft",0);g(this,"onTimeChange");g(this,"isDragging",!1);this.layer=t,this.currentTime=e,this.zoom=i,this.theme=n,this.onTimeChange=r,this.playheadGroup=it.createGroup(),this.layer.add(this.playheadGroup),this.playheadLine=it.createLine([0,0,0,s],this.theme.playhead,1),this.playheadGroup.add(this.playheadLine),this.playheadTriangle=new X.RegularPolygon({x:0,y:5,sides:3,radius:10,fill:this.theme.playhead,rotation:180}),this.playheadGroup.add(this.playheadTriangle),this.initEventListeners(),this.render()}initEventListeners(){var t,e,i;this.playheadGroup.on("mousedown",()=>{this.isDragging=!0}),(t=this.layer.getStage())==null||t.on("mousemove",s=>{this.isDragging&&this.handleMouseMove(s.evt)}),(e=this.layer.getStage())==null||e.on("mouseup",()=>{this.isDragging=!1}),(i=this.layer.getStage())==null||i.on("mouseleave",()=>{this.isDragging=!1})}handleMouseMove(t){if(!this.isDragging)return;const e=this.layer.getStage();if(!e)return;const i=e.container();if(!i)return;const s=i.getBoundingClientRect(),n=t.clientX-s.left,r=z.pixelsToTime(n-ot+this.scrollLeft,this.zoom);this.setTime(r)}setTime(t){this.currentTime=Math.max(0,t),this.onTimeChange(this.currentTime),this.render()}setZoom(t){this.zoom=t,this.render()}setScrollLeft(t){this.scrollLeft=t,this.render()}setHeight(t){this.playheadLine.points([0,0,0,t]),this.render()}render(){const t=z.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+ot;this.playheadGroup.x(t),this.playheadGroup.visible(t>=0&&t<=this.layer.width()),this.layer.batchDraw()}getTime(){return this.currentTime}getPlayheadGroup(){return this.playheadGroup}}class vn{constructor(t,e,i,s){g(this,"container");g(this,"tracks",[]);g(this,"theme");g(this,"width",200);g(this,"timeScaleHeight",40);g(this,"includeTimeScaleSpacer",!0);g(this,"trackList",null);g(this,"onMuteTrack");var n,r,o,l,h,c;this.container=t.container,this.width=t.width||200,this.timeScaleHeight=t.timeScaleHeight||40,this.includeTimeScaleSpacer=t.includeTimeScaleSpacer??!0,this.theme={background:((n=t.theme)==null?void 0:n.background)||"#1a1a1a",border:((r=t.theme)==null?void 0:r.border)||"#333333",text:((o=t.theme)==null?void 0:o.text)||"#ffffff",buttonBackground:((l=t.theme)==null?void 0:l.buttonBackground)||"#2a2a2a",buttonHover:((h=t.theme)==null?void 0:h.buttonHover)||"#3a3a3a",buttonDanger:((c=t.theme)==null?void 0:c.buttonDanger)||"#dc3545"},this.onMuteTrack=s,this.init()}init(){this.container.className="track-info-panel",this.container.style.position="relative",this.container.style.overflow="hidden",this.container.style.width=`${this.width}px`,this.container.style.background=this.theme.background,this.container.style.borderRight=`1px solid ${this.theme.border}`,this.container.style.color=this.theme.text,this.render()}setTracks(t){this.tracks=[...t],this.render()}getTracks(){return[...this.tracks]}render(){this.container.innerHTML="";const t=document.createElement("div");if(t.className="track-info-list",t.style.willChange="transform",t.style.transform="translateY(0px)",this.trackList=t,this.includeTimeScaleSpacer){const e=document.createElement("div");e.className="track-info-spacer",e.style.height=`${this.timeScaleHeight}px`,this.container.appendChild(e)}this.tracks.forEach((e,i)=>{const s=this.createTrackItem(e,i);t.appendChild(s)}),this.container.appendChild(t)}setScrollTop(t){this.trackList&&(this.trackList.style.transform=`translateY(${-Math.max(0,t)}px)`)}createTrackItem(t,e){const i=t.type==="video"?_t.VIDEO:_t.AUDIO,s=document.createElement("div");s.className="track-info-item",s.style.height=`${i}px`,s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="space-between",s.style.padding="0 12px",s.style.borderBottom=`1px solid ${this.theme.border}`,s.style.transition="background-color 0.15s ease",s.dataset.index=e.toString(),s.dataset.trackId=t.id,s.addEventListener("mouseenter",()=>{s.style.background=this.theme.buttonHover}),s.addEventListener("mouseleave",()=>{s.style.background="transparent"});const n=document.createElement("div");n.style.display="flex",n.style.alignItems="center",n.style.gap="8px";const r=document.createElement("span");r.className="track-icon",r.textContent=t.type==="video"?"🎬":"🎵",r.style.fontSize="18px",r.style.userSelect="none",n.appendChild(r);const o=document.createElement("div");o.style.display="flex",o.style.alignItems="center",o.style.gap="4px";const l=document.createElement("button");return l.className="track-mute-btn",l.textContent=t.isMuted?"🔇":"🔊",l.title=t.isMuted?"取消静音":"静音",l.style.background="transparent",l.style.border="none",l.style.color=this.theme.text,l.style.padding="4px",l.style.borderRadius="4px",l.style.cursor="pointer",l.style.fontSize="14px",l.style.transition="background-color 0.15s ease",l.addEventListener("click",h=>{h.stopPropagation(),this.onMuteTrack&&this.onMuteTrack(t.id,!t.isMuted)}),l.addEventListener("mouseenter",()=>{l.style.background=this.theme.buttonBackground}),l.addEventListener("mouseleave",()=>{l.style.background="transparent"}),o.appendChild(l),s.appendChild(n),s.appendChild(o),s}destroy(){this.trackList=null,this.container.innerHTML=""}}const Go={backgroundColor:"#1e1e1e",borderColor:"#333",textColor:"#e0e0e0",labelColor:"#999",inputBackground:"#2d2d2d",inputBorder:"#444",inputFocusBorder:"#409eff",buttonBackground:"#2d2d2d",buttonBorder:"#444",buttonActiveBackground:"#409eff",buttonActiveBorder:"#409eff",buttonActiveText:"#fff"},Z={container:"clip-config-panel",tabBar:"clip-config-tab-bar",tabButton:"clip-config-tab-button",content:"clip-config-content",visualPanel:"clip-config-visual-panel",audioPanel:"clip-config-audio-panel",actionBar:"clip-config-action-bar",section:"clip-config-section",sectionTitle:"clip-config-section-title",row:"clip-config-row",label:"clip-config-label",slider:"clip-config-slider",input:"clip-config-input",presetGrid:"clip-config-preset-grid",presetButton:"clip-config-preset-button",resetButton:"clip-config-reset-button",emptyState:"clip-config-empty-state"},Bo={visual:"画面",audio:"音频"};class bn{constructor(t){g(this,"container");g(this,"rootElement",null);g(this,"theme");g(this,"onClipUpdate");g(this,"currentClip",null);g(this,"activeTab","visual");g(this,"tabBar",null);g(this,"contentArea",null);g(this,"visualPanel",null);g(this,"audioPanel",null);g(this,"xSlider",null);g(this,"xInput",null);g(this,"ySlider",null);g(this,"yInput",null);g(this,"scaleSlider",null);g(this,"scaleInput",null);g(this,"volumeSlider",null);g(this,"volumeInput",null);this.container=t.container,this.theme=t.theme??Go,this.onClipUpdate=t.onClipUpdate,this.render()}setClip(t){this.currentClip=t,(t==null?void 0:t.type)==="video"?this.activeTab="visual":(t==null?void 0:t.type)==="audio"&&(this.activeTab="audio"),this.render()}destroy(){this.rootElement&&(this.rootElement.remove(),this.rootElement=null)}getAvailableTabs(){return this.currentClip?this.currentClip.type==="audio"?["audio"]:["visual","audio"]:[]}render(){this.rootElement&&this.rootElement.remove(),this.rootElement=document.createElement("div"),this.rootElement.className=Z.container,this.applyBaseTheme(),this.currentClip?this.renderPanel():this.renderEmptyState(),this.container.appendChild(this.rootElement)}applyBaseTheme(){this.rootElement&&(this.rootElement.style.backgroundColor=this.theme.backgroundColor,this.rootElement.style.border=`1px solid ${this.theme.borderColor}`,this.rootElement.style.borderRadius="4px",this.rootElement.style.color=this.theme.textColor,this.rootElement.style.fontFamily='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',this.rootElement.style.fontSize="13px",this.rootElement.style.display="flex",this.rootElement.style.flexDirection="column",this.rootElement.style.overflow="hidden",this.rootElement.style.height="100%")}renderEmptyState(){const t=document.createElement("div");t.className=Z.emptyState,t.style.textAlign="center",t.style.padding="40px 20px",t.style.color=this.theme.labelColor;const e=document.createElement("div");e.style.fontSize="24px",e.style.marginBottom="8px",e.textContent="🎬";const i=document.createElement("div");i.style.fontSize="13px",i.textContent="请选择一个片段",t.appendChild(e),t.appendChild(i),this.rootElement.appendChild(t)}renderPanel(){this.renderTabBar(),this.renderContentArea(),this.renderActionBar()}renderTabBar(){const t=this.getAvailableTabs();this.tabBar=document.createElement("div"),this.tabBar.className=Z.tabBar,this.tabBar.style.display="flex",this.tabBar.style.gap="12px",this.tabBar.style.padding="4px",this.tabBar.style.backgroundColor="#2a2a2a",this.tabBar.style.borderRadius="4px 4px 0 0",t.forEach(e=>{const i=document.createElement("button");i.className=Z.tabButton,i.textContent=Bo[e],i.style.lineHeight="22px",i.style.padding="0 6px",i.style.border="none",i.style.cursor="pointer",i.style.fontSize="13px",i.style.fontFamily="inherit",i.style.transition="background-color 0.15s, color 0.15s";const s=this.activeTab===e;i.style.backgroundColor=s?"#595A5D":"transparent",i.style.color=s?"#fff":"#b5b6bf",i.style.borderRadius="4px",i.addEventListener("click",()=>{this.activeTab=e,this.updateTabBarState(),this.updateContentVisibility()}),this.tabBar.appendChild(i)}),this.rootElement.appendChild(this.tabBar)}updateTabBarState(){if(!this.tabBar)return;const t=this.tabBar.querySelectorAll(`.${Z.tabButton}`),e=this.getAvailableTabs();t.forEach((i,s)=>{const r=e[s]===this.activeTab,o=i;o.style.backgroundColor=r?"#595A5D":"transparent",o.style.color=r?"#fff":"#b5b6bf"})}renderContentArea(){this.contentArea=document.createElement("div"),this.contentArea.className=Z.content,this.contentArea.style.padding="12px",this.contentArea.style.flex="1",this.contentArea.style.overflowY="auto",this.contentArea.style.minHeight="0",this.renderVisualPanel(),this.renderAudioPanel(),this.updateContentVisibility(),this.rootElement.appendChild(this.contentArea)}updateContentVisibility(){this.visualPanel&&(this.visualPanel.style.display=this.activeTab==="visual"?"block":"none"),this.audioPanel&&(this.audioPanel.style.display=this.activeTab==="audio"?"block":"none")}renderVisualPanel(){this.visualPanel=document.createElement("div"),this.visualPanel.className=Z.visualPanel;const t=document.createElement("div");t.className=Z.section,t.style.marginBottom="16px";const e=document.createElement("div");e.className=Z.sectionTitle,e.style.fontSize="12px",e.style.color=this.theme.labelColor,e.style.marginBottom="8px",e.style.textTransform="uppercase",e.textContent="位置",t.appendChild(e),this.renderPositionControl(t,"X","x"),this.renderPositionControl(t,"Y","y"),this.renderPresetGrid(t),this.visualPanel.appendChild(t);const i=document.createElement("div");i.className=Z.section,i.style.borderTop=`1px solid ${this.theme.borderColor}`,i.style.paddingTop="16px";const s=document.createElement("div");s.className=Z.sectionTitle,s.style.fontSize="12px",s.style.color=this.theme.labelColor,s.style.marginBottom="8px",s.style.textTransform="uppercase",s.textContent="缩放",i.appendChild(s),this.renderScaleControl(i),this.visualPanel.appendChild(i),this.contentArea.appendChild(this.visualPanel)}renderAudioPanel(){this.audioPanel=document.createElement("div"),this.audioPanel.className=Z.audioPanel;const t=document.createElement("div");t.className=Z.section;const e=document.createElement("div");e.className=Z.sectionTitle,e.style.fontSize="12px",e.style.color=this.theme.labelColor,e.style.marginBottom="8px",e.style.textTransform="uppercase",e.textContent="音量",t.appendChild(e),this.renderVolumeControl(t),this.audioPanel.appendChild(t),this.contentArea.appendChild(this.audioPanel)}renderActionBar(){const t=document.createElement("div");t.className=Z.actionBar,t.style.borderTop=`1px solid ${this.theme.borderColor}`,t.style.borderRadius="0 0 4px 4px",t.style.minHeight="36px",t.style.backgroundColor="#2a2a2a",this.rootElement.appendChild(t)}renderPositionControl(t,e,i){var u,p,f,y,T,S;const s=document.createElement("div");s.className=Z.row,s.style.display="flex",s.style.alignItems="center",s.style.gap="8px",s.style.marginBottom="8px";const n=document.createElement("label");n.className=Z.label,n.style.width="16px",n.style.fontSize="13px",n.style.color=this.theme.labelColor,n.textContent=e,s.appendChild(n);const o=(((p=(u=this.currentClip)==null?void 0:u.visualTransform)==null?void 0:p.scale)??1)/2,l=-o,h=1+o,c=document.createElement("input");c.type="range",c.className=Z.slider,c.min=String(l),c.max=String(h),c.step="0.01",c.value=String(((y=(f=this.currentClip)==null?void 0:f.visualTransform)==null?void 0:y[i])??.5),c.style.flex="1",c.style.height="4px",c.addEventListener("input",v=>{const b=parseFloat(v.target.value);this.handleTransformChange(i,b)}),s.appendChild(c);const d=document.createElement("input");d.type="number",d.className=Z.input,d.min=String(l),d.max=String(h),d.step="0.01",d.value=String(((S=(T=this.currentClip)==null?void 0:T.visualTransform)==null?void 0:S[i])??.5),d.style.width="60px",d.style.padding="4px 6px",d.style.border=`1px solid ${this.theme.inputBorder}`,d.style.borderRadius="4px",d.style.fontSize="12px",d.style.backgroundColor=this.theme.inputBackground,d.style.color=this.theme.textColor,d.addEventListener("change",v=>{const b=parseFloat(v.target.value);this.handleTransformChange(i,b)}),s.appendChild(d),i==="x"?(this.xSlider=c,this.xInput=d):(this.ySlider=c,this.yInput=d),t.appendChild(s)}renderPresetGrid(t){const e=document.createElement("div");e.className=Z.presetGrid,e.style.display="grid",e.style.gridTemplateColumns="repeat(3, 1fr)",e.style.gap="4px",[{label:"↖ 左上",x:"left",y:"top"},{label:"↑ 上中",x:"center",y:"top"},{label:"↗ 右上",x:"right",y:"top"},{label:"← 左中",x:"left",y:"center"},{label:"● 居中",x:"center",y:"center"},{label:"右中 →",x:"right",y:"center"},{label:"↙ 左下",x:"left",y:"bottom"},{label:"↓ 下中",x:"center",y:"bottom"},{label:"↘ 右下",x:"right",y:"bottom"}].forEach(s=>{const n=document.createElement("button");n.className=Z.presetButton,n.textContent=s.label,n.style.padding="6px",n.style.border=`1px solid ${this.theme.buttonBorder}`,n.style.borderRadius="4px",n.style.background=this.theme.buttonBackground,n.style.fontSize="11px",n.style.cursor="pointer",n.style.color=this.theme.textColor,n.addEventListener("click",()=>{const{x:r,y:o}=this.calculatePresetPosition(s.x,s.y);this.handleTransformChanges({x:r,y:o})}),e.appendChild(n)}),t.appendChild(e)}calculatePresetPosition(t,e){var o,l;const s=(((l=(o=this.currentClip)==null?void 0:o.visualTransform)==null?void 0:l.scale)??1)/2,n={left:s,center:.5,right:1-s},r={top:s,center:.5,bottom:1-s};return{x:n[t],y:r[e]}}renderScaleControl(t){var r,o,l,h;const e=document.createElement("div");e.className=Z.row,e.style.display="flex",e.style.alignItems="center",e.style.gap="8px";const i=document.createElement("input");i.type="range",i.className=Z.slider,i.min="0.1",i.max="8",i.step="0.1",i.value=String(((o=(r=this.currentClip)==null?void 0:r.visualTransform)==null?void 0:o.scale)??1),i.style.flex="1",i.style.height="4px",i.addEventListener("input",c=>{const d=parseFloat(c.target.value);this.handleTransformChange("scale",d)}),e.appendChild(i);const s=document.createElement("input");s.type="number",s.className=Z.input,s.min="0.1",s.max="8",s.step="0.1",s.value=String(((h=(l=this.currentClip)==null?void 0:l.visualTransform)==null?void 0:h.scale)??1),s.style.width="60px",s.style.padding="4px 6px",s.style.border=`1px solid ${this.theme.inputBorder}`,s.style.borderRadius="4px",s.style.fontSize="12px",s.style.backgroundColor=this.theme.inputBackground,s.style.color=this.theme.textColor,s.addEventListener("change",c=>{const d=parseFloat(c.target.value);this.handleTransformChange("scale",d)}),e.appendChild(s);const n=document.createElement("button");n.className=Z.resetButton,n.textContent="重置",n.style.padding="4px 8px",n.style.border=`1px solid ${this.theme.buttonBorder}`,n.style.borderRadius="4px",n.style.background=this.theme.buttonBackground,n.style.fontSize="11px",n.style.cursor="pointer",n.style.color=this.theme.textColor,n.addEventListener("click",()=>{this.handleTransformChange("scale",1)}),e.appendChild(n),this.scaleSlider=i,this.scaleInput=s,t.appendChild(e)}renderVolumeControl(t){var r,o;const e=document.createElement("div");e.className=Z.row,e.style.display="flex",e.style.alignItems="center",e.style.gap="8px";const i=document.createElement("input");i.type="range",i.className=Z.slider,i.min="0",i.max="1",i.step="0.01",i.value=String(((r=this.currentClip)==null?void 0:r.volume)??1),i.style.flex="1",i.style.height="4px",i.addEventListener("input",l=>{const h=parseFloat(l.target.value);this.handleVolumeChange(h)}),e.appendChild(i);const s=document.createElement("input");s.type="number",s.className=Z.input,s.min="0",s.max="100",s.step="1",s.value=String(Math.round((((o=this.currentClip)==null?void 0:o.volume)??1)*100)),s.style.width="60px",s.style.padding="4px 6px",s.style.border=`1px solid ${this.theme.inputBorder}`,s.style.borderRadius="4px",s.style.fontSize="12px",s.style.backgroundColor=this.theme.inputBackground,s.style.color=this.theme.textColor,s.addEventListener("change",l=>{const h=parseFloat(l.target.value)/100;this.handleVolumeChange(Math.max(0,Math.min(1,h)))}),e.appendChild(s);const n=document.createElement("span");n.style.fontSize="12px",n.style.color=this.theme.labelColor,n.textContent="%",e.appendChild(n),this.volumeSlider=i,this.volumeInput=s,t.appendChild(e)}handleVolumeChange(t){if(!this.currentClip||!this.onClipUpdate)return;const e=Math.max(0,Math.min(1,t));this.currentClip={...this.currentClip,volume:e},this.updateVolumeControls(),this.onClipUpdate(this.currentClip.id,{volume:e})}updateVolumeControls(){var e;const t=((e=this.currentClip)==null?void 0:e.volume)??1;this.volumeSlider&&(this.volumeSlider.value=String(t)),this.volumeInput&&(this.volumeInput.value=String(Math.round(t*100)))}clampValue(t,e){return t==="scale"?Math.max(.1,Math.min(8,e)):e}updateUIControls(){var n;const t=((n=this.currentClip)==null?void 0:n.visualTransform)??{x:.5,y:.5,scale:1},e=t.scale/2,i=-e,s=1+e;this.updateSliderAndInput(this.xSlider,this.xInput,t.x,i,s),this.updateSliderAndInput(this.ySlider,this.yInput,t.y,i,s),this.scaleSlider&&(this.scaleSlider.value=String(t.scale)),this.scaleInput&&(this.scaleInput.value=String(t.scale))}updateSliderAndInput(t,e,i,s,n){t&&(t.value=String(i),t.min=String(s),t.max=String(n)),e&&(e.value=String(i),e.min=String(s),e.max=String(n))}handleTransformChange(t,e){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(t,e),n={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[t]:i};this.currentClip={...this.currentClip,visualTransform:n},this.updateUIControls(),this.onClipUpdate(this.currentClip.id,{visualTransform:n})}handleTransformChanges(t){if(!this.currentClip||!this.onClipUpdate)return;const i={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1}};t.x!==void 0&&(i.x=this.clampValue("x",t.x)),t.y!==void 0&&(i.y=this.clampValue("y",t.y)),t.scale!==void 0&&(i.scale=this.clampValue("scale",t.scale)),this.currentClip={...this.currentClip,visualTransform:i},this.updateUIControls(),this.onClipUpdate(this.currentClip.id,{visualTransform:i})}}class Cs{constructor(t){this.timelineStore=t}selectClip(t){return this.updateSelection(t)}clearSelection(){return this.updateSelection(null)}findClipById(t,e){for(const i of t){const s=i.getClips().find(n=>n.id===e);if(s)return{clip:s,track:i,trackId:this.resolveTrackId(i)}}return null}findClipAtTime(t,e){for(const i of t){const s=i.getClips().find(n=>e>=n.startTime&&e<n.startTime+n.duration);if(s)return{clip:s,track:i,trackId:this.resolveTrackId(i)}}return null}prepareRemoveClip(t,e){const i=this.findClipById(e,t);return i?{exists:!0,clip:i.clip,trackId:i.trackId,shouldClearSelection:this.timelineStore.getSelectedClipId()===t}:{exists:!1,clip:null,trackId:null,shouldClearSelection:!1}}prepareMoveClipToTrack(t,e,i){var c;const s=this.findClipById(i,t);if(!s||!s.trackId)return{status:"missing_source_track",clipId:t,targetTrackId:e};const{clip:n,track:r,trackId:o}=s;if(o===e)return{status:"noop",clipId:t,sourceTrackId:o,targetTrackId:e};const l=i.find(d=>this.resolveTrackId(d)===e);if(!l)return{status:"missing_target_track",clipId:t,targetTrackId:e,sourceTrackId:o};const h=(c=l.getTrackType)==null?void 0:c.call(l);return h&&h!==n.type?{status:"track_type_mismatch",clipId:t,targetTrackId:e,sourceTrackId:o}:{status:"ready",clip:n,sourceTrack:r,sourceTrackId:o,targetTrack:l,targetTrackId:e}}planTrackPlacement(t,e){var n;const i=t.startTime+t.duration;for(const r of e){if(((n=r.getTrackType)==null?void 0:n.call(r))!==t.type)continue;if(!r.getClips().some(l=>t.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(r);if(l)return{status:"use_existing_track",trackId:l}}}const s=e.filter(r=>{var o;return((o=r.getTrackType)==null?void 0:o.call(r))===t.type}).length+1;return{status:"create_track",trackType:t.type,suggestedTrackName:t.type==="video"?`视频轨道 ${s}`:`音频轨道 ${s}`}}planCrossTrackMove(t,e,i,s,n,r){var f;const o=this.resolveTrackTargetByY(e,s,n,t.type);if(o.status==="create_track")return{status:"create_track",trackType:t.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const h=r.find(y=>this.resolveTrackId(y)===l);if(!h)return{status:"missing_target_track_view",targetTrackId:l};const c=this.resolveTrackType(h)??((f=n.find(y=>y.id===l))==null?void 0:f.type)??null;if(c!==t.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:c};if(!this.hasOverlapOnTrack(t,h))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(t.type,l,e,s,n);if(d)return{status:"create_track",trackType:t.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=n.filter(y=>y.type===t.type).map(y=>y.id),p=u.indexOf(l);for(let y=1;y<=u.length;y+=1){const T=p-y;if(T>=0){const v=u[T],b=r.find(k=>this.resolveTrackId(k)===v);if(b&&!this.hasOverlapOnTrack(t,b))return{status:"move_to_track",targetTrackId:v}}const S=p+y;if(S<u.length){const v=u[S],b=r.find(k=>this.resolveTrackId(k)===v);if(b&&!this.hasOverlapOnTrack(t,b))return{status:"move_to_track",targetTrackId:v}}}return{status:"create_track",trackType:t.type,insertionPlacement:t.type==="video"?"before_primary":"after_primary"}}planCrossTrackPreview(t,e,i,s,n,r){const o=this.planCrossTrackMove(t,e,i,s,n,r);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(t){const e=Math.max(0,t);return this.updateCurrentTime(e)}setZoom(t){const e=Math.max(ct.MIN,Math.min(ct.MAX,t));return this.updateZoom(e)}setSpeed(t){const e=Math.max(.1,Math.min(10,t));return this.updateSpeed(e)}updateSelection(t){const e=this.timelineStore.getSelectedClipId();return e===t?{previousClipId:e,nextClipId:t,changed:!1}:(t===null?this.timelineStore.clearSelection():this.timelineStore.setSelectedClipId(t),{previousClipId:e,nextClipId:t,changed:!0})}updateCurrentTime(t){const e=this.timelineStore.getCurrentTime();return e===t?{previousValue:e,nextValue:t,changed:!1}:(this.timelineStore.setCurrentTime(t),{previousValue:e,nextValue:t,changed:!0})}updateZoom(t){const e=this.timelineStore.getZoom();return e===t?{previousValue:e,nextValue:t,changed:!1}:(this.timelineStore.setZoom(t),{previousValue:e,nextValue:t,changed:!0})}updateSpeed(t){const e=this.timelineStore.getSpeed();return e===t?{previousValue:e,nextValue:t,changed:!1}:(this.timelineStore.setSpeed(t),{previousValue:e,nextValue:t,changed:!0})}resolveTrackId(t){return typeof t.getId=="function"?t.getId():typeof t.id=="string"?t.id:null}resolveTrackType(t){return typeof t.getTrackType=="function"?t.getTrackType():t.type??null}resolveTrackTargetByY(t,e,i,s){let n=e,r=null,o=null;for(const l of i){const h=l.type==="video"?_t.VIDEO:_t.AUDIO,c=n+h;if(l.type===s&&(r===null&&(r=n),o=c),t>=n&&t<c)return{status:"existing_track",targetTrackId:l.id};n=c}return s==="video"&&r!==null&&t<r?{status:"create_track",insertionPlacement:"top_of_type_region"}:s==="audio"&&o!==null&&t>=o?{status:"create_track",insertionPlacement:"bottom_of_type_region"}:{status:"missing_target_track_by_position"}}resolvePreferredInsertionPlacement(t,e,i,s,n){let r=s;const o=n.map(d=>{const u=r,p=d.type==="video"?_t.VIDEO:_t.AUDIO,f=u+p;return r=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:p}}).filter(d=>d.type===t),l=o.findIndex(d=>d.id===e);if(l===-1)return null;const h=o[l],c=Math.min(12,Math.max(6,Math.floor(h.height/4)));return h.role==="primary"?{insertionPlacement:t==="video"?"before_track":"after_track",referenceTrackId:e}:l<o.length-1&&i>=h.endY-c?{insertionPlacement:"after_track",referenceTrackId:e}:{insertionPlacement:"before_track",referenceTrackId:e}}hasOverlapOnTrack(t,e){const i=t.startTime+t.duration;return e.getClips().some(s=>s.id===t.id?!1:t.startTime<s.endTime&&i>s.startTime)}}class Pi{constructor(t,e,i,s=100){g(this,"state");g(this,"maxHistorySize",100);g(this,"onActionUndo");g(this,"onActionRedo");g(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=s,this.onActionUndo=t,this.onActionRedo=e,this.onHistoryChange=i}addAction(t){this.state.past.length>=this.maxHistorySize&&this.state.past.shift(),this.state.past.push({...t,timestamp:Date.now()}),this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}undo(){if(this.state.past.length===0)return!1;const t=this.state.past.pop();return this.state.future.push(t),this.onActionUndo(t),this.onHistoryChange&&this.onHistoryChange(),!0}redo(){if(this.state.future.length===0)return!1;const t=this.state.future.pop();return this.state.past.push(t),this.onActionRedo(t),this.onHistoryChange&&this.onHistoryChange(),!0}clear(){this.state.past=[],this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}canUndo(){return this.state.past.length>0}canRedo(){return this.state.future.length>0}getState(){return{...this.state}}createAddClipAction(t){return{type:"add_clip",data:t,timestamp:Date.now()}}createRemoveClipAction(t){return{type:"remove_clip",data:{clip:t,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null},timestamp:Date.now()}}createRemoveClipActionWithTrackSnapshot(t,e,i,s=null){return{type:"remove_clip",data:{clip:t,sourceTrackId:e,sourceTrackSnapshot:i,sourceTrackRestoreAnchor:s},timestamp:Date.now()}}createUpdateClipAction(t,e,i){return{type:"update_clip",data:{clipId:t,updates:e,previousState:i},timestamp:Date.now()}}createSplitClipAction(t,e,i){return{type:"split_clip",data:{originalClip:t,clip1:e,clip2:i},timestamp:Date.now()}}createMoveClipAction(t,e,i){return{type:"move_clip",data:{clipId:t,newStartTime:e,previousStartTime:i},timestamp:Date.now()}}createResizeClipAction(t,e,i,s,n){return{type:"resize_clip",data:{clipId:t,newDuration:e,newStartTime:i,previousDuration:s,previousStartTime:n},timestamp:Date.now()}}createSetTimeAction(t,e){return{type:"set_time",data:{newTime:t,previousTime:e},timestamp:Date.now()}}createRemoveGapsAction(t){return{type:"remove_gaps",data:{clipsBefore:t},timestamp:Date.now()}}createMultiClipUpdateAction(t){return{type:"multi_clip_update",data:{clipUpdates:t},timestamp:Date.now()}}createMoveClipBetweenTracksAction(t,e,i,s,n,r,o){return{type:"move_clip_between_tracks",data:{clipId:t,sourceTrackId:e,targetTrackId:i,clipBefore:s,clipAfter:n,sourceTrackSnapshot:r,targetTrackSnapshot:o},timestamp:Date.now()}}createSeparateClipAudioAction(t,e,i,s){return{type:"separate_clip_audio",data:{videoClipBefore:t,videoClipAfter:e,audioClip:i,audioTrackId:s},timestamp:Date.now()}}createRestoreClipAudioAction(t,e,i,s){return{type:"restore_clip_audio",data:{videoClipBefore:t,videoClipAfter:e,audioClip:i,audioTrackId:s},timestamp:Date.now()}}createCompoundAction(t,e){return{type:"compound",data:{actions:t,...e?{label:e}:{}},timestamp:Date.now()}}}class Ss{constructor(t){this.target=t}executeUndo(t){this.executeUndoInternal(t,new Map)}executeRedo(t){this.executeRedoInternal(t,new Map)}executeUndoInternal(t,e){var i,s;switch(t.type){case"add_clip":this.target.removeClip(t.data.id);break;case"remove_clip":{const n=this.normalizeRemoveClipActionData(t.data);let r=!1;const o=this.resolveTrackIdForHistorySnapshot(n.sourceTrackSnapshot,n.sourceTrackId,e,n.sourceTrackRestoreAnchor);if(o&&(r=this.target.addClipToTrack(o,n.clip)),!r){const l=this.target.findTrackByClipId(n.clip.id)||this.target.getDefaultTrack();l==null||l.addClip(n.clip)}(s=(i=this.target).loadClipThumbnails)==null||s.call(i,n.clip);break}case"update_clip":this.target.updateClip(t.data.clipId,t.data.previousState);break;case"split_clip":{this.target.removeClip(t.data.clip1.id),this.target.removeClip(t.data.clip2.id);const n=this.target.findTrackByClipId(t.data.originalClip.id)||this.target.getDefaultTrack();n==null||n.addClip(t.data.originalClip);break}case"move_clip":this.target.updateClip(t.data.clipId,{startTime:t.data.previousStartTime});break;case"resize_clip":this.target.updateClip(t.data.clipId,{duration:t.data.previousDuration,startTime:t.data.previousStartTime});break;case"remove_gaps":this.target.getClips().forEach(n=>this.target.removeClip(n.id)),t.data.clipsBefore.forEach(n=>{const r=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();r==null||r.addClip(n)});break;case"multi_clip_update":t.data.clipUpdates.forEach(n=>{this.target.updateClip(n.clipId,n.previousState)});break;case"move_clip_between_tracks":this.restoreMovedClip(t.data.clipId,t.data.sourceTrackSnapshot,t.data.clipBefore,e);break;case"separate_clip_audio":t.data.audioClip&&this.target.removeClip(t.data.audioClip.id),this.target.updateClip(t.data.videoClipBefore.id,t.data.videoClipBefore);break;case"restore_clip_audio":this.target.updateClip(t.data.videoClipBefore.id,t.data.videoClipBefore);break;case"compound":[...t.data.actions].reverse().forEach(n=>{this.executeUndoInternal(n,e)});break;default:O.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:t.type})}}executeRedoInternal(t,e){var i,s;switch(t.type){case"add_clip":{const n=t.data,r=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();r==null||r.addClip(n),(s=(i=this.target).loadClipThumbnails)==null||s.call(i,n);break}case"remove_clip":this.target.removeClip(t.data.clip.id);break;case"update_clip":this.target.updateClip(t.data.clipId,t.data.updates);break;case"split_clip":{this.target.removeClip(t.data.originalClip.id);const n=this.target.findTrackByClipId(t.data.originalClip.id)||this.target.getDefaultTrack();n==null||n.addClip(t.data.clip1),n==null||n.addClip(t.data.clip2);break}case"move_clip":this.target.updateClip(t.data.clipId,{startTime:t.data.newStartTime});break;case"resize_clip":this.target.updateClip(t.data.clipId,{duration:t.data.newDuration,startTime:t.data.newStartTime});break;case"remove_gaps":this.target.removeClipGaps();break;case"multi_clip_update":t.data.clipUpdates.forEach(n=>{this.target.updateClip(n.clipId,n.newState)});break;case"move_clip_between_tracks":this.restoreMovedClip(t.data.clipId,t.data.targetTrackSnapshot,t.data.clipAfter,e);break;case"separate_clip_audio":this.target.updateClip(t.data.videoClipAfter.id,t.data.videoClipAfter),t.data.audioClip&&t.data.audioTrackId&&this.target.addClipToTrack(t.data.audioTrackId,t.data.audioClip);break;case"restore_clip_audio":this.target.updateClip(t.data.videoClipAfter.id,t.data.videoClipAfter);break;case"compound":t.data.actions.forEach(n=>{this.executeRedoInternal(n,e)});break;default:O.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:t.type})}}restoreMovedClip(t,e,i,s){const n=this.resolveTrackIdForHistorySnapshot(e,(e==null?void 0:e.id)??null,s,null);n&&this.target.moveClipToTrack(t,n),this.target.updateClip(t,i)}normalizeRemoveClipActionData(t){return"clip"in t?t:{clip:t,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null}}resolveTrackIdForHistorySnapshot(t,e,i,s){const n=(t==null?void 0:t.id)??e??null;if(n){const o=i.get(n);if(o)return o}if(!t)return e;const r=this.target.ensureTrackFromHistorySnapshot(t,this.resolveRestoreAnchor(s,i))??e;return n&&r&&i.set(n,r),r}resolveRestoreAnchor(t,e){return t?{previousTrackId:t.previousTrackId?e.get(t.previousTrackId)??t.previousTrackId:null,nextTrackId:t.nextTrackId?e.get(t.nextTrackId)??t.nextTrackId:null}:null}}const Ho=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId"],zo=new Set(["thumbnails"]);function No(a,t){return Object.is(a,t)?!0:a===void 0||t===void 0?!1:typeof a=="object"&&typeof t=="object"?JSON.stringify(a)===JSON.stringify(t):!1}class Ts{constructor(t){this.history=t}recordAddClip(t){const e=this.history.createAddClipAction(t);return this.history.addAction(e),e}createRemoveClipAction(t,e=null,i=null,s=null){return e||i?this.history.createRemoveClipActionWithTrackSnapshot(t,e,i,s):this.history.createRemoveClipAction(t)}recordRemoveClip(t,e=null,i=null,s=null){const n=this.createRemoveClipAction(t,e,i,s);return this.history.addAction(n),n}recordClipUpdate(t,e,i){const s=this.createClipUpdateAction(t,e,i);return s?(this.history.addAction(s),s):null}recordSplitClip(t,e){const i={...t,id:t.id.replace("_split_",""),duration:t.duration+e.duration,endTime:e.endTime,endTimeAtSource:e.endTimeAtSource},s=this.history.createSplitClipAction(i,t,e);return this.history.addAction(s),s}recordRemoveGaps(t){if(t.length===0)return null;const e=this.history.createRemoveGapsAction(t);return this.history.addAction(e),e}recordMoveClipBetweenTracks(t,e,i,s,n,r,o){const l=this.history.createMoveClipBetweenTracksAction(t,e,i,s,n,r,o);return this.history.addAction(l),l}recordSeparateClipAudio(t,e,i,s){const n=this.history.createSeparateClipAudioAction(t,e,i,s);return this.history.addAction(n),n}recordRestoreClipAudio(t,e,i,s){const n=this.history.createRestoreClipAudioAction(t,e,i,s);return this.history.addAction(n),n}createSeparateClipAudioAction(t,e,i,s){return this.history.createSeparateClipAudioAction(t,e,i,s)}createRestoreClipAudioAction(t,e,i,s){return this.history.createRestoreClipAudioAction(t,e,i,s)}recordCompoundAction(t,e){if(t.length===0)return null;const i=this.history.createCompoundAction(t,e);return this.history.addAction(i),i}createClipUpdateAction(t,e,i){if(i&&i.length>0)return this.history.createMultiClipUpdateAction(i);if(!e)return null;if(e.startTime!==t.startTime&&e.duration===t.duration)return this.history.createMoveClipAction(t.id,t.startTime,e.startTime);if(e.duration!==t.duration)return this.history.createResizeClipAction(t.id,t.duration,t.startTime,e.duration,e.startTime);const r={},o={};return Ho.forEach(h=>{No(t[h],e[h])||(r[h]=t[h],o[h]=e[h])}),Object.keys(r).length===0||Object.keys(r).every(h=>zo.has(h))?null:this.history.createUpdateClipAction(t.id,r,o)}}function Ne(a){a.notifySelectionChange(),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function Fo(a){var t,e;a.notifySelectionChange(),(t=a.reloadClipThumbnailsIfNeeded)==null||t.call(a),(e=a.checkTrackDurationChange)==null||e.call(a),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function Vo(a,t,e=!1){if(!t||!e||a.type==="audio")return!1;const i=t.duration!==a.duration,s=t.startTimeAtSource!==a.startTimeAtSource||t.endTimeAtSource!==a.endTimeAtSource;return i||s}function Wo(a,t){if(a.length===0)return!1;const e=Math.max(...a.map(i=>i.endTime));return t<e}function Yo(a){return a.currentCanPlay===a.nextCanPlay?a.currentCanPlay:(a.setCanPlay(a.nextCanPlay),a.currentCanPlay&&!a.nextCanPlay&&a.playState==="playing"&&(a.pauseTimeline(),a.setCurrentTime(a.clipEndTime||1)),a.emitCanPlayChange(a.nextCanPlay),a.nextCanPlay)}function Xo(a){const t=!a.id&&a.startTime>0;return{shouldJumpToTime:t,jumpTime:t?a.startTime:null,shouldSelectClip:!!a.id}}function Ue(a){var t;return a.applied?(a.isExecutingHistoryAction||(t=a.recordHistory)==null||t.call(a),a.applyEffects(),!0):!1}function Uo(a){return Ue({applied:a.applied,isExecutingHistoryAction:a.isExecutingHistoryAction,recordHistory:()=>{var t;(t=a.recordMoveClipBetweenTracks)==null||t.call(a,a.clipId,a.sourceTrackId,a.targetTrackId,a.clipBefore,a.clipAfter,a.sourceTrackSnapshot,a.targetTrackSnapshot)},applyEffects:a.applyEffects})}function $o(a){var t;a.isExecutingHistoryAction||(t=a.recordSplitClip)==null||t.call(a,a.clip1,a.clip2),a.emitClipUpdated(a.clip1),a.emitClipAdded(a.clip2),a.applyEffects()}const ci={x:.5,y:.5,scale:1},Ko=.1,jo=8;function di(a,t){return typeof a=="number"&&Number.isFinite(a)?a:t}function Zo(a){return Math.min(jo,Math.max(Ko,a))}function ft(a){return{x:di(a==null?void 0:a.x,ci.x),y:di(a==null?void 0:a.y,ci.y),scale:Zo(di(a==null?void 0:a.scale,ci.scale))}}function kn(a,t,e=1e-4){const i=ft(a),s=ft(t);return Math.abs(i.x-s.x)<=e&&Math.abs(i.y-s.y)<=e&&Math.abs(i.scale-s.scale)<=e}function wn(a,t){if(a.width<=0||a.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const e=t.width>0?t.width:a.width,i=t.height>0?t.height:a.height,s=e/i,n=a.width/a.height;let r=a.width,o=a.height;s>n?o=r/s:r=o*s;const l=(a.width-r)/2,h=(a.height-o)/2;return{left:l,top:h,width:r,height:o,centerX:l+r/2,centerY:h+o/2}}function vs(a,t,e){const i=wn(a,t),s=ft(e),n=i.width*s.scale,r=i.height*s.scale,o=a.width*s.x,l=a.height*s.y;return{left:o-n/2,top:l-r/2,width:n,height:r,centerX:o,centerY:l}}function qo(a,t,e,i){const s=ft(a),n=i.width>0?i.width:1,r=i.height>0?i.height:1;return ft({x:s.x+t/n,y:s.y+e/r,scale:s.scale})}function Jo(a,t,e,i,s,n){const r=ft(n),o=Math.max(s.width/2,1),l=Math.max(s.height/2,1),h=Math.abs(e-a)/o,c=Math.abs(i-t)/l;return ft({x:r.x,y:r.y,scale:Math.max(h,c)})}function bs(a){if(!a)return 0;const t=Number.parseFloat(a);return Number.isFinite(t)?t:0}class Qo{constructor(t={}){g(this,"frameElement",null);g(this,"overlayElement",null);g(this,"boxElement",null);g(this,"handleElements",new Map);g(this,"handlePointerDownHandlers",new Map);g(this,"state",null);g(this,"interaction",null);g(this,"callbacks");g(this,"boundPointerMove",t=>{this.handleDocumentPointerMove(t)});g(this,"boundPointerUp",()=>{this.finishInteraction(!0)});g(this,"boundVisibilityChange",()=>{var t;(t=this.getDocument())!=null&&t.hidden&&this.finishInteraction(!1)});g(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});g(this,"handleMovePointerDown",t=>{var i,s;const e=t;(e.button??0)!==0||!this.state||((i=e.preventDefault)==null||i.call(e),(s=e.stopPropagation)==null||s.call(e),this.interaction={clipId:this.state.clipId,mode:"move",pointerStart:this.toLocalPoint(e),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing"},this.setGlobalCursor("grabbing"),this.bindDocumentListeners())});this.callbacks=t}attach(t){if(this.frameElement===t&&this.overlayElement){this.render();return}this.detach(),this.frameElement=t;const e=document.createElement("div");e.className="timeline-preview-transform-overlay",e.style.position="absolute",e.style.inset="0",e.style.pointerEvents="none",e.style.zIndex="3000";const i=document.createElement("div");i.className="timeline-preview-transform-box",i.style.position="absolute",i.style.display="none",i.style.boxSizing="border-box",i.style.border="1px solid rgba(80, 227, 194, 0.95)",i.style.cursor="grab",i.style.pointerEvents="auto",i.style.userSelect="none",i.addEventListener("pointerdown",this.handleMovePointerDown),e.appendChild(i),this.overlayElement=e,this.boxElement=i,this.createHandle("top-left","nwse-resize"),this.createHandle("top-right","nesw-resize"),this.createHandle("bottom-right","nwse-resize"),this.createHandle("bottom-left","nesw-resize"),t.appendChild(e),this.render()}detach(){var t,e;this.finishInteraction(!1),(t=this.boxElement)==null||t.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,s)=>{const n=this.handlePointerDownHandlers.get(s);n&&i.removeEventListener("pointerdown",n)}),this.handleElements.clear(),this.handlePointerDownHandlers.clear(),(e=this.overlayElement)==null||e.remove(),this.overlayElement=null,this.boxElement=null,this.frameElement=null,this.state=null}sync(t){if(!t){this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==t.clipId&&this.finishInteraction(!1),this.state=t,this.render()}createHandle(t,e){if(!this.boxElement)return;const i=document.createElement("div");i.className=`timeline-preview-transform-handle timeline-preview-transform-handle--${t}`,i.style.position="absolute",i.style.width="10px",i.style.height="10px",i.style.border="1px solid rgba(80, 227, 194, 0.95)",i.style.background="#000000",i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=e,i.style.boxSizing="border-box",i.style.transform="translate(-50%, -50%)";const s=this.getHandlePointerDown(t);i.addEventListener("pointerdown",s),this.handleElements.set(t,i),this.handlePointerDownHandlers.set(t,s),this.boxElement.appendChild(i)}getHandlePointerDown(t){return e=>{var n,r;const i=e;if((i.button??0)!==0||!this.state)return;(n=i.preventDefault)==null||n.call(i),(r=i.stopPropagation)==null||r.call(i);const s=t==="top-right"||t==="bottom-left"?"nesw-resize":"nwse-resize";this.interaction={clipId:this.state.clipId,mode:"scale",pointerStart:this.toLocalPoint(i),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:s},this.setGlobalCursor(s),this.bindDocumentListeners()}}bindDocumentListeners(){var e,i,s,n,r;const t=this.getDocument();t&&((e=t.addEventListener)==null||e.call(t,"pointermove",this.boundPointerMove),(i=t.addEventListener)==null||i.call(t,"pointerup",this.boundPointerUp),(s=t.addEventListener)==null||s.call(t,"visibilitychange",this.boundVisibilityChange),(r=(n=globalThis.window)==null?void 0:n.addEventListener)==null||r.call(n,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var e,i,s,n,r;const t=this.getDocument();t&&((e=t.removeEventListener)==null||e.call(t,"pointermove",this.boundPointerMove),(i=t.removeEventListener)==null||i.call(t,"pointerup",this.boundPointerUp),(s=t.removeEventListener)==null||s.call(t,"visibilitychange",this.boundVisibilityChange),(r=(n=globalThis.window)==null?void 0:n.removeEventListener)==null||r.call(n,"blur",this.boundWindowBlur))}handleDocumentPointerMove(t){var n,r,o;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const e=t;(n=e.preventDefault)==null||n.call(e);const i=this.toLocalPoint(e);let s=this.interaction.startTransform;if(this.interaction.mode==="move")s=qo(this.interaction.startTransform,i.x-this.interaction.pointerStart.x,i.y-this.interaction.pointerStart.y,this.interaction.frameSize);else{const l=this.interaction.startTransform.x*this.interaction.frameSize.width,h=this.interaction.startTransform.y*this.interaction.frameSize.height;s=Jo(l,h,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=s,this.interaction.changed=!kn(this.interaction.startTransform,s),(o=(r=this.callbacks).onPreviewTransformChange)==null||o.call(r,this.interaction.clipId,s)}finishInteraction(t){var i,s,n,r;const e=this.interaction;if(!e){this.setGlobalCursor(null),this.unbindDocumentListeners();return}t&&e.changed&&((s=(i=this.callbacks).onPreviewTransformCommit)==null||s.call(i,e.clipId,e.nextTransform)),(r=(n=this.callbacks).onPreviewTransformChange)==null||r.call(n,e.clipId,null),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners()}render(){if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none");return}const{displayRect:t}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${t.left}px`,this.boxElement.style.top=`${t.top}px`,this.boxElement.style.width=`${t.width}px`,this.boxElement.style.height=`${t.height}px`,this.positionHandle("top-left",0,0),this.positionHandle("top-right",t.width,0),this.positionHandle("bottom-right",t.width,t.height),this.positionHandle("bottom-left",0,t.height)}positionHandle(t,e,i){const s=this.handleElements.get(t);s&&(s.style.left=`${e}px`,s.style.top=`${i}px`)}toLocalPoint(t){const e=this.getFrameBounds();return{x:(t.clientX??0)-e.left,y:(t.clientY??0)-e.top}}getFrameBounds(){var e,i;if(!this.frameElement)return{left:0,top:0,width:0,height:0};const t=(i=(e=this.frameElement).getBoundingClientRect)==null?void 0:i.call(e);return t&&Number.isFinite(t.width)&&Number.isFinite(t.height)?{left:t.left,top:t.top,width:t.width,height:t.height}:{left:bs(this.frameElement.style.left),top:bs(this.frameElement.style.top),width:this.frameElement.clientWidth,height:this.frameElement.clientHeight}}getDocument(){var t;return(t=this.frameElement)!=null&&t.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}setGlobalCursor(t){var i;const e=(i=this.getDocument())==null?void 0:i.body;e&&(e.style.cursor=t||"")}}function tl(a,t){return!Qt(a.mode)||!t?a:{mode:vt.mode,width:t.width,height:t.height}}function el(a){return a.getAttribute("src")||a.currentSrc||a.src||""}function ks(a){return typeof HTMLVideoElement<"u"?a instanceof HTMLVideoElement:a.tagName==="VIDEO"}function le(a){try{a.load()}catch{}}function qt(a){try{a.pause()}catch{}}function il(a){var t;try{const e=a.play();(t=e==null?void 0:e.catch)==null||t.call(e,()=>{})}catch{}}function ws(a,t){try{a.currentTime=Math.max(0,t)}catch{}}function Fe(a,t){var i;const e=(i=a==null?void 0:a.clip.style)==null?void 0:i[t];return typeof e=="number"&&e>0?e:null}function _s(a){if(!a)return 0;const t=Number.parseFloat(a);return Number.isFinite(t)?t:0}class sl{constructor(t={},e={}){g(this,"container",null);g(this,"rootElement",null);g(this,"frameElement",null);g(this,"pendingOverlayElement",null);g(this,"pendingOverlayStatusElement",null);g(this,"pendingOverlayDetailElement",null);g(this,"pendingOverlayActionElement",null);g(this,"resizeObserver",null);g(this,"trackSlots",new Map);g(this,"audioContext",null);g(this,"masterGainNode",null);g(this,"isBuffering",!1);g(this,"loadingCount",0);g(this,"selectedClipId",null);g(this,"transientVisualTransform",null);g(this,"callbacks");g(this,"dependencies");g(this,"transformOverlay");g(this,"requestedAspectRatio",{...vt});g(this,"resolvedAutoAspectRatio",null);g(this,"aspectRatioProbe",null);g(this,"aspectRatioProbeSrc",null);g(this,"isAspectRatioProbeLoading",!1);g(this,"pendingState",null);this.callbacks=t,this.dependencies=e,this.transformOverlay=new Qo({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,s)=>{var n,r;(r=(n=this.callbacks).onVisualTransformCommit)==null||r.call(n,i,s)}})}hasPreview(){return!!this.container}attach(t){if(this.container===t&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=t;const e=document.createElement("div");e.className=this.dependencies.rootClassName??"timeline-preview-root",e.style.position="relative",e.style.width="100%",e.style.height="100%",e.style.overflow="hidden";const i=document.createElement("div");i.className=this.dependencies.frameClassName??"timeline-preview-frame",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.overflow="hidden",i.style.background="#000000",e.appendChild(i);const s=document.createElement("div");s.className="timeline-preview-pending-overlay",s.style.position="absolute",s.style.inset="0",s.style.display="none",s.style.alignItems="center",s.style.justifyContent="center",s.style.flexDirection="column",s.style.gap="8px",s.style.background="rgba(0, 0, 0, 0.56)",s.style.color="#ffffff",s.style.fontSize="13px",s.style.zIndex="2000";const n=document.createElement("div");n.className="timeline-preview-pending-overlay__status",n.style.fontWeight="600";const r=document.createElement("div");r.className="timeline-preview-pending-overlay__detail",r.style.opacity="0.88";const o=document.createElement("button");o.className="timeline-preview-pending-overlay__action",o.style.display="none",o.style.padding="6px 12px",o.style.border="0",o.style.borderRadius="6px",o.style.cursor="pointer",o.style.background="#4c8dff",o.style.color="#ffffff",o.textContent="刷新重试",o.addEventListener("click",()=>{var l,h;(h=(l=this.callbacks).onPendingPreviewRetry)==null||h.call(l)}),s.appendChild(n),s.appendChild(r),s.appendChild(o),e.appendChild(s),t.appendChild(e),this.rootElement=e,this.frameElement=i,this.pendingOverlayElement=s,this.pendingOverlayStatusElement=n,this.pendingOverlayDetailElement=r,this.pendingOverlayActionElement=o,this.transformOverlay.attach(i),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(t)),this.updateFrameLayout(),this.refreshPendingOverlay()}detach(){var t,e,i,s,n,r;(t=this.resizeObserver)==null||t.disconnect(),this.resizeObserver=null,this.transformOverlay.detach();for(const o of this.trackSlots.values())this.destroySlot(o.current),this.destroySlot(o.preload);this.trackSlots.clear(),this.aspectRatioProbe&&(qt(this.aspectRatioProbe),this.aspectRatioProbe.src="",le(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.isAspectRatioProbeLoading=!1,this.audioContext&&((n=(i=(e=this.audioContext).close)==null?void 0:(s=i.call(e)).catch)==null||n.call(s,()=>{}),this.audioContext=null,this.masterGainNode=null),(r=this.rootElement)==null||r.remove(),this.rootElement=null,this.frameElement=null,this.pendingOverlayElement=null,this.pendingOverlayStatusElement=null,this.pendingOverlayDetailElement=null,this.pendingOverlayActionElement=null,this.container=null,this.selectedClipId=null,this.transientVisualTransform=null,this.pendingState=null,this.setBufferingState(!1),this.setLoadingCount(0)}setPendingState(t){this.pendingState=t,this.refreshPendingOverlay()}sync(t){var n,r;if(!this.rootElement||!this.frameElement)return;this.selectedClipId=t.selectedClipId??null,this.maybeResolveAutoAspectRatio(t.autoAspectRatioClip);const e=[...t.activeClips].sort((o,l)=>o.trackOrder-l.trackOrder),i=new Set(e.map(o=>o.trackId)),s=new Map(t.nextClips.map(o=>[o.trackId,o]));for(const o of e){this.getTrackSlots(o.trackId,o.trackType).preload.attachedClipId===o.clip.id&&this.swapTrackSlots(o.trackId);const h=this.getTrackSlots(o.trackId,o.trackType);this.assignClipToSlot(h.current,o),this.syncCurrentSlot(h.current,o,t.speed,t.playState),this.preparePreloadSlot(h.preload,s.get(o.trackId)||null)}for(const[o,l]of this.trackSlots.entries())i.has(o)||(l.current.isActive=!1,l.current.entry=null,l.current.isBuffering=!1,qt(l.current.element),this.setSlotVisible(l.current,!1,0),this.preparePreloadSlot(l.preload,s.get(o)||null));this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.selectedClipId&&(this.transientVisualTransform=null),this.refreshVisualLayout(),this.refreshLoadingState(),this.refreshBufferingState(),(r=(n=this.callbacks).onSyncProcessed)==null||r.call(n,t.syncRequestId)}applyAspectRatio(t){this.requestedAspectRatio=Dt(t),this.updateFrameLayout()}getAspectRatio(){return tl(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}createMediaElement(t,e){const i=this.dependencies.createMediaElement,s=i?i(t,e):document.createElement(t==="video"?"video":"audio");return s.preload=e==="preload"?"auto":"metadata",s.crossOrigin="anonymous",s.loop=!1,s.controls=!1,ks(s)?(s.playsInline=!0,s.disablePictureInPicture=!0,s.style.position="absolute",s.style.inset="0",s.style.width="100%",s.style.height="100%",s.style.objectFit="fill",s.style.background="#000000",s.style.pointerEvents="none"):s.style.display="none",s}createSlot(t,e,i){var p,f;const s=this.createMediaElement(e,i),n=e==="video"?document.createElement("div"):null;if(n){const y=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";n.className=`${y} timeline-preview-slot--${t} timeline-preview-slot--${i}`,n.style.position="absolute",n.style.overflow="hidden",n.style.background="#000000",n.style.pointerEvents="none",n.style.display="none",n.appendChild(s),(p=this.frameElement)==null||p.appendChild(n)}const r={role:i,trackId:t,kind:e,wrapper:n,element:s,attachedClipId:null,attachedSrc:null,entry:null,isActive:!1,isLoading:!1,isBuffering:!1,isSeeking:!1,sourceNode:null,gainNode:null,audioRoutingFailed:!1,cleanup:[]},o=()=>{r.isLoading=!0,this.refreshLoadingState()},l=()=>{r.isLoading=!1,r.isSeeking=!1,r.isBuffering=!1,this.tryResolveAutoAspectRatioFromSlot(r),this.refreshVisualLayout(),this.refreshLoadingState(),this.refreshBufferingState()},h=()=>{r.isBuffering=r.isActive,this.refreshBufferingState()},c=()=>{r.isSeeking=!0,r.isBuffering=r.isActive,this.refreshBufferingState()},d=()=>{r.isSeeking=!1,r.isBuffering=!1,this.refreshBufferingState()},u=()=>{r.isLoading=!1,r.isSeeking=!1,r.isBuffering=!1,this.refreshLoadingState(),this.refreshBufferingState()};return s.addEventListener("loadstart",o),s.addEventListener("loadedmetadata",l),s.addEventListener("canplay",l),s.addEventListener("playing",l),s.addEventListener("waiting",h),s.addEventListener("stalled",h),s.addEventListener("seeking",c),s.addEventListener("seeked",d),s.addEventListener("error",u),r.cleanup.push(()=>s.removeEventListener("loadstart",o),()=>s.removeEventListener("loadedmetadata",l),()=>s.removeEventListener("canplay",l),()=>s.removeEventListener("playing",l),()=>s.removeEventListener("waiting",h),()=>s.removeEventListener("stalled",h),()=>s.removeEventListener("seeking",c),()=>s.removeEventListener("seeked",d),()=>s.removeEventListener("error",u)),e==="audio"&&((f=this.rootElement)==null||f.appendChild(s)),r}destroySlot(t){var e,i,s,n,r;t.cleanup.forEach(o=>o()),qt(t.element),t.element.src="",le(t.element),(i=(e=t.gainNode)==null?void 0:e.disconnect)==null||i.call(e),(n=(s=t.sourceNode)==null?void 0:s.disconnect)==null||n.call(s),t.gainNode=null,t.sourceNode=null,(r=t.wrapper)==null||r.remove(),t.element.remove()}getTrackSlots(t,e){const i=this.trackSlots.get(t);if(i)return i;const s={current:this.createSlot(t,e,"current"),preload:this.createSlot(t,e,"preload")};return this.trackSlots.set(t,s),s}swapTrackSlots(t){const e=this.trackSlots.get(t);e&&(e.current.role="preload",e.preload.role="current",this.trackSlots.set(t,{current:e.preload,preload:e.current}))}assignClipToSlot(t,e){t.entry=e,t.isActive=t.role==="current";const i=e.clip.src,s=t.attachedSrc||el(t.element);(t.attachedClipId!==e.clip.id||s!==i)&&(t.attachedClipId=e.clip.id,t.attachedSrc=i,t.isLoading=!0,t.isBuffering=!1,t.element.setAttribute("src",i),le(t.element)),this.configureAudioRouting(t,e)}configureAudioRouting(t,e){if(!e.hasAudio){t.element.muted=!0;return}const i=this.getAudioContext();if(!i||t.audioRoutingFailed){t.element.muted=e.muted;return}if(!t.sourceNode||!t.gainNode)try{t.sourceNode=i.createMediaElementSource(t.element),t.gainNode=i.createGain(),t.sourceNode.connect(t.gainNode),t.gainNode.connect(this.getMasterGainNode(i))}catch{t.audioRoutingFailed=!0,t.element.muted=e.muted;return}t.element.muted=!1,t.gainNode.gain.value=e.muted?0:1}syncCurrentSlot(t,e,i,s){t.isActive=!0,t.entry=e,t.element.playbackRate=i;const n=e.mediaTime/1e3,r=Math.max(.1,i*.15);Math.abs(t.element.currentTime-n)>r&&(t.isSeeking=!0,t.isBuffering=!0,ws(t.element,n),this.refreshBufferingState()),s==="playing"?(this.resumeAudioContext(),il(t.element)):qt(t.element),this.setSlotVisible(t,e.hasVisual,1e3-e.trackOrder)}preparePreloadSlot(t,e){if(t.isActive=!1,t.isBuffering=!1,t.isSeeking=!1,!e){qt(t.element),t.entry=null,t.attachedClipId=null,t.attachedSrc=null,t.isLoading=!1,t.element.removeAttribute("src"),le(t.element),this.setSlotVisible(t,!1,0);return}this.assignClipToSlot(t,e),t.element.playbackRate=1,ws(t.element,e.clip.startTimeAtSource/1e3),qt(t.element),this.setSlotVisible(t,!1,0)}setSlotVisible(t,e,i){if(t.kind!=="video"||!t.wrapper){t.element.style.display="none";return}t.wrapper.style.display=e?"block":"none",t.wrapper.style.zIndex=String(i),t.wrapper.style.pointerEvents="none",t.element.style.display=e?"block":"none",t.element.style.zIndex=String(i)}getAudioContext(){if(this.audioContext)return this.audioContext;const t=this.dependencies.createAudioContext;if(t)return this.audioContext=t(),this.audioContext;if(typeof window>"u")return null;const e=window.AudioContext||window.webkitAudioContext;return e?(this.audioContext=new e,this.audioContext):null}getMasterGainNode(t){if(this.masterGainNode)return this.masterGainNode;const e=t.createGain();return e.gain.value=1,e.connect(t.destination),this.masterGainNode=e,e}resumeAudioContext(){var t,e,i,s;!this.audioContext||this.audioContext.state!=="suspended"||(s=(e=(t=this.audioContext).resume)==null?void 0:(i=e.call(t)).catch)==null||s.call(i,()=>{})}updateFrameLayout(){if(!this.container||!this.frameElement)return;const{width:t,height:e}=this.getAspectRatio(),i=this.container.clientWidth,s=this.container.clientHeight;if(i<=0||s<=0||t<=0||e<=0)return;const n=t/e,r=i/s;let o=i,l=s;n>r?l=i/n:o=s*n,this.frameElement.style.width=`${o}px`,this.frameElement.style.height=`${l}px`,this.frameElement.style.left=`${(i-o)/2}px`,this.frameElement.style.top=`${(s-l)/2}px`,this.refreshVisualLayout()}maybeResolveAutoAspectRatio(t){if(!Qt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!t||!t.hasVisual)return;const e=Fe(t,"sys_width"),i=Fe(t,"sys_height");if(e&&i){this.handleResolvedAutoAspectRatio(e,i);return}if(this.aspectRatioProbeSrc===t.clip.src)return;const s=this.getAspectRatioProbe();this.aspectRatioProbeSrc=t.clip.src,this.isAspectRatioProbeLoading=!0,this.refreshLoadingState(),s.crossOrigin="anonymous",s.preload="metadata",s.muted=!0,s.src=t.clip.src,le(s)}getAspectRatioProbe(){var s,n;if(this.aspectRatioProbe)return this.aspectRatioProbe;const t=((n=(s=this.dependencies).createAspectRatioProbe)==null?void 0:n.call(s))||document.createElement("video"),e=()=>{this.isAspectRatioProbeLoading=!1,this.refreshLoadingState(),t.videoWidth>0&&t.videoHeight>0&&this.handleResolvedAutoAspectRatio(t.videoWidth,t.videoHeight)},i=()=>{this.isAspectRatioProbeLoading=!1,this.refreshLoadingState()};return t.addEventListener("loadedmetadata",e),t.addEventListener("error",i),this.aspectRatioProbe=t,t}tryResolveAutoAspectRatioFromSlot(t){if(!Qt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||t.kind!=="video")return;const e=t.element;e.videoWidth>0&&e.videoHeight>0&&this.handleResolvedAutoAspectRatio(e.videoWidth,e.videoHeight)}handleResolvedAutoAspectRatio(t,e){var i,s;t<=0||e<=0||(this.resolvedAutoAspectRatio={width:t,height:e},this.updateFrameLayout(),Qt(this.requestedAspectRatio.mode)&&((s=(i=this.callbacks).onAspectRatioChange)==null||s.call(i,this.getAspectRatio())))}refreshBufferingState(){const t=Array.from(this.trackSlots.values()).some(({current:e,preload:i})=>e.isBuffering||i.isBuffering);this.setBufferingState(t)}setBufferingState(t){var e,i;this.isBuffering!==t&&(this.isBuffering=t,(i=(e=this.callbacks).onBufferingStateChange)==null||i.call(e,t))}refreshLoadingState(){let t=this.isAspectRatioProbeLoading?1:0;for(const{current:e,preload:i}of this.trackSlots.values())e.isLoading&&(t+=1),i.isLoading&&(t+=1);this.setLoadingCount(t)}setLoadingCount(t){var e,i;this.loadingCount!==t&&(this.loadingCount=t,(i=(e=this.callbacks).onSourceLoadingChange)==null||i.call(e,t))}refreshPendingOverlay(){if(!this.pendingOverlayElement||!this.pendingOverlayStatusElement||!this.pendingOverlayDetailElement||!this.pendingOverlayActionElement)return;if(!this.pendingState){this.pendingOverlayElement.style.display="none",this.pendingOverlayActionElement.style.display="none";return}if(this.pendingOverlayElement.style.display="flex",this.pendingState.errorMessage){this.pendingOverlayStatusElement.textContent="资源加载异常",this.pendingOverlayDetailElement.textContent=this.pendingState.errorMessage,this.pendingOverlayActionElement.style.display="inline-flex";return}const t=this.pendingState.loadingPending>0;this.pendingOverlayStatusElement.textContent=t?"资源加载中…":"正在缓冲预览…",this.pendingOverlayDetailElement.textContent=t?`目标时间 ${Math.round(this.pendingState.targetTime)}ms,待加载资源 ${this.pendingState.loadingPending} 个`:`目标时间 ${Math.round(this.pendingState.targetTime)}ms,等待媒体可播放`,this.pendingOverlayActionElement.style.display="none"}handlePreviewTransformChange(t,e){var i;if(!e){((i=this.transientVisualTransform)==null?void 0:i.clipId)===t&&(this.transientVisualTransform=null,this.refreshVisualLayout());return}this.transientVisualTransform={clipId:t,transform:e},this.refreshVisualLayout()}refreshVisualLayout(){for(const{current:t,preload:e}of this.trackSlots.values())this.refreshSlotVisualLayout(t),this.refreshSlotVisualLayout(e);this.transformOverlay.sync(this.buildSelectedOverlayState())}refreshSlotVisualLayout(t){if(t.kind!=="video"||!t.wrapper||!t.entry||!this.frameElement)return;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return;const i=this.getMediaSize(t,t.entry,e),s=this.getEffectiveVisualTransform(t.entry),n=vs(e,i,s);t.wrapper.style.left=`${n.left}px`,t.wrapper.style.top=`${n.top}px`,t.wrapper.style.width=`${n.width}px`,t.wrapper.style.height=`${n.height}px`}buildSelectedOverlayState(){if(!this.selectedClipId)return null;const t=this.getFrameSize();if(t.width<=0||t.height<=0)return null;for(const{current:e}of this.trackSlots.values()){if(e.kind!=="video"||!e.isActive||!e.entry||e.entry.clip.id!==this.selectedClipId)continue;const i=this.getMediaSize(e,e.entry,t),s=this.getEffectiveVisualTransform(e.entry);return{clipId:e.entry.clip.id,transform:s,frameSize:t,baseRect:wn(t,i),displayRect:vs(t,i,s)}}return null}getFrameSize(){var i,s,n,r;const t=((i=this.frameElement)==null?void 0:i.clientWidth)??0,e=((s=this.frameElement)==null?void 0:s.clientHeight)??0;return{width:t>0?t:_s((n=this.frameElement)==null?void 0:n.style.width),height:e>0?e:_s((r=this.frameElement)==null?void 0:r.style.height)}}getMediaSize(t,e,i){if(ks(t.element)&&t.element.videoWidth>0&&t.element.videoHeight>0)return{width:t.element.videoWidth,height:t.element.videoHeight};const s=Fe(e,"sys_width"),n=Fe(e,"sys_height");return s&&n?{width:s,height:n}:{width:i.width,height:i.height}}getEffectiveVisualTransform(t){var e;return((e=this.transientVisualTransform)==null?void 0:e.clipId)===t.clip.id?this.transientVisualTransform.transform:ft(t.clip.visualTransform)}}class nl extends sl{destroy(){this.detach()}}function rl(a){return"dom"}const al=36e5,ol=3e5;function _n(a){return a.length===0?0:a.reduce((t,e)=>Math.max(t,e.startTime+e.duration),0)}function Pn(a){return Math.max(a+ol,al)}function ll(a){const t=_n(a.clips);return t===a.lastTrackDuration?a.lastTrackDuration:(a.setLastTrackDuration(t),a.setTimelineDuration(Pn(t)),a.emitTrackDurationChange(t),t)}class Ps{constructor(t={}){g(this,"listeners",new Map);this.initialPayloadProviders=t}on(t,e){this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t).push(e);const i=this.initialPayloadProviders[t];i&&e(t,i())}off(t,e){this.listeners.has(t)&&this.listeners.set(t,this.listeners.get(t).filter(i=>i!==e))}emit(t,e){this.listeners.has(t)&&this.listeners.get(t).forEach(i=>{try{i(t,e)}catch(s){O.error("TimelineEventDispatcher",`Error in event listener for ${t}:`,{error:s})}})}clear(){this.listeners.clear()}}function hl(a){return[...a].sort((t,e)=>t.order-e.order)}function cl(a){return[...a].sort((t,e)=>t.startTime-e.startTime)}function ui(a,t,e){return{trackId:a.id,trackType:a.type,trackOrder:a.order,clip:t,mediaTime:e,muted:(a.isMuted??!1)||(t.isMuted??!1),kind:a.type,hasVisual:a.type==="video",hasAudio:!0}}class dl{resolveActiveClipsAtTime(t,e){return this.resolvePlaybackPlan(t,e).activeClips}resolvePlaybackPlan(t,e){const i=hl(t),s=[],n=[];let r=null;for(const o of i){const l=cl(o.clips),h=l.find(d=>e>=d.startTime&&e<d.endTime);if(h){const d=h.startTimeAtSource+(e-h.startTime);s.push(ui(o,h,d))}const c=l.find(d=>d.startTime>e);if(c&&n.push(ui(o,c,c.startTimeAtSource)),!r&&o.type==="video"){const d=l[0];d&&(r=ui(o,d,d.startTimeAtSource))}}return{activeClips:s,nextClips:n,firstVideoClip:r}}}function ul(a){var e;const t=a.getSelectedClip()||((e=a.findFallbackSelectedClip)==null?void 0:e.call(a))||null;return{clip:t,hasSelectedClip:!!t}}function gl(a){var i;const t=a.resolveSelectedClip(),e=((i=t.clip)==null?void 0:i.id)||null;return e===a.lastSelectedClipId?a.lastSelectedClipId:(a.emitSelectedClipChange(t),e)}function xn(a,t){var e,i,s,n;return((i=(e=a.findById(t))==null?void 0:e.getId)==null?void 0:i.call(e))||((n=(s=a.getLastTrack())==null?void 0:s.getId)==null?void 0:n.call(s))||t}function fl(a){if(a.placement.status==="use_existing_track")return a.trackCollection.addClipToTrack(a.placement.trackId,a.clip);const t=a.createTrack(a.placement.trackType,a.placement.suggestedTrackName),e=xn(a.trackCollection,t);return e?a.trackCollection.addClipToTrack(e,a.clip):!1}function xs(a,t,e){return t.trackId?a.removeClipFromTrack(t.trackId,e):!1}function pl(a){return a.trackCollection.moveClipToTrack(a.command.clip,a.command.sourceTrackId,a.command.targetTrackId)}function ml(a){const t=a.createTrack(a.trackType,a.trackName),e=xn(a.trackCollection,t);return e?a.trackCollection.moveClipToTrack(a.clip,a.currentTrackId,e):!1}function It(a){var t,e,i,s,n;(t=a.checkTrackDurationChange)==null||t.call(a),(e=a.updateCanPlayState)==null||e.call(a),(i=a.updateTrackInfoPanel)==null||i.call(a),(s=a.handleClipChange)==null||s.call(a),(n=a.cleanupEmptyTracks)==null||n.call(a)}function yl(a){var t,e;a.notifySelectionChange(),(t=a.cleanupEmptyTracks)==null||t.call(a),a.updateTrackInfoPanel(),(e=a.batchDraw)==null||e.call(a),a.syncPreviewSession()}class Cl{constructor(){g(this,"panel",null)}init(t){var i,s,n,r;const e=((i=t.theme)==null?void 0:i.background)||"#1a1a1a";this.panel=new vn({container:t.container,theme:{background:e,border:((s=t.theme)==null?void 0:s.border)||"#333333",text:((n=t.theme)==null?void 0:n.clipName)||"#ffffff",buttonBackground:((r=t.theme)==null?void 0:r.clipBackground)||"#2a2a2a",buttonHover:"#3a3a3a",buttonDanger:"#dc3545"},width:200,timeScaleHeight:t.timeScaleHeight||40,includeTimeScaleSpacer:t.includeTimeScaleSpacer},t.onRenameTrack,t.onRemoveTrack,t.onMuteTrack)}hasPanel(){return!!this.panel}update(t){var e;(e=this.panel)==null||e.setTracks(t)}setScrollTop(t){var e;(e=this.panel)==null||e.setScrollTop(t)}destroy(){var t;(t=this.panel)==null||t.destroy(),this.panel=null}}class As{syncCurrentTime(t,e,i,s){t==null||t.setCurrentTime(s),e==null||e.setCurrentTime(s),i.syncCurrentTime(s)}syncZoom(t,e,i,s){t==null||t.setZoom(s),e==null||e.setZoom(s),i.syncZoom(s)}syncScrollLeft(t,e,i){t==null||t.setScrollLeft(i),e.syncScrollLeft(i)}syncScrollTop(t,e,i){t==null||t.setScrollTop(i),e==null||e.setScrollTop(i)}syncSelection(t,e,i){const s=t.getAll(),n=s.some(o=>o.updateSelectionVisual),r=s.some(o=>o.updateClipSelection);if(i&&i.length>0&&r){const o=new Set(i);t.forEach(l=>{l.getClips().forEach(c=>{var d;(d=l.updateClipSelection)==null||d.call(l,c.id,o.has(c.id))})});return}if(n){t.forEach(o=>{var l;(l=o.updateSelectionVisual)==null||l.call(o,e)});return}if(e){let o=null;t.forEach(h=>{var u,p;const c=(u=h.getSelectedClip)==null?void 0:u.call(h);h.getClips().some(f=>f.id===e)&&(o=h),(!c||c.id!==e)&&((p=h.clearSelection)==null||p.call(h))});const l=o==null?void 0:o.selectClip;typeof l=="function"&&l(e);return}t.clearSelection()}findSelectedClip(t){var e;for(const i of t.getAll()){const s=(e=i.getSelectedClip)==null?void 0:e.call(i);if(s)return s}return null}}class Es{constructor(t,e=Ze){this.handlers=t,this.TrackCtor=e}createTrack(t){return new this.TrackCtor(t.layer,t.config,t.trackType,t.zoom,t.trackY,t.trackHeight,t.theme,this.handlers.onClipUpdate,this.handlers.onClipAdd,this.handlers.onClipRemove,this.handlers.onClipSplit,this.handlers.onClipSelect,this.handlers.onTimeJump,this.handlers.onHorizontalDragAutoScroll,this.handlers.onClipOverlap,this.handlers.onClipCrossTrackPreview,this.handlers.onClipCrossTrack,this.handlers.onClearDropPreview,this.handlers.onClearSelection,this.handlers.onSnapGuideChange,this.handlers.onClipToggleSelection,this.handlers.onSetSingleSelection,this.handlers.getMultiDragClipIds,this.handlers.onMultiDragMove,this.handlers.onMultiDragInteractionEnd,t.dragActivationThreshold,t.enableClipSnap,t.clipSnapThreshold)}}class Sl{constructor(t){this.tracks=t}getAll(){return this.tracks}getDefaultTrack(){return this.tracks[0]||null}getPrimaryTrack(){return this.tracks.find(t=>{var e;return((e=t.getRole)==null?void 0:e.call(t))==="primary"})||this.getDefaultTrack()}getLastTrack(){return this.tracks.length>0?this.tracks[this.tracks.length-1]:null}add(t){this.tracks.push(t)}findById(t){return this.tracks.find(e=>this.resolveTrackId(e)===t)||null}removeById(t){const e=this.findIndexById(t);if(e===-1)return null;const[i]=this.tracks.splice(e,1);return i||null}removeEmptyNonPrimaryTracks(){var e;const t=[];for(let i=this.tracks.length-1;i>=0;i-=1){const s=this.tracks[i];if(((e=s.getRole)==null?void 0:e.call(s))==="primary"||(typeof s.getClips=="function"?s.getClips():[]).length>0)continue;const[r]=this.tracks.splice(i,1);r&&t.push(r)}return t.reverse()}findTrackByClipId(t){return this.tracks.find(e=>e.getClips().some(i=>i.id===t))||null}getAllClips(){return this.tracks.flatMap(t=>t.getClips())}syncCurrentTime(t){this.tracks.forEach(e=>{var i;return(i=e.setCurrentTime)==null?void 0:i.call(e,t)})}syncZoom(t){this.tracks.forEach(e=>{var i;return(i=e.setZoom)==null?void 0:i.call(e,t)})}syncScrollLeft(t){this.tracks.forEach(e=>{var i;return(i=e.setScrollLeft)==null?void 0:i.call(e,t)})}syncScrollTop(t){this.tracks.forEach(e=>{var i;return(i=e.setScrollTop)==null?void 0:i.call(e,t)})}updateClip(t,e){this.tracks.forEach(i=>{var s;return(s=i.updateClip)==null?void 0:s.call(i,t,e)})}removeClip(t){this.tracks.forEach(e=>{var i;return(i=e.removeClip)==null?void 0:i.call(e,t)})}addClipToTrack(t,e){const i=this.findById(t);return i!=null&&i.addClip?(i.addClip(e),!0):!1}removeClipFromTrack(t,e){const i=this.findById(t);return i!=null&&i.removeClip?(i.removeClip(e),!0):!1}moveClipToTrack(t,e,i){if(e===i)return!0;const s=this.findById(e),n=this.findById(i);return!(s!=null&&s.removeClip)||!(n!=null&&n.addClip)?!1:(s.removeClip(t.id),n.addClip(t),!0)}removeClipGaps(){this.tracks.forEach(t=>{var e;return(e=t.removeClipGaps)==null?void 0:e.call(t)})}clearSelection(){this.tracks.forEach(t=>{var e;return(e=t.clearSelection)==null?void 0:e.call(t)})}forEach(t){this.tracks.forEach(t)}findIndexById(t){return this.tracks.findIndex(e=>this.resolveTrackId(e)===t)}resolveTrackId(t){return typeof t.getId=="function"?t.getId():typeof t.id=="string"?t.id:null}}class An{constructor(t=[]){g(this,"tracks",[]);g(this,"trackCounter",0);this.tracks=[...t],this.trackCounter=this.tracks.length}createTrack(t,e,i,s){this.trackCounter++;const n=e||`${t==="video"?"视频":"音频"}轨道 ${this.trackCounter}`,r=this.tracks.length===0?"primary":"normal",o={id:`track_${Date.now()}_${this.trackCounter}`,type:t,name:n,order:this.tracks.length,role:r,clips:[]};return this.insertTrack(o,i,s),O.debugLazy("TrackManager",()=>`创建轨道: ${n}`,()=>({trackId:o.id,type:t,order:o.order})),o}removeTrack(t){var i;const e=this.tracks.findIndex(s=>s.id===t);return e===-1?(O.warn("TrackManager",`轨道不存在: ${t}`),!1):((i=this.tracks[e])==null?void 0:i.role)==="primary"?(O.warn("TrackManager",`主轨不可删除: ${t}`),!1):(this.tracks.splice(e,1),this.recalculateOrder(),O.debugLazy("TrackManager",()=>`删除轨道: ${t}`),!0)}renameTrack(t,e){const i=this.tracks.find(s=>s.id===t);return i?(i.name=e,O.debugLazy("TrackManager",()=>`重命名轨道: ${t} -> ${e}`),!0):(O.warn("TrackManager",`轨道不存在: ${t}`),!1)}getTracks(){return[...this.tracks]}getTrack(t){return this.tracks.find(e=>e.id===t)}getTracksByType(t){return this.tracks.filter(e=>e.type===t)}updateTrack(t,e){const i=this.tracks.find(s=>s.id===t);return i?(Object.assign(i,e),O.debugLazy("TrackManager",()=>`更新轨道: ${t}`,()=>e),!0):(O.warn("TrackManager",`轨道不存在: ${t}`),!1)}recalculateOrder(){this.tracks.forEach((t,e)=>{t.order=e})}insertTrack(t,e,i){const s=this.tracks.findIndex(r=>r.role==="primary"),n=e??(t.type==="video"?"before_primary":"after_primary");if(s===-1||t.role==="primary"){this.tracks.push(t),this.recalculateOrder();return}if((n==="before_track"||n==="after_track")&&i){const r=this.tracks.findIndex(o=>o.id===i);if(r!==-1){this.tracks.splice(r+(n==="after_track"?1:0),0,t),this.recalculateOrder();return}}if(n==="top_of_type_region"){const r=this.tracks.findIndex(o=>o.type===t.type);if(r!==-1){this.tracks.splice(r,0,t),this.recalculateOrder();return}}if(n==="bottom_of_type_region"){const r=this.tracks.reduce((o,l,h)=>l.type===t.type?h:o,-1);if(r!==-1){this.tracks.splice(r+1,0,t),this.recalculateOrder();return}}n==="before_primary"?this.tracks.splice(s,0,t):this.tracks.splice(s+1,0,t),this.recalculateOrder()}muteTrack(t,e){const i=this.tracks.find(s=>s.id===t);return i?(i.isMuted=e,O.debugLazy("TrackManager",()=>`${e?"静音":"取消静音"}轨道:${t}`),!0):(O.warn("TrackManager",`轨道不存在:${t}`),!1)}isTrackMuted(t){const e=this.tracks.find(i=>i.id===t);return(e==null?void 0:e.isMuted)??!1}getTrackCount(){return this.tracks.length}getTrackCountByType(t){return this.tracks.filter(e=>e.type===t).length}}function Vt(a){return a==="video"?_t.VIDEO:_t.AUDIO}function he(a,t,e){let i=e;for(const s of a){if(s.id===t)break;i+=Vt(s.type)}return i}function Is(a,t){return a.reduce((e,i)=>e+Vt(i.type),t)}function Tl(a,t){let e=t;return a.map(i=>{const s=Vt(i.type),n={trackId:i.id,y:e,height:s};return e+=s,n})}const En=200,In=8,Ms="timeline-manager-managed-layout-styles";function vl(){if(typeof document>"u"||document.getElementById(Ms))return;const a=document.createElement("style");a.id=Ms,a.textContent=`
14
+ `,Yi=()=>{if(typeof document>"u")throw new Error(js)};class ue{constructor(e=[1,0,0,1,0,0]){this.dirty=!1,this.m=e&&e.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new ue(this.m)}copyInto(e){e.m[0]=this.m[0],e.m[1]=this.m[1],e.m[2]=this.m[2],e.m[3]=this.m[3],e.m[4]=this.m[4],e.m[5]=this.m[5]}point(e){const t=this.m;return{x:t[0]*e.x+t[2]*e.y+t[4],y:t[1]*e.x+t[3]*e.y+t[5]}}translate(e,t){return this.m[4]+=this.m[0]*e+this.m[2]*t,this.m[5]+=this.m[1]*e+this.m[3]*t,this}scale(e,t){return this.m[0]*=e,this.m[1]*=e,this.m[2]*=t,this.m[3]*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),n=this.m[0]*t+this.m[2]*i,s=this.m[1]*t+this.m[3]*i,r=this.m[0]*-i+this.m[2]*t,o=this.m[1]*-i+this.m[3]*t;return this.m[0]=n,this.m[1]=s,this.m[2]=r,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(e,t){const i=this.m[0]+this.m[2]*t,n=this.m[1]+this.m[3]*t,s=this.m[2]+this.m[0]*e,r=this.m[3]+this.m[1]*e;return this.m[0]=i,this.m[1]=n,this.m[2]=s,this.m[3]=r,this}multiply(e){const t=this.m[0]*e.m[0]+this.m[2]*e.m[1],i=this.m[1]*e.m[0]+this.m[3]*e.m[1],n=this.m[0]*e.m[2]+this.m[2]*e.m[3],s=this.m[1]*e.m[2]+this.m[3]*e.m[3],r=this.m[0]*e.m[4]+this.m[2]*e.m[5]+this.m[4],o=this.m[1]*e.m[4]+this.m[3]*e.m[5]+this.m[5];return this.m[0]=t,this.m[1]=i,this.m[2]=n,this.m[3]=s,this.m[4]=r,this.m[5]=o,this}invert(){const e=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),t=this.m[3]*e,i=-this.m[1]*e,n=-this.m[2]*e,s=this.m[0]*e,r=e*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=e*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=t,this.m[1]=i,this.m[2]=n,this.m[3]=s,this.m[4]=r,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const e=this.m[0],t=this.m[1],i=this.m[2],n=this.m[3],s=this.m[4],r=this.m[5],o=e*n-t*i,l={x:s,y:r,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(e!=0||t!=0){const h=Math.sqrt(e*e+t*t);l.rotation=t>0?Math.acos(e/h):-Math.acos(e/h),l.scaleX=h,l.scaleY=o/h,l.skewX=(e*i+t*n)/o,l.skewY=0}else if(i!=0||n!=0){const h=Math.sqrt(i*i+n*n);l.rotation=Math.PI/2-(n>0?Math.acos(-i/h):-Math.acos(i/h)),l.scaleX=o/h,l.scaleY=h,l.skewX=0,l.skewY=(e*i+t*n)/o}return l.rotation=v._getRotation(l.rotation),l}}const Zs="[object Array]",Js="[object Number]",Qs="[object String]",er="[object Boolean]",tr=Math.PI/180,ir=180/Math.PI,ot="#",nr="",sr="0",rr="Konva warning: ",Xi="Konva error: ",ar="rgb(",ri={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},or=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let Rt=[],lt=null;const lr=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(a){setTimeout(a,16)},v={_isElement(a){return!!(a&&a.nodeType==1)},_isFunction(a){return!!(a&&a.constructor&&a.call&&a.apply)},_isPlainObject(a){return!!a&&a.constructor===Object},_isArray(a){return Object.prototype.toString.call(a)===Zs},_isNumber(a){return Object.prototype.toString.call(a)===Js&&!isNaN(a)&&isFinite(a)},_isString(a){return Object.prototype.toString.call(a)===Qs},_isBoolean(a){return Object.prototype.toString.call(a)===er},isObject(a){return a instanceof Object},isValidSelector(a){if(typeof a!="string")return!1;const e=a[0];return e==="#"||e==="."||e===e.toUpperCase()},_sign(a){return a===0||a>0?1:-1},requestAnimFrame(a){Rt.push(a),Rt.length===1&&lr(function(){const e=Rt;Rt=[],e.forEach(function(t){t()})})},createCanvasElement(){Yi();const a=document.createElement("canvas");try{a.style=a.style||{}}catch{}return a},createImageElement(){return Yi(),document.createElement("img")},_isInDocument(a){for(;a=a.parentNode;)if(a==document)return!0;return!1},_urlToImage(a,e){const t=v.createImageElement();t.onload=function(){e(t)},t.src=a},_rgbToHex(a,e,t){return((1<<24)+(a<<16)+(e<<8)+t).toString(16).slice(1)},_hexToRgb(a){a=a.replace(ot,nr);const e=parseInt(a,16);return{r:e>>16&255,g:e>>8&255,b:e&255}},getRandomColor(){let a=(Math.random()*16777215<<0).toString(16);for(;a.length<6;)a=sr+a;return ot+a},isCanvasFarblingActive(){if(lt!==null)return lt;if(typeof document>"u")return lt=!1,!1;const a=this.createCanvasElement();a.width=10,a.height=10;const e=a.getContext("2d",{willReadFrequently:!0});e.clearRect(0,0,10,10),e.fillStyle="#282828",e.fillRect(0,0,10,10);const t=e.getImageData(0,0,10,10).data;let i=!1;for(let n=0;n<100;n++)if(t[n*4]!==40||t[n*4+1]!==40||t[n*4+2]!==40||t[n*4+3]!==255){i=!0;break}return lt=i,this.releaseCanvas(a),lt},getHitColor(){const a=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(a):a},getHitColorKey(a,e,t){return this.isCanvasFarblingActive()&&(a=Math.round(a/5)*5,e=Math.round(e/5)*5,t=Math.round(t/5)*5),ot+this._rgbToHex(a,e,t)},getSnappedHexColor(a){const e=this._hexToRgb(a);return ot+this._rgbToHex(Math.round(e.r/5)*5,Math.round(e.g/5)*5,Math.round(e.b/5)*5)},getRGB(a){let e;return a in ri?(e=ri[a],{r:e[0],g:e[1],b:e[2]}):a[0]===ot?this._hexToRgb(a.substring(1)):a.substr(0,4)===ar?(e=or.exec(a.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA(a){return a=a||"black",v._namedColorToRBA(a)||v._hex3ColorToRGBA(a)||v._hex4ColorToRGBA(a)||v._hex6ColorToRGBA(a)||v._hex8ColorToRGBA(a)||v._rgbColorToRGBA(a)||v._rgbaColorToRGBA(a)||v._hslColorToRGBA(a)},_namedColorToRBA(a){const e=ri[a.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(a){if(a.indexOf("rgb(")===0){a=a.match(/rgb\(([^)]+)\)/)[1];const e=a.split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(a){if(a.indexOf("rgba(")===0){a=a.match(/rgba\(([^)]+)\)/)[1];const e=a.split(/ *, */).map((t,i)=>t.slice(-1)==="%"?i===3?parseInt(t)/100:parseInt(t)/100*255:Number(t));return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex8ColorToRGBA(a){if(a[0]==="#"&&a.length===9)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:parseInt(a.slice(7,9),16)/255}},_hex6ColorToRGBA(a){if(a[0]==="#"&&a.length===7)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:1}},_hex4ColorToRGBA(a){if(a[0]==="#"&&a.length===5)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:parseInt(a[4]+a[4],16)/255}},_hex3ColorToRGBA(a){if(a[0]==="#"&&a.length===4)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:1}},_hslColorToRGBA(a){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(a)){const[e,...t]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a),i=Number(t[0])/360,n=Number(t[1])/100,s=Number(t[2])/100;let r,o,l;if(n===0)return l=s*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};s<.5?r=s*(1+n):r=s+n-s*n;const h=2*s-r,c=[0,0,0];for(let d=0;d<3;d++)o=i+1/3*-(d-1),o<0&&o++,o>1&&o--,6*o<1?l=h+(r-h)*6*o:2*o<1?l=r:3*o<2?l=h+(r-h)*(2/3-o)*6:l=h,c[d]=l*255;return{r:Math.round(c[0]),g:Math.round(c[1]),b:Math.round(c[2]),a:1}}},haveIntersection(a,e){return!(e.x>a.x+a.width||e.x+e.width<a.x||e.y>a.y+a.height||e.y+e.height<a.y)},cloneObject(a){const e={};for(const t in a)this._isPlainObject(a[t])?e[t]=this.cloneObject(a[t]):this._isArray(a[t])?e[t]=this.cloneArray(a[t]):e[t]=a[t];return e},cloneArray(a){return a.slice(0)},degToRad(a){return a*tr},radToDeg(a){return a*ir},_degToRad(a){return v.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),v.degToRad(a)},_radToDeg(a){return v.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),v.radToDeg(a)},_getRotation(a){return E.angleDeg?v.radToDeg(a):a},_capitalize(a){return a.charAt(0).toUpperCase()+a.slice(1)},throw(a){throw new Error(Xi+a)},error(a){console.error(Xi+a)},warn(a){E.showWarnings&&console.warn(rr+a)},each(a,e){for(const t in a)e(t,a[t])},_inRange(a,e,t){return e<=a&&a<t},_getProjectionToSegment(a,e,t,i,n,s){let r,o,l;const h=(a-t)*(a-t)+(e-i)*(e-i);if(h==0)r=a,o=e,l=(n-t)*(n-t)+(s-i)*(s-i);else{const c=((n-a)*(t-a)+(s-e)*(i-e))/h;c<0?(r=a,o=e,l=(a-n)*(a-n)+(e-s)*(e-s)):c>1?(r=t,o=i,l=(t-n)*(t-n)+(i-s)*(i-s)):(r=a+c*(t-a),o=e+c*(i-e),l=(r-n)*(r-n)+(o-s)*(o-s))}return[r,o,l]},_getProjectionToLine(a,e,t){const i=v.cloneObject(a);let n=Number.MAX_VALUE;return e.forEach(function(s,r){if(!t&&r===e.length-1)return;const o=e[(r+1)%e.length],l=v._getProjectionToSegment(s.x,s.y,o.x,o.y,a.x,a.y),h=l[0],c=l[1],d=l[2];d<n&&(i.x=h,i.y=c,n=d)}),i},_prepareArrayForTween(a,e,t){const i=[],n=[];if(a.length>e.length){const r=e;e=a,a=r}for(let r=0;r<a.length;r+=2)i.push({x:a[r],y:a[r+1]});for(let r=0;r<e.length;r+=2)n.push({x:e[r],y:e[r+1]});const s=[];return n.forEach(function(r){const o=v._getProjectionToLine(r,i,t);s.push(o.x),s.push(o.y)}),s},_prepareToStringify(a){let e;a.visitedByCircularReferenceRemoval=!0;for(const t in a)if(a.hasOwnProperty(t)&&a[t]&&typeof a[t]=="object"){if(e=Object.getOwnPropertyDescriptor(a,t),a[t].visitedByCircularReferenceRemoval||v._isElement(a[t]))if(e.configurable)delete a[t];else return null;else if(v._prepareToStringify(a[t])===null)if(e.configurable)delete a[t];else return null}return delete a.visitedByCircularReferenceRemoval,a},_assign(a,e){for(const t in e)a[t]=e[t];return a},_getFirstPointerId(a){return a.touches?a.changedTouches[0].identifier:a.pointerId||999},releaseCanvas(...a){E.releaseCanvasOnDestroy&&a.forEach(e=>{e.width=0,e.height=0})},drawRoundedRectPath(a,e,t,i){let n=e<0?e:0,s=t<0?t:0;e=Math.abs(e),t=Math.abs(t);let r=0,o=0,l=0,h=0;typeof i=="number"?r=o=l=h=Math.min(i,e/2,t/2):(r=Math.min(i[0]||0,e/2,t/2),o=Math.min(i[1]||0,e/2,t/2),h=Math.min(i[2]||0,e/2,t/2),l=Math.min(i[3]||0,e/2,t/2)),a.moveTo(n+r,s),a.lineTo(n+e-o,s),a.arc(n+e-o,s+o,o,Math.PI*3/2,0,!1),a.lineTo(n+e,s+t-h),a.arc(n+e-h,s+t-h,h,0,Math.PI/2,!1),a.lineTo(n+l,s+t),a.arc(n+l,s+t-l,l,Math.PI/2,Math.PI,!1),a.lineTo(n,s+r),a.arc(n+r,s+r,r,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(a,e,t,i,n){i=Math.abs(i);for(let s=0;s<t;s++){const r=e[(s-1+t)%t],o=e[s],l=e[(s+1)%t],h={x:o.x-r.x,y:o.y-r.y},c={x:l.x-o.x,y:l.y-o.y},d=Math.hypot(h.x,h.y),u=Math.hypot(c.x,c.y);let f;typeof n=="number"?f=n:f=s<n.length?n[s]:0,f=i*Math.cos(Math.PI/t)*Math.min(1,f/i*2);const y={x:h.x/d,y:h.y/d},S={x:c.x/u,y:c.y/u},C={x:o.x-y.x*f,y:o.y-y.y*f},T={x:o.x+S.x*f,y:o.y+S.y*f};s===0?a.moveTo(C.x,C.y):a.lineTo(C.x,C.y),a.arcTo(o.x,o.y,T.x,T.y,f)}}};function hr(a){const e=[],t=a.length,i=v;for(let n=0;n<t;n++){let s=a[n];i._isNumber(s)?s=Math.round(s*1e3)/1e3:i._isString(s)||(s=s+""),e.push(s)}return e}const Ui=",",cr="(",dr=")",ur="([",gr="])",pr=";",fr="()",mr="=",$i=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],yr=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],Sr=100;let Dt=null;function qi(){if(Dt!==null)return Dt;try{const e=v.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(Dt=!1,!1)}catch{return Dt=!1,!1}}class ii{constructor(e){this.canvas=e,E.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let i=this.traceArr,n=i.length,s="",r,o,l,h;for(r=0;r<n;r++)o=i[r],l=o.method,l?(h=o.args,s+=l,e?s+=fr:v._isArray(h[0])?s+=ur+h.join(Ui)+gr:(t&&(h=h.map(c=>typeof c=="number"?Math.floor(c):c)),s+=cr+h.join(Ui)+dr)):(s+=o.property,e||(s+=mr+o.val)),s+=pr;return s}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=Sr&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}_applyMiterLimit(e){const t=e.attrs.miterLimit;t!=null&&this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,i,n,s,r){this._context.arc(e,t,i,n,s,r)}arcTo(e,t,i,n,s){this._context.arcTo(e,t,i,n,s)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,i,n,s,r){this._context.bezierCurveTo(e,t,i,n,s,r)}clearRect(e,t,i,n){this._context.clearRect(e,t,i,n)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const i=arguments;if(i.length===2)return this._context.createImageData(e,t);if(i.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,i,n){return this._context.createLinearGradient(e,t,i,n)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,i,n,s,r){return this._context.createRadialGradient(e,t,i,n,s,r)}drawImage(e,t,i,n,s,r,o,l,h){const c=arguments,d=this._context;c.length===3?d.drawImage(e,t,i):c.length===5?d.drawImage(e,t,i,n,s):c.length===9&&d.drawImage(e,t,i,n,s,r,o,l,h)}ellipse(e,t,i,n,s,r,o,l){this._context.ellipse(e,t,i,n,s,r,o,l)}isPointInPath(e,t,i,n){return i?this._context.isPointInPath(i,e,t,n):this._context.isPointInPath(e,t,n)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,i,n){this._context.fillRect(e,t,i,n)}strokeRect(e,t,i,n){this._context.strokeRect(e,t,i,n)}fillText(e,t,i,n){n?this._context.fillText(e,t,i,n):this._context.fillText(e,t,i)}measureText(e){return this._context.measureText(e)}getImageData(e,t,i,n){return this._context.getImageData(e,t,i,n)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,i,n){this._context.rect(e,t,i,n)}roundRect(e,t,i,n,s){this._context.roundRect(e,t,i,n,s)}putImageData(e,t,i){this._context.putImageData(e,t,i)}quadraticCurveTo(e,t,i,n){this._context.quadraticCurveTo(e,t,i,n)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,i,n,s,r){this._context.setTransform(e,t,i,n,s,r)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,i,n){this._context.strokeText(e,t,i,n)}transform(e,t,i,n,s,r){this._context.transform(e,t,i,n,s,r)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=$i.length,i=this.setAttr,n,s;const r=function(o){let l=e[o],h;e[o]=function(){return s=hr(Array.prototype.slice.call(arguments,0)),h=l.apply(e,arguments),e._trace({method:o,args:s}),h}};for(n=0;n<t;n++)r($i[n]);e.setAttr=function(){i.apply(e,arguments);const o=arguments[0];let l=arguments[1];(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")&&(l=l/this.canvas.getPixelRatio()),e._trace({property:o,val:l})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}}yr.forEach(function(a){Object.defineProperty(ii.prototype,a,{get(){return this._context[a]},set(e){this._context[a]=e}})});class Cr extends ii{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),i=e.getFillPriority();if(t&&i==="color"){this._fillColor(e);return}const n=e.getFillPatternImage();if(n&&i==="pattern"){this._fillPattern(e);return}const s=e.getFillLinearGradientColorStops();if(s&&i==="linear-gradient"){this._fillLinearGradient(e);return}const r=e.getFillRadialGradientColorStops();if(r&&i==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):n?this._fillPattern(e):s?this._fillLinearGradient(e):r&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),i=e.getStrokeLinearGradientEndPoint(),n=e.getStrokeLinearGradientColorStops(),s=this.createLinearGradient(t.x,t.y,i.x,i.y);if(n){for(let r=0;r<n.length;r+=2)s.addColorStop(n[r],n[r+1]);this.setAttr("strokeStyle",s)}}_stroke(e){const t=e.dash(),i=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!i){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),i||this.restore()}}_applyShadow(e){var t,i,n;const s=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",r=(i=e.getShadowBlur())!==null&&i!==void 0?i:5,o=(n=e.getShadowOffset())!==null&&n!==void 0?n:{x:0,y:0},l=e.getAbsoluteScale(),h=this.canvas.getPixelRatio(),c=l.x*h,d=l.y*h;this.setAttr("shadowColor",s),this.setAttr("shadowBlur",r*Math.min(Math.abs(c),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*c),this.setAttr("shadowOffsetY",o.y*d)}}class vr extends ii{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e);const i=e.hitStrokeWidth(),n=i==="auto"?e.strokeWidth():i;this.setAttr("lineWidth",n),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}}let Ot;function Tr(){if(Ot)return Ot;const a=v.createCanvasElement(),e=a.getContext("2d");return Ot=function(){const t=E._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),v.releaseCanvas(a),Ot}class Bi{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||E.pixelRatio||Tr();this.pixelRatio=i,this._canvas=v.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(n){return v.error("Unable to get data URL. "+n.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class Oe extends Bi{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new Cr(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class Gi extends Bi{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new vr(this),this.setSize(e.width,e.height)}}const $={get isDragging(){let a=!1;return $._dragElements.forEach(e=>{e.dragStatus==="dragging"&&(a=!0)}),a},justDragged:!1,get node(){let a;return $._dragElements.forEach(e=>{a=e.node}),a},_dragElements:new Map,_drag(a){const e=[];$._dragElements.forEach((t,i)=>{const{node:n}=t,s=n.getStage();s.setPointersPositions(a),t.pointerId===void 0&&(t.pointerId=v._getFirstPointerId(a));const r=s._changedPointerPositions.find(o=>o.id===t.pointerId);if(r){if(t.dragStatus!=="dragging"){const o=n.dragDistance();if(Math.max(Math.abs(r.x-t.startPointerPos.x),Math.abs(r.y-t.startPointerPos.y))<o||(n.startDrag({evt:a}),!n.isDragging()))return}n._setDragPosition(a,t),e.push(n)}}),e.forEach(t=>{t.fire("dragmove",{type:"dragmove",target:t,evt:a},!0)})},_endDragBefore(a){const e=[];$._dragElements.forEach(t=>{const{node:i}=t,n=i.getStage();if(a&&n.setPointersPositions(a),!n._changedPointerPositions.find(o=>o.id===t.pointerId))return;(t.dragStatus==="dragging"||t.dragStatus==="stopped")&&($.justDragged=!0,E._mouseListenClick=!1,E._touchListenClick=!1,E._pointerListenClick=!1,t.dragStatus="stopped");const r=t.node.getLayer()||t.node instanceof E.Stage&&t.node;r&&e.indexOf(r)===-1&&e.push(r)}),e.forEach(t=>{t.draw()})},_endDragAfter(a){$._dragElements.forEach((e,t)=>{e.dragStatus==="stopped"&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:a},!0),e.dragStatus!=="dragging"&&$._dragElements.delete(t)})}};E.isBrowser&&(window.addEventListener("mouseup",$._endDragBefore,!0),window.addEventListener("touchend",$._endDragBefore,!0),window.addEventListener("touchcancel",$._endDragBefore,!0),window.addEventListener("mousemove",$._drag),window.addEventListener("touchmove",$._drag),window.addEventListener("mouseup",$._endDragAfter,!1),window.addEventListener("touchend",$._endDragAfter,!1),window.addEventListener("touchcancel",$._endDragAfter,!1));function Be(a){return v._isString(a)?'"'+a+'"':Object.prototype.toString.call(a)==="[object Number]"||v._isBoolean(a)?a:Object.prototype.toString.call(a)}function $n(a){return a>255?255:a<0?0:Math.round(a)}function I(){if(E.isUnminified)return function(a,e){return v._isNumber(a)||v.warn(Be(a)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),a}}function ni(a){if(E.isUnminified)return function(e,t){let i=v._isNumber(e),n=v._isArray(e)&&e.length==a;return!i&&!n&&v.warn(Be(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+a+")"),e}}function Hi(){if(E.isUnminified)return function(a,e){return v._isNumber(a)||a==="auto"||v.warn(Be(a)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),a}}function Xe(){if(E.isUnminified)return function(a,e){return v._isString(a)||v.warn(Be(a)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),a}}function qn(){if(E.isUnminified)return function(a,e){const t=v._isString(a),i=Object.prototype.toString.call(a)==="[object CanvasGradient]"||a&&a.addColorStop;return t||i||v.warn(Be(a)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),a}}function br(){if(E.isUnminified)return function(a,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&a instanceof t||(v._isArray(a)?a.forEach(function(i){v._isNumber(i)||v.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):v.warn(Be(a)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),a}}function me(){if(E.isUnminified)return function(a,e){return a===!0||a===!1||v.warn(Be(a)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),a}}function wr(a){if(E.isUnminified)return function(e,t){return e==null||v.isObject(e)||v.warn(Be(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+a),e}}const ht="get",ct="set",m={addGetterSetter(a,e,t,i,n){m.addGetter(a,e,t),m.addSetter(a,e,i,n),m.addOverloadedGetterSetter(a,e)},addGetter(a,e,t){const i=ht+v._capitalize(e);a.prototype[i]=a.prototype[i]||function(){const n=this.attrs[e];return n===void 0?t:n}},addSetter(a,e,t,i){const n=ct+v._capitalize(e);a.prototype[n]||m.overWriteSetter(a,e,t,i)},overWriteSetter(a,e,t,i){const n=ct+v._capitalize(e);a.prototype[n]=function(s){return t&&s!==void 0&&s!==null&&(s=t.call(this,s,e)),this._setAttr(e,s),i&&i.call(this),this}},addComponentsGetterSetter(a,e,t,i,n){const s=t.length,r=v._capitalize,o=ht+r(e),l=ct+r(e);a.prototype[o]=function(){const c={};for(let d=0;d<s;d++){const u=t[d];c[u]=this.getAttr(e+r(u))}return c};const h=wr(t);a.prototype[l]=function(c){const d=this.attrs[e];i&&(c=i.call(this,c,e)),h&&h.call(this,c,e);for(const u in c)c.hasOwnProperty(u)&&this._setAttr(e+r(u),c[u]);return c||t.forEach(u=>{this._setAttr(e+r(u),void 0)}),this._fireChangeEvent(e,d,c),n&&n.call(this),this},m.addOverloadedGetterSetter(a,e)},addOverloadedGetterSetter(a,e){const t=v._capitalize(e),i=ct+t,n=ht+t;a.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[n]()}},addDeprecatedGetterSetter(a,e,t,i){v.error("Adding deprecated "+e);const n=ht+v._capitalize(e),s=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";a.prototype[n]=function(){v.error(s);const r=this.attrs[e];return r===void 0?t:r},m.addSetter(a,e,i,function(){v.error(s)}),m.addOverloadedGetterSetter(a,e)},backCompat(a,e){v.each(e,function(t,i){const n=a.prototype[i],s=ht+v._capitalize(t),r=ct+v._capitalize(t);function o(){n.apply(this,arguments),v.error('"'+t+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}a.prototype[t]=o,a.prototype[s]=o,a.prototype[r]=o})},afterSetFilter(){this._filterUpToDate=!1}};function kr(a){const e=/(\w+)\(([^)]+)\)/g;let t;for(;(t=e.exec(a))!==null;){const[,i,n]=t;switch(i){case"blur":{const s=parseFloat(n.replace("px",""));return function(r){this.blurRadius(s*.5);const o=E.Filters;o&&o.Blur&&o.Blur.call(this,r)}}case"brightness":{const s=n.includes("%")?parseFloat(n)/100:parseFloat(n);return function(r){this.brightness(s);const o=E.Filters;o&&o.Brightness&&o.Brightness.call(this,r)}}case"contrast":{const s=parseFloat(n);return function(r){const o=100*(Math.sqrt(s)-1);this.contrast(o);const l=E.Filters;l&&l.Contrast&&l.Contrast.call(this,r)}}case"grayscale":return function(s){const r=E.Filters;r&&r.Grayscale&&r.Grayscale.call(this,s)};case"sepia":return function(s){const r=E.Filters;r&&r.Sepia&&r.Sepia.call(this,s)};case"invert":return function(s){const r=E.Filters;r&&r.Invert&&r.Invert.call(this,s)};default:v.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const qt="absoluteOpacity",Ki="allEventListeners",Pe="absoluteTransform",ji="absoluteScale",ze="canvas",Pr="Change",_r="children",xr="konva",Si="listening",Ir="mouseenter",Ar="mouseleave",Er="pointerenter",Mr="pointerleave",Lr="touchenter",Rr="touchleave",Zi="set",Ji="Shape",Kt=" ",Qi="stage",Le="transform",Dr="Stage",Ci="visible",Or=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Kt);let Br=1;class x{constructor(e){this._id=Br++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(e),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(e){(e===Le||e===Pe)&&this._cache.get(e)?this._cache.get(e).dirty=!0:e?this._cache.delete(e):this._cache.clear()}_getCache(e,t){let i=this._cache.get(e);return(i===void 0||(e===Le||e===Pe)&&i.dirty===!0)&&(i=t.call(this),this._cache.set(e,i)),i}_calculate(e,t,i){if(!this._attachedDepsListeners.get(e)){const n=t.map(s=>s+"Change.konva").join(Kt);this.on(n,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(ze)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Pe&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(ze)){const{scene:e,filter:t,hit:i}=this._cache.get(ze);v.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(ze)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){const t=e||{};let i={};(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)&&(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let n=Math.ceil(t.width||i.width),s=Math.ceil(t.height||i.height),r=t.pixelRatio,o=t.x===void 0?Math.floor(i.x):t.x,l=t.y===void 0?Math.floor(i.y):t.y,h=t.offset||0,c=t.drawBorder||!1,d=t.hitCanvasPixelRatio||1;if(!n||!s){v.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const u=Math.abs(Math.round(i.x)-o)>.5?1:0,f=Math.abs(Math.round(i.y)-l)>.5?1:0;n+=h*2+u,s+=h*2+f,o-=h,l-=h;const p=new Oe({pixelRatio:r,width:n,height:s}),y=new Oe({pixelRatio:r,width:0,height:0,willReadFrequently:!0}),S=new Gi({pixelRatio:d,width:n,height:s}),C=p.getContext(),T=S.getContext(),b=new Oe({width:p.width/p.pixelRatio+Math.abs(o),height:p.height/p.pixelRatio+Math.abs(l),pixelRatio:p.pixelRatio}),w=b.getContext();return S.isCache=!0,p.isCache=!0,this._cache.delete(ze),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(p.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),C.save(),T.save(),w.save(),C.translate(-o,-l),T.translate(-o,-l),w.translate(-o,-l),b.x=o,b.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(qt),this._clearSelfAndDescendantCache(ji),this.drawScene(p,this,b),this.drawHit(S,this),this._isUnderCache=!1,C.restore(),T.restore(),c&&(C.save(),C.beginPath(),C.rect(0,0,n,s),C.closePath(),C.setAttr("strokeStyle","red"),C.setAttr("lineWidth",5),C.stroke(),C.restore()),v.releaseCanvas(b._canvas),this._cache.set(ze,{scene:p,filter:y,hit:S,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(ze)}getClientRect(e){throw new Error('abstract "getClientRect" method call')}_transformedRect(e,t){const i=[{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}];let n=1/0,s=1/0,r=-1/0,o=-1/0;const l=this.getAbsoluteTransform(t);return i.forEach(function(h){const c=l.point(h);n===void 0&&(n=r=c.x,s=o=c.y),n=Math.min(n,c.x),s=Math.min(s,c.y),r=Math.max(r,c.x),o=Math.max(o,c.y)}),{x:n,y:s,width:r-n,height:o-s}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);const t=this._getCanvasCache();e.translate(t.x,t.y);const i=this._getCachedSceneCanvas(),n=i.pixelRatio;e.drawImage(i._canvas,0,0,i.width/n,i.height/n),e.restore()}_drawCachedHitCanvas(e){const t=this._getCanvasCache(),i=t.hit;e.save(),e.translate(t.x,t.y),e.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),i=t.scene,n=t.filter,s=n.getContext(),r,o,l,h;if(!e||e.length===0)return i;if(this._filterUpToDate)return n;let c=!0;for(let u=0;u<e.length;u++)if(typeof e[u]=="string"&&qi(),typeof e[u]!="string"||!qi()){c=!1;break}const d=i.pixelRatio;if(n.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),c){const u=e.join(" ");return s.save(),s.setAttr("filter",u),s.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),s.restore(),this._filterUpToDate=!0,n}try{for(r=e.length,s.clear(),s.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),o=s.getImageData(0,0,n.getWidth(),n.getHeight()),l=0;l<r;l++)h=e[l],typeof h=="string"&&(h=kr(h)),h.call(this,o),s.putImageData(o,0,0)}catch(u){v.error("Unable to apply filter. "+u.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,n}on(e,t){if(this._cache&&this._cache.delete(Ki),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Kt);for(let n=0;n<i.length;n++){const r=i[n].split("."),o=r[0],l=r[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:t})}return this}off(e,t){let i=(e||"").split(Kt),n=i.length,s,r,o,l,h,c;if(this._cache&&this._cache.delete(Ki),!e)for(r in this.eventListeners)this._off(r);for(s=0;s<n;s++)if(o=i[s],l=o.split("."),h=l[0],c=l[1],h)this.eventListeners[h]&&this._off(h,c,t);else for(r in this.eventListeners)this._off(r,c,t);return this}dispatchEvent(e){const t={target:this,type:e.type,evt:e};return this.fire(e.type,t),this}addEventListener(e,t){return this.on(e,function(i){t.call(this,i.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,i){const n=this;this.on(e,function(s){const r=s.target.findAncestors(t,!0,n);for(let o=0;o<r.length;o++)s=v.cloneObject(s),s.currentTarget=r[o],i.call(r[o],s)})}remove(){return this.isDragging()&&this.stopDrag(),$._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Pe),this._clearSelfAndDescendantCache(qt),this._clearSelfAndDescendantCache(ji),this._clearSelfAndDescendantCache(Qi),this._clearSelfAndDescendantCache(Ci),this._clearSelfAndDescendantCache(Si)}_remove(){this._clearCaches();const e=this.getParent();e&&e.children&&(e.children.splice(this.index,1),e._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(e){const t="get"+v._capitalize(e);return v._isFunction(this[t])?this[t]():this.attrs[e]}getAncestors(){let e=this.getParent(),t=[];for(;e;)t.push(e),e=e.getParent();return t}getAttrs(){return this.attrs||{}}setAttrs(e){return this._batchTransformChanges(()=>{let t,i;if(!e)return this;for(t in e)t!==_r&&(i=Zi+v._capitalize(t),v._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(Si,this._isListening)}_isListening(e){if(!this.listening())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isListening(e):!0}isVisible(){return this._getCache(Ci,this._isVisible)}_isVisible(e){if(!this.visible())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isVisible(e):!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);const i=this.getLayer();let n=!1;$._dragElements.forEach(r=>{r.dragStatus==="dragging"&&(r.node.nodeType==="Stage"||r.node.getLayer()===i)&&(n=!0)});const s=!t&&!E.hitOnDragEnabled&&(n||E.isTransforming());return this.isListening()&&this.isVisible()&&!s}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let e=this.getDepth(),t=this,i=0,n,s,r,o;function l(c){for(n=[],s=c.length,r=0;r<s;r++)o=c[r],i++,o.nodeType!==Ji&&(n=n.concat(o.getChildren().slice())),o._id===t._id&&(r=s);n.length>0&&n[0].getDepth()<=e&&l(n)}const h=this.getStage();return t.nodeType!==Dr&&h&&l(h.getChildren()),i}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}_batchTransformChanges(e){this._batchingTransformChange=!0,e(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(Le),this._clearSelfAndDescendantCache(Pe)),this._needClearTransformCache=!1}setPosition(e){return this._batchTransformChanges(()=>{this.x(e.x),this.y(e.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const e=this.getStage();if(!e)return null;const t=e.getPointerPosition();if(!t)return null;const i=this.getAbsoluteTransform().copy();return i.invert(),i.point(t)}getAbsolutePosition(e){let t=!1,i=this.parent;for(;i;){if(i.isCached()){t=!0;break}i=i.parent}t&&!e&&(e=!0);const n=this.getAbsoluteTransform(e).getMatrix(),s=new ue,r=this.offset();return s.m=n.slice(),s.translate(r.x,r.y),s.getTranslation()}setAbsolutePosition(e){const{x:t,y:i,...n}=this._clearTransform();this.attrs.x=t,this.attrs.y=i,this._clearCache(Le);const s=this._getAbsoluteTransform().copy();return s.invert(),s.translate(e.x,e.y),e={x:this.attrs.x+s.getTranslation().x,y:this.attrs.y+s.getTranslation().y},this._setTransform(n),this.setPosition({x:e.x,y:e.y}),this._clearCache(Le),this._clearSelfAndDescendantCache(Pe),this}_setTransform(e){let t;for(t in e)this.attrs[t]=e[t]}_clearTransform(){const e={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,e}move(e){let t=e.x,i=e.y,n=this.x(),s=this.y();return t!==void 0&&(n+=t),i!==void 0&&(s+=i),this.setPosition({x:n,y:s}),this}_eachAncestorReverse(e,t){let i=[],n=this.getParent(),s,r;if(!(t&&t._id===this._id)){for(i.unshift(this);n&&(!t||n._id!==t._id);)i.unshift(n),n=n.parent;for(s=i.length,r=0;r<s;r++)e(i[r])}}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return v.warn("Node has no parent. moveToTop function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return v.warn("Node has no parent. moveUp function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return v.warn("Node has no parent. moveDown function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return v.warn("Node has no parent. moveToBottom function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(e){if(!this.parent)return v.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&v.warn("Unexpected value "+e+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const t=this.index;return this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(qt,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let e=this.opacity();const t=this.getParent();return t&&!t._isUnderCache&&(e*=t.getAbsoluteOpacity()),e}moveTo(e){return this.getParent()!==e&&(this._remove(),e.add(this)),this}toObject(){let e=this.getAttrs(),t,i,n,s,r;const o={attrs:{},className:this.getClassName()};for(t in e)i=e[t],r=v.isObject(i)&&!v._isPlainObject(i)&&!v._isArray(i),!r&&(n=typeof this[t]=="function"&&this[t],delete e[t],s=n?n.call(this):null,e[t]=i,s!==i&&(o.attrs[t]=i));return v._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,i){const n=[];t&&this._isMatch(e)&&n.push(this);let s=this.parent;for(;s;){if(s===i)return n;s._isMatch(e)&&n.push(s),s=s.parent}return n}isAncestorOf(e){return!1}findAncestor(e,t,i){return this.findAncestors(e,t,i)[0]}_isMatch(e){if(!e)return!1;if(typeof e=="function")return e(this);let t=e.replace(/ /g,"").split(","),i=t.length,n,s;for(n=0;n<i;n++)if(s=t[n],v.isValidSelector(s)||(v.warn('Selector "'+s+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),v.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),v.warn("Konva is awesome, right?")),s.charAt(0)==="#"){if(this.id()===s.slice(1))return!0}else if(s.charAt(0)==="."){if(this.hasName(s.slice(1)))return!0}else if(this.className===s||this.nodeType===s)return!0;return!1}getLayer(){const e=this.getParent();return e?e.getLayer():null}getStage(){return this._getCache(Qi,this._getStage)}_getStage(){const e=this.getParent();return e?e.getStage():null}fire(e,t={},i){return t.target=t.target||this,i?this._fireAndBubble(e,t):this._fire(e,t),this}getAbsoluteTransform(e){return e?this._getAbsoluteTransform(e):this._getCache(Pe,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new ue,this._eachAncestorReverse(function(i){const n=i.transformsEnabled();n==="all"?t.multiply(i.getTransform()):n==="position"&&t.translate(i.x()-i.offsetX(),i.y()-i.offsetY())},e),t;{t=this._cache.get(Pe)||new ue,this.parent?this.parent.getAbsoluteTransform().copyInto(t):t.reset();const i=this.transformsEnabled();if(i==="all")t.multiply(this.getTransform());else if(i==="position"){const n=this.attrs.x||0,s=this.attrs.y||0,r=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(n-r,s-o)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;for(;t;)t._isUnderCache&&(e=t),t=t.getParent();const n=this.getAbsoluteTransform(e).decompose();return{x:n.scaleX,y:n.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(Le,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get(Le)||new ue;i.reset();const n=this.x(),s=this.y(),r=E.getAngle(this.rotation()),o=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,l=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,h=this.attrs.skewX||0,c=this.attrs.skewY||0,d=this.attrs.offsetX||0,u=this.attrs.offsetY||0;return(n!==0||s!==0)&&i.translate(n,s),r!==0&&i.rotate(r),(h!==0||c!==0)&&i.skew(h,c),(o!==1||l!==1)&&i.scale(o,l),(d!==0||u!==0)&&i.translate(-1*d,-1*u),i.dirty=!1,i}clone(e){let t=v.cloneObject(this.attrs),i,n,s,r,o;for(i in e)t[i]=e[i];const l=new this.constructor(t);for(i in this.eventListeners)for(n=this.eventListeners[i],s=n.length,r=0;r<s;r++)o=n[r],o.name.indexOf(xr)<0&&(l.eventListeners[i]||(l.eventListeners[i]=[]),l.eventListeners[i].push(o));return l}_toKonvaCanvas(e){e=e||{};const t=this.getClientRect(),i=this.getStage(),n=e.x!==void 0?e.x:Math.floor(t.x),s=e.y!==void 0?e.y:Math.floor(t.y),r=e.pixelRatio||1,o=new Oe({width:e.width||Math.ceil(t.width)||(i?i.width():0),height:e.height||Math.ceil(t.height)||(i?i.height():0),pixelRatio:r}),l=o.getContext(),h=new Oe({width:o.width/o.pixelRatio+Math.abs(n),height:o.height/o.pixelRatio+Math.abs(s),pixelRatio:o.pixelRatio});return e.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(n||s)&&l.translate(-1*n,-1*s),this.drawScene(o,void 0,h),l.restore(),o}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};const t=e.mimeType||null,i=e.quality||null,n=this._toKonvaCanvas(e).toDataURL(t,i);return e.callback&&e.callback(n),n}toImage(e){return new Promise((t,i)=>{try{const n=e==null?void 0:e.callback;n&&delete e.callback,v._urlToImage(this.toDataURL(e),function(s){t(s),n==null||n(s)})}catch(n){i(n)}})}toBlob(e){return new Promise((t,i)=>{try{const n=e==null?void 0:e.callback;n&&delete e.callback,this.toCanvas(e).toBlob(s=>{t(s),n==null||n(s)},e==null?void 0:e.mimeType,e==null?void 0:e.quality)}catch(n){i(n)}})}setSize(e){return this.width(e.width),this.height(e.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():E.dragDistance}_off(e,t,i){let n=this.eventListeners[e],s,r,o;for(s=0;s<n.length;s++)if(r=n[s].name,o=n[s].handler,(r!=="konva"||t==="konva")&&(!t||r===t)&&(!i||i===o)){if(n.splice(s,1),n.length===0){delete this.eventListeners[e];break}s--}}_fireChangeEvent(e,t,i){this._fire(e+Pr,{oldVal:t,newVal:i})}addName(e){if(!this.hasName(e)){const t=this.name(),i=t?t+" "+e:e;this.name(i)}return this}hasName(e){if(!e)return!1;const t=this.name();return t?(t||"").split(/\s/g).indexOf(e)!==-1:!1}removeName(e){const t=(this.name()||"").split(/\s/g),i=t.indexOf(e);return i!==-1&&(t.splice(i,1),this.name(t.join(" "))),this}setAttr(e,t){const i=this[Zi+v._capitalize(e)];return v._isFunction(i)?i.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(E.autoDrawEnabled){const e=this.getLayer()||this.getStage();e==null||e.batchDraw()}}_setAttr(e,t){const i=this.attrs[e];i===t&&!v.isObject(t)||(t==null?delete this.attrs[e]:this.attrs[e]=t,this._shouldFireChangeEvents&&this._fireChangeEvent(e,i,t),this._requestDraw())}_setComponentAttr(e,t,i){let n;i!==void 0&&(n=this.attrs[e],n||(this.attrs[e]=this.getAttr(e)),this.attrs[e][t]=i,this._fireChangeEvent(e,n,i))}_fireAndBubble(e,t,i){t&&this.nodeType===Ji&&(t.target=this);const n=[Ir,Ar,Er,Mr,Lr,Rr];if(!(n.indexOf(e)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(e,t);const r=n.indexOf(e)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!r&&(i&&i.parent?this._fireAndBubble.call(this.parent,e,t,i):this._fireAndBubble.call(this.parent,e,t))}}_getProtoListeners(e){var t,i;const{nodeType:n}=this,s=x.protoListenerMap.get(n)||{};let r=s==null?void 0:s[e];if(r===void 0){r=[];let o=Object.getPrototypeOf(this);for(;o;){const l=(i=(t=o.eventListeners)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:[];r.push(...l),o=Object.getPrototypeOf(o)}s[e]=r,x.protoListenerMap.set(n,s)}return r}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;const i=this._getProtoListeners(e);if(i)for(let s=0;s<i.length;s++)i[s].handler.call(this,t);const n=this.eventListeners[e];if(n)for(let s=0;s<n.length;s++)n[s].handler.call(this,t)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){const t=e?e.pointerId:void 0,i=this.getStage(),n=this.getAbsolutePosition();if(!i)return;const s=i._getPointerById(t)||i._changedPointerPositions[0]||n;$._dragElements.set(this._id,{node:this,startPointerPos:s,offset:{x:s.x-n.x,y:s.y-n.y},dragStatus:"ready",pointerId:t})}startDrag(e,t=!0){$._dragElements.has(this._id)||this._createDragElement(e);const i=$._dragElements.get(this._id);i.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:e&&e.evt},t)}_setDragPosition(e,t){const i=this.getStage()._getPointerById(t.pointerId);if(!i)return;let n={x:i.x-t.offset.x,y:i.y-t.offset.y};const s=this.dragBoundFunc();if(s!==void 0){const r=s.call(this,n,e);r?n=r:v.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==n.x||this._lastPos.y!==n.y)&&(this.setAbsolutePosition(n),this._requestDraw()),this._lastPos=n}stopDrag(e){const t=$._dragElements.get(this._id);t&&(t.dragStatus="stopped"),$._endDragBefore(e),$._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=$._dragElements.get(this._id);return e?e.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(e){if(!(!(e.evt.button!==void 0)||E.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let n=!1;$._dragElements.forEach(s=>{this.isAncestorOf(s.node)&&(n=!0)}),n||this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=$._dragElements.get(this._id),i=t&&t.dragStatus==="dragging",n=t&&t.dragStatus==="ready";i?this.stopDrag():n&&$._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(e={x:0,y:0}){const t=this.getStage();if(!t)return!1;const i={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return v.haveIntersection(i,this.getClientRect())}static create(e,t){return v._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let i=x.prototype.getClassName.call(e),n=e.children,s,r,o;t&&(e.attrs.container=t),E[i]||(v.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=E[i];if(s=new l(e.attrs),n)for(r=n.length,o=0;o<r;o++)s.add(x._createNode(n[o]));return s}}x.protoListenerMap=new Map;x.prototype.nodeType="Node";x.prototype._attrsAffectingSize=[];x.prototype.eventListeners={};x.prototype.on.call(x.prototype,Or,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(Le),this._clearSelfAndDescendantCache(Pe)});x.prototype.on.call(x.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(Ci)});x.prototype.on.call(x.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(Si)});x.prototype.on.call(x.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(qt)});const J=m.addGetterSetter;J(x,"zIndex");J(x,"absolutePosition");J(x,"position");J(x,"x",0,I());J(x,"y",0,I());J(x,"globalCompositeOperation","source-over",Xe());J(x,"opacity",1,I());J(x,"name","",Xe());J(x,"id","",Xe());J(x,"rotation",0,I());m.addComponentsGetterSetter(x,"scale",["x","y"]);J(x,"scaleX",1,I());J(x,"scaleY",1,I());m.addComponentsGetterSetter(x,"skew",["x","y"]);J(x,"skewX",0,I());J(x,"skewY",0,I());m.addComponentsGetterSetter(x,"offset",["x","y"]);J(x,"offsetX",0,I());J(x,"offsetY",0,I());J(x,"dragDistance",void 0,I());J(x,"width",0,I());J(x,"height",0,I());J(x,"listening",!0,me());J(x,"preventDefault",!0,me());J(x,"filters",void 0,function(a){return this._filterUpToDate=!1,a});J(x,"visible",!0,me());J(x,"transformsEnabled","all",Xe());J(x,"size");J(x,"dragBoundFunc");J(x,"draggable",!1,me());m.backCompat(x,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class ge extends x{constructor(){super(...arguments),this.children=[]}getChildren(e){const t=this.children||[];return e?t.filter(e):t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let i=0;i<e.length;i++)this.add(e[i]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const i=[];return this._descendants(n=>{const s=n._isMatch(e);return s&&i.push(n),!!(s&&t)}),i}_descendants(e){let t=!1;const i=this.getChildren();for(const n of i){if(t=e(n),t)return!0;if(n.hasChildren()&&(t=n._descendants(e),t))return!0}return!1}toObject(){const e=x.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=x.prototype.clone.call(this,e);return this.getChildren().forEach(function(i){t.add(i.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(i=>{i.isVisible()&&i.intersects(e)&&t.push(i)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(i){i._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,i){t.index=i}),this._requestDraw()}drawScene(e,t,i){const n=this.getLayer(),s=e||n&&n.getCanvas(),r=s&&s.getContext(),o=this._getCanvasCache(),l=o&&o.scene,h=s&&s.isCache;if(!this.isVisible()&&!h)return this;if(l){r.save();const c=this.getAbsoluteTransform(t).getMatrix();r.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedSceneCanvas(r),r.restore()}else this._drawChildren("drawScene",s,t,i);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const i=this.getLayer(),n=e||i&&i.hitCanvas,s=n&&n.getContext(),r=this._getCanvasCache();if(r&&r.hit){s.save();const l=this.getAbsoluteTransform(t).getMatrix();s.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(s),s.restore()}else this._drawChildren("drawHit",n,t);return this}_drawChildren(e,t,i,n){var s;const r=t&&t.getContext(),o=this.clipWidth(),l=this.clipHeight(),h=this.clipFunc(),c=typeof o=="number"&&typeof l=="number"||h,d=i===this;if(c){r.save();const f=this.getAbsoluteTransform(i);let p=f.getMatrix();r.transform(p[0],p[1],p[2],p[3],p[4],p[5]),r.beginPath();let y;if(h)y=h.call(this,r,this);else{const S=this.clipX(),C=this.clipY();r.rect(S||0,C||0,o,l)}r.clip.apply(r,y),p=f.copy().invert().getMatrix(),r.transform(p[0],p[1],p[2],p[3],p[4],p[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";u&&(r.save(),r._applyGlobalCompositeOperation(this)),(s=this.children)===null||s===void 0||s.forEach(function(f){f[e](t,i,n)}),u&&r.restore(),c&&r.restore()}getClientRect(e={}){var t;const i=e.skipTransform,n=e.relativeTo;let s,r,o,l,h={x:1/0,y:1/0,width:0,height:0};const c=this;(t=this.children)===null||t===void 0||t.forEach(function(f){if(!f.visible())return;const p=f.getClientRect({relativeTo:c,skipShadow:e.skipShadow,skipStroke:e.skipStroke});p.width===0&&p.height===0||(s===void 0?(s=p.x,r=p.y,o=p.x+p.width,l=p.y+p.height):(s=Math.min(s,p.x),r=Math.min(r,p.y),o=Math.max(o,p.x+p.width),l=Math.max(l,p.y+p.height)))});const d=this.find("Shape");let u=!1;for(let f=0;f<d.length;f++)if(d[f]._isVisible(this)){u=!0;break}return u&&s!==void 0?h={x:s,y:r,width:o-s,height:l-r}:h={x:0,y:0,width:0,height:0},i?h:this._transformedRect(h,n)}}m.addComponentsGetterSetter(ge,"clip",["x","y","width","height"]);m.addGetterSetter(ge,"clipX",void 0,I());m.addGetterSetter(ge,"clipY",void 0,I());m.addGetterSetter(ge,"clipWidth",void 0,I());m.addGetterSetter(ge,"clipHeight",void 0,I());m.addGetterSetter(ge,"clipFunc");const At=new Map,Kn=E._global.PointerEvent!==void 0;function ai(a){return At.get(a)}function Ni(a){return{evt:a,pointerId:a.pointerId}}function jn(a,e){return At.get(a)===e}function Zn(a,e){Tt(a),e.getStage()&&(At.set(a,e),Kn&&e._fire("gotpointercapture",Ni(new PointerEvent("gotpointercapture"))))}function Tt(a,e){const t=At.get(a);if(!t)return;const i=t.getStage();i&&i.content,At.delete(a),Kn&&t._fire("lostpointercapture",Ni(new PointerEvent("lostpointercapture")))}const Gr="Stage",Hr="string",en="px",Nr="mouseout",Jn="mouseleave",Qn="mouseover",es="mouseenter",ts="mousemove",is="mousedown",ns="mouseup",pt="pointermove",ft="pointerdown",nt="pointerup",mt="pointercancel",zr="lostpointercapture",Bt="pointerout",yt="pointerleave",Gt="pointerover",Ht="pointerenter",vi="contextmenu",ss="touchstart",rs="touchend",as="touchmove",os="touchcancel",Ti="wheel",Fr=5,Vr=[[es,"_pointerenter"],[is,"_pointerdown"],[ts,"_pointermove"],[ns,"_pointerup"],[Jn,"_pointerleave"],[ss,"_pointerdown"],[as,"_pointermove"],[rs,"_pointerup"],[os,"_pointercancel"],[Qn,"_pointerover"],[Ti,"_wheel"],[vi,"_contextmenu"],[ft,"_pointerdown"],[pt,"_pointermove"],[nt,"_pointerup"],[mt,"_pointercancel"],[yt,"_pointerleave"],[zr,"_lostpointercapture"]],oi={mouse:{[Bt]:Nr,[yt]:Jn,[Gt]:Qn,[Ht]:es,[pt]:ts,[ft]:is,[nt]:ns,[mt]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Bt]:"touchout",[yt]:"touchleave",[Gt]:"touchover",[Ht]:"touchenter",[pt]:as,[ft]:ss,[nt]:rs,[mt]:os,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Bt]:Bt,[yt]:yt,[Gt]:Gt,[Ht]:Ht,[pt]:pt,[ft]:ft,[nt]:nt,[mt]:mt,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},St=a=>a.indexOf("pointer")>=0?"pointer":a.indexOf("touch")>=0?"touch":"mouse",je=a=>{const e=St(a);if(e==="pointer")return E.pointerEventsEnabled&&oi.pointer;if(e==="touch")return oi.touch;if(e==="mouse")return oi.mouse};function tn(a={}){return(a.clipFunc||a.clipWidth||a.clipHeight)&&v.warn("Stage does not support clipping. Please use clip for Layers or Groups."),a}const Wr="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",bt=[];class si extends ge{constructor(e){super(tn(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),bt.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{tn(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",i=e.getType()==="FastLayer";t||i||v.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const e=this.visible()?"":"none";this.content.style.display=e}setContainer(e){if(typeof e===Hr){let t;if(e.charAt(0)==="."){const i=e.slice(1);e=document.getElementsByClassName(i)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),ge.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&v._isInDocument(e)&&this.container().removeChild(e);const t=bt.indexOf(this);return t>-1&&bt.splice(t,1),v.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const e=this._pointerPositions[0]||this._changedPointerPositions[0];return e?{x:e.x,y:e.y}:(v.warn(Wr),null)}_getPointerById(e){return this._pointerPositions.find(t=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();const t=new Oe({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),i=t.getContext()._context,n=this.children;return(e.x||e.y)&&i.translate(-1*e.x,-1*e.y),n.forEach(function(s){if(!s.isVisible())return;const r=s._toKonvaCanvas(e);i.drawImage(r._canvas,e.x,e.y,r.getWidth()/r.getPixelRatio(),r.getHeight()/r.getPixelRatio())}),t}getIntersection(e){if(!e)return null;const t=this.children,i=t.length,n=i-1;for(let s=n;s>=0;s--){const r=t[s].getIntersection(e);if(r)return r}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+en,this.content.style.height=t+en),this.bufferCanvas.setSize(e,t),this.bufferHitCanvas.setSize(e,t),this.children.forEach(i=>{i.setSize({width:e,height:t}),i.draw()})}add(e,...t){if(arguments.length>1){for(let n=0;n<arguments.length;n++)this.add(arguments[n]);return this}super.add(e);const i=this.children.length;return i>Fr&&v.warn("The stage has "+i+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),E.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return jn(e,this)}setPointerCapture(e){Zn(e,this)}releaseCapture(e){Tt(e)}getLayers(){return this.children}_bindContentEvents(){E.isBrowser&&Vr.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=je(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=je(e.type);t&&this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];return t&&!t.getStage()&&(t=null),t}_pointerleave(e){const t=je(e.type),i=St(e.type);if(!t)return;this.setPointersPositions(e);const n=this._getTargetShape(i),s=!(E.isDragging()||E.isTransforming())||E.hitOnDragEnabled;n&&s?(n._fireAndBubble(t.pointerout,{evt:e}),n._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[i+"targetShape"]=null):s&&(this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){const t=je(e.type),i=St(e.type);if(!t)return;this.setPointersPositions(e);let n=!1;this._changedPointerPositions.forEach(s=>{const r=this.getIntersection(s);if($.justDragged=!1,E["_"+i+"ListenClick"]=!0,!r||!r.isListening()){this[i+"ClickStartShape"]=void 0;return}E.capturePointerEventsEnabled&&r.setPointerCapture(s.id),this[i+"ClickStartShape"]=r,r._fireAndBubble(t.pointerdown,{evt:e,pointerId:s.id}),n=!0;const o=e.type.indexOf("touch")>=0;r.preventDefault()&&e.cancelable&&o&&e.preventDefault()}),n||this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){const t=je(e.type),i=St(e.type);if(!t)return;const n=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(E.isDragging()&&$.node.preventDefault()&&e.cancelable&&n&&e.preventDefault(),this.setPointersPositions(e),!(!(E.isDragging()||E.isTransforming())||E.hitOnDragEnabled))return;const r={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(h=>{const c=ai(h.id)||this.getIntersection(h),d=h.id,u={evt:e,pointerId:d},f=l!==c;if(f&&l&&(l._fireAndBubble(t.pointerout,{...u},c),l._fireAndBubble(t.pointerleave,{...u},c)),c){if(r[c._id])return;r[c._id]=!0}c&&c.isListening()?(o=!0,f&&(c._fireAndBubble(t.pointerover,{...u},l),c._fireAndBubble(t.pointerenter,{...u},l),this[i+"targetShape"]=c),c._fireAndBubble(t.pointermove,{...u})):l&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:d}),this[i+"targetShape"]=null)}),o||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=je(e.type),i=St(e.type);if(!t)return;this.setPointersPositions(e);const n=this[i+"ClickStartShape"],s=this[i+"ClickEndShape"],r={};let o=!1;this._changedPointerPositions.forEach(l=>{const h=ai(l.id)||this.getIntersection(l);if(h){if(h.releaseCapture(l.id),r[h._id])return;r[h._id]=!0}const c=l.id,d={evt:e,pointerId:c};let u=!1;E["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):$.justDragged||(E["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){E["_"+i+"InDblClickWindow"]=!1},E.dblClickWindow),h&&h.isListening()?(o=!0,this[i+"ClickEndShape"]=h,h._fireAndBubble(t.pointerup,{...d}),E["_"+i+"ListenClick"]&&n&&n===h&&(h._fireAndBubble(t.pointerclick,{...d}),u&&s&&s===h&&h._fireAndBubble(t.pointerdblclick,{...d}))):(this[i+"ClickEndShape"]=null,o||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),E["_"+i+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:c}),u&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:c}))}),o||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),E["_"+i+"ListenClick"]=!1,e.cancelable&&i!=="touch"&&i!=="pointer"&&e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(vi,{evt:e}):this._fire(vi,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Ti,{evt:e}):this._fire(Ti,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=ai(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(nt,Ni(e)),Tt(e.pointerId)}_lostpointercapture(e){Tt(e.pointerId)}setPointersPositions(e){const t=this._getContentPosition();let i=null,n=null;e=e||window.event,e.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,s=>{this._pointerPositions.push({id:s.identifier,x:(s.clientX-t.left)/t.scaleX,y:(s.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,s=>{this._changedPointerPositions.push({id:s.identifier,x:(s.clientX-t.left)/t.scaleX,y:(s.clientY-t.top)/t.scaleY})})):(i=(e.clientX-t.left)/t.scaleX,n=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:i,y:n},this._pointerPositions=[{x:i,y:n,id:v._getFirstPointerId(e)}],this._changedPointerPositions=[{x:i,y:n,id:v._getFirstPointerId(e)}])}_setPointerPosition(e){v.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new Oe({width:this.width(),height:this.height()}),this.bufferHitCanvas=new Gi({pixelRatio:1,width:this.width(),height:this.height()}),!E.isBrowser)return;const e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),this._resizeDOM()}cache(){return v.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}}si.prototype.nodeType=Gr;ne(si);m.addGetterSetter(si,"container");E.isBrowser&&document.addEventListener("visibilitychange",()=>{bt.forEach(a=>{a.batchDraw()})});const ls="hasShadow",hs="shadowRGBA",cs="patternImage",ds="linearGradient",us="radialGradient";let Nt;function li(){return Nt||(Nt=v.createCanvasElement().getContext("2d"),Nt)}const wt={};function Yr(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function Xr(a){a.stroke()}function Ur(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function $r(a){a.stroke()}function qr(){this._clearCache(ls)}function Kr(){this._clearCache(hs)}function jr(){this._clearCache(cs)}function Zr(){this._clearCache(ds)}function Jr(){this._clearCache(us)}class P extends x{constructor(e){super(e);let t,i=0;for(;t=v.getHitColor(),!(t&&!(t in wt));)if(i++,i>=1e4){v.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=v.getRandomColor();break}this.colorKey=t,wt[t]=this}getContext(){return v.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return v.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(ls,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(cs,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=li().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new ue;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(E.getAngle(this.fillPatternRotation())),i.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),i.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const n=i.getMatrix(),s=typeof DOMMatrix>"u"?{a:n[0],b:n[1],c:n[2],d:n[3],e:n[4],f:n[5]}:new DOMMatrix(n);t.setTransform(s)}return t}}_getLinearGradient(){return this._getCache(ds,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=li(),i=this.fillLinearGradientStartPoint(),n=this.fillLinearGradientEndPoint(),s=t.createLinearGradient(i.x,i.y,n.x,n.y);for(let r=0;r<e.length;r+=2)s.addColorStop(e[r],e[r+1]);return s}}_getRadialGradient(){return this._getCache(us,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=li(),i=this.fillRadialGradientStartPoint(),n=this.fillRadialGradientEndPoint(),s=t.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),n.x,n.y,this.fillRadialGradientEndRadius());for(let r=0;r<e.length;r+=2)s.addColorStop(e[r],e[r+1]);return s}}getShadowRGBA(){return this._getCache(hs,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=v.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const e=this.hitStrokeWidth();return e==="auto"?this.hasStroke():this.strokeEnabled()&&!!e}intersects(e){const t=this.getStage();if(!t)return!1;const i=t.bufferHitCanvas;return i.getContext().clear(),this.drawHit(i,void 0,!0),i.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return x.prototype.destroy.call(this),delete wt[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0?t:!0))return!1;const n=e||this.hasFill(),s=this.hasStroke(),r=this.getAbsoluteOpacity()!==1;if(n&&s&&r)return!0;const o=this.hasShadow(),l=this.shadowForStrokeEnabled();return!!(n&&s&&o&&l)}setStrokeHitEnabled(e){v.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,i=this.getParent();for(;i;){if(i.isCached()){t=!0;break}i=i.getParent()}const n=e.skipTransform,s=e.relativeTo||t&&this.getStage()||void 0,r=this.getSelfRect(),l=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,h=r.width+l,c=r.height+l,d=!e.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,f=d?this.shadowOffsetY():0,p=h+Math.abs(u),y=c+Math.abs(f),S=d&&this.shadowBlur()||0,C=p+S*2,T=y+S*2,b={width:C,height:T,x:-(l/2+S)+Math.min(u,0)+r.x,y:-(l/2+S)+Math.min(f,0)+r.y};return n?b:this._transformedRect(b,s)}drawScene(e,t,i){const n=this.getLayer(),s=e||n.getCanvas(),r=s.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),h=this.hasShadow();let c;const d=t===this;if(!this.isVisible()&&!d)return this;if(o){r.save();const u=this.getAbsoluteTransform(t).getMatrix();return r.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(r),r.restore(),this}if(!l)return this;if(r.save(),this._useBufferCanvas()){c=this.getStage();const u=i||c.bufferCanvas,f=u.getContext();i?(f.save(),f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,u.width,u.height),f.restore()):f.clear(),f.save(),f._applyLineJoin(this),f._applyMiterLimit(this);const p=this.getAbsoluteTransform(t).getMatrix();f.transform(p[0],p[1],p[2],p[3],p[4],p[5]),l.call(this,f,this),f.restore();const y=u.pixelRatio;h&&r._applyShadow(this),d||(r._applyOpacity(this),r._applyGlobalCompositeOperation(this)),r.drawImage(u._canvas,u.x||0,u.y||0,u.width/y,u.height/y)}else{if(r._applyLineJoin(this),r._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(t).getMatrix();r.transform(u[0],u[1],u[2],u[3],u[4],u[5]),r._applyOpacity(this),r._applyGlobalCompositeOperation(this)}h&&r._applyShadow(this),l.call(this,r,this)}return r.restore(),this}drawHit(e,t,i=!1){if(!this.shouldDrawHit(t,i))return this;const n=this.getLayer(),s=e||n.hitCanvas,r=s&&s.getContext(),o=this.hitFunc()||this.sceneFunc(),l=this._getCanvasCache(),h=l&&l.hit;if(this.colorKey||v.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),h){r.save();const d=this.getAbsoluteTransform(t).getMatrix();return r.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(r),r.restore(),this}if(!o)return this;if(r.save(),r._applyLineJoin(this),r._applyMiterLimit(this),!(this===t)){const d=this.getAbsoluteTransform(t).getMatrix();r.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,r,this),r.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),i=this._getCachedSceneCanvas(),n=t.hit,s=n.getContext(),r=n.getWidth(),o=n.getHeight();s.clear(),s.drawImage(i._canvas,0,0,r,o);try{const l=s.getImageData(0,0,r,o),h=l.data,c=h.length,d=v._hexToRgb(this.colorKey);for(let u=0;u<c;u+=4)h[u+3]>e?(h[u]=d.r,h[u+1]=d.g,h[u+2]=d.b,h[u+3]=255):h[u+3]=0;s.putImageData(l,0,0)}catch(l){v.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(e){return jn(e,this)}setPointerCapture(e){Zn(e,this)}releaseCapture(e){Tt(e)}}P.prototype._fillFunc=Yr;P.prototype._strokeFunc=Xr;P.prototype._fillFuncHit=Ur;P.prototype._strokeFuncHit=$r;P.prototype._centroid=!1;P.prototype.nodeType="Shape";ne(P);P.prototype.eventListeners={};P.prototype.on.call(P.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",qr);P.prototype.on.call(P.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Kr);P.prototype.on.call(P.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",jr);P.prototype.on.call(P.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Zr);P.prototype.on.call(P.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Jr);m.addGetterSetter(P,"stroke",void 0,qn());m.addGetterSetter(P,"strokeWidth",2,I());m.addGetterSetter(P,"fillAfterStrokeEnabled",!1);m.addGetterSetter(P,"hitStrokeWidth","auto",Hi());m.addGetterSetter(P,"strokeHitEnabled",!0,me());m.addGetterSetter(P,"perfectDrawEnabled",!0,me());m.addGetterSetter(P,"shadowForStrokeEnabled",!0,me());m.addGetterSetter(P,"lineJoin");m.addGetterSetter(P,"lineCap");m.addGetterSetter(P,"miterLimit");m.addGetterSetter(P,"sceneFunc");m.addGetterSetter(P,"hitFunc");m.addGetterSetter(P,"dash");m.addGetterSetter(P,"dashOffset",0,I());m.addGetterSetter(P,"shadowColor",void 0,Xe());m.addGetterSetter(P,"shadowBlur",0,I());m.addGetterSetter(P,"shadowOpacity",1,I());m.addComponentsGetterSetter(P,"shadowOffset",["x","y"]);m.addGetterSetter(P,"shadowOffsetX",0,I());m.addGetterSetter(P,"shadowOffsetY",0,I());m.addGetterSetter(P,"fillPatternImage");m.addGetterSetter(P,"fill",void 0,qn());m.addGetterSetter(P,"fillPatternX",0,I());m.addGetterSetter(P,"fillPatternY",0,I());m.addGetterSetter(P,"fillLinearGradientColorStops");m.addGetterSetter(P,"strokeLinearGradientColorStops");m.addGetterSetter(P,"fillRadialGradientStartRadius",0);m.addGetterSetter(P,"fillRadialGradientEndRadius",0);m.addGetterSetter(P,"fillRadialGradientColorStops");m.addGetterSetter(P,"fillPatternRepeat","repeat");m.addGetterSetter(P,"fillEnabled",!0);m.addGetterSetter(P,"strokeEnabled",!0);m.addGetterSetter(P,"shadowEnabled",!0);m.addGetterSetter(P,"dashEnabled",!0);m.addGetterSetter(P,"strokeScaleEnabled",!0);m.addGetterSetter(P,"fillPriority","color");m.addComponentsGetterSetter(P,"fillPatternOffset",["x","y"]);m.addGetterSetter(P,"fillPatternOffsetX",0,I());m.addGetterSetter(P,"fillPatternOffsetY",0,I());m.addComponentsGetterSetter(P,"fillPatternScale",["x","y"]);m.addGetterSetter(P,"fillPatternScaleX",1,I());m.addGetterSetter(P,"fillPatternScaleY",1,I());m.addComponentsGetterSetter(P,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(P,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(P,"fillLinearGradientStartPointX",0);m.addGetterSetter(P,"strokeLinearGradientStartPointX",0);m.addGetterSetter(P,"fillLinearGradientStartPointY",0);m.addGetterSetter(P,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(P,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(P,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(P,"fillLinearGradientEndPointX",0);m.addGetterSetter(P,"strokeLinearGradientEndPointX",0);m.addGetterSetter(P,"fillLinearGradientEndPointY",0);m.addGetterSetter(P,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(P,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(P,"fillRadialGradientStartPointX",0);m.addGetterSetter(P,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(P,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(P,"fillRadialGradientEndPointX",0);m.addGetterSetter(P,"fillRadialGradientEndPointY",0);m.addGetterSetter(P,"fillPatternRotation",0);m.addGetterSetter(P,"fillRule",void 0,Xe());m.backCompat(P,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Qr="beforeDraw",ea="draw",gs=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],ta=gs.length;class Ue extends ge{constructor(e){super(e),this.canvas=new Oe,this.hitCanvas=new Gi({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){x.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!x.prototype.moveUp.call(this))return!1;const t=this.getStage();return!t||!t.content?!1:(t.content.removeChild(this.getNativeCanvasElement()),this.index<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[this.index+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(x.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(x.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return x.prototype.remove.call(this),e&&e.parentNode&&v._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&v.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),x.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){v.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){v.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,v.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,i=!1;for(;;){for(let n=0;n<ta;n++){const s=gs[n],r=this._getIntersection({x:e.x+s.x*t,y:e.y+s.y*t}),o=r.shape;if(o)return o;if(i=!!r.antialiased,!r.antialiased)break}if(i)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,i=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,n=i[3];if(n===255){const s=v.getHitColorKey(i[0],i[1],i[2]),r=wt[s];return r?{shape:r}:{antialiased:!0}}else if(n>0)return{antialiased:!0};return{}}drawScene(e,t,i){const n=this.getLayer(),s=e||n&&n.getCanvas();return this._fire(Qr,{node:this}),this.clearBeforeDraw()&&s.getContext().clear(),ge.prototype.drawScene.call(this,s,t,i),this._fire(ea,{node:this}),this}drawHit(e,t){const i=this.getLayer(),n=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),ge.prototype.drawHit.call(this,n,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){v.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return v.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;!!this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return v.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}Ue.prototype.nodeType="Layer";ne(Ue);m.addGetterSetter(Ue,"imageSmoothingEnabled",!0);m.addGetterSetter(Ue,"clearBeforeDraw",!0);m.addGetterSetter(Ue,"hitGraphEnabled",!0,me());class zi extends Ue{constructor(e){super(e),this.listening(!1),v.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}zi.prototype.nodeType="FastLayer";ne(zi);class rt extends ge{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&v.throw("You may only add groups and shapes to groups.")}}rt.prototype.nodeType="Group";ne(rt);const hi=function(){return We.performance&&We.performance.now?function(){return We.performance.now()}:function(){return new Date().getTime()}}();class pe{constructor(e,t){this.id=pe.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:hi(),frameRate:0},this.func=e,this.setLayers(t)}setLayers(e){let t=[];return e&&(t=Array.isArray(e)?e:[e]),this.layers=t,this}getLayers(){return this.layers}addLayer(e){const t=this.layers,i=t.length;for(let n=0;n<i;n++)if(t[n]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){const t=pe.animations,i=t.length;for(let n=0;n<i;n++)if(t[n].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=hi(),pe._addAnimation(this),this}stop(){return pe._removeAnimation(this),this}_updateFrameObject(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(e){this.animations.push(e),this._handleAnimation()}static _removeAnimation(e){const t=e.id,i=this.animations,n=i.length;for(let s=0;s<n;s++)if(i[s].id===t){this.animations.splice(s,1);break}}static _runFrames(){const e={},t=this.animations;for(let i=0;i<t.length;i++){const n=t[i],s=n.layers,r=n.func;n._updateFrameObject(hi());const o=s.length;let l;if(r?l=r.call(n,n.frame)!==!1:l=!0,!!l)for(let h=0;h<o;h++){const c=s[h];c._id!==void 0&&(e[c._id]=c)}}for(const i in e)e.hasOwnProperty(i)&&e[i].batchDraw()}static _animationLoop(){const e=pe;e.animations.length?(e._runFrames(),v.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,v.requestAnimFrame(this._animationLoop))}}pe.animations=[];pe.animIdCounter=0;pe.animRunning=!1;const ia={node:1,duration:1,easing:1,onFinish:1,yoyo:1},na=1,nn=2,sn=3,rn=["fill","stroke","shadowColor"];let sa=0;class ra{constructor(e,t,i,n,s,r,o){this.prop=e,this.propFunc=t,this.begin=n,this._pos=n,this.duration=r,this._change=0,this.prevPos=0,this.yoyo=o,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=i,this._change=s-this.begin,this.pause()}fire(e){const t=this[e];t&&t()}setTime(e){e>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():e<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=e,this.update())}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){return e===void 0&&(e=this._time),this.func(e,this.begin,this._change,this.duration)}play(){this.state=nn,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=sn,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const e=this.getTimer()-this._startTime;this.state===nn?this.setTime(e):this.state===sn&&this.setTime(this.duration-e)}pause(){this.state=na,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Q{constructor(e){const t=this,i=e.node,n=i._id,s=e.easing||kt.Linear,r=!!e.yoyo;let o,l;typeof e.duration>"u"?o=.3:e.duration===0?o=.001:o=e.duration,this.node=i,this._id=sa++;const h=i.getLayer()||(i instanceof E.Stage?i.getLayers():null);h||v.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new pe(function(){t.tween.onEnterFrame()},h),this.tween=new ra(l,function(c){t._tweenFunc(c)},s,0,1,o*1e3,r),this._addListeners(),Q.attrs[n]||(Q.attrs[n]={}),Q.attrs[n][this._id]||(Q.attrs[n][this._id]={}),Q.tweens[n]||(Q.tweens[n]={});for(l in e)ia[l]===void 0&&this._addAttr(l,e[l]);this.reset(),this.onFinish=e.onFinish,this.onReset=e.onReset,this.onUpdate=e.onUpdate}_addAttr(e,t){const i=this.node,n=i._id;let s,r,o,l,h;const c=Q.tweens[n][e];c&&delete Q.attrs[n][c][e];let d=i.getAttr(e);if(v._isArray(t))if(s=[],r=Math.max(t.length,d.length),e==="points"&&t.length!==d.length&&(t.length>d.length?(l=d,d=v._prepareArrayForTween(d,t,i.closed())):(o=t,t=v._prepareArrayForTween(t,d,i.closed()))),e.indexOf("fill")===0)for(let u=0;u<r;u++)if(u%2===0)s.push(t[u]-d[u]);else{const f=v.colorToRGBA(d[u]);h=v.colorToRGBA(t[u]),d[u]=f,s.push({r:h.r-f.r,g:h.g-f.g,b:h.b-f.b,a:h.a-f.a})}else for(let u=0;u<r;u++)s.push(t[u]-d[u]);else rn.indexOf(e)!==-1?(d=v.colorToRGBA(d),h=v.colorToRGBA(t),s={r:h.r-d.r,g:h.g-d.g,b:h.b-d.b,a:h.a-d.a}):s=t-d;Q.attrs[n][this._id][e]={start:d,diff:s,end:t,trueEnd:o,trueStart:l},Q.tweens[n][e]=this._id}_tweenFunc(e){const t=this.node,i=Q.attrs[t._id][this._id];let n,s,r,o,l,h,c,d;for(n in i){if(s=i[n],r=s.start,o=s.diff,d=s.end,v._isArray(r))if(l=[],c=Math.max(r.length,d.length),n.indexOf("fill")===0)for(h=0;h<c;h++)h%2===0?l.push((r[h]||0)+o[h]*e):l.push("rgba("+Math.round(r[h].r+o[h].r*e)+","+Math.round(r[h].g+o[h].g*e)+","+Math.round(r[h].b+o[h].b*e)+","+(r[h].a+o[h].a*e)+")");else for(h=0;h<c;h++)l.push((r[h]||0)+o[h]*e);else rn.indexOf(n)!==-1?l="rgba("+Math.round(r.r+o.r*e)+","+Math.round(r.g+o.g*e)+","+Math.round(r.b+o.b*e)+","+(r.a+o.a*e)+")":l=r+o*e;t.setAttr(n,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const e=this.node,t=Q.attrs[e._id][this._id];t.points&&t.points.trueEnd&&e.setAttr("points",t.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const e=this.node,t=Q.attrs[e._id][this._id];t.points&&t.points.trueStart&&e.points(t.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(e){return this.tween.seek(e*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const e=this.node._id,t=this._id,i=Q.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const n in i)delete Q.tweens[e][n];delete Q.attrs[e][t],Q.tweens[e]&&(Object.keys(Q.tweens[e]).length===0&&delete Q.tweens[e],Object.keys(Q.attrs[e]).length===0&&delete Q.attrs[e])}}Q.attrs={};Q.tweens={};x.prototype.to=function(a){const e=a.onFinish;a.node=this,a.onFinish=function(){this.destroy(),e&&e()},new Q(a).play()};const kt={BackEaseIn(a,e,t,i){return t*(a/=i)*a*((1.70158+1)*a-1.70158)+e},BackEaseOut(a,e,t,i){return t*((a=a/i-1)*a*((1.70158+1)*a+1.70158)+1)+e},BackEaseInOut(a,e,t,i){let n=1.70158;return(a/=i/2)<1?t/2*(a*a*(((n*=1.525)+1)*a-n))+e:t/2*((a-=2)*a*(((n*=1.525)+1)*a+n)+2)+e},ElasticEaseIn(a,e,t,i,n,s){let r=0;return a===0?e:(a/=i)===1?e+t:(s||(s=i*.3),!n||n<Math.abs(t)?(n=t,r=s/4):r=s/(2*Math.PI)*Math.asin(t/n),-(n*Math.pow(2,10*(a-=1))*Math.sin((a*i-r)*(2*Math.PI)/s))+e)},ElasticEaseOut(a,e,t,i,n,s){let r=0;return a===0?e:(a/=i)===1?e+t:(s||(s=i*.3),!n||n<Math.abs(t)?(n=t,r=s/4):r=s/(2*Math.PI)*Math.asin(t/n),n*Math.pow(2,-10*a)*Math.sin((a*i-r)*(2*Math.PI)/s)+t+e)},ElasticEaseInOut(a,e,t,i,n,s){let r=0;return a===0?e:(a/=i/2)===2?e+t:(s||(s=i*(.3*1.5)),!n||n<Math.abs(t)?(n=t,r=s/4):r=s/(2*Math.PI)*Math.asin(t/n),a<1?-.5*(n*Math.pow(2,10*(a-=1))*Math.sin((a*i-r)*(2*Math.PI)/s))+e:n*Math.pow(2,-10*(a-=1))*Math.sin((a*i-r)*(2*Math.PI)/s)*.5+t+e)},BounceEaseOut(a,e,t,i){return(a/=i)<1/2.75?t*(7.5625*a*a)+e:a<2/2.75?t*(7.5625*(a-=1.5/2.75)*a+.75)+e:a<2.5/2.75?t*(7.5625*(a-=2.25/2.75)*a+.9375)+e:t*(7.5625*(a-=2.625/2.75)*a+.984375)+e},BounceEaseIn(a,e,t,i){return t-kt.BounceEaseOut(i-a,0,t,i)+e},BounceEaseInOut(a,e,t,i){return a<i/2?kt.BounceEaseIn(a*2,0,t,i)*.5+e:kt.BounceEaseOut(a*2-i,0,t,i)*.5+t*.5+e},EaseIn(a,e,t,i){return t*(a/=i)*a+e},EaseOut(a,e,t,i){return-t*(a/=i)*(a-2)+e},EaseInOut(a,e,t,i){return(a/=i/2)<1?t/2*a*a+e:-t/2*(--a*(a-2)-1)+e},StrongEaseIn(a,e,t,i){return t*(a/=i)*a*a*a*a+e},StrongEaseOut(a,e,t,i){return t*((a=a/i-1)*a*a*a*a+1)+e},StrongEaseInOut(a,e,t,i){return(a/=i/2)<1?t/2*a*a*a*a*a+e:t/2*((a-=2)*a*a*a*a+2)+e},Linear(a,e,t,i){return t*a/i+e}},an=v._assign(E,{Util:v,Transform:ue,Node:x,Container:ge,Stage:si,stages:bt,Layer:Ue,FastLayer:zi,Group:rt,DD:$,Shape:P,shapes:wt,Animation:pe,Tween:Q,Easings:kt,Context:ii,Canvas:Bi});class Ie extends P{_sceneFunc(e){const t=E.getAngle(this.angle()),i=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,i),e.arc(0,0,this.innerRadius(),t,0,!i),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),i=this.clockwise(),n=E.getAngle(i?360-this.angle():this.angle()),s=Math.cos(Math.min(n,Math.PI)),r=1,o=Math.sin(Math.min(Math.max(Math.PI,n),3*Math.PI/2)),l=Math.sin(Math.min(n,Math.PI/2)),h=s*(s>0?e:t),c=r*t,d=o*(o>0?e:t),u=l*(l>0?t:e);return{x:h,y:i?-1*u:d,width:c-h,height:u-d}}}Ie.prototype._centroid=!0;Ie.prototype.className="Arc";Ie.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];ne(Ie);m.addGetterSetter(Ie,"innerRadius",0,I());m.addGetterSetter(Ie,"outerRadius",0,I());m.addGetterSetter(Ie,"angle",0,I());m.addGetterSetter(Ie,"clockwise",!1,me());function bi(a,e,t,i,n,s,r){const o=Math.sqrt(Math.pow(t-a,2)+Math.pow(i-e,2)),l=Math.sqrt(Math.pow(n-t,2)+Math.pow(s-i,2)),h=r*o/(o+l),c=r*l/(o+l),d=t-h*(n-a),u=i-h*(s-e),f=t+c*(n-a),p=i+c*(s-e);return[d,u,f,p]}function on(a,e){const t=a.length,i=[];for(let n=2;n<t-2;n+=2){const s=bi(a[n-2],a[n-1],a[n],a[n+1],a[n+2],a[n+3],e);isNaN(s[0])||(i.push(s[0]),i.push(s[1]),i.push(a[n]),i.push(a[n+1]),i.push(s[2]),i.push(s[3]))}return i}function aa(a){const e=[[a[0],a[2],a[4],a[6]],[a[1],a[3],a[5],a[7]]],t=[];for(const i of e){const n=-3*i[0]+9*i[1]-9*i[2]+3*i[3];if(n!==0){const s=6*i[0]-12*i[1]+6*i[2],r=-3*i[0]+3*i[1],o=s*s-4*n*r;if(o>=0){const l=Math.sqrt(o);t.push((-s+l)/(2*n)),t.push((-s-l)/(2*n))}}}return t.filter(i=>i>0&&i<1).flatMap(i=>e.map(n=>{const s=1-i;return s*s*s*n[0]+3*s*s*i*n[1]+3*s*i*i*n[2]+i*i*i*n[3]}))}class Ae extends P{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),i=t.length,n=this.tension(),s=this.closed(),r=this.bezier();if(!i)return;let o=0;if(e.beginPath(),e.moveTo(t[0],t[1]),n!==0&&i>4){const l=this.getTensionPoints(),h=l.length;for(o=s?0:4,s||e.quadraticCurveTo(l[0],l[1],l[2],l[3]);o<h-2;)e.bezierCurveTo(l[o++],l[o++],l[o++],l[o++],l[o++],l[o++]);s||e.quadraticCurveTo(l[h-2],l[h-1],t[i-2],t[i-1])}else if(r)for(o=2;o<i;)e.bezierCurveTo(t[o++],t[o++],t[o++],t[o++],t[o++],t[o++]);else for(o=2;o<i;o+=2)e.lineTo(t[o],t[o+1]);s?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():on(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),n=bi(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),s=bi(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),r=on(e,i);return[n[2],n[3]].concat(r).concat([s[0],s[1],e[t-2],e[t-1],s[2],s[3],n[0],n[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:this.bezier()?e=[e[0],e[1],...aa(this.points()),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],i=e[0],n=e[1],s=e[1],r,o;for(let l=0;l<e.length/2;l++)r=e[l*2],o=e[l*2+1],t=Math.min(t,r),i=Math.max(i,r),n=Math.min(n,o),s=Math.max(s,o);return{x:t,y:n,width:i-t,height:s-n}}}Ae.prototype.className="Line";Ae.prototype._attrsAffectingSize=["points","bezier","tension"];ne(Ae);m.addGetterSetter(Ae,"closed",!1);m.addGetterSetter(Ae,"bezier",!1);m.addGetterSetter(Ae,"tension",0,I());m.addGetterSetter(Ae,"points",[],br());const oa=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],la=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],ha=[[1],[1,1],[1,2,1],[1,3,3,1]],ln=(a,e,t)=>{let i,n;const r=t/2;i=0;for(let o=0;o<20;o++)n=r*oa[20][o]+r,i+=la[20][o]*ca(a,e,n);return r*i},hn=(a,e,t)=>{t===void 0&&(t=1);const i=a[0]-2*a[1]+a[2],n=e[0]-2*e[1]+e[2],s=2*a[1]-2*a[0],r=2*e[1]-2*e[0],o=4*(i*i+n*n),l=4*(i*s+n*r),h=s*s+r*r;if(o===0)return t*Math.sqrt(Math.pow(a[2]-a[0],2)+Math.pow(e[2]-e[0],2));const c=l/(2*o),d=h/o,u=t+c,f=d-c*c,p=u*u+f>0?Math.sqrt(u*u+f):0,y=c*c+f>0?Math.sqrt(c*c+f):0,S=c+Math.sqrt(c*c+f)!==0?f*Math.log(Math.abs((u+p)/(c+y))):0;return Math.sqrt(o)/2*(u*p-c*y+S)};function ca(a,e,t){const i=wi(1,t,a),n=wi(1,t,e),s=i*i+n*n;return Math.sqrt(s)}const wi=(a,e,t)=>{const i=t.length-1;let n,s;if(i===0)return 0;if(a===0){s=0;for(let r=0;r<=i;r++)s+=ha[i][r]*Math.pow(1-e,i-r)*Math.pow(e,r)*t[r];return s}else{n=new Array(i);for(let r=0;r<i;r++)n[r]=i*(t[r+1]-t[r]);return wi(a-1,e,n)}},cn=(a,e,t)=>{let i=1,n=a/e,s=(a-t(n))/e,r=0;for(;i>.001;){const o=t(n+s),l=Math.abs(a-o)/e;if(l<i)i=l,n+=s;else{const h=t(n-s),c=Math.abs(a-h)/e;c<i?(i=c,n-=s):s/=2}if(r++,r>500)break}return n};class ee extends P{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=ee.parsePathData(this.data()),this.pathLength=ee.getPathLength(this.dataArray)}_sceneFunc(e){const t=this.dataArray;e.beginPath();let i=!1;for(let n=0;n<t.length;n++){const s=t[n].command,r=t[n].points;switch(s){case"L":e.lineTo(r[0],r[1]);break;case"M":e.moveTo(r[0],r[1]);break;case"C":e.bezierCurveTo(r[0],r[1],r[2],r[3],r[4],r[5]);break;case"Q":e.quadraticCurveTo(r[0],r[1],r[2],r[3]);break;case"A":const o=r[0],l=r[1],h=r[2],c=r[3],d=r[4],u=r[5],f=r[6],p=r[7],y=h>c?h:c,S=h>c?1:h/c,C=h>c?c/h:1;e.translate(o,l),e.rotate(f),e.scale(S,C),e.arc(0,0,y,d,d+u,1-p),e.scale(1/S,1/C),e.rotate(-f),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const h=l.points[4],c=l.points[5],d=l.points[4]+c;let u=Math.PI/180;if(Math.abs(h-d)<u&&(u=Math.abs(h-d)),c<0)for(let f=h-u;f>d;f-=u){const p=ee.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],f,0);e.push(p.x,p.y)}else for(let f=h+u;f<d;f+=u){const p=ee.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],f,0);e.push(p.x,p.y)}}else if(l.command==="C")for(let h=0;h<=1;h+=.01){const c=ee.getPointOnCubicBezier(h,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);e.push(c.x,c.y)}else e=e.concat(l.points)});let t=e[0],i=e[0],n=e[1],s=e[1],r,o;for(let l=0;l<e.length/2;l++)r=e[l*2],o=e[l*2+1],isNaN(r)||(t=Math.min(t,r),i=Math.max(i,r)),isNaN(o)||(n=Math.min(n,o),s=Math.max(s,o));return{x:t,y:n,width:i-t,height:s-n}}getLength(){return this.pathLength}getPointAtLength(e){return ee.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,i,n){return Math.sqrt((i-e)*(i-e)+(n-t)*(n-t))}static getPathLength(e){let t=0;for(let i=0;i<e.length;++i)t+=e[i].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let i,n=0,s=t.length;if(!s)return null;for(;n<s&&e>t[n].pathLength;)e-=t[n].pathLength,++n;if(n===s)return i=t[n-1].points.slice(-2),{x:i[0],y:i[1]};if(e<.01)return t[n].command==="M"?(i=t[n].points.slice(0,2),{x:i[0],y:i[1]}):{x:t[n].start.x,y:t[n].start.y};const r=t[n],o=r.points;switch(r.command){case"L":return ee.getPointOnLine(e,r.start.x,r.start.y,o[0],o[1]);case"C":return ee.getPointOnCubicBezier(cn(e,ee.getPathLength(t),y=>ln([r.start.x,o[0],o[2],o[4]],[r.start.y,o[1],o[3],o[5]],y)),r.start.x,r.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return ee.getPointOnQuadraticBezier(cn(e,ee.getPathLength(t),y=>hn([r.start.x,o[0],o[2]],[r.start.y,o[1],o[3]],y)),r.start.x,r.start.y,o[0],o[1],o[2],o[3]);case"A":const l=o[0],h=o[1],c=o[2],d=o[3],u=o[5],f=o[6];let p=o[4];return p+=u*e/r.pathLength,ee.getPointOnEllipticalArc(l,h,c,d,p,f)}return null}static getPointOnLine(e,t,i,n,s,r,o){r=r??t,o=o??i;const l=this.getLineLength(t,i,n,s);if(l<1e-10)return{x:t,y:i};if(n===t)return{x:r,y:o+(s>i?e:-e)};const h=(s-i)/(n-t),c=Math.sqrt(e*e/(1+h*h))*(n<t?-1:1),d=h*c;if(Math.abs(o-i-h*(r-t))<1e-10)return{x:r+c,y:o+d};const u=((r-t)*(n-t)+(o-i)*(s-i))/(l*l),f=t+u*(n-t),p=i+u*(s-i),y=this.getLineLength(r,o,f,p),S=Math.sqrt(e*e-y*y),C=Math.sqrt(S*S/(1+h*h))*(n<t?-1:1),T=h*C;return{x:f+C,y:p+T}}static getPointOnCubicBezier(e,t,i,n,s,r,o,l,h){function c(S){return S*S*S}function d(S){return 3*S*S*(1-S)}function u(S){return 3*S*(1-S)*(1-S)}function f(S){return(1-S)*(1-S)*(1-S)}const p=l*c(e)+r*d(e)+n*u(e)+t*f(e),y=h*c(e)+o*d(e)+s*u(e)+i*f(e);return{x:p,y}}static getPointOnQuadraticBezier(e,t,i,n,s,r,o){function l(f){return f*f}function h(f){return 2*f*(1-f)}function c(f){return(1-f)*(1-f)}const d=r*l(e)+n*h(e)+t*c(e),u=o*l(e)+s*h(e)+i*c(e);return{x:d,y:u}}static getPointOnEllipticalArc(e,t,i,n,s,r){const o=Math.cos(r),l=Math.sin(r),h={x:i*Math.cos(s),y:n*Math.sin(s)};return{x:e+(h.x*o-h.y*l),y:t+(h.x*l+h.y*o)}}static parsePathData(e){if(!e)return[];let t=e;const i=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(let d=0;d<i.length;d++)t=t.replace(new RegExp(i[d],"g"),"|"+i[d]);const n=t.split("|"),s=[],r=[];let o=0,l=0;const h=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let c;for(let d=1;d<n.length;d++){let u=n[d],f=u.charAt(0);for(u=u.slice(1),r.length=0;c=h.exec(u);)r.push(c[0]);let p=[],y=f==="A"||f==="a"?0:-1;for(let S=0,C=r.length;S<C;S++){const T=r[S];if(T==="00"){p.push(0,0),y>=0&&(y+=2,y>=7&&(y-=7));continue}if(y>=0){if(y===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(T)){p.push(parseInt(T[0],10)),p.push(parseInt(T[1],10)),p.push(parseFloat(T.slice(2))),y+=3,y>=7&&(y-=7);continue}if(T==="11"||T==="10"||T==="01"){p.push(parseInt(T[0],10)),p.push(parseInt(T[1],10)),y+=2,y>=7&&(y-=7);continue}if(T==="0"||T==="1"){p.push(parseInt(T,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(T)){p.push(parseInt(T[0],10)),p.push(parseFloat(T.slice(1))),y+=2,y>=7&&(y-=7);continue}if(T==="0"||T==="1"){p.push(parseInt(T,10)),y+=1,y>=7&&(y-=7);continue}}const b=parseFloat(T);isNaN(b)?p.push(0):p.push(b),y+=1,y>=7&&(y-=7)}else{const b=parseFloat(T);isNaN(b)?p.push(0):p.push(b)}}for(;p.length>0&&!isNaN(p[0]);){let S="",C=[];const T=o,b=l;let w,k,_,O,A,M,D,z,B,W;switch(f){case"l":o+=p.shift(),l+=p.shift(),S="L",C.push(o,l);break;case"L":o=p.shift(),l=p.shift(),C.push(o,l);break;case"m":const F=p.shift(),H=p.shift();if(o+=F,l+=H,S="M",s.length>2&&s[s.length-1].command==="z"){for(let R=s.length-2;R>=0;R--)if(s[R].command==="M"){o=s[R].points[0]+F,l=s[R].points[1]+H;break}}C.push(o,l),f="l";break;case"M":o=p.shift(),l=p.shift(),S="M",C.push(o,l),f="L";break;case"h":o+=p.shift(),S="L",C.push(o,l);break;case"H":o=p.shift(),S="L",C.push(o,l);break;case"v":l+=p.shift(),S="L",C.push(o,l);break;case"V":l=p.shift(),S="L",C.push(o,l);break;case"C":C.push(p.shift(),p.shift(),p.shift(),p.shift()),o=p.shift(),l=p.shift(),C.push(o,l);break;case"c":C.push(o+p.shift(),l+p.shift(),o+p.shift(),l+p.shift()),o+=p.shift(),l+=p.shift(),S="C",C.push(o,l);break;case"S":k=o,_=l,w=s[s.length-1],w.command==="C"&&(k=o+(o-w.points[2]),_=l+(l-w.points[3])),C.push(k,_,p.shift(),p.shift()),o=p.shift(),l=p.shift(),S="C",C.push(o,l);break;case"s":k=o,_=l,w=s[s.length-1],w.command==="C"&&(k=o+(o-w.points[2]),_=l+(l-w.points[3])),C.push(k,_,o+p.shift(),l+p.shift()),o+=p.shift(),l+=p.shift(),S="C",C.push(o,l);break;case"Q":C.push(p.shift(),p.shift()),o=p.shift(),l=p.shift(),C.push(o,l);break;case"q":C.push(o+p.shift(),l+p.shift()),o+=p.shift(),l+=p.shift(),S="Q",C.push(o,l);break;case"T":k=o,_=l,w=s[s.length-1],w.command==="Q"&&(k=o+(o-w.points[0]),_=l+(l-w.points[1])),o=p.shift(),l=p.shift(),S="Q",C.push(k,_,o,l);break;case"t":k=o,_=l,w=s[s.length-1],w.command==="Q"&&(k=o+(o-w.points[0]),_=l+(l-w.points[1])),o+=p.shift(),l+=p.shift(),S="Q",C.push(k,_,o,l);break;case"A":O=p.shift(),A=p.shift(),M=p.shift(),D=p.shift(),z=p.shift(),B=o,W=l,o=p.shift(),l=p.shift(),S="A",C=this.convertEndpointToCenterParameterization(B,W,o,l,D,z,O,A,M);break;case"a":O=p.shift(),A=p.shift(),M=p.shift(),D=p.shift(),z=p.shift(),B=o,W=l,o+=p.shift(),l+=p.shift(),S="A",C=this.convertEndpointToCenterParameterization(B,W,o,l,D,z,O,A,M);break}s.push({command:S||f,points:C,start:{x:T,y:b},pathLength:this.calcLength(T,b,S||f,C)})}(f==="z"||f==="Z")&&s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(e,t,i,n){let s,r,o,l;const h=ee;switch(i){case"L":return h.getLineLength(e,t,n[0],n[1]);case"C":return ln([e,n[0],n[2],n[4]],[t,n[1],n[3],n[5]],1);case"Q":return hn([e,n[0],n[2]],[t,n[1],n[3]],1);case"A":s=0;const c=n[4],d=n[5],u=n[4]+d;let f=Math.PI/180;if(Math.abs(c-u)<f&&(f=Math.abs(c-u)),r=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],c,0),d<0)for(l=c-f;l>u;l-=f)o=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],l,0),s+=h.getLineLength(r.x,r.y,o.x,o.y),r=o;else for(l=c+f;l<u;l+=f)o=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],l,0),s+=h.getLineLength(r.x,r.y,o.x,o.y),r=o;return o=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],u,0),s+=h.getLineLength(r.x,r.y,o.x,o.y),s}return 0}static convertEndpointToCenterParameterization(e,t,i,n,s,r,o,l,h){const c=h*(Math.PI/180),d=Math.cos(c)*(e-i)/2+Math.sin(c)*(t-n)/2,u=-1*Math.sin(c)*(e-i)/2+Math.cos(c)*(t-n)/2,f=d*d/(o*o)+u*u/(l*l);f>1&&(o*=Math.sqrt(f),l*=Math.sqrt(f));let p=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));s===r&&(p*=-1),isNaN(p)&&(p=0);const y=p*o*u/l,S=p*-l*d/o,C=(e+i)/2+Math.cos(c)*y-Math.sin(c)*S,T=(t+n)/2+Math.sin(c)*y+Math.cos(c)*S,b=function(D){return Math.sqrt(D[0]*D[0]+D[1]*D[1])},w=function(D,z){return(D[0]*z[0]+D[1]*z[1])/(b(D)*b(z))},k=function(D,z){return(D[0]*z[1]<D[1]*z[0]?-1:1)*Math.acos(w(D,z))},_=k([1,0],[(d-y)/o,(u-S)/l]),O=[(d-y)/o,(u-S)/l],A=[(-1*d-y)/o,(-1*u-S)/l];let M=k(O,A);return w(O,A)<=-1&&(M=Math.PI),w(O,A)>=1&&(M=0),r===0&&M>0&&(M=M-2*Math.PI),r===1&&M<0&&(M=M+2*Math.PI),[C,T,o,l,_,M,c,r]}}ee.prototype.className="Path";ee.prototype._attrsAffectingSize=["data"];ne(ee);m.addGetterSetter(ee,"data");class $e extends Ae{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,i=this.points();let n=i;const s=this.tension()!==0&&i.length>4;s&&(n=this.getTensionPoints());const r=this.pointerLength(),o=i.length;let l,h;if(s){const u=[n[n.length-4],n[n.length-3],n[n.length-2],n[n.length-1],i[o-2],i[o-1]],f=ee.calcLength(n[n.length-4],n[n.length-3],"C",u),p=ee.getPointOnQuadraticBezier(Math.min(1,1-r/f),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-p.x,h=i[o-1]-p.y}else l=i[o-2]-i[o-4],h=i[o-1]-i[o-3];const c=(Math.atan2(h,l)+t)%t,d=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(i[o-2],i[o-1]),e.rotate(c),e.moveTo(0,0),e.lineTo(-r,d/2),e.lineTo(-r,-d/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(i[0],i[1]),s?(l=(n[0]+n[2])/2-i[0],h=(n[1]+n[3])/2-i[1]):(l=i[2]-i[0],h=i[3]-i[1]),e.rotate((Math.atan2(-h,-l)+t)%t),e.moveTo(0,0),e.lineTo(-r,d/2),e.lineTo(-r,-d/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}}$e.prototype.className="Arrow";ne($e);m.addGetterSetter($e,"pointerLength",10,I());m.addGetterSetter($e,"pointerWidth",10,I());m.addGetterSetter($e,"pointerAtBeginning",!1);m.addGetterSetter($e,"pointerAtEnding",!0);class at extends P{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}at.prototype._centroid=!0;at.prototype.className="Circle";at.prototype._attrsAffectingSize=["radius"];ne(at);m.addGetterSetter(at,"radius",0,I());class Ge extends P{_sceneFunc(e){const t=this.radiusX(),i=this.radiusY();e.beginPath(),e.save(),t!==i&&e.scale(1,i/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}Ge.prototype.className="Ellipse";Ge.prototype._centroid=!0;Ge.prototype._attrsAffectingSize=["radiusX","radiusY"];ne(Ge);m.addComponentsGetterSetter(Ge,"radius",["x","y"]);m.addGetterSetter(Ge,"radiusX",0,I());m.addGetterSetter(Ge,"radiusY",0,I());let ye=class ps extends P{constructor(e){super(e),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",t=>{this._removeImageLoad(t.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const e=this.image();e&&e.complete||e&&e.readyState===4||e&&e.addEventListener&&e.addEventListener("load",this._loadListener)}_removeImageLoad(e){e&&e.removeEventListener&&e.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const e=!!this.cornerRadius(),t=this.hasShadow();return e&&t?!0:super._useBufferCanvas(!0)}_sceneFunc(e){const t=this.getWidth(),i=this.getHeight(),n=this.cornerRadius(),s=this.attrs.image;let r;if(s){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?r=[s,this.cropX(),this.cropY(),o,l,0,0,t,i]:r=[s,0,0,t,i]}(this.hasFill()||this.hasStroke()||n)&&(e.beginPath(),n?v.drawRoundedRectPath(e,t,i,n):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)),s&&(n&&e.clip(),e.drawImage.apply(e,r))}_hitFunc(e){const t=this.width(),i=this.height(),n=this.cornerRadius();e.beginPath(),n?v.drawRoundedRectPath(e,t,i,n):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}getWidth(){var e,t,i;return(i=(e=this.attrs.width)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.width)!==null&&i!==void 0?i:0}getHeight(){var e,t,i;return(i=(e=this.attrs.height)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.height)!==null&&i!==void 0?i:0}static fromURL(e,t,i=null){const n=v.createImageElement();n.onload=function(){const s=new ps({image:n});t(s)},n.onerror=i,n.crossOrigin="Anonymous",n.src=e}};ye.prototype.className="Image";ye.prototype._attrsAffectingSize=["image"];ne(ye);m.addGetterSetter(ye,"cornerRadius",0,ni(4));m.addGetterSetter(ye,"image");m.addComponentsGetterSetter(ye,"crop",["x","y","width","height"]);m.addGetterSetter(ye,"cropX",0,I());m.addGetterSetter(ye,"cropY",0,I());m.addGetterSetter(ye,"cropWidth",0,I());m.addGetterSetter(ye,"cropHeight",0,I());const fs=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],da="Change.konva",ua="none",ki="up",Pi="right",_i="down",xi="left",ga=fs.length;class Fi extends rt{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,i;const n=function(){t._sync()};for(i=0;i<ga;i++)e.on(fs[i]+da,n)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),i,n,s,r,o,l,h;if(e&&t){switch(i=e.width(),n=e.height(),s=t.pointerDirection(),r=t.pointerWidth(),h=t.pointerHeight(),o=0,l=0,s){case ki:o=i/2,l=-1*h;break;case Pi:o=i+r,l=n/2;break;case _i:o=i/2,l=n+h;break;case xi:o=-1*r,l=n/2;break}t.setAttrs({x:-1*o,y:-1*l,width:i,height:n}),e.setAttrs({x:-1*o,y:-1*l})}}}Fi.prototype.className="Label";ne(Fi);class qe extends P{_sceneFunc(e){const t=this.width(),i=this.height(),n=this.pointerDirection(),s=this.pointerWidth(),r=this.pointerHeight(),o=this.cornerRadius();let l=0,h=0,c=0,d=0;typeof o=="number"?l=h=c=d=Math.min(o,t/2,i/2):(l=Math.min(o[0]||0,t/2,i/2),h=Math.min(o[1]||0,t/2,i/2),d=Math.min(o[2]||0,t/2,i/2),c=Math.min(o[3]||0,t/2,i/2)),e.beginPath(),e.moveTo(l,0),n===ki&&(e.lineTo((t-s)/2,0),e.lineTo(t/2,-1*r),e.lineTo((t+s)/2,0)),e.lineTo(t-h,0),e.arc(t-h,h,h,Math.PI*3/2,0,!1),n===Pi&&(e.lineTo(t,(i-r)/2),e.lineTo(t+s,i/2),e.lineTo(t,(i+r)/2)),e.lineTo(t,i-d),e.arc(t-d,i-d,d,0,Math.PI/2,!1),n===_i&&(e.lineTo((t+s)/2,i),e.lineTo(t/2,i+r),e.lineTo((t-s)/2,i)),e.lineTo(c,i),e.arc(c,i-c,c,Math.PI/2,Math.PI,!1),n===xi&&(e.lineTo(0,(i+r)/2),e.lineTo(-1*s,i/2),e.lineTo(0,(i-r)/2)),e.lineTo(0,l),e.arc(l,l,l,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,i=this.pointerWidth(),n=this.pointerHeight(),s=this.pointerDirection(),r=this.width(),o=this.height();return s===ki?(t-=n,o+=n):s===_i?o+=n:s===xi?(e-=i*1.5,r+=i):s===Pi&&(r+=i*1.5),{x:e,y:t,width:r,height:o}}}qe.prototype.className="Tag";ne(qe);m.addGetterSetter(qe,"pointerDirection",ua);m.addGetterSetter(qe,"pointerWidth",0,I());m.addGetterSetter(qe,"pointerHeight",0,I());m.addGetterSetter(qe,"cornerRadius",0,ni(4));class Et extends P{_sceneFunc(e){const t=this.cornerRadius(),i=this.width(),n=this.height();e.beginPath(),t?v.drawRoundedRectPath(e,i,n,t):e.rect(0,0,i,n),e.closePath(),e.fillStrokeShape(this)}}Et.prototype.className="Rect";ne(Et);m.addGetterSetter(Et,"cornerRadius",0,ni(4));class He extends P{_sceneFunc(e){const t=this._getPoints(),i=this.radius(),n=this.sides(),s=this.cornerRadius();if(e.beginPath(),s)v.drawRoundedPolygonPath(e,t,n,i,s);else{e.moveTo(t[0].x,t[0].y);for(let r=1;r<t.length;r++)e.lineTo(t[r].x,t[r].y)}e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,i=[];for(let n=0;n<e;n++)i.push({x:t*Math.sin(n*2*Math.PI/e),y:-1*t*Math.cos(n*2*Math.PI/e)});return i}getSelfRect(){const e=this._getPoints();let t=e[0].x,i=e[0].x,n=e[0].y,s=e[0].y;return e.forEach(r=>{t=Math.min(t,r.x),i=Math.max(i,r.x),n=Math.min(n,r.y),s=Math.max(s,r.y)}),{x:t,y:n,width:i-t,height:s-n}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}He.prototype.className="RegularPolygon";He.prototype._centroid=!0;He.prototype._attrsAffectingSize=["radius"];ne(He);m.addGetterSetter(He,"radius",0,I());m.addGetterSetter(He,"sides",0,I());m.addGetterSetter(He,"cornerRadius",0,ni(4));const dn=Math.PI*2;class Ke extends P{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,dn,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),dn,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}Ke.prototype.className="Ring";Ke.prototype._centroid=!0;Ke.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ne(Ke);m.addGetterSetter(Ke,"innerRadius",0,I());m.addGetterSetter(Ke,"outerRadius",0,I());class we extends P{constructor(e){super(e),this._updated=!0,this.anim=new pe(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),i=this.frameIndex(),n=i*4,s=this.animations()[t],r=this.frameOffsets(),o=s[n+0],l=s[n+1],h=s[n+2],c=s[n+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,h,c),e.closePath(),e.fillStrokeShape(this)),d)if(r){const u=r[t],f=i*2;e.drawImage(d,o,l,h,c,u[f+0],u[f+1],h,c)}else e.drawImage(d,o,l,h,c,0,0,h,c)}_hitFunc(e){const t=this.animation(),i=this.frameIndex(),n=i*4,s=this.animations()[t],r=this.frameOffsets(),o=s[n+2],l=s[n+3];if(e.beginPath(),r){const h=r[t],c=i*2;e.rect(h[c+0],h[c+1],o,l)}else e.rect(0,0,o,l);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation(),i=this.animations(),n=i[t],s=n.length/4;e<s-1?this.frameIndex(e+1):this.frameIndex(0)}}we.prototype.className="Sprite";ne(we);m.addGetterSetter(we,"animation");m.addGetterSetter(we,"animations");m.addGetterSetter(we,"frameOffsets");m.addGetterSetter(we,"image");m.addGetterSetter(we,"frameIndex",0,I());m.addGetterSetter(we,"frameRate",17,I());m.backCompat(we,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Ne extends P{_sceneFunc(e){const t=this.innerRadius(),i=this.outerRadius(),n=this.numPoints();e.beginPath(),e.moveTo(0,0-i);for(let s=1;s<n*2;s++){const r=s%2===0?i:t,o=r*Math.sin(s*Math.PI/n),l=-1*r*Math.cos(s*Math.PI/n);e.lineTo(o,l)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}Ne.prototype.className="Star";Ne.prototype._centroid=!0;Ne.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ne(Ne);m.addGetterSetter(Ne,"numPoints",5,I());m.addGetterSetter(Ne,"innerRadius",0,I());m.addGetterSetter(Ne,"outerRadius",0,I());function Re(a){return[...a].reduce((e,t,i,n)=>{if(new RegExp("\\p{Emoji}","u").test(t)){const s=n[i+1];s&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(s)?(e.push(t+s),n[i+1]=""):e.push(t)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(t+(n[i+1]||""))?e.push(t+n[i+1]):i>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(t)?e[e.length-1]+=t:t&&e.push(t);return e},[])}const Ze="auto",pa="center",ms="inherit",dt="justify",fa="Change.konva",ma="2d",un="-",ys="left",ya="text",Sa="Text",Ca="top",va="bottom",gn="middle",Ss="normal",Ta="px ",zt=" ",ba="right",pn="rtl",wa="word",ka="char",fn="none",ci="…",Cs=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Pa=Cs.length;function _a(a){return a.split(",").map(e=>{e=e.trim();const t=e.indexOf(" ")>=0,i=e.indexOf('"')>=0||e.indexOf("'")>=0;return t&&!i&&(e=`"${e}"`),e}).join(", ")}let Ft;function di(){return Ft||(Ft=v.createCanvasElement().getContext(ma),Ft)}function xa(a){a.fillText(this._partialText,this._partialTextX,this._partialTextY)}function Ia(a){a.setAttr("miterLimit",2),a.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Aa(a){return a=a||{},!a.fillLinearGradientColorStops&&!a.fillRadialGradientColorStops&&!a.fillPatternImage&&(a.fill=a.fill||"black"),a}class te extends P{constructor(e){super(Aa(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<Pa;t++)this.on(Cs[t]+fa,this._setTextData);this._setTextData()}_sceneFunc(e){var t,i;const n=this.textArr,s=n.length;if(!this.text())return;let r=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,h=this.verticalAlign(),c=this.direction(),d=0,u=this.align(),f=this.getWidth(),p=this.letterSpacing(),y=this.charRenderFunc(),S=this.fill(),C=this.textDecoration(),T=this.underlineOffset(),b=C.indexOf("underline")!==-1,w=C.indexOf("line-through")!==-1,k;c=c===ms?e.direction:c;let _=l/2,O=gn;if(!E.legacyTextRendering){const A=this.measureSize("M");O="alphabetic";const M=(t=A.fontBoundingBoxAscent)!==null&&t!==void 0?t:A.actualBoundingBoxAscent,D=(i=A.fontBoundingBoxDescent)!==null&&i!==void 0?i:A.actualBoundingBoxDescent;_=(M-D)/2+l/2}for(c===pn&&e.setAttr("direction",c),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",O),e.setAttr("textAlign",ys),h===gn?d=(this.getHeight()-s*l-r*2)/2:h===va&&(d=this.getHeight()-s*l-r*2),e.translate(r,d+r),k=0;k<s;k++){let A=0,M=0;const D=n[k],z=D.text,B=D.width,W=D.lastInParagraph;if(e.save(),u===ba?A+=f-B-r*2:u===pa&&(A+=(f-B-r*2)/2),b){e.save(),e.beginPath();const H=T??(E.legacyTextRendering?Math.round(o/2):Math.round(o/4)),R=A,K=_+M+H;e.moveTo(R,K);const G=u===dt&&!W?f-r*2:B;e.lineTo(R+Math.round(G),K),e.lineWidth=o/15;const U=this._getLinearGradient();e.strokeStyle=U||S,e.stroke(),e.restore()}const F=A;if(c!==pn&&(p!==0||u===dt||y)){const H=z.split(" ").length-1,R=Re(z);for(let K=0;K<R.length;K++){const G=R[K];if(G===" "&&!W&&u===dt&&(A+=(f-r*2-B)/H),this._partialTextX=A,this._partialTextY=_+M,this._partialText=G,y){e.save();const Z=n.slice(0,k).reduce((se,he)=>se+Re(he.text).length,0),q=K+Z;y({char:G,index:q,x:A,y:_+M,lineIndex:k,column:K,isLastInLine:W,width:this.measureSize(G).width,context:e})}e.fillStrokeShape(this),y&&e.restore(),A+=this.measureSize(G).width+p}}else p!==0&&e.setAttr("letterSpacing",`${p}px`),this._partialTextX=A,this._partialTextY=_+M,this._partialText=z,e.fillStrokeShape(this);if(w){e.save(),e.beginPath();const H=E.legacyTextRendering?0:-Math.round(o/4),R=F;e.moveTo(R,_+M+H);const K=u===dt&&!W?f-r*2:B;e.lineTo(R+Math.round(K),_+M+H),e.lineWidth=o/15;const G=this._getLinearGradient();e.strokeStyle=G||S,e.stroke(),e.restore()}e.restore(),s>1&&(_+=l)}}_hitFunc(e){const t=this.getWidth(),i=this.getHeight();e.beginPath(),e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=v._isString(e)?e:e==null?"":e+"";return this._setAttr(ya,t),this}getWidth(){return this.attrs.width===Ze||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===Ze||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return v.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,i,n,s,r,o,l,h,c,d,u;let f=di(),p=this.fontSize(),y;f.save(),f.font=this._getContextFont(),y=f.measureText(e),f.restore();const S=p/100;return{actualBoundingBoxAscent:(t=y.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*S,actualBoundingBoxDescent:(i=y.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(n=y.actualBoundingBoxLeft)!==null&&n!==void 0?n:-7.421875*S,actualBoundingBoxRight:(s=y.actualBoundingBoxRight)!==null&&s!==void 0?s:75.732421875*S,alphabeticBaseline:(r=y.alphabeticBaseline)!==null&&r!==void 0?r:0,emHeightAscent:(o=y.emHeightAscent)!==null&&o!==void 0?o:100*S,emHeightDescent:(l=y.emHeightDescent)!==null&&l!==void 0?l:-20*S,fontBoundingBoxAscent:(h=y.fontBoundingBoxAscent)!==null&&h!==void 0?h:91*S,fontBoundingBoxDescent:(c=y.fontBoundingBoxDescent)!==null&&c!==void 0?c:21*S,hangingBaseline:(d=y.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*S,ideographicBaseline:(u=y.ideographicBaseline)!==null&&u!==void 0?u:-21*S,width:y.width,height:p}}_getContextFont(){return this.fontStyle()+zt+this.fontVariant()+zt+(this.fontSize()+Ta)+_a(this.fontFamily())}_addTextLine(e){this.align()===dt&&(e=e.trim());const i=this._getTextWidth(e);return this.textArr.push({text:e,width:i,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),i=e.length;return di().measureText(e).width+t*i}_setTextData(){let e=this.text().split(`
15
+ `),t=+this.fontSize(),i=0,n=this.lineHeight()*t,s=this.attrs.width,r=this.attrs.height,o=s!==Ze&&s!==void 0,l=r!==Ze&&r!==void 0,h=this.padding(),c=s-h*2,d=r-h*2,u=0,f=this.wrap(),p=f!==fn,y=f!==ka&&p,S=this.ellipsis();this.textArr=[],di().font=this._getContextFont();const C=S?this._getTextWidth(ci):0;for(let T=0,b=e.length;T<b;++T){let w=e[T],k=this._getTextWidth(w);if(o&&k>c)for(;w.length>0;){let _=0,O=Re(w).length,A="",M=0;for(;_<O;){const D=_+O>>>1,z=Re(w),B=z.slice(0,D+1).join(""),W=this._getTextWidth(B);(S&&l&&u+n>d?W+C:W)<=c?(_=D+1,A=B,M=W):O=D}if(A){if(y){const B=Re(w),W=Re(A),F=B[W.length],H=F===zt||F===un;let R;if(H&&M<=c)R=W.length;else{const K=W.lastIndexOf(zt),G=W.lastIndexOf(un);R=Math.max(K,G)+1}R>0&&(_=R,A=B.slice(0,_).join(""),M=this._getTextWidth(A))}if(A=A.trimRight(),this._addTextLine(A),i=Math.max(i,M),u+=n,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(w=Re(w).slice(_).join("").trimLeft(),w.length>0&&(k=this._getTextWidth(w),k<=c)){this._addTextLine(w),u+=n,i=Math.max(i,k);break}}else break}else this._addTextLine(w),u+=n,i=Math.max(i,k),this._shouldHandleEllipsis(u)&&T<b-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),l&&u+n>d)break}this.textHeight=t,this.textWidth=i}_shouldHandleEllipsis(e){const t=+this.fontSize(),i=this.lineHeight()*t,n=this.attrs.height,s=n!==Ze&&n!==void 0,r=this.padding(),o=n-r*2;return!(this.wrap()!==fn)||s&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==Ze&&e!==void 0,i=this.padding(),n=e-i*2,s=this.ellipsis(),r=this.textArr[this.textArr.length-1];!r||!s||(t&&(this._getTextWidth(r.text+ci)<n||(r.text=r.text.slice(0,r.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(r.text+ci))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t?!0:super._useBufferCanvas()}}te.prototype._fillFunc=xa;te.prototype._strokeFunc=Ia;te.prototype.className=Sa;te.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];ne(te);m.overWriteSetter(te,"width",Hi());m.overWriteSetter(te,"height",Hi());m.addGetterSetter(te,"direction",ms);m.addGetterSetter(te,"fontFamily","Arial");m.addGetterSetter(te,"fontSize",12,I());m.addGetterSetter(te,"fontStyle",Ss);m.addGetterSetter(te,"fontVariant",Ss);m.addGetterSetter(te,"padding",0,I());m.addGetterSetter(te,"align",ys);m.addGetterSetter(te,"verticalAlign",Ca);m.addGetterSetter(te,"lineHeight",1,I());m.addGetterSetter(te,"wrap",wa);m.addGetterSetter(te,"ellipsis",!1,me());m.addGetterSetter(te,"letterSpacing",0,I());m.addGetterSetter(te,"text","",Xe());m.addGetterSetter(te,"textDecoration","");m.addGetterSetter(te,"underlineOffset",void 0,I());m.addGetterSetter(te,"charRenderFunc",void 0);const Ea="",vs="normal";function Ts(a){a.fillText(this.partialText,0,0)}function bs(a){a.strokeText(this.partialText,0,0)}class re extends P{constructor(e){super(e),this.dummyCanvas=v.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return ee.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:ee.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=ee.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),i=this.fill(),n=this.fontSize(),s=this.glyphInfo,r=t.indexOf("underline")!==-1,o=t.indexOf("line-through")!==-1;r&&e.beginPath();for(let l=0;l<s.length;l++){e.save();const h=s[l].p0;e.translate(h.x,h.y),e.rotate(s[l].rotation),this.partialText=s[l].text,e.fillStrokeShape(this),r&&(l===0&&e.moveTo(0,n/2+1),e.lineTo(s[l].width,n/2+1)),e.restore()}if(r&&(e.strokeStyle=i,e.lineWidth=n/20,e.stroke()),o){e.beginPath();for(let l=0;l<s.length;l++){e.save();const h=s[l].p0;e.translate(h.x,h.y),e.rotate(s[l].rotation),l===0&&e.moveTo(0,0),e.lineTo(s[l].width,0),e.restore()}e.strokeStyle=i,e.lineWidth=n/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const i=t[0].p0;e.moveTo(i.x,i.y)}for(let i=0;i<t.length;i++){const n=t[i].p1;e.lineTo(n.x,n.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return v.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return te.prototype.setText.call(this,e)}_getContextFont(){return te.prototype._getContextFont.call(this)}_getTextSize(e){const i=this.dummyCanvas.getContext("2d");i.save(),i.font=this._getContextFont();const n=i.measureText(e);return i.restore(),{width:n.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const e=Re(this.text()),t=[];let i=0;for(let d=0;d<e.length;d++)t.push({char:e[d],width:this._getTextSize(e[d]).width}),i+=t[d].width;const{height:n}=this._getTextSize(this.attrs.text);if(this.textWidth=i,this.textHeight=n,this.glyphInfo=[],!this.attrs.data)return null;const s=this.letterSpacing(),r=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*s,0);let h=0;r==="center"&&(h=Math.max(0,this.pathLength/2-l/2)),r==="right"&&(h=Math.max(0,this.pathLength-l));let c=h;for(let d=0;d<t.length;d++){const u=this._getPointAtLength(c);if(!u)return;const f=t[d].char;let p=t[d].width+s;if(f===" "&&r==="justify"){const w=this.text().split(" ").length-1;p+=(this.pathLength-l)/w}const y=this._getPointAtLength(c+p);if(!y)return;const S=ee.getLineLength(u.x,u.y,y.x,y.y);let C=0;if(o)try{C=o(t[d-1].char,f)*this.fontSize()}catch{C=0}u.x+=C,y.x+=C,this.textWidth+=C;const T=ee.getPointOnLine(C+S/2,u.x,u.y,y.x,y.y),b=Math.atan2(y.y-u.y,y.x-u.x);this.glyphInfo.push({transposeX:T.x,transposeY:T.y,text:e[d],rotation:b,p0:u,p1:y,width:S}),c+=p}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(h){e.push(h.p0.x),e.push(h.p0.y),e.push(h.p1.x),e.push(h.p1.y)});let t=e[0]||0,i=e[0]||0,n=e[1]||0,s=e[1]||0,r,o;for(let h=0;h<e.length/2;h++)r=e[h*2],o=e[h*2+1],t=Math.min(t,r),i=Math.max(i,r),n=Math.min(n,o),s=Math.max(s,o);const l=this.fontSize();return{x:t-l/2,y:n-l/2,width:i-t+l,height:s-n+l}}destroy(){return v.releaseCanvas(this.dummyCanvas),super.destroy()}}re.prototype._fillFunc=Ts;re.prototype._strokeFunc=bs;re.prototype._fillFuncHit=Ts;re.prototype._strokeFuncHit=bs;re.prototype.className="TextPath";re.prototype._attrsAffectingSize=["text","fontSize","data"];ne(re);m.addGetterSetter(re,"data");m.addGetterSetter(re,"fontFamily","Arial");m.addGetterSetter(re,"fontSize",12,I());m.addGetterSetter(re,"fontStyle",vs);m.addGetterSetter(re,"align","left");m.addGetterSetter(re,"letterSpacing",0,I());m.addGetterSetter(re,"textBaseline","middle");m.addGetterSetter(re,"fontVariant",vs);m.addGetterSetter(re,"text",Ea);m.addGetterSetter(re,"textDecoration","");m.addGetterSetter(re,"kerningFunc",void 0);const ws="tr-konva",Ma=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(a=>a+`.${ws}`).join(" "),mn="nodesRect",La=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Ra={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Da="ontouchstart"in E._global;function Oa(a,e,t){if(a==="rotater")return t;e+=v.degToRad(Ra[a]||0);const i=(v.radToDeg(e)%360+360)%360;return v._inRange(i,315+22.5,360)||v._inRange(i,0,22.5)?"ns-resize":v._inRange(i,45-22.5,45+22.5)?"nesw-resize":v._inRange(i,90-22.5,90+22.5)?"ew-resize":v._inRange(i,135-22.5,135+22.5)?"nwse-resize":v._inRange(i,180-22.5,180+22.5)?"ns-resize":v._inRange(i,225-22.5,225+22.5)?"nesw-resize":v._inRange(i,270-22.5,270+22.5)?"ew-resize":v._inRange(i,315-22.5,315+22.5)?"nwse-resize":(v.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}const Qt=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function Ba(a){return{x:a.x+a.width/2*Math.cos(a.rotation)+a.height/2*Math.sin(-a.rotation),y:a.y+a.height/2*Math.cos(a.rotation)+a.width/2*Math.sin(a.rotation)}}function ks(a,e,t){const i=t.x+(a.x-t.x)*Math.cos(e)-(a.y-t.y)*Math.sin(e),n=t.y+(a.x-t.x)*Math.sin(e)+(a.y-t.y)*Math.cos(e);return{...a,rotation:a.rotation+e,x:i,y:n}}function Ga(a,e){const t=Ba(a);return ks(a,e,t)}function Ha(a,e,t){let i=e;for(let n=0;n<a.length;n++){const s=E.getAngle(a[n]),r=Math.abs(s-e)%(Math.PI*2);Math.min(r,Math.PI*2-r)<t&&(i=s)}return i}let Ii=0;class Y extends rt{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(Ma,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return v.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return ws+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(n=>n.isAncestorOf(this)?(v.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(n=>{const s=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(n._attrsAffectingSize.length){const r=n._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");n.on(r,s)}n.on(La.map(r=>r+`.${this._getEventNamespace()}`).join(" "),s),n.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(n)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,i=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(i,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,i=>{if(!t)return;const n=e.getAbsolutePosition(),s=n.x-t.x,r=n.y-t.y;this.nodes().forEach(o=>{if(o===e||o.isDragging())return;const l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+s,y:l.y+r}),o.startDrag(i)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(mn),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(mn,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),i){const n=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=e.getAbsoluteScale(i),r=e.getAbsolutePosition(i),o=n.x*s.x-e.offsetX()*s.x,l=n.y*s.y-e.offsetY()*s.y,h=(E.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),c={x:r.x+o*Math.cos(h)+l*Math.sin(-h),y:r.y+l*Math.cos(h)+o*Math.sin(h),width:n.width*s.x,height:n.height*s.y,rotation:h};return ks(c,-E.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(h=>{const c=h.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:c.x,y:c.y},{x:c.x+c.width,y:c.y},{x:c.x+c.width,y:c.y+c.height},{x:c.x,y:c.y+c.height}],u=h.getAbsoluteTransform();d.forEach(function(f){const p=u.point(f);t.push(p)})});const i=new ue;i.rotate(-E.getAngle(this.rotation()));let n=1/0,s=1/0,r=-1/0,o=-1/0;t.forEach(function(h){const c=i.point(h);n===void 0&&(n=r=c.x,s=o=c.y),n=Math.min(n,c.x),s=Math.min(s,c.y),r=Math.max(r,c.x),o=Math.max(o,c.y)}),i.invert();const l=i.point({x:n,y:s});return{x:l.x,y:l.y,width:r-n,height:o-s,rotation:E.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Qt.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new Et({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Da?10:"auto"}),i=this;t.on("mousedown touchstart",function(n){i._handleMouseDown(n)}),t.on("dragstart",n=>{t.stopDrag(),n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),t.on("mouseenter",()=>{const n=E.getAngle(this.rotation()),s=this.rotateAnchorCursor(),r=Oa(e,n,s);t.getStage().content&&(t.getStage().content.style.cursor=r),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new P({name:"back",width:0,height:0,sceneFunc(t,i){const n=i.getParent(),s=n.padding(),r=i.width(),o=i.height();if(t.beginPath(),t.rect(-s,-s,r+s*2,o+s*2),n.rotateEnabled()&&n.rotateLineVisible()){const l=n.rotateAnchorAngle(),h=n.rotateAnchorOffset(),c=v.degToRad(l),d=Math.sin(c),u=-Math.cos(c),f=r/2,p=o/2;let y=1/0;u<0?y=Math.min(y,-p/u):u>0&&(y=Math.min(y,(o-p)/u)),d<0?y=Math.min(y,-f/d):d>0&&(y=Math.min(y,(r-f)/d));const S=f+d*y,C=p+u*y,T=v._sign(o),b=S+d*h*T,w=C+u*h*T;t.moveTo(S,C),t.lineTo(b,w)}t.fillStrokeShape(i)},hitFunc:(t,i)=>{if(!this.shouldOverdrawWholeArea())return;const n=this.padding();t.beginPath(),t.rect(-n,-n,i.width()+n*2,i.height()+n*2),t.fillStrokeShape(i)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),i=t.width,n=t.height,s=Math.sqrt(Math.pow(i,2)+Math.pow(n,2));this.sin=Math.abs(n/s),this.cos=Math.abs(i/s),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const r=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-r.x,y:o.y-r.y},Ii++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(l=>{l._fire("transformstart",{evt:e.evt,target:l})})}_handleMouseMove(e){let t,i,n;const s=this.findOne("."+this._movingAnchorName),r=s.getStage();r.setPointersPositions(e);const o=r.getPointerPosition();let l={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const h=s.getAbsolutePosition();this.anchorDragBoundFunc()&&(l=this.anchorDragBoundFunc()(h,l,e)),s.setAbsolutePosition(l);const c=s.getAbsolutePosition();if(h.x===c.x&&h.y===c.y)return;if(this._movingAnchorName==="rotater"){const T=this._getNodeRect();t=s.x()-T.width/2,i=-s.y()+T.height/2;const b=E.getAngle(this.rotateAnchorAngle());let w=Math.atan2(-i,t)+Math.PI/2-b;T.height<0&&(w-=Math.PI);const _=E.getAngle(this.rotation())+w,O=E.getAngle(this.rotationSnapTolerance()),M=Ha(this.rotationSnaps(),_,O)-T.rotation,D=Ga(T,M);this._fitNodesInto(D,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let f=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const T=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};n=Math.sqrt(Math.pow(T.x-s.x(),2)+Math.pow(T.y-s.y(),2));const b=this.findOne(".top-left").x()>T.x?-1:1,w=this.findOne(".top-left").y()>T.y?-1:1;t=n*this.cos*b,i=n*this.sin*w,this.findOne(".top-left").x(T.x-t),this.findOne(".top-left").y(T.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(s.y());else if(this._movingAnchorName==="top-right"){if(u){const T=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};n=Math.sqrt(Math.pow(s.x()-T.x,2)+Math.pow(T.y-s.y(),2));const b=this.findOne(".top-right").x()<T.x?-1:1,w=this.findOne(".top-right").y()>T.y?-1:1;t=n*this.cos*b,i=n*this.sin*w,this.findOne(".top-right").x(T.x+t),this.findOne(".top-right").y(T.y-i)}var p=s.position();this.findOne(".top-left").y(p.y),this.findOne(".bottom-right").x(p.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(s.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(s.x());else if(this._movingAnchorName==="bottom-left"){if(u){const T=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};n=Math.sqrt(Math.pow(T.x-s.x(),2)+Math.pow(s.y()-T.y,2));const b=T.x<s.x()?-1:1,w=s.y()<T.y?-1:1;t=n*this.cos*b,i=n*this.sin*w,s.x(T.x-t),s.y(T.y+i)}p=s.position(),this.findOne(".top-left").x(p.x),this.findOne(".bottom-right").y(p.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.y());else if(this._movingAnchorName==="bottom-right"){if(u){const T=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};n=Math.sqrt(Math.pow(s.x()-T.x,2)+Math.pow(s.y()-T.y,2));const b=this.findOne(".bottom-right").x()<T.x?-1:1,w=this.findOne(".bottom-right").y()<T.y?-1:1;t=n*this.cos*b,i=n*this.sin*w,this.findOne(".bottom-right").x(T.x+t),this.findOne(".bottom-right").y(T.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(f=this.centeredScaling()||e.altKey,f){const T=this.findOne(".top-left"),b=this.findOne(".bottom-right"),w=T.x(),k=T.y(),_=this.getWidth()-b.x(),O=this.getHeight()-b.y();b.move({x:-w,y:-k}),T.move({x:_,y:O})}const y=this.findOne(".top-left").getAbsolutePosition();t=y.x,i=y.y;const S=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),C=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:i,width:S,height:C,rotation:E.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const i=this.getNode();Ii--,this._fire("transformend",{evt:e,target:i}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),i&&this._nodes.forEach(n=>{var s;n._fire("transformend",{evt:e,target:n}),(s=n.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const i=this._getNodeRect(),n=1;if(v._inRange(e.width,-this.padding()*2-n,n)){this.update();return}if(v._inRange(e.height,-this.padding()*2-n,n)){this.update();return}const s=new ue;if(s.rotate(E.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const u=s.point({x:-this.padding()*2,y:0});e.x+=u.x,e.y+=u.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const u=s.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const u=s.point({x:0,y:-this.padding()*2});e.x+=u.x,e.y+=u.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const u=s.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const u=this.boundBoxFunc()(i,e);u?e=u:v.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const r=1e7,o=new ue;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/r,i.height/r);const l=new ue,h=e.width/r,c=e.height/r;this.flipEnabled()===!1?(l.translate(e.x,e.y),l.rotate(e.rotation),l.translate(e.width<0?e.width:0,e.height<0?e.height:0),l.scale(Math.abs(h),Math.abs(c))):(l.translate(e.x,e.y),l.rotate(e.rotation),l.scale(h,c));const d=l.multiply(o.invert());this._nodes.forEach(u=>{var f;if(!u.getStage())return;const p=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const S=new ue;S.multiply(p.copy().invert()).multiply(d).multiply(p).multiply(y);const C=S.decompose();u.setAttrs(C),(f=u.getLayer())===null||f===void 0||f.batchDraw()}),this.rotation(v._getRotation(e.rotation)),this._nodes.forEach(u=>{this._fire("transform",{evt:t,target:u}),u._fire("transform",{evt:t,target:u})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(v._getRotation(t.rotation));const i=t.width,n=t.height,s=this.enabledAnchors(),r=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),h=this.find("._anchor");h.forEach(_=>{_.setAttrs({width:l,height:l,offsetX:l/2,offsetY:l/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:l/2+o,offsetY:l/2+o,visible:r&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:r&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:r&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:n/2,offsetX:l/2+o,visible:r&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:n/2,offsetX:l/2-o,visible:r&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:n,offsetX:l/2+o,offsetY:l/2-o,visible:r&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:n,offsetY:l/2-o,visible:r&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:n,offsetX:l/2-o,offsetY:l/2-o,visible:r&&s.indexOf("bottom-right")>=0});const c=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=v.degToRad(c),f=Math.sin(u),p=-Math.cos(u),y=i/2,S=n/2;let C=1/0;p<0?C=Math.min(C,-S/p):p>0&&(C=Math.min(C,(n-S)/p)),f<0?C=Math.min(C,-y/f):f>0&&(C=Math.min(C,(i-y)/f));const T=y+f*C,b=S+p*C,w=v._sign(n);this._batchChangeChild(".rotater",{x:T+f*d*w,y:b+p*d*w-o*p,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:n,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(_=>_.draggable()),x:0,y:0});const k=this.anchorStyleFunc();k&&h.forEach(_=>{k(_)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),rt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return x.prototype.toObject.call(this)}clone(e){return x.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}Y.isTransforming=()=>Ii>0;function Na(a){return a instanceof Array||v.warn("enabledAnchors value should be an array"),a instanceof Array&&a.forEach(function(e){Qt.indexOf(e)===-1&&v.warn("Unknown anchor name: "+e+". Available names are: "+Qt.join(", "))}),a||[]}Y.prototype.className="Transformer";ne(Y);m.addGetterSetter(Y,"enabledAnchors",Qt,Na);m.addGetterSetter(Y,"flipEnabled",!0,me());m.addGetterSetter(Y,"resizeEnabled",!0);m.addGetterSetter(Y,"anchorSize",10,I());m.addGetterSetter(Y,"rotateEnabled",!0);m.addGetterSetter(Y,"rotateLineVisible",!0);m.addGetterSetter(Y,"rotationSnaps",[]);m.addGetterSetter(Y,"rotateAnchorOffset",50,I());m.addGetterSetter(Y,"rotateAnchorAngle",0,I());m.addGetterSetter(Y,"rotateAnchorCursor","crosshair");m.addGetterSetter(Y,"rotationSnapTolerance",5,I());m.addGetterSetter(Y,"borderEnabled",!0);m.addGetterSetter(Y,"anchorStroke","rgb(0, 161, 255)");m.addGetterSetter(Y,"anchorStrokeWidth",1,I());m.addGetterSetter(Y,"anchorFill","white");m.addGetterSetter(Y,"anchorCornerRadius",0,I());m.addGetterSetter(Y,"borderStroke","rgb(0, 161, 255)");m.addGetterSetter(Y,"borderStrokeWidth",1,I());m.addGetterSetter(Y,"borderDash");m.addGetterSetter(Y,"keepRatio",!0);m.addGetterSetter(Y,"shiftBehavior","default");m.addGetterSetter(Y,"centeredScaling",!1);m.addGetterSetter(Y,"ignoreStroke",!1);m.addGetterSetter(Y,"padding",0,I());m.addGetterSetter(Y,"nodes");m.addGetterSetter(Y,"node");m.addGetterSetter(Y,"boundBoxFunc");m.addGetterSetter(Y,"anchorDragBoundFunc");m.addGetterSetter(Y,"anchorStyleFunc");m.addGetterSetter(Y,"shouldOverdrawWholeArea",!1);m.addGetterSetter(Y,"useSingleNodeRotation",!0);m.backCompat(Y,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Ee extends P{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,E.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Ee.prototype.className="Wedge";Ee.prototype._centroid=!0;Ee.prototype._attrsAffectingSize=["radius"];ne(Ee);m.addGetterSetter(Ee,"radius",0,I());m.addGetterSetter(Ee,"angle",0,I());m.addGetterSetter(Ee,"clockwise",!1);m.backCompat(Ee,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function yn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const za=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],Fa=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function Va(a,e){const t=a.data,i=a.width,n=a.height;let s,r,o,l,h,c,d,u,f,p,y,S,C,T,b,w,k,_,O,A;const M=e+e+1,D=i-1,z=n-1,B=e+1,W=B*(B+1)/2,F=new yn,H=za[e],R=Fa[e];let K=null,G=F,U=null,Z=null;for(let q=1;q<M;q++)G=G.next=new yn,q===B&&(K=G);G.next=F,o=r=0;for(let q=0;q<n;q++){S=C=T=b=l=h=c=d=0,u=B*(w=t[r]),f=B*(k=t[r+1]),p=B*(_=t[r+2]),y=B*(O=t[r+3]),l+=W*w,h+=W*k,c+=W*_,d+=W*O,G=F;for(let se=0;se<B;se++)G.r=w,G.g=k,G.b=_,G.a=O,G=G.next;for(let se=1;se<B;se++)s=r+((D<se?D:se)<<2),l+=(G.r=w=t[s])*(A=B-se),h+=(G.g=k=t[s+1])*A,c+=(G.b=_=t[s+2])*A,d+=(G.a=O=t[s+3])*A,S+=w,C+=k,T+=_,b+=O,G=G.next;U=F,Z=K;for(let se=0;se<i;se++)t[r+3]=O=d*H>>R,O!==0?(O=255/O,t[r]=(l*H>>R)*O,t[r+1]=(h*H>>R)*O,t[r+2]=(c*H>>R)*O):t[r]=t[r+1]=t[r+2]=0,l-=u,h-=f,c-=p,d-=y,u-=U.r,f-=U.g,p-=U.b,y-=U.a,s=o+((s=se+e+1)<D?s:D)<<2,S+=U.r=t[s],C+=U.g=t[s+1],T+=U.b=t[s+2],b+=U.a=t[s+3],l+=S,h+=C,c+=T,d+=b,U=U.next,u+=w=Z.r,f+=k=Z.g,p+=_=Z.b,y+=O=Z.a,S-=w,C-=k,T-=_,b-=O,Z=Z.next,r+=4;o+=i}for(let q=0;q<i;q++){C=T=b=S=h=c=d=l=0,r=q<<2,u=B*(w=t[r]),f=B*(k=t[r+1]),p=B*(_=t[r+2]),y=B*(O=t[r+3]),l+=W*w,h+=W*k,c+=W*_,d+=W*O,G=F;for(let he=0;he<B;he++)G.r=w,G.g=k,G.b=_,G.a=O,G=G.next;let se=i;for(let he=1;he<=e;he++)r=se+q<<2,l+=(G.r=w=t[r])*(A=B-he),h+=(G.g=k=t[r+1])*A,c+=(G.b=_=t[r+2])*A,d+=(G.a=O=t[r+3])*A,S+=w,C+=k,T+=_,b+=O,G=G.next,he<z&&(se+=i);r=q,U=F,Z=K;for(let he=0;he<n;he++)s=r<<2,t[s+3]=O=d*H>>R,O>0?(O=255/O,t[s]=(l*H>>R)*O,t[s+1]=(h*H>>R)*O,t[s+2]=(c*H>>R)*O):t[s]=t[s+1]=t[s+2]=0,l-=u,h-=f,c-=p,d-=y,u-=U.r,f-=U.g,p-=U.b,y-=U.a,s=q+((s=he+B)<z?s:z)*i<<2,l+=S+=U.r=t[s],h+=C+=U.g=t[s+1],c+=T+=U.b=t[s+2],d+=b+=U.a=t[s+3],U=U.next,u+=w=Z.r,f+=k=Z.g,p+=_=Z.b,y+=O=Z.a,S-=w,C-=k,T-=_,b-=O,Z=Z.next,r+=i}}const Wa=function(e){const t=Math.round(this.blurRadius());t>0&&Va(e,t)};m.addGetterSetter(x,"blurRadius",0,I(),m.afterSetFilter);const Ya=function(a){const e=this.brightness()*255,t=a.data,i=t.length;for(let n=0;n<i;n+=4)t[n]+=e,t[n+1]+=e,t[n+2]+=e};m.addGetterSetter(x,"brightness",0,I(),m.afterSetFilter);const Xa=function(a){const e=this.brightness(),t=a.data,i=t.length;for(let n=0;n<i;n+=4)t[n]=Math.min(255,t[n]*e),t[n+1]=Math.min(255,t[n+1]*e),t[n+2]=Math.min(255,t[n+2]*e)},Ua=function(a){const e=Math.pow((this.contrast()+100)/100,2),t=a.data,i=t.length;let n=150,s=150,r=150;for(let o=0;o<i;o+=4)n=t[o],s=t[o+1],r=t[o+2],n/=255,n-=.5,n*=e,n+=.5,n*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,r/=255,r-=.5,r*=e,r+=.5,r*=255,n=n<0?0:n>255?255:n,s=s<0?0:s>255?255:s,r=r<0?0:r>255?255:r,t[o]=n,t[o+1]=s,t[o+2]=r};m.addGetterSetter(x,"contrast",0,I(),m.afterSetFilter);const $a=function(a){var e,t,i,n,s,r,o,l,h;const c=a.data,d=a.width,u=a.height,f=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),p=Math.min(1,Math.max(0,(n=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&n!==void 0?n:.5)),S=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(r=(s=this.embossDirection)===null||s===void 0?void 0:s.call(this))!==null&&r!==void 0?r:"top-left"])!==null&&o!==void 0?o:315,C=!!((h=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&h!==void 0&&h),T=f*10,b=p*255,w=S*Math.PI/180,k=Math.cos(w),_=Math.sin(w),O=128/1020*T,A=new Uint8ClampedArray(c),M=new Float32Array(d*u);for(let F=0,H=0;H<c.length;H+=4,F++)M[F]=.2126*A[H]+.7152*A[H+1]+.0722*A[H+2];const D=[-1,0,1,-2,0,2,-1,0,1],z=[-1,-2,-1,0,0,0,1,2,1],B=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],W=F=>F<0?0:F>255?255:F;for(let F=1;F<u-1;F++)for(let H=1;H<d-1;H++){const R=F*d+H;let K=0,G=0;K+=M[R+B[0]]*D[0],G+=M[R+B[0]]*z[0],K+=M[R+B[1]]*D[1],G+=M[R+B[1]]*z[1],K+=M[R+B[2]]*D[2],G+=M[R+B[2]]*z[2],K+=M[R+B[3]]*D[3],G+=M[R+B[3]]*z[3],K+=M[R+B[5]]*D[5],G+=M[R+B[5]]*z[5],K+=M[R+B[6]]*D[6],G+=M[R+B[6]]*z[6],K+=M[R+B[7]]*D[7],G+=M[R+B[7]]*z[7],K+=M[R+B[8]]*D[8],G+=M[R+B[8]]*z[8];const U=k*K+_*G,Z=W(b+U*O),q=R*4;if(C){const se=Z-b;c[q]=W(A[q]+se),c[q+1]=W(A[q+1]+se),c[q+2]=W(A[q+2]+se),c[q+3]=A[q+3]}else c[q]=c[q+1]=c[q+2]=Z,c[q+3]=A[q+3]}for(let F=0;F<d;F++){let H=F*4,R=((u-1)*d+F)*4;c[H]=A[H],c[H+1]=A[H+1],c[H+2]=A[H+2],c[H+3]=A[H+3],c[R]=A[R],c[R+1]=A[R+1],c[R+2]=A[R+2],c[R+3]=A[R+3]}for(let F=1;F<u-1;F++){let H=F*d*4,R=(F*d+(d-1))*4;c[H]=A[H],c[H+1]=A[H+1],c[H+2]=A[H+2],c[H+3]=A[H+3],c[R]=A[R],c[R+1]=A[R+1],c[R+2]=A[R+2],c[R+3]=A[R+3]}return a};m.addGetterSetter(x,"embossStrength",.5,I(),m.afterSetFilter);m.addGetterSetter(x,"embossWhiteLevel",.5,I(),m.afterSetFilter);m.addGetterSetter(x,"embossDirection","top-left",void 0,m.afterSetFilter);m.addGetterSetter(x,"embossBlend",!1,void 0,m.afterSetFilter);function ui(a,e,t,i,n){const s=t-e,r=n-i;if(s===0)return i+r/2;if(r===0)return i;let o=(a-e)/s;return o=r*o+i,o}const qa=function(a){const e=a.data,t=e.length;let i=e[0],n=i,s,r=e[1],o=r,l,h=e[2],c=h,d;const u=this.enhance();if(u===0)return;for(let b=0;b<t;b+=4)s=e[b+0],s<i?i=s:s>n&&(n=s),l=e[b+1],l<r?r=l:l>o&&(o=l),d=e[b+2],d<h?h=d:d>c&&(c=d);n===i&&(n=255,i=0),o===r&&(o=255,r=0),c===h&&(c=255,h=0);let f,p,y,S,C,T;if(u>0)f=n+u*(255-n),p=i-u*(i-0),y=o+u*(255-o),S=r-u*(r-0),C=c+u*(255-c),T=h-u*(h-0);else{const b=(n+i)*.5;f=n+u*(n-b),p=i+u*(i-b);const w=(o+r)*.5;y=o+u*(o-w),S=r+u*(r-w);const k=(c+h)*.5;C=c+u*(c-k),T=h+u*(h-k)}for(let b=0;b<t;b+=4)e[b+0]=ui(e[b+0],i,n,p,f),e[b+1]=ui(e[b+1],r,o,S,y),e[b+2]=ui(e[b+2],h,c,T,C)};m.addGetterSetter(x,"enhance",0,I(),m.afterSetFilter);const Ka=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4){const n=.34*e[i]+.5*e[i+1]+.16*e[i+2];e[i]=n,e[i+1]=n,e[i+2]=n}};m.addGetterSetter(x,"hue",0,I(),m.afterSetFilter);m.addGetterSetter(x,"saturation",0,I(),m.afterSetFilter);m.addGetterSetter(x,"luminance",0,I(),m.afterSetFilter);const ja=function(a){const e=a.data,t=e.length,i=1,n=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,r=this.luminance()*127,o=i*n*Math.cos(s*Math.PI/180),l=i*n*Math.sin(s*Math.PI/180),h=.299*i+.701*o+.167*l,c=.587*i-.587*o+.33*l,d=.114*i-.114*o-.497*l,u=.299*i-.299*o-.328*l,f=.587*i+.413*o+.035*l,p=.114*i-.114*o+.293*l,y=.299*i-.3*o+1.25*l,S=.587*i-.586*o-1.05*l,C=.114*i+.886*o-.2*l;let T,b,w,k;for(let _=0;_<t;_+=4)T=e[_+0],b=e[_+1],w=e[_+2],k=e[_+3],e[_+0]=h*T+c*b+d*w+r,e[_+1]=u*T+f*b+p*w+r,e[_+2]=y*T+S*b+C*w+r,e[_+3]=k},Za=function(a){const e=a.data,t=e.length,i=Math.pow(2,this.value()),n=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,r=i*n*Math.cos(s*Math.PI/180),o=i*n*Math.sin(s*Math.PI/180),l=.299*i+.701*r+.167*o,h=.587*i-.587*r+.33*o,c=.114*i-.114*r-.497*o,d=.299*i-.299*r-.328*o,u=.587*i+.413*r+.035*o,f=.114*i-.114*r+.293*o,p=.299*i-.3*r+1.25*o,y=.587*i-.586*r-1.05*o,S=.114*i+.886*r-.2*o;for(let C=0;C<t;C+=4){const T=e[C+0],b=e[C+1],w=e[C+2],k=e[C+3];e[C+0]=l*T+h*b+c*w,e[C+1]=d*T+u*b+f*w,e[C+2]=p*T+y*b+S*w,e[C+3]=k}};m.addGetterSetter(x,"hue",0,I(),m.afterSetFilter);m.addGetterSetter(x,"saturation",0,I(),m.afterSetFilter);m.addGetterSetter(x,"value",0,I(),m.afterSetFilter);const Ja=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4)e[i]=255-e[i],e[i+1]=255-e[i+1],e[i+2]=255-e[i+2]},Qa=function(a,e,t){const i=a.data,n=e.data,s=a.width,r=a.height,o=t.polarCenterX||s/2,l=t.polarCenterY||r/2;let h=Math.sqrt(o*o+l*l),c=s-o,d=r-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const f=r,p=s,y=360/p*Math.PI/180;for(let S=0;S<p;S+=1){const C=Math.sin(S*y),T=Math.cos(S*y);for(let b=0;b<f;b+=1){c=Math.floor(o+h*b/f*T),d=Math.floor(l+h*b/f*C);let w=(d*s+c)*4;const k=i[w+0],_=i[w+1],O=i[w+2],A=i[w+3];w=(S+b*s)*4,n[w+0]=k,n[w+1]=_,n[w+2]=O,n[w+3]=A}}},eo=function(a,e,t){const i=a.data,n=e.data,s=a.width,r=a.height,o=t.polarCenterX||s/2,l=t.polarCenterY||r/2;let h=Math.sqrt(o*o+l*l),c=s-o,d=r-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const f=r,p=s,y=0;let S,C;for(c=0;c<s;c+=1)for(d=0;d<r;d+=1){const T=c-o,b=d-l,w=Math.sqrt(T*T+b*b)*f/h;let k=(Math.atan2(b,T)*180/Math.PI+360+y)%360;k=k*p/360,S=Math.floor(k),C=Math.floor(w);let _=(C*s+S)*4;const O=i[_+0],A=i[_+1],M=i[_+2],D=i[_+3];_=(d*s+c)*4,n[_+0]=O,n[_+1]=A,n[_+2]=M,n[_+3]=D}},to=function(a){const e=a.width,t=a.height;let i,n,s,r,o,l,h,c,d,u,f=Math.round(this.kaleidoscopePower());const p=Math.round(this.kaleidoscopeAngle()),y=Math.floor(e*(p%360)/360);if(f<1)return;const S=v.createCanvasElement();S.width=e,S.height=t;const C=S.getContext("2d").getImageData(0,0,e,t);v.releaseCanvas(S),Qa(a,C,{polarCenterX:e/2,polarCenterY:t/2});let T=e/Math.pow(2,f);for(;T<=8;)T=T*2,f-=1;T=Math.ceil(T);let b=T,w=0,k=b,_=1;for(y+T>e&&(w=b,k=0,_=-1),n=0;n<t;n+=1)for(i=w;i!==k;i+=_)s=Math.round(i+y)%e,d=(e*n+s)*4,o=C.data[d+0],l=C.data[d+1],h=C.data[d+2],c=C.data[d+3],u=(e*n+i)*4,C.data[u+0]=o,C.data[u+1]=l,C.data[u+2]=h,C.data[u+3]=c;for(n=0;n<t;n+=1)for(b=Math.floor(T),r=0;r<f;r+=1){for(i=0;i<b+1;i+=1)d=(e*n+i)*4,o=C.data[d+0],l=C.data[d+1],h=C.data[d+2],c=C.data[d+3],u=(e*n+b*2-i-1)*4,C.data[u+0]=o,C.data[u+1]=l,C.data[u+2]=h,C.data[u+3]=c;b*=2}eo(C,a,{})};m.addGetterSetter(x,"kaleidoscopePower",2,I(),m.afterSetFilter);m.addGetterSetter(x,"kaleidoscopeAngle",0,I(),m.afterSetFilter);function Vt(a,e,t){let i=(t*a.width+e)*4;const n=[];return n.push(a.data[i++],a.data[i++],a.data[i++],a.data[i++]),n}function ut(a,e){return Math.sqrt(Math.pow(a[0]-e[0],2)+Math.pow(a[1]-e[1],2)+Math.pow(a[2]-e[2],2))}function io(a){const e=[0,0,0];for(let t=0;t<a.length;t++)e[0]+=a[t][0],e[1]+=a[t][1],e[2]+=a[t][2];return e[0]/=a.length,e[1]/=a.length,e[2]/=a.length,e}function no(a,e){const t=Vt(a,0,0),i=Vt(a,a.width-1,0),n=Vt(a,0,a.height-1),s=Vt(a,a.width-1,a.height-1),r=e||10;if(ut(t,i)<r&&ut(i,s)<r&&ut(s,n)<r&&ut(n,t)<r){const o=io([i,t,s,n]),l=[];for(let h=0;h<a.width*a.height;h++){const c=ut(o,[a.data[h*4],a.data[h*4+1],a.data[h*4+2]]);l[h]=c<r?0:255}return l}}function so(a,e){for(let t=0;t<a.width*a.height;t++)a.data[4*t+3]=e[t]}function ro(a,e,t){const i=[1,1,1,1,0,1,1,1,1],n=Math.round(Math.sqrt(i.length)),s=Math.floor(n/2),r=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const h=o*e+l;let c=0;for(let d=0;d<n;d++)for(let u=0;u<n;u++){const f=o+d-s,p=l+u-s;if(f>=0&&f<t&&p>=0&&p<e){const y=f*e+p,S=i[d*n+u];c+=a[y]*S}}r[h]=c===255*8?255:0}return r}function ao(a,e,t){const i=[1,1,1,1,1,1,1,1,1],n=Math.round(Math.sqrt(i.length)),s=Math.floor(n/2),r=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const h=o*e+l;let c=0;for(let d=0;d<n;d++)for(let u=0;u<n;u++){const f=o+d-s,p=l+u-s;if(f>=0&&f<t&&p>=0&&p<e){const y=f*e+p,S=i[d*n+u];c+=a[y]*S}}r[h]=c>=255*4?255:0}return r}function oo(a,e,t){const i=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],n=Math.round(Math.sqrt(i.length)),s=Math.floor(n/2),r=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const h=o*e+l;let c=0;for(let d=0;d<n;d++)for(let u=0;u<n;u++){const f=o+d-s,p=l+u-s;if(f>=0&&f<t&&p>=0&&p<e){const y=f*e+p,S=i[d*n+u];c+=a[y]*S}}r[h]=c}return r}const lo=function(a){const e=this.threshold();let t=no(a,e);return t&&(t=ro(t,a.width,a.height),t=ao(t,a.width,a.height),t=oo(t,a.width,a.height),so(a,t)),a};m.addGetterSetter(x,"threshold",0,I(),m.afterSetFilter);const ho=function(a){const e=this.noise()*255,t=a.data,i=t.length,n=e/2;for(let s=0;s<i;s+=4)t[s+0]+=n-2*n*Math.random(),t[s+1]+=n-2*n*Math.random(),t[s+2]+=n-2*n*Math.random()};m.addGetterSetter(x,"noise",.2,I(),m.afterSetFilter);const co=function(a){let e=Math.ceil(this.pixelSize()),t=a.width,i=a.height,n=Math.ceil(t/e),s=Math.ceil(i/e),r=a.data;if(e<=0){v.error("pixelSize value can not be <= 0");return}for(let o=0;o<n;o+=1)for(let l=0;l<s;l+=1){let h=0,c=0,d=0,u=0;const f=o*e,p=f+e,y=l*e,S=y+e;let C=0;for(let T=f;T<p;T+=1)if(!(T>=t))for(let b=y;b<S;b+=1){if(b>=i)continue;const w=(t*b+T)*4;h+=r[w+0],c+=r[w+1],d+=r[w+2],u+=r[w+3],C+=1}h=h/C,c=c/C,d=d/C,u=u/C;for(let T=f;T<p;T+=1)if(!(T>=t))for(let b=y;b<S;b+=1){if(b>=i)continue;const w=(t*b+T)*4;r[w+0]=h,r[w+1]=c,r[w+2]=d,r[w+3]=u}}};m.addGetterSetter(x,"pixelSize",8,I(),m.afterSetFilter);const uo=function(a){const e=Math.round(this.levels()*254)+1,t=a.data,i=t.length,n=255/e;for(let s=0;s<i;s+=1)t[s]=Math.floor(t[s]/n)*n};m.addGetterSetter(x,"levels",.5,I(),m.afterSetFilter);const go=function(a){const e=a.data,t=e.length,i=this.red(),n=this.green(),s=this.blue();for(let r=0;r<t;r+=4){const o=(.34*e[r]+.5*e[r+1]+.16*e[r+2])/255;e[r]=o*i,e[r+1]=o*n,e[r+2]=o*s,e[r+3]=e[r+3]}};m.addGetterSetter(x,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(x,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(x,"blue",0,$n,m.afterSetFilter);const po=function(a){const e=a.data,t=e.length,i=this.red(),n=this.green(),s=this.blue(),r=this.alpha();for(let o=0;o<t;o+=4){const l=1-r;e[o]=i*r+e[o]*l,e[o+1]=n*r+e[o+1]*l,e[o+2]=s*r+e[o+2]*l}};m.addGetterSetter(x,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(x,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(x,"blue",0,$n,m.afterSetFilter);m.addGetterSetter(x,"alpha",1,function(a){return this._filterUpToDate=!1,a>1?1:a<0?0:a});const fo=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4){const n=e[i+0],s=e[i+1],r=e[i+2];e[i+0]=Math.min(255,n*.393+s*.769+r*.189),e[i+1]=Math.min(255,n*.349+s*.686+r*.168),e[i+2]=Math.min(255,n*.272+s*.534+r*.131)}},mo=function(a){const t=a.data;for(let i=0;i<t.length;i+=4){const n=t[i],s=t[i+1],r=t[i+2];.2126*n+.7152*s+.0722*r>=128&&(t[i]=255-n,t[i+1]=255-s,t[i+2]=255-r)}return a},yo=function(a){const e=this.threshold()*255,t=a.data,i=t.length;for(let n=0;n<i;n+=1)t[n]=t[n]<e?0:255};m.addGetterSetter(x,"threshold",.5,I(),m.afterSetFilter);const X=an.Util._assign(an,{Arc:Ie,Arrow:$e,Circle:at,Ellipse:Ge,Image:ye,Label:Fi,Tag:qe,Line:Ae,Path:ee,Rect:Et,RegularPolygon:He,Ring:Ke,Sprite:we,Star:Ne,Text:te,TextPath:re,Transformer:Y,Wedge:Ee,Filters:{Blur:Wa,Brightness:Xa,Brighten:Ya,Contrast:Ua,Emboss:$a,Enhance:qa,Grayscale:Ka,HSL:ja,HSV:Za,Invert:Ja,Kaleidoscope:to,Mask:lo,Noise:ho,Pixelate:co,Posterize:uo,RGB:go,RGBA:po,Sepia:fo,Solarize:mo,Threshold:yo}}),Sn={debug:10,info:20,warn:30,error:40},Wt={enabled:!0,level:"warn",moduleLevels:{}},Cn=400;function So(a,e){return a.moduleLevels[e]??a.level}function Fe(a,e,t){if(!a.enabled)return!1;const i=So(a,t);return Sn[e]>=Sn[i]}function vn(a){if(!a||typeof a!="object")return null;const e="clientX"in a||"clientY"in a,t="deltaX"in a||"deltaY"in a,i="shiftKey"in a||"metaKey"in a||"ctrlKey"in a||"altKey"in a;return!e&&!t&&!i?null:{type:typeof a.type=="string"?a.type:void 0,clientX:typeof a.clientX=="number"?a.clientX:void 0,clientY:typeof a.clientY=="number"?a.clientY:void 0,button:typeof a.button=="number"?a.button:void 0,buttons:typeof a.buttons=="number"?a.buttons:void 0,deltaX:typeof a.deltaX=="number"?a.deltaX:void 0,deltaY:typeof a.deltaY=="number"?a.deltaY:void 0,shiftKey:!!a.shiftKey,metaKey:!!a.metaKey,ctrlKey:!!a.ctrlKey,altKey:!!a.altKey}}function Co(a){if(a===void 0)return;const e=vn(a);if(e)return e;if(a&&typeof a=="object"&&"evt"in a){const t=vn(a.evt);if(t)return{...a,evt:t}}return a}function vo(a,e,t,i){const n=Co(i);n===void 0?a(`${e} ${t}`):a(`${e} ${t}`,n)}class L{static setConfig(e){if(!e){this.config={...Wt};return}this.config={enabled:e.enabled??Wt.enabled,level:e.level??Wt.level,moduleLevels:e.moduleLevels??{}}}static debug(e,t,i){Fe(this.config,"debug",e)&&this.emit("debug",e,t,i)}static debugLazy(e,t,i){if(!Fe(this.config,"debug",e))return;const n=t(),s=i?i():void 0;this.emit("debug",e,n,s)}static info(e,t,i){Fe(this.config,"info",e)&&this.emit("info",e,t,i)}static infoLazy(e,t,i){if(!Fe(this.config,"info",e))return;const n=t(),s=i?i():void 0;this.emit("info",e,n,s)}static warn(e,t,i){Fe(this.config,"warn",e)&&this.emit("warn",e,t,i)}static warnLazy(e,t,i){if(!Fe(this.config,"warn",e))return;const n=t(),s=i?i():void 0;this.emit("warn",e,n,s)}static error(e,t,i){Fe(this.config,"error",e)&&this.emit("error",e,t,i)}static setDedupeWindowMs(e){this.dedupeWindowMs=Number.isFinite(e)&&e>=0?e:Cn}static emit(e,t,i,n){const s=Date.now(),r=`${e}:${t}:${i}`,o=this.dedupeState.get(r);if(o&&s-o.lastPrintedAt<this.dedupeWindowMs){o.suppressed+=1;return}const l=(o==null?void 0:o.suppressed)??0,h=l>0?`${i} (+${l} repeats)`:i;this.dedupeState.set(r,{lastPrintedAt:s,suppressed:0});const c=`[${e.toUpperCase()}] [${t}]`,d=this.resolveConsoleMethod(e);vo(d,c,h,n)}static resolveConsoleMethod(e){return e==="debug"?console.log.bind(console):e==="info"?console.info.bind(console):e==="warn"?console.warn.bind(console):console.error.bind(console)}}g(L,"config",{...Wt}),g(L,"dedupeWindowMs",Cn),g(L,"dedupeState",new Map);const Ct="media-editor-track.preview-load-trace.v1",To=18e4,bo=4,wo=20,ko=40;function Po(){const a=Math.random().toString(36).slice(2,10);return`preview-${Date.now().toString(36)}-${a}`}function _o(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function Ps(a){if(!a||typeof a!="object")return!1;const e=Object.getPrototypeOf(a);return e===Object.prototype||e===null}function Ai(a,e,t){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean")return a??null;if(typeof a=="bigint")return a.toString();if(a instanceof Error)return{name:a.name,message:a.message,stack:a.stack??null};if(e>=bo)return"[max-depth]";if(Array.isArray(a))return a.slice(0,wo).map(i=>Ai(i,e+1,t));if(typeof a=="object"){if(t.has(a))return"[circular]";if(t.add(a),"tagName"in a&&typeof a.tagName=="string")return{tagName:a.tagName};if(!Ps(a))return String(a);const i={};for(const n of Object.keys(a).slice(0,ko))i[n]=Ai(a[n],e+1,t);return i}return String(a)}function _s(a){if(!a)return null;const e=Ai(a,0,new WeakSet);return Ps(e)?e:{value:e}}function tt(a=[]){return{version:1,currentSessionId:Po(),updatedAt:Date.now(),entries:a.slice(-400)}}function xs(){try{return typeof globalThis.localStorage<"u"?globalThis.localStorage:null}catch{return null}}function xo(a){if(!a||typeof a!="object")return null;const e=a;return typeof e.id!="string"||typeof e.sessionId!="string"||typeof e.createdAt!="number"||typeof e.isoTime!="string"||!["debug","info","warn","error"].includes(e.level)||typeof e.event!="string"?null:{id:e.id,sessionId:e.sessionId,createdAt:e.createdAt,isoTime:e.isoTime,perfTimeMs:typeof e.perfTimeMs=="number"?e.perfTimeMs:null,level:e.level,event:e.event,data:_s(e.data)}}function Io(){const a=xs();if(!a)return tt();try{const e=a.getItem(Ct);if(!e)return tt();const t=JSON.parse(e);if(t.version!==1||!Array.isArray(t.entries))return tt();const i=t.entries.map(n=>xo(n)).filter(n=>!!n);return{...tt(i),updatedAt:typeof t.updatedAt=="number"?t.updatedAt:Date.now()}}catch{return tt()}}function Tn(a){let e=a.entries.slice(-400);for(;e.length>0;){const t={...a,entries:e};if(JSON.stringify(t).length<=To)return t;e=e.slice(Math.ceil(e.length/8))}return{...a,entries:[]}}class Ao{constructor(){g(this,"state",Io());g(this,"listeners",new Set);var e,t;this.append({level:"info",event:"session.started",data:{href:typeof((e=globalThis.location)==null?void 0:e.href)=="string"?globalThis.location.href:null,userAgent:typeof((t=globalThis.navigator)==null?void 0:t.userAgent)=="string"?globalThis.navigator.userAgent:null}})}getStorageKey(){return Ct}getSnapshot(){return{storageKey:Ct,currentSessionId:this.state.currentSessionId,updatedAt:this.state.updatedAt,entries:[...this.state.entries]}}subscribe(e){return this.listeners.add(e),e(this.getSnapshot()),()=>{this.listeners.delete(e)}}append(e){const t=Date.now(),i={id:`${t}-${Math.random().toString(36).slice(2,8)}`,sessionId:this.state.currentSessionId,createdAt:t,isoTime:new Date(t).toISOString(),perfTimeMs:_o(),level:e.level,event:e.event,data:_s(e.data)};return this.state=Tn({...this.state,updatedAt:t,entries:[...this.state.entries,i]}),this.persist(),this.emit(),i}clear(){this.state=tt(),this.persist(),this.emit()}exportJson(e=200){const t=this.getSnapshot();return JSON.stringify({...t,exportedAt:new Date().toISOString(),exportedEntryCount:Math.min(e,t.entries.length),entries:t.entries.slice(-e)},null,2)}persist(){const e=xs();if(e)try{e.setItem(Ct,JSON.stringify(this.state))}catch{this.state=Tn({...this.state,entries:this.state.entries.slice(-Math.max(40,Math.floor(this.state.entries.length/2)))});try{e.setItem(Ct,JSON.stringify(this.state))}catch{}}}emit(){const e=this.getSnapshot();this.listeners.forEach(t=>t(e))}}const Eo=new Ao;class Ce{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={}}static renderClipCovers(e,t,i,n,s,r=!1){L.debugLazy("ClipCoverRenderer",()=>"renderClipCovers",()=>({videoSrc:s,coverCount:(t==null?void 0:t.length)??0,coverWidth:i,coverHeight:n}));const o=(e.getAttr(this.COVER_RENDER_VERSION_KEY)||0)+1;if(e.setAttr(this.COVER_RENDER_VERSION_KEY,o),!t||t.length===0){e.destroyChildren(),r||this.requestRender(e);return}const l=this.buildSegmentsDataSync(t,i,n,s);if(l){this.renderSegments(e,l,i,n),r||this.requestRender(e);return}r||(e.destroyChildren(),this.requestRender(e)),this.startRenderJob({coversGroup:e,coverSource:t,coverWidth:i,coverHeight:n,videoSrc:s,version:o})}static async startRenderJob(e){const{coversGroup:t,coverSource:i,coverWidth:n,coverHeight:s,videoSrc:r,version:o}=e,l=await this.buildSegmentsData(i,n,s,r);if(this.isRenderJobCurrent(t,o)){if(this.renderSegments(t,l,n,s),!this.isRenderJobCurrent(t,o)){t.destroyChildren();return}this.requestRender(t)}}static async buildSegmentsData(e,t,i,n){const s=e.length,r=n||e[0]||"",o=await this.getSafeKeyframeDimensions(r,e[0]),l=o.width/o.height,h=i*l,c=l>=1;let d;c?d=Math.min(s,Math.max(1,Math.floor(t/h))):d=Math.min(s,Math.max(1,Math.floor(t/this.MIN_IMAGE_DISPLAY_WIDTH)));const u=t/d,f=[];if(d===1)f.push(0);else for(let y=0;y<d;y++)f.push(Math.round(y*(s-1)/(d-1)));const p=[];for(let y=0;y<d;y++){const S=e[f[y]],C=await this.getSafeKeyframeDimensions(r,S),T=C.width/C.height;p.push({coverUrl:S,singleImageWidth:i*T,segmentStartX:y*u,segmentWidth:u})}return p}static buildSegmentsDataSync(e,t,i,n){const s=e.length,r=n||e[0]||"",o=this.getCachedKeyframeDimensions(r,e[0]);if(!o)return null;const l=o.width/o.height,h=i*l,c=l>=1;let d;c?d=Math.min(s,Math.max(1,Math.floor(t/h))):d=Math.min(s,Math.max(1,Math.floor(t/this.MIN_IMAGE_DISPLAY_WIDTH)));const u=t/d,f=[];if(d===1)f.push(0);else for(let y=0;y<d;y++)f.push(Math.round(y*(s-1)/(d-1)));const p=[];for(let y=0;y<d;y++){const S=e[f[y]],C=this.getCachedKeyframeDimensions(r,S);if(!C)return null;const T=C.width/C.height;p.push({coverUrl:S,singleImageWidth:i*T,segmentStartX:y*u,segmentWidth:u})}return p}static requestRender(e){var i,n;const t=(i=e.getLayer)==null?void 0:i.call(e);if((n=t==null?void 0:t.getStage)!=null&&n.call(t))try{e.draw(),t.batchDraw()}catch{}}static isRenderJobCurrent(e,t){return e.getAttr(this.COVER_RENDER_VERSION_KEY)===t}static renderSegments(e,t,i,n){e.destroyChildren(),e.clip({x:0,y:0,width:i,height:n});for(const{coverUrl:s,singleImageWidth:r,segmentStartX:o,segmentWidth:l}of t){const h=Math.max(r,.01),c=Math.max(1,Math.ceil(l/h)),d=Math.max(r,.01),u=this.getCachedImage(s),f=new X.Group({x:o,y:0,clip:{x:0,y:0,width:l,height:n},name:"cover-segment"});u.src||(u.src=s);for(let p=0;p<c;p++){const y=p*d,S=l-y,C=i-o-y,T=Math.min(d,S,C);if(T<=0)continue;const b=new X.Image({image:u,cornerRadius:2,name:"cover-image"});b.x(y),b.y(0),b.width(T),b.height(n),f.add(b)}e.add(f)}}static async getSafeKeyframeDimensions(e,t){try{const i=await this.getKeyframeDimensions(e,t);if(i!=null&&i.width&&(i!=null&&i.height))return i}catch{}return this.DEFAULT_DIMENSIONS}static getKeyframeDimensions(e,t){const i=t||e;if(this.keyframeDimensionsCache[i])return Promise.resolve(this.keyframeDimensionsCache[i]);if(this.keyframeDimensionsPromiseCache[i])return this.keyframeDimensionsPromiseCache[i];const n=new Promise(s=>{const r=this.getCachedImage(t);if(r.complete&&r.width>0){const l={width:r.width,height:r.height};this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],s(l);return}const o=l=>{this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],s(l)};r.onload=()=>{const l={width:r.width,height:r.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},r.onerror=()=>{o(this.DEFAULT_DIMENSIONS)},r.src||(r.src=t)});return this.keyframeDimensionsPromiseCache[i]=n,n}static getCachedKeyframeDimensions(e,t){const i=t||e,n=this.keyframeDimensionsCache[i];if(n!=null&&n.width&&(n!=null&&n.height))return n;const s=this.imageCache[t];if(s!=null&&s.complete&&s.width>0&&s.height>0){const r={width:s.width,height:s.height};return this.keyframeDimensionsCache[i]=r,r}return null}static getCachedImage(e){const t=this.imageCache[e];if(t)return t;const i=new Image;return this.imageCache[e]=i,this.checkAndTrimCache(),i}static checkAndTrimCache(){const e=Object.keys(this.imageCache);if(e.length<=this.MAX_CACHE_SIZE)return;const t=e.length-this.MAX_CACHE_SIZE,i=e.filter(r=>{const o=this.imageCache[r];return o&&!o.complete}),n=e.filter(r=>!i.includes(r));let s=0;for(const r of i){if(s>=t)break;delete this.imageCache[r],s++}for(const r of n){if(s>=t)break;delete this.imageCache[r],s++}}}g(Ce,"MIN_IMAGE_DISPLAY_WIDTH",24),g(Ce,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),g(Ce,"MAX_CACHE_SIZE",1e3),g(Ce,"DEFAULT_DIMENSIONS",{width:160,height:90}),g(Ce,"keyframeDimensionsCache",{}),g(Ce,"keyframeDimensionsPromiseCache",{}),g(Ce,"imageCache",{});const oe=3,bn=10,Mo=8,Lo=8,Ro=10,gi=4,wn=14,Is=10,Do=[4,10,14,10,4],kn=[3,7,11,15,11,7,3],Vi=28,Oo=14,As=8,Bo=[4,9,14,9,4];function Te(a,e,t,i,n="#ffffff",s="#000000",r=1){return new X.Rect({x:a,y:e,width:t,height:i,fill:n,stroke:s,strokeWidth:r})}function Es(a,e,t,i=12,n="Arial",s="#000000",r="left",o="top"){return new X.Text({text:a,x:e,y:t,fontSize:i,fontFamily:n,fill:s,align:r,verticalAlign:o})}function xe(a=0,e=0){return new X.Group({x:a,y:e})}function Wi(a,e,t,i){if(i){a.add(new X.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),a.add(new X.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}a.add(new X.Rect({x:0,y:0,width:oe,height:t,name:"clip-resize-left"})),a.add(new X.Rect({x:e-oe,y:0,width:oe,height:t,name:"clip-resize-right"}))}function Go(a,e,t,i){const n=a.findOne(".clip-resize-left"),s=a.findOne(".clip-resize-right");return!n||!s?!1:(n.x(0),n.y(0),n.width(oe),n.height(t),s.x(e-oe),s.y(0),s.width(oe),s.height(t),!0)}function Ms(a,e,t){return t==="audio"?{background:e?a.clipSelectedBackground||a.audioClipBackground||a.clipBackground:a.audioClipBackground||a.clipBackground,label:e?a.clipSelectedName||a.audioClipText||a.clipName:a.audioClipText||a.clipName,accent:e?a.clipSelectedHandle||a.audioClipAccent||a.clipHandle:a.audioClipAccent||a.clipHandle,coverBackground:a.clipCoverBackground||"#333333"}:{background:e&&a.clipSelectedBackground||a.clipBackground,label:e&&a.clipSelectedName||a.clipName,accent:e&&a.clipSelectedHandle||a.clipHandle,coverBackground:e?a.clipSelectedCoverBackground||a.clipCoverBackground||"#FFF2A0":a.clipCoverBackground||"#FFF2A0"}}function Ho(a,e,t,i){const n=Te(0,0,e,t,i.background,"transparent",0);n.cornerRadius(Math.min(4,Math.floor(e/2))),n.name("clip-background"),a.add(n),Wi(a,e,t,!0)}function No(a,e,t){const i=Te(0,0,e.width,e.height,t.background,"transparent",0);i.cornerRadius(4),i.name("clip-background"),a.add(i),Wi(a,e.width,e.height,!1);const n=15,s=e.height-n-4,r=e.width-oe*2,o=xe(oe,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:r,height:s}),a.add(o);const l=Te(0,0,r,s,t.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const h=xe(0,0);h.name("clip-covers-group"),o.add(h),Ce.renderClipCovers(h,e.thumbnails??[],r,s,e.videoSrc,e.deferCoverRender);const c=r>=120?Vi+As:0,d=Es(`${e.clipName} ${N.formatDuration(e.duration)}`,oe,e.height-n,Is,"Arial",t.label,"left","middle");d.ellipsis(!0),d.width(Math.max(0,r-c)),d.height(n),d.name("clip-label"),a.add(d),c>0&&Ls(a,e.width,e.height,t.label,e.hasSeparatedAudio)}function zo(a,e,t){const i=a.findOne(".clip-background"),n=a.findOne(".clip-cover-container"),s=a.findOne(".clip-cover-background"),r=a.findOne(".clip-covers-group"),o=a.findOne(".clip-label");if(!i||!n||!s||!r||!o||(i.width(e.width),i.height(e.height),i.fill(t.background),i.stroke("transparent"),i.strokeWidth(0),i.cornerRadius(4),!Go(a,e.width,e.height)))return!1;const l=15,h=e.height-l-4,c=e.width-oe*2;n.x(oe),n.y(2),n.clip({x:0,y:0,width:c,height:h}),s.width(c),s.height(h),s.fill(t.coverBackground),s.cornerRadius(2),Ce.renderClipCovers(r,e.thumbnails??[],c,h,e.videoSrc,e.deferCoverRender);const d=c>=120?Vi+As:0;o.text(`${e.clipName} ${N.formatDuration(e.duration)}`),o.x(oe),o.y(e.height-l),o.fill(t.label),o.width(Math.max(0,c-d)),o.height(l),o.ellipsis(!0);const u=a.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&Ls(a,e.width,e.height,t.label,e.hasSeparatedAudio),!0}function Ei(a,e,t,i,n,s,r){return a.name(n),e.forEach((o,l)=>{const h=Te(l*(s+r),Math.max(0,(t-o)/2),s,o,i,"transparent",0);h.cornerRadius(1),h.name(`${n}-bar-${l}`),a.add(h)}),e.length*s+Math.max(0,e.length-1)*r}function Ls(a,e,t,i,n){const s=xe(Math.max(oe,e-oe-Vi),Math.max(0,t-15));if(s.name("video-audio-status"),n){const c=xe(0,0);c.name("video-audio-status-separated");const d=Te(0,5,3,3,i,"transparent",0);d.cornerRadius(1.5),d.name("video-audio-status-separated-left-dot"),c.add(d);const u=Te(6,6,16,2,i,"transparent",0);u.cornerRadius(1),u.name("video-audio-status-separated-line"),c.add(u);const f=Te(25,5,3,3,i,"transparent",0);f.cornerRadius(1.5),f.name("video-audio-status-separated-right-dot"),c.add(f),s.add(c),a.add(s);return}const r=xe(2,0);r.name("video-audio-status-active");const o=Te(0,5,3,3,i,"transparent",0);o.cornerRadius(1.5),o.name("video-audio-status-active-left-dot"),r.add(o);const l=xe(5,0);Ei(l,Bo,Oo,i,"video-audio-status-active-bars",2,2),r.add(l);const h=Te(25,5,3,3,i,"transparent",0);h.cornerRadius(1.5),h.name("video-audio-status-active-right-dot"),r.add(h),s.add(r),a.add(s)}function Fo(a,e,t){const i=Te(0,0,e.width,e.height,t.background,"transparent",0);i.cornerRadius(6),i.name("clip-background"),a.add(i),Wi(a,e.width,e.height,!1);const n=oe+bn,s=Math.max(0,e.width-oe*2-bn*2),r=Mo,o=xe(n,r),l=Ei(o,Do,14,t.accent,"audio-clip-icon",2,2);a.add(o);const h=n+l+Ro,c=Math.max(0,n+s-h),d=3+gi,u=Math.min(kn.length,Math.floor((c+gi)/d));if(u>0){const p=xe(h,r);Ei(p,kn.slice(0,u),15,t.accent,"audio-clip-waveform",3,gi),a.add(p)}const f=Es(e.clipName,n,e.height-Lo-wn,Is,"Arial",t.label,"left","middle");f.ellipsis(!0),f.width(s),f.height(wn),f.name("clip-label"),a.add(f)}function Rs(a,e){const t=e.width<=It,i=Ms(e.theme,e.isSelected,e.clipType);if(a.destroyChildren(),t){Ho(a,e.width,e.height,i);return}if(e.clipType==="audio"){Fo(a,e,i);return}No(a,e,i)}function Vo(a,e){if(e.width<=It||e.clipType!=="video")return!1;const i=Ms(e.theme,e.isSelected,e.clipType);return zo(a,e,i)}function Wo(a,e,t,i,n,s,r,o=!1,l,h,c="video",d=!1,u=!1){const f=xe(a,e);return f.clip({x:0,y:0,width:t,height:i}),Rs(f,{width:t,height:i,clipName:n,duration:s,theme:r,isSelected:o,thumbnails:l,videoSrc:h,clipType:c,hasSeparatedAudio:d,deferCoverRender:u}),f}function Yo(a,e,t,i,n,s,r=!1,o,l,h="video",c=!1,d=!1){a.clip({x:0,y:0,width:e,height:t});const u={width:e,height:t,clipName:i,duration:n,theme:s??Jt,isSelected:r,thumbnails:o,videoSrc:l,clipType:h,hasSeparatedAudio:c,deferCoverRender:d};Vo(a,u)||Rs(a,u)}function Xo(a,e,t,i){return new X.Rect({x:a,y:e,width:t,height:i,stroke:"#50E3C2",strokeWidth:2,dash:[5,5],fillEnabled:!1})}function Mi(a,e="#000000",t=1){return new X.Line({points:a,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function Uo(a,e,t,i=12,n="Arial",s="#000000",r="left",o="top"){return new X.Text({text:a,x:e,y:t,fontSize:i,fontFamily:n,fill:s,align:r,verticalAlign:o})}function $o(a=0,e=0){return new X.Group({x:a,y:e})}function qo(a,e,t,i,n,s,r,o){const l=o||i,h=r==="major"?l*.6:l*.3,c=Mi([e,t,e,t+h],s.timeTick,r==="major"?1:.5);if(c.name("time-tick-line"),a.add(c),r==="major"){const d=t+h+5,u=Uo(N.formatTime(n),e,d,10,"Arial",s.timeText,"center");u.name("time-tick-text"),a.add(u)}}function Ko(a,e,t,i,n,s){const r=$o(e,t);for(let o=0;o<=i;o+=s)r.add(Mi([o,0,o,n],"#E0E0E0",.5));for(let o=0;o<=n;o+=s)r.add(Mi([0,o,i,o],"#E0E0E0",.5));a.add(r)}class ie{static createStage(e,t,i){return new X.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new X.Layer;return t.name(e),t}static createRect(e,t,i,n,s="#ffffff",r="#000000",o=1){return new X.Rect({x:e,y:t,width:i,height:n,fill:s,stroke:r,strokeWidth:o})}static createText(e,t,i,n=12,s="Arial",r="#000000",o="left",l="top"){return new X.Text({text:e,x:t,y:i,fontSize:n,fontFamily:s,fill:r,align:o,verticalAlign:l})}static createLine(e,t="#000000",i=1){return new X.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new X.Group({x:e,y:t})}static createPlayhead(e,t,i){const n=new X.Group({x:e,y:t}),s=this.createLine([0,0,0,i],"#FF0000",2),r=new X.RegularPolygon({x:0,y:-10,sides:3,radius:5,fill:"#FF0000",rotation:180});return n.add(s),n.add(r),n}static drawTimeTick(e,t,i,n,s,r,o,l){qo(e,t,i,n,s,r,o,l)}static drawGrid(e,t,i,n,s,r){Ko(e,t,i,n,s,r)}static clearImageCache(){Ce.clearImageCache()}static createClipGroup(e,t,i,n,s,r,o,l=!1,h,c,d="video",u=!1,f=!1){return Wo(e,t,i,n,s,r,o,l,h,c,d,u,f)}static updateClipGroup(e,t,i,n,s,r,o=!1,l,h,c="video",d=!1,u=!1){Yo(e,t,i,n,s,r,o,l,h,c,d,u)}static createSelectionEffect(e,t,i,n){return Xo(e,t,i,n)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}g(ie,"RESIZE_AREA_WIDTH",3);function Mt(a){let e=!1;return typeof window<"u"&&(window.addEventListener("mousemove",a.onPointerMove),window.addEventListener("mouseup",a.onPointerEnd),window.addEventListener("blur",a.onWindowBlur||a.onPointerEnd),e=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",a.onVisibilityChange),e=!0),e}function Lt(a){typeof window<"u"&&(window.removeEventListener("mousemove",a.onPointerMove),window.removeEventListener("mouseup",a.onPointerEnd),window.removeEventListener("blur",a.onWindowBlur||a.onPointerEnd)),typeof document<"u"&&document.removeEventListener("visibilitychange",a.onVisibilityChange)}class jo{constructor(e,t,i,n,s,r){g(this,"stage");g(this,"gridLayer");g(this,"config");g(this,"theme");g(this,"isDragging",!1);g(this,"startDragX",0);g(this,"scrollLeft",0);g(this,"timeScaleHeight",40);g(this,"onTimeChange");g(this,"onZoomChange");g(this,"onScrollChange");g(this,"animationFrameId",null);g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"isScrollbarDragging",!1);g(this,"scrollbarDragStartX",0);g(this,"scrollbarDragStartScrollLeft",0);g(this,"isPointerInsideTimeline",!1);g(this,"lastPointerXInTimeline",null);g(this,"scrollbarHeight",12);g(this,"scrollbarMargin",4);g(this,"handleGlobalPointerMove",e=>{this.isPointerSessionActive()&&this.handlePointerMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.finalizePointerInteraction()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finalizePointerInteraction()});g(this,"leftPadding",le);this.stage=e,this.gridLayer=t,this.onTimeChange=n,this.onZoomChange=s,this.onScrollChange=r,this.config={duration:i.duration||36e5,zoom:i.zoom||de.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:xt(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,i.timeScaleHeight&&(this.timeScaleHeight=i.timeScaleHeight),this.initEventListeners(),this.render()}initEventListeners(){this.stage.on("wheel",e=>{e.evt.preventDefault(),this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0;const{deltaX:t,deltaY:i,shiftKey:n}=e.evt,s=Math.abs(t)>0;if(n||s){const l=(s?t:i)*1.5,h=this.stage.width(),c=N.timeToPixels(this.config.duration,this.config.zoom),d=Math.max(0,c-h),u=Math.max(0,Math.min(d,this.scrollLeft+l));u!==this.scrollLeft&&this.animateHorizontalScroll(u)}else Math.abs(i)>0&&this.handleZoom(e)}),this.stage.on("click",e=>{let t=e.target.getLayer();const i=e.target.name()==="scrollbar-background"||e.target.name()==="scrollbar-thumb";t===this.gridLayer&&!i&&this.handleClick(e.evt.offsetX)}),this.stage.on("mousedown",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0;let t=e.target.getLayer(),i=e.target.name()==="scrollbar-background"||e.target.name()==="scrollbar-thumb";t===this.gridLayer&&e.target.name()==="scrollbar-thumb"?(this.isScrollbarDragging=!0,this.scrollbarDragStartX=e.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):t===this.gridLayer&&e.target.name()==="scrollbar-background"?(this.jumpScrollbarToPointer(e.evt.offsetX),this.isScrollbarDragging=!0,this.scrollbarDragStartX=e.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):t===this.gridLayer&&!i&&(this.isDragging=!0,this.startDragX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isPointerSessionActive()&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.finalizePointerInteraction()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Lt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}isPointerSessionActive(){return this.isDragging||this.isScrollbarDragging}finalizePointerInteraction(){this.isDragging=!1,this.isScrollbarDragging=!1,this.unbindGlobalPointerListenersForDrag()}handlePointerMove(e){if(this.isScrollbarDragging){const t=this.stage.width(),i=this.getTotalDurationPixels(),n=Math.max(0,i-t);if(n<=0)return;const s=this.getScrollbarThumbWidth(),r=Math.max(1,t-s),o=e.clientX-this.scrollbarDragStartX,l=this.scrollLeft,h=this.scrollbarDragStartScrollLeft+o/r*n;this.scrollLeft=Math.max(0,Math.min(n,h)),this.render(),this.scrollLeft!==l&&this.onScrollChange(this.scrollLeft)}else if(this.isDragging){const t=e.clientX-this.startDragX,i=this.scrollLeft;this.scrollLeft-=t;const n=this.stage.width(),s=N.timeToPixels(this.config.duration,this.config.zoom);this.scrollLeft=Math.max(0,Math.min(s-n,this.scrollLeft)),this.startDragX=e.clientX,this.render(),this.scrollLeft!==i&&this.onScrollChange(this.scrollLeft)}}handleZoom(e){const t=e.evt.deltaY;if(t===0)return;const i=t>0?.5:1.5,n=Math.max(de.MIN,Math.min(de.MAX,this.config.zoom*i));if(n!==this.config.zoom){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const s=e.evt.offsetX;this.animateZoom(n,s)}}animateZoom(e,t){const i=this.config.zoom,n=Xn.DURATION,s=Date.now(),r=this.pixelToTime(t),o=()=>{const l=Date.now()-s,h=Math.min(l/n,1),c=this.easeOutCubic(h),d=i+(e-i)*c,u=N.timeToPixels(r,d),f=Math.max(0,u-(t-this.leftPadding));if(this.scrollLeft=f,this.config.zoom=d,this.onZoomChange(d),this.onScrollChange(f),this.render(),h<1)this.animationFrameId=requestAnimationFrame(o);else{const p=N.timeToPixels(r,e),y=Math.max(0,p-(t-this.leftPadding));this.config.zoom=e,this.scrollLeft=y,this.onZoomChange(e),this.onScrollChange(y),this.render()}};this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),o()}animateHorizontalScroll(e){const t=this.scrollLeft,i=300,n=Date.now(),s=this.stage.width(),r=N.timeToPixels(this.config.duration,this.config.zoom);this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const o=()=>{const l=Date.now()-n,h=Math.min(l/i,1),c=this.easeOutCubic(h),d=t+(e-t)*c;this.scrollLeft=Math.max(0,Math.min(r-s,d)),this.onScrollChange(this.scrollLeft),this.render(),h<1?this.animationFrameId=requestAnimationFrame(o):(this.scrollLeft=Math.max(0,Math.min(r-s,e)),this.onScrollChange(this.scrollLeft),this.render())};o()}easeOutCubic(e){return 1-Math.pow(1-e,3)}handleClick(e){const t=this.pixelToTime(e);this.setCurrentTime(t)}pixelToTime(e){return N.pixelsToTime(e-this.leftPadding+this.scrollLeft,this.config.zoom)}timeToPixel(e){return N.timeToPixels(e,this.config.zoom)-this.scrollLeft+this.leftPadding}setCurrentTime(e){this.config.currentTime=Math.max(0,e),this.onTimeChange(this.config.currentTime)}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setPlayState(e){this.config.playState=e,this.render()}update(){this.render()}render(){const e=this.stage.width(),t=this.stage.height(),i=this.gridLayer.findOne(".timeline-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const n=ie.createRect(0,0,e,t,this.theme.background,this.theme.border,1);n.name("timeline-background"),this.gridLayer.add(n)}this.gridLayer.find(".grid-line").forEach(n=>n.remove()),this.gridLayer.find(".time-tick-line").forEach(n=>n.remove()),this.gridLayer.find(".time-tick-text").forEach(n=>n.remove()),this.renderTimeTicks(),this.renderScrollbar(),this.gridLayer.batchDraw()}renderScrollbar(){const e=this.stage.width(),t=this.stage.height(),i=Math.max(this.timeScaleHeight,t-this.scrollbarHeight-this.scrollbarMargin),n=this.getScrollbarThumbWidth(),s=this.getScrollbarThumbX(n),r=this.gridLayer.findOne(".scrollbar-background");if(r)r.x(0),r.y(i),r.width(e),r.height(this.scrollbarHeight),r.fill(this.theme.scrollbarBackground||"#333333"),r.stroke(this.theme.scrollbarBorder||"#555555"),r.visible(!0);else{const l=ie.createRect(0,i,e,this.scrollbarHeight,this.theme.scrollbarBackground||"#333333",this.theme.scrollbarBorder||"#555555",1);l.name("scrollbar-background"),this.gridLayer.add(l)}const o=this.gridLayer.findOne(".scrollbar-thumb");if(o)o.x(s),o.y(i),o.width(n),o.height(this.scrollbarHeight),o.fill(this.theme.scrollbarThumb||"#444444"),o.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555"),o.visible(n<e);else{const l=ie.createRect(s,i,n,this.scrollbarHeight,this.theme.scrollbarThumb||"#444444",this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555",1);l.name("scrollbar-thumb"),l.visible(n<e),this.gridLayer.add(l)}}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,n=N.pixelsToTime(t,this.config.zoom),s=N.pixelsToTime(i,this.config.zoom),r=N.msToSeconds(n),o=N.msToSeconds(s),l=10,h=r-l,c=o+l,{majorStep:d,minorStep:u}=N.getTickConfig(this.config.zoom),f=N.generateVisibleTicks(h,c,d,u);let p=0;const y=20;for(const S of f){const C=this.timeToPixel(S.time);C>=-y&&C<=e+y&&(ie.drawTimeTick(this.gridLayer,C,0,this.timeScaleHeight,S.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},S.type,this.timeScaleHeight),p++)}L.debugLazy("Timeline",()=>`Timeline - scrollLeft: ${this.scrollLeft}px, zoom: ${this.config.zoom}px/s, visible time: ${Math.round(r)}s to ${Math.round(o)}s, ticks: ${f.length} generated, ${p} drawn`)}getConfig(){return{...this.config}}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){const t=this.stage.width(),i=this.getTotalDurationPixels();this.scrollLeft=Math.max(0,Math.min(i-t,e)),this.render()}getTotalDurationPixels(){return N.timeToPixels(this.config.duration,this.config.zoom)}getScrollbarThumbWidth(){const e=this.stage.width(),t=this.getTotalDurationPixels();return t<=0||t<=e?e:Math.max(40,e/t*e)}getScrollbarThumbX(e){const t=this.stage.width(),i=this.getTotalDurationPixels(),n=Math.max(0,i-t);if(n<=0||e>=t)return 0;const s=t-e;return this.scrollLeft/n*s}jumpScrollbarToPointer(e){const t=this.stage.width(),i=this.getTotalDurationPixels(),n=Math.max(0,i-t);if(n<=0)return;const s=this.getScrollbarThumbWidth(),r=Math.max(1,t-s),l=Math.max(s/2,Math.min(t-s/2,e))-s/2,h=this.scrollLeft;this.scrollLeft=l/r*n,this.render(),this.scrollLeft!==h&&this.onScrollChange(this.scrollLeft)}scrollToTime(e){const t=N.timeToPixels(e,this.config.zoom),i=this.stage.width(),n=Math.max(0,t-i/2);this.setScrollLeft(n),this.onScrollChange(n)}scrollToClip(e){const t=N.timeToPixels(e.startTime,this.config.zoom),n=N.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,s=this.stage.width();let r;n<=s?r=Math.max(0,t-(s-n)/2):r=Math.max(0,t),this.setScrollLeft(r),this.onScrollChange(r)}getStage(){return this.stage}getGridLayer(){return this.gridLayer}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}resize(e,t){this.render()}}const vt=8;function ce(a,e,t){return ie.timeToPixels(a,e)-t+le}function ve(a,e){const t=ie.timeToPixels(a,e);return a<=1e3||t<=It?It:t}function Pn(a,e){const t=ce(a.startTime,a.zoom,a.scrollLeft),i=ve(a.duration,a.zoom);return t+i>0&&t<e}function Zo(a){for(const e of a.clips){const t=ce(e.startTime,a.zoom,a.scrollLeft),i=ve(e.duration,a.zoom),n=a.y>=a.trackY&&a.y<=a.trackY+a.trackHeight;if(a.x>=t&&a.x<=t+vt&&n||a.x>=t+i-vt&&a.x<=t+i&&n)return"ew-resize";if(a.x>t+vt&&a.x<t+i-vt&&n)return"pointer"}return"default"}class jt{constructor(e,t,i){g(this,"clip");g(this,"onUpdate");g(this,"onSplit");this.clip=Oi({...e,endTime:N.calculateEndTime(e.startTime,e.duration)},{isDragging:e.isDragging,isResizingLeft:e.isResizingLeft,isResizingRight:e.isResizingRight,isSelected:e.isSelected,isResizing:e.isResizing,zIndex:e.zIndex,opacity:e.opacity}),this.onUpdate=t,this.onSplit=i}getClip(){return{...this.clip}}applyPreviewState(e){this.clip={...this.clip,...e,endTime:N.calculateEndTime(e.startTime,e.duration)}}setSelected(e){this.clip={...this.clip,isSelected:e},this.onUpdate(this.clip)}isPointInResizeHandle(e,t,i,n,s,r){const o=ce(this.clip.startTime,i,r),l=ve(this.clip.duration,i),h=vt;return t<n||t>n+s?(this.setResizeHandleState(!1,!1),!1):e>=o&&e<=o+h?(this.setResizeHandleState(!0,!1),!0):e>=o+l-h&&e<=o+l?(this.setResizeHandleState(!1,!0),!0):(this.setResizeHandleState(!1,!1),!1)}startDrag(e){this.clip={...this.clip,isDragging:!0,isResizing:!1,isResizingLeft:!1,isResizingRight:!1},this.onUpdate(this.clip)}startResize(e){this.clip={...this.clip,isDragging:!0,isResizing:!0},this.onUpdate(this.clip)}endDrag(){this.clip={...this.clip,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1}}split(e){e>this.clip.startTime+1&&e<this.clip.endTime-1&&this.onSplit(this.clip,e)}setResizeHandleState(e,t){this.clip={...this.clip,isResizingLeft:e,isResizingRight:t}}}function ei(){return{kind:"idle"}}function pi(a){return!!a&&a.kind!=="idle"}function Pt(a){return(a==null?void 0:a.kind)==="draggingMove"||(a==null?void 0:a.kind)==="draggingResizeLeft"||(a==null?void 0:a.kind)==="draggingResizeRight"}function Je(a){return!a||a.kind==="idle"||a.kind==="boxSelecting"?null:a.context}function _t(a){return!a||a.kind==="idle"||a.kind==="boxSelecting"?null:a.kind==="pressed"?a.operation:a.kind==="draggingResizeLeft"?"resize-left":a.kind==="draggingResizeRight"?"resize-right":"move"}function Jo(a){const e=_t(a);return e?e==="move"?"grabbing":"ew-resize":null}function Yt(a,e){if(e.type==="POINTER_DOWN")return{state:{kind:"pressed",operation:e.operation,context:{clipId:e.clipId,originalClipsState:e.originalClipsState,nonDraggedClips:e.nonDraggedClips,snapCandidateClips:e.snapCandidateClips,pointerStartClientX:e.clientX,pointerStartClientY:e.clientY,pointerStartX:e.localX,pointerStartY:e.localY,dragStartScrollLeft:e.scrollLeft,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:e.localY,crossTrackDragOffsetY:0}},effects:{bindGlobalListeners:!0}};if(e.type==="BOX_SELECT_START")return{state:{kind:"boxSelecting",context:{startClientX:e.clientX,startClientY:e.clientY,startLocalX:e.localX,startLocalY:e.localY,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY,additive:e.additive}},effects:{bindGlobalListeners:!0}};if(a.kind==="idle")return{state:a,effects:{}};if(a.kind==="boxSelecting")return e.type==="BOX_SELECT_MOVE"?{state:{kind:"boxSelecting",context:{...a.context,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY}},effects:{updatePreview:!0}}:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP"||e.type==="CANCEL"||e.type==="VISIBILITY_HIDDEN"||e.type==="WINDOW_BLUR"?{state:ei(),effects:{unbindGlobalListeners:!0,commit:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP",cleanup:!0}}:{state:a,effects:{}};if(e.type==="POINTER_MOVE"){const i=el(a.context,e,_t(a)||"move");return a.kind==="pressed"?tl(a.context,e.activationThreshold,e.clientX,e.clientY)?{state:Qo(a.operation,i),effects:{updatePreview:!0}}:{state:{...a,context:i},effects:{}}:{state:{...a,context:i},effects:{updatePreview:!0}}}if(e.type==="SCROLL_LEFT_CHANGED")return{state:a,effects:{updatePreview:Pt(a)}};const t=e.type==="POINTER_UP"&&Pt(a);return{state:ei(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function Qo(a,e){return a==="resize-left"?{kind:"draggingResizeLeft",context:e}:a==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function el(a,e,t){const i=t==="move";return{...a,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:i?e.localY:a.pointerStartY,crossTrackDragOffsetY:i?e.localY-a.pointerStartY:0}}function tl(a,e,t,i){const n=t-a.pointerStartClientX,s=i-a.pointerStartClientY;return Math.hypot(n,s)>=Math.max(0,e)}const Se=class Se{constructor(e,t,i,n,s,r,o,l,h,c,d,u,f,p,y,S,C,T,b,w,k,_,O,A,M,D=Se.DEFAULT_DRAG_ACTIVATION_THRESHOLD,z=!1,B=Se.DEFAULT_CLIP_SNAP_THRESHOLD){g(this,"layer");g(this,"trackGroup");g(this,"dragOverlayLayer",null);g(this,"dropPreviewGroup",null);g(this,"dropPreviewClips",[]);g(this,"config");g(this,"theme");g(this,"trackType");g(this,"clips",[]);g(this,"clipGroups",new Map);g(this,"zoom",100);g(this,"scrollLeft",0);g(this,"trackY",0);g(this,"trackHeight",64);g(this,"selectedClip",null);g(this,"hasSelectedClip",!1);g(this,"selectedClipIds",new Set);g(this,"multiDragOriginalPositions",new Map);g(this,"promotedClipParents",new Map);g(this,"interactionState",ei());g(this,"legacyInteractionSnapshot");g(this,"isVisualUpdate",!1);g(this,"onClipUpdate");g(this,"onClipAdd");g(this,"onClipRemove");g(this,"onClipSplit");g(this,"onClipSelect");g(this,"onTimeJump");g(this,"onClipOverlap");g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"hasLockedGlobalCursor",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"onHorizontalDragAutoScroll");g(this,"onClipCrossTrackPreview");g(this,"onClipCrossTrack");g(this,"onClearDropPreview");g(this,"onClearSelection");g(this,"onSnapGuideChange");g(this,"onClipToggleSelection");g(this,"onSetSingleSelection");g(this,"getMultiDragClipIds");g(this,"onMultiDragMove");g(this,"onMultiDragInteractionEnd");g(this,"resolveSnapTargetClips");g(this,"dragActivationThreshold");g(this,"enableClipSnap");g(this,"clipSnapThreshold");g(this,"handleGlobalPointerMove",e=>{pi(this.interactionState)&&this.handleDragMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});g(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});g(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const e=this.resolveInteractionState();if(!Pt(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),n=Je(e);if(!i||!n){this.stopEdgeAutoScroll();return}const s=i.getBoundingClientRect(),r=n.lastPointerClientX-s.left,o=this.calculateHorizontalAutoScrollVelocity(r,s.width);if(o===0){this.stopEdgeAutoScroll();return}const l=this.scrollLeft,h=this.onHorizontalDragAutoScroll(this.scrollLeft+o),c=typeof h=="number"?h:this.scrollLeft;if(Math.abs(c-l)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.layer=e,this.config=t,this.theme=o,this.trackType=i,this.zoom=n,this.trackY=s,this.trackHeight=r,this.onClipUpdate=l,this.onClipAdd=h,this.onClipRemove=c,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=f,this.onHorizontalDragAutoScroll=p,this.onClipOverlap=y,this.onClipCrossTrackPreview=S,this.onClipCrossTrack=C,this.onClearDropPreview=T,this.onClearSelection=b,this.onSnapGuideChange=w,this.onClipToggleSelection=k,this.onSetSingleSelection=_,this.getMultiDragClipIds=O,this.onMultiDragMove=A,this.onMultiDragInteractionEnd=M,this.dragActivationThreshold=Math.max(0,D),this.enableClipSnap=z,this.clipSnapThreshold=Math.max(0,B),this.trackGroup=ie.createGroup(0,s),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}get hasDragMoved(){return this.getLegacyInteractionSnapshot().hasDragMoved}set hasDragMoved(e){this.getLegacyInteractionSnapshot().hasDragMoved=e}get activePointerOperation(){return this.getLegacyInteractionSnapshot().activePointerOperation}set activePointerOperation(e){this.getLegacyInteractionSnapshot().activePointerOperation=e}get originalClipsState(){return this.getLegacyInteractionSnapshot().originalClipsState}set originalClipsState(e){this.getLegacyInteractionSnapshot().originalClipsState=Array.isArray(e)?e:[]}get nonDraggedClips(){return this.getLegacyInteractionSnapshot().nonDraggedClips}set nonDraggedClips(e){this.getLegacyInteractionSnapshot().nonDraggedClips=Array.isArray(e)?e:[]}get snapCandidateClips(){return this.getLegacyInteractionSnapshot().snapCandidateClips}set snapCandidateClips(e){this.getLegacyInteractionSnapshot().snapCandidateClips=Array.isArray(e)?e:[]}get dragStartY(){return this.getLegacyInteractionSnapshot().dragStartY}set dragStartY(e){this.getLegacyInteractionSnapshot().dragStartY=typeof e=="number"?e:0}get dragTargetTrackY(){return this.getLegacyInteractionSnapshot().dragTargetTrackY}set dragTargetTrackY(e){this.getLegacyInteractionSnapshot().dragTargetTrackY=typeof e=="number"?e:0}get crossTrackDragOffsetY(){return this.getLegacyInteractionSnapshot().crossTrackDragOffsetY}set crossTrackDragOffsetY(e){this.getLegacyInteractionSnapshot().crossTrackDragOffsetY=typeof e=="number"?e:0}get crossTrackDragStartX(){return this.getLegacyInteractionSnapshot().crossTrackDragStartX}set crossTrackDragStartX(e){this.getLegacyInteractionSnapshot().crossTrackDragStartX=typeof e=="number"?e:0}get dragStartScrollLeft(){return this.getLegacyInteractionSnapshot().dragStartScrollLeft}set dragStartScrollLeft(e){this.getLegacyInteractionSnapshot().dragStartScrollLeft=typeof e=="number"?e:0}get dragGestureStartClientX(){return this.getLegacyInteractionSnapshot().dragGestureStartClientX}set dragGestureStartClientX(e){this.getLegacyInteractionSnapshot().dragGestureStartClientX=typeof e=="number"?e:null}get dragGestureStartClientY(){return this.getLegacyInteractionSnapshot().dragGestureStartClientY}set dragGestureStartClientY(e){this.getLegacyInteractionSnapshot().dragGestureStartClientY=typeof e=="number"?e:null}get lastDragClientX(){return this.getLegacyInteractionSnapshot().lastDragClientX}set lastDragClientX(e){this.getLegacyInteractionSnapshot().lastDragClientX=typeof e=="number"?e:null}get lastDragClientY(){return this.getLegacyInteractionSnapshot().lastDragClientY}set lastDragClientY(e){this.getLegacyInteractionSnapshot().lastDragClientY=typeof e=="number"?e:null}initClips(){this.clips=this.config.clips.map(e=>{const t=new jt(e,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));return this.createClipGroup(e),t})}getLegacyInteractionSnapshot(){return this.legacyInteractionSnapshot||(this.legacyInteractionSnapshot={hasDragMoved:!1,activePointerOperation:null,originalClipsState:[],nonDraggedClips:[],snapCandidateClips:[],dragStartY:0,dragTargetTrackY:0,crossTrackDragOffsetY:0,crossTrackDragStartX:0,dragStartScrollLeft:0,dragGestureStartClientX:null,dragGestureStartClientY:null,lastDragClientX:null,lastDragClientY:null}),this.legacyInteractionSnapshot}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const e=ie.createGroup(0,0);return e.name("clip-drop-preview"),e.visible(!1),e.listening(!1),this.trackGroup.add(e),this.dropPreviewGroup=e,e}createDropPreviewRect(e){const t=this.trackType==="video"?"rgba(80, 227, 194, 0.18)":"rgba(181, 186, 255, 0.18)",i=this.trackType==="video"?"#50e3c2":"#b5baff",n=ce(e.startTime,this.zoom,this.scrollLeft),s=ve(e.duration,this.zoom),r=ie.createRect(n,2,Math.max(s,1),Math.max(this.trackHeight-4,1),t,i,1);return r.dash([6,4]),r.cornerRadius(4),r.listening(!1),r.visible(n+s>0&&n<this.layer.width()),r}showDropPreview(e){const t=this.ensureDropPreviewGroup(),i=Array.isArray(e)?e:[e];this.dropPreviewClips=i.map(s=>({...s})),t.destroyChildren();let n=!1;for(const s of this.dropPreviewClips){const r=this.createDropPreviewRect(s);n=n||r.visible(),t.add(r)}t.x(0),t.y(0),t.visible(n),t.moveToTop()}hideDropPreview(){var e;this.dropPreviewClips=[],(e=this.dropPreviewGroup)==null||e.visible(!1)}initEventListeners(){const e=this.layer.getStage();e&&e.on("mouseup",()=>{this.handleClipMouseUp()})}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Lt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}),this.hasBoundGlobalPointerListenersForDrag=!1)}handleTrackBackgroundClick(e){const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=Math.max(0,N.pixelsToTime(s-le+this.scrollLeft,this.zoom));this.onTimeJump(r),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(e){}updateClipSelection(e,t){const i=this.clips.find(n=>n.getClip().id===e);i&&(this.isVisualUpdate=!0,i.setSelected(t),this.isVisualUpdate=!1,t?this.selectedClipIds.add(e):this.selectedClipIds.delete(e),this.syncSelectionState(e),this.updateClipGroup(i.getClip()),this.render(!1),this.layer.batchDraw())}createClipGroup(e){const t=ce(e.startTime,this.zoom,this.scrollLeft),i=ve(e.duration,this.zoom),n=2,s=this.trackHeight-4,r=ie.createClipGroup(t,n,i,s,e.name,e.duration,this.theme,!1,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId);r.name(`clip-${e.id}`),r.on("click",o=>{this.handleClipClick(e.id,o.evt)}),r.on("mousedown",o=>{this.handleClipMouseDown(e.id,o.evt)}),r.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),r.on("mouseleave",()=>{this.handleClipMouseLeave()}),r.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(r),this.clipGroups.set(e.id,r)}handleClipClick(e,t){if(t.button!==0)return;this.clips.find(n=>n.getClip().id===e)&&this.render()}handleClipMouseDown(e,t){var c;if(t.button!==0)return;if(t.ctrlKey||t.metaKey){this.onClipToggleSelection&&this.onClipToggleSelection(e);return}const i=(c=this.getMultiDragClipIds)==null?void 0:c.call(this,e),n=i!=null&&i.length>1;if(!n)this.selectedClipIds.clear(),this.selectedClipIds.add(e),this.onSetSingleSelection&&this.onSetSingleSelection(e);else{this.selectedClipIds.clear();for(const d of i)this.selectedClipIds.add(d)}this.clips.sort((d,u)=>d.getClip().startTime-u.getClip().startTime);const s=this.clips.map(d=>({...d.getClip()})),r=this.clips.filter(d=>d.getClip().id!==e).map(d=>({...d.getClip()})),l=(this.resolveSnapTargetClips?this.resolveSnapTargetClips():this.clips.map(d=>d.getClip())).filter(d=>d.id!==e).map(d=>({...d})),h=this.clips.find(d=>d.getClip().id===e);if(h){n||(this.applySelectionVisual(new Set([e])),this.onClipSelect(h.getClip())),this.selectedClip=h;const d=this.layer.getStage();if(!d)return;const u=d.container();if(!u)return;const f=u.getBoundingClientRect(),p=t.clientX-f.left,y=t.clientY-f.top;if(n){this.multiDragOriginalPositions.clear();for(const C of this.selectedClipIds){const T=this.clips.find(b=>b.getClip().id===C);if(T){const b=T.getClip();this.multiDragOriginalPositions.set(C,{startTime:b.startTime,duration:b.duration})}}}let S;h.isPointInResizeHandle(p,y,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(S=h.getClip().isResizingLeft?"resize-left":"resize-right",h.startResize({x:p,y})):(S="move",h.startDrag({x:p,y}),this.trackGroup.moveToTop()),this.applyInteractionTransition(Yt(this.interactionState,{type:"POINTER_DOWN",operation:S,clipId:e,originalClipsState:s,nonDraggedClips:r,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:p,localY:y,scrollLeft:this.scrollLeft})),this.render()}}handleClipMouseMove(e){this.updateHoverCursor(e.clientX,e.clientY)}handleTrackBackgroundMouseMove(){if(this.isDragSessionActive())return;const e=this.layer.getStage(),t=e==null?void 0:e.container();t&&(t.style.cursor="default")}handleClipMouseUp(){this.finishPointerInteraction("POINTER_UP")}finishPointerInteraction(e){const t=this.interactionState;try{if(!this.selectedClip)return;const i=this.selectedClip.getClip();if(!i.isDragging)return;const n=i;this.selectedClip.endDrag();const s=Yt(t,{type:e});this.interactionState=s.state,s.effects.commit&&this.handleClipMoveEnd(n,t),this.layer.batchDraw()}finally{this.interactionState=ei(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}applyInteractionTransition(e){var i,n;this.interactionState=e.state,this.syncLegacyInteractionMirror(e.state),e.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const t=Jo(e.state);t&&this.lockPointerCursor(t),e.effects.cleanup&&(this.releasePointerCursor(),this.hideDropPreview(),(i=this.onClearDropPreview)==null||i.call(this),this.updateSnapGuideLine(null),this.stopEdgeAutoScroll(),this.clearClipDragOverlay(),this.multiDragOriginalPositions.size>0&&((n=this.onMultiDragInteractionEnd)==null||n.call(this),this.multiDragOriginalPositions.clear())),e.effects.unbindGlobalListeners&&this.unbindGlobalPointerListenersForDrag()}resolveInteractionState(e=this.interactionState){var r;if(pi(e))return e;const t=this.getLegacyInteractionSnapshot(),i=(r=this.selectedClip)==null?void 0:r.getClip();if(!(i!=null&&i.id)||!i.isDragging)return e;const n=t.activePointerOperation||(i.isResizingLeft?"resize-left":i.isResizingRight?"resize-right":"move"),s={clipId:i.id,originalClipsState:t.originalClipsState,nonDraggedClips:t.nonDraggedClips,snapCandidateClips:t.snapCandidateClips,pointerStartClientX:t.dragGestureStartClientX??0,pointerStartClientY:t.dragGestureStartClientY??0,pointerStartX:t.crossTrackDragStartX,pointerStartY:t.dragStartY,dragStartScrollLeft:t.dragStartScrollLeft||this.scrollLeft,lastPointerClientX:t.lastDragClientX??0,lastPointerClientY:t.lastDragClientY??0,dragTargetTrackY:t.dragTargetTrackY,crossTrackDragOffsetY:t.crossTrackDragOffsetY};return t.hasDragMoved?n==="resize-left"?{kind:"draggingResizeLeft",context:s}:n==="resize-right"?{kind:"draggingResizeRight",context:s}:{kind:"draggingMove",context:s}:{kind:"pressed",operation:n,context:s}}syncLegacyInteractionMirror(e=this.interactionState){const t=this.getLegacyInteractionSnapshot(),i=Je(e);t.hasDragMoved=Pt(e),t.activePointerOperation=_t(e),t.originalClipsState=(i==null?void 0:i.originalClipsState)??[],t.nonDraggedClips=(i==null?void 0:i.nonDraggedClips)??[],t.snapCandidateClips=(i==null?void 0:i.snapCandidateClips)??[],t.dragStartY=(i==null?void 0:i.pointerStartY)??0,t.dragTargetTrackY=(i==null?void 0:i.dragTargetTrackY)??0,t.crossTrackDragOffsetY=(i==null?void 0:i.crossTrackDragOffsetY)??0,t.crossTrackDragStartX=(i==null?void 0:i.pointerStartX)??0,t.dragStartScrollLeft=(i==null?void 0:i.dragStartScrollLeft)??0,t.dragGestureStartClientX=(i==null?void 0:i.pointerStartClientX)??null,t.dragGestureStartClientY=(i==null?void 0:i.pointerStartClientY)??null,t.lastDragClientX=(i==null?void 0:i.lastPointerClientX)??null,t.lastDragClientY=(i==null?void 0:i.lastPointerClientY)??null}handleClipMoveEnd(e,t){var S,C,T;const i=this.resolveInteractionState(t),n=this.getLegacyInteractionSnapshot(),s=Je(i)||{clipId:e.id,originalClipsState:n.originalClipsState.length>0?n.originalClipsState:[e],nonDraggedClips:n.nonDraggedClips,snapCandidateClips:n.snapCandidateClips,dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:n.dragTargetTrackY,crossTrackDragOffsetY:n.crossTrackDragOffsetY},o=(_t(i)||n.activePointerOperation||"move")==="move",l=o&&this.multiDragOriginalPositions.size>0,h=(S=this.clipGroups)==null?void 0:S.get(e.id);if(h&&h.y(2),l){const b=this.multiDragOriginalPositions.get(e.id),w=b?e.startTime-b.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:e.id,deltaTime:w,targetTrackY:s.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:s.crossTrackDragOffsetY,isFinal:!0})){for(const D of this.selectedClipIds){const z=(C=this.clipGroups)==null?void 0:C.get(D);z==null||z.y(2)}this.multiDragOriginalPositions.clear();return}const k=[],_=[];for(const[M,D]of this.multiDragOriginalPositions){const z=this.clips.find(R=>R.getClip().id===M);if(!z)continue;const B=Math.max(0,D.startTime+w),W={...z.getClip(),startTime:B,endTime:B+D.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(M)};k.push(W);const F=s.originalClipsState.find(R=>R.id===M);F&&_.push(F);const H=(T=this.clipGroups)==null?void 0:T.get(M);H&&H.y(2)}const O=[];for(const M of this.clips){const D=M.getClip(),z=k.find(B=>B.id===D.id);z?O.push(z):O.push({...D,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}O.sort((M,D)=>M.startTime-D.startTime),this.isVisualUpdate=!0;for(const M of O)this.clips.find(z=>z.getClip().id===M.id)&&this.handleClipUpdate(M);this.isVisualUpdate=!1;const A=_.map(M=>{const D=k.find(z=>z.id===M.id);return D&&(M.startTime!==D.startTime||M.duration!==D.duration)?{clipId:M.id,previousState:M,newState:D}:null}).filter(M=>M!==null);A.length>0&&this.onClipUpdate(e,_.find(M=>M.id===e.id),A),this.multiDragOriginalPositions.clear();return}if(o&&this.onClipCrossTrack&&this.config.id){const b=s.originalClipsState.find(k=>k.id===e.id)??null;if(this.onClipCrossTrack(e,b,s.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}const c=o?[...s.nonDraggedClips]:[];let d=!1;const u=e.startTime+e.duration;for(const b of c){const w=b.startTime+b.duration;if(e.startTime<w&&u>b.startTime){d=!0;break}}if(o&&d&&this.onClipOverlap&&this.config.id){this.onClipOverlap(e,this.config.id);return}const f=[...s.nonDraggedClips];let p=f.findIndex(b=>b.startTime>=e.startTime);p===-1&&(p=f.length),s.nonDraggedClips.forEach(b=>{b.isSelected=!1});const y={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};f.splice(p,0,y),this.updateAllClips(f),this.buildAndSendUpdates(y,f,s.originalClipsState)}updateAllClips(e){const t=this.clips??[];this.isVisualUpdate=!0,e.forEach(i=>{t.find(s=>s.getClip().id===i.id)&&this.handleClipUpdate(i)}),this.isVisualUpdate=!1,t.sort((i,n)=>i.getClip().startTime-n.getClip().startTime),this.clips=t}buildAndSendUpdates(e,t,i){const n=i.map(s=>{const r=t.find(o=>o.id===s.id);return r&&(s.startTime!==r.startTime||s.duration!==r.duration||s.opacity!==r.opacity)?{clipId:s.id,previousState:s,newState:r}:null}).filter(s=>s!==null);n.length>0&&this.onClipUpdate(e,i.find(s=>s.id===e.id),n)}updateHoverCursor(e,t){const i=this.layer.getStage();if(!i)return;const n=i.container();if(!n||this.isDragSessionActive())return;const s=n.getBoundingClientRect(),r=e-s.left,o=t-s.top;n.style.cursor=Zo({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:r,y:o})}isDragSessionActive(){return pi(this.resolveInteractionState())}handleDragMove(e){const t=this.resolveInteractionState(),i=this.layer.getStage(),n=i==null?void 0:i.container();if(!n)return;const s=n.getBoundingClientRect(),r=Yt(t,{type:"POINTER_MOVE",clientX:e.clientX,clientY:e.clientY,localY:e.clientY-s.top,activationThreshold:this.dragActivationThreshold});this.interactionState=r.state,this.syncLegacyInteractionMirror(r.state),r.effects.updatePreview&&this.updateDraggedClipFromPointer(e.clientX,e.clientY,!0)}handleClipMouseLeave(){if(this.isDragSessionActive())return;const e=this.layer.getStage();e&&e.container()&&(e.container().style.cursor="default")}lockPointerCursor(e){const t=typeof this.layer.getStage=="function"?this.layer.getStage():null,i=t==null?void 0:t.container();i&&(i.style.cursor=e),typeof document<"u"&&document.body&&(document.body.style.cursor=e,this.hasLockedGlobalCursor=!0)}releasePointerCursor(){const e=typeof this.layer.getStage=="function"?this.layer.getStage():null,t=e==null?void 0:e.container();t&&(t.style.cursor="default"),this.hasLockedGlobalCursor&&typeof document<"u"&&document.body&&(document.body.style.cursor="",this.hasLockedGlobalCursor=!1)}updateClipGroup(e,t=!1){const i=this.clipGroups.get(e.id);if(i){const n=ce(e.startTime,this.zoom,this.scrollLeft),s=ve(e.duration,this.zoom);i.x(n),i.visible(Pn({startTime:e.startTime,duration:e.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width()));const r=e.isSelected;(e.isDragging||r)&&i.moveToTop(),i.opacity(e.opacity),ie.updateClipGroup(i,s,this.trackHeight-4,e.name,e.duration,this.theme,r,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,t)}}handleClipUpdate(e){const t=this.clips.findIndex(i=>i.getClip().id===e.id);if(t!==-1){const i=this.clips[t].getClip(),n={...e,isSelected:this.isVisualUpdate?e.isSelected:this.selectedClipIds.has(e.id)};this.clips[t]=new jt(n,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this)),this.syncSelectionState(e.id),this.updateClipGroup(n);const s=this.clipGroups.get(e.id);s&&s.opacity(n.opacity),this.isVisualUpdate||this.onClipUpdate(n,i),this.layer.batchDraw()}}handleClipSplit(e,t){const i=t-e.startTime,n=e.duration-i,s=e.startTimeAtSource+i,r={...e,duration:i,endTime:t,endTimeAtSource:s},o={...e,id:`${e.id}_split_${Date.now()}`,startTime:t,duration:n,endTime:N.calculateEndTime(t,n),startTimeAtSource:s,endTimeAtSource:e.endTimeAtSource};this.removeClip(e.id),this.addClip(r),this.addClip(o),this.onClipSplit(r,o),this.layer.batchDraw()}addClip(e){if(e.type!==this.trackType){L.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new jt(t,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));this.clips.push(i),this.createClipGroup(t),this.onClipAdd(t),this.layer.batchDraw()}removeClip(e){const t=this.clips.findIndex(i=>i.getClip().id===e);if(t!==-1){this.clips.splice(t,1),this.selectedClipIds.delete(e),this.syncSelectionState();const i=this.clipGroups.get(e);i&&(this.getPromotedClipParents().delete(e),i.remove(),this.clipGroups.delete(e)),this.onClipRemove(e),this.hideDropPreview(),this.render(!1),this.layer.batchDraw()}}updateClip(e,t){const i=this.clips.find(n=>n.getClip().id===e);if(i){const s={...i.getClip(),...t};(t.startTime!==void 0||t.duration!==void 0)&&(s.endTime=s.startTime+s.duration),this.handleClipUpdate(s)}}setZoom(e){this.zoom=e,this.clips.forEach(t=>{this.updateClipGroup(t.getClip())}),this.layer.batchDraw()}setCurrentTime(e){this.layer.batchDraw()}setScrollLeft(e){this.scrollLeft=e,this.clips.forEach(s=>{const r=s.getClip();this.updateClipGroup(r),this.updateClipVisibility(r)});const t=this.resolveInteractionState(),i=Je(t),n=Yt(t,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=n.state,this.syncLegacyInteractionMirror(n.state),n.effects.updatePreview&&i&&this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1),this.layer.batchDraw()}updateClipVisibility(e){const t=this.clipGroups.get(e.id);if(t){const i=Pn({startTime:e.startTime,duration:e.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width());t.visible(i)}}setTrackY(e){const t=e-this.trackY;this.trackY=e,this.trackGroup.y(e),this.getPromotedClipParents().forEach((i,n)=>{i.baseY=e;const s=this.clipGroups.get(n);s&&s.y(s.y()+t)})}setTrackStackOrder(e){this.trackGroup.zIndex(e)}setDragOverlayLayer(e){this.dragOverlayLayer=e}setClipsDragOverlayActive(e,t){e.forEach(i=>{this.setClipDragOverlayActive(i,t)})}clearClipDragOverlay(){Array.from(this.getPromotedClipParents().keys()).forEach(e=>{this.setClipDragOverlayActive(e,!1)})}getTrackType(){return this.trackType}render(e=!0){const t=this.getTrackBackgroundFill();if(this.trackGroup.children.length===0){const i=ie.createRect(0,0,this.layer.width(),this.trackHeight,t,this.theme.trackBorder,1);i.name("track-background"),i.on("click",n=>{this.handleTrackBackgroundClick(n.evt)}),i.on("mousedown",n=>{this.handleTrackBackgroundMouseDown(n.evt)}),i.on("mousemove",()=>{this.handleTrackBackgroundMouseMove()}),i.on("mouseleave",()=>{this.handleClipMouseLeave()}),this.trackGroup.add(i)}else{const i=this.trackGroup.findOne(".track-background");i&&(i.width(this.layer.width()),typeof i.height=="function"&&i.height(this.trackHeight),i.fill(t),i.stroke(this.theme.trackBorder),i.listening()||i.listening(!0))}e&&this.layer.batchDraw()}getTrackBackgroundFill(){return this.hasSelectedClip?this.theme.trackSelectedBackground||"#292929":this.theme.trackBackground}getClips(){return this.clips.map(e=>e.getClip())}getPrimarySelectedClip(){return this.selectedClip?this.selectedClip.getClip():null}clearSelection(){this.setSelection([])}setSelection(e,t){const i=new Set(e);this.applySelectionVisual(i),this.selectedClipIds=i,this.syncSelectionState(t??e[0]??void 0),this.render()}applySelectionVisual(e){this.isVisualUpdate=!0;try{this.clips.forEach(t=>{const i=t.getClip().id,n=e.has(i);t.setSelected(n)})}finally{this.isVisualUpdate=!1}}syncSelectionState(e){var r;const t=this.clips.filter(o=>this.selectedClipIds.has(o.getClip().id)),n=t.length>0?t:this.clips.filter(o=>o.getClip().isSelected);if(this.selectedClipIds=new Set(n.map(o=>o.getClip().id)),this.hasSelectedClip=n.length>0,!this.hasSelectedClip){this.selectedClip=null;return}const s=e??((r=this.selectedClip)==null?void 0:r.getClip().id)??null;this.selectedClip=n.find(o=>o.getClip().id===s)??n[n.length-1]??null}splitSelectedClip(e){const t=this.clips.find(i=>{const n=i.getClip();return e>=n.startTime&&e<n.endTime});t&&t.split(e)}removeClipGaps(){L.debugLazy("Track",()=>"Removing clip gaps");const e=this.clips.map(i=>i.getClip()).sort((i,n)=>i.startTime-n.startTime);if(e.length===0)return;let t=0;for(let i=0;i<e.length;i++){const n=e[i];if(t-n.startTime<0||i===0){const r=t,o=r+n.duration;this.handleClipUpdate({...n,startTime:r,endTime:o}),t=o}else t=n.startTime+n.duration}}getTrackGroup(){return this.trackGroup}getId(){return this.config.id||"default"}updateClipPosition(e,t,i,n=0){var l;const s=this.clips.find(h=>h.getClip().id===e);if(!s)return;const r=s.getClip(),o=this.clipGroups.get(e);if(i)this.setClipDragOverlayActive(e,!1),this.updateClipPositionFinal(e,t);else if(o){const h=ce(t,this.zoom,this.scrollLeft);o.x(h),o.y(this.resolveClipRenderY(e,n)),o.moveToTop(),ie.updateClipGroup(o,ve(r.duration,this.zoom),this.trackHeight-4,r.name,r.duration,this.theme,!0,r.thumbnails,r.src,r.type,!!r.separatedAudioClipId,!0),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw()}}updateClipPositionFinal(e,t){const i=this.clips.find(r=>r.getClip().id===e);if(!i)return;const n=i.getClip(),s=this.clipGroups.get(e);this.setClipDragOverlayActive(e,!1),s==null||s.y(2),this.isVisualUpdate=!0,this.handleClipUpdate({...n,startTime:t,endTime:t+n.duration}),this.isVisualUpdate=!1}setTrackHeight(e){var t,i;if(this.trackHeight=e,(t=this.dropPreviewGroup)!=null&&t.visible()&&Array.isArray(this.dropPreviewClips)&&this.dropPreviewClips.length>0)this.showDropPreview(this.dropPreviewClips);else if((i=this.dropPreviewGroup)!=null&&i.visible()){const n=this.dropPreviewGroup.children[0];n==null||n.height(Math.max(this.trackHeight-4,1))}this.clips.forEach(n=>{this.updateClipGroup(n.getClip(),!0)}),this.render(!1)}showClipDropPreview(e){this.showDropPreview(e),this.layer.batchDraw()}showClipDropPreviews(e){this.showDropPreview(e),this.layer.batchDraw()}clearClipDropPreview(){this.hideDropPreview(),this.layer.batchDraw()}getRole(){return this.config.role||"normal"}setClipSnapEnabled(e){this.enableClipSnap=e,e||this.updateSnapGuideLine(null);const t=this.resolveInteractionState(),i=Je(t);if(Pt(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var S,C,T,b,w;const n=this.resolveInteractionState(),s=Je(n),r=_t(n),o=this.layer.getStage();if(!o||!this.selectedClip||!s||!r)return;const l=o.container();if(!l)return;const h=l.getBoundingClientRect(),c=e-h.left,d=t-h.top,u=r==="move",f=u&&this.multiDragOriginalPositions.size>0;u&&L.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:d,currentTrackId:this.config.id,offsetY:s.crossTrackDragOffsetY}));const p=this.selectedClip.getClip(),y=(S=this.clipGroups)==null?void 0:S.get(p.id);if(y){const k=u&&s.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(p.id,k);const _=s.originalClipsState.find(F=>F.id===p.id);if(!_)return;const O=this.buildPreviewClip(p,_,c,s,r);if(!O){this.hideDropPreview(),(C=this.onClearDropPreview)==null||C.call(this),this.updateSnapGuideLine(null);return}const A=O.clip,M=A.startTime-_.startTime,D=this.applyPreviewClipState(A),z=ce(A.startTime,this.zoom,this.scrollLeft),B=ve(A.duration,this.zoom);y.x(z),y.y(this.resolveClipRenderY(p.id,s.crossTrackDragOffsetY)),y.visible(z+B>0&&z<this.layer.width()),D&&(this.updateClipGroup(A),y.y(this.resolveClipRenderY(p.id,s.crossTrackDragOffsetY)));let W=!1;if(f){this.onMultiDragMove&&this.config.id&&(W=this.onMultiDragMove({draggedClipId:p.id,deltaTime:M,targetTrackY:s.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:s.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[F,H]of this.multiDragOriginalPositions){if(F===p.id)continue;const R=this.clips.find(U=>U.getClip().id===F);if(!R)continue;const K=Math.max(0,H.startTime+M),G=(T=this.clipGroups)==null?void 0:T.get(F);if(G){const U=ce(K,this.zoom,this.scrollLeft);G.x(U),G.y(this.resolveClipRenderY(F,s.crossTrackDragOffsetY)),G.visible(U+ve(H.duration,this.zoom)>0&&U<this.layer.width());const Z=R.getClip();ie.updateClipGroup(G,ve(Z.duration,this.zoom),this.trackHeight-4,Z.name,Z.duration,this.theme,!0,Z.thumbnails,Z.src,Z.type,!!Z.separatedAudioClipId,!0)}}}u&&this.onClipCrossTrackPreview&&this.config.id&&!W?this.onClipCrossTrackPreview(A,s.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():W?this.hideDropPreview():this.showDropPreview(A),this.updateSnapGuideLine(O.guideTime)}else this.hideDropPreview(),(b=this.onClearDropPreview)==null||b.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(c,h.width),this.layer.batchDraw(),(w=this.dragOverlayLayer)==null||w.batchDraw()}buildPreviewClip(e,t,i,n,s){const r=i-n.pointerStartX+(this.scrollLeft-n.dragStartScrollLeft),o=N.pixelsToTime(r,this.zoom);let l;return s==="resize-left"||e.isResizingLeft?l=this.buildResizeLeftPreviewClip(e,t,o):s==="resize-right"||e.isResizingRight?l=this.buildResizeRightPreviewClip(e,t,o):l={...e,startTime:Math.max(0,t.startTime+o),endTime:Math.max(0,t.startTime+o)+e.duration},this.constrainResizePreviewToTrackBounds(this.applyClipSnap(l,t,n.snapCandidateClips),t,n.nonDraggedClips)}constrainResizePreviewToTrackBounds(e,t,i){if(e.clip.isResizingLeft){const n=this.getResizeLeftBoundaryStart(t,i);if(e.clip.startTime>=n)return e;const s=e.clip.endTime,r=s-n;return{clip:{...e.clip,startTime:n,duration:r,endTime:s,startTimeAtSource:t.endTimeAtSource-r,endTimeAtSource:t.endTimeAtSource},guideTime:e.guideTime===n?e.guideTime:null}}if(e.clip.isResizingRight){const n=this.getResizeRightBoundaryEnd(t,i);if(e.clip.startTime+e.clip.duration<=n)return e;const r=n-e.clip.startTime;return{clip:{...e.clip,duration:r,endTime:n,endTimeAtSource:t.startTimeAtSource+r},guideTime:e.guideTime===n?e.guideTime:null}}return e}getResizeLeftBoundaryStart(e,t){let i=0;for(const n of t){if(n.startTime>=e.startTime)continue;const s=n.startTime+n.duration;i=Math.max(i,s)}return i}getResizeRightBoundaryEnd(e,t){let i=Number.POSITIVE_INFINITY;for(const n of t)n.startTime<e.endTime||(i=Math.min(i,n.startTime));return Number.isFinite(i)?i:Number.POSITIVE_INFINITY}buildResizeLeftPreviewClip(e,t,i){const s=Math.max(0,t.startTime+i)-t.startTime,o=Math.max(0,t.startTimeAtSource+i)-t.startTimeAtSource,l=Math.abs(s)<Math.abs(o)?s:o,h=N.calculateEndTime(t.startTime,t.duration);let c=t.startTime+l,d=t.duration-l,u;return d<1e3?(d=1e3,c=h-d,u=t.endTimeAtSource-d):u=t.startTimeAtSource+l,{...e,startTime:c,duration:d,endTime:c+d,startTimeAtSource:u,endTimeAtSource:t.endTimeAtSource}}buildResizeRightPreviewClip(e,t,i){let n=Math.max(1e3,t.duration+i);const s=t.startTimeAtSource,r=Math.min(t.sourceDuration,s+n);return n=r-s,{...e,startTime:t.startTime,duration:n,endTime:t.startTime+n,startTimeAtSource:s,endTimeAtSource:r}}applyClipSnap(e,t,i){if(!this.enableClipSnap||i.length===0)return{clip:e,guideTime:null};const n=i.flatMap(h=>[h.startTime,h.startTime+h.duration]);if(n.length===0)return{clip:e,guideTime:null};const s=N.pixelsToTime(this.clipSnapThreshold,this.zoom),r=e.startTime+e.duration,o=[];if(e.isResizingLeft)for(const h of n){const c=r-h,d=t.endTimeAtSource-c,u=Math.abs(h-e.startTime);u>s||c<1e3||d<0||o.push({clip:{...e,startTime:h,duration:c,endTime:r,startTimeAtSource:d,endTimeAtSource:t.endTimeAtSource},guideTime:h,distance:u})}else if(e.isResizingRight)for(const h of n){const c=h-e.startTime,d=t.startTimeAtSource+c,u=Math.abs(h-r);u>s||c<1e3||d>t.sourceDuration||o.push({clip:{...e,duration:c,endTime:e.startTime+c,endTimeAtSource:d},guideTime:h,distance:u})}else for(const h of n){const c=Math.abs(h-e.startTime);c<=s&&h>=0&&o.push({clip:{...e,startTime:h,endTime:h+e.duration},guideTime:h,distance:c});const d=h-e.duration,u=Math.abs(h-r);u<=s&&d>=0&&o.push({clip:{...e,startTime:d,endTime:d+e.duration},guideTime:h,distance:u})}if(o.length===0)return{clip:e,guideTime:null};o.sort((h,c)=>h.distance-c.distance);const l=o[0];return{clip:l.clip,guideTime:l.guideTime}}applyPreviewClipState(e){return this.selectedClip&&typeof this.selectedClip.applyPreviewState=="function"?(this.selectedClip.applyPreviewState(e),!0):(this.isVisualUpdate=!0,this.handleClipUpdate(e),this.isVisualUpdate=!1,!1)}setClipDragOverlayActive(e,t){var o,l;const i=this.getPromotedClipParents(),n=this.clipGroups.get(e);if(!n){i.delete(e);return}if(!t){const h=i.get(e);if(!h)return;n.remove(),h.parent.add(n);const c=(o=this.clips.find(d=>d.getClip().id===e))==null?void 0:o.getClip();c&&n.x(ce(c.startTime,this.zoom,this.scrollLeft)),n.y(2),i.delete(e),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw();return}if(i.has(e)||!this.dragOverlayLayer)return;const s=n.getParent();if(!s)return;const r=n.getAbsolutePosition();i.set(e,{parent:s,baseY:this.trackY}),n.remove(),this.dragOverlayLayer.add(n),n.position(r),n.moveToTop(),this.layer.batchDraw(),this.dragOverlayLayer.batchDraw()}resolveClipRenderY(e,t){const i=this.getPromotedClipParents().get(e);return((i==null?void 0:i.baseY)??0)+2+t}getPromotedClipParents(){return this.promotedClipParents instanceof Map||(this.promotedClipParents=new Map),this.promotedClipParents}updateSnapGuideLine(e){var t;(t=this.onSnapGuideChange)==null||t.call(this,this.enableClipSnap?e:null)}updateEdgeAutoScrollState(e,t){if(this.calculateHorizontalAutoScrollVelocity(e,t)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(Se.AUTO_SCROLL_EDGE_THRESHOLD,t/2),n=Se.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-n;if(e>=t)return n;if(e<i){const s=(i-e)/i;return-Math.max(1,Math.round(s*n))}if(e>t-i){const s=(e-(t-i))/i;return Math.max(1,Math.round(s*n))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}};g(Se,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),g(Se,"DEFAULT_CLIP_SNAP_THRESHOLD",8),g(Se,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(Se,"AUTO_SCROLL_MAX_SPEED",18);let ti=Se;class il{constructor(e,t,i,n,s,r){g(this,"layer");g(this,"playheadGroup");g(this,"playheadLine");g(this,"playheadTriangle");g(this,"theme");g(this,"currentTime",0);g(this,"zoom",100);g(this,"scrollLeft",0);g(this,"onTimeChange");g(this,"isDragging",!1);this.layer=e,this.currentTime=t,this.zoom=i,this.theme=s,this.onTimeChange=r,this.playheadGroup=ie.createGroup(),this.layer.add(this.playheadGroup),this.playheadLine=ie.createLine([0,0,0,n],this.theme.playhead,1),this.playheadGroup.add(this.playheadLine),this.playheadTriangle=new X.RegularPolygon({x:0,y:5,sides:3,radius:10,fill:this.theme.playhead,rotation:180}),this.playheadGroup.add(this.playheadTriangle),this.initEventListeners(),this.render()}initEventListeners(){var e,t,i;this.playheadGroup.on("mousedown",()=>{this.isDragging=!0}),(e=this.layer.getStage())==null||e.on("mousemove",n=>{this.isDragging&&this.handleMouseMove(n.evt)}),(t=this.layer.getStage())==null||t.on("mouseup",()=>{this.isDragging=!1}),(i=this.layer.getStage())==null||i.on("mouseleave",()=>{this.isDragging=!1})}handleMouseMove(e){if(!this.isDragging)return;const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=N.pixelsToTime(s-le+this.scrollLeft,this.zoom);this.setTime(r)}setTime(e){this.currentTime=Math.max(0,e),this.onTimeChange(this.currentTime),this.render()}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=e,this.render()}setHeight(e){this.playheadLine.points([0,0,0,e]),this.render()}render(){const e=N.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+le;this.playheadGroup.x(e),this.playheadGroup.visible(e>=0&&e<=this.layer.width()),this.layer.batchDraw()}getTime(){return this.currentTime}getPlayheadGroup(){return this.playheadGroup}}class Ds{constructor(e,t,i,n){g(this,"container");g(this,"tracks",[]);g(this,"theme");g(this,"width",200);g(this,"timeScaleHeight",40);g(this,"includeTimeScaleSpacer",!0);g(this,"trackList",null);g(this,"onMuteTrack");var s,r,o,l,h,c;this.container=e.container,this.width=e.width||200,this.timeScaleHeight=e.timeScaleHeight||40,this.includeTimeScaleSpacer=e.includeTimeScaleSpacer??!0,this.theme={background:((s=e.theme)==null?void 0:s.background)||"#1a1a1a",border:((r=e.theme)==null?void 0:r.border)||"#333333",text:((o=e.theme)==null?void 0:o.text)||"#ffffff",buttonBackground:((l=e.theme)==null?void 0:l.buttonBackground)||"#2a2a2a",buttonHover:((h=e.theme)==null?void 0:h.buttonHover)||"#3a3a3a",buttonDanger:((c=e.theme)==null?void 0:c.buttonDanger)||"#dc3545"},this.onMuteTrack=n,this.init()}init(){this.container.className="track-info-panel",this.container.style.position="relative",this.container.style.overflow="hidden",this.container.style.width=`${this.width}px`,this.container.style.background=this.theme.background,this.container.style.borderRight=`1px solid ${this.theme.border}`,this.container.style.color=this.theme.text,this.render()}setTracks(e){this.tracks=[...e],this.render()}getTracks(){return[...this.tracks]}render(){this.container.innerHTML="";const e=document.createElement("div");if(e.className="track-info-list",e.style.willChange="transform",e.style.transform="translateY(0px)",this.trackList=e,this.includeTimeScaleSpacer){const t=document.createElement("div");t.className="track-info-spacer",t.style.height=`${this.timeScaleHeight}px`,this.container.appendChild(t)}this.tracks.forEach((t,i)=>{const n=this.createTrackItem(t,i);e.appendChild(n)}),this.container.appendChild(e)}setScrollTop(e){this.trackList&&(this.trackList.style.transform=`translateY(${-Math.max(0,e)}px)`)}createTrackItem(e,t){const i=e.type==="video"?_e.VIDEO:_e.AUDIO,n=document.createElement("div");n.className="track-info-item",n.style.height=`${i}px`,n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="space-between",n.style.padding="0 12px",n.style.borderBottom=`1px solid ${this.theme.border}`,n.style.transition="background-color 0.15s ease",n.dataset.index=t.toString(),n.dataset.trackId=e.id,n.addEventListener("mouseenter",()=>{n.style.background=this.theme.buttonHover}),n.addEventListener("mouseleave",()=>{n.style.background="transparent"});const s=document.createElement("div");s.style.display="flex",s.style.alignItems="center",s.style.gap="8px";const r=document.createElement("span");r.className="track-icon",r.textContent=e.type==="video"?"🎬":"🎵",r.style.fontSize="18px",r.style.userSelect="none",s.appendChild(r);const o=document.createElement("div");o.style.display="flex",o.style.alignItems="center",o.style.gap="4px";const l=document.createElement("button");return l.className="track-mute-btn",l.textContent=e.isMuted?"🔇":"🔊",l.title=e.isMuted?"取消静音":"静音",l.style.background="transparent",l.style.border="none",l.style.color=this.theme.text,l.style.padding="4px",l.style.borderRadius="4px",l.style.cursor="pointer",l.style.fontSize="14px",l.style.transition="background-color 0.15s ease",l.addEventListener("click",h=>{h.stopPropagation(),this.onMuteTrack&&this.onMuteTrack(e.id,!e.isMuted)}),l.addEventListener("mouseenter",()=>{l.style.background=this.theme.buttonBackground}),l.addEventListener("mouseleave",()=>{l.style.background="transparent"}),o.appendChild(l),n.appendChild(s),n.appendChild(o),n}destroy(){this.trackList=null,this.container.innerHTML=""}}const nl={backgroundColor:"#1e1e1e",borderColor:"#333",textColor:"#e0e0e0",labelColor:"#999",inputBackground:"#2d2d2d",inputBorder:"#444",inputFocusBorder:"#409eff",buttonBackground:"#2d2d2d",buttonBorder:"#444",buttonActiveBackground:"#409eff",buttonActiveBorder:"#409eff",buttonActiveText:"#fff"},j={container:"clip-config-panel",tabBar:"clip-config-tab-bar",tabButton:"clip-config-tab-button",content:"clip-config-content",visualPanel:"clip-config-visual-panel",audioPanel:"clip-config-audio-panel",actionBar:"clip-config-action-bar",section:"clip-config-section",sectionTitle:"clip-config-section-title",row:"clip-config-row",label:"clip-config-label",slider:"clip-config-slider",input:"clip-config-input",presetGrid:"clip-config-preset-grid",presetButton:"clip-config-preset-button",resetButton:"clip-config-reset-button",emptyState:"clip-config-empty-state"},sl={visual:"画面",audio:"音频"};class Os{constructor(e){g(this,"container");g(this,"rootElement",null);g(this,"theme");g(this,"onClipUpdate");g(this,"currentClip",null);g(this,"activeTab","visual");g(this,"tabBar",null);g(this,"contentArea",null);g(this,"visualPanel",null);g(this,"audioPanel",null);g(this,"xSlider",null);g(this,"xInput",null);g(this,"ySlider",null);g(this,"yInput",null);g(this,"scaleSlider",null);g(this,"scaleInput",null);g(this,"volumeSlider",null);g(this,"volumeInput",null);this.container=e.container,this.theme=e.theme??nl,this.onClipUpdate=e.onClipUpdate,this.render()}setClip(e){this.currentClip=e,(e==null?void 0:e.type)==="video"?this.activeTab="visual":(e==null?void 0:e.type)==="audio"&&(this.activeTab="audio"),this.render()}destroy(){this.rootElement&&(this.rootElement.remove(),this.rootElement=null)}getAvailableTabs(){return this.currentClip?this.currentClip.type==="audio"?["audio"]:["visual","audio"]:[]}render(){this.rootElement&&this.rootElement.remove(),this.rootElement=document.createElement("div"),this.rootElement.className=j.container,this.applyBaseTheme(),this.currentClip?this.renderPanel():this.renderEmptyState(),this.container.appendChild(this.rootElement)}applyBaseTheme(){this.rootElement&&(this.rootElement.style.backgroundColor=this.theme.backgroundColor,this.rootElement.style.border=`1px solid ${this.theme.borderColor}`,this.rootElement.style.borderRadius="4px",this.rootElement.style.color=this.theme.textColor,this.rootElement.style.fontFamily='-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',this.rootElement.style.fontSize="13px",this.rootElement.style.display="flex",this.rootElement.style.flexDirection="column",this.rootElement.style.overflow="hidden",this.rootElement.style.height="100%")}renderEmptyState(){const e=document.createElement("div");e.className=j.emptyState,e.style.textAlign="center",e.style.padding="40px 20px",e.style.color=this.theme.labelColor;const t=document.createElement("div");t.style.fontSize="24px",t.style.marginBottom="8px",t.textContent="🎬";const i=document.createElement("div");i.style.fontSize="13px",i.textContent="请选择一个片段",e.appendChild(t),e.appendChild(i),this.rootElement.appendChild(e)}renderPanel(){this.renderTabBar(),this.renderContentArea(),this.renderActionBar()}renderTabBar(){const e=this.getAvailableTabs();this.tabBar=document.createElement("div"),this.tabBar.className=j.tabBar,this.tabBar.style.display="flex",this.tabBar.style.gap="12px",this.tabBar.style.padding="4px",this.tabBar.style.backgroundColor="#2a2a2a",this.tabBar.style.borderRadius="4px 4px 0 0",e.forEach(t=>{const i=document.createElement("button");i.className=j.tabButton,i.textContent=sl[t],i.style.lineHeight="22px",i.style.padding="0 6px",i.style.border="none",i.style.cursor="pointer",i.style.fontSize="13px",i.style.fontFamily="inherit",i.style.transition="background-color 0.15s, color 0.15s";const n=this.activeTab===t;i.style.backgroundColor=n?"#595A5D":"transparent",i.style.color=n?"#fff":"#b5b6bf",i.style.borderRadius="4px",i.addEventListener("click",()=>{this.activeTab=t,this.updateTabBarState(),this.updateContentVisibility()}),this.tabBar.appendChild(i)}),this.rootElement.appendChild(this.tabBar)}updateTabBarState(){if(!this.tabBar)return;const e=this.tabBar.querySelectorAll(`.${j.tabButton}`),t=this.getAvailableTabs();e.forEach((i,n)=>{const r=t[n]===this.activeTab,o=i;o.style.backgroundColor=r?"#595A5D":"transparent",o.style.color=r?"#fff":"#b5b6bf"})}renderContentArea(){this.contentArea=document.createElement("div"),this.contentArea.className=j.content,this.contentArea.style.padding="12px",this.contentArea.style.flex="1",this.contentArea.style.overflowY="auto",this.contentArea.style.minHeight="0",this.renderVisualPanel(),this.renderAudioPanel(),this.updateContentVisibility(),this.rootElement.appendChild(this.contentArea)}updateContentVisibility(){this.visualPanel&&(this.visualPanel.style.display=this.activeTab==="visual"?"block":"none"),this.audioPanel&&(this.audioPanel.style.display=this.activeTab==="audio"?"block":"none")}renderVisualPanel(){this.visualPanel=document.createElement("div"),this.visualPanel.className=j.visualPanel;const e=document.createElement("div");e.className=j.section,e.style.marginBottom="16px";const t=document.createElement("div");t.className=j.sectionTitle,t.style.fontSize="12px",t.style.color=this.theme.labelColor,t.style.marginBottom="8px",t.style.textTransform="uppercase",t.textContent="位置",e.appendChild(t),this.renderPositionControl(e,"X","x"),this.renderPositionControl(e,"Y","y"),this.renderPresetGrid(e),this.visualPanel.appendChild(e);const i=document.createElement("div");i.className=j.section,i.style.borderTop=`1px solid ${this.theme.borderColor}`,i.style.paddingTop="16px";const n=document.createElement("div");n.className=j.sectionTitle,n.style.fontSize="12px",n.style.color=this.theme.labelColor,n.style.marginBottom="8px",n.style.textTransform="uppercase",n.textContent="缩放",i.appendChild(n),this.renderScaleControl(i),this.visualPanel.appendChild(i),this.contentArea.appendChild(this.visualPanel)}renderAudioPanel(){this.audioPanel=document.createElement("div"),this.audioPanel.className=j.audioPanel;const e=document.createElement("div");e.className=j.section;const t=document.createElement("div");t.className=j.sectionTitle,t.style.fontSize="12px",t.style.color=this.theme.labelColor,t.style.marginBottom="8px",t.style.textTransform="uppercase",t.textContent="音量",e.appendChild(t),this.renderVolumeControl(e),this.audioPanel.appendChild(e),this.contentArea.appendChild(this.audioPanel)}renderActionBar(){const e=document.createElement("div");e.className=j.actionBar,e.style.borderTop=`1px solid ${this.theme.borderColor}`,e.style.borderRadius="0 0 4px 4px",e.style.minHeight="36px",e.style.backgroundColor="#2a2a2a",this.rootElement.appendChild(e)}renderPositionControl(e,t,i){var u,f,p,y,S,C;const n=document.createElement("div");n.className=j.row,n.style.display="flex",n.style.alignItems="center",n.style.gap="8px",n.style.marginBottom="8px";const s=document.createElement("label");s.className=j.label,s.style.width="16px",s.style.fontSize="13px",s.style.color=this.theme.labelColor,s.textContent=t,n.appendChild(s);const o=(((f=(u=this.currentClip)==null?void 0:u.visualTransform)==null?void 0:f.scale)??1)/2,l=-o,h=1+o,c=document.createElement("input");c.type="range",c.className=j.slider,c.min=String(l),c.max=String(h),c.step="0.01",c.value=String(((y=(p=this.currentClip)==null?void 0:p.visualTransform)==null?void 0:y[i])??.5),c.style.flex="1",c.style.height="4px",c.addEventListener("input",T=>{const b=parseFloat(T.target.value);this.handleTransformChange(i,b)}),n.appendChild(c);const d=document.createElement("input");d.type="number",d.className=j.input,d.min=String(l),d.max=String(h),d.step="0.01",d.value=String(((C=(S=this.currentClip)==null?void 0:S.visualTransform)==null?void 0:C[i])??.5),d.style.width="60px",d.style.padding="4px 6px",d.style.border=`1px solid ${this.theme.inputBorder}`,d.style.borderRadius="4px",d.style.fontSize="12px",d.style.backgroundColor=this.theme.inputBackground,d.style.color=this.theme.textColor,d.addEventListener("change",T=>{const b=parseFloat(T.target.value);this.handleTransformChange(i,b)}),n.appendChild(d),i==="x"?(this.xSlider=c,this.xInput=d):(this.ySlider=c,this.yInput=d),e.appendChild(n)}renderPresetGrid(e){const t=document.createElement("div");t.className=j.presetGrid,t.style.display="grid",t.style.gridTemplateColumns="repeat(3, 1fr)",t.style.gap="4px",[{label:"↖ 左上",x:"left",y:"top"},{label:"↑ 上中",x:"center",y:"top"},{label:"↗ 右上",x:"right",y:"top"},{label:"← 左中",x:"left",y:"center"},{label:"● 居中",x:"center",y:"center"},{label:"右中 →",x:"right",y:"center"},{label:"↙ 左下",x:"left",y:"bottom"},{label:"↓ 下中",x:"center",y:"bottom"},{label:"↘ 右下",x:"right",y:"bottom"}].forEach(n=>{const s=document.createElement("button");s.className=j.presetButton,s.textContent=n.label,s.style.padding="6px",s.style.border=`1px solid ${this.theme.buttonBorder}`,s.style.borderRadius="4px",s.style.background=this.theme.buttonBackground,s.style.fontSize="11px",s.style.cursor="pointer",s.style.color=this.theme.textColor,s.addEventListener("click",()=>{const{x:r,y:o}=this.calculatePresetPosition(n.x,n.y);this.handleTransformChanges({x:r,y:o})}),t.appendChild(s)}),e.appendChild(t)}calculatePresetPosition(e,t){var o,l;const n=(((l=(o=this.currentClip)==null?void 0:o.visualTransform)==null?void 0:l.scale)??1)/2,s={left:n,center:.5,right:1-n},r={top:n,center:.5,bottom:1-n};return{x:s[e],y:r[t]}}renderScaleControl(e){var r,o,l,h;const t=document.createElement("div");t.className=j.row,t.style.display="flex",t.style.alignItems="center",t.style.gap="8px";const i=document.createElement("input");i.type="range",i.className=j.slider,i.min="0.1",i.max="8",i.step="0.1",i.value=String(((o=(r=this.currentClip)==null?void 0:r.visualTransform)==null?void 0:o.scale)??1),i.style.flex="1",i.style.height="4px",i.addEventListener("input",c=>{const d=parseFloat(c.target.value);this.handleTransformChange("scale",d)}),t.appendChild(i);const n=document.createElement("input");n.type="number",n.className=j.input,n.min="0.1",n.max="8",n.step="0.1",n.value=String(((h=(l=this.currentClip)==null?void 0:l.visualTransform)==null?void 0:h.scale)??1),n.style.width="60px",n.style.padding="4px 6px",n.style.border=`1px solid ${this.theme.inputBorder}`,n.style.borderRadius="4px",n.style.fontSize="12px",n.style.backgroundColor=this.theme.inputBackground,n.style.color=this.theme.textColor,n.addEventListener("change",c=>{const d=parseFloat(c.target.value);this.handleTransformChange("scale",d)}),t.appendChild(n);const s=document.createElement("button");s.className=j.resetButton,s.textContent="重置",s.style.padding="4px 8px",s.style.border=`1px solid ${this.theme.buttonBorder}`,s.style.borderRadius="4px",s.style.background=this.theme.buttonBackground,s.style.fontSize="11px",s.style.cursor="pointer",s.style.color=this.theme.textColor,s.addEventListener("click",()=>{this.handleTransformChange("scale",1)}),t.appendChild(s),this.scaleSlider=i,this.scaleInput=n,e.appendChild(t)}renderVolumeControl(e){var r,o;const t=document.createElement("div");t.className=j.row,t.style.display="flex",t.style.alignItems="center",t.style.gap="8px";const i=document.createElement("input");i.type="range",i.className=j.slider,i.min="0",i.max="1",i.step="0.01",i.value=String(((r=this.currentClip)==null?void 0:r.volume)??1),i.style.flex="1",i.style.height="4px",i.addEventListener("input",l=>{const h=parseFloat(l.target.value);this.handleVolumeChange(h)}),t.appendChild(i);const n=document.createElement("input");n.type="number",n.className=j.input,n.min="0",n.max="100",n.step="1",n.value=String(Math.round((((o=this.currentClip)==null?void 0:o.volume)??1)*100)),n.style.width="60px",n.style.padding="4px 6px",n.style.border=`1px solid ${this.theme.inputBorder}`,n.style.borderRadius="4px",n.style.fontSize="12px",n.style.backgroundColor=this.theme.inputBackground,n.style.color=this.theme.textColor,n.addEventListener("change",l=>{const h=parseFloat(l.target.value)/100;this.handleVolumeChange(Math.max(0,Math.min(1,h)))}),t.appendChild(n);const s=document.createElement("span");s.style.fontSize="12px",s.style.color=this.theme.labelColor,s.textContent="%",t.appendChild(s),this.volumeSlider=i,this.volumeInput=n,e.appendChild(t)}handleVolumeChange(e){if(!this.currentClip||!this.onClipUpdate)return;const t=Math.max(0,Math.min(1,e));this.currentClip={...this.currentClip,volume:t},this.updateVolumeControls(),this.onClipUpdate(this.currentClip.id,{volume:t})}updateVolumeControls(){var t;const e=((t=this.currentClip)==null?void 0:t.volume)??1;this.volumeSlider&&(this.volumeSlider.value=String(e)),this.volumeInput&&(this.volumeInput.value=String(Math.round(e*100)))}clampValue(e,t){return e==="scale"?Math.max(.1,Math.min(8,t)):t}updateUIControls(){var s;const e=((s=this.currentClip)==null?void 0:s.visualTransform)??{x:.5,y:.5,scale:1},t=e.scale/2,i=-t,n=1+t;this.updateSliderAndInput(this.xSlider,this.xInput,e.x,i,n),this.updateSliderAndInput(this.ySlider,this.yInput,e.y,i,n),this.scaleSlider&&(this.scaleSlider.value=String(e.scale)),this.scaleInput&&(this.scaleInput.value=String(e.scale))}updateSliderAndInput(e,t,i,n,s){e&&(e.value=String(i),e.min=String(n),e.max=String(s)),t&&(t.value=String(i),t.min=String(n),t.max=String(s))}handleTransformChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(e,t),s={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:i};this.currentClip={...this.currentClip,visualTransform:s},this.updateUIControls(),this.onClipUpdate(this.currentClip.id,{visualTransform:s})}handleTransformChanges(e){if(!this.currentClip||!this.onClipUpdate)return;const i={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1}};e.x!==void 0&&(i.x=this.clampValue("x",e.x)),e.y!==void 0&&(i.y=this.clampValue("y",e.y)),e.scale!==void 0&&(i.scale=this.clampValue("scale",e.scale)),this.currentClip={...this.currentClip,visualTransform:i},this.updateUIControls(),this.onClipUpdate(this.currentClip.id,{visualTransform:i})}}class _n{constructor(e){this.timelineStore=e}selectClip(e){return this.updateSelection(e)}clearSelection(){return this.updateSelection(null)}findClipById(e,t){for(const i of e){const n=i.getClips().find(s=>s.id===t);if(n)return{clip:n,track:i,trackId:this.resolveTrackId(i)}}return null}findClipAtTime(e,t){for(const i of e){const n=i.getClips().find(s=>t>=s.startTime&&t<s.startTime+s.duration);if(n)return{clip:n,track:i,trackId:this.resolveTrackId(i)}}return null}prepareRemoveClip(e,t){const i=this.findClipById(t,e);return i?{exists:!0,clip:i.clip,trackId:i.trackId,shouldClearSelection:this.timelineStore.getPrimarySelectedClipId()===e}:{exists:!1,clip:null,trackId:null,shouldClearSelection:!1}}prepareMoveClipToTrack(e,t,i){var c;const n=this.findClipById(i,e);if(!n||!n.trackId)return{status:"missing_source_track",clipId:e,targetTrackId:t};const{clip:s,track:r,trackId:o}=n;if(o===t)return{status:"noop",clipId:e,sourceTrackId:o,targetTrackId:t};const l=i.find(d=>this.resolveTrackId(d)===t);if(!l)return{status:"missing_target_track",clipId:e,targetTrackId:t,sourceTrackId:o};const h=(c=l.getTrackType)==null?void 0:c.call(l);return h&&h!==s.type?{status:"track_type_mismatch",clipId:e,targetTrackId:t,sourceTrackId:o}:{status:"ready",clip:s,sourceTrack:r,sourceTrackId:o,targetTrack:l,targetTrackId:t}}planTrackPlacement(e,t){var s;const i=e.startTime+e.duration;for(const r of t){if(((s=r.getTrackType)==null?void 0:s.call(r))!==e.type)continue;if(!r.getClips().some(l=>e.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(r);if(l)return{status:"use_existing_track",trackId:l}}}const n=t.filter(r=>{var o;return((o=r.getTrackType)==null?void 0:o.call(r))===e.type}).length+1;return{status:"create_track",trackType:e.type,suggestedTrackName:e.type==="video"?`视频轨道 ${n}`:`音频轨道 ${n}`}}planCrossTrackMove(e,t,i,n,s,r){var p;const o=this.resolveTrackTargetByY(t,n,s,e.type);if(o.status==="create_track")return{status:"create_track",trackType:e.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const h=r.find(y=>this.resolveTrackId(y)===l);if(!h)return{status:"missing_target_track_view",targetTrackId:l};const c=this.resolveTrackType(h)??((p=s.find(y=>y.id===l))==null?void 0:p.type)??null;if(c!==e.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:c};if(!this.hasOverlapOnTrack(e,h))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(e.type,l,t,n,s);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=s.filter(y=>y.type===e.type).map(y=>y.id),f=u.indexOf(l);for(let y=1;y<=u.length;y+=1){const S=f-y;if(S>=0){const T=u[S],b=r.find(w=>this.resolveTrackId(w)===T);if(b&&!this.hasOverlapOnTrack(e,b))return{status:"move_to_track",targetTrackId:T}}const C=f+y;if(C<u.length){const T=u[C],b=r.find(w=>this.resolveTrackId(w)===T);if(b&&!this.hasOverlapOnTrack(e,b))return{status:"move_to_track",targetTrackId:T}}}return{status:"create_track",trackType:e.type,insertionPlacement:e.type==="video"?"before_primary":"after_primary"}}planCrossTrackPreview(e,t,i,n,s,r){const o=this.planCrossTrackMove(e,t,i,n,s,r);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(e){const t=Math.max(0,e);return this.updateCurrentTime(t)}setZoom(e){const t=Math.max(de.MIN,Math.min(de.MAX,e));return this.updateZoom(t)}setSpeed(e){const t=Math.max(.1,Math.min(10,e));return this.updateSpeed(t)}updateSelection(e){const t=this.timelineStore.getPrimarySelectedClipId();return t===e?{previousClipId:t,nextClipId:e,changed:!1}:(e===null?this.timelineStore.clearSelection():this.timelineStore.setPrimarySelectedClipId(e),{previousClipId:t,nextClipId:e,changed:!0})}updateCurrentTime(e){const t=this.timelineStore.getCurrentTime();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setCurrentTime(e),{previousValue:t,nextValue:e,changed:!0})}updateZoom(e){const t=this.timelineStore.getZoom();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setZoom(e),{previousValue:t,nextValue:e,changed:!0})}updateSpeed(e){const t=this.timelineStore.getSpeed();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setSpeed(e),{previousValue:t,nextValue:e,changed:!0})}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}resolveTrackType(e){return typeof e.getTrackType=="function"?e.getTrackType():e.type??null}resolveTrackTargetByY(e,t,i,n){let s=t,r=null,o=null;for(const l of i){const h=l.type==="video"?_e.VIDEO:_e.AUDIO,c=s+h;if(l.type===n&&(r===null&&(r=s),o=c),e>=s&&e<c)return{status:"existing_track",targetTrackId:l.id};s=c}return n==="video"&&r!==null&&e<r?{status:"create_track",insertionPlacement:"top_of_type_region"}:n==="audio"&&o!==null&&e>=o?{status:"create_track",insertionPlacement:"bottom_of_type_region"}:{status:"missing_target_track_by_position"}}resolvePreferredInsertionPlacement(e,t,i,n,s){let r=n;const o=s.map(d=>{const u=r,f=d.type==="video"?_e.VIDEO:_e.AUDIO,p=u+f;return r=p,{id:d.id,type:d.type,role:d.role,startY:u,endY:p,height:f}}).filter(d=>d.type===e),l=o.findIndex(d=>d.id===t);if(l===-1)return null;const h=o[l],c=Math.min(12,Math.max(6,Math.floor(h.height/4)));return h.role==="primary"?{insertionPlacement:e==="video"?"before_track":"after_track",referenceTrackId:t}:l<o.length-1&&i>=h.endY-c?{insertionPlacement:"after_track",referenceTrackId:t}:{insertionPlacement:"before_track",referenceTrackId:t}}hasOverlapOnTrack(e,t){const i=e.startTime+e.duration;return t.getClips().some(n=>n.id===e.id?!1:e.startTime<n.endTime&&i>n.startTime)}}class Li{constructor(e,t,i,n=100){g(this,"state");g(this,"maxHistorySize",100);g(this,"onActionUndo");g(this,"onActionRedo");g(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=n,this.onActionUndo=e,this.onActionRedo=t,this.onHistoryChange=i}addAction(e){this.state.past.length>=this.maxHistorySize&&this.state.past.shift(),this.state.past.push({...e,timestamp:Date.now()}),this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}undo(){if(this.state.past.length===0)return!1;const e=this.state.past.pop();return this.state.future.push(e),this.onActionUndo(e),this.onHistoryChange&&this.onHistoryChange(),!0}redo(){if(this.state.future.length===0)return!1;const e=this.state.future.pop();return this.state.past.push(e),this.onActionRedo(e),this.onHistoryChange&&this.onHistoryChange(),!0}clear(){this.state.past=[],this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}canUndo(){return this.state.past.length>0}canRedo(){return this.state.future.length>0}getState(){return{...this.state}}createAddClipAction(e){return{type:"add_clip",data:e,timestamp:Date.now()}}createRemoveClipAction(e){return{type:"remove_clip",data:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null},timestamp:Date.now()}}createRemoveClipActionWithTrackSnapshot(e,t,i,n=null){return{type:"remove_clip",data:{clip:e,sourceTrackId:t,sourceTrackSnapshot:i,sourceTrackRestoreAnchor:n},timestamp:Date.now()}}createUpdateClipAction(e,t,i){return{type:"update_clip",data:{clipId:e,updates:t,previousState:i},timestamp:Date.now()}}createSplitClipAction(e,t,i){return{type:"split_clip",data:{originalClip:e,clip1:t,clip2:i},timestamp:Date.now()}}createMoveClipAction(e,t,i){return{type:"move_clip",data:{clipId:e,newStartTime:t,previousStartTime:i},timestamp:Date.now()}}createResizeClipAction(e,t,i,n,s){return{type:"resize_clip",data:{clipId:e,newDuration:t,newStartTime:i,previousDuration:n,previousStartTime:s},timestamp:Date.now()}}createSetTimeAction(e,t){return{type:"set_time",data:{newTime:e,previousTime:t},timestamp:Date.now()}}createRemoveGapsAction(e){return{type:"remove_gaps",data:{clipsBefore:e},timestamp:Date.now()}}createMultiClipUpdateAction(e){return{type:"multi_clip_update",data:{clipUpdates:e},timestamp:Date.now()}}createMoveClipBetweenTracksAction(e,t,i,n,s,r,o){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:n,clipAfter:s,sourceTrackSnapshot:r,targetTrackSnapshot:o},timestamp:Date.now()}}createSeparateClipAudioAction(e,t,i,n){return{type:"separate_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:n},timestamp:Date.now()}}createRestoreClipAudioAction(e,t,i,n){return{type:"restore_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:n},timestamp:Date.now()}}createCompoundAction(e,t){return{type:"compound",data:{actions:e,...t?{label:t}:{}},timestamp:Date.now()}}}class xn{constructor(e){this.target=e}executeUndo(e){this.executeUndoInternal(e,new Map)}executeRedo(e){this.executeRedoInternal(e,new Map)}executeUndoInternal(e,t){var i,n;switch(e.type){case"add_clip":this.target.removeClip(e.data.id);break;case"remove_clip":{const s=this.normalizeRemoveClipActionData(e.data);let r=!1;const o=this.resolveTrackIdForHistorySnapshot(s.sourceTrackSnapshot,s.sourceTrackId,t,s.sourceTrackRestoreAnchor);if(o&&(r=this.target.addClipToTrack(o,s.clip)),!r){const l=this.target.findTrackByClipId(s.clip.id)||this.target.getDefaultTrack();l==null||l.addClip(s.clip)}(n=(i=this.target).loadClipThumbnails)==null||n.call(i,s.clip);break}case"update_clip":this.target.updateClip(e.data.clipId,e.data.previousState);break;case"split_clip":{this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id);const s=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack();s==null||s.addClip(e.data.originalClip);break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.previousStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.previousDuration,startTime:e.data.previousStartTime});break;case"remove_gaps":this.target.getClips().forEach(s=>this.target.removeClip(s.id)),e.data.clipsBefore.forEach(s=>{const r=this.target.findTrackByClipId(s.id)||this.target.getDefaultTrack();r==null||r.addClip(s)});break;case"multi_clip_update":e.data.clipUpdates.forEach(s=>{this.target.updateClip(s.clipId,s.previousState)});break;case"move_clip_between_tracks":this.restoreMovedClip(e.data.clipId,e.data.sourceTrackSnapshot,e.data.clipBefore,t);break;case"separate_clip_audio":e.data.audioClip&&this.target.removeClip(e.data.audioClip.id),this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"compound":[...e.data.actions].reverse().forEach(s=>{this.executeUndoInternal(s,t)});break;default:L.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:e.type})}}executeRedoInternal(e,t){var i,n;switch(e.type){case"add_clip":{const s=e.data,r=this.target.findTrackByClipId(s.id)||this.target.getDefaultTrack();r==null||r.addClip(s),(n=(i=this.target).loadClipThumbnails)==null||n.call(i,s);break}case"remove_clip":this.target.removeClip(e.data.clip.id);break;case"update_clip":this.target.updateClip(e.data.clipId,e.data.updates);break;case"split_clip":{this.target.removeClip(e.data.originalClip.id);const s=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack();s==null||s.addClip(e.data.clip1),s==null||s.addClip(e.data.clip2);break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.newStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.newDuration,startTime:e.data.newStartTime});break;case"remove_gaps":this.target.removeClipGaps();break;case"multi_clip_update":e.data.clipUpdates.forEach(s=>{this.target.updateClip(s.clipId,s.newState)});break;case"move_clip_between_tracks":this.restoreMovedClip(e.data.clipId,e.data.targetTrackSnapshot,e.data.clipAfter,t);break;case"separate_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter),e.data.audioClip&&e.data.audioTrackId&&this.target.addClipToTrack(e.data.audioTrackId,e.data.audioClip);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter);break;case"compound":e.data.actions.forEach(s=>{this.executeRedoInternal(s,t)});break;default:L.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:e.type})}}restoreMovedClip(e,t,i,n){const s=this.resolveTrackIdForHistorySnapshot(t,(t==null?void 0:t.id)??null,n,null);s&&this.target.moveClipToTrack(e,s),this.target.updateClip(e,i)}normalizeRemoveClipActionData(e){return"clip"in e?e:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null}}resolveTrackIdForHistorySnapshot(e,t,i,n){const s=(e==null?void 0:e.id)??t??null;if(s){const o=i.get(s);if(o)return o}if(!e)return t;const r=this.target.ensureTrackFromHistorySnapshot(e,this.resolveRestoreAnchor(n,i))??t;return s&&r&&i.set(s,r),r}resolveRestoreAnchor(e,t){return e?{previousTrackId:e.previousTrackId?t.get(e.previousTrackId)??e.previousTrackId:null,nextTrackId:e.nextTrackId?t.get(e.nextTrackId)??e.nextTrackId:null}:null}}const rl=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId"],al=new Set(["thumbnails"]);function ol(a,e){return Object.is(a,e)?!0:a===void 0||e===void 0?!1:typeof a=="object"&&typeof e=="object"?JSON.stringify(a)===JSON.stringify(e):!1}class In{constructor(e){this.history=e}recordAddClip(e){const t=this.history.createAddClipAction(e);return this.history.addAction(t),t}createRemoveClipAction(e,t=null,i=null,n=null){return t||i?this.history.createRemoveClipActionWithTrackSnapshot(e,t,i,n):this.history.createRemoveClipAction(e)}recordRemoveClip(e,t=null,i=null,n=null){const s=this.createRemoveClipAction(e,t,i,n);return this.history.addAction(s),s}recordClipUpdate(e,t,i){const n=this.createClipUpdateAction(e,t,i);return n?(this.history.addAction(n),n):null}recordSplitClip(e,t){const i={...e,id:e.id.replace("_split_",""),duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},n=this.history.createSplitClipAction(i,e,t);return this.history.addAction(n),n}recordRemoveGaps(e){if(e.length===0)return null;const t=this.history.createRemoveGapsAction(e);return this.history.addAction(t),t}recordMoveClipBetweenTracks(e,t,i,n,s,r,o){const l=this.history.createMoveClipBetweenTracksAction(e,t,i,n,s,r,o);return this.history.addAction(l),l}recordSeparateClipAudio(e,t,i,n){const s=this.history.createSeparateClipAudioAction(e,t,i,n);return this.history.addAction(s),s}recordRestoreClipAudio(e,t,i,n){const s=this.history.createRestoreClipAudioAction(e,t,i,n);return this.history.addAction(s),s}createSeparateClipAudioAction(e,t,i,n){return this.history.createSeparateClipAudioAction(e,t,i,n)}createRestoreClipAudioAction(e,t,i,n){return this.history.createRestoreClipAudioAction(e,t,i,n)}recordCompoundAction(e,t){if(e.length===0)return null;const i=this.history.createCompoundAction(e,t);return this.history.addAction(i),i}createClipUpdateAction(e,t,i){if(i&&i.length>0)return this.history.createMultiClipUpdateAction(i);if(!t)return null;if(t.startTime!==e.startTime&&t.duration===e.duration)return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);if(t.duration!==e.duration)return this.history.createResizeClipAction(e.id,e.duration,e.startTime,t.duration,t.startTime);const r={},o={};return rl.forEach(h=>{ol(e[h],t[h])||(r[h]=e[h],o[h]=t[h])}),Object.keys(r).length===0||Object.keys(r).every(h=>al.has(h))?null:this.history.createUpdateClipAction(e.id,r,o)}}function Xt(a){a.notifySelectionChange(),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function ll(a){var e,t;a.notifySelectionChange(),(e=a.reloadClipThumbnailsIfNeeded)==null||e.call(a),(t=a.checkTrackDurationChange)==null||t.call(a),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function hl(a,e,t=!1){if(!e||!t||a.type==="audio")return!1;const i=e.duration!==a.duration,n=e.startTimeAtSource!==a.startTimeAtSource||e.endTimeAtSource!==a.endTimeAtSource;return i||n}function cl(a,e){if(a.length===0)return!1;const t=Math.max(...a.map(i=>i.endTime));return e<t}function dl(a){return a.currentCanPlay===a.nextCanPlay?a.currentCanPlay:(a.setCanPlay(a.nextCanPlay),a.currentCanPlay&&!a.nextCanPlay&&a.playState==="playing"&&(a.pauseTimeline(),a.setCurrentTime(a.clipEndTime||1)),a.emitCanPlayChange(a.nextCanPlay),a.nextCanPlay)}function ul(a){const e=!a.id&&a.startTime>0;return{shouldJumpToTime:e,jumpTime:e?a.startTime:null,shouldSelectClip:!!a.id}}function Zt(a){var e;return a.applied?(a.isExecutingHistoryAction||(e=a.recordHistory)==null||e.call(a),a.applyEffects(),!0):!1}function gl(a){return Zt({applied:a.applied,isExecutingHistoryAction:a.isExecutingHistoryAction,recordHistory:()=>{var e;(e=a.recordMoveClipBetweenTracks)==null||e.call(a,a.clipId,a.sourceTrackId,a.targetTrackId,a.clipBefore,a.clipAfter,a.sourceTrackSnapshot,a.targetTrackSnapshot)},applyEffects:a.applyEffects})}function pl(a){var e;a.isExecutingHistoryAction||(e=a.recordSplitClip)==null||e.call(a,a.clip1,a.clip2),a.emitClipUpdated(a.clip1),a.emitClipAdded(a.clip2),a.applyEffects()}const fi={x:.5,y:.5,scale:1},fl=.1,ml=8;function mi(a,e){return typeof a=="number"&&Number.isFinite(a)?a:e}function yl(a){return Math.min(ml,Math.max(fl,a))}function fe(a){return{x:mi(a==null?void 0:a.x,fi.x),y:mi(a==null?void 0:a.y,fi.y),scale:yl(mi(a==null?void 0:a.scale,fi.scale))}}function Bs(a,e,t=1e-4){const i=fe(a),n=fe(e);return Math.abs(i.x-n.x)<=t&&Math.abs(i.y-n.y)<=t&&Math.abs(i.scale-n.scale)<=t}function Gs(a,e){if(a.width<=0||a.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const t=e.width>0?e.width:a.width,i=e.height>0?e.height:a.height,n=t/i,s=a.width/a.height;let r=a.width,o=a.height;n>s?o=r/n:r=o*n;const l=(a.width-r)/2,h=(a.height-o)/2;return{left:l,top:h,width:r,height:o,centerX:l+r/2,centerY:h+o/2}}function An(a,e,t){const i=Gs(a,e),n=fe(t),s=i.width*n.scale,r=i.height*n.scale,o=a.width*n.x,l=a.height*n.y;return{left:o-s/2,top:l-r/2,width:s,height:r,centerX:o,centerY:l}}function Sl(a,e,t,i){const n=fe(a),s=i.width>0?i.width:1,r=i.height>0?i.height:1;return fe({x:n.x+e/s,y:n.y+t/r,scale:n.scale})}function Cl(a,e,t,i,n,s){const r=fe(s),o=Math.max(n.width/2,1),l=Math.max(n.height/2,1),h=Math.abs(t-a)/o,c=Math.abs(i-e)/l;return fe({x:r.x,y:r.y,scale:Math.max(h,c)})}function En(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}class vl{constructor(e={}){g(this,"frameElement",null);g(this,"overlayElement",null);g(this,"boxElement",null);g(this,"handleElements",new Map);g(this,"handlePointerDownHandlers",new Map);g(this,"state",null);g(this,"interaction",null);g(this,"callbacks");g(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});g(this,"boundPointerUp",()=>{this.finishInteraction(!0)});g(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});g(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});g(this,"handleMovePointerDown",e=>{var i,n;const t=e;(t.button??0)!==0||!this.state||((i=t.preventDefault)==null||i.call(t),(n=t.stopPropagation)==null||n.call(t),this.interaction={clipId:this.state.clipId,mode:"move",pointerStart:this.toLocalPoint(t),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing"},this.setGlobalCursor("grabbing"),this.bindDocumentListeners())});this.callbacks=e}attach(e){if(this.frameElement===e&&this.overlayElement){this.render();return}this.detach(),this.frameElement=e;const t=document.createElement("div");t.className="timeline-preview-transform-overlay",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="3000";const i=document.createElement("div");i.className="timeline-preview-transform-box",i.style.position="absolute",i.style.display="none",i.style.boxSizing="border-box",i.style.border="1px solid rgba(80, 227, 194, 0.95)",i.style.cursor="grab",i.style.pointerEvents="auto",i.style.userSelect="none",i.addEventListener("pointerdown",this.handleMovePointerDown),t.appendChild(i),this.overlayElement=t,this.boxElement=i,this.createHandle("top-left","nwse-resize"),this.createHandle("top-right","nesw-resize"),this.createHandle("bottom-right","nwse-resize"),this.createHandle("bottom-left","nesw-resize"),e.appendChild(t),this.render()}detach(){var e,t;this.finishInteraction(!1),(e=this.boxElement)==null||e.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,n)=>{const s=this.handlePointerDownHandlers.get(n);s&&i.removeEventListener("pointerdown",s)}),this.handleElements.clear(),this.handlePointerDownHandlers.clear(),(t=this.overlayElement)==null||t.remove(),this.overlayElement=null,this.boxElement=null,this.frameElement=null,this.state=null}sync(e){if(!e){this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==e.clipId&&this.finishInteraction(!1),this.state=e,this.render()}createHandle(e,t){if(!this.boxElement)return;const i=document.createElement("div");i.className=`timeline-preview-transform-handle timeline-preview-transform-handle--${e}`,i.style.position="absolute",i.style.width="10px",i.style.height="10px",i.style.border="1px solid rgba(80, 227, 194, 0.95)",i.style.background="#000000",i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=t,i.style.boxSizing="border-box",i.style.transform="translate(-50%, -50%)";const n=this.getHandlePointerDown(e);i.addEventListener("pointerdown",n),this.handleElements.set(e,i),this.handlePointerDownHandlers.set(e,n),this.boxElement.appendChild(i)}getHandlePointerDown(e){return t=>{var s,r;const i=t;if((i.button??0)!==0||!this.state)return;(s=i.preventDefault)==null||s.call(i),(r=i.stopPropagation)==null||r.call(i);const n=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize";this.interaction={clipId:this.state.clipId,mode:"scale",pointerStart:this.toLocalPoint(i),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:n},this.setGlobalCursor(n),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,n,s,r;const e=this.getDocument();e&&((t=e.addEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.addEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(n=e.addEventListener)==null||n.call(e,"visibilitychange",this.boundVisibilityChange),(r=(s=globalThis.window)==null?void 0:s.addEventListener)==null||r.call(s,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,n,s,r;const e=this.getDocument();e&&((t=e.removeEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.removeEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(n=e.removeEventListener)==null||n.call(e,"visibilitychange",this.boundVisibilityChange),(r=(s=globalThis.window)==null?void 0:s.removeEventListener)==null||r.call(s,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var s,r,o;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const t=e;(s=t.preventDefault)==null||s.call(t);const i=this.toLocalPoint(t);let n=this.interaction.startTransform;if(this.interaction.mode==="move")n=Sl(this.interaction.startTransform,i.x-this.interaction.pointerStart.x,i.y-this.interaction.pointerStart.y,this.interaction.frameSize);else{const l=this.interaction.startTransform.x*this.interaction.frameSize.width,h=this.interaction.startTransform.y*this.interaction.frameSize.height;n=Cl(l,h,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=n,this.interaction.changed=!Bs(this.interaction.startTransform,n),(o=(r=this.callbacks).onPreviewTransformChange)==null||o.call(r,this.interaction.clipId,n)}finishInteraction(e){var i,n,s,r;const t=this.interaction;if(!t){this.setGlobalCursor(null),this.unbindDocumentListeners();return}e&&t.changed&&((n=(i=this.callbacks).onPreviewTransformCommit)==null||n.call(i,t.clipId,t.nextTransform)),(r=(s=this.callbacks).onPreviewTransformChange)==null||r.call(s,t.clipId,null),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners()}render(){if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none");return}const{displayRect:e}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${e.left}px`,this.boxElement.style.top=`${e.top}px`,this.boxElement.style.width=`${e.width}px`,this.boxElement.style.height=`${e.height}px`,this.positionHandle("top-left",0,0),this.positionHandle("top-right",e.width,0),this.positionHandle("bottom-right",e.width,e.height),this.positionHandle("bottom-left",0,e.height)}positionHandle(e,t,i){const n=this.handleElements.get(e);n&&(n.style.left=`${t}px`,n.style.top=`${i}px`)}toLocalPoint(e){const t=this.getFrameBounds();return{x:(e.clientX??0)-t.left,y:(e.clientY??0)-t.top}}getFrameBounds(){var t,i;if(!this.frameElement)return{left:0,top:0,width:0,height:0};const e=(i=(t=this.frameElement).getBoundingClientRect)==null?void 0:i.call(t);return e&&Number.isFinite(e.width)&&Number.isFinite(e.height)?{left:e.left,top:e.top,width:e.width,height:e.height}:{left:En(this.frameElement.style.left),top:En(this.frameElement.style.top),width:this.frameElement.clientWidth,height:this.frameElement.clientHeight}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}setGlobalCursor(e){var i;const t=(i=this.getDocument())==null?void 0:i.body;t&&(t.style.cursor=e||"")}}const Tl=0,bl=2,wl=250,kl=2,Pl=120;function _l(a,e){return!st(a.mode)||!e?a:{mode:be.mode,width:e.width,height:e.height}}function it(a){return a.getAttribute("src")||a.currentSrc||a.src||""}function Mn(a){return typeof HTMLVideoElement<"u"?a instanceof HTMLVideoElement:a.tagName==="VIDEO"}function Qe(a){try{a.load()}catch{}}function et(a){try{a.pause()}catch{}}function xl(a){var e;try{const t=a.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function Ln(a,e){try{a.currentTime=Math.max(0,e)}catch{}}function Ut(a,e){var i;const t=(i=a==null?void 0:a.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function Rn(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}function Il(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function ae(a){return{tsMs:Il(),currentTime:Number.isFinite(a.currentTime)?Number(a.currentTime.toFixed(3)):null,currentSrc:it(a)||null,readyState:typeof a.readyState=="number"?a.readyState:null,networkState:typeof a.networkState=="number"?a.networkState:null,paused:typeof a.paused=="boolean"?a.paused:null,ended:typeof a.ended=="boolean"?a.ended:null}}function Al(a){return`${a.clip.id}:${Math.floor(a.mediaTime/wl)}`}function Ve(a){return typeof(a==null?void 0:a.then)=="function"}function El(a,e){var t;return((t=a.entry)==null?void 0:t.clip.id)===e}function Ml(a,e){const t=new Map(a.activeClips.map(s=>[s.trackId,s])),i=new Map(a.nextClips.map(s=>[s.trackId,s])),n=new Map;return e.forEach(s=>{n.set(s.trackId,{kind:s.kind,order:s.order})}),a.activeClips.forEach(s=>{n.set(s.trackId,{kind:s.trackType,order:s.trackOrder})}),a.nextClips.forEach(s=>{n.set(s.trackId,{kind:s.trackType,order:s.trackOrder})}),Array.from(n.entries()).map(([s,r])=>{const o=t.get(s)||null,l=i.get(s)||null;return{trackId:s,kind:r.kind,order:r.order,current:{role:"current",entry:o,playState:a.playState,speed:a.speed,visible:!!(o!=null&&o.hasVisual),zIndex:o?1e3-o.trackOrder:0,syncRequestId:a.syncRequestId},preload:{role:"preload",entry:l,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:a.syncRequestId}}}).sort((s,r)=>s.order-r.order)}class Ll{constructor(e={},t={}){g(this,"container",null);g(this,"rootElement",null);g(this,"frameElement",null);g(this,"pendingOverlayElement",null);g(this,"pendingOverlayStatusElement",null);g(this,"pendingOverlayDetailElement",null);g(this,"pendingOverlayActionElement",null);g(this,"resizeObserver",null);g(this,"trackSlots",new Map);g(this,"audioContext",null);g(this,"masterGainNode",null);g(this,"loadingCount",0);g(this,"isBuffering",!1);g(this,"bufferingVisibleTimeoutId",null);g(this,"lastRuntimeSignature",null);g(this,"lastRuntimeState",{phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]});g(this,"lastSettledSyncRequestId",null);g(this,"primarySelectedClipId",null);g(this,"transientVisualTransform",null);g(this,"callbacks");g(this,"dependencies");g(this,"transformOverlay");g(this,"requestedAspectRatio",{...be});g(this,"resolvedAutoAspectRatio",null);g(this,"aspectRatioProbe",null);g(this,"aspectRatioProbeSrc",null);g(this,"aspectRatioProbeResolveToken",0);g(this,"isAspectRatioProbeLoading",!1);g(this,"pendingState",null);g(this,"activeSyncRequestId");g(this,"isSyncProjecting",!1);this.callbacks=e,this.dependencies=t,this.transformOverlay=new vl({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,n)=>{var s,r;(r=(s=this.callbacks).onVisualTransformCommit)==null||r.call(s,i,n)}})}logLoadTrace(e,t,i){Eo.append({level:e,event:t,data:{syncRequestId:this.activeSyncRequestId??null,...i}})}buildSlotTraceData(e,t){var i;return{trackId:e.trackId,role:e.role,kind:e.kind,clipId:((i=e.entry)==null?void 0:i.clip.id)??null,desiredSource:e.desiredSource,actualSource:it(e.element)||null,phase:e.phase,retryCount:e.retryCount,...t}}hasPreview(){return!!this.container}attach(e){if(this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e;const t=document.createElement("div");t.className=this.dependencies.rootClassName??"timeline-preview-root",t.style.position="relative",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden";const i=document.createElement("div");i.className=this.dependencies.frameClassName??"timeline-preview-frame",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.overflow="hidden",i.style.background="#000000",t.appendChild(i);const n=document.createElement("div");n.className="timeline-preview-pending-overlay",n.style.position="absolute",n.style.inset="0",n.style.display="none",n.style.alignItems="center",n.style.justifyContent="center",n.style.flexDirection="column",n.style.gap="8px",n.style.background="rgba(0, 0, 0, 0.56)",n.style.color="#ffffff",n.style.fontSize="13px",n.style.zIndex="2000";const s=document.createElement("div");s.className="timeline-preview-pending-overlay__status",s.style.fontWeight="600";const r=document.createElement("div");r.className="timeline-preview-pending-overlay__detail",r.style.opacity="0.88";const o=document.createElement("button");o.className="timeline-preview-pending-overlay__action",o.style.display="none",o.style.padding="6px 12px",o.style.border="0",o.style.borderRadius="6px",o.style.cursor="pointer",o.style.background="#4c8dff",o.style.color="#ffffff",o.textContent="刷新重试",o.addEventListener("click",()=>{var l,h;(h=(l=this.callbacks).onPendingPreviewRetry)==null||h.call(l)}),n.appendChild(s),n.appendChild(r),n.appendChild(o),t.appendChild(n),e.appendChild(t),this.rootElement=t,this.frameElement=i,this.pendingOverlayElement=n,this.pendingOverlayStatusElement=s,this.pendingOverlayDetailElement=r,this.pendingOverlayActionElement=o,this.transformOverlay.attach(i),this.logLoadTrace("info","preview.attach",{containerWidth:e.clientWidth,containerHeight:e.clientHeight}),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(e)),this.updateFrameLayout(),this.refreshPendingOverlay(),this.refreshRuntimeState()}detach(){var e,t,i,n,s,r;this.logLoadTrace("info","preview.detach",{slotCount:this.trackSlots.size}),(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,this.transformOverlay.detach();for(const o of this.trackSlots.values())this.destroySlot(o.current),this.destroySlot(o.preload);this.trackSlots.clear(),this.aspectRatioProbe&&(et(this.aspectRatioProbe),this.aspectRatioProbe.src="",Qe(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.aspectRatioProbeResolveToken+=1,this.isAspectRatioProbeLoading=!1,this.audioContext&&((s=(i=(t=this.audioContext).close)==null?void 0:(n=i.call(t)).catch)==null||s.call(n,()=>{}),this.audioContext=null,this.masterGainNode=null),(r=this.rootElement)==null||r.remove(),this.rootElement=null,this.frameElement=null,this.pendingOverlayElement=null,this.pendingOverlayStatusElement=null,this.pendingOverlayDetailElement=null,this.pendingOverlayActionElement=null,this.container=null,this.primarySelectedClipId=null,this.transientVisualTransform=null,this.pendingState=null,this.activeSyncRequestId=void 0,this.isSyncProjecting=!1,this.loadingCount=0,this.isBuffering=!1,this.clearBufferingVisibleTimeout(),this.lastRuntimeSignature=null,this.lastSettledSyncRequestId=null,this.lastRuntimeState={phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]},this.refreshPendingOverlay(),this.refreshRuntimeState()}setPendingState(e){this.pendingState=e,this.refreshPendingOverlay()}sync(e){if(!this.rootElement||!this.frameElement)return;this.primarySelectedClipId=e.primarySelectedClipId??null,this.activeSyncRequestId=e.syncRequestId,this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.maybeResolveAutoAspectRatio(e.autoAspectRatioClip);const t=Array.from(this.trackSlots.entries()).map(([r,o],l)=>{var h,c;return{trackId:r,kind:o.current.kind,order:((h=o.current.entry)==null?void 0:h.trackOrder)??((c=o.preload.entry)==null?void 0:c.trackOrder)??1e4+l}}),s=Ml(e,t).map(r=>this.applyTrackPlan(r)).filter(r=>Ve(r));if(this.isSyncProjecting=s.length>0,this.refreshVisualLayout(),this.refreshRuntimeState(),s.length===0){this.refreshVisualLayout(),this.refreshRuntimeState();return}Promise.all(s).then(()=>{this.activeSyncRequestId===e.syncRequestId&&(this.isSyncProjecting=!1,this.refreshVisualLayout(),this.refreshRuntimeState())}).catch(r=>{this.logLoadTrace("error","preview.sync.failed",{syncRequestId:e.syncRequestId??null,error:r}),L.warn("TimelinePreviewSession","preview sync failed",{error:r,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=De(e),this.updateFrameLayout()}getAspectRatio(){return _l(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}createMediaElement(e,t){const i=this.dependencies.createMediaElement,n=i?i(e,t):document.createElement(e==="video"?"video":"audio");return n.preload=t==="preload"?"auto":"metadata",n.crossOrigin="anonymous",n.loop=!1,n.controls=!1,Mn(n)?(n.playsInline=!0,n.disablePictureInPicture=!0,n.style.position="absolute",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.objectFit="fill",n.style.background="#000000",n.style.pointerEvents="none"):n.style.display="none",n}createSlot(e,t,i){var T,b;const n=this.createMediaElement(t,i),s=t==="video"?document.createElement("div"):null;if(s){const w=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";s.className=`${w} timeline-preview-slot--${e} timeline-preview-slot--${i}`,s.style.position="absolute",s.style.overflow="hidden",s.style.background="#000000",s.style.pointerEvents="none",s.style.display="none",s.appendChild(n),(T=this.frameElement)==null||T.appendChild(s)}const r={role:i,trackId:e,kind:t,wrapper:s,element:n,entry:null,desiredSource:null,requestedPlayState:"paused",isActive:!1,isLoading:!1,isBuffering:!1,isSeeking:!1,phase:"idle",errorMessage:null,retryCount:0,recoveryKey:null,sourceNode:null,gainNode:null,audioRoutingFailed:!1,consecutiveStalledCount:0,forceRecover:!1,resolveToken:0,applyToken:0,cleanup:[]},o=()=>{r.isLoading=!1,r.isSeeking=!1,r.isBuffering=!1,r.errorMessage=null,r.consecutiveStalledCount=0,r.entry?r.phase=r.isActive?"active":"primed":r.phase="idle",this.tryResolveAutoAspectRatioFromSlot(r),this.refreshVisualLayout(),this.refreshRuntimeState()},l=()=>{var w;if(!r.entry){r.isLoading=!1,r.phase="idle",this.refreshRuntimeState();return}this.logLoadTrace("info","media.loadstart",this.buildSlotTraceData(r,ae(r.element))),L.debug("TimelinePreviewSession","media event: loadstart",{trackId:r.trackId,role:r.role,clipId:((w=r.entry)==null?void 0:w.clip.id)??null,phase:r.phase,...ae(r.element)}),r.isLoading=!0,r.phase!=="recovering"&&(r.phase="binding"),this.refreshRuntimeState()},h=w=>{var k;this.logLoadTrace("info",`media.${w.type}`,this.buildSlotTraceData(r,ae(r.element))),L.debug("TimelinePreviewSession","media event: ready",{trackId:r.trackId,role:r.role,clipId:((k=r.entry)==null?void 0:k.clip.id)??null,eventType:w.type,phase:r.phase,...ae(r.element)}),o()},c=()=>{var w;this.logLoadTrace("warn","media.waiting",this.buildSlotTraceData(r,{active:r.isActive,...ae(r.element)})),L.debug("TimelinePreviewSession","media event: waiting",{trackId:r.trackId,role:r.role,clipId:((w=r.entry)==null?void 0:w.clip.id)??null,active:r.isActive,phase:r.phase,...ae(r.element)}),r.isBuffering=r.isActive&&!r.element.paused,this.refreshRuntimeState()},d=()=>{var w;this.logLoadTrace("warn","media.stalled",this.buildSlotTraceData(r,{active:r.isActive,...ae(r.element)})),L.debug("TimelinePreviewSession","media event: stalled",{trackId:r.trackId,role:r.role,clipId:((w=r.entry)==null?void 0:w.clip.id)??null,active:r.isActive,phase:r.phase,...ae(r.element)}),r.isBuffering=r.isActive&&!r.element.paused,r.consecutiveStalledCount+=1,this.refreshRuntimeState(),r.isActive&&r.consecutiveStalledCount>=kl&&this.recoverSlot(r,"stalled")},u=()=>{var w;if(!r.entry){r.isSeeking=!1,r.phase="idle",this.refreshRuntimeState();return}this.logLoadTrace("debug","media.seeking",this.buildSlotTraceData(r,{active:r.isActive,...ae(r.element)})),L.debug("TimelinePreviewSession","media event: seeking",{trackId:r.trackId,role:r.role,clipId:((w=r.entry)==null?void 0:w.clip.id)??null,active:r.isActive,phase:r.phase,...ae(r.element)}),r.isSeeking=!0,this.refreshRuntimeState()},f=()=>{var w;this.logLoadTrace("debug","media.seeked",this.buildSlotTraceData(r,ae(r.element))),L.debug("TimelinePreviewSession","media event: seeked",{trackId:r.trackId,role:r.role,clipId:((w=r.entry)==null?void 0:w.clip.id)??null,phase:r.phase,...ae(r.element)}),r.isSeeking=!1,r.isBuffering=!1,r.entry&&r.phase!=="failed"&&(r.phase=r.isActive?"active":"primed"),this.refreshRuntimeState()},p=w=>{var k;this.logLoadTrace(w==="error"?"error":"warn",`media.${w}`,this.buildSlotTraceData(r,{error:r.element.error?{code:r.element.error.code,message:r.element.error.message}:null,...ae(r.element)})),L.warn("TimelinePreviewSession",`media event: ${w}`,{trackId:r.trackId,role:r.role,clipId:((k=r.entry)==null?void 0:k.clip.id)??null,phase:r.phase,error:r.element.error?{code:r.element.error.code,message:r.element.error.message}:null,...ae(r.element)}),r.forceRecover=!0,r.isLoading=!1,r.isSeeking=!1,r.isBuffering=!1,this.refreshRuntimeState(),this.recoverSlot(r,w)},y=()=>p("abort"),S=()=>p("emptied"),C=()=>p("error");return n.addEventListener("loadstart",l),n.addEventListener("loadedmetadata",h),n.addEventListener("canplay",h),n.addEventListener("playing",h),n.addEventListener("waiting",c),n.addEventListener("stalled",d),n.addEventListener("seeking",u),n.addEventListener("seeked",f),n.addEventListener("abort",y),n.addEventListener("emptied",S),n.addEventListener("error",C),r.cleanup.push(()=>n.removeEventListener("loadstart",l),()=>n.removeEventListener("loadedmetadata",h),()=>n.removeEventListener("canplay",h),()=>n.removeEventListener("playing",h),()=>n.removeEventListener("waiting",c),()=>n.removeEventListener("stalled",d),()=>n.removeEventListener("seeking",u),()=>n.removeEventListener("seeked",f),()=>n.removeEventListener("abort",y),()=>n.removeEventListener("emptied",S),()=>n.removeEventListener("error",C)),t==="audio"&&((b=this.rootElement)==null||b.appendChild(n)),r}destroySlot(e){var t,i,n,s,r;e.resolveToken+=1,e.applyToken+=1,e.cleanup.forEach(o=>o()),et(e.element),e.element.removeAttribute("src"),Qe(e.element),(i=(t=e.gainNode)==null?void 0:t.disconnect)==null||i.call(t),(s=(n=e.sourceNode)==null?void 0:n.disconnect)==null||s.call(n),e.gainNode=null,e.sourceNode=null,(r=e.wrapper)==null||r.remove(),e.element.remove()}getTrackSlots(e,t){const i=this.trackSlots.get(e);if(i&&i.current.kind===t&&i.preload.kind===t)return i;i&&(this.destroySlot(i.current),this.destroySlot(i.preload),this.trackSlots.delete(e));const n={current:this.createSlot(e,t,"current"),preload:this.createSlot(e,t,"preload")};return this.trackSlots.set(e,n),n}swapTrackSlots(e){const t=this.trackSlots.get(e);t&&(t.current.role="preload",t.preload.role="current",this.trackSlots.set(e,{current:t.preload,preload:t.current}))}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);e.current.entry&&El(t.preload,e.current.entry.clip.id)&&(this.swapTrackSlots(e.trackId),t=this.getTrackSlots(e.trackId,e.kind));const i=this.applySlotTarget(t.current,e.current),n=this.applySlotTarget(t.preload,e.preload);if(Ve(i)||Ve(n))return Promise.all([Promise.resolve(i),Promise.resolve(n)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,n=e.entry,s=it(e.element)||null;if(e.entry=t.entry,e.requestedPlayState=t.playState,e.isActive=t.role==="current"&&!!t.entry,e.errorMessage=t.entry?e.errorMessage:null,e.isBuffering=t.entry?e.isBuffering:!1,e.isSeeking=t.entry?e.isSeeking:!1,e.consecutiveStalledCount=t.entry?e.consecutiveStalledCount:0,!t.entry){(n||s)&&this.logLoadTrace("info","slot.cleared",this.buildSlotTraceData(e,{previousClipId:(n==null?void 0:n.clip.id)??null,previousSource:s})),et(e.element),e.desiredSource=null,e.errorMessage=null,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.retryCount=0,e.recoveryKey=null,e.forceRecover=!1,e.element.removeAttribute("src"),Qe(e.element),e.phase="idle",this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}const r=this.resolveDesiredSource(e,t.entry,i);if(Ve(r))return r.then(o=>{if(!(!o||!this.isCurrentRequest(e,i,t.entry))){if(e.desiredSource=o,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,o))return Promise.resolve(this.recoverSlot(e,"reconcile",t,i)).then(()=>{});e.forceRecover=!1,e.retryCount=0,e.recoveryKey=null,this.applyResolvedSlotState(e,t)}});if(!(!r||!this.isCurrentRequest(e,i,t.entry))){if(e.desiredSource=r,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,r))return this.recoverSlot(e,"reconcile",t,i);e.forceRecover=!1,e.retryCount=0,e.recoveryKey=null,this.applyResolvedSlotState(e,t)}}resolveDesiredSource(e,t,i){const n=this.dependencies.previewSourceResolver;if(!n)return t.clip.src;try{const s=n(t.clip);if(Ve(s)){e.resolveToken+=1;const r=e.resolveToken;return e.phase="binding",e.isLoading=!0,this.logLoadTrace("info","source.resolve.pending",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,requestToken:i,resolveToken:r})),this.refreshRuntimeState(),s.then(o=>r!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:o?(this.logLoadTrace("info","source.resolve.resolved",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,resolvedUrl:o.url,mimeType:o.mimeType,mediaKind:o.kind})),o.url):(this.logLoadTrace("warn","source.resolve.missing",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(o=>(this.logLoadTrace("error","source.resolve.failed",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,error:o})),L.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:o}),this.failSlot(e,t,"预览源解析失败"),null))}return s?(this.logLoadTrace("info","source.resolve.resolved",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,resolvedUrl:s.url,mimeType:s.mimeType,mediaKind:s.kind})),s.url):(this.logLoadTrace("warn","source.resolve.missing",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)}catch(s){return this.logLoadTrace("error","source.resolve.failed",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,error:s})),L.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:s}),this.failSlot(e,t,"预览源解析失败"),null}}slotNeedsRecovery(e,t){const i=it(e.element);return!!(e.forceRecover||!i||i!==t||(typeof e.element.networkState=="number"?e.element.networkState:null)===Tl)}recoverSlot(e,t,i,n){const s=i??(e.entry?{role:e.role,entry:e.entry,playState:e.requestedPlayState,speed:e.isActive&&e.element.playbackRate||1,visible:e.isActive&&!!e.entry.hasVisual,zIndex:e.entry?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null);if(!e.entry||!s||n!==void 0&&!this.isCurrentRequest(e,n,e.entry))return;const r=e.desiredSource??this.resolveDesiredSource(e,e.entry,e.applyToken);if(Ve(r))return r.then(o=>{o&&this.finishSlotRecovery(e,t,s,o,n)});r&&this.finishSlotRecovery(e,t,s,r,n)}finishSlotRecovery(e,t,i,n,s){if(!e.entry)return;const r=Al(e.entry);if(e.recoveryKey===r){if(e.retryCount>=bl){this.failSlot(e,e.entry,"媒体恢复失败,请刷新重试");return}e.retryCount+=1}else e.recoveryKey=r,e.retryCount=1;e.phase="recovering",e.errorMessage=null,e.forceRecover=!1,e.isLoading=!0,e.isBuffering=e.isActive&&i.playState==="playing",e.isSeeking=!1,e.consecutiveStalledCount=0,this.refreshRuntimeState(),this.logLoadTrace(t==="reconcile"?"info":"warn","slot.recover",this.buildSlotTraceData(e,{reason:t,desiredSource:n,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState})),L.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:n,...ae(e.element)});const l=!!it(e.element)||t!=="reconcile"||e.retryCount>1;et(e.element),l&&(e.element.removeAttribute("src"),Qe(e.element)),e.element.setAttribute("src",n),Qe(e.element),this.logLoadTrace("info","source.assigned",this.buildSlotTraceData(e,{reason:t,desiredSource:n,hardReset:l})),!(s!==void 0&&!this.isCurrentRequest(e,s,e.entry))&&this.applyResolvedSlotState(e,i)}applyResolvedSlotState(e,t){t.entry&&(e.errorMessage=null,e.element.playbackRate=t.role==="current"?t.speed:1,t.role==="current"?this.syncCurrentSlot(e,t.entry,t.speed,t.playState):this.preparePreloadSlot(e,t.entry),!e.isLoading&&!e.isSeeking&&e.phase!=="failed"&&(e.phase=e.isActive?"active":"primed"),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState())}isCurrentRequest(e,t,i){var n;return e.applyToken===t&&((n=e.entry)==null?void 0:n.clip.id)===i.clip.id}failSlot(e,t,i){e.phase="failed",e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.errorMessage=i,e.forceRecover=!1,this.logLoadTrace("error","slot.failed",this.buildSlotTraceData(e,{clipId:t.clip.id,errorMessage:i})),L.warn("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,...ae(e.element)}),this.refreshRuntimeState()}configureAudioRouting(e,t){const i=Math.max(0,Math.min(1,t.clip.volume??1)),n=t.muted?0:i;if(!t.hasAudio){e.element.muted=!0,e.element.volume=0;return}const s=this.getAudioContext();if(!s||e.audioRoutingFailed){e.element.muted=t.muted,e.element.volume=n;return}if(!e.sourceNode||!e.gainNode)try{e.sourceNode=s.createMediaElementSource(e.element),e.gainNode=s.createGain(),e.sourceNode.connect(e.gainNode),e.gainNode.connect(this.getMasterGainNode(s))}catch{e.audioRoutingFailed=!0,e.element.muted=t.muted,e.element.volume=n;return}e.element.muted=!1,e.element.volume=1,e.gainNode.gain.value=n}syncCurrentSlot(e,t,i,n){e.isActive=!0,e.entry=t,e.element.playbackRate=i;const s=t.mediaTime/1e3,r=Math.max(.1,i*.15);Math.abs(e.element.currentTime-s)>r&&(L.debug("TimelinePreviewSession","seek current slot",{trackId:e.trackId,role:e.role,clipId:t.clip.id,playState:n,speed:i,fromSeconds:Number(e.element.currentTime.toFixed(3)),toSeconds:Number(s.toFixed(3)),deltaSeconds:Number(Math.abs(e.element.currentTime-s).toFixed(3)),thresholdSeconds:Number(r.toFixed(3)),...ae(e.element)}),e.isSeeking=!0,Ln(e.element,s)),n==="playing"?(this.resumeAudioContext(),xl(e.element)):et(e.element),this.setSlotVisible(e,t.hasVisual,1e3-t.trackOrder)}preparePreloadSlot(e,t){e.isActive=!1,e.isBuffering=!1,e.isSeeking=!1,e.entry=t,e.element.playbackRate=1,L.debug("TimelinePreviewSession","prime preload slot seek",{trackId:e.trackId,role:e.role,clipId:t.clip.id,toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3)),...ae(e.element)}),Ln(e.element,t.clip.startTimeAtSource/1e3),et(e.element),this.setSlotVisible(e,!1,0)}setSlotVisible(e,t,i){if(e.kind!=="video"||!e.wrapper){e.element.style.display="none";return}e.wrapper.style.display=t?"block":"none",e.wrapper.style.zIndex=String(i),e.wrapper.style.pointerEvents="none",e.element.style.display=t?"block":"none",e.element.style.zIndex=String(i)}getAudioContext(){if(this.audioContext)return this.audioContext;const e=this.dependencies.createAudioContext;if(e)return this.audioContext=e(),this.audioContext;if(typeof window>"u")return null;const t=window.AudioContext||window.webkitAudioContext;return t?(this.audioContext=new t,this.audioContext):null}getMasterGainNode(e){if(this.masterGainNode)return this.masterGainNode;const t=e.createGain();return t.gain.value=1,t.connect(e.destination),this.masterGainNode=t,t}resumeAudioContext(){var e,t,i,n;!this.audioContext||this.audioContext.state!=="suspended"||(n=(t=(e=this.audioContext).resume)==null?void 0:(i=t.call(e)).catch)==null||n.call(i,()=>{})}updateFrameLayout(){if(!this.container||!this.frameElement)return;const{width:e,height:t}=this.getAspectRatio(),i=this.container.clientWidth,n=this.container.clientHeight;if(i<=0||n<=0||e<=0||t<=0)return;const s=e/t,r=i/n;let o=i,l=n;s>r?l=i/s:o=n*s,this.frameElement.style.width=`${o}px`,this.frameElement.style.height=`${l}px`,this.frameElement.style.left=`${(i-o)/2}px`,this.frameElement.style.top=`${(n-l)/2}px`,this.refreshVisualLayout()}maybeResolveAutoAspectRatio(e){if(!st(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=Ut(e,"sys_width"),i=Ut(e,"sys_height");if(t&&i){this.handleResolvedAutoAspectRatio(t,i);return}if(this.aspectRatioProbeSrc===e.clip.id)return;const n=++this.aspectRatioProbeResolveToken;(async()=>{const r=await this.resolveAspectRatioProbeSource(e,n);if(!r||n!==this.aspectRatioProbeResolveToken)return;const o=this.getAspectRatioProbe();this.aspectRatioProbeSrc=e.clip.id,this.isAspectRatioProbeLoading=!0,this.logLoadTrace("info","aspect-ratio.probe.start",{clipId:e.clip.id,source:r}),this.refreshRuntimeState(),o.crossOrigin="anonymous",o.preload="metadata",o.muted=!0,o.src=r,Qe(o)})().catch(()=>{})}async resolveAspectRatioProbeSource(e,t){const i=this.dependencies.previewSourceResolver;if(!i)return e.clip.src;const n=i(e.clip);if(!Ve(n))return(n==null?void 0:n.url)??null;this.isAspectRatioProbeLoading=!0,this.refreshRuntimeState();const s=await n;return t!==this.aspectRatioProbeResolveToken?null:(s==null?void 0:s.url)??null}getAspectRatioProbe(){var n,s;if(this.aspectRatioProbe)return this.aspectRatioProbe;const e=((s=(n=this.dependencies).createAspectRatioProbe)==null?void 0:s.call(n))||document.createElement("video"),t=()=>{this.isAspectRatioProbeLoading=!1,this.logLoadTrace("info","aspect-ratio.probe.loadedmetadata",{clipId:this.aspectRatioProbeSrc,videoWidth:e.videoWidth,videoHeight:e.videoHeight}),this.refreshRuntimeState(),e.videoWidth>0&&e.videoHeight>0&&this.handleResolvedAutoAspectRatio(e.videoWidth,e.videoHeight)},i=()=>{this.isAspectRatioProbeLoading=!1,this.logLoadTrace("warn","aspect-ratio.probe.error",{clipId:this.aspectRatioProbeSrc,currentSrc:e.currentSrc||e.src||null}),this.refreshRuntimeState()};return e.addEventListener("loadedmetadata",t),e.addEventListener("error",i),this.aspectRatioProbe=e,e}tryResolveAutoAspectRatioFromSlot(e){if(!st(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const t=e.element;t.videoWidth>0&&t.videoHeight>0&&this.handleResolvedAutoAspectRatio(t.videoWidth,t.videoHeight)}handleResolvedAutoAspectRatio(e,t){var i,n;e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),st(this.requestedAspectRatio.mode)&&((n=(i=this.callbacks).onAspectRatioChange)==null||n.call(i,this.getAspectRatio())))}refreshRuntimeState(){var u,f,p,y,S,C,T;const e=[];let t=this.isAspectRatioProbeLoading?1:0,i=!1,n=null,s=!1,r=!1,o=!1;for(const{current:b,preload:w}of this.trackSlots.values())for(const k of[b,w]){const _=it(k.element)||null;e.push({trackId:k.trackId,role:k.role,kind:k.kind,clipId:((u=k.entry)==null?void 0:u.clip.id)??null,desiredSource:k.desiredSource,actualSource:_,phase:k.phase,retryCount:k.retryCount,errorMessage:k.errorMessage}),k.phase!=="idle"&&(s=!0),(k.isLoading||k.phase==="binding"||k.phase==="recovering")&&(t+=1),k.isBuffering&&(i=!0),k.phase==="failed"&&!n&&(n=k.errorMessage||"资源加载异常,请刷新重试",r=!0),k.isActive&&k.entry&&(k.isSeeking||k.phase!=="active"&&k.phase!=="failed")&&(o=!0)}let l="idle";this.activeSyncRequestId!==void 0&&this.isSyncProjecting?l="awaiting-sync":r?l="failed":t>0||i||o?l="awaiting-media":s&&(l="ready"),this.loadingCount!==t&&(this.loadingCount=t,(p=(f=this.callbacks).onSourceLoadingChange)==null||p.call(f,t)),this.syncVisibleBufferingState(i);const h={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:l,loadingCount:t,isBuffering:i,errorMessage:n,slots:e},c=this.lastRuntimeState,d=JSON.stringify(h);d!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=d,this.lastRuntimeState=h,(c.phase!==h.phase||c.loadingCount!==h.loadingCount||c.isBuffering!==h.isBuffering||c.errorMessage!==h.errorMessage)&&this.logLoadTrace(h.phase==="failed"?"error":"info","runtime.state",{previousPhase:c.phase,phase:h.phase,loadingCount:h.loadingCount,isBuffering:h.isBuffering,errorMessage:h.errorMessage,slots:h.slots.map(b=>({trackId:b.trackId,role:b.role,clipId:b.clipId,phase:b.phase,retryCount:b.retryCount}))}),(S=(y=this.callbacks).onRuntimeStateChange)==null||S.call(y,h)),(l==="ready"||l==="failed")&&h.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==h.syncRequestId&&(this.lastSettledSyncRequestId=h.syncRequestId,(T=(C=this.callbacks).onSyncProcessed)==null||T.call(C,h.syncRequestId)),this.refreshPendingOverlay()}syncVisibleBufferingState(e){var t,i;if(e){if(this.isBuffering||this.bufferingVisibleTimeoutId)return;this.bufferingVisibleTimeoutId=setTimeout(()=>{var n,s;this.bufferingVisibleTimeoutId=null,!this.isBuffering&&(this.isBuffering=!0,(s=(n=this.callbacks).onBufferingStateChange)==null||s.call(n,!0))},Pl);return}this.clearBufferingVisibleTimeout(),this.isBuffering&&(this.isBuffering=!1,(i=(t=this.callbacks).onBufferingStateChange)==null||i.call(t,!1))}clearBufferingVisibleTimeout(){this.bufferingVisibleTimeoutId&&(clearTimeout(this.bufferingVisibleTimeoutId),this.bufferingVisibleTimeoutId=null)}refreshPendingOverlay(){if(!this.pendingOverlayElement||!this.pendingOverlayStatusElement||!this.pendingOverlayDetailElement||!this.pendingOverlayActionElement)return;if(!this.pendingState){this.pendingOverlayElement.style.display="none",this.pendingOverlayActionElement.style.display="none";return}this.pendingOverlayElement.style.display="flex";const e=this.lastRuntimeState;if(this.pendingState.errorMessage||e.phase==="failed"){this.pendingOverlayStatusElement.textContent="资源加载异常",this.pendingOverlayDetailElement.textContent=this.pendingState.errorMessage||e.errorMessage||"资源加载异常,请刷新重试",this.pendingOverlayActionElement.style.display="inline-flex";return}const t=this.pendingState.loadingPending>0||e.loadingCount>0;this.pendingOverlayStatusElement.textContent=t?"资源加载中…":"正在缓冲预览…",this.pendingOverlayDetailElement.textContent=t?`目标时间 ${Math.round(this.pendingState.targetTime)}ms,待加载资源 ${Math.max(this.pendingState.loadingPending,e.loadingCount)} 个`:`目标时间 ${Math.round(this.pendingState.targetTime)}ms,等待媒体可播放`,this.pendingOverlayActionElement.style.display="none"}handlePreviewTransformChange(e,t){var i;if(!t){((i=this.transientVisualTransform)==null?void 0:i.clipId)===e&&(this.transientVisualTransform=null,this.refreshVisualLayout());return}this.transientVisualTransform={clipId:e,transform:t},this.refreshVisualLayout()}refreshVisualLayout(){for(const{current:e,preload:t}of this.trackSlots.values())this.refreshSlotVisualLayout(e),this.refreshSlotVisualLayout(t);this.transformOverlay.sync(this.buildSelectedOverlayState())}refreshSlotVisualLayout(e){if(e.kind!=="video"||!e.wrapper||!e.entry||!this.frameElement)return;const t=this.getFrameSize();if(t.width<=0||t.height<=0)return;const i=this.getMediaSize(e,e.entry,t),n=this.getEffectiveVisualTransform(e.entry),s=An(t,i,n);e.wrapper.style.left=`${s.left}px`,e.wrapper.style.top=`${s.top}px`,e.wrapper.style.width=`${s.width}px`,e.wrapper.style.height=`${s.height}px`}buildSelectedOverlayState(){if(!this.primarySelectedClipId)return null;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return null;for(const{current:t}of this.trackSlots.values()){if(t.kind!=="video"||!t.isActive||!t.entry||t.entry.clip.id!==this.primarySelectedClipId)continue;const i=this.getMediaSize(t,t.entry,e),n=this.getEffectiveVisualTransform(t.entry);return{clipId:t.entry.clip.id,transform:n,frameSize:e,baseRect:Gs(e,i),displayRect:An(e,i,n)}}return null}getFrameSize(){var i,n,s,r;const e=((i=this.frameElement)==null?void 0:i.clientWidth)??0,t=((n=this.frameElement)==null?void 0:n.clientHeight)??0;return{width:e>0?e:Rn((s=this.frameElement)==null?void 0:s.style.width),height:t>0?t:Rn((r=this.frameElement)==null?void 0:r.style.height)}}getMediaSize(e,t,i){if(Mn(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const n=Ut(t,"sys_width"),s=Ut(t,"sys_height");return n&&s?{width:n,height:s}:{width:i.width,height:i.height}}getEffectiveVisualTransform(e){var t;return((t=this.transientVisualTransform)==null?void 0:t.clipId)===e.clip.id?this.transientVisualTransform.transform:fe(e.clip.visualTransform)}}class Rl extends Ll{constructor(e={}){super(e.callbacks,{previewSourceResolver:e.previewSourceResolver,rootClassName:e.rootClassName,frameClassName:e.frameClassName,slotClassNamePrefix:e.slotClassNamePrefix})}destroy(){this.detach()}}function Dl(a){return"dom"}const Ol=36e5,Bl=3e5;function Gl(a){return a.length===0?0:a.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function Dn(a){if(a.length===0)return 0;const e=a.reduce((i,n)=>Math.min(i,n.startTime),Number.POSITIVE_INFINITY),t=a.reduce((i,n)=>Math.max(i,n.startTime+n.duration),0);return Math.max(0,t-e)}function On(a){return Math.max(a+Bl,Ol)}class Bn{constructor(e={}){g(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(n){L.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:n})}})}clear(){this.listeners.clear()}}function Hl(a){return[...a].sort((e,t)=>e.order-t.order)}function Nl(a){return[...a].sort((e,t)=>e.startTime-t.startTime)}function yi(a,e,t){return{trackId:a.id,trackType:a.type,trackOrder:a.order,clip:e,mediaTime:t,muted:(a.isMuted??!1)||(e.isMuted??!1),kind:a.type,hasVisual:a.type==="video",hasAudio:!0}}class zl{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t){const i=Hl(e),n=[],s=[];let r=null;for(const o of i){const l=Nl(o.clips),h=l.find(d=>t>=d.startTime&&t<d.endTime);if(h){const d=h.startTimeAtSource+(t-h.startTime);n.push(yi(o,h,d))}const c=l.find(d=>d.startTime>t);if(c&&s.push(yi(o,c,c.startTimeAtSource)),!r&&o.type==="video"){const d=l[0];d&&(r=yi(o,d,d.startTimeAtSource))}}return{activeClips:n,nextClips:s,firstVideoClip:r}}}class Fl{constructor(e){g(this,"options");g(this,"_previewSession");g(this,"_previewMountContainer",null);g(this,"_resolvedPreviewBackend","dom");g(this,"_runtimePreviewBackendOverride",null);g(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const Vl=8e3;class Wl{constructor(e){g(this,"callbacks");g(this,"pendingTimeoutMs");g(this,"_previewSourceLoadingCount",0);g(this,"_previewBuffering",!1);g(this,"_previewAwaitingMedia",!1);g(this,"_pendingPreviewState",null);g(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.pendingTimeoutMs=e.pendingTimeoutMs??Vl}get previewSourceLoadingCount(){return this._previewSourceLoadingCount}set previewSourceLoadingCount(e){this._previewSourceLoadingCount=Math.max(0,e)}get previewBuffering(){return this._previewBuffering}set previewBuffering(e){this._previewBuffering=e}get pendingPreviewState(){return this._pendingPreviewState}set pendingPreviewState(e){this._pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this._nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this._nextPendingPreviewSyncRequestId=Math.max(0,e)}handleBufferingStateChange(e){this._previewBuffering=e,this.callbacks.emitBufferingStateChange(e),this.updatePendingPreviewState()}handleSourceLoadingChange(e){this._previewSourceLoadingCount=Math.max(0,e),this.callbacks.emitSourceLoadingStateChange(),this.updatePendingPreviewState()}handleRuntimeStateChange(e){const t=Math.max(0,e.loadingCount),i=this._previewBuffering!==e.isBuffering,n=this._previewSourceLoadingCount!==t;this._previewAwaitingMedia=e.phase==="awaiting-media",this._previewBuffering=e.isBuffering,this._previewSourceLoadingCount=t,this._pendingPreviewState&&e.syncRequestId===this._pendingPreviewState.syncRequestId&&((e.phase==="awaiting-media"||e.phase==="ready"||e.phase==="failed")&&(this._pendingPreviewState.awaitingSync=!1),e.phase==="failed"?this._pendingPreviewState.errorMessage=e.errorMessage||"资源加载异常,请刷新重试":this._pendingPreviewState.errorMessage||(this._pendingPreviewState.errorMessage=null)),i&&this.callbacks.emitBufferingStateChange(e.isBuffering),n&&this.callbacks.emitSourceLoadingStateChange(),this.updatePendingPreviewState()}markSyncProcessed(e){this._pendingPreviewState&&e===this._pendingPreviewState.syncRequestId&&(this._pendingPreviewState.awaitingSync=!1),this.updatePendingPreviewState()}beginPendingPreview(e,t,i){this.clearPendingPreviewTimeout(),this._pendingPreviewState={mode:t,targetTime:e,resumePlayOnReady:i,errorMessage:null,timeoutId:null,awaitingSync:!0,syncRequestId:++this._nextPendingPreviewSyncRequestId}}buildPreviewPendingState(){return!this._pendingPreviewState||this._pendingPreviewState.mode==="scrub"?null:{mode:this._pendingPreviewState.mode,targetTime:this._pendingPreviewState.targetTime,loadingPending:this._previewSourceLoadingCount,isBuffering:this._previewAwaitingMedia||this._previewBuffering,errorMessage:this._pendingPreviewState.errorMessage}}updatePendingPreviewState(){if(!this._pendingPreviewState){this.callbacks.applyPendingState(null);return}const e=this._previewSourceLoadingCount>0||this._previewAwaitingMedia;if(this._pendingPreviewState.errorMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.awaitingSync){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(e){this.ensurePendingPreviewTimeout(),this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const t=this._pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),t&&this.callbacks.resumePlayback()}retryPendingPreview(){this._pendingPreviewState&&(this._pendingPreviewState.errorMessage=null,this._pendingPreviewState.awaitingSync=!0,this._pendingPreviewState.syncRequestId=++this._nextPendingPreviewSyncRequestId,this.clearPendingPreviewTimeout(),this.callbacks.requestPreviewSync())}clearPendingPreviewState(){this.clearPendingPreviewTimeout(),this._pendingPreviewState=null,this.callbacks.applyPendingState(null)}resetPreviewRuntimeState(){const e=this._previewBuffering,t=this._previewSourceLoadingCount!==0;this._previewBuffering=!1,this._previewAwaitingMedia=!1,this._previewSourceLoadingCount=0,e&&this.callbacks.emitBufferingStateChange(!1),t&&this.callbacks.emitSourceLoadingStateChange()}ensurePendingPreviewTimeout(){if(!this._pendingPreviewState||this._pendingPreviewState.mode==="scrub"||this._pendingPreviewState.timeoutId!==null)return;const e=this._pendingPreviewState.syncRequestId;this._pendingPreviewState.timeoutId=setTimeout(()=>{!this._pendingPreviewState||this._pendingPreviewState.syncRequestId!==e||(this._pendingPreviewState.errorMessage="资源加载异常,请刷新重试",this.clearPendingPreviewTimeout(),this.callbacks.applyPendingState(this.buildPreviewPendingState()))},this.pendingTimeoutMs)}clearPendingPreviewTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.timeoutId&&(clearTimeout(this._pendingPreviewState.timeoutId),this._pendingPreviewState.timeoutId=null)}}function Yl(a){var t;const e=a.getPrimarySelectedClip()||((t=a.findFallbackSelectedClip)==null?void 0:t.call(a))||null;return{clip:e,hasSelectedClip:!!e}}function Xl(a){var i;const e=a.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===a.lastSelectedClipId?a.lastSelectedClipId:(a.emitSelectedClipChange(e),t)}function Hs(a,e){var t,i,n,s;return((i=(t=a.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((s=(n=a.getLastTrack())==null?void 0:n.getId)==null?void 0:s.call(n))||e}function Ul(a){if(a.placement.status==="use_existing_track")return a.trackCollection.addClipToTrack(a.placement.trackId,a.clip);const e=a.createTrack(a.placement.trackType,a.placement.suggestedTrackName),t=Hs(a.trackCollection,e);return t?a.trackCollection.addClipToTrack(t,a.clip):!1}function Gn(a,e,t){return e.trackId?a.removeClipFromTrack(e.trackId,t):!1}function $l(a){return a.trackCollection.moveClipToTrack(a.command.clip,a.command.sourceTrackId,a.command.targetTrackId)}function ql(a){const e=a.createTrack(a.trackType,a.trackName),t=Hs(a.trackCollection,e);return t?a.trackCollection.moveClipToTrack(a.clip,a.currentTrackId,t):!1}function Me(a){var e,t,i,n,s;(e=a.checkTrackDurationChange)==null||e.call(a),(t=a.updateCanPlayState)==null||t.call(a),(i=a.updateTrackInfoPanel)==null||i.call(a),(n=a.handleClipChange)==null||n.call(a),(s=a.cleanupEmptyTracks)==null||s.call(a)}function Kl(a){var e,t;a.notifySelectionChange(),(e=a.cleanupEmptyTracks)==null||e.call(a),a.updateTrackInfoPanel(),(t=a.batchDraw)==null||t.call(a),a.syncPreviewSession()}class jl{constructor(){g(this,"panel",null)}init(e){var i,n,s,r;const t=((i=e.theme)==null?void 0:i.background)||"#1a1a1a";this.panel=new Ds({container:e.container,theme:{background:t,border:((n=e.theme)==null?void 0:n.border)||"#333333",text:((s=e.theme)==null?void 0:s.clipName)||"#ffffff",buttonBackground:((r=e.theme)==null?void 0:r.clipBackground)||"#2a2a2a",buttonHover:"#3a3a3a",buttonDanger:"#dc3545"},width:200,timeScaleHeight:e.timeScaleHeight||40,includeTimeScaleSpacer:e.includeTimeScaleSpacer},e.onRenameTrack,e.onRemoveTrack,e.onMuteTrack)}hasPanel(){return!!this.panel}update(e){var t;(t=this.panel)==null||t.setTracks(e)}setScrollTop(e){var t;(t=this.panel)==null||t.setScrollTop(e)}destroy(){var e;(e=this.panel)==null||e.destroy(),this.panel=null}}class Hn{syncCurrentTime(e,t,i,n){e==null||e.setCurrentTime(n),t==null||t.setCurrentTime(n),i.syncCurrentTime(n)}syncZoom(e,t,i,n){e==null||e.setZoom(n),t==null||t.setZoom(n),i.syncZoom(n)}syncScrollLeft(e,t,i){e==null||e.setScrollLeft(i),t.syncScrollLeft(i)}syncScrollTop(e,t,i){e==null||e.setScrollTop(i),t==null||t.setScrollTop(i)}syncSelection(e,t){e.syncSelection(t,t[0]??null)}findSelectedClip(e){return e.findPrimarySelectedClip()}}class Nn{constructor(e,t=ti){this.handlers=e,this.TrackCtor=t}createTrack(e){return new this.TrackCtor(e.layer,e.config,e.trackType,e.zoom,e.trackY,e.trackHeight,e.theme,this.handlers.onClipUpdate,this.handlers.onClipAdd,this.handlers.onClipRemove,this.handlers.onClipSplit,this.handlers.onClipSelect,this.handlers.onTimeJump,this.handlers.onHorizontalDragAutoScroll,this.handlers.onClipOverlap,this.handlers.onClipCrossTrackPreview,this.handlers.onClipCrossTrack,this.handlers.onClearDropPreview,this.handlers.onClearSelection,this.handlers.onSnapGuideChange,this.handlers.onClipToggleSelection,this.handlers.onSetSingleSelection,this.handlers.getMultiDragClipIds,this.handlers.onMultiDragMove,this.handlers.onMultiDragInteractionEnd,e.dragActivationThreshold,e.enableClipSnap,e.clipSnapThreshold)}}class Zl{constructor(e){this.tracks=e}getAll(){return this.tracks}getDefaultTrack(){return this.tracks[0]||null}getPrimaryTrack(){return this.tracks.find(e=>{var t;return((t=e.getRole)==null?void 0:t.call(e))==="primary"})||this.getDefaultTrack()}getLastTrack(){return this.tracks.length>0?this.tracks[this.tracks.length-1]:null}add(e){this.tracks.push(e)}findById(e){return this.tracks.find(t=>this.resolveTrackId(t)===e)||null}removeById(e){const t=this.findIndexById(e);if(t===-1)return null;const[i]=this.tracks.splice(t,1);return i||null}removeEmptyNonPrimaryTracks(){var t;const e=[];for(let i=this.tracks.length-1;i>=0;i-=1){const n=this.tracks[i];if(((t=n.getRole)==null?void 0:t.call(n))==="primary"||(typeof n.getClips=="function"?n.getClips():[]).length>0)continue;const[r]=this.tracks.splice(i,1);r&&e.push(r)}return e.reverse()}findTrackByClipId(e){return this.tracks.find(t=>t.getClips().some(i=>i.id===e))||null}getAllClips(){return this.tracks.flatMap(e=>e.getClips())}syncCurrentTime(e){this.tracks.forEach(t=>{var i;return(i=t.setCurrentTime)==null?void 0:i.call(t,e)})}syncZoom(e){this.tracks.forEach(t=>{var i;return(i=t.setZoom)==null?void 0:i.call(t,e)})}syncScrollLeft(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollLeft)==null?void 0:i.call(t,e)})}syncScrollTop(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollTop)==null?void 0:i.call(t,e)})}updateClip(e,t){this.tracks.forEach(i=>{var n;return(n=i.updateClip)==null?void 0:n.call(i,e,t)})}removeClip(e){this.tracks.forEach(t=>{var i;return(i=t.removeClip)==null?void 0:i.call(t,e)})}addClipToTrack(e,t){const i=this.findById(e);return i!=null&&i.addClip?(i.addClip(t),!0):!1}removeClipFromTrack(e,t){const i=this.findById(e);return i!=null&&i.removeClip?(i.removeClip(t),!0):!1}moveClipToTrack(e,t,i){if(t===i)return!0;const n=this.findById(t),s=this.findById(i);return!(n!=null&&n.removeClip)||!(s!=null&&s.addClip)?!1:(n.removeClip(e.id),s.addClip(e),!0)}removeClipGaps(){this.tracks.forEach(e=>{var t;return(t=e.removeClipGaps)==null?void 0:t.call(e)})}clearSelection(){this.tracks.forEach(e=>{var t;return(t=e.clearSelection)==null?void 0:t.call(e)})}syncSelection(e,t=e[0]??null){this.tracks.forEach(i=>{var n;(n=i.setSelection)==null||n.call(i,e,t)})}findPrimarySelectedClip(){var e;for(const t of this.tracks){const i=(e=t.getPrimarySelectedClip)==null?void 0:e.call(t);if(i)return i}return null}forEach(e){this.tracks.forEach(e)}findIndexById(e){return this.tracks.findIndex(t=>this.resolveTrackId(t)===e)}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}class Ns{constructor(e=[]){g(this,"tracks",[]);g(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,n){this.trackCounter++;const s=t||`${e==="video"?"视频":"音频"}轨道 ${this.trackCounter}`,r=this.tracks.length===0?"primary":"normal",o={id:`track_${Date.now()}_${this.trackCounter}`,type:e,name:s,order:this.tracks.length,role:r,clips:[]};return this.insertTrack(o,i,n),L.debugLazy("TrackManager",()=>`创建轨道: ${s}`,()=>({trackId:o.id,type:e,order:o.order})),o}removeTrack(e){var i;const t=this.tracks.findIndex(n=>n.id===e);return t===-1?(L.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(L.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),L.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(n=>n.id===e);return i?(i.name=t,L.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(L.warn("TrackManager",`轨道不存在: ${e}`),!1)}getTracks(){return[...this.tracks]}getTrack(e){return this.tracks.find(t=>t.id===e)}getTracksByType(e){return this.tracks.filter(t=>t.type===e)}updateTrack(e,t){const i=this.tracks.find(n=>n.id===e);return i?(Object.assign(i,t),L.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(L.warn("TrackManager",`轨道不存在: ${e}`),!1)}recalculateOrder(){this.tracks.forEach((e,t)=>{e.order=t})}insertTrack(e,t,i){const n=this.tracks.findIndex(r=>r.role==="primary"),s=t??(e.type==="video"?"before_primary":"after_primary");if(n===-1||e.role==="primary"){this.tracks.push(e),this.recalculateOrder();return}if((s==="before_track"||s==="after_track")&&i){const r=this.tracks.findIndex(o=>o.id===i);if(r!==-1){this.tracks.splice(r+(s==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(s==="top_of_type_region"){const r=this.tracks.findIndex(o=>o.type===e.type);if(r!==-1){this.tracks.splice(r,0,e),this.recalculateOrder();return}}if(s==="bottom_of_type_region"){const r=this.tracks.reduce((o,l,h)=>l.type===e.type?h:o,-1);if(r!==-1){this.tracks.splice(r+1,0,e),this.recalculateOrder();return}}s==="before_primary"?this.tracks.splice(n,0,e):this.tracks.splice(n+1,0,e),this.recalculateOrder()}muteTrack(e,t){const i=this.tracks.find(n=>n.id===e);return i?(i.isMuted=t,L.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(L.warn("TrackManager",`轨道不存在:${e}`),!1)}isTrackMuted(e){const t=this.tracks.find(i=>i.id===e);return(t==null?void 0:t.isMuted)??!1}clearAllTracks(){this.tracks=[],this.trackCounter=0,L.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}function Ye(a){return a==="video"?_e.VIDEO:_e.AUDIO}function gt(a,e,t){let i=t;for(const n of a){if(n.id===e)break;i+=Ye(n.type)}return i}function zn(a,e){return a.reduce((t,i)=>t+Ye(i.type),e)}function Jl(a,e){let t=e;return a.map(i=>{const n=Ye(i.type),s={trackId:i.id,y:t,height:n};return t+=n,s})}const zs=200,Fs=8,Fn="timeline-manager-managed-layout-styles";function Ql(){if(typeof document>"u"||document.getElementById(Fn))return;const a=document.createElement("style");a.id=Fn,a.textContent=`
16
16
  .timeline-manager-root {
17
17
  position: relative;
18
18
  overflow: hidden;
@@ -38,4 +38,4 @@ js: import "konva/skia-backend";
38
38
  height: 0;
39
39
  display: none;
40
40
  }
41
- `,document.head.appendChild(a)}function bl(a,t){vl();const e=t.leftPanelWidth??En,i=t.scrollbarSize??In;a.innerHTML="",a.classList.add("timeline-manager-root"),a.style.gridTemplateColumns=`${e}px minmax(0, 1fr)`,a.style.gridTemplateRows=`${t.timeScaleHeight}px minmax(0, 1fr)`,a.style.background=t.theme.background;const s=kt("div");s.className="timeline-manager-header-corner",Ve(s,t.theme),s.style.gridColumn="1",s.style.gridRow="1",s.style.borderBottom=`1px solid ${t.theme.border}`;const n=kt("div");n.className="timeline-manager-header-viewport",Ve(n,t.theme),n.style.gridColumn="2",n.style.gridRow="1",n.style.borderBottom=`1px solid ${t.theme.border}`,n.style.overflow="hidden";const r=kt("div");r.className="timeline-manager-header-canvas-host",r.style.width="100%",r.style.height="100%",n.appendChild(r);const o=kt("div");o.className="timeline-manager-track-info-viewport",Ve(o,t.theme),o.style.gridColumn="1",o.style.gridRow="2",o.style.overflow="hidden",o.style.borderRight=`1px solid ${t.theme.border}`;const l=kt("div");l.className="timeline-manager-scroll-viewport timeline-manager-body-viewport",Ve(l,t.theme),l.style.gridColumn="2",l.style.gridRow="2",l.style.overflowX="hidden",l.style.overflowY="auto";const h=kt("div");h.className="timeline-manager-body-canvas-host",h.style.width="100%",h.style.height="100%",h.style.position="relative",h.style.background=t.theme.background,l.appendChild(h);const c=kt("div");c.className="timeline-manager-v-scrollbar-canvas-host",c.style.position="absolute",c.style.top=`${t.timeScaleHeight}px`,c.style.right="0",c.style.bottom="0",c.style.width=`${i}px`,c.style.zIndex="5";const d=kt("div");d.className="timeline-manager-h-scrollbar-canvas-host",d.style.position="absolute",d.style.left=`${e}px`,d.style.right="0",d.style.bottom="0",d.style.height=`${i}px`,d.style.zIndex="4";const u=kt("div");return u.className="timeline-manager-playhead-overlay",u.style.position="absolute",u.style.left=`${e}px`,u.style.top="0",u.style.right="0",u.style.bottom="0",u.style.pointerEvents="none",u.style.zIndex="3",a.appendChild(s),a.appendChild(n),a.appendChild(o),a.appendChild(l),a.appendChild(c),a.appendChild(d),a.appendChild(u),{headerCorner:s,headerViewport:n,headerCanvasHost:r,trackInfoViewport:o,bodyViewport:l,bodyCanvasHost:h,verticalScrollbarCanvasHost:c,horizontalScrollbarCanvasHost:d,playheadOverlay:u}}function kt(a){return document.createElement(a)}function Ve(a,t){a.style.position="relative",a.style.minWidth="0",a.style.minHeight="0",a.style.maxWidth="100%",a.style.boxSizing="border-box",a.style.background=t.background,a.style.color=t.clipName}class kl{constructor(t){g(this,"currentTime");g(this,"playState");g(this,"speed");this.currentTime=t.currentTime,this.playState=t.playState,this.speed=t.speed}getCurrentTime(){return this.currentTime}setCurrentTime(t){this.currentTime=t}getPlayState(){return this.playState}setPlayState(t){this.playState=t}getSpeed(){return this.speed}setSpeed(t){this.speed=t}}class Mn{constructor(){g(this,"selectedClipIds",new Set)}getSelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(t){this.selectedClipIds.add(t)}removeFromSelection(t){this.selectedClipIds.delete(t)}toggleSelection(t){this.selectedClipIds.has(t)?this.selectedClipIds.delete(t):this.selectedClipIds.add(t)}setSelection(t){this.selectedClipIds=new Set(t)}setSelectedClipId(t){t===null?this.selectedClipIds.clear():this.selectedClipIds=new Set([t])}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(t){return this.selectedClipIds.has(t)}getSelectionCount(){return this.selectedClipIds.size}}class wl{constructor(t){g(this,"zoom");g(this,"duration");g(this,"scrollLeft");g(this,"scrollTop");g(this,"viewportWidth");g(this,"viewportHeight");g(this,"contentHeight");this.zoom=t.zoom,this.duration=t.duration,this.scrollLeft=t.scrollLeft||0,this.scrollTop=t.scrollTop||0,this.viewportWidth=t.viewportWidth||0,this.viewportHeight=t.viewportHeight||0,this.contentHeight=t.contentHeight||0}getZoom(){return this.zoom}setZoom(t){this.zoom=t}getDuration(){return this.duration}setDuration(t){this.duration=t}getScrollLeft(){return this.scrollLeft}setScrollLeft(t){this.scrollLeft=t}getScrollTop(){return this.scrollTop}setScrollTop(t){this.scrollTop=t}getViewportWidth(){return this.viewportWidth}setViewportWidth(t){this.viewportWidth=t}getViewportHeight(){return this.viewportHeight}setViewportHeight(t){this.viewportHeight=t}getContentHeight(){return this.contentHeight}setContentHeight(t){this.contentHeight=t}}class Ls{constructor(t){g(this,"selectionStore");g(this,"playbackStore");g(this,"viewportStore");this.selectionStore=new Mn,this.playbackStore=new kl({currentTime:t.currentTime,playState:t.playState,speed:t.speed}),this.viewportStore=new wl({zoom:t.zoom,duration:t.duration,scrollLeft:t.scrollLeft,scrollTop:t.scrollTop,viewportWidth:t.viewportWidth,viewportHeight:t.viewportHeight,contentHeight:t.contentHeight}),t.selectedClipId!==void 0&&this.selectionStore.setSelectedClipId(t.selectedClipId)}getSelectedClipId(){return this.selectionStore.getSelectedClipId()}setSelectedClipId(t){this.selectionStore.setSelectedClipId(t)}clearSelection(){this.selectionStore.clear()}hasSelection(){return this.selectionStore.hasSelection()}getCurrentTime(){return this.playbackStore.getCurrentTime()}setCurrentTime(t){this.playbackStore.setCurrentTime(t)}getPlayState(){return this.playbackStore.getPlayState()}setPlayState(t){this.playbackStore.setPlayState(t)}getSpeed(){return this.playbackStore.getSpeed()}setSpeed(t){this.playbackStore.setSpeed(t)}getZoom(){return this.viewportStore.getZoom()}setZoom(t){this.viewportStore.setZoom(t)}getDuration(){return this.viewportStore.getDuration()}setDuration(t){this.viewportStore.setDuration(t)}getScrollLeft(){return this.viewportStore.getScrollLeft()}setScrollLeft(t){this.viewportStore.setScrollLeft(t)}getScrollTop(){return this.viewportStore.getScrollTop()}setScrollTop(t){this.viewportStore.setScrollTop(t)}getViewportWidth(){return this.viewportStore.getViewportWidth()}setViewportWidth(t){this.viewportStore.setViewportWidth(t)}getViewportHeight(){return this.viewportStore.getViewportHeight()}setViewportHeight(t){this.viewportStore.setViewportHeight(t)}getContentHeight(){return this.viewportStore.getContentHeight()}setContentHeight(t){this.viewportStore.setContentHeight(t)}}class _l{constructor(t,e,i,s,n){g(this,"stage");g(this,"layer");g(this,"onTimeChange");g(this,"onScrollChange");g(this,"config");g(this,"theme");g(this,"scrollLeft",0);g(this,"timeScaleHeight",40);g(this,"isDragging",!1);g(this,"dragStartX",0);g(this,"isPointerInsideTimeline",!1);g(this,"lastPointerXInTimeline",null);g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"handleGlobalPointerMove",t=>{this.isDragging&&this.handlePointerMove(t)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=t,this.layer=e,this.onTimeChange=s,this.onScrollChange=n,this.config={duration:i.duration||36e5,zoom:i.zoom||ct.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:be(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(t){}setZoom(t){this.config.zoom=t,this.render()}setDuration(t){this.config.duration=t,this.render()}setScrollLeft(t){this.scrollLeft=this.clampScrollLeft(t),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(t){const e=z.timeToPixels(t,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,e-i/2))}scrollToClip(t){const e=z.timeToPixels(t.startTime,this.config.zoom),s=z.timeToPixels(t.startTime+t.duration,this.config.zoom)-e,n=this.stage.width(),r=s<=n?Math.max(0,e-(n-s)/2):Math.max(0,e);this.setScrollLeft(r)}resize(t){this.stage.width(t),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",t=>{t.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(t.evt.offsetX),"seek")}),this.stage.on("mousedown",t=>{t.target.getLayer()===this.layer&&(this.updatePointerPosition(t.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=t.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",t=>{this.updatePointerPosition(t.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(t.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(t){if(!Number.isFinite(t))return;const e=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(e,t))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Pe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(xe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(t){const e=t.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-e),s=this.scrollLeft;this.dragStartX=t.clientX,this.scrollLeft=i,this.render(),s!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(t){return z.pixelsToTime(t-ot+this.scrollLeft,this.config.zoom)}timeToPixel(t){return z.timeToPixels(t,this.config.zoom)-this.scrollLeft+ot}render(){const t=this.stage.width(),e=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(t),i.height(e),i.fill(this.theme.background),i.stroke(this.theme.border);else{const s=it.createRect(0,0,t,e,this.theme.background,this.theme.border,1);s.name("timeline-header-background"),this.layer.add(s)}this.layer.find(".time-tick-line").forEach(s=>s.remove()),this.layer.find(".time-tick-text").forEach(s=>s.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const t=this.stage.width(),e=this.scrollLeft,i=this.scrollLeft+t,s=z.pixelsToTime(e,this.config.zoom),n=z.pixelsToTime(i,this.config.zoom),r=z.msToSeconds(s),o=z.msToSeconds(n),{majorStep:l,minorStep:h}=z.getTickConfig(this.config.zoom),c=z.generateVisibleTicks(r-10,o+10,l,h);for(const d of c){const u=this.timeToPixel(d.time);u>=-20&&u<=t+20&&it.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(t){const e=Math.max(0,z.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(e,t))}}const V=class V{constructor(t,e,i,s,n,r,o){g(this,"container");g(this,"visualElement");g(this,"lineHitAreaElement");g(this,"theme");g(this,"onTimeChange");g(this,"onHorizontalAutoScroll");g(this,"currentTime");g(this,"zoom");g(this,"scrollLeft",0);g(this,"height");g(this,"isDragging",!1);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"lastPointerClientX",null);g(this,"handleGlobalPointerMove",t=>{this.isDragging&&(this.lastPointerClientX=t.clientX,this.updateTimeFromClientX(t.clientX),this.updateEdgeAutoScrollState(t.clientX))});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleMouseDown",t=>{t.preventDefault(),t.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=t.clientX,this.bindGlobalPointerListeners()});g(this,"handleHandleClick",t=>{t.preventDefault(),t.stopPropagation()});g(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const t=this.container.getBoundingClientRect(),e=this.lastPointerClientX-t.left,i=this.calculateHorizontalAutoScrollVelocity(e,t.width);if(i===0){this.stopEdgeAutoScroll();return}const s=this.scrollLeft,n=this.onHorizontalAutoScroll(this.scrollLeft+i),r=typeof n=="number"?n:this.scrollLeft;if(this.scrollLeft=Math.max(0,r),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-s)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=t,this.currentTime=e,this.zoom=i,this.height=s,this.theme=n,this.onTimeChange=r,this.onHorizontalAutoScroll=o,this.container.innerHTML="",this.container.style.position="absolute",this.container.style.pointerEvents="none",this.container.style.overflow="visible",this.visualElement=document.createElementNS(V.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${V.VISUAL_WIDTH}`),this.visualElement.style.position="absolute",this.visualElement.style.top="0",this.visualElement.style.marginLeft=`${-14/2}px`,this.visualElement.style.pointerEvents="none",this.visualElement.style.overflow="visible",this.lineHitAreaElement=document.createElement("div"),this.lineHitAreaElement.className="timeline-manager-playhead-hit-area",this.lineHitAreaElement.style.position="absolute",this.lineHitAreaElement.style.top="0",this.lineHitAreaElement.style.width=`${V.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(t){this.currentTime=Math.max(0,t),this.render()}setTime(t){this.setCurrentTime(t)}setZoom(t){this.zoom=t,this.render()}setScrollLeft(t){this.scrollLeft=Math.max(0,t),this.render()}setHeight(t){this.height=Math.max(0,t),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Pe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(xe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(t){const e=this.container.getBoundingClientRect(),i=t-e.left,s=z.pixelsToTime(i-ot+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,s),"scrub")}updateEdgeAutoScrollState(t){if(!this.onHorizontalAutoScroll)return;const e=this.container.getBoundingClientRect(),i=t-e.left;if(this.calculateHorizontalAutoScrollVelocity(i,e.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(t,e){if(e<=0)return 0;const i=Math.min(V.AUTO_SCROLL_EDGE_THRESHOLD,e/2),s=V.AUTO_SCROLL_MAX_SPEED;if(t<=0)return-s;if(t>=e)return s;if(t<i){const n=(i-t)/i;return-Math.max(1,Math.round(n*s))}if(t>e-i){const n=(t-(e-i))/i;return Math.max(1,Math.round(n*s))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const t=z.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+ot,e=t>=0&&t<=this.container.clientWidth,i=Math.max(V.HANDLE_HEIGHT+V.END_CAP_HEIGHT,this.height);this.visualElement.style.display=e?"block":"none",this.lineHitAreaElement.style.display=e?"block":"none",this.visualElement.style.left=`${t}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${V.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${t}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(t){const e=this.theme.clipSelectedBackground||"#8c90ff",i=Math.max(V.HANDLE_HEIGHT,t-V.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(e),this.createMainLine(i),this.createEndCap(i,this.theme.playhead))}createHandleShadowPath(){const t=document.createElementNS(V.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-shadow"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill","rgba(0, 0, 0, 0.22)"),t.setAttribute("transform","translate(-0.5, 0.75)"),t}createHandleBadgePath(t){const e=document.createElementNS(V.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-badge"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill",t),e}createGripLines(t){return[4.5,7,9.5].map(e=>{const i=document.createElementNS(V.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${e}`),i.setAttribute("y2",`${e}`),i.setAttribute("stroke",t),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(t){const e=document.createElementNS(V.SVG_NS,"rect");return e.setAttribute("class","timeline-manager-playhead-line"),e.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),e.setAttribute("y",`${V.HANDLE_LINE_START}`),e.setAttribute("width",`${V.LINE_WIDTH}`),e.setAttribute("height",`${Math.max(0,t-V.HANDLE_LINE_START+1)}`),e.setAttribute("rx","1"),e.setAttribute("fill",this.theme.playhead),e}createEndCap(t,e){const i=document.createElementNS(V.SVG_NS,"g");i.setAttribute("class","timeline-manager-playhead-end-cap"),i.setAttribute("transform",`translate(0 ${t})`);const s=document.createElementNS(V.SVG_NS,"rect");s.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),s.setAttribute("y","0"),s.setAttribute("width",`${V.LINE_WIDTH}`),s.setAttribute("height","7"),s.setAttribute("rx","1"),s.setAttribute("fill",e);const n=document.createElementNS(V.SVG_NS,"rect");return n.setAttribute("x",`${(V.VISUAL_WIDTH-V.END_CAP_WIDTH)/2}`),n.setAttribute("y","7"),n.setAttribute("width",`${V.END_CAP_WIDTH}`),n.setAttribute("height","3"),n.setAttribute("rx","1.5"),n.setAttribute("fill",e),i.appendChild(s),i.appendChild(n),i}};g(V,"SVG_NS","http://www.w3.org/2000/svg"),g(V,"VISUAL_WIDTH",14),g(V,"HANDLE_HEIGHT",16),g(V,"HANDLE_LINE_START",13),g(V,"LINE_WIDTH",2),g(V,"LINE_HIT_WIDTH",12),g(V,"END_CAP_WIDTH",14),g(V,"END_CAP_HEIGHT",10),g(V,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(V,"AUTO_SCROLL_MAX_SPEED",18);let xi=V;class Ds{constructor(t){g(this,"container");g(this,"orientation");g(this,"theme");g(this,"onScrollChange");g(this,"leadingInset");g(this,"trailingInset");g(this,"stage");g(this,"layer");g(this,"hitAreaRect");g(this,"thumbRect");g(this,"viewportSize",0);g(this,"contentSize",0);g(this,"scrollOffset",0);g(this,"isDragging",!1);g(this,"dragStartClient",0);g(this,"dragStartOffset",0);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"handleGlobalPointerMove",t=>{this.isDragging&&this.handleDragMove(t)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleStageMouseDown",t=>{var s;t.evt.preventDefault();const e=t.target===this.thumbRect||typeof((s=t.target)==null?void 0:s.name)=="function"&&t.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?t.evt.clientX:t.evt.clientY;e||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});g(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});g(this,"handleStageMouseEnter",()=>{this.updateCursor()});g(this,"handleStageMouseMove",()=>{this.updateCursor()});g(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=t.container,this.orientation=t.orientation,this.theme=t.theme,this.onScrollChange=t.onScrollChange,this.leadingInset=Math.max(0,t.leadingInset||0),this.trailingInset=Math.max(0,t.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new X.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new X.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=it.createRect(0,0,0,0,"rgba(0, 0, 0, 0.001)","transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=it.createRect(0,0,0,0,this.theme.scrollbarThumb||"#444444",this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555",1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(t,e){this.viewportSize=Math.max(0,t),this.contentSize=Math.max(0,e),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(t){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(t),this.render())}setScrollTop(t){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(t),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Pe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(xe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(t){const i=(this.orientation==="horizontal"?t.clientX:t.clientY)-this.dragStartClient,s=this.getAvailableTrackSize(),n=this.getThumbSize(s),r=Math.max(1,s-n),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/r*o;this.emitScrollChange(l)}jumpToPointer(t){const e=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?t-e.left:t-e.top,s=this.getAvailableTrackSize(),n=this.getThumbSize(s),r=Math.max(1,s-n),o=Math.max(0,Math.min(s,i-this.leadingInset)),l=Math.max(0,Math.min(r,o-n/2)),h=this.getMaxScrollOffset(),c=r<=0?0:l/r*h;this.emitScrollChange(c)}emitScrollChange(t){const e=this.clampScrollOffset(t);this.scrollOffset=e,this.render(),this.onScrollChange(e)}render(){const t=Math.max(0,this.container.clientWidth),e=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(t),this.stage.height(e),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(t),this.hitAreaRect.height(e),this.thumbRect.fill(this.theme.scrollbarThumb||"#444444"),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555");const s=this.getAvailableTrackSize();if(s<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const n=this.getThumbSize(s),r=this.leadingInset+this.getThumbPosition(s,n);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(r),this.thumbRect.y(0),this.thumbRect.width(n),this.thumbRect.height(e)):(this.thumbRect.x(0),this.thumbRect.y(r),this.thumbRect.width(t),this.thumbRect.height(n)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(t){return Math.max(0,Math.min(this.getMaxScrollOffset(),t))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(t){return t<=0||this.contentSize<=0?t:this.contentSize<=this.viewportSize?Math.min(t,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*t)}getThumbPosition(t,e){const i=this.getMaxScrollOffset();if(i<=0||e>=t)return 0;const s=Math.max(1,t-e);return this.scrollOffset/i*s}}class Pl{constructor(){g(this,"entries",new Map)}register(t,e){this.entries.set(t,{id:t,destroy:e})}unregister(t){this.entries.delete(t)}destroyAll(){for(const t of this.entries.values())t.destroy();this.entries.clear()}}class xl{constructor(){g(this,"panel",null);g(this,"config",null);g(this,"isInternalUpdate",!1)}init(t){this.config=t;const e=this.convertTheme(t.theme);this.panel=new bn({container:t.container,theme:e,onClipUpdate:(i,s)=>{this.isInternalUpdate=!0,t.updateClip(i,s),setTimeout(()=>{this.isInternalUpdate=!1},0)}})}update(){if(!this.panel||!this.config)return;const t=this.config.getSelectedClip();this.panel.setClip(t)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}convertTheme(t){return{backgroundColor:t.background||"#1e1e1e",borderColor:t.border||"#333",textColor:t.clipName||"#e0e0e0",labelColor:t.timeText||"#999",inputBackground:t.trackBackground||"#2d2d2d",inputBorder:t.trackBorder||"#444",inputFocusBorder:"#409eff",buttonBackground:t.clipBackground||"#2d2d2d",buttonBorder:t.clipBorder||"#444",buttonActiveBackground:t.clipSelectedBackground||"#409eff",buttonActiveBorder:t.clipSelectedBorder||"#409eff",buttonActiveText:t.clipSelectedName||"#fff"}}}const Al="2.0.3",El={version:Al},Il=1,Ml=2,Ll=8e3;class Dl{constructor(t={}){g(this,"timeline",null);g(this,"tracks",[]);g(this,"trackManager");g(this,"trackInfoPanelController");g(this,"playhead",null);g(this,"history");g(this,"config");g(this,"eventDispatcher");g(this,"animationFrameId",null);g(this,"lastUpdateTime",0);g(this,"isInitialized",!1);g(this,"stage",null);g(this,"headerStage",null);g(this,"headerLayer",null);g(this,"backgroundLayer",null);g(this,"trackLayer",null);g(this,"dragOverlayLayer",null);g(this,"snapGuideLayer",null);g(this,"selectionBoxLayer",null);g(this,"selectionBoxRect",null);g(this,"isBoxSelecting",!1);g(this,"boxSelectStartX",0);g(this,"boxSelectStartY",0);g(this,"resizeObserver",null);g(this,"rootContainer",null);g(this,"layout",null);g(this,"bodyBackgroundRect",null);g(this,"snapGuideLine",null);g(this,"trackInsertionPreviewLine",null);g(this,"trackInsertionPreviewY",null);g(this,"snapGuideTime",null);g(this,"horizontalScrollbar",null);g(this,"verticalScrollbar",null);g(this,"isExecutingHistoryAction",!1);g(this,"lastTrackDuration",0);g(this,"thumbnailProvider",null);g(this,"canPlay",!1);g(this,"sourceLoadingCount",0);g(this,"timelineStore");g(this,"timelineCommands");g(this,"timelineHistoryExecutor");g(this,"timelineHistoryRecorder");g(this,"timelinePresentationAdapter");g(this,"timelineTrackBridge");g(this,"timelinePlaybackResolver");g(this,"previewSession");g(this,"previewMountContainer",null);g(this,"resolvedPreviewBackend","dom");g(this,"runtimePreviewBackendOverride",null);g(this,"lastSelectedClipId",null);g(this,"previewSourceLoadingCount",0);g(this,"previewBuffering",!1);g(this,"pendingPreviewState",null);g(this,"nextPendingPreviewSyncRequestId",0);g(this,"activePreviewCallbackToken",0);g(this,"previewAspectRatio",{...vt});g(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});g(this,"bodyCanvasHostClickListener",t=>{this.handleBodyCanvasHostClick(t)});g(this,"rootWheelListener",t=>{this.handleUnifiedWheel(t)});g(this,"mountManager",new Pl);g(this,"pendingDraftData",null);g(this,"selectionStore",new Mn);g(this,"multiDragSession",null);g(this,"clipRemovalBatchDepth",0);this.config={duration:t.duration||36e5,zoom:t.zoom||ct.MEDIUM,currentTime:t.currentTime||0,playState:t.playState||"paused",container:t.container,theme:be(t.theme),timeScaleHeight:t.timeScaleHeight,logConfig:t.logConfig,speed:t.speed||1,dragActivationThreshold:t.dragActivationThreshold??4,enableClipSnap:t.enableClipSnap??!1,clipSnapThreshold:t.clipSnapThreshold??8,thumbnailProvider:t.thumbnailProvider,previewBackend:t.previewBackend??"dom",previewSourceResolver:t.previewSourceResolver},O.setConfig(this.config.logConfig),O.debug("TimelineManager","日志系统初始化完成",{logConfig:this.config.logConfig}),this.thumbnailProvider=t.thumbnailProvider||null,this.trackInfoPanelController=new Cl,this.eventDispatcher=new Ps({can_play_change:()=>({canPlay:this.canPlay}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new Pi(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Ts(this.history),this.timelineHistoryExecutor=new Ss({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)}),this.trackManager=new An,this.timelineStore=new Ls({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new Cs(this.timelineStore),this.timelinePresentationAdapter=new As,this.timelineTrackBridge=new Es({onClipUpdate:(e,i,s)=>this.handleClipUpdate(e,i,s),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),t.draftData&&(this.pendingDraftData=t.draftData),this.config.container&&this.init(this.config.container)}getTimelineStore(){var t,e,i,s,n;if(!this.timelineStore){const r=((t=this.config)==null?void 0:t.currentTime)??0,o=((e=this.config)==null?void 0:e.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,h=((s=this.config)==null?void 0:s.zoom)||ct.MEDIUM,c=((n=this.config)==null?void 0:n.duration)||36e5;this.timelineStore=new Ls({currentTime:r,playState:o,speed:l,zoom:h,duration:c})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new Cs(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Sl(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new As),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Es({onClipUpdate:(t,e,i)=>this.handleClipUpdate(t,e,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this)})),this.timelineTrackBridge}getTimelinePlaybackResolver(){return this.timelinePlaybackResolver||(this.timelinePlaybackResolver=new dl),this.timelinePlaybackResolver}resolveConfiguredPreviewBackend(){return this.runtimePreviewBackendOverride?(this.resolvedPreviewBackend=this.runtimePreviewBackendOverride,this.resolvedPreviewBackend):(this.resolvedPreviewBackend=rl(this.config.previewBackend),this.resolvedPreviewBackend)}createPreviewBackendCallbacks(t=this.activePreviewCallbackToken){return{onBufferingStateChange:e=>{this.isActivePreviewCallbackToken(t)&&(this.previewBuffering=e,this.emitEvent("buffering_state_change",{isBuffering:e}),this.updatePendingPreviewState())},onSourceLoadingChange:e=>{this.isActivePreviewCallbackToken(t)&&(this.previewSourceLoadingCount=e,this.emitEvent("source_loading_change",this.getSourceLoadingState()),this.updatePendingPreviewState())},onSyncProcessed:e=>{this.isActivePreviewCallbackToken(t)&&(this.pendingPreviewState&&e===this.pendingPreviewState.syncRequestId&&(this.pendingPreviewState.awaitingSync=!1),this.updatePendingPreviewState())},onAspectRatioChange:e=>{this.isActivePreviewCallbackToken(t)&&(this.previewAspectRatio=Dt(e),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onVisualTransformCommit:(e,i)=>{this.isActivePreviewCallbackToken(t)&&this.commitPreviewVisualTransform(e,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(t)&&this.retryPendingPreview()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(t)&&this.handlePreviewBackendRuntimeError()}}}createPreviewBackend(t=this.resolveConfiguredPreviewBackend()){const e=this.createPreviewBackendCallbacks(++this.activePreviewCallbackToken);return new nl(e)}isActivePreviewCallbackToken(t){return t===this.activePreviewCallbackToken}getPreviewSession(){return this.previewSession||(this.previewSession=this.createPreviewBackend()),this.previewSession}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Ps({can_play_change:()=>({canPlay:this.canPlay??!1}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new Pi(()=>{},()=>{})),this.timelineHistoryRecorder=new Ts(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new Ss({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)})),this.timelineHistoryExecutor}get selectedClipId(){return this.getTimelineStore().getSelectedClipId()}set selectedClipId(t){this.getTimelineStore().setSelectedClipId(t)}ensureConfigState(){return this.config||(this.config={duration:36e5,zoom:ct.MEDIUM,currentTime:0,playState:"paused",theme:be(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,clipSnapThreshold:8,previewBackend:"dom"}),this.config}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(t){this.getTimelineStore().setPlayState(t),this.ensureConfigState().playState=t}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(t){this.getTimelineStore().setDuration(t),this.ensureConfigState().duration=t}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(t){this.getTimelineStore().setScrollLeft(t)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(t){this.getTimelineStore().setScrollTop(t)}setViewportMetrics(t,e,i){const s=this.getTimelineStore();s.setViewportWidth(t),s.setViewportHeight(e),s.setContentHeight(i)}syncCurrentTimeToScene(t){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),t)}syncZoomToScene(t){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),t)}syncScrollTopPresentation(t){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,t)}refreshScrollbarMetrics(){var i,s,n,r;const t=this.getViewportWidth(),e=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(s=this.verticalScrollbar)==null||s.resize(),(n=this.horizontalScrollbar)==null||n.setViewportMetrics(t,this.getHorizontalContentWidth()),(r=this.verticalScrollbar)==null||r.setViewportMetrics(e,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var t;return((t=this.layout)==null?void 0:t.bodyViewport.clientWidth)||0}getViewportHeight(){var t;return((t=this.layout)==null?void 0:t.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return z.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(t){const e=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(e,t))}clampScrollTop(t){const e=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(e,t))}syncScrollLeft(t){var i,s;const e=this.clampScrollLeft(t);this.setScrollLeftState(e),(i=this.timeline)==null||i.setScrollLeft(e),(s=this.horizontalScrollbar)==null||s.setScrollLeft(e),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),e),this.refreshSnapGuideLine()}syncScrollTop(t){var i;const e=this.clampScrollTop(t);this.setScrollTopState(e),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-e)>.5&&(this.layout.bodyViewport.scrollTop=e),this.syncScrollTopPresentation(e)}getResolvedTracksSnapshot(){const t=this.getTrackCollection();return this.trackManager.getTracks().map(e=>{const i=t.findById(e.id);return{...e,clips:i?i.getClips():[...e.clips]}})}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(t=>({id:t.id,type:t.type,order:t.order,isMuted:t.isMuted??!1,clips:t.clips}))}buildPlaybackPlan(t=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),t)}getPreviewAutoAspectRatioClipOrderMap(){const t=this;return t.previewAutoAspectRatioVideoClipOrder instanceof Map||(t.previewAutoAspectRatioVideoClipOrder=new Map),t.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const t=this;return Number.isFinite(t.nextPreviewAutoAspectRatioVideoClipOrder)||(t.nextPreviewAutoAspectRatioVideoClipOrder=0),t.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const t=this.getPreviewAutoAspectRatioClipOrderMap(),e=this.getPlaybackTracksSnapshot().slice().sort((r,o)=>r.order-o.order);let i=null,s=null,n=Number.POSITIVE_INFINITY;for(const r of e){if(r.type!=="video")continue;const o=[...r.clips].sort((l,h)=>l.startTime-h.startTime);for(const l of o){const h={trackId:r.id,trackType:r.type,trackOrder:r.order,clip:l,mediaTime:l.startTimeAtSource,muted:(r.isMuted??!1)||(l.isMuted??!1),kind:r.type,hasVisual:!0,hasAudio:!0};i||(i=h);const c=t.get(l.id);c===void 0||c>=n||(s=h,n=c)}}return s||i}registerPreviewAutoAspectRatioClip(t){const e=this,i=this.getPreviewAutoAspectRatioClipOrderMap();t.type!=="video"||i.has(t.id)||(i.set(t.id,this.getNextPreviewAutoAspectRatioOrder()),e.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}syncPreviewSession(){var s,n,r;if(!((s=this.previewSession)!=null&&s.hasPreview()))return;const t=this.buildPlaybackPlan(),e=this.getAutoAspectRatioClip(),i=Dt(this.previewAspectRatio);this.previewAspectRatio=i,this.previewSession.applyAspectRatio(i),this.previewSession.sync({...t,autoAspectRatioClip:e,currentTime:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),selectedClipId:this.selectedClipId,...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),(r=(n=this.previewSession).setPendingState)==null||r.call(n,this.buildPreviewPendingState())}beginPendingPreview(t,e="seek"){var s,n;if(!((s=this.previewSession)!=null&&s.hasPreview()))return;const i=((n=this.pendingPreviewState)==null?void 0:n.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPlayStateState()==="playing"&&this.pause(),this.clearPendingPreviewTimeout(),this.pendingPreviewState={mode:e,targetTime:t,resumePlayOnReady:i,errorMessage:null,timeoutId:null,awaitingSync:!0,syncRequestId:++this.nextPendingPreviewSyncRequestId}}updatePendingPreviewState(){var i,s,n,r,o,l,h,c;if(!this.pendingPreviewState){(s=(i=this.previewSession)==null?void 0:i.setPendingState)==null||s.call(i,null);return}const t=this.previewSourceLoadingCount>0||this.previewBuffering;if(this.pendingPreviewState.errorMessage){(r=(n=this.previewSession)==null?void 0:n.setPendingState)==null||r.call(n,this.buildPreviewPendingState());return}if(this.pendingPreviewState.awaitingSync){(l=(o=this.previewSession)==null?void 0:o.setPendingState)==null||l.call(o,this.buildPreviewPendingState());return}if(t){this.ensurePendingPreviewTimeout(),(c=(h=this.previewSession)==null?void 0:h.setPendingState)==null||c.call(h,this.buildPreviewPendingState());return}const e=this.pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),e&&this.play()}buildPreviewPendingState(){return!this.pendingPreviewState||this.pendingPreviewState.mode==="scrub"?null:{mode:this.pendingPreviewState.mode,targetTime:this.pendingPreviewState.targetTime,loadingPending:this.previewSourceLoadingCount,isBuffering:this.previewBuffering,errorMessage:this.pendingPreviewState.errorMessage}}ensurePendingPreviewTimeout(){if(!this.pendingPreviewState||this.pendingPreviewState.mode==="scrub"||this.pendingPreviewState.timeoutId!==null)return;const t=this.pendingPreviewState.syncRequestId;this.pendingPreviewState.timeoutId=setTimeout(()=>{var e,i;!this.pendingPreviewState||this.pendingPreviewState.syncRequestId!==t||(this.pendingPreviewState.errorMessage="资源加载异常,请刷新重试",this.clearPendingPreviewTimeout(),(i=(e=this.previewSession)==null?void 0:e.setPendingState)==null||i.call(e,this.buildPreviewPendingState()))},Ll)}clearPendingPreviewTimeout(){var t;(t=this.pendingPreviewState)!=null&&t.timeoutId&&(clearTimeout(this.pendingPreviewState.timeoutId),this.pendingPreviewState.timeoutId=null)}clearPendingPreviewState(){var t,e;this.clearPendingPreviewTimeout(),this.pendingPreviewState=null,(e=(t=this.previewSession)==null?void 0:t.setPendingState)==null||e.call(t,null)}resetPreviewRuntimeState(){const t=this.previewBuffering,e=this.previewSourceLoadingCount!==0;this.previewBuffering=!1,this.previewSourceLoadingCount=0,t&&this.emitEvent("buffering_state_change",{isBuffering:!1}),e&&this.emitEvent("source_loading_change",this.getSourceLoadingState())}destroyPreviewSession(t=!1){this.activePreviewCallbackToken+=1;const e=this.previewSession;e==null||e.destroy(),t&&(this.previewSession=void 0),this.resetPreviewRuntimeState()}recreateDetachedPreviewSession(){this.previewSession&&(this.previewSession=this.createPreviewBackend(this.resolvedPreviewBackend))}retryPendingPreview(){this.pendingPreviewState&&(this.pendingPreviewState.errorMessage=null,this.pendingPreviewState.awaitingSync=!0,this.pendingPreviewState.syncRequestId=++this.nextPendingPreviewSyncRequestId,this.clearPendingPreviewTimeout(),this.syncPreviewSession())}handlePreviewBackendRuntimeError(){if(this.resolvedPreviewBackend!=="pixi"||!this.previewSession)return;const t=this.previewMountContainer;if(this.clearPendingPreviewState(),this.destroyPreviewSession(!0),this.runtimePreviewBackendOverride="dom",this.resolvedPreviewBackend="dom",t){const e=this.createPreviewBackend("dom");this.previewSession=e,e.attach(t),e.applyAspectRatio(Dt(this.previewAspectRatio)),this.previewAspectRatio=e.getAspectRatio(),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}}init(t){var i,s,n,r,o,l,h;if(this.isInitialized){O.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=t,this.layout=bl(t,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:En,scrollbarSize:In}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(s=(i=this.layout.bodyCanvasHost).addEventListener)==null||s.call(i,"click",this.bodyCanvasHostClickListener),(r=(n=this.rootContainer)==null?void 0:n.addEventListener)==null||r.call(n,"wheel",this.rootWheelListener,{passive:!1}),this.headerStage=new X.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new X.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new X.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new X.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new X.Layer({name:"trackLayer"}),this.dragOverlayLayer=new X.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new X.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new X.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const e=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(e&&e.addEventListener("mousedown",this.handleStageMouseDown.bind(this)),this.timeline=new _l(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new xi(this.layout.playheadOverlay,this.getCurrentTimeState(),this.getZoomState(),this.getTimeScaleHeight()+this.getViewportHeight(),this.config.theme,this.handleTimeChange.bind(this),this.handleHorizontalDragAutoScroll.bind(this)),this.horizontalScrollbar=new Ds({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:ot,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Ds({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:c=>{this.syncScrollTop(c)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(t),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(h=this.stage)==null||h.batchDraw(),this.pendingDraftData){const c=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(c).catch(d=>{O.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(t,e,i,s){var c,d,u;if(!this.trackLayer)return O.error("TimelineManager","Track layer not initialized"),"";const n=this.trackManager.createTrack(t,e,i,s),r=n.id,o=Vt(t),l=this.calculateTrackY(r),h=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:r,clips:[],role:n.role},trackType:t,zoom:this.getZoomState(),trackY:l,trackHeight:o,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(c=h.setSnapTargetResolver)==null||c.call(h,()=>this.getClips()),(d=h.setDragOverlayLayer)==null||d.call(h,this.dragOverlayLayer),this.getTrackCollection().add(h),this.updateAllTrackPositions(),(u=this.stage)==null||u.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),r}removeTrack(t){var s,n,r,o;const e=this.getTrackCollection().findById(t);if(!e)return!1;if(e.getClips().length>0)return O.warn("TimelineManager","Cannot remove track with clips"),!1;if(((s=e.getRole)==null?void 0:s.call(e))==="primary")return O.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(t);return i&&((r=(n=e.getTrackGroup)==null?void 0:n.call(e))==null||r.destroy(),this.getTrackCollection().removeById(t),this.updateAllTrackPositions(),(o=this.stage)==null||o.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),i}renameTrack(t,e){const i=this.trackManager.renameTrack(t,e);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}getTracks(){return this.getResolvedTracksSnapshot()}initTrackInfoPanel(t){O.warn("TimelineManager","initTrackInfoPanel() is deprecated. TimelineManager now manages the frozen track-info panel inside the root container.")}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(t,e){const i=this.trackManager.muteTrack(t,e);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}isTrackMuted(t){return this.trackManager.isTrackMuted(t)}calculateTrackY(t){return he(this.trackManager.getTracks(),t,this.getTrackContentTopOffset())}calculateTotalHeight(){return Is(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var e,i;const t=Tl(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const s of t){const n=this.getTrackCollection().findById(s.trackId);n&&((e=n.setTrackY)==null||e.call(n,s.y),(i=n.setTrackHeight)==null||i.call(n,s.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}cleanupEmptyTracks(){var e,i,s,n;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return;const t=this.getTrackCollection().removeEmptyNonPrimaryTracks();if(t.length!==0){for(const r of t){const o=(e=r.getId)==null?void 0:e.call(r);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(s=(i=r.getTrackGroup)==null?void 0:i.call(r))==null||s.destroy(),this.getTrackCollection().removeById(o))}this.updateAllTrackPositions(),(n=this.stage)==null||n.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()}}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(t=>{var e;return(e=t.clearClipDropPreview)==null?void 0:e.call(t)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(t,e){this.showClipDropPreviews(new Map([[e,[t]]]))}showClipDropPreviews(t){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(e=>{var n,r,o,l;const i=(n=e.getId)==null?void 0:n.call(e),s=i?t.get(i)??[]:[];if(s.length>0){s.length===1?(r=e.showClipDropPreview)==null||r.call(e,s[0]):(o=e.showClipDropPreviews)==null||o.call(e,s);return}(l=e.clearClipDropPreview)==null||l.call(e)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const t=it.createLine([0,0,0,0],this.config.theme.clipSelectedBorder,2);t.name("timeline-track-insertion-preview-line"),t.dash([8,4]),t.visible(!1),t.listening(!1),this.snapGuideLayer.add(t),this.trackInsertionPreviewLine=t}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(t=!0){var i,s,n;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),t&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const e=((s=this.stage)==null?void 0:s.width())??0;this.trackInsertionPreviewLine.stroke(this.config.theme.clipSelectedBorder),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,e,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(e>0),this.trackInsertionPreviewLine.moveToTop(),t&&((n=this.snapGuideLayer)==null||n.batchDraw())}showTrackInsertionPreview(t,e,i){this.getTrackCollection().forEach(n=>{var r;return(r=n.clearClipDropPreview)==null?void 0:r.call(n)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(t,e,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var t;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw())}resolveTrackInsertionPreviewY(t,e,i){const s=this.trackManager.getTracks(),n=s.find(h=>h.role==="primary"),r=s.find(h=>h.type===t),o=[...s].reverse().find(h=>h.type===t);if((e==="before_track"||e==="after_track")&&i){const h=s.find(c=>c.id===i);if(h){const c=he(s,h.id,this.getTrackContentTopOffset());return e==="before_track"?c:c+Vt(h.type)}}if(e==="top_of_type_region"&&r)return he(s,r.id,this.getTrackContentTopOffset());if(e==="bottom_of_type_region"&&o)return he(s,o.id,this.getTrackContentTopOffset())+Vt(o.type);if(!n)return t==="video"?this.getTrackContentTopOffset():Is(s,this.getTrackContentTopOffset());const l=he(s,n.id,this.getTrackContentTopOffset());return t==="video"?l:l+Vt(n.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const t=this.layout.bodyViewport.clientWidth,e=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),s=Math.max(i,e),n=this.clampScrollLeft(this.getScrollLeftState()),r=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(t,e,s),this.headerStage.width(t),this.timeline.resize(t),this.stage.width(t),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${s}px`,this.renderBodyBackground(t,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+e),this.refreshScrollbarMetrics(),this.syncScrollLeft(n),this.syncScrollTop(r),this.stage.batchDraw()}renderBodyBackground(t,e,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(t),this.bodyBackgroundRect.height(e),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const s=new X.Rect({x:0,y:0,width:t,height:e,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});s.on("click",n=>{this.handleBodyBackgroundClick(n.evt.offsetX)}),this.bodyBackgroundRect=s,this.backgroundLayer.add(s),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(t){const e=z.pixelsToTime(t-ot+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,e))}handleBodyCanvasHostClick(t){if(!this.layout||t.target!==this.layout.bodyCanvasHost)return;const e=this.layout.bodyCanvasHost.getBoundingClientRect(),i=t.clientX-e.left;this.handleBodyBackgroundClick(i)}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const t=this.config.theme;this.snapGuideLine=it.createLine([0,0,0,this.calculateTotalHeight()],t.snapGuideLineColor||t.clipSelectedBorder,t.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(t=!0){var s,n;if(!this.snapGuideLine)return;const e=this.config.theme;if(this.snapGuideLine.stroke(e.snapGuideLineColor||e.clipSelectedBorder),this.snapGuideLine.strokeWidth(e.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),t&&((s=this.snapGuideLayer)==null||s.batchDraw());return}const i=ht(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),t&&((n=this.snapGuideLayer)==null||n.batchDraw())}updateSnapGuideLine(t){var e;if(this.snapGuideTime=t,t===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var e;const t=(e=this.layout)==null?void 0:e.bodyViewport;t&&this.syncScrollTop(t.scrollTop)}handleHorizontalDragAutoScroll(t){return this.syncScrollLeft(t),this.getScrollLeftState()}handleUnifiedWheel(t){const e=this.normalizeWheelDelta(t.deltaX,t.deltaMode,"x"),i=this.normalizeWheelDelta(t.deltaY,t.deltaMode,"y");if(t.metaKey||t.ctrlKey){const n=this.getPrimaryWheelDelta(e,i);if(n===0)return;t.preventDefault(),this.handleWheelZoom(n,t.clientX);return}if(t.shiftKey||this.isHorizontalWheelGesture(e,i)){const n=this.getHorizontalScrollDelta(e,i,t.shiftKey);if(n===0)return;t.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+n);return}i!==0&&(t.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(t,e,i){if(!Number.isFinite(t)||t===0)return 0;if(e===Il)return t*16;if(e===Ml){const s=i==="x"?this.getViewportWidth():this.getViewportHeight();return t*(s||1)}return t}getPrimaryWheelDelta(t,e){return Math.abs(e)>=Math.abs(t)?e:t}isHorizontalWheelGesture(t,e){const i=Math.abs(t);if(i<.5)return!1;const s=Math.abs(e);return s<.5?!0:i>s*1.2}getHorizontalScrollDelta(t,e,i){return i&&Math.abs(e)>=Math.abs(t)?e:t}handleWheelZoom(t,e){const i=this.getZoomState(),s=Math.exp(-t*.002),n=Math.max(ct.MIN,Math.min(ct.MAX,i*s));Math.abs(n-i)<1e-4||this.setZoomCenteredOnTimelinePointer(n,this.getWheelAnchorPointerX(e))}getWheelAnchorPointerX(t){var n;const e=(n=this.layout)==null?void 0:n.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!e||i<=0)return 0;const s=t-e.left;return Math.max(0,Math.min(i,s))}play(){if(this.getPlayStateState()!=="playing"){if(this.pendingPreviewState){O.debugLazy("TimelineManager",()=>"Play blocked by pending preview state");return}if(!this.canPlay){O.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}this.setPlayStateState("playing"),this.lastUpdateTime=Date.now(),this.animate(),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession()}}pause(){this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession())}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused")return;const t=Date.now(),e=t-this.lastUpdateTime;this.lastUpdateTime=t;const i=this.getCurrentTimeState()+e*this.getSpeedState();this.setCurrentTime(i),this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}setCurrentTime(t){const e=this.getTimelineCommands().setCurrentTime(t);if(!e.changed){this.pendingPreviewState&&this.pendingPreviewState.targetTime===e.nextValue&&this.syncPreviewSession();return}const i=e.nextValue;this.ensureConfigState().currentTime=i,this.syncCurrentTimeToScene(i),this.emitEvent("time_change",{time:i}),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(t){this.ensureConfigState().enableClipSnap=t,t||this.updateSnapGuideLine(null),this.tracks.forEach(e=>{e.setClipSnapEnabled(t)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setZoom(t){const e=this.getTimelineCommands().setZoom(t);if(!e.changed)return;const i=e.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(t){const e=this.getZoomState(),i=this.getCurrentTimeState(),s=this.getTimelineCommands().setZoom(t);if(!s.changed)return;const n=s.nextValue;if(this.ensureConfigState().zoom=n,this.syncZoomToScene(n),this.refreshScrollbarMetrics(),this.timeline){const r=this.timeline.getScrollLeft(),o=z.timeToPixels(i,e),h=z.timeToPixels(i,n)-o+r;this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft())}this.emitEvent("zoom_change",{zoom:n})}setZoomByInteraction(t){const e=this.timeline;if(!e){this.setZoomCenteredOnPlayhead(t);return}const i=e.getPointerXInTimeline();if(e.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(t,i);return}this.setZoomCenteredOnPlayhead(t)}setZoomCenteredOnTimelinePointer(t,e){if(!this.timeline){this.setZoom(t);return}const i=this.getZoomState(),s=this.timeline.getScrollLeft(),n=z.pixelsToTime(e-ot+s,i),r=this.getTimelineCommands().setZoom(t);if(!r.changed)return;const o=r.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const h=z.timeToPixels(n,o)-(e-ot);this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft()),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(t){const e=this.getTimelineCommands().setSpeed(t);if(!e.changed)return;const i=e.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount+this.previewSourceLoadingCount>0}getSourceLoadingState(){const t=this.sourceLoadingCount+this.previewSourceLoadingCount;return{isLoading:t>0,pending:t}}setThumbnailProvider(t){this.thumbnailProvider=t,this.config.thumbnailProvider=t,this.getClips().forEach(i=>{i.thumbnails||this.loadClipThumbnails(i)})}async loadClipThumbnails(t){if(!this.thumbnailProvider||t.type==="audio")return!1;try{const e=this.thumbnailProvider.getThumbnails(t);if(Array.isArray(e))return this.updateClip(t.id,{thumbnails:e}),!0;if(e instanceof Promise){const i=await e;if(Array.isArray(i))return this.updateClip(t.id,{thumbnails:i}),O.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:t.id,count:i.length})),!0}}catch(e){O.warn("TimelineManager","Error loading clip thumbnails:",{error:e,clipId:t.id})}return!1}async refreshClipThumbnails(t){const e=this.getClips().find(i=>i.id===t);return e?this.loadClipThumbnails(e):!1}async refreshAllClipThumbnails(){const t=this.getClips();return await Promise.all(t.map(i=>this.loadClipThumbnails(i)))}async addClip(t){this.beginSourceLoading();try{return await this.addClipInternal(t)}finally{this.endSourceLoading()}}async addClips(t){if(t.length===0)return[];this.beginSourceLoading();try{const e=[];for(const i of t){const s=await this.addClipInternal(i);e.push(s)}return e}finally{this.endSourceLoading()}}async addClipInternal(t){var d;let e=t.startTime;if(e===void 0){const u=this.getClips();u.length>0?e=Math.max(...u.map(p=>p.endTime)):e=0}const i=t.startTimeAtSource||0,s=t.duration,n=t.endTimeAtSource||i+s;let r=t.sourceDuration;if(!r)try{r=await z.getVideoDuration(t.src),r<=0&&(r=n)}catch(u){O.error("TimelineManager","Failed to get video duration:",{error:u}),r=n}let o=t.thumbnails;const l=t.id||`clip_${t.name}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=t.type||"video",c=Ei({id:l,type:h,externalId:t.externalId,src:t.src,name:t.name,isMuted:t.isMuted??!1,startTime:e,duration:s,startTimeAtSource:i,endTimeAtSource:n,sourceDuration:r,endTime:e+s,thumbnails:o,style:t.style,visualTransform:t.visualTransform,separatedAudioClipId:t.separatedAudioClipId,separatedFromVideoClipId:t.separatedFromVideoClipId});if(O.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:c.id,type:c.type,startTime:c.startTime,duration:c.duration})),this.tracks.length>0){if(t.trackId){const y=this.getTrackCollection().findById(t.trackId);if(y){if(this.registerPreviewAutoAspectRatioClip(c),(d=y.addClip)==null||d.call(y,c),Ue({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{O.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(T){O.warn("TimelineManager","Error loading clip thumbnails:",{error:T})}return c.id}}const u=this.getTimelineCommands().planTrackPlacement(c,this.tracks),p=this.getTrackCollection(),f=fl({clip:c,placement:u,trackCollection:p,createTrack:this.createTrack.bind(this)});Ue({applied:f,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}if(this.thumbnailProvider)try{O.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(u){O.warn("TimelineManager","Error loading clip thumbnails:",{error:u})}return c.id}removeClip(t){const e=this.getTimelineCommands().prepareRemoveClip(t,this.tracks);e.exists&&(e.shouldClearSelection&&this.clearSelection(),Ue({applied:xs(this.getTrackCollection(),e,t),isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(e.clip,e.trackId,e.trackId?this.cloneTrackSnapshot(e.trackId):null,e.trackId?this.getTrackRestoreAnchor(e.trackId):null)},applyEffects:()=>It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)})}))}removeClipsByExternalId(t){if(!t)return!1;const e=this.resolveClipIdsForExternalIdRemoval(t);if(e.length===0)return!1;const i=new Set(e);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let s=!1;return this.withClipRemovalBatch(()=>{for(const n of e){const r=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);r.exists&&(s=xs(this.getTrackCollection(),r,n)||s)}}),s?(Ne({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(t,e){this.getTimelineCommands().findClipById(this.tracks,t)&&(this.getTrackCollection().updateClip(t,e),It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitClip(t,e){const i=this.getTimelineCommands().findClipById(this.tracks,t);i!=null&&i.track.splitSelectedClip&&(i.track.splitSelectedClip(e),It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitCurrentClip(){const t=this.getCurrentTime(),e=this.resolveSelectedClipAtTime(t)??this.getTimelineCommands().findClipAtTime(this.tracks,t);e!=null&&e.track.splitSelectedClip&&(e.track.splitSelectedClip(t),It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var s,n,r;const t=this.getPreviewAspectRatio();let e=t.width,i=t.height;if(Qt(t.mode)&&e===vt.width&&i===vt.height){const o=(s=this.getAutoAspectRatioClip())==null?void 0:s.clip,l=(n=o==null?void 0:o.style)==null?void 0:n.sys_width,h=(r=o==null?void 0:o.style)==null?void 0:r.sys_height;typeof l=="number"&&l>0&&typeof h=="number"&&h>0&&(e=l,i=h)}return{width:e,height:i,aspectRatio:`${e}:${i}`,mode:t.mode}}exportTimeline(){var i,s,n;const t=this.getResolvedTracksSnapshot().slice().sort((r,o)=>r.order-o.order).map(r=>{const o=r.clips.map(l=>({id:l.id,type:l.type,externalId:l.externalId,src:l.src,name:l.name,isMuted:l.isMuted??!1,startTime:Math.round(l.startTime),duration:Math.round(l.duration),endTime:Math.round(l.endTime),startTimeAtSource:Math.round(l.startTimeAtSource),endTimeAtSource:Math.round(l.endTimeAtSource),sourceDuration:Math.round(l.sourceDuration),thumbnails:l.thumbnails,visualTransform:l.type==="video"?ft(l.visualTransform):void 0,separatedAudioClipId:l.separatedAudioClipId,separatedFromVideoClipId:l.separatedFromVideoClipId})).sort((l,h)=>l.startTime-h.startTime);return{id:r.id,type:r.type,name:r.name||"未命名轨道",order:r.order,isMuted:r.isMuted??!1,clips:o}}),e=((n=(s=(i=t[0].clips)==null?void 0:i[0])==null?void 0:s.thumbnails)==null?void 0:n[0])||"";return{version:this.getVersion(),exportTime:Date.now(),coverUrl:e,composition:this.getExportComposition(),tracks:t}}async importTimeline(t){if(!t||!t.composition||!t.tracks){O.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}this.clearAllTracksAndClips(),t.composition.mode==="manual"?this.setPreviewAspectRatio({width:t.composition.width,height:t.composition.height}):this.resetPreviewAspectRatioToAuto();const e=new Map,i=[...t.tracks].sort((o,l)=>o.order-l.order);for(const o of i){const l=this.createTrack(o.type,o.name);this.muteTrack(l,o.isMuted),e.set(o.id,l)}const s=new Map,n=[];for(const o of i){const l=e.get(o.id);if(l)for(const h of o.clips)try{let c=h.separatedAudioClipId;c&&s.has(c)&&(c=s.get(c));let d=h.separatedFromVideoClipId;d&&s.has(d)&&(d=s.get(d));const u={id:h.id,type:h.type,externalId:h.externalId,src:h.src,name:h.name,isMuted:h.isMuted,startTime:h.startTime,duration:h.duration,startTimeAtSource:h.startTimeAtSource,endTimeAtSource:h.endTimeAtSource,sourceDuration:h.sourceDuration,thumbnails:h.thumbnails,visualTransform:h.visualTransform,separatedAudioClipId:c,separatedFromVideoClipId:d,trackId:l},p=await this.addClip(u);s.set(h.id,p)}catch(c){n.push({clipId:h.id,error:c}),O.error("TimelineManager",`Failed to import clip ${h.id}:`,{error:c})}}this.clearHistory();const r={errors:n};this.emitEvent("draft_loaded",r)}getClipsData(){return this.getClips()}getVersion(){return El.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const t=this.getClips();if(t.length===0)return;const e=Math.min(...t.map(h=>h.startTime)),s=(Math.max(...t.map(h=>h.endTime))-e)/1e3,n=((l=this.stage)==null?void 0:l.width())||0,r=n-ot*2;O.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:s,containerWidth:n,availableWidth:r}));const o=Math.min(r/s,ct.MAX);if(this.setZoom(o),this.timeline){const h=t.reduce((c,d)=>d.startTime<c.startTime?d:c);this.scrollToClip(h.id)}}removeClipGaps(){const t=this.getClips().map(e=>({...e}));this.getTrackCollection().removeClipGaps(),t.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(t),this.checkTrackDurationChange()}handleTimeChange(t,e="seek"){this.beginPendingPreview(t,e),this.setCurrentTime(t)}handleScrollChange(t){this.syncScrollLeft(t)}handleClipUpdate(t,e,i){this.isExecutingHistoryAction||this.getTimelineHistoryRecorder().recordClipUpdate(t,e,i),this.emitEvent("clip_updated",{clip:t}),Fo({notifySelectionChange:this.notifySelectionChange.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(t,e),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipAdd(t){this.registerPreviewAutoAspectRatioClip(t),this.emitEvent("clip_added",{clip:t}),Ne({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(t){this.emitEvent("clip_removed",{clipId:t}),!(this.clipRemovalBatchDepth>0)&&Ne({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(t,e){Vo(t,e,!!this.thumbnailProvider)&&this.loadClipThumbnails(t).catch(i=>{O.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:t.id})})}updateCanPlayState(){var n;const t=this.getClips(),e=this.getCurrentTime(),i=Wo(t,e),s=this.canPlay;this.canPlay=Yo({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:((n=t[t.length-1])==null?void 0:n.endTime)||1,setCanPlay:r=>{this.canPlay=r},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:r=>{this.emitEvent("can_play_change",{canPlay:r})}}),s!==this.canPlay&&O.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:s,newState:this.canPlay}))}handleClipSplit(t,e){$o({clip1:t,clip2:e,isExecutingHistoryAction:this.isExecutingHistoryAction,recordSplitClip:this.getTimelineHistoryRecorder().recordSplitClip.bind(this.getTimelineHistoryRecorder()),emitClipUpdated:i=>{this.emitEvent("clip_updated",{clip:i})},emitClipAdded:i=>{this.emitEvent("clip_added",{clip:i})},applyEffects:()=>Ne({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(t){const e=Xo(t);e.shouldJumpToTime&&e.jumpTime!==null?(this.setCurrentTime(e.jumpTime),this.emitEvent("clip_selected",{clip:t}),O.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:t.startTime}))):e.shouldSelectClip&&this.selectClip(t.id,t)}handleActionUndo(t){O.debugLazy("TimelineManager",()=>"Undo action",()=>({type:t==null?void 0:t.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeUndo(t),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}handleActionRedo(t){O.debugLazy("TimelineManager",()=>"Redo action",()=>({type:t==null?void 0:t.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeRedo(t),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}on(t,e){this.getEventDispatcher().on(t,e)}off(t,e){this.getEventDispatcher().off(t,e)}emitEvent(t,e){this.getEventDispatcher().emit(t,e)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=gl({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:t=>this.emitEvent("selected_clip_change",t)})}beginSourceLoading(){this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}handleClipOverlap(t,e){O.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:t.id,currentTrackId:e}));const i=this.getTrackCollection();if(!i.findById(e))return;const s=t.type,n=this.trackManager.getTracksByType(s).length+1,r=s==="video"?`视频轨道 ${n}`:`音频轨道 ${n}`;ml({clip:t,currentTrackId:e,trackType:s,trackName:r,trackCollection:i,createTrack:this.createTrack.bind(this)}),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(t,e,i){const s=this.resolveCrossTrackPreviewDestination(t,e,i);return s.status==="existing_track"?(this.showClipDropPreview(t,s.targetTrackId),s.targetTrackId===i?"self":"external"):s.status==="new_track_insertion"?(this.showTrackInsertionPreview(s.trackType,s.insertionPlacement,s.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(t,e,i,s){O.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:t.id,targetTrackY:i,currentTrackId:s}));const n=this.resolveCrossTrackMoveDestination(t,i,s);return n.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):n.status==="same_track"?(O.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(t,s),!1):(O.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:t.id,targetTrackId:n.targetTrackId})),this.showClipDropPreview(t,n.targetTrackId),this.moveClipToTrackWithHistorySnapshot(t.id,n.targetTrackId,e,t))}getPlayState(){return this.getPlayStateState()}setDuration(t){this.setDurationState(t),this.timeline&&this.timeline.setDuration(t),this.updateViewportLayout()}getDuration(){return this.getDurationState()}resize(t,e){this.rootContainer&&(this.rootContainer.style.width=`${t}px`,this.rootContainer.style.height=`${e}px`,this.updateViewportLayout())}scrollToTime(t,e=!1){this.timeline&&(this.timeline.scrollToTime(t),this.handleScrollChange(this.timeline.getScrollLeft()),e&&this.setCurrentTime(t))}notifySelectionChange(){var e;const t=((e=this.selectionStore)==null?void 0:e.getSelectedClipIds())??[];this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),this.selectedClipId,t)}selectClip(t,e){var s;const i=e||((s=this.getTimelineCommands().findClipById(this.tracks,t))==null?void 0:s.clip);this.getTimelineCommands().selectClip(t),this.notifySelectionChange(),i&&this.emitEvent("clip_selected",{clip:i}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}clearSelection(){this.resetMultiDragSession(),this.getTimelineCommands().clearSelection(),this.selectionStore.clear(),this.notifySelectionChange(),this.emitSelectedClipChangeIfNeeded(),this.updateAllTracksSelectionVisual(),this.syncPreviewSession()}getSelectedClipIds(){return this.selectionStore.getSelectedClipIds()}addToSelection(t){this.resetMultiDragSession(),this.selectionStore.addToSelection(t),this.emitSelectionChangeEvent()}removeFromSelection(t){this.resetMultiDragSession(),this.selectionStore.removeFromSelection(t),this.emitSelectionChangeEvent()}toggleSelection(t){this.resetMultiDragSession(),this.selectionStore.toggleSelection(t),this.emitSelectionChangeEvent(),this.updateAllTracksSelectionVisual()}isClipSelected(t){return this.selectionStore.isSelected(t)}deleteSelectedClips(){this.resetMultiDragSession();const t=this.selectionStore.getSelectedClipIds();if(t.length===0)return;const e=this.getTimelineHistoryRecorder(),i=t.map(n=>{const r=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);return!r.exists||!r.clip?null:e.createRemoveClipAction({...r.clip},r.trackId,r.trackId?this.cloneTrackSnapshot(r.trackId):null,r.trackId?this.getTrackRestoreAnchor(r.trackId):null)}).filter(n=>n!==null);this.clearSelection();const s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const n of t)this.removeClip(n)}finally{this.isExecutingHistoryAction=s}s||e.recordCompoundAction(i,"delete_selected_clips"),this.emitSelectionChangeEvent()}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.resetMultiDragSession(),this.selectionStore.clear();for(const t of this.tracks)for(const e of t.getClips())this.selectionStore.addToSelection(e.id);this.updateAllTracksSelectionVisual(),this.emitSelectionChangeEvent()}emitSelectionChangeEvent(){this.resetMultiDragSession(),this.emitEvent("selection_change",{selectedClipIds:this.selectionStore.getSelectedClipIds()})}updateAllTracksSelectionVisual(){var t;for(const e of this.tracks){const i=e.getClips();for(const s of i)(t=e.updateClipSelection)==null||t.call(e,s.id,this.selectionStore.isSelected(s.id))}}scrollToClip(t,e={}){const{selectClip:i=!1,setCurrentTime:s=!1}=e,n=this.getClips().find(r=>r.id===t);!n||!this.timeline||(this.timeline.scrollToClip(n),this.handleScrollChange(this.timeline.getScrollLeft()),s&&this.setCurrentTime(n.startTime),i&&this.selectClip(t))}getSelectedClip(){return this.selectedClipId&&this.getClips().find(t=>t.id===this.selectedClipId)||null}getSelectedClips(){const t=this.selectionStore.getSelectedClipIds();if(t.length===0)return[];const e=new Map(this.getClips().map(i=>[i.id,i]));return t.map(i=>e.get(i)||null).filter(i=>i!==null)}canDeleteSelectedClips(){return this.selectionStore.getSelectedClipIds().length>0}getSelectedClipAudioAction(){const t=this.getSelectedClips().filter(s=>s.type==="video");return t.length===0?null:t.some(s=>this.canSeparateClipAudio(s.id))?"separate":t.some(s=>this.canRestoreClipAudio(s.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const t=this.getSelectedClipAudioAction();return t?this.applySelectedClipAudioAction(t):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(t){return this.buildPlaybackPlan(t)}getActiveClipsAtTime(t){return this.buildPlaybackPlan(t).activeClips}attachPreview(t){const e=t instanceof HTMLElement?{container:t}:t;this.previewMountContainer=e.container,this.runtimePreviewBackendOverride=null,e.aspectRatio&&(this.previewAspectRatio=Dt({mode:e.aspectRatio.mode??(e.aspectRatio.width&&e.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:e.aspectRatio.width??this.previewAspectRatio.width,height:e.aspectRatio.height??this.previewAspectRatio.height}));const i=this.getPreviewSession();i.attach(e.container),i.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=i.getAspectRatio(),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){var t;(t=this.previewSession)!=null&&t.hasPreview()&&(this.clearPendingPreviewState(),this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this.previewMountContainer=null,O.debugLazy("TimelineManager",()=>"TimelineManager detached from preview container"))}attachClipConfig(t){const e=new xl;e.init({container:t,theme:this.config.theme,getSelectedClip:()=>this.getSelectedClip(),updateClip:(n,r)=>{this.updateClip(n,r),this.handleClipChange()}});const i=()=>e.update(),s=(n,r)=>{var l;const o=this.getSelectedClip();o&&((l=r==null?void 0:r.clip)==null?void 0:l.id)===o.id&&e.updateFromExternal()};return this.on("selected_clip_change",i),this.on("clip_updated",s),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",i),this.off("clip_updated",s),e.destroy()}),e.update(),e}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}getPreviewAspectRatio(){return Dt(this.previewAspectRatio)}setPreviewAspectRatio(t){var e;this.previewAspectRatio=Dt({mode:"manual",width:Math.max(1,t.width),height:Math.max(1,t.height)}),(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var t,e;this.previewAspectRatio={...vt},(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((e=this.previewSession)==null?void 0:e.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){if(this.selectionStore.getSelectedClipIds().length>1)return this.deleteSelectedClips(),!0;const e=this.getSelectedClip()||this.getSelectedClips()[0]||null;return e?(this.removeClip(e.id),!0):!1}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(t){const e=this.getClips().find(i=>i.id===t);return!!e&&e.type==="video"&&!e.separatedAudioClipId}canRestoreClipAudio(t){const e=this.getClips().find(i=>i.id===t);return!!e&&e.type==="video"&&!!e.separatedAudioClipId}async separateClipAudio(t){if(!this.canSeparateClipAudio(t))return null;const e=this.getClips().find(l=>l.id===t);if(!e||e.type!=="video")return null;const i=this.isExecutingHistoryAction;let s=null;this.isExecutingHistoryAction=!0;try{if(s=await this.addClip({type:"audio",src:e.src,name:`${e.name} 原声`,startTime:e.startTime,duration:e.duration,startTimeAtSource:e.startTimeAtSource,endTimeAtSource:e.endTimeAtSource,sourceDuration:e.sourceDuration,separatedFromVideoClipId:e.id,isMuted:!1}),!s)return null;this.updateClip(t,{isMuted:!0,separatedAudioClipId:s})}finally{this.isExecutingHistoryAction=i}if(!s)return null;const n=this.getClips().find(l=>l.id===t),r=this.getClips().find(l=>l.id===s)??null,o=this.resolveTrackIdByClipId(s);return n?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(e,n,r,o),s):null}restoreClipAudio(t){if(!this.canRestoreClipAudio(t))return!1;const e=this.getClips().find(l=>l.id===t);if(!e||e.type!=="video")return!1;const i=e.separatedAudioClipId??null,s=i?this.getClips().find(l=>l.id===i)??null:null,n=i?this.resolveTrackIdByClipId(i):null,r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(t,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=r}const o=this.getClips().find(l=>l.id===t);return o?(r||this.getTimelineHistoryRecorder().recordRestoreClipAudio(e,o,s,n),!0):!1}async applySelectedClipAudioAction(t){const e=this.getSelectedClips().filter(o=>o.type==="video"),i=t==="separate"?e.filter(o=>this.canSeparateClipAudio(o.id)):e.filter(o=>this.canRestoreClipAudio(o.id));if(i.length===0)return!1;if(i.length===1){const[o]=i;return t==="separate"?!!await this.separateClipAudio(o.id):this.restoreClipAudio(o.id)}const s=this.getTimelineHistoryRecorder(),n=[],r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{if(t==="restore")for(const o of i){const l=this.getClips().find(f=>f.id===o.id);if(!l||l.type!=="video")continue;const h=l.separatedAudioClipId??null,c=h?this.getClips().find(f=>f.id===h)??null:null,d=h?this.resolveTrackIdByClipId(h):null,u=this.restoreClipAudio(o.id),p=this.getClips().find(f=>f.id===o.id);!u||!p||n.push(s.createRestoreClipAudioAction({...l},{...p},c?{...c}:null,d))}else for(const o of i){const l=this.getClips().find(p=>p.id===o.id);if(!l||l.type!=="video")continue;const h=await this.separateClipAudio(o.id),c=this.getClips().find(p=>p.id===o.id),d=h?this.getClips().find(p=>p.id===h)??null:null,u=h?this.resolveTrackIdByClipId(h):null;!h||!c||n.push(s.createSeparateClipAudioAction({...l},{...c},d?{...d}:null,u))}}finally{this.isExecutingHistoryAction=r}return r||s.recordCompoundAction(n,`selected_clips_audio_${t}`),n.length>0}moveClipToTrack(t,e){return this.moveClipToTrackWithHistorySnapshot(t,e,null)}moveClipToTrackWithHistorySnapshot(t,e,i,s=null){const n=this.getTimelineCommands().prepareMoveClipToTrack(t,e,this.tracks);if(n.status==="missing_source_track")return O.warn("TimelineManager",`片段不在任何轨道中: ${t}`),!1;if(n.status==="noop")return O.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${t}`),!0;if(n.status==="missing_target_track")return O.warn("TimelineManager",`目标轨道不存在: ${e}`),!1;if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var f,y,T;return{targetTrackType:(y=(f=this.getTrackCollection().findById(e))==null?void 0:f.getTrackType)==null?void 0:y.call(f),clipType:(T=this.getTimelineCommands().findClipById(this.tracks,t))==null?void 0:T.clip.type}}),!1;if(n.status!=="ready")return!1;const{sourceTrackId:r,targetTrackId:o}=n,l=i?{...i}:{...n.clip},h=s?{...s}:{...n.clip},c=this.cloneTrackSnapshot(r),d=this.cloneTrackSnapshot(o),u=pl({command:{...n,clip:h},trackCollection:this.getTrackCollection()}),p=this.getClips().find(f=>f.id===t)??null;return Uo({applied:u,clipId:t,sourceTrackId:r,targetTrackId:o,clipBefore:l,clipAfter:p??l,sourceTrackSnapshot:c,targetTrackSnapshot:d,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>yl({notifySelectionChange:this.notifySelectionChange.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),batchDraw:()=>{var f;(f=this.stage)==null||f.batchDraw()},syncPreviewSession:this.syncPreviewSession.bind(this)})})?(this.clearAllTrackDropPreviews(),!0):!1}getTrackTotalDuration(){return _n(this.getClips())}destroy(){var t,e,i,s,n,r,o,l,h,c,d;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPendingPreviewState(),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(t=this.layout)==null||t.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(s=(e=this.layout)==null?void 0:(i=e.bodyCanvasHost).removeEventListener)==null||s.call(i,"click",this.bodyCanvasHostClickListener),(r=(n=this.rootContainer)==null?void 0:n.removeEventListener)==null||r.call(n,"wheel",this.rootWheelListener),(o=this.horizontalScrollbar)==null||o.destroy(),(l=this.verticalScrollbar)==null||l.destroy(),(h=this.playhead)==null||h.destroy(),(c=this.timeline)==null||c.destroy(),(d=this.stage)==null||d.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(t){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return t()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(t){const e=this.getClips(),i=new Map(e.map(r=>[r.id,r])),s=new Set,n=e.filter(r=>r.externalId===t).map(r=>r.id);for(let r=0;r<n.length;r+=1){const o=n[r];if(s.has(o))continue;s.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!s.has(l.separatedAudioClipId)&&n.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!s.has(l.separatedFromVideoClipId)&&n.push(l.separatedFromVideoClipId))}return e.filter(r=>s.has(r.id)).map(r=>r.id)}shouldClearSelectionForClipIds(t){return this.selectedClipId&&t.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(e=>t.has(e))}resolveSelectedClipAtTime(t){var i;const e=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const s of e){const n=this.getTimelineCommands().findClipById(this.tracks,s),r=n==null?void 0:n.clip;if(r&&t>=r.startTime&&t<r.endTime)return n}return null}handleClipToggleSelection(t){this.resetMultiDragSession(),this.selectionStore.toggleSelection(t),this.emitSelectionChangeEvent(),this.updateAllTracksSelectionVisual()}handleSetSingleSelection(t){this.resetMultiDragSession(),this.selectionStore.setSelection([t]),this.emitSelectionChangeEvent(),this.updateAllTracksSelectionVisual()}getMultiDragClipIds(t){return this.selectionStore.isSelected(t)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(t){const e=this.ensureMultiDragSession(t);if(!e)return!1;try{if(t.isFinal){const i=this.finalizeMultiDragCrossTrack(e,t);return i||this.syncMultiDragPeerClips(e,t,!0),i}return this.syncMultiDragOverlayState(e,t.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(e,t,!1),t.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(e,t.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(e,t)}finally{t.isFinal&&(this.syncMultiDragOverlayState(e,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((t,e)=>{var i;(i=t.setTrackStackOrder)==null||i.call(t,e)})}elevateMultiDragTrackGroups(t,e){var o,l,h;const i=this.resolveMultiDragSessionTrackIds(t);if(i.length<=1)return;const s=i.indexOf(e);s>=0&&(i.splice(s,1),i.push(e));const n=new Set(i);let r=0;for(const c of this.tracks){const d=(o=c.getId)==null?void 0:o.call(c);!d||n.has(d)||(l=c.setTrackStackOrder)==null||l.call(c,r++)}for(const c of i){const d=this.getTrackCollection().findById(c);(h=d==null?void 0:d.setTrackStackOrder)==null||h.call(d,r++)}}resolveMultiDragSessionTrackIds(t){var i;const e=new Set;for(const s of this.tracks){const n=(i=s.getId)==null?void 0:i.call(s);if(!n)continue;t.selectedClipIds.some(o=>{var l;return((l=t.clips.get(o))==null?void 0:l.trackId)===n})&&e.add(n)}return[...e]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(t,e){const i=new Map;for(const s of t.selectedClipIds){const n=t.clips.get(s);if(!n)continue;const r=i.get(n.trackId);r?r.push(s):i.set(n.trackId,[s])}i.forEach((s,n)=>{var o;const r=this.getTrackCollection().findById(n);(o=r==null?void 0:r.setClipsDragOverlayActive)==null||o.call(r,s,e)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(t=>{var e;return(e=t.clearClipDragOverlay)==null?void 0:e.call(t)})}ensureMultiDragSession(t){var s;const e=this.selectionStore.getSelectedClipIds();if(e.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===t.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,e))return this.multiDragSession;const i=new Map;for(const n of e){const r=this.findTrackByClipId(n),o=((s=r==null?void 0:r.getId)==null?void 0:s.call(r))??this.resolveTrackIdByClipId(n),l=r==null?void 0:r.getClips().find(c=>c.id===n);if(!o||!l)continue;const h=n===t.draggedClipId?this.restoreDraggedClipSnapshot(l,t.deltaTime):{...l};i.set(n,{clipId:n,trackId:o,clip:h})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:t.draggedClipId,selectedClipIds:e.slice(),clips:i},this.multiDragSession)}haveSameClipIds(t,e){if(t.length!==e.length)return!1;const i=new Set(e);return t.every(s=>i.has(s))}restoreDraggedClipSnapshot(t,e){const i=Math.max(0,t.startTime-e);return{...t,startTime:i,endTime:i+t.duration}}syncMultiDragPeerClips(t,e,i){for(const s of t.selectedClipIds){if(s===e.draggedClipId)continue;const n=t.clips.get(s);if(!n||n.trackId===e.currentTrackId)continue;const r=this.getTrackCollection().findById(n.trackId);if(!(r!=null&&r.updateClipPosition))continue;const o=Math.max(0,n.clip.startTime+e.deltaTime);r.updateClipPosition(s,o,i,i?0:e.crossTrackOffsetY)}}previewMultiDragCrossTrack(t,e){const i=t.clips.get(e.draggedClipId);if(!i)return!1;const s=this.buildMovedClipSnapshot(i.clip,e.deltaTime),n=this.resolveCrossTrackPreviewDestination(s,e.targetTrackY,i.trackId);if(n.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(n.trackType,n.insertionPlacement,n.referenceTrackId),!0;if(n.status!=="existing_track"||n.targetTrackId===i.trackId)return!1;const r=this.resolveTrackIndexDelta(i.trackId,n.targetTrackId,i.clip.type);if(r===null)return!1;const o=new Map;this.appendPreviewClip(o,n.targetTrackId,s);for(const l of t.selectedClipIds){if(l===e.draggedClipId)continue;const h=t.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,e.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(h,r,c);!d||d===h.trackId||this.appendPreviewClip(o,d,c)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(t,e){const i=t.clips.get(e.draggedClipId);if(!i)return!1;const s=this.buildMovedClipSnapshot(i.clip,e.deltaTime),n=this.resolveCrossTrackMoveDestination(s,e.targetTrackY,i.trackId);if(n.status==="blocked"||n.status==="same_track")return!1;const r=n.targetTrackId;if(!r)return!1;const o=this.resolveTrackIndexDelta(i.trackId,r,i.clip.type);if(o===null)return!1;for(const l of t.selectedClipIds){const h=t.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,e.deltaTime),d=c.startTime,u=l===e.draggedClipId?r:this.resolveMultiDragTargetTrackId(h,o,c);if(u){if(u===h.trackId){this.updateClipPositionWithHistory(h.trackId,h.clipId,d);continue}this.updateClipPositionSilently(h.trackId,h.clipId,d),this.moveClipToTrackWithHistorySnapshot(h.clipId,u,h.clip,c)}}return!0}resolveTrackIndexDelta(t,e,i){const s=this.getTrackIdsByType(i),n=s.indexOf(t),r=s.indexOf(e);return n===-1||r===-1?null:r-n}resolveMultiDragTargetTrackId(t,e,i){const s=this.ensureTrackIdByRelativeIndex(t.trackId,t.clip.type,e);if(!s)return t.trackId;const n=this.calculateTrackY(s)+1,r=this.resolveCrossTrackMoveDestination(i,n,t.trackId);return r.status==="blocked"?s:r.targetTrackId}resolveMultiDragPreviewTargetTrackId(t,e,i){const s=this.findTrackIdByRelativeIndex(t.trackId,t.clip.type,e);if(!s)return null;const n=this.calculateTrackY(s)+1,r=this.resolveCrossTrackPreviewDestination(i,n,t.trackId);return r.status==="existing_track"?r.targetTrackId:null}buildMovedClipSnapshot(t,e){const i=Math.max(0,t.startTime+e);return{...t,startTime:i,endTime:i+t.duration}}appendPreviewClip(t,e,i){const s=t.get(e);if(s){s.push(i);return}t.set(e,[i])}resolveCrossTrackMoveDestination(t,e,i){const s=this.trackManager.getTracks(),n=this.getTimelineCommands().planCrossTrackMove(t,e,i,this.getTrackContentTopOffset(),s,this.tracks);if(n.status==="missing_target_track_by_position")return O.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return O.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:t.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};O.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:t.id}));const r=this.createTrack(n.trackType,void 0,n.insertionPlacement,n.referenceTrackId);return r?{status:"move_to_track",targetTrackId:r}:{status:"blocked"}}resolveCrossTrackPreviewDestination(t,e,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const s=this.trackManager.getTracks();if(!Array.isArray(s)||s.length===0)return{status:"clear"};const n=this.getTimelineCommands().planCrossTrackPreview(t,e,i,this.getTrackContentTopOffset(),s,this.tracks);return n.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:n.targetTrackId}:n.status==="new_track_insertion"?{status:"new_track_insertion",trackType:n.trackType,insertionPlacement:n.insertionPlacement,referenceTrackId:n.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(t,e,i){let s=this.getTrackIdsByType(e);const n=s.indexOf(t);if(n===-1)return null;let r=n+i;for(;r<0;){if(!this.createTrack(e,void 0,"top_of_type_region"))return null;s=this.getTrackIdsByType(e),r+=1}for(;r>=s.length;){if(!this.createTrack(e,void 0,"bottom_of_type_region"))return null;s=this.getTrackIdsByType(e)}return s[r]??null}findTrackIdByRelativeIndex(t,e,i){const s=this.getTrackIdsByType(e),n=s.indexOf(t);if(n===-1)return null;const r=n+i;return r<0||r>=s.length?null:s[r]??null}getTrackIdsByType(t){return this.trackManager.getTracks().filter(e=>e.type===t).map(e=>e.id)}updateClipPositionWithHistory(t,e,i){var n;const s=this.getTrackCollection().findById(t);(n=s==null?void 0:s.updateClipPosition)==null||n.call(s,e,i,!0)}updateClipPositionSilently(t,e,i){const s=this.getTrackCollection().findById(t);if(!(s!=null&&s.updateClipPosition))return;const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{s.updateClipPosition(e,i,!0)}finally{this.isExecutingHistoryAction=n}}ensureSelectionBoxRect(){var e;if(this.selectionBoxRect)return this.selectionBoxRect;const t=new X.Rect({fill:"rgba(80, 130, 230, 0.15)",stroke:"#5082e6",strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(e=this.selectionBoxLayer)==null||e.add(t),this.selectionBoxRect=t,t}showSelectionBoxRect(t,e,i,s){var r;const n=this.ensureSelectionBoxRect();n.x(t),n.y(e),n.width(Math.max(i,1)),n.height(Math.max(s,1)),n.visible(!0),(r=this.selectionBoxLayer)==null||r.batchDraw()}hideSelectionBoxRect(){var t;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(t=this.selectionBoxLayer)==null||t.batchDraw())}handleStageMouseDown(t){if(t.button!==0)return;const e=this.stage;if(!e)return;const i=e.container();if(!i)return;const s=i.getBoundingClientRect(),n=t.clientX-s.left,r=t.clientY-s.top;if(this.isPointOnClip(n,r))return;this.isBoxSelecting=!1,this.boxSelectStartX=n,this.boxSelectStartY=r;const l=c=>{this.handleBoxSelectMove(c)},h=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",h)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",h)}handleBoxSelectMove(t){const e=this.stage;if(!e)return;const i=e.container();if(!i)return;const s=i.getBoundingClientRect(),n=t.clientX-s.left,r=t.clientY-s.top,o=Math.abs(n-this.boxSelectStartX),l=Math.abs(r-this.boxSelectStartY);if(!this.isBoxSelecting&&(o>4||l>4)&&(this.isBoxSelecting=!0),!this.isBoxSelecting)return;const h=Math.min(this.boxSelectStartX,n),c=Math.min(this.boxSelectStartY,r),d=Math.abs(n-this.boxSelectStartX),u=Math.abs(r-this.boxSelectStartY);this.showSelectionBoxRect(h,c,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const t=this.selectionBoxRect;if(t){const e={x:t.x(),y:t.y(),width:t.width(),height:t.height()},i=this.getClipsIntersectingBox(e);this.selectionStore.clear();for(const s of i)this.selectionStore.addToSelection(s);this.emitSelectionChangeEvent(),this.updateAllTracksSelectionVisual()}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(t,e){for(const i of this.tracks){const s=i.getTrackGroup(),n=s.y(),r=s.height()||64;if(!(e<n||e>n+r))for(const o of i.getClips()){const l=ht(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=z.timeToPixels(o.duration,this.getZoomState());if(t>=l&&t<=l+h&&e>=n+2&&e<=n+r-2)return!0}}return!1}getClipsIntersectingBox(t){const e=[];for(const i of this.tracks){const s=i.getTrackGroup(),n=s.y(),r=s.height()||64;for(const o of i.getClips()){const l=ht(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=z.timeToPixels(o.duration,this.getZoomState()),c=n+2,d=r-4,u=l+h,p=c+d,f=t.x+t.width,y=t.y+t.height;l<f&&u>t.x&&c<y&&p>t.y&&e.push(o.id)}}return e}addClipToTrack(t,e){return this.registerPreviewAutoAspectRatioClip(e),this.getTrackCollection().addClipToTrack(t,e)?(It({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(t){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const e=this.getResolvedTracksSnapshot().find(s=>s.id===t);return e?{...e,clips:e.clips.map(s=>({...s}))}:null}ensureTrackFromHistorySnapshot(t,e=null){var d;if(this.getTrackCollection().findById(t.id))return this.renameTrack(t.id,t.name),this.muteTrack(t.id,t.isMuted??!1),t.id;if(t.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const s=this.resolveTrackInsertionFromRestoreAnchor(e);if(s){const u=this.createTrack(t.type,t.name,s.insertionPlacement,s.referenceTrackId);return this.muteTrack(u,t.isMuted??!1),u}const n=[...this.getTracks()].sort((u,p)=>u.order-p.order),r=n.find(u=>u.order>=t.order),o=r?n[n.findIndex(u=>u.id===r.id)-1]??null:n[n.length-1]??null;let l,h;r?(l="before_track",h=r.id):o&&(l="after_track",h=o.id);const c=this.createTrack(t.type,t.name,l,h);return this.muteTrack(c,t.isMuted??!1),c}getTrackRestoreAnchor(t){var s,n,r;if(!((s=this.trackManager)!=null&&s.getTracks))return null;const e=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=e.findIndex(o=>o.id===t);return i===-1?null:{previousTrackId:((n=e[i-1])==null?void 0:n.id)??null,nextTrackId:((r=e[i+1])==null?void 0:r.id)??null}}resolveTrackInsertionFromRestoreAnchor(t){return t?t.previousTrackId&&this.getTrackCollection().findById(t.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:t.previousTrackId}:t.nextTrackId&&this.getTrackCollection().findById(t.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:t.nextTrackId}:null:null}resolveTrackIdByClipId(t){var e;return((e=this.getTimelineCommands().findClipById(this.tracks,t))==null?void 0:e.trackId)??null}findTrackByClipId(t){return this.getTrackCollection().findTrackByClipId(t)}checkTrackDurationChange(){const t=this.lastTrackDuration,e=ll({clips:this.getClips(),lastTrackDuration:this.lastTrackDuration,setLastTrackDuration:i=>{this.lastTrackDuration=i},setTimelineDuration:i=>{var s;this.setDurationState(i),(s=this.timeline)==null||s.setDuration(i),this.updateViewportLayout()},emitTrackDurationChange:i=>{this.emitEvent("track_duration_change",{duration:i})}});e!==t&&O.debugLazy("TimelineManager",()=>`Track duration changed: ${e}ms, setting timeline duration to ${Pn(e)}ms`)}resolveSelectedClipSnapshot(){return ul({getSelectedClip:()=>{var t;return((t=this.getSelectedClip)==null?void 0:t.call(this))||null},findFallbackSelectedClip:()=>this.tracks?this.getTimelinePresentationAdapter().findSelectedClip(this.getTrackCollection()):null})}commitPreviewVisualTransform(t,e){const i=this.getClips().find(r=>r.id===t);if(!i||i.type!=="video")return;const s=ft(i.visualTransform),n=ft(e);kn(s,n)||this.updateClip(t,{visualTransform:n})}clearAllTracksAndClips(){var i,s,n,r;const t=this.getTracks();for(const o of t){const l=this.getTrackCollection().findById(o.id);if(l){const h=[...l.getClips()];for(const c of h)(i=l.removeClip)==null||i.call(l,c.id)}}for(const o of t)if(o.role!=="primary"){const l=o.id,h=this.getTrackCollection().findById(l);(n=(s=h==null?void 0:h.getTrackGroup)==null?void 0:s.call(h))==null||n.destroy(),this.trackManager.removeTrack(l),this.getTrackCollection().removeById(l)}const e=t.find(o=>o.role==="primary");e&&(this.trackManager.renameTrack(e.id,"视频轨道 1"),this.trackManager.muteTrack(e.id,!1)),this.updateAllTrackPositions(),(r=this.stage)==null||r.batchDraw()}}exports.CLIP_LAYER=On;exports.Clip=Xe;exports.ClipConfigPanel=bn;exports.DEFAULT_CLIP_VIEW_STATE=Rs;exports.DEFAULT_PREVIEW_ASPECT_RATIO=vt;exports.HistoryManager=Pi;exports.MIN_CLIP_LINE_WIDTH=ke;exports.PREVIEW_ASPECT_RATIO_PRESETS=Rn;exports.Playhead=Oo;exports.TIMELINE_LEFT_PADDING=ot;exports.TIME_SCALE=Gn;exports.TRACK_HEIGHT=_t;exports.TimeUtils=z;exports.Timeline=Eo;exports.TimelineManager=Dl;exports.Track=Ze;exports.TrackInfoPanel=vn;exports.TrackManager=An;exports.ZOOM_ANIMATION=Os;exports.ZOOM_PRESETS=ct;exports.createClipViewState=Gs;exports.createClipWithViewState=Ei;exports.defaultDarkTheme=$e;exports.isAutoPreviewAspectRatioMode=Qt;exports.normalizePreviewAspectRatio=Dt;exports.normalizePreviewAspectRatioMode=Ai;exports.resolveTheme=be;
41
+ `,document.head.appendChild(a)}function eh(a,e){Ql();const t=e.leftPanelWidth??zs,i=e.scrollbarSize??Fs;a.innerHTML="",a.classList.add("timeline-manager-root"),a.style.gridTemplateColumns=`${t}px minmax(0, 1fr)`,a.style.gridTemplateRows=`${e.timeScaleHeight}px minmax(0, 1fr)`,a.style.background=e.theme.background;const n=ke("div");n.className="timeline-manager-header-corner",$t(n,e.theme),n.style.gridColumn="1",n.style.gridRow="1",n.style.borderBottom=`1px solid ${e.theme.border}`;const s=ke("div");s.className="timeline-manager-header-viewport",$t(s,e.theme),s.style.gridColumn="2",s.style.gridRow="1",s.style.borderBottom=`1px solid ${e.theme.border}`,s.style.overflow="hidden";const r=ke("div");r.className="timeline-manager-header-canvas-host",r.style.width="100%",r.style.height="100%",s.appendChild(r);const o=ke("div");o.className="timeline-manager-track-info-viewport",$t(o,e.theme),o.style.gridColumn="1",o.style.gridRow="2",o.style.overflow="hidden",o.style.borderRight=`1px solid ${e.theme.border}`;const l=ke("div");l.className="timeline-manager-scroll-viewport timeline-manager-body-viewport",$t(l,e.theme),l.style.gridColumn="2",l.style.gridRow="2",l.style.overflowX="hidden",l.style.overflowY="auto";const h=ke("div");h.className="timeline-manager-body-canvas-host",h.style.width="100%",h.style.height="100%",h.style.position="relative",h.style.background=e.theme.background,l.appendChild(h);const c=ke("div");c.className="timeline-manager-v-scrollbar-canvas-host",c.style.position="absolute",c.style.top=`${e.timeScaleHeight}px`,c.style.right="0",c.style.bottom="0",c.style.width=`${i}px`,c.style.zIndex="5";const d=ke("div");d.className="timeline-manager-h-scrollbar-canvas-host",d.style.position="absolute",d.style.left=`${t}px`,d.style.right="0",d.style.bottom="0",d.style.height=`${i}px`,d.style.zIndex="4";const u=ke("div");return u.className="timeline-manager-playhead-overlay",u.style.position="absolute",u.style.left=`${t}px`,u.style.top="0",u.style.right="0",u.style.bottom="0",u.style.pointerEvents="none",u.style.zIndex="3",a.appendChild(n),a.appendChild(s),a.appendChild(o),a.appendChild(l),a.appendChild(c),a.appendChild(d),a.appendChild(u),{headerCorner:n,headerViewport:s,headerCanvasHost:r,trackInfoViewport:o,bodyViewport:l,bodyCanvasHost:h,verticalScrollbarCanvasHost:c,horizontalScrollbarCanvasHost:d,playheadOverlay:u}}function ke(a){return document.createElement(a)}function $t(a,e){a.style.position="relative",a.style.minWidth="0",a.style.minHeight="0",a.style.maxWidth="100%",a.style.boxSizing="border-box",a.style.background=e.background,a.style.color=e.clipName}class th{constructor(e){g(this,"currentTime");g(this,"playState");g(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class Vs{constructor(){g(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class ih{constructor(e){g(this,"zoom");g(this,"duration");g(this,"scrollLeft");g(this,"scrollTop");g(this,"viewportWidth");g(this,"viewportHeight");g(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class Vn{constructor(e){g(this,"selectionStore");g(this,"playbackStore");g(this,"viewportStore");this.selectionStore=new Vs,this.playbackStore=new th({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new ih({zoom:e.zoom,duration:e.duration,scrollLeft:e.scrollLeft,scrollTop:e.scrollTop,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,contentHeight:e.contentHeight}),e.selectedClipIds!==void 0?this.selectionStore.setSelection(e.selectedClipIds):e.selectedClipId!==void 0&&this.selectionStore.setPrimarySelection(e.selectedClipId)}getPrimarySelectedClipId(){return this.selectionStore.getPrimarySelectedClipId()}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return this.selectionStore.getSelectedClipIds()}setSelectedClipIds(e){this.selectionStore.setSelection(e)}setPrimarySelectedClipId(e){this.selectionStore.setPrimarySelection(e)}setSelectedClipId(e){this.setPrimarySelectedClipId(e)}clearSelection(){this.selectionStore.clear()}hasSelection(){return this.selectionStore.hasSelection()}getCurrentTime(){return this.playbackStore.getCurrentTime()}setCurrentTime(e){this.playbackStore.setCurrentTime(e)}getPlayState(){return this.playbackStore.getPlayState()}setPlayState(e){this.playbackStore.setPlayState(e)}getSpeed(){return this.playbackStore.getSpeed()}setSpeed(e){this.playbackStore.setSpeed(e)}getZoom(){return this.viewportStore.getZoom()}setZoom(e){this.viewportStore.setZoom(e)}getDuration(){return this.viewportStore.getDuration()}setDuration(e){this.viewportStore.setDuration(e)}getScrollLeft(){return this.viewportStore.getScrollLeft()}setScrollLeft(e){this.viewportStore.setScrollLeft(e)}getScrollTop(){return this.viewportStore.getScrollTop()}setScrollTop(e){this.viewportStore.setScrollTop(e)}getViewportWidth(){return this.viewportStore.getViewportWidth()}setViewportWidth(e){this.viewportStore.setViewportWidth(e)}getViewportHeight(){return this.viewportStore.getViewportHeight()}setViewportHeight(e){this.viewportStore.setViewportHeight(e)}getContentHeight(){return this.viewportStore.getContentHeight()}setContentHeight(e){this.viewportStore.setContentHeight(e)}}class nh{constructor(e,t,i,n,s){g(this,"stage");g(this,"layer");g(this,"onTimeChange");g(this,"onScrollChange");g(this,"config");g(this,"theme");g(this,"scrollLeft",0);g(this,"timeScaleHeight",40);g(this,"isDragging",!1);g(this,"dragStartX",0);g(this,"isPointerInsideTimeline",!1);g(this,"lastPointerXInTimeline",null);g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=n,this.onScrollChange=s,this.config={duration:i.duration||36e5,zoom:i.zoom||de.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:xt(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(e){}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setScrollLeft(e){this.scrollLeft=this.clampScrollLeft(e),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(e){const t=N.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=N.timeToPixels(e.startTime,this.config.zoom),n=N.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,s=this.stage.width(),r=n<=s?Math.max(0,t-(s-n)/2):Math.max(0,t);this.setScrollLeft(r)}resize(e){this.stage.width(e),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",e=>{e.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(e.evt.offsetX),"seek")}),this.stage.on("mousedown",e=>{e.target.getLayer()===this.layer&&(this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Lt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(e){const t=e.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-t),n=this.scrollLeft;this.dragStartX=e.clientX,this.scrollLeft=i,this.render(),n!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(e){return N.pixelsToTime(e-le+this.scrollLeft,this.config.zoom)}timeToPixel(e){return N.timeToPixels(e,this.config.zoom)-this.scrollLeft+le}render(){const e=this.stage.width(),t=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const n=ie.createRect(0,0,e,t,this.theme.background,this.theme.border,1);n.name("timeline-header-background"),this.layer.add(n)}this.layer.find(".time-tick-line").forEach(n=>n.remove()),this.layer.find(".time-tick-text").forEach(n=>n.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,n=N.pixelsToTime(t,this.config.zoom),s=N.pixelsToTime(i,this.config.zoom),r=N.msToSeconds(n),o=N.msToSeconds(s),{majorStep:l,minorStep:h}=N.getTickConfig(this.config.zoom),c=N.generateVisibleTicks(r-10,o+10,l,h);for(const d of c){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&ie.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,N.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const V=class V{constructor(e,t,i,n,s,r,o){g(this,"container");g(this,"visualElement");g(this,"lineHitAreaElement");g(this,"theme");g(this,"onTimeChange");g(this,"onHorizontalAutoScroll");g(this,"currentTime");g(this,"zoom");g(this,"scrollLeft",0);g(this,"height");g(this,"isDragging",!1);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"lastPointerClientX",null);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});g(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});g(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const n=this.scrollLeft,s=this.onHorizontalAutoScroll(this.scrollLeft+i),r=typeof s=="number"?s:this.scrollLeft;if(this.scrollLeft=Math.max(0,r),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-n)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=e,this.currentTime=t,this.zoom=i,this.height=n,this.theme=s,this.onTimeChange=r,this.onHorizontalAutoScroll=o,this.container.innerHTML="",this.container.style.position="absolute",this.container.style.pointerEvents="none",this.container.style.overflow="visible",this.visualElement=document.createElementNS(V.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${V.VISUAL_WIDTH}`),this.visualElement.style.position="absolute",this.visualElement.style.top="0",this.visualElement.style.marginLeft=`${-14/2}px`,this.visualElement.style.pointerEvents="none",this.visualElement.style.overflow="visible",this.lineHitAreaElement=document.createElement("div"),this.lineHitAreaElement.className="timeline-manager-playhead-hit-area",this.lineHitAreaElement.style.position="absolute",this.lineHitAreaElement.style.top="0",this.lineHitAreaElement.style.width=`${V.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Lt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,n=N.pixelsToTime(i-le+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,n),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(V.AUTO_SCROLL_EDGE_THRESHOLD,t/2),n=V.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-n;if(e>=t)return n;if(e<i){const s=(i-e)/i;return-Math.max(1,Math.round(s*n))}if(e>t-i){const s=(e-(t-i))/i;return Math.max(1,Math.round(s*n))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const e=N.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+le,t=e>=0&&e<=this.container.clientWidth,i=Math.max(V.HANDLE_HEIGHT+V.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${V.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=this.theme.clipSelectedBackground||"#8c90ff",i=Math.max(V.HANDLE_HEIGHT,e-V.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i,this.theme.playhead))}createHandleShadowPath(){const e=document.createElementNS(V.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill","rgba(0, 0, 0, 0.22)"),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(V.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(V.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(V.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),t.setAttribute("y",`${V.HANDLE_LINE_START}`),t.setAttribute("width",`${V.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-V.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e,t){const i=document.createElementNS(V.SVG_NS,"g");i.setAttribute("class","timeline-manager-playhead-end-cap"),i.setAttribute("transform",`translate(0 ${e})`);const n=document.createElementNS(V.SVG_NS,"rect");n.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),n.setAttribute("y","0"),n.setAttribute("width",`${V.LINE_WIDTH}`),n.setAttribute("height","7"),n.setAttribute("rx","1"),n.setAttribute("fill",t);const s=document.createElementNS(V.SVG_NS,"rect");return s.setAttribute("x",`${(V.VISUAL_WIDTH-V.END_CAP_WIDTH)/2}`),s.setAttribute("y","7"),s.setAttribute("width",`${V.END_CAP_WIDTH}`),s.setAttribute("height","3"),s.setAttribute("rx","1.5"),s.setAttribute("fill",t),i.appendChild(n),i.appendChild(s),i}};g(V,"SVG_NS","http://www.w3.org/2000/svg"),g(V,"VISUAL_WIDTH",14),g(V,"HANDLE_HEIGHT",16),g(V,"HANDLE_LINE_START",13),g(V,"LINE_WIDTH",2),g(V,"LINE_HIT_WIDTH",12),g(V,"END_CAP_WIDTH",14),g(V,"END_CAP_HEIGHT",10),g(V,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(V,"AUTO_SCROLL_MAX_SPEED",18);let Ri=V;class Wn{constructor(e){g(this,"container");g(this,"orientation");g(this,"theme");g(this,"onScrollChange");g(this,"leadingInset");g(this,"trailingInset");g(this,"stage");g(this,"layer");g(this,"hitAreaRect");g(this,"thumbRect");g(this,"viewportSize",0);g(this,"contentSize",0);g(this,"scrollOffset",0);g(this,"isDragging",!1);g(this,"dragStartClient",0);g(this,"dragStartOffset",0);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleStageMouseDown",e=>{var n;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((n=e.target)==null?void 0:n.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});g(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});g(this,"handleStageMouseEnter",()=>{this.updateCursor()});g(this,"handleStageMouseMove",()=>{this.updateCursor()});g(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new X.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new X.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=ie.createRect(0,0,0,0,"rgba(0, 0, 0, 0.001)","transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=ie.createRect(0,0,0,0,this.theme.scrollbarThumb||"#444444",this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555",1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Lt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(e){const i=(this.orientation==="horizontal"?e.clientX:e.clientY)-this.dragStartClient,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),r=Math.max(1,n-s),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/r*o;this.emitScrollChange(l)}jumpToPointer(e){const t=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?e-t.left:e-t.top,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),r=Math.max(1,n-s),o=Math.max(0,Math.min(n,i-this.leadingInset)),l=Math.max(0,Math.min(r,o-s/2)),h=this.getMaxScrollOffset(),c=r<=0?0:l/r*h;this.emitScrollChange(c)}emitScrollChange(e){const t=this.clampScrollOffset(e);this.scrollOffset=t,this.render(),this.onScrollChange(t)}render(){const e=Math.max(0,this.container.clientWidth),t=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(e),this.stage.height(t),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(e),this.hitAreaRect.height(t),this.thumbRect.fill(this.theme.scrollbarThumb||"#444444"),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555");const n=this.getAvailableTrackSize();if(n<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const s=this.getThumbSize(n),r=this.leadingInset+this.getThumbPosition(n,s);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(r),this.thumbRect.y(0),this.thumbRect.width(s),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(r),this.thumbRect.width(e),this.thumbRect.height(s)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const n=Math.max(1,e-t);return this.scrollOffset/i*n}}class sh{constructor(){g(this,"entries",new Map)}register(e,t){this.entries.set(e,{id:e,destroy:t})}unregister(e){this.entries.delete(e)}destroyAll(){for(const e of this.entries.values())e.destroy();this.entries.clear()}}class rh{constructor(){g(this,"panel",null);g(this,"config",null);g(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new Os({container:e.container,theme:t,onClipUpdate:(i,n)=>{this.isInternalUpdate=!0,e.updateClip(i,n),setTimeout(()=>{this.isInternalUpdate=!1},0)}})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip();this.panel.setClip(e)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}convertTheme(e){return{backgroundColor:e.background||"#1e1e1e",borderColor:e.border||"#333",textColor:e.clipName||"#e0e0e0",labelColor:e.timeText||"#999",inputBackground:e.trackBackground||"#2d2d2d",inputBorder:e.trackBorder||"#444",inputFocusBorder:"#409eff",buttonBackground:e.clipBackground||"#2d2d2d",buttonBorder:e.clipBorder||"#444",buttonActiveBackground:e.clipSelectedBackground||"#409eff",buttonActiveBorder:e.clipSelectedBorder||"#409eff",buttonActiveText:e.clipSelectedName||"#fff"}}}const ah="2.0.5",oh={version:ah},lh=1,hh=2,ch=120;class dh{constructor(e={}){g(this,"timeline",null);g(this,"tracks",[]);g(this,"trackManager");g(this,"trackInfoPanelController");g(this,"playhead",null);g(this,"history");g(this,"config");g(this,"eventDispatcher");g(this,"animationFrameId",null);g(this,"lastUpdateTime",0);g(this,"isInitialized",!1);g(this,"stage",null);g(this,"headerStage",null);g(this,"headerLayer",null);g(this,"backgroundLayer",null);g(this,"trackLayer",null);g(this,"dragOverlayLayer",null);g(this,"snapGuideLayer",null);g(this,"selectionBoxLayer",null);g(this,"selectionBoxRect",null);g(this,"isBoxSelecting",!1);g(this,"boxSelectStartX",0);g(this,"boxSelectStartY",0);g(this,"resizeObserver",null);g(this,"rootContainer",null);g(this,"layout",null);g(this,"bodyBackgroundRect",null);g(this,"snapGuideLine",null);g(this,"trackInsertionPreviewLine",null);g(this,"trackInsertionPreviewY",null);g(this,"snapGuideTime",null);g(this,"horizontalScrollbar",null);g(this,"verticalScrollbar",null);g(this,"isExecutingHistoryAction",!1);g(this,"lastTrackDuration",0);g(this,"lastEffectiveTrackDuration",0);g(this,"thumbnailProvider",null);g(this,"canPlay",!1);g(this,"sourceLoadingCount",0);g(this,"timelineStore");g(this,"timelineCommands");g(this,"timelineHistoryExecutor");g(this,"timelineHistoryRecorder");g(this,"timelinePresentationAdapter");g(this,"timelineTrackBridge");g(this,"timelinePlaybackResolver");g(this,"previewRuntimeController");g(this,"previewStateController");g(this,"previewPlaybackSuspendedByBuffering",!1);g(this,"previewPlaybackAutoResume",!1);g(this,"previewBufferingSuspendTimeoutId",null);g(this,"lastSelectedClipId",null);g(this,"previewAspectRatio",{...be});g(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});g(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});g(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});g(this,"mountManager",new sh);g(this,"pendingDraftData",null);g(this,"selectionStore",new Vs);g(this,"multiDragSession",null);g(this,"clipRemovalBatchDepth",0);this.config={duration:e.duration||36e5,zoom:e.zoom||de.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:xt(e.theme),timeScaleHeight:e.timeScaleHeight,logConfig:e.logConfig,speed:e.speed||1,dragActivationThreshold:e.dragActivationThreshold??4,enableClipSnap:e.enableClipSnap??!1,clipSnapThreshold:e.clipSnapThreshold??8,thumbnailProvider:e.thumbnailProvider,previewBackend:e.previewBackend??"dom",previewSourceResolver:e.previewSourceResolver},L.setConfig(this.config.logConfig),L.debug("TimelineManager","日志系统初始化完成",{logConfig:this.config.logConfig}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new jl,this.eventDispatcher=new Bn({can_play_change:()=>({canPlay:this.canPlay}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new Li(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new In(this.history),this.timelineHistoryExecutor=new xn({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)}),this.trackManager=new Ns,this.timelineStore=new Vn({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new _n(this.timelineStore),this.timelinePresentationAdapter=new Hn,this.timelineTrackBridge=new Nn({onClipUpdate:(t,i,n)=>this.handleClipUpdate(t,i,n),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),e.draftData&&(this.pendingDraftData=e.draftData),this.config.container&&this.init(this.config.container)}getTimelineStore(){var e,t,i,n,s;if(!this.timelineStore){const r=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,h=((n=this.config)==null?void 0:n.zoom)||de.MEDIUM,c=((s=this.config)==null?void 0:s.duration)||36e5;this.timelineStore=new Vn({currentTime:r,playState:o,speed:l,zoom:h,duration:c})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new _n(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Zl(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new Hn),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Nn({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this)})),this.timelineTrackBridge}getTimelinePlaybackResolver(){return this.timelinePlaybackResolver||(this.timelinePlaybackResolver=new zl),this.timelinePlaybackResolver}get previewSession(){return this.getPreviewRuntimeController().previewSession}set previewSession(e){this.getPreviewRuntimeController().previewSession=e}get previewMountContainer(){return this.getPreviewRuntimeController().previewMountContainer}set previewMountContainer(e){this.getPreviewRuntimeController().previewMountContainer=e}get resolvedPreviewBackend(){return this.getPreviewRuntimeController().resolvedPreviewBackend}set resolvedPreviewBackend(e){this.getPreviewRuntimeController().resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this.getPreviewRuntimeController().runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this.getPreviewRuntimeController().runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this.getPreviewRuntimeController().activePreviewCallbackToken}set activePreviewCallbackToken(e){this.getPreviewRuntimeController().activePreviewCallbackToken=e}get previewSourceLoadingCount(){return this.getPreviewStateController().previewSourceLoadingCount}set previewSourceLoadingCount(e){this.getPreviewStateController().previewSourceLoadingCount=e}get previewBuffering(){return this.getPreviewStateController().previewBuffering}set previewBuffering(e){this.getPreviewStateController().previewBuffering=e}get pendingPreviewState(){return this.getPreviewStateController().pendingPreviewState}set pendingPreviewState(e){this.getPreviewStateController().pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this.getPreviewStateController().nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this.getPreviewStateController().nextPendingPreviewSyncRequestId=e}getPreviewStateController(){return this.previewStateController||(this.previewStateController=new Wl({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitBufferingStateChange:e=>{this.syncPlaybackClockToPreviewBuffering(e),this.emitEvent("buffering_state_change",{isBuffering:e})},emitSourceLoadingStateChange:()=>{this.emitEvent("source_loading_change",this.getSourceLoadingState())},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new Fl({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Rl({callbacks:t,previewSourceResolver:this.config.previewSourceResolver}),resolveConfiguredBackend:e=>e||Dl(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onBufferingStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleBufferingStateChange(t)},onSourceLoadingChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleSourceLoadingChange(t)},onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleRuntimeStateChange(t)},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=De(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(e)&&this.retryPendingPreview()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Bn({can_play_change:()=>({canPlay:this.canPlay??!1}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new Li(()=>{},()=>{})),this.timelineHistoryRecorder=new In(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new xn({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)})),this.timelineHistoryExecutor}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:36e5,zoom:de.MEDIUM,currentTime:0,playState:"paused",theme:xt(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,clipSnapThreshold:8,previewBackend:"dom"}),this.config}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(e){this.getTimelineStore().setPlayState(e),this.ensureConfigState().playState=e}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(e){this.getTimelineStore().setDuration(e),this.ensureConfigState().duration=e}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(e){this.getTimelineStore().setScrollLeft(e)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(e){this.getTimelineStore().setScrollTop(e)}setViewportMetrics(e,t,i){const n=this.getTimelineStore();n.setViewportWidth(e),n.setViewportHeight(t),n.setContentHeight(i)}syncCurrentTimeToScene(e){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncZoomToScene(e){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncScrollTopPresentation(e){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,e)}refreshScrollbarMetrics(){var i,n,s,r;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(n=this.verticalScrollbar)==null||n.resize(),(s=this.horizontalScrollbar)==null||s.setViewportMetrics(e,this.getHorizontalContentWidth()),(r=this.verticalScrollbar)==null||r.setViewportMetrics(t,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientWidth)||0}getViewportHeight(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return N.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(e){const t=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(t,e))}clampScrollTop(e){const t=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(t,e))}syncScrollLeft(e){var i,n;const t=this.clampScrollLeft(e);this.setScrollLeftState(t),(i=this.timeline)==null||i.setScrollLeft(t),(n=this.horizontalScrollbar)==null||n.setScrollLeft(t),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),t),this.refreshSnapGuideLine()}syncScrollTop(e){var i;const t=this.clampScrollTop(e);this.setScrollTopState(t),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-t)>.5&&(this.layout.bodyViewport.scrollTop=t),this.syncScrollTopPresentation(t)}getResolvedTracksSnapshot(){const e=this.getTrackCollection();return this.trackManager.getTracks().map(t=>{const i=e.findById(t.id);return{...t,clips:i?i.getClips():[...t.clips]}})}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(e=>({id:e.id,type:e.type,order:e.order,isMuted:e.isMuted??!1,clips:e.clips}))}buildPlaybackPlan(e=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),e)}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((r,o)=>r.order-o.order);let i=null,n=null,s=Number.POSITIVE_INFINITY;for(const r of t){if(r.type!=="video")continue;const o=[...r.clips].sort((l,h)=>l.startTime-h.startTime);for(const l of o){const h={trackId:r.id,trackType:r.type,trackOrder:r.order,clip:l,mediaTime:l.startTimeAtSource,muted:(r.isMuted??!1)||(l.isMuted??!1),kind:r.type,hasVisual:!0,hasAudio:!0};i||(i=h);const c=e.get(l.id);c===void 0||c>=s||(n=h,s=c)}}return n||i}registerPreviewAutoAspectRatioClip(e){const t=this,i=this.getPreviewAutoAspectRatioClipOrderMap();e.type!=="video"||i.has(e.id)||(i.set(e.id,this.getNextPreviewAutoAspectRatioOrder()),t.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}syncPreviewSession(){var n,s,r;if(!((n=this.previewSession)!=null&&n.hasPreview()))return;const e=this.buildPlaybackPlan(),t=this.getAutoAspectRatioClip(),i=De(this.previewAspectRatio);this.previewAspectRatio=i,this.previewSession.applyAspectRatio(i),this.previewSession.sync({...e,autoAspectRatioClip:t,currentTime:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),primarySelectedClipId:this.getPrimarySelectedClipId(),...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),(r=(s=this.previewSession).setPendingState)==null||r.call(s,this.buildPreviewPendingState())}beginPendingPreview(e,t="seek"){var n,s;if(!((n=this.previewSession)!=null&&n.hasPreview()))return;const i=((s=this.pendingPreviewState)==null?void 0:s.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPlayStateState()==="playing"&&this.pause(),this.getPreviewStateController().beginPendingPreview(e,t,i)}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState()}destroyPreviewSession(e=!1){this.getPreviewRuntimeController().destroyPreviewSession(e),this.resetPreviewRuntimeState()}retryPendingPreview(){this.getPreviewStateController().retryPendingPreview()}handlePreviewBackendRuntimeError(){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();const e=this.getPreviewRuntimeController().fallbackToDom(De(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,n,s,r,o,l,h;if(this.isInitialized){L.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=eh(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:zs,scrollbarSize:Fs}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(n=(i=this.layout.bodyCanvasHost).addEventListener)==null||n.call(i,"click",this.bodyCanvasHostClickListener),(r=(s=this.rootContainer)==null?void 0:s.addEventListener)==null||r.call(s,"wheel",this.rootWheelListener,{passive:!1}),this.headerStage=new X.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new X.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new X.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new X.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new X.Layer({name:"trackLayer"}),this.dragOverlayLayer=new X.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new X.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new X.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const t=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(t&&t.addEventListener("mousedown",this.handleStageMouseDown.bind(this)),this.timeline=new nh(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new Ri(this.layout.playheadOverlay,this.getCurrentTimeState(),this.getZoomState(),this.getTimeScaleHeight()+this.getViewportHeight(),this.config.theme,this.handleTimeChange.bind(this),this.handleHorizontalDragAutoScroll.bind(this)),this.horizontalScrollbar=new Wn({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:le,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Wn({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:c=>{this.syncScrollTop(c)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(e),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(h=this.stage)==null||h.batchDraw(),this.pendingDraftData){const c=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(c).catch(d=>{L.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,n){var c,d,u;if(!this.trackLayer)return L.error("TimelineManager","Track layer not initialized"),"";const s=this.trackManager.createTrack(e,t,i,n),r=s.id,o=Ye(e),l=this.calculateTrackY(r),h=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:r,clips:[],role:s.role},trackType:e,zoom:this.getZoomState(),trackY:l,trackHeight:o,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(c=h.setSnapTargetResolver)==null||c.call(h,()=>this.getClips()),(d=h.setDragOverlayLayer)==null||d.call(h,this.dragOverlayLayer),this.getTrackCollection().add(h),this.updateAllTrackPositions(),(u=this.stage)==null||u.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),r}removeTrack(e){var n,s,r,o;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return L.warn("TimelineManager","Cannot remove track with clips"),!1;if(((n=t.getRole)==null?void 0:n.call(t))==="primary")return L.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((r=(s=t.getTrackGroup)==null?void 0:s.call(t))==null||r.destroy(),this.getTrackCollection().removeById(e),this.updateAllTrackPositions(),(o=this.stage)==null||o.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),i}renameTrack(e,t){const i=this.trackManager.renameTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}getTracks(){return this.getResolvedTracksSnapshot()}initTrackInfoPanel(e){L.warn("TimelineManager","initTrackInfoPanel() is deprecated. TimelineManager now manages the frozen track-info panel inside the root container.")}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){const i=this.trackManager.muteTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return gt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return zn(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=Jl(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const n of e){const s=this.getTrackCollection().findById(n.trackId);s&&((t=s.setTrackY)==null||t.call(s,n.y),(i=s.setTrackHeight)==null||i.call(s,n.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}cleanupEmptyTracks(){var t,i,n,s;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return;const e=this.getTrackCollection().removeEmptyNonPrimaryTracks();if(e.length!==0){for(const r of e){const o=(t=r.getId)==null?void 0:t.call(r);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(n=(i=r.getTrackGroup)==null?void 0:i.call(r))==null||n.destroy(),this.getTrackCollection().removeById(o))}this.updateAllTrackPositions(),(s=this.stage)==null||s.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()}}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDropPreview)==null?void 0:t.call(e)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(e,t){this.showClipDropPreviews(new Map([[t,[e]]]))}showClipDropPreviews(e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(t=>{var s,r,o,l;const i=(s=t.getId)==null?void 0:s.call(t),n=i?e.get(i)??[]:[];if(n.length>0){n.length===1?(r=t.showClipDropPreview)==null||r.call(t,n[0]):(o=t.showClipDropPreviews)==null||o.call(t,n);return}(l=t.clearClipDropPreview)==null||l.call(t)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const e=ie.createLine([0,0,0,0],this.config.theme.clipSelectedBorder,2);e.name("timeline-track-insertion-preview-line"),e.dash([8,4]),e.visible(!1),e.listening(!1),this.snapGuideLayer.add(e),this.trackInsertionPreviewLine=e}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(e=!0){var i,n,s;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),e&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const t=((n=this.stage)==null?void 0:n.width())??0;this.trackInsertionPreviewLine.stroke(this.config.theme.clipSelectedBorder),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,t,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(t>0),this.trackInsertionPreviewLine.moveToTop(),e&&((s=this.snapGuideLayer)==null||s.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(s=>{var r;return(r=s.clearClipDropPreview)==null?void 0:r.call(s)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const n=this.trackManager.getTracks(),s=n.find(h=>h.role==="primary"),r=n.find(h=>h.type===e),o=[...n].reverse().find(h=>h.type===e);if((t==="before_track"||t==="after_track")&&i){const h=n.find(c=>c.id===i);if(h){const c=gt(n,h.id,this.getTrackContentTopOffset());return t==="before_track"?c:c+Ye(h.type)}}if(t==="top_of_type_region"&&r)return gt(n,r.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return gt(n,o.id,this.getTrackContentTopOffset())+Ye(o.type);if(!s)return e==="video"?this.getTrackContentTopOffset():zn(n,this.getTrackContentTopOffset());const l=gt(n,s.id,this.getTrackContentTopOffset());return e==="video"?l:l+Ye(s.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),n=Math.max(i,t),s=this.clampScrollLeft(this.getScrollLeftState()),r=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(e,t,n),this.headerStage.width(e),this.timeline.resize(e),this.stage.width(e),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${n}px`,this.renderBodyBackground(e,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+t),this.refreshScrollbarMetrics(),this.syncScrollLeft(s),this.syncScrollTop(r),this.stage.batchDraw()}renderBodyBackground(e,t,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(e),this.bodyBackgroundRect.height(t),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const n=new X.Rect({x:0,y:0,width:e,height:t,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});n.on("click",s=>{this.handleBodyBackgroundClick(s.evt.offsetX)}),this.bodyBackgroundRect=n,this.backgroundLayer.add(n),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(e){const t=N.pixelsToTime(e-le+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,t))}handleBodyCanvasHostClick(e){if(!this.layout||e.target!==this.layout.bodyCanvasHost)return;const t=this.layout.bodyCanvasHost.getBoundingClientRect(),i=e.clientX-t.left;this.handleBodyBackgroundClick(i)}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=ie.createLine([0,0,0,this.calculateTotalHeight()],e.snapGuideLineColor||e.clipSelectedBorder,e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var n,s;if(!this.snapGuideLine)return;const t=this.config.theme;if(this.snapGuideLine.stroke(t.snapGuideLineColor||t.clipSelectedBorder),this.snapGuideLine.strokeWidth(t.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),e&&((n=this.snapGuideLayer)==null||n.batchDraw());return}const i=ce(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((s=this.snapGuideLayer)==null||s.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const s=this.getPrimaryWheelDelta(t,i);if(s===0)return;e.preventDefault(),this.handleWheelZoom(s,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const s=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(s===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+s);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===lh)return e*16;if(t===hh){const n=i==="x"?this.getViewportWidth():this.getViewportHeight();return e*(n||1)}return e}getPrimaryWheelDelta(e,t){return Math.abs(t)>=Math.abs(e)?t:e}isHorizontalWheelGesture(e,t){const i=Math.abs(e);if(i<.5)return!1;const n=Math.abs(t);return n<.5?!0:i>n*1.2}getHorizontalScrollDelta(e,t,i){return i&&Math.abs(t)>=Math.abs(e)?t:e}handleWheelZoom(e,t){const i=this.getZoomState(),n=Math.exp(-e*.002),s=Math.max(de.MIN,Math.min(de.MAX,i*n));Math.abs(s-i)<1e-4||this.setZoomCenteredOnTimelinePointer(s,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var s;const t=(s=this.layout)==null?void 0:s.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const n=e-t.left;return Math.max(0,Math.min(i,n))}play(){if(this.getPlayStateState()!=="playing"){if(this.pendingPreviewState){L.debugLazy("TimelineManager",()=>"Play blocked by pending preview state");return}if(!this.canPlay){L.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}this.setPlayStateState("playing"),this.lastUpdateTime=Date.now(),this.previewBuffering?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession()}}pause(){this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession())}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused")return;if(this.previewBuffering){this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0,this.animationFrameId=null;return}const e=Date.now(),t=e-this.lastUpdateTime;this.lastUpdateTime=e;const i=this.getCurrentTimeState()+t*this.getSpeedState();this.setCurrentTime(i),this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}syncPlaybackClockToPreviewBuffering(e){if(e){if(this.getPlayStateState()!=="playing"||(this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering||this.previewBufferingSuspendTimeoutId))return;this.previewBufferingSuspendTimeoutId=setTimeout(()=>{this.previewBufferingSuspendTimeoutId=null,!(this.getPlayStateState()!=="playing"||!this.previewBuffering||this.previewPlaybackSuspendedByBuffering)&&(this.previewPlaybackSuspendedByBuffering=!0,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null))},ch);return}if(this.clearPreviewBufferingSuspendTimeout(),!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&this.getPlayStateState()==="playing"&&!this.pendingPreviewState;this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,!(!t||this.animationFrameId)&&(this.lastUpdateTime=Date.now(),this.animate())}clearPreviewBufferingSuspendTimeout(){this.previewBufferingSuspendTimeoutId&&(clearTimeout(this.previewBufferingSuspendTimeoutId),this.previewBufferingSuspendTimeoutId=null)}setCurrentTime(e){const t=this.getTimelineCommands().setCurrentTime(e);if(!t.changed){this.pendingPreviewState&&this.pendingPreviewState.targetTime===t.nextValue&&this.syncPreviewSession();return}const i=t.nextValue;this.ensureConfigState().currentTime=i,this.syncCurrentTimeToScene(i),this.emitEvent("time_change",{time:i}),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(e){this.ensureConfigState().enableClipSnap=e,e||this.updateSnapGuideLine(null),this.tracks.forEach(t=>{t.setClipSnapEnabled(e)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setZoom(e){const t=this.getTimelineCommands().setZoom(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(e){const t=this.getZoomState(),i=this.getCurrentTimeState(),n=this.getTimelineCommands().setZoom(e);if(!n.changed)return;const s=n.nextValue;if(this.ensureConfigState().zoom=s,this.syncZoomToScene(s),this.refreshScrollbarMetrics(),this.timeline){const r=this.timeline.getScrollLeft(),o=N.timeToPixels(i,t),h=N.timeToPixels(i,s)-o+r;this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft())}this.emitEvent("zoom_change",{zoom:s})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),n=this.timeline.getScrollLeft(),s=N.pixelsToTime(t-le+n,i),r=this.getTimelineCommands().setZoom(e);if(!r.changed)return;const o=r.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const h=N.timeToPixels(s,o)-(t-le);this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft()),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(e){const t=this.getTimelineCommands().setSpeed(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount+this.previewSourceLoadingCount>0}getSourceLoadingState(){const e=this.sourceLoadingCount+this.previewSourceLoadingCount;return{isLoading:e>0,pending:e}}setThumbnailProvider(e){this.thumbnailProvider=e,this.config.thumbnailProvider=e,this.getClips().forEach(i=>{i.thumbnails||this.loadClipThumbnails(i)})}async loadClipThumbnails(e){if(!this.thumbnailProvider||e.type==="audio")return!1;try{const t=this.thumbnailProvider.getThumbnails(e);if(Array.isArray(t))return this.updateClip(e.id,{thumbnails:t}),!0;if(t instanceof Promise){const i=await t;if(Array.isArray(i))return this.updateClip(e.id,{thumbnails:i}),L.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:i.length})),!0}}catch(t){L.warn("TimelineManager","Error loading clip thumbnails:",{error:t,clipId:e.id})}return!1}async refreshClipThumbnails(e){const t=this.getClips().find(i=>i.id===e);return t?this.loadClipThumbnails(t):!1}async refreshAllClipThumbnails(){const e=this.getClips();return await Promise.all(e.map(i=>this.loadClipThumbnails(i)))}async addClip(e){this.beginSourceLoading();try{return await this.addClipInternal(e)}finally{this.endSourceLoading()}}async addClips(e){if(e.length===0)return[];this.beginSourceLoading();try{const t=[];for(const i of e){const n=await this.addClipInternal(i);t.push(n)}return t}finally{this.endSourceLoading()}}async addClipInternal(e){var p;let t=e.startTime;if(t===void 0){const y=this.getClips();y.length>0?t=Math.max(...y.map(S=>S.endTime)):t=0}const i=e.startTimeAtSource||0,n=e.duration,s=e.endTimeAtSource||i+n;let r=e.sourceDuration;if(!r)try{r=await N.getVideoDuration(e.src),r<=0&&(r=s)}catch(y){L.error("TimelineManager","Failed to get video duration:",{error:y}),r=s}let o=e.thumbnails;const l=e.id||`clip_${e.name}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=e.type||"video",c=Oi({id:l,type:h,externalId:e.externalId,src:e.src,name:e.name,isMuted:e.isMuted??!1,startTime:t,duration:n,startTimeAtSource:i,endTimeAtSource:s,sourceDuration:r,endTime:t+n,thumbnails:o,style:e.style,visualTransform:e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1});if(L.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:c.id,type:c.type,startTime:c.startTime,duration:c.duration})),e.trackId){const y=this.getTrackCollection().findById(e.trackId);if(y){if(this.registerPreviewAutoAspectRatioClip(c),(p=y.addClip)==null||p.call(y,c),Zt({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{L.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(S){L.warn("TimelineManager","Error loading clip thumbnails:",{error:S})}return c.id}}const d=this.getTimelineCommands().planTrackPlacement(c,this.tracks),u=this.getTrackCollection(),f=Ul({clip:c,placement:d,trackCollection:u,createTrack:this.createTrack.bind(this)});if(Zt({applied:f,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{L.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(y){L.warn("TimelineManager","Error loading clip thumbnails:",{error:y})}return c.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),Zt({applied:Gn(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)})}))}removeClipsByExternalId(e){if(!e)return!1;const t=this.resolveClipIdsForExternalIdRemoval(e);if(t.length===0)return!1;const i=new Set(t);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let n=!1;return this.withClipRemovalBatch(()=>{for(const s of t){const r=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);r.exists&&(n=Gn(this.getTrackCollection(),r,s)||n)}}),n?(Xt({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){this.getTimelineCommands().findClipById(this.tracks,e)&&(this.getTrackCollection().updateClip(e,t),Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);i!=null&&i.track.splitSelectedClip&&(i.track.splitSelectedClip(t),Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e)??this.getTimelineCommands().findClipAtTime(this.tracks,e);t!=null&&t.track.splitSelectedClip&&(t.track.splitSelectedClip(e),Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var n,s,r;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(st(e.mode)&&t===be.width&&i===be.height){const o=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,l=(s=o==null?void 0:o.style)==null?void 0:s.sys_width,h=(r=o==null?void 0:o.style)==null?void 0:r.sys_height;typeof l=="number"&&l>0&&typeof h=="number"&&h>0&&(t=l,i=h)}return{width:t,height:i,aspectRatio:`${t}:${i}`,mode:e.mode}}exportTimeline(){var i,n,s;const e=this.getResolvedTracksSnapshot().slice().sort((r,o)=>r.order-o.order).map(r=>{const o=r.clips.map(l=>({id:l.id,type:l.type,externalId:l.externalId,src:l.src,name:l.name,isMuted:l.isMuted??!1,startTime:Math.round(l.startTime),duration:Math.round(l.duration),endTime:Math.round(l.endTime),startTimeAtSource:Math.round(l.startTimeAtSource),endTimeAtSource:Math.round(l.endTimeAtSource),sourceDuration:Math.round(l.sourceDuration),thumbnails:l.thumbnails,visualTransform:l.type==="video"?fe(l.visualTransform):void 0,separatedAudioClipId:l.separatedAudioClipId,separatedFromVideoClipId:l.separatedFromVideoClipId,volume:l.volume??1})).sort((l,h)=>l.startTime-h.startTime);return{id:r.id,type:r.type,name:r.name||"未命名轨道",order:r.order,isMuted:r.isMuted??!1,clips:o}}),t=((s=(n=(i=e[0].clips)==null?void 0:i[0])==null?void 0:n.thumbnails)==null?void 0:s[0])||"";return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){L.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const t=new Map,i=[...e.tracks].sort((o,l)=>o.order-l.order);for(const o of i){const l=this.createTrack(o.type,o.name);this.muteTrack(l,o.isMuted),t.set(o.id,l)}const n=new Map,s=[];for(const o of i){const l=t.get(o.id);if(l)for(const h of o.clips)try{let c=h.separatedAudioClipId;c&&n.has(c)&&(c=n.get(c));let d=h.separatedFromVideoClipId;d&&n.has(d)&&(d=n.get(d));const u={id:h.id,type:h.type,externalId:h.externalId,src:h.src,name:h.name,isMuted:h.isMuted,startTime:h.startTime,duration:h.duration,startTimeAtSource:h.startTimeAtSource,endTimeAtSource:h.endTimeAtSource,sourceDuration:h.sourceDuration,thumbnails:h.thumbnails,visualTransform:h.visualTransform,separatedAudioClipId:c,separatedFromVideoClipId:d,volume:h.volume,trackId:l},f=await this.addClip(u);n.set(h.id,f)}catch(c){s.push({clipId:h.id,error:c}),L.error("TimelineManager",`Failed to import clip ${h.id}:`,{error:c})}}this.clearHistory();const r={errors:s};this.emitEvent("draft_loaded",r)}stopPlaybackForImport(){var i;const e=this.getPlayStateState()==="playing",t=(i=this.previewSession)!=null&&i.hasPreview()?this.previewMountContainer:null;this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),e?this.pause():this.setPlayStateState("paused"),this.destroyPreviewSession(!0),t&&(this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t,this.previewAspectRatio)),this.syncPreviewSession()}getClipsData(){return this.getClips()}getVersion(){return oh.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(h=>h.startTime)),n=(Math.max(...e.map(h=>h.endTime))-t)/1e3,s=((l=this.stage)==null?void 0:l.width())||0,r=s-le*2;L.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:n,containerWidth:s,availableWidth:r}));const o=Math.min(r/n,de.MAX);if(this.setZoom(o),this.timeline){const h=e.reduce((c,d)=>d.startTime<c.startTime?d:c);this.scrollToClip(h.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){this.beginPendingPreview(e,t),this.setCurrentTime(e)}handleScrollChange(e){this.syncScrollLeft(e)}handleClipUpdate(e,t,i){this.isExecutingHistoryAction||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i),this.emitEvent("clip_updated",{clip:e});const n=this.selectedClipId===e.id;ll({notifySelectionChange:this.notifySelectionChange.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),n&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){this.registerPreviewAutoAspectRatioClip(e),this.emitEvent("clip_added",{clip:e}),Xt({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(e){this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Xt({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){hl(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{L.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){var s;const e=this.getClips(),t=this.getCurrentTime(),i=cl(e,t),n=this.canPlay;this.canPlay=dl({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:((s=e[e.length-1])==null?void 0:s.endTime)||1,setCanPlay:r=>{this.canPlay=r},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:r=>{this.emitEvent("can_play_change",{canPlay:r})}}),n!==this.canPlay&&L.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:n,newState:this.canPlay}))}handleClipSplit(e,t){pl({clip1:e,clip2:t,isExecutingHistoryAction:this.isExecutingHistoryAction,recordSplitClip:this.getTimelineHistoryRecorder().recordSplitClip.bind(this.getTimelineHistoryRecorder()),emitClipUpdated:i=>{this.emitEvent("clip_updated",{clip:i})},emitClipAdded:i=>{this.emitEvent("clip_added",{clip:i})},applyEffects:()=>Xt({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=ul(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),L.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){L.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeUndo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}handleActionRedo(e){L.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeRedo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}on(e,t){this.getEventDispatcher().on(e,t)}off(e,t){this.getEventDispatcher().off(e,t)}emitEvent(e,t){this.getEventDispatcher().emit(e,t)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=Xl({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}handleClipOverlap(e,t){L.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const i=this.getTrackCollection();if(!i.findById(t))return;const n=e.type,s=this.trackManager.getTracksByType(n).length+1,r=n==="video"?`视频轨道 ${s}`:`音频轨道 ${s}`;ql({clip:e,currentTrackId:t,trackType:n,trackName:r,trackCollection:i,createTrack:this.createTrack.bind(this)}),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const n=this.resolveCrossTrackPreviewDestination(e,t,i);return n.status==="existing_track"?(this.showClipDropPreview(e,n.targetTrackId),n.targetTrackId===i?"self":"external"):n.status==="new_track_insertion"?(this.showTrackInsertionPreview(n.trackType,n.insertionPlacement,n.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,n){L.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:n}));const s=this.resolveCrossTrackMoveDestination(e,i,n);return s.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):s.status==="same_track"?(L.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,n),!1):(L.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:s.targetTrackId})),this.showClipDropPreview(e,s.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,s.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}resize(e,t){this.rootContainer&&(this.rootContainer.style.width=`${e}px`,this.rootContainer.style.height=`${t}px`,this.updateViewportLayout())}scrollToTime(e,t=!1){this.timeline&&(this.timeline.scrollToTime(e),this.handleScrollChange(this.timeline.getScrollLeft()),t&&this.setCurrentTime(e))}notifySelectionChange(){const e=this.getSelectedClipIds();this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),e)}syncPrimarySelectionFromSelectionStore(){var t,i,n,s;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((s=(n=this.selectionStore)==null?void 0:n.getSelectedClipId)==null?void 0:s.call(n))??null;this.selectedClipId=e}getOrderedSelectionClipIds(e,t){const i=Array.from(new Set(e));if(i.length<=1)return i;const n=t&&i.includes(t)&&t||this.selectedClipId&&i.includes(this.selectedClipId)&&this.selectedClipId||i[0]||null;return n?[n,...i.filter(s=>s!==n)]:i}setSelection(e,t={}){this.resetMultiDragSession();const i=this.getOrderedSelectionClipIds(e,t.preferredPrimaryClipId);this.selectionStore.setSelection(i),this.syncPrimarySelectionFromSelectionStore(),this.notifySelectionChange(),this.emitSelectionChangeEvent(),t.selectedClipEventClip&&this.emitEvent("clip_selected",{clip:t.selectedClipEventClip}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}selectClip(e,t){var n;const i=t||((n=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:n.clip);this.setSelection([e],{preferredPrimaryClipId:e,selectedClipEventClip:i??null})}clearSelection(){this.setSelection([])}getSelectedClipIds(){var e,t;return((t=(e=this.selectionStore)==null?void 0:e.getSelectedClipIds)==null?void 0:t.call(e))??(this.selectedClipId?[this.selectedClipId]:[])}getPrimarySelectedClipId(){return this.getSelectedClipIds()[0]??null}addToSelection(e){this.setSelection([...this.selectionStore.getSelectedClipIds(),e],{preferredPrimaryClipId:this.selectedClipId??e})}removeFromSelection(e){this.setSelection(this.selectionStore.getSelectedClipIds().filter(t=>t!==e))}toggleSelection(e){const t=this.selectionStore.getSelectedClipIds(),i=t.includes(e);this.setSelection(i?t.filter(n=>n!==e):[...t,e],{preferredPrimaryClipId:i?void 0:e})}isClipSelected(e){return this.selectionStore.isSelected(e)}deleteSelectedClips(){this.resetMultiDragSession();const e=this.selectionStore.getSelectedClipIds();if(e.length===0)return;const t=this.getTimelineHistoryRecorder(),i=e.map(s=>{const r=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);return!r.exists||!r.clip?null:t.createRemoveClipAction({...r.clip},r.trackId,r.trackId?this.cloneTrackSnapshot(r.trackId):null,r.trackId?this.getTrackRestoreAnchor(r.trackId):null)}).filter(s=>s!==null);this.clearSelection();const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const s of e)this.removeClip(s)}finally{this.isExecutingHistoryAction=n}n||t.recordCompoundAction(i,"delete_selected_clips"),this.emitSelectionChangeEvent()}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.setSelection(this.tracks.flatMap(e=>e.getClips().map(t=>t.id)),{preferredPrimaryClipId:this.selectedClipId})}emitSelectionChangeEvent(){this.emitEvent("selection_change",{selectedClipIds:this.selectionStore.getSelectedClipIds()})}scrollToClip(e,t={}){const{selectClip:i=!1,setCurrentTime:n=!1}=t,s=this.getClips().find(r=>r.id===e);!s||!this.timeline||(this.timeline.scrollToClip(s),this.handleScrollChange(this.timeline.getScrollLeft()),n&&this.setCurrentTime(s.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}canDeleteSelectedClips(){return this.getSelectedClipIds().length>0}getSelectedClipAudioAction(){const e=this.getSelectedClips().filter(n=>n.type==="video");return e.length===0?null:e.some(n=>this.canSeparateClipAudio(n.id))?"separate":e.some(n=>this.canRestoreClipAudio(n.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const e=this.getSelectedClipAudioAction();return e?this.applySelectedClipAudioAction(e):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(e){return this.buildPlaybackPlan(e)}getActiveClipsAtTime(e){return this.buildPlaybackPlan(e).activeClips}attachPreview(e){const t=e instanceof HTMLElement?{container:e}:e;t.aspectRatio&&(this.previewAspectRatio=De({mode:t.aspectRatio.mode??(t.aspectRatio.width&&t.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:t.aspectRatio.width??this.previewAspectRatio.width,height:t.aspectRatio.height??this.previewAspectRatio.height})),this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t.container,this.previewAspectRatio),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){this.getPreviewRuntimeController().detachPreviewSession()&&(this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),L.debugLazy("TimelineManager",()=>"TimelineManager detached from preview container"))}attachClipConfig(e){const t=new rh;t.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),updateClip:(s,r)=>{this.updateClip(s,r),this.handleClipChange()}});const i=()=>t.update(),n=(s,r)=>{var l;const o=this.getPrimarySelectedClip();o&&((l=r==null?void 0:r.clip)==null?void 0:l.id)===o.id&&t.updateFromExternal()};return this.on("selected_clip_change",i),this.on("clip_updated",n),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",i),this.off("clip_updated",n),t.destroy()}),t.update(),t}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return De(this.previewAspectRatio)}setPreviewAspectRatio(e){var t;this.previewAspectRatio=De({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...be},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}resolvePreferredSeparatedAudioTrackId(e,t){var l;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return null;const i=this.resolveTrackIdByClipId(e);if(!i)return null;const n=[...this.getResolvedTracksSnapshot()].sort((h,c)=>h.order-c.order),s=n.findIndex(h=>h.id===i);if(s===-1)return null;const r=t.startTime+t.duration,o=n.map((h,c)=>({track:h,index:c})).filter(({track:h})=>h.type==="audio").filter(({track:h})=>!h.clips.some(c=>t.startTime<c.endTime&&r>c.startTime));return o.length===0?null:(o.sort((h,c)=>{const d=Math.abs(h.index-s)-Math.abs(c.index-s);return d!==0?d:h.index-c.index}),((l=o[0])==null?void 0:l.track.id)??null)}async separateClipAudio(e){if(!this.canSeparateClipAudio(e))return null;const t=this.getClips().find(h=>h.id===e);if(!t||t.type!=="video")return null;const i=this.isExecutingHistoryAction,n=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let s=null;this.isExecutingHistoryAction=!0;try{if(s=await this.addClip({type:"audio",src:t.src,name:t.name,startTime:t.startTime,duration:t.duration,startTimeAtSource:t.startTimeAtSource,endTimeAtSource:t.endTimeAtSource,sourceDuration:t.sourceDuration,separatedFromVideoClipId:t.id,isMuted:!1,volume:t.volume??1,trackId:n??void 0}),!s)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:s})}finally{this.isExecutingHistoryAction=i}if(!s)return null;const r=this.getClips().find(h=>h.id===e),o=this.getClips().find(h=>h.id===s)??null,l=this.resolveTrackIdByClipId(s);return r?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,r,o,l),s):null}restoreClipAudio(e){if(!this.canRestoreClipAudio(e))return!1;const t=this.getClips().find(l=>l.id===e);if(!t||t.type!=="video")return!1;const i=t.separatedAudioClipId??null,n=i?this.getClips().find(l=>l.id===i)??null:null,s=i?this.resolveTrackIdByClipId(i):null,r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=r}const o=this.getClips().find(l=>l.id===e);return o?(r||this.getTimelineHistoryRecorder().recordRestoreClipAudio(t,o,n,s),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(o=>o.type==="video"),i=e==="separate"?t.filter(o=>this.canSeparateClipAudio(o.id)):t.filter(o=>this.canRestoreClipAudio(o.id));if(i.length===0)return!1;if(i.length===1){const[o]=i;return e==="separate"?!!await this.separateClipAudio(o.id):this.restoreClipAudio(o.id)}const n=this.getTimelineHistoryRecorder(),s=[],r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{if(e==="restore")for(const o of i){const l=this.getClips().find(p=>p.id===o.id);if(!l||l.type!=="video")continue;const h=l.separatedAudioClipId??null,c=h?this.getClips().find(p=>p.id===h)??null:null,d=h?this.resolveTrackIdByClipId(h):null,u=this.restoreClipAudio(o.id),f=this.getClips().find(p=>p.id===o.id);!u||!f||s.push(n.createRestoreClipAudioAction({...l},{...f},c?{...c}:null,d))}else for(const o of i){const l=this.getClips().find(f=>f.id===o.id);if(!l||l.type!=="video")continue;const h=await this.separateClipAudio(o.id),c=this.getClips().find(f=>f.id===o.id),d=h?this.getClips().find(f=>f.id===h)??null:null,u=h?this.resolveTrackIdByClipId(h):null;!h||!c||s.push(n.createSeparateClipAudioAction({...l},{...c},d?{...d}:null,u))}}finally{this.isExecutingHistoryAction=r}return r||n.recordCompoundAction(s,`selected_clips_audio_${e}`),s.length>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,n=null){const s=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(s.status==="missing_source_track")return L.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(s.status==="noop")return L.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(s.status==="missing_target_track")return L.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(s.status==="track_type_mismatch")return L.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var p,y,S;return{targetTrackType:(y=(p=this.getTrackCollection().findById(t))==null?void 0:p.getTrackType)==null?void 0:y.call(p),clipType:(S=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:S.clip.type}}),!1;if(s.status!=="ready")return!1;const{sourceTrackId:r,targetTrackId:o}=s,l=i?{...i}:{...s.clip},h=n?{...n}:{...s.clip},c=this.cloneTrackSnapshot(r),d=this.cloneTrackSnapshot(o),u=$l({command:{...s,clip:h},trackCollection:this.getTrackCollection()}),f=this.getClips().find(p=>p.id===e)??null;return gl({applied:u,clipId:e,sourceTrackId:r,targetTrackId:o,clipBefore:l,clipAfter:f??l,sourceTrackSnapshot:c,targetTrackSnapshot:d,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>Kl({notifySelectionChange:this.notifySelectionChange.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),batchDraw:()=>{var p;(p=this.stage)==null||p.batchDraw()},syncPreviewSession:this.syncPreviewSession.bind(this)})})?(this.clearAllTrackDropPreviews(),!0):!1}getTrackTotalDuration(){return Dn(this.getClips())}destroy(){var e,t,i,n,s,r,o,l,h,c,d;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPreviewBufferingSuspendTimeout(),this.clearPendingPreviewState(),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(e=this.layout)==null||e.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(n=(t=this.layout)==null?void 0:(i=t.bodyCanvasHost).removeEventListener)==null||n.call(i,"click",this.bodyCanvasHostClickListener),(r=(s=this.rootContainer)==null?void 0:s.removeEventListener)==null||r.call(s,"wheel",this.rootWheelListener),(o=this.horizontalScrollbar)==null||o.destroy(),(l=this.verticalScrollbar)==null||l.destroy(),(h=this.playhead)==null||h.destroy(),(c=this.timeline)==null||c.destroy(),(d=this.stage)==null||d.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(e){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return e()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(e){const t=this.getClips(),i=new Map(t.map(r=>[r.id,r])),n=new Set,s=t.filter(r=>r.externalId===e).map(r=>r.id);for(let r=0;r<s.length;r+=1){const o=s[r];if(n.has(o))continue;n.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!n.has(l.separatedAudioClipId)&&s.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!n.has(l.separatedFromVideoClipId)&&s.push(l.separatedFromVideoClipId))}return t.filter(r=>n.has(r.id)).map(r=>r.id)}shouldClearSelectionForClipIds(e){return this.selectedClipId&&e.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(t=>e.has(t))}resolveSelectedClipAtTime(e){var i;const t=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const n of t){const s=this.getTimelineCommands().findClipById(this.tracks,n),r=s==null?void 0:s.clip;if(r&&e>=r.startTime&&e<r.endTime)return s}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{if(e.isFinal){const i=this.finalizeMultiDragCrossTrack(t,e);return i||this.syncMultiDragPeerClips(t,e,!0),i}return this.syncMultiDragOverlayState(t,e.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(t,e,!1),e.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(t,e.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(t,e)}finally{e.isFinal&&(this.syncMultiDragOverlayState(t,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((e,t)=>{var i;(i=e.setTrackStackOrder)==null||i.call(e,t)})}elevateMultiDragTrackGroups(e,t){var o,l,h;const i=this.resolveMultiDragSessionTrackIds(e);if(i.length<=1)return;const n=i.indexOf(t);n>=0&&(i.splice(n,1),i.push(t));const s=new Set(i);let r=0;for(const c of this.tracks){const d=(o=c.getId)==null?void 0:o.call(c);!d||s.has(d)||(l=c.setTrackStackOrder)==null||l.call(c,r++)}for(const c of i){const d=this.getTrackCollection().findById(c);(h=d==null?void 0:d.setTrackStackOrder)==null||h.call(d,r++)}}resolveMultiDragSessionTrackIds(e){var i;const t=new Set;for(const n of this.tracks){const s=(i=n.getId)==null?void 0:i.call(n);if(!s)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===s})&&t.add(s)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const n of e.selectedClipIds){const s=e.clips.get(n);if(!s)continue;const r=i.get(s.trackId);r?r.push(n):i.set(s.trackId,[n])}i.forEach((n,s)=>{var o;const r=this.getTrackCollection().findById(s);(o=r==null?void 0:r.setClipsDragOverlayActive)==null||o.call(r,n,t)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDragOverlay)==null?void 0:t.call(e)})}ensureMultiDragSession(e){var n;const t=this.selectionStore.getSelectedClipIds();if(t.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===e.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,t))return this.multiDragSession;const i=new Map;for(const s of t){const r=this.findTrackByClipId(s),o=((n=r==null?void 0:r.getId)==null?void 0:n.call(r))??this.resolveTrackIdByClipId(s),l=r==null?void 0:r.getClips().find(c=>c.id===s);if(!o||!l)continue;const h=s===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(s,{clipId:s,trackId:o,clip:h})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:e.draggedClipId,selectedClipIds:t.slice(),clips:i},this.multiDragSession)}haveSameClipIds(e,t){if(e.length!==t.length)return!1;const i=new Set(t);return e.every(n=>i.has(n))}restoreDraggedClipSnapshot(e,t){const i=Math.max(0,e.startTime-t);return{...e,startTime:i,endTime:i+e.duration}}syncMultiDragPeerClips(e,t,i){for(const n of e.selectedClipIds){if(n===t.draggedClipId)continue;const s=e.clips.get(n);if(!s||s.trackId===t.currentTrackId)continue;const r=this.getTrackCollection().findById(s.trackId);if(!(r!=null&&r.updateClipPosition))continue;const o=Math.max(0,s.clip.startTime+t.deltaTime);r.updateClipPosition(n,o,i,i?0:t.crossTrackOffsetY)}}previewMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const n=this.buildMovedClipSnapshot(i.clip,t.deltaTime),s=this.resolveCrossTrackPreviewDestination(n,t.targetTrackY,i.trackId);if(s.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(s.trackType,s.insertionPlacement,s.referenceTrackId),!0;if(s.status!=="existing_track"||s.targetTrackId===i.trackId)return!1;const r=this.resolveTrackIndexDelta(i.trackId,s.targetTrackId,i.clip.type);if(r===null)return!1;const o=new Map;this.appendPreviewClip(o,s.targetTrackId,n);for(const l of e.selectedClipIds){if(l===t.draggedClipId)continue;const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(h,r,c);!d||d===h.trackId||this.appendPreviewClip(o,d,c)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const n=this.buildMovedClipSnapshot(i.clip,t.deltaTime),s=this.resolveCrossTrackMoveDestination(n,t.targetTrackY,i.trackId);if(s.status==="blocked"||s.status==="same_track")return!1;const r=s.targetTrackId;if(!r)return!1;const o=this.resolveTrackIndexDelta(i.trackId,r,i.clip.type);if(o===null)return!1;for(const l of e.selectedClipIds){const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=c.startTime,u=l===t.draggedClipId?r:this.resolveMultiDragTargetTrackId(h,o,c);if(u){if(u===h.trackId){this.updateClipPositionWithHistory(h.trackId,h.clipId,d);continue}this.updateClipPositionSilently(h.trackId,h.clipId,d),this.moveClipToTrackWithHistorySnapshot(h.clipId,u,h.clip,c)}}return!0}resolveTrackIndexDelta(e,t,i){const n=this.getTrackIdsByType(i),s=n.indexOf(e),r=n.indexOf(t);return s===-1||r===-1?null:r-s}resolveMultiDragTargetTrackId(e,t,i){const n=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!n)return e.trackId;const s=this.calculateTrackY(n)+1,r=this.resolveCrossTrackMoveDestination(i,s,e.trackId);return r.status==="blocked"?n:r.targetTrackId}resolveMultiDragPreviewTargetTrackId(e,t,i){const n=this.findTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!n)return null;const s=this.calculateTrackY(n)+1,r=this.resolveCrossTrackPreviewDestination(i,s,e.trackId);return r.status==="existing_track"?r.targetTrackId:null}buildMovedClipSnapshot(e,t){const i=Math.max(0,e.startTime+t);return{...e,startTime:i,endTime:i+e.duration}}appendPreviewClip(e,t,i){const n=e.get(t);if(n){n.push(i);return}e.set(t,[i])}resolveCrossTrackMoveDestination(e,t,i){const n=this.trackManager.getTracks(),s=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),n,this.tracks);if(s.status==="missing_target_track_by_position")return L.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(s.status==="same_track")return{status:"same_track",targetTrackId:s.targetTrackId};if(s.status==="missing_target_track_view")return L.warn("TimelineManager","目标轨道不存在",{targetTrackId:s.targetTrackId}),{status:"blocked"};if(s.status==="track_type_mismatch")return L.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:s.targetTrackType,clipType:e.type})),{status:"blocked"};if(s.status==="move_to_track")return{status:"move_to_track",targetTrackId:s.targetTrackId};L.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const r=this.createTrack(s.trackType,void 0,s.insertionPlacement,s.referenceTrackId);return r?{status:"move_to_track",targetTrackId:r}:{status:"blocked"}}resolveCrossTrackPreviewDestination(e,t,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const n=this.trackManager.getTracks();if(!Array.isArray(n)||n.length===0)return{status:"clear"};const s=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),n,this.tracks);return s.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:s.targetTrackId}:s.status==="new_track_insertion"?{status:"new_track_insertion",trackType:s.trackType,insertionPlacement:s.insertionPlacement,referenceTrackId:s.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(e,t,i){let n=this.getTrackIdsByType(t);const s=n.indexOf(e);if(s===-1)return null;let r=s+i;for(;r<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;n=this.getTrackIdsByType(t),r+=1}for(;r>=n.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;n=this.getTrackIdsByType(t)}return n[r]??null}findTrackIdByRelativeIndex(e,t,i){const n=this.getTrackIdsByType(t),s=n.indexOf(e);if(s===-1)return null;const r=s+i;return r<0||r>=n.length?null:n[r]??null}getTrackIdsByType(e){return this.trackManager.getTracks().filter(t=>t.type===e).map(t=>t.id)}updateClipPositionWithHistory(e,t,i){var s;const n=this.getTrackCollection().findById(e);(s=n==null?void 0:n.updateClipPosition)==null||s.call(n,t,i,!0)}updateClipPositionSilently(e,t,i){const n=this.getTrackCollection().findById(e);if(!(n!=null&&n.updateClipPosition))return;const s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{n.updateClipPosition(t,i,!0)}finally{this.isExecutingHistoryAction=s}}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new X.Rect({fill:"rgba(80, 130, 230, 0.15)",stroke:"#5082e6",strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(t=this.selectionBoxLayer)==null||t.add(e),this.selectionBoxRect=e,e}showSelectionBoxRect(e,t,i,n){var r;const s=this.ensureSelectionBoxRect();s.x(e),s.y(t),s.width(Math.max(i,1)),s.height(Math.max(n,1)),s.visible(!0),(r=this.selectionBoxLayer)==null||r.batchDraw()}hideSelectionBoxRect(){var e;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(e=this.selectionBoxLayer)==null||e.batchDraw())}handleStageMouseDown(e){if(e.button!==0)return;const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top;if(this.isPointOnClip(s,r))return;this.isBoxSelecting=!1,this.boxSelectStartX=s,this.boxSelectStartY=r;const l=c=>{this.handleBoxSelectMove(c)},h=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",h)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",h)}handleBoxSelectMove(e){const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top,o=Math.abs(s-this.boxSelectStartX),l=Math.abs(r-this.boxSelectStartY);if(!this.isBoxSelecting&&(o>4||l>4)&&(this.isBoxSelecting=!0),!this.isBoxSelecting)return;const h=Math.min(this.boxSelectStartX,s),c=Math.min(this.boxSelectStartY,r),d=Math.abs(s-this.boxSelectStartX),u=Math.abs(r-this.boxSelectStartY);this.showSelectionBoxRect(h,c,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const e=this.selectionBoxRect;if(e){const t={x:e.x(),y:e.y(),width:e.width(),height:e.height()},i=this.getClipsIntersectingBox(t);this.setSelection(i,{preferredPrimaryClipId:this.selectedClipId})}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(e,t){for(const i of this.tracks){const n=i.getTrackGroup(),s=n.y(),r=n.height()||64;if(!(t<s||t>s+r))for(const o of i.getClips()){const l=ce(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=N.timeToPixels(o.duration,this.getZoomState());if(e>=l&&e<=l+h&&t>=s+2&&t<=s+r-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const n=i.getTrackGroup(),s=n.y(),r=n.height()||64;for(const o of i.getClips()){const l=ce(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=N.timeToPixels(o.duration,this.getZoomState()),c=s+2,d=r-4,u=l+h,f=c+d,p=e.x+e.width,y=e.y+e.height;l<p&&u>e.x&&c<y&&f>e.y&&t.push(o.id)}}return t}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Me({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(n=>n.id===e);return t?{...t,clips:t.clips.map(n=>({...n}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const n=this.resolveTrackInsertionFromRestoreAnchor(t);if(n){const u=this.createTrack(e.type,e.name,n.insertionPlacement,n.referenceTrackId);return this.muteTrack(u,e.isMuted??!1),u}const s=[...this.getTracks()].sort((u,f)=>u.order-f.order),r=s.find(u=>u.order>=e.order),o=r?s[s.findIndex(u=>u.id===r.id)-1]??null:s[s.length-1]??null;let l,h;r?(l="before_track",h=r.id):o&&(l="after_track",h=o.id);const c=this.createTrack(e.type,e.name,l,h);return this.muteTrack(c,e.isMuted??!1),c}getTrackRestoreAnchor(e){var n,s,r;if(!((n=this.trackManager)!=null&&n.getTracks))return null;const t=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=t.findIndex(o=>o.id===e);return i===-1?null:{previousTrackId:((s=t[i-1])==null?void 0:s.id)??null,nextTrackId:((r=t[i+1])==null?void 0:r.id)??null}}resolveTrackInsertionFromRestoreAnchor(e){return e?e.previousTrackId&&this.getTrackCollection().findById(e.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:e.previousTrackId}:e.nextTrackId&&this.getTrackCollection().findById(e.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:e.nextTrackId}:null:null}resolveTrackIdByClipId(e){var t;return((t=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:t.trackId)??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var r;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastEffectiveTrackDuration,n=Gl(e),s=Dn(e);if(n!==t){this.lastTrackDuration=n;const o=On(n);this.setDurationState(o),(r=this.timeline)==null||r.setDuration(o),this.updateViewportLayout()}s!==i&&(this.lastEffectiveTrackDuration=s,this.emitEvent("track_duration_change",{duration:s})),!(n===t&&s===i)&&L.debugLazy("TimelineManager",()=>`Track duration changed: effective=${s}ms, extent=${n}ms, timeline=${On(n)}ms`)}resolveSelectedClipSnapshot(){return Yl({getPrimarySelectedClip:()=>{var e;return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null},findFallbackSelectedClip:()=>this.tracks?this.getTimelinePresentationAdapter().findSelectedClip(this.getTrackCollection()):null})}commitPreviewVisualTransform(e,t){const i=this.getClips().find(r=>r.id===e);if(!i||i.type!=="video")return;const n=fe(i.visualTransform),s=fe(t);Bs(n,s)||this.updateClip(e,{visualTransform:s})}clearAllTracksAndClips(){var t,i,n,s;const e=this.getTracks();for(const r of e){const o=this.getTrackCollection().findById(r.id);if(o){const l=[...o.getClips()];for(const h of l)(t=o.removeClip)==null||t.call(o,h.id)}}for(const r of e){const o=r.id,l=this.getTrackCollection().findById(o);(n=(i=l==null?void 0:l.getTrackGroup)==null?void 0:i.call(l))==null||n.destroy(),this.getTrackCollection().removeById(o)}this.trackManager.clearAllTracks(),this.updateAllTrackPositions(),(s=this.stage)==null||s.batchDraw()}}exports.CLIP_LAYER=Us;exports.Clip=jt;exports.ClipConfigPanel=Os;exports.DEFAULT_CLIP_VIEW_STATE=Yn;exports.DEFAULT_PREVIEW_ASPECT_RATIO=be;exports.HistoryManager=Li;exports.MIN_CLIP_LINE_WIDTH=It;exports.PREVIEW_ASPECT_RATIO_PRESETS=Xs;exports.Playhead=il;exports.TIMELINE_LEFT_PADDING=le;exports.TIME_SCALE=$s;exports.TRACK_HEIGHT=_e;exports.TimeUtils=N;exports.Timeline=jo;exports.TimelineManager=dh;exports.Track=ti;exports.TrackInfoPanel=Ds;exports.TrackManager=Ns;exports.ZOOM_ANIMATION=Xn;exports.ZOOM_PRESETS=de;exports.createClipViewState=Un;exports.createClipWithViewState=Oi;exports.defaultDarkTheme=Jt;exports.isAutoPreviewAspectRatioMode=st;exports.normalizePreviewAspectRatio=De;exports.normalizePreviewAspectRatioMode=Di;exports.resolveTheme=xt;