@linker-design-plus/timeline-track 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/components/timeline/ManagedPlayhead.d.ts +27 -3
- package/dist/components/track/Track.d.ts +25 -1
- package/dist/components/track/trackInteractionState.d.ts +37 -1
- package/dist/core/controllers/timelineTrackMutationController.d.ts +1 -0
- package/dist/core/facade/timelineManager.d.ts +71 -0
- package/dist/core/history/history.d.ts +3 -1
- package/dist/core/history/timelineHistoryExecutor.d.ts +7 -2
- package/dist/core/history/timelineHistoryRecorder.d.ts +6 -2
- package/dist/core/models/types.d.ts +24 -3
- package/dist/core/presentation/timelinePresentationAdapter.d.ts +1 -1
- package/dist/core/stores/selectionStore.d.ts +8 -1
- package/dist/core/tracks/index.d.ts +1 -0
- package/dist/core/tracks/timelineTrackBridge.d.ts +14 -1
- package/dist/core/tracks/timelineTrackCollection.d.ts +8 -0
- package/dist/index.cjs.js +4 -4
- package/dist/index.es.js +5189 -4001
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
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.
|
|
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
|
-
`,Oi=()=>{if(typeof document>"u")throw new Error(Gs)};class ht{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 ht(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),n=this.m[0]*e+this.m[2]*i,s=this.m[1]*e+this.m[3]*i,a=this.m[0]*-i+this.m[2]*e,o=this.m[1]*-i+this.m[3]*e;return this.m[0]=n,this.m[1]=s,this.m[2]=a,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,n=this.m[1]+this.m[3]*e,s=this.m[2]+this.m[0]*t,a=this.m[3]+this.m[1]*t;return this.m[0]=i,this.m[1]=n,this.m[2]=s,this.m[3]=a,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],n=this.m[0]*t.m[2]+this.m[2]*t.m[3],s=this.m[1]*t.m[2]+this.m[3]*t.m[3],a=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]=n,this.m[3]=s,this.m[4]=a,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,n=-this.m[2]*t,s=this.m[0]*t,a=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]=n,this.m[3]=s,this.m[4]=a,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],e=this.m[1],i=this.m[2],n=this.m[3],s=this.m[4],a=this.m[5],o=t*n-e*i,l={x:s,y:a,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*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=(t*i+e*n)/o}return l.rotation=C._getRotation(l.rotation),l}}const Os="[object Array]",Bs="[object Number]",Hs="[object String]",zs="[object Boolean]",Ns=Math.PI/180,Fs=180/Math.PI,ee="#",Vs="",Ws="0",Ys="Konva warning: ",Bi="Konva error: ",Xs="rgb(",Ze={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]},Us=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let xe=[],ie=null;const $s=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(r){setTimeout(r,16)},C={_isElement(r){return!!(r&&r.nodeType==1)},_isFunction(r){return!!(r&&r.constructor&&r.call&&r.apply)},_isPlainObject(r){return!!r&&r.constructor===Object},_isArray(r){return Object.prototype.toString.call(r)===Os},_isNumber(r){return Object.prototype.toString.call(r)===Bs&&!isNaN(r)&&isFinite(r)},_isString(r){return Object.prototype.toString.call(r)===Hs},_isBoolean(r){return Object.prototype.toString.call(r)===zs},isObject(r){return r instanceof Object},isValidSelector(r){if(typeof r!="string")return!1;const t=r[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(r){return r===0||r>0?1:-1},requestAnimFrame(r){xe.push(r),xe.length===1&&$s(function(){const t=xe;xe=[],t.forEach(function(e){e()})})},createCanvasElement(){Oi();const r=document.createElement("canvas");try{r.style=r.style||{}}catch{}return r},createImageElement(){return Oi(),document.createElement("img")},_isInDocument(r){for(;r=r.parentNode;)if(r==document)return!0;return!1},_urlToImage(r,t){const e=C.createImageElement();e.onload=function(){t(e)},e.src=r},_rgbToHex(r,t,e){return((1<<24)+(r<<16)+(t<<8)+e).toString(16).slice(1)},_hexToRgb(r){r=r.replace(ee,Vs);const t=parseInt(r,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let r=(Math.random()*16777215<<0).toString(16);for(;r.length<6;)r=Ws+r;return ee+r},isCanvasFarblingActive(){if(ie!==null)return ie;if(typeof document>"u")return ie=!1,!1;const r=this.createCanvasElement();r.width=10,r.height=10;const t=r.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 n=0;n<100;n++)if(e[n*4]!==40||e[n*4+1]!==40||e[n*4+2]!==40||e[n*4+3]!==255){i=!0;break}return ie=i,this.releaseCanvas(r),ie},getHitColor(){const r=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(r):r},getHitColorKey(r,t,e){return this.isCanvasFarblingActive()&&(r=Math.round(r/5)*5,t=Math.round(t/5)*5,e=Math.round(e/5)*5),ee+this._rgbToHex(r,t,e)},getSnappedHexColor(r){const t=this._hexToRgb(r);return ee+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(r){let t;return r in Ze?(t=Ze[r],{r:t[0],g:t[1],b:t[2]}):r[0]===ee?this._hexToRgb(r.substring(1)):r.substr(0,4)===Xs?(t=Us.exec(r.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(r){return r=r||"black",C._namedColorToRBA(r)||C._hex3ColorToRGBA(r)||C._hex4ColorToRGBA(r)||C._hex6ColorToRGBA(r)||C._hex8ColorToRGBA(r)||C._rgbColorToRGBA(r)||C._rgbaColorToRGBA(r)||C._hslColorToRGBA(r)},_namedColorToRBA(r){const t=Ze[r.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(r){if(r.indexOf("rgb(")===0){r=r.match(/rgb\(([^)]+)\)/)[1];const t=r.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(r){if(r.indexOf("rgba(")===0){r=r.match(/rgba\(([^)]+)\)/)[1];const t=r.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(r){if(r[0]==="#"&&r.length===9)return{r:parseInt(r.slice(1,3),16),g:parseInt(r.slice(3,5),16),b:parseInt(r.slice(5,7),16),a:parseInt(r.slice(7,9),16)/255}},_hex6ColorToRGBA(r){if(r[0]==="#"&&r.length===7)return{r:parseInt(r.slice(1,3),16),g:parseInt(r.slice(3,5),16),b:parseInt(r.slice(5,7),16),a:1}},_hex4ColorToRGBA(r){if(r[0]==="#"&&r.length===5)return{r:parseInt(r[1]+r[1],16),g:parseInt(r[2]+r[2],16),b:parseInt(r[3]+r[3],16),a:parseInt(r[4]+r[4],16)/255}},_hex3ColorToRGBA(r){if(r[0]==="#"&&r.length===4)return{r:parseInt(r[1]+r[1],16),g:parseInt(r[2]+r[2],16),b:parseInt(r[3]+r[3],16),a:1}},_hslColorToRGBA(r){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(r)){const[t,...e]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(r),i=Number(e[0])/360,n=Number(e[1])/100,s=Number(e[2])/100;let a,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?a=s*(1+n):a=s+n-s*n;const h=2*s-a,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+(a-h)*6*o:2*o<1?l=a:3*o<2?l=h+(a-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(r,t){return!(t.x>r.x+r.width||t.x+t.width<r.x||t.y>r.y+r.height||t.y+t.height<r.y)},cloneObject(r){const t={};for(const e in r)this._isPlainObject(r[e])?t[e]=this.cloneObject(r[e]):this._isArray(r[e])?t[e]=this.cloneArray(r[e]):t[e]=r[e];return t},cloneArray(r){return r.slice(0)},degToRad(r){return r*Ns},radToDeg(r){return r*Fs},_degToRad(r){return C.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),C.degToRad(r)},_radToDeg(r){return C.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),C.radToDeg(r)},_getRotation(r){return E.angleDeg?C.radToDeg(r):r},_capitalize(r){return r.charAt(0).toUpperCase()+r.slice(1)},throw(r){throw new Error(Bi+r)},error(r){console.error(Bi+r)},warn(r){E.showWarnings&&console.warn(Ys+r)},each(r,t){for(const e in r)t(e,r[e])},_inRange(r,t,e){return t<=r&&r<e},_getProjectionToSegment(r,t,e,i,n,s){let a,o,l;const h=(r-e)*(r-e)+(t-i)*(t-i);if(h==0)a=r,o=t,l=(n-e)*(n-e)+(s-i)*(s-i);else{const c=((n-r)*(e-r)+(s-t)*(i-t))/h;c<0?(a=r,o=t,l=(r-n)*(r-n)+(t-s)*(t-s)):c>1?(a=e,o=i,l=(e-n)*(e-n)+(i-s)*(i-s)):(a=r+c*(e-r),o=t+c*(i-t),l=(a-n)*(a-n)+(o-s)*(o-s))}return[a,o,l]},_getProjectionToLine(r,t,e){const i=C.cloneObject(r);let n=Number.MAX_VALUE;return t.forEach(function(s,a){if(!e&&a===t.length-1)return;const o=t[(a+1)%t.length],l=C._getProjectionToSegment(s.x,s.y,o.x,o.y,r.x,r.y),h=l[0],c=l[1],d=l[2];d<n&&(i.x=h,i.y=c,n=d)}),i},_prepareArrayForTween(r,t,e){const i=[],n=[];if(r.length>t.length){const a=t;t=r,r=a}for(let a=0;a<r.length;a+=2)i.push({x:r[a],y:r[a+1]});for(let a=0;a<t.length;a+=2)n.push({x:t[a],y:t[a+1]});const s=[];return n.forEach(function(a){const o=C._getProjectionToLine(a,i,e);s.push(o.x),s.push(o.y)}),s},_prepareToStringify(r){let t;r.visitedByCircularReferenceRemoval=!0;for(const e in r)if(r.hasOwnProperty(e)&&r[e]&&typeof r[e]=="object"){if(t=Object.getOwnPropertyDescriptor(r,e),r[e].visitedByCircularReferenceRemoval||C._isElement(r[e]))if(t.configurable)delete r[e];else return null;else if(C._prepareToStringify(r[e])===null)if(t.configurable)delete r[e];else return null}return delete r.visitedByCircularReferenceRemoval,r},_assign(r,t){for(const e in t)r[e]=t[e];return r},_getFirstPointerId(r){return r.touches?r.changedTouches[0].identifier:r.pointerId||999},releaseCanvas(...r){E.releaseCanvasOnDestroy&&r.forEach(t=>{t.width=0,t.height=0})},drawRoundedRectPath(r,t,e,i){let n=t<0?t:0,s=e<0?e:0;t=Math.abs(t),e=Math.abs(e);let a=0,o=0,l=0,h=0;typeof i=="number"?a=o=l=h=Math.min(i,t/2,e/2):(a=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)),r.moveTo(n+a,s),r.lineTo(n+t-o,s),r.arc(n+t-o,s+o,o,Math.PI*3/2,0,!1),r.lineTo(n+t,s+e-h),r.arc(n+t-h,s+e-h,h,0,Math.PI/2,!1),r.lineTo(n+l,s+e),r.arc(n+l,s+e-l,l,Math.PI/2,Math.PI,!1),r.lineTo(n,s+a),r.arc(n+a,s+a,a,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(r,t,e,i,n){i=Math.abs(i);for(let s=0;s<e;s++){const a=t[(s-1+e)%e],o=t[s],l=t[(s+1)%e],h={x:o.x-a.x,y:o.y-a.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 n=="number"?p=n:p=s<n.length?n[s]: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};s===0?r.moveTo(S.x,S.y):r.lineTo(S.x,S.y),r.arcTo(o.x,o.y,v.x,v.y,p)}}};function qs(r){const t=[],e=r.length,i=C;for(let n=0;n<e;n++){let s=r[n];i._isNumber(s)?s=Math.round(s*1e3)/1e3:i._isString(s)||(s=s+""),t.push(s)}return t}const Hi=",",Ks="(",js=")",Zs="([",Js="])",Qs=";",tr="()",er="=",zi=["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"],ir=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],nr=100;let Ee=null;function Ni(){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,n=i.length,s="",a,o,l,h;for(a=0;a<n;a++)o=i[a],l=o.method,l?(h=o.args,s+=l,t?s+=tr:C._isArray(h[0])?s+=Zs+h.join(Hi)+Js:(e&&(h=h.map(c=>typeof c=="number"?Math.floor(c):c)),s+=Ks+h.join(Hi)+js)):(s+=o.property,t||(s+=er+o.val)),s+=Qs;return s}clearTrace(){this.traceArr=[]}_trace(t){let e=this.traceArr,i;e.push(t),i=e.length,i>=nr&&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,n,s,a){this._context.arc(t,e,i,n,s,a)}arcTo(t,e,i,n,s){this._context.arcTo(t,e,i,n,s)}beginPath(){this._context.beginPath()}bezierCurveTo(t,e,i,n,s,a){this._context.bezierCurveTo(t,e,i,n,s,a)}clearRect(t,e,i,n){this._context.clearRect(t,e,i,n)}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,n){return this._context.createLinearGradient(t,e,i,n)}createPattern(t,e){return this._context.createPattern(t,e)}createRadialGradient(t,e,i,n,s,a){return this._context.createRadialGradient(t,e,i,n,s,a)}drawImage(t,e,i,n,s,a,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,n,s):c.length===9&&d.drawImage(t,e,i,n,s,a,o,l,h)}ellipse(t,e,i,n,s,a,o,l){this._context.ellipse(t,e,i,n,s,a,o,l)}isPointInPath(t,e,i,n){return i?this._context.isPointInPath(i,t,e,n):this._context.isPointInPath(t,e,n)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,e,i,n){this._context.fillRect(t,e,i,n)}strokeRect(t,e,i,n){this._context.strokeRect(t,e,i,n)}fillText(t,e,i,n){n?this._context.fillText(t,e,i,n):this._context.fillText(t,e,i)}measureText(t){return this._context.measureText(t)}getImageData(t,e,i,n){return this._context.getImageData(t,e,i,n)}lineTo(t,e){this._context.lineTo(t,e)}moveTo(t,e){this._context.moveTo(t,e)}rect(t,e,i,n){this._context.rect(t,e,i,n)}roundRect(t,e,i,n,s){this._context.roundRect(t,e,i,n,s)}putImageData(t,e,i){this._context.putImageData(t,e,i)}quadraticCurveTo(t,e,i,n){this._context.quadraticCurveTo(t,e,i,n)}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,n,s,a){this._context.setTransform(t,e,i,n,s,a)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,e,i,n){this._context.strokeText(t,e,i,n)}transform(t,e,i,n,s,a){this._context.transform(t,e,i,n,s,a)}translate(t,e){this._context.translate(t,e)}_enableTrace(){let t=this,e=zi.length,i=this.setAttr,n,s;const a=function(o){let l=t[o],h;t[o]=function(){return s=qs(Array.prototype.slice.call(arguments,0)),h=l.apply(t,arguments),t._trace({method:o,args:s}),h}};for(n=0;n<e;n++)a(zi[n]);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)}}ir.forEach(function(r){Object.defineProperty(qe.prototype,r,{get(){return this._context[r]},set(t){this._context[r]=t}})});class sr 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 n=t.getFillPatternImage();if(n&&i==="pattern"){this._fillPattern(t);return}const s=t.getFillLinearGradientColorStops();if(s&&i==="linear-gradient"){this._fillLinearGradient(t);return}const a=t.getFillRadialGradientColorStops();if(a&&i==="radial-gradient"){this._fillRadialGradient(t);return}e?this._fillColor(t):n?this._fillPattern(t):s?this._fillLinearGradient(t):a&&this._fillRadialGradient(t)}_strokeLinearGradient(t){const e=t.getStrokeLinearGradientStartPoint(),i=t.getStrokeLinearGradientEndPoint(),n=t.getStrokeLinearGradientColorStops(),s=this.createLinearGradient(e.x,e.y,i.x,i.y);if(n){for(let a=0;a<n.length;a+=2)s.addColorStop(n[a],n[a+1]);this.setAttr("strokeStyle",s)}}_stroke(t){const e=t.dash(),i=t.getStrokeScaleEnabled();if(t.hasStroke()){if(!i){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,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,n;const s=(e=t.getShadowRGBA())!==null&&e!==void 0?e:"black",a=(i=t.getShadowBlur())!==null&&i!==void 0?i:5,o=(n=t.getShadowOffset())!==null&&n!==void 0?n:{x:0,y:0},l=t.getAbsoluteScale(),h=this.canvas.getPixelRatio(),c=l.x*h,d=l.y*h;this.setAttr("shadowColor",s),this.setAttr("shadowBlur",a*Math.min(Math.abs(c),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*c),this.setAttr("shadowOffsetY",o.y*d)}}class rr 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 s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(t);const i=t.hitStrokeWidth(),n=i==="auto"?t.strokeWidth():i;this.setAttr("lineWidth",n),this.setAttr("strokeStyle",t.colorKey),t._strokeFuncHit(this),e||this.restore()}}}let Ae;function ar(){if(Ae)return Ae;const r=C.createCanvasElement(),t=r.getContext("2d");return Ae=function(){const e=E._global.devicePixelRatio||1,i=t.webkitBackingStorePixelRatio||t.mozBackingStorePixelRatio||t.msBackingStorePixelRatio||t.oBackingStorePixelRatio||t.backingStorePixelRatio||1;return e/i}(),C.releaseCanvas(r),Ae}class Ei{constructor(t){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(t||{}).pixelRatio||E.pixelRatio||ar();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(n){return C.error("Unable to get data URL. "+n.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class Lt extends Ei{constructor(t={width:0,height:0,willReadFrequently:!1}){super(t),this.context=new sr(this,{willReadFrequently:t.willReadFrequently}),this.setSize(t.width,t.height)}}class Ai extends Ei{constructor(t={width:0,height:0}){super(t),this.hitCanvas=!0,this.context=new rr(this),this.setSize(t.width,t.height)}}const Y={get isDragging(){let r=!1;return Y._dragElements.forEach(t=>{t.dragStatus==="dragging"&&(r=!0)}),r},justDragged:!1,get node(){let r;return Y._dragElements.forEach(t=>{r=t.node}),r},_dragElements:new Map,_drag(r){const t=[];Y._dragElements.forEach((e,i)=>{const{node:n}=e,s=n.getStage();s.setPointersPositions(r),e.pointerId===void 0&&(e.pointerId=C._getFirstPointerId(r));const a=s._changedPointerPositions.find(o=>o.id===e.pointerId);if(a){if(e.dragStatus!=="dragging"){const o=n.dragDistance();if(Math.max(Math.abs(a.x-e.startPointerPos.x),Math.abs(a.y-e.startPointerPos.y))<o||(n.startDrag({evt:r}),!n.isDragging()))return}n._setDragPosition(r,e),t.push(n)}}),t.forEach(e=>{e.fire("dragmove",{type:"dragmove",target:e,evt:r},!0)})},_endDragBefore(r){const t=[];Y._dragElements.forEach(e=>{const{node:i}=e,n=i.getStage();if(r&&n.setPointersPositions(r),!n._changedPointerPositions.find(o=>o.id===e.pointerId))return;(e.dragStatus==="dragging"||e.dragStatus==="stopped")&&(Y.justDragged=!0,E._mouseListenClick=!1,E._touchListenClick=!1,E._pointerListenClick=!1,e.dragStatus="stopped");const a=e.node.getLayer()||e.node instanceof E.Stage&&e.node;a&&t.indexOf(a)===-1&&t.push(a)}),t.forEach(e=>{e.draw()})},_endDragAfter(r){Y._dragElements.forEach((t,e)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:r},!0),t.dragStatus!=="dragging"&&Y._dragElements.delete(e)})}};E.isBrowser&&(window.addEventListener("mouseup",Y._endDragBefore,!0),window.addEventListener("touchend",Y._endDragBefore,!0),window.addEventListener("touchcancel",Y._endDragBefore,!0),window.addEventListener("mousemove",Y._drag),window.addEventListener("touchmove",Y._drag),window.addEventListener("mouseup",Y._endDragAfter,!1),window.addEventListener("touchend",Y._endDragAfter,!1),window.addEventListener("touchcancel",Y._endDragAfter,!1));function Rt(r){return C._isString(r)?'"'+r+'"':Object.prototype.toString.call(r)==="[object Number]"||C._isBoolean(r)?r:Object.prototype.toString.call(r)}function Gn(r){return r>255?255:r<0?0:Math.round(r)}function x(){if(E.isUnminified)return function(r,t){return C._isNumber(r)||C.warn(Rt(r)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),r}}function Ke(r){if(E.isUnminified)return function(t,e){let i=C._isNumber(t),n=C._isArray(t)&&t.length==r;return!i&&!n&&C.warn(Rt(t)+' is a not valid value for "'+e+'" attribute. The value should be a number or Array<number>('+r+")"),t}}function Li(){if(E.isUnminified)return function(r,t){return C._isNumber(r)||r==="auto"||C.warn(Rt(r)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),r}}function Vt(){if(E.isUnminified)return function(r,t){return C._isString(r)||C.warn(Rt(r)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),r}}function On(){if(E.isUnminified)return function(r,t){const e=C._isString(r),i=Object.prototype.toString.call(r)==="[object CanvasGradient]"||r&&r.addColorStop;return e||i||C.warn(Rt(r)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),r}}function or(){if(E.isUnminified)return function(r,t){const e=Int8Array?Object.getPrototypeOf(Int8Array):null;return e&&r instanceof e||(C._isArray(r)?r.forEach(function(i){C._isNumber(i)||C.warn('"'+t+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):C.warn(Rt(r)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),r}}function ft(){if(E.isUnminified)return function(r,t){return r===!0||r===!1||C.warn(Rt(r)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),r}}function lr(r){if(E.isUnminified)return function(t,e){return t==null||C.isObject(t)||C.warn(Rt(t)+' is a not valid value for "'+e+'" attribute. The value should be an object with properties '+r),t}}const ne="get",se="set",m={addGetterSetter(r,t,e,i,n){m.addGetter(r,t,e),m.addSetter(r,t,i,n),m.addOverloadedGetterSetter(r,t)},addGetter(r,t,e){const i=ne+C._capitalize(t);r.prototype[i]=r.prototype[i]||function(){const n=this.attrs[t];return n===void 0?e:n}},addSetter(r,t,e,i){const n=se+C._capitalize(t);r.prototype[n]||m.overWriteSetter(r,t,e,i)},overWriteSetter(r,t,e,i){const n=se+C._capitalize(t);r.prototype[n]=function(s){return e&&s!==void 0&&s!==null&&(s=e.call(this,s,t)),this._setAttr(t,s),i&&i.call(this),this}},addComponentsGetterSetter(r,t,e,i,n){const s=e.length,a=C._capitalize,o=ne+a(t),l=se+a(t);r.prototype[o]=function(){const c={};for(let d=0;d<s;d++){const u=e[d];c[u]=this.getAttr(t+a(u))}return c};const h=lr(e);r.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+a(u),c[u]);return c||e.forEach(u=>{this._setAttr(t+a(u),void 0)}),this._fireChangeEvent(t,d,c),n&&n.call(this),this},m.addOverloadedGetterSetter(r,t)},addOverloadedGetterSetter(r,t){const e=C._capitalize(t),i=se+e,n=ne+e;r.prototype[t]=function(){return arguments.length?(this[i](arguments[0]),this):this[n]()}},addDeprecatedGetterSetter(r,t,e,i){C.error("Adding deprecated "+t);const n=ne+C._capitalize(t),s=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";r.prototype[n]=function(){C.error(s);const a=this.attrs[t];return a===void 0?e:a},m.addSetter(r,t,i,function(){C.error(s)}),m.addOverloadedGetterSetter(r,t)},backCompat(r,t){C.each(t,function(e,i){const n=r.prototype[i],s=ne+C._capitalize(e),a=se+C._capitalize(e);function o(){n.apply(this,arguments),C.error('"'+e+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}r.prototype[e]=o,r.prototype[s]=o,r.prototype[a]=o})},afterSetFilter(){this._filterUpToDate=!1}};function hr(r){const t=/(\w+)\(([^)]+)\)/g;let e;for(;(e=t.exec(r))!==null;){const[,i,n]=e;switch(i){case"blur":{const s=parseFloat(n.replace("px",""));return function(a){this.blurRadius(s*.5);const o=E.Filters;o&&o.Blur&&o.Blur.call(this,a)}}case"brightness":{const s=n.includes("%")?parseFloat(n)/100:parseFloat(n);return function(a){this.brightness(s);const o=E.Filters;o&&o.Brightness&&o.Brightness.call(this,a)}}case"contrast":{const s=parseFloat(n);return function(a){const o=100*(Math.sqrt(s)-1);this.contrast(o);const l=E.Filters;l&&l.Contrast&&l.Contrast.call(this,a)}}case"grayscale":return function(s){const a=E.Filters;a&&a.Grayscale&&a.Grayscale.call(this,s)};case"sepia":return function(s){const a=E.Filters;a&&a.Sepia&&a.Sepia.call(this,s)};case"invert":return function(s){const a=E.Filters;a&&a.Invert&&a.Invert.call(this,s)};default:C.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Fe="absoluteOpacity",Fi="allEventListeners",vt="absoluteTransform",Vi="absoluteScale",Ot="canvas",cr="Change",dr="children",ur="konva",di="listening",fr="mouseenter",gr="mouseleave",pr="pointerenter",mr="pointerleave",yr="touchenter",Sr="touchleave",Wi="set",Yi="Shape",Ve=" ",Xi="stage",xt="transform",Cr="Stage",ui="visible",Tr=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Ve);let vr=1;class _{constructor(t){this._id=vr++,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===xt||t===vt)&&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===xt||t===vt)&&i.dirty===!0)&&(i=e.call(this),this._cache.set(t,i)),i}_calculate(t,e,i){if(!this._attachedDepsListeners.get(t)){const n=e.map(s=>s+"Change.konva").join(Ve);this.on(n,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,i)}_getCanvasCache(){return this._cache.get(Ot)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===vt&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(Ot)){const{scene:t,filter:e,hit:i}=this._cache.get(Ot);C.releaseCanvas(t._canvas,e._canvas,i._canvas),this._cache.delete(Ot)}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 n=Math.ceil(e.width||i.width),s=Math.ceil(e.height||i.height),a=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(!n||!s){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;n+=h*2+u,s+=h*2+p,o-=h,l-=h;const g=new Lt({pixelRatio:a,width:n,height:s}),y=new Lt({pixelRatio:a,width:0,height:0,willReadFrequently:!0}),T=new Ai({pixelRatio:d,width:n,height:s}),S=g.getContext(),v=T.getContext(),b=new Lt({width:g.width/g.pixelRatio+Math.abs(o),height:g.height/g.pixelRatio+Math.abs(l),pixelRatio:g.pixelRatio}),w=b.getContext();return T.isCache=!0,g.isCache=!0,this._cache.delete(Ot),this._filterUpToDate=!1,e.imageSmoothingEnabled===!1&&(g.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),S.save(),v.save(),w.save(),S.translate(-o,-l),v.translate(-o,-l),w.translate(-o,-l),b.x=o,b.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Fe),this._clearSelfAndDescendantCache(Vi),this.drawScene(g,this,b),this.drawHit(T,this),this._isUnderCache=!1,S.restore(),v.restore(),c&&(S.save(),S.beginPath(),S.rect(0,0,n,s),S.closePath(),S.setAttr("strokeStyle","red"),S.setAttr("lineWidth",5),S.stroke(),S.restore()),C.releaseCanvas(b._canvas),this._cache.set(Ot,{scene:g,filter:y,hit:T,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(Ot)}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 n=1/0,s=1/0,a=-1/0,o=-1/0;const l=this.getAbsoluteTransform(e);return i.forEach(function(h){const c=l.point(h);n===void 0&&(n=a=c.x,s=o=c.y),n=Math.min(n,c.x),s=Math.min(s,c.y),a=Math.max(a,c.x),o=Math.max(o,c.y)}),{x:n,y:s,width:a-n,height:o-s}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const e=this._getCanvasCache();t.translate(e.x,e.y);const i=this._getCachedSceneCanvas(),n=i.pixelRatio;t.drawImage(i._canvas,0,0,i.width/n,i.height/n),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,n=e.filter,s=n.getContext(),a,o,l,h;if(!t||t.length===0)return i;if(this._filterUpToDate)return n;let c=!0;for(let u=0;u<t.length;u++)if(typeof t[u]=="string"&&Ni(),typeof t[u]!="string"||!Ni()){c=!1;break}const d=i.pixelRatio;if(n.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),c){const u=t.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(a=t.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<a;l++)h=t[l],typeof h=="string"&&(h=hr(h)),h.call(this,o),s.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,n}on(t,e){if(this._cache&&this._cache.delete(Fi),arguments.length===3)return this._delegate.apply(this,arguments);const i=t.split(Ve);for(let n=0;n<i.length;n++){const a=i[n].split("."),o=a[0],l=a[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:e})}return this}off(t,e){let i=(t||"").split(Ve),n=i.length,s,a,o,l,h,c;if(this._cache&&this._cache.delete(Fi),!t)for(a in this.eventListeners)this._off(a);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,e);else for(a in this.eventListeners)this._off(a,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 n=this;this.on(t,function(s){const a=s.target.findAncestors(e,!0,n);for(let o=0;o<a.length;o++)s=C.cloneObject(s),s.currentTarget=a[o],i.call(a[o],s)})}remove(){return this.isDragging()&&this.stopDrag(),Y._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(vt),this._clearSelfAndDescendantCache(Fe),this._clearSelfAndDescendantCache(Vi),this._clearSelfAndDescendantCache(Xi),this._clearSelfAndDescendantCache(ui),this._clearSelfAndDescendantCache(di)}_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!==dr&&(i=Wi+C._capitalize(e),C._isFunction(this[i])?this[i](t[e]):this._setAttr(e,t[e]))}),this}isListening(){return this._getCache(di,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(ui,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 n=!1;Y._dragElements.forEach(a=>{a.dragStatus==="dragging"&&(a.node.nodeType==="Stage"||a.node.getLayer()===i)&&(n=!0)});const s=!e&&!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 t=this.getDepth(),e=this,i=0,n,s,a,o;function l(c){for(n=[],s=c.length,a=0;a<s;a++)o=c[a],i++,o.nodeType!==Yi&&(n=n.concat(o.getChildren().slice())),o._id===e._id&&(a=s);n.length>0&&n[0].getDepth()<=t&&l(n)}const h=this.getStage();return e.nodeType!==Cr&&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(xt),this._clearSelfAndDescendantCache(vt)),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 n=this.getAbsoluteTransform(t).getMatrix(),s=new ht,a=this.offset();return s.m=n.slice(),s.translate(a.x,a.y),s.getTranslation()}setAbsolutePosition(t){const{x:e,y:i,...n}=this._clearTransform();this.attrs.x=e,this.attrs.y=i,this._clearCache(xt);const s=this._getAbsoluteTransform().copy();return s.invert(),s.translate(t.x,t.y),t={x:this.attrs.x+s.getTranslation().x,y:this.attrs.y+s.getTranslation().y},this._setTransform(n),this.setPosition({x:t.x,y:t.y}),this._clearCache(xt),this._clearSelfAndDescendantCache(vt),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,n=this.x(),s=this.y();return e!==void 0&&(n+=e),i!==void 0&&(s+=i),this.setPosition({x:n,y:s}),this}_eachAncestorReverse(t,e){let i=[],n=this.getParent(),s,a;if(!(e&&e._id===this._id)){for(i.unshift(this);n&&(!e||n._id!==e._id);)i.unshift(n),n=n.parent;for(s=i.length,a=0;a<s;a++)t(i[a])}}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(Fe,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,n,s,a;const o={attrs:{},className:this.getClassName()};for(e in t)i=t[e],a=C.isObject(i)&&!C._isPlainObject(i)&&!C._isArray(i),!a&&(n=typeof this[e]=="function"&&this[e],delete t[e],s=n?n.call(this):null,t[e]=i,s!==i&&(o.attrs[e]=i));return C._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,e,i){const n=[];e&&this._isMatch(t)&&n.push(this);let s=this.parent;for(;s;){if(s===i)return n;s._isMatch(t)&&n.push(s),s=s.parent}return n}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,n,s;for(n=0;n<i;n++)if(s=e[n],C.isValidSelector(s)||(C.warn('Selector "'+s+'" 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?")),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 t=this.getParent();return t?t.getLayer():null}getStage(){return this._getCache(Xi,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(vt,this._getAbsoluteTransform)}_getAbsoluteTransform(t){let e;if(t)return e=new ht,this._eachAncestorReverse(function(i){const n=i.transformsEnabled();n==="all"?e.multiply(i.getTransform()):n==="position"&&e.translate(i.x()-i.offsetX(),i.y()-i.offsetY())},t),e;{e=this._cache.get(vt)||new ht,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 n=this.attrs.x||0,s=this.attrs.y||0,a=this.attrs.offsetX||0,o=this.attrs.offsetY||0;e.translate(n-a,s-o)}return e.dirty=!1,e}}getAbsoluteScale(t){let e=this;for(;e;)e._isUnderCache&&(t=e),e=e.getParent();const n=this.getAbsoluteTransform(t).decompose();return{x:n.scaleX,y:n.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(xt,this._getTransform)}_getTransform(){var t,e;const i=this._cache.get(xt)||new ht;i.reset();const n=this.x(),s=this.y(),a=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(n!==0||s!==0)&&i.translate(n,s),a!==0&&i.rotate(a),(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,n,s,a,o;for(i in t)e[i]=t[i];const l=new this.constructor(e);for(i in this.eventListeners)for(n=this.eventListeners[i],s=n.length,a=0;a<s;a++)o=n[a],o.name.indexOf(ur)<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(),n=t.x!==void 0?t.x:Math.floor(e.x),s=t.y!==void 0?t.y:Math.floor(e.y),a=t.pixelRatio||1,o=new Lt({width:t.width||Math.ceil(e.width)||(i?i.width():0),height:t.height||Math.ceil(e.height)||(i?i.height():0),pixelRatio:a}),l=o.getContext(),h=new Lt({width:o.width/o.pixelRatio+Math.abs(n),height:o.height/o.pixelRatio+Math.abs(s),pixelRatio:o.pixelRatio});return t.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(t){return this._toKonvaCanvas(t)._canvas}toDataURL(t){t=t||{};const e=t.mimeType||null,i=t.quality||null,n=this._toKonvaCanvas(t).toDataURL(e,i);return t.callback&&t.callback(n),n}toImage(t){return new Promise((e,i)=>{try{const n=t==null?void 0:t.callback;n&&delete t.callback,C._urlToImage(this.toDataURL(t),function(s){e(s),n==null||n(s)})}catch(n){i(n)}})}toBlob(t){return new Promise((e,i)=>{try{const n=t==null?void 0:t.callback;n&&delete t.callback,this.toCanvas(t).toBlob(s=>{e(s),n==null||n(s)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(n){i(n)}})}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 n=this.eventListeners[t],s,a,o;for(s=0;s<n.length;s++)if(a=n[s].name,o=n[s].handler,(a!=="konva"||e==="konva")&&(!e||a===e)&&(!i||i===o)){if(n.splice(s,1),n.length===0){delete this.eventListeners[t];break}s--}}_fireChangeEvent(t,e,i){this._fire(t+cr,{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[Wi+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 n;i!==void 0&&(n=this.attrs[t],n||(this.attrs[t]=this.getAttr(t)),this.attrs[t][e]=i,this._fireChangeEvent(t,n,i))}_fireAndBubble(t,e,i){e&&this.nodeType===Yi&&(e.target=this);const n=[fr,gr,pr,mr,yr,Sr];if(!(n.indexOf(t)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(t,e);const a=n.indexOf(t)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(e&&!e.cancelBubble||!e)&&this.parent&&this.parent.isListening()&&!a&&(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:n}=this,s=_.protoListenerMap.get(n)||{};let a=s==null?void 0:s[t];if(a===void 0){a=[];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:[];a.push(...l),o=Object.getPrototypeOf(o)}s[t]=a,_.protoListenerMap.set(n,s)}return a}_fire(t,e){e=e||{},e.currentTarget=this,e.type=t;const i=this._getProtoListeners(t);if(i)for(let s=0;s<i.length;s++)i[s].handler.call(this,e);const n=this.eventListeners[t];if(n)for(let s=0;s<n.length;s++)n[s].handler.call(this,e)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(t){const e=t?t.pointerId:void 0,i=this.getStage(),n=this.getAbsolutePosition();if(!i)return;const s=i._getPointerById(e)||i._changedPointerPositions[0]||n;Y._dragElements.set(this._id,{node:this,startPointerPos:s,offset:{x:s.x-n.x,y:s.y-n.y},dragStatus:"ready",pointerId:e})}startDrag(t,e=!0){Y._dragElements.has(this._id)||this._createDragElement(t);const i=Y._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 n={x:i.x-e.offset.x,y:i.y-e.offset.y};const s=this.dragBoundFunc();if(s!==void 0){const a=s.call(this,n,t);a?n=a: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!==n.x||this._lastPos.y!==n.y)&&(this.setAbsolutePosition(n),this._requestDraw()),this._lastPos=n}stopDrag(t){const e=Y._dragElements.get(this._id);e&&(e.dragStatus="stopped"),Y._endDragBefore(t),Y._endDragAfter(t)}setDraggable(t){this._setAttr("draggable",t),this._dragChange()}isDragging(){const t=Y._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 n=!1;Y._dragElements.forEach(s=>{this.isAncestorOf(s.node)&&(n=!0)}),n||this._createDragElement(t)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const e=Y._dragElements.get(this._id),i=e&&e.dragStatus==="dragging",n=e&&e.dragStatus==="ready";i?this.stopDrag():n&&Y._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=_.prototype.getClassName.call(t),n=t.children,s,a,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(s=new l(t.attrs),n)for(a=n.length,o=0;o<a;o++)s.add(_._createNode(n[o]));return s}}_.protoListenerMap=new Map;_.prototype.nodeType="Node";_.prototype._attrsAffectingSize=[];_.prototype.eventListeners={};_.prototype.on.call(_.prototype,Tr,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(xt),this._clearSelfAndDescendantCache(vt)});_.prototype.on.call(_.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(ui)});_.prototype.on.call(_.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(di)});_.prototype.on.call(_.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Fe)});const K=m.addGetterSetter;K(_,"zIndex");K(_,"absolutePosition");K(_,"position");K(_,"x",0,x());K(_,"y",0,x());K(_,"globalCompositeOperation","source-over",Vt());K(_,"opacity",1,x());K(_,"name","",Vt());K(_,"id","",Vt());K(_,"rotation",0,x());m.addComponentsGetterSetter(_,"scale",["x","y"]);K(_,"scaleX",1,x());K(_,"scaleY",1,x());m.addComponentsGetterSetter(_,"skew",["x","y"]);K(_,"skewX",0,x());K(_,"skewY",0,x());m.addComponentsGetterSetter(_,"offset",["x","y"]);K(_,"offsetX",0,x());K(_,"offsetY",0,x());K(_,"dragDistance",void 0,x());K(_,"width",0,x());K(_,"height",0,x());K(_,"listening",!0,ft());K(_,"preventDefault",!0,ft());K(_,"filters",void 0,function(r){return this._filterUpToDate=!1,r});K(_,"visible",!0,ft());K(_,"transformsEnabled","all",Vt());K(_,"size");K(_,"dragBoundFunc");K(_,"draggable",!1,ft());m.backCompat(_,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class ct extends _{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(n=>{const s=n._isMatch(t);return s&&i.push(n),!!(s&&e)}),i}_descendants(t){let e=!1;const i=this.getChildren();for(const n of i){if(e=t(n),e)return!0;if(n.hasChildren()&&(e=n._descendants(t),e))return!0}return!1}toObject(){const t=_.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=_.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 n=this.getLayer(),s=t||n&&n.getCanvas(),a=s&&s.getContext(),o=this._getCanvasCache(),l=o&&o.scene,h=s&&s.isCache;if(!this.isVisible()&&!h)return this;if(l){a.save();const c=this.getAbsoluteTransform(e).getMatrix();a.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedSceneCanvas(a),a.restore()}else this._drawChildren("drawScene",s,e,i);return this}drawHit(t,e){if(!this.shouldDrawHit(e))return this;const i=this.getLayer(),n=t||i&&i.hitCanvas,s=n&&n.getContext(),a=this._getCanvasCache();if(a&&a.hit){s.save();const l=this.getAbsoluteTransform(e).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,e);return this}_drawChildren(t,e,i,n){var s;const a=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){a.save();const p=this.getAbsoluteTransform(i);let g=p.getMatrix();a.transform(g[0],g[1],g[2],g[3],g[4],g[5]),a.beginPath();let y;if(h)y=h.call(this,a,this);else{const T=this.clipX(),S=this.clipY();a.rect(T||0,S||0,o,l)}a.clip.apply(a,y),g=p.copy().invert().getMatrix(),a.transform(g[0],g[1],g[2],g[3],g[4],g[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";u&&(a.save(),a._applyGlobalCompositeOperation(this)),(s=this.children)===null||s===void 0||s.forEach(function(p){p[t](e,i,n)}),u&&a.restore(),c&&a.restore()}getClientRect(t={}){var e;const i=t.skipTransform,n=t.relativeTo;let s,a,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 g=p.getClientRect({relativeTo:c,skipShadow:t.skipShadow,skipStroke:t.skipStroke});g.width===0&&g.height===0||(s===void 0?(s=g.x,a=g.y,o=g.x+g.width,l=g.y+g.height):(s=Math.min(s,g.x),a=Math.min(a,g.y),o=Math.max(o,g.x+g.width),l=Math.max(l,g.y+g.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&&s!==void 0?h={x:s,y:a,width:o-s,height:l-a}:h={x:0,y:0,width:0,height:0},i?h:this._transformedRect(h,n)}}m.addComponentsGetterSetter(ct,"clip",["x","y","width","height"]);m.addGetterSetter(ct,"clipX",void 0,x());m.addGetterSetter(ct,"clipY",void 0,x());m.addGetterSetter(ct,"clipWidth",void 0,x());m.addGetterSetter(ct,"clipHeight",void 0,x());m.addGetterSetter(ct,"clipFunc");const we=new Map,Bn=E._global.PointerEvent!==void 0;function Je(r){return we.get(r)}function Mi(r){return{evt:r,pointerId:r.pointerId}}function Hn(r,t){return we.get(r)===t}function zn(r,t){pe(r),t.getStage()&&(we.set(r,t),Bn&&t._fire("gotpointercapture",Mi(new PointerEvent("gotpointercapture"))))}function pe(r,t){const e=we.get(r);if(!e)return;const i=e.getStage();i&&i.content,we.delete(r),Bn&&e._fire("lostpointercapture",Mi(new PointerEvent("lostpointercapture")))}const br="Stage",wr="string",Ui="px",kr="mouseout",Nn="mouseleave",Fn="mouseover",Vn="mouseenter",Wn="mousemove",Yn="mousedown",Xn="mouseup",he="pointermove",ce="pointerdown",Zt="pointerup",de="pointercancel",_r="lostpointercapture",Le="pointerout",ue="pointerleave",Me="pointerover",Re="pointerenter",fi="contextmenu",Un="touchstart",$n="touchend",qn="touchmove",Kn="touchcancel",gi="wheel",Pr=5,xr=[[Vn,"_pointerenter"],[Yn,"_pointerdown"],[Wn,"_pointermove"],[Xn,"_pointerup"],[Nn,"_pointerleave"],[Un,"_pointerdown"],[qn,"_pointermove"],[$n,"_pointerup"],[Kn,"_pointercancel"],[Fn,"_pointerover"],[gi,"_wheel"],[fi,"_contextmenu"],[ce,"_pointerdown"],[he,"_pointermove"],[Zt,"_pointerup"],[de,"_pointercancel"],[ue,"_pointerleave"],[_r,"_lostpointercapture"]],Qe={mouse:{[Le]:kr,[ue]:Nn,[Me]:Fn,[Re]:Vn,[he]:Wn,[ce]:Yn,[Zt]:Xn,[de]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Le]:"touchout",[ue]:"touchleave",[Me]:"touchover",[Re]:"touchenter",[he]:qn,[ce]:Un,[Zt]:$n,[de]:Kn,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Le]:Le,[ue]:ue,[Me]:Me,[Re]:Re,[he]:he,[ce]:ce,[Zt]:Zt,[de]:de,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},fe=r=>r.indexOf("pointer")>=0?"pointer":r.indexOf("touch")>=0?"touch":"mouse",$t=r=>{const t=fe(r);if(t==="pointer")return E.pointerEventsEnabled&&Qe.pointer;if(t==="touch")return Qe.touch;if(t==="mouse")return Qe.mouse};function $i(r={}){return(r.clipFunc||r.clipWidth||r.clipHeight)&&C.warn("Stage does not support clipping. Please use clip for Layers or Groups."),r}const Er="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);",me=[];class je extends ct{constructor(t){super($i(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),me.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{$i(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===wr){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"),ct.prototype.clone.call(this,t)}destroy(){super.destroy();const t=this.content;t&&C._isInDocument(t)&&this.container().removeChild(t);const e=me.indexOf(this);return e>-1&&me.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(Er),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 Lt({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),i=e.getContext()._context,n=this.children;return(t.x||t.y)&&i.translate(-1*t.x,-1*t.y),n.forEach(function(s){if(!s.isVisible())return;const a=s._toKonvaCanvas(t);i.drawImage(a._canvas,t.x,t.y,a.getWidth()/a.getPixelRatio(),a.getHeight()/a.getPixelRatio())}),e}getIntersection(t){if(!t)return null;const e=this.children,i=e.length,n=i-1;for(let s=n;s>=0;s--){const a=e[s].getIntersection(t);if(a)return a}return null}_resizeDOM(){const t=this.width(),e=this.height();this.content&&(this.content.style.width=t+Ui,this.content.style.height=e+Ui),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 n=0;n<arguments.length;n++)this.add(arguments[n]);return this}super.add(t);const i=this.children.length;return i>Pr&&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 Hn(t,this)}setPointerCapture(t){zn(t,this)}releaseCapture(t){pe(t)}getLayers(){return this.children}_bindContentEvents(){E.isBrowser&&xr.forEach(([t,e])=>{this.content.addEventListener(t,i=>{this[e](i)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const e=$t(t.type);e&&this._fire(e.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const e=$t(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=$t(t.type),i=fe(t.type);if(!e)return;this.setPointersPositions(t);const n=this._getTargetShape(i),s=!(E.isDragging()||E.isTransforming())||E.hitOnDragEnabled;n&&s?(n._fireAndBubble(e.pointerout,{evt:t}),n._fireAndBubble(e.pointerleave,{evt:t}),this._fire(e.pointerleave,{evt:t,target:this,currentTarget:this}),this[i+"targetShape"]=null):s&&(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=$t(t.type),i=fe(t.type);if(!e)return;this.setPointersPositions(t);let n=!1;this._changedPointerPositions.forEach(s=>{const a=this.getIntersection(s);if(Y.justDragged=!1,E["_"+i+"ListenClick"]=!0,!a||!a.isListening()){this[i+"ClickStartShape"]=void 0;return}E.capturePointerEventsEnabled&&a.setPointerCapture(s.id),this[i+"ClickStartShape"]=a,a._fireAndBubble(e.pointerdown,{evt:t,pointerId:s.id}),n=!0;const o=t.type.indexOf("touch")>=0;a.preventDefault()&&t.cancelable&&o&&t.preventDefault()}),n||this._fire(e.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(t){const e=$t(t.type),i=fe(t.type);if(!e)return;const n=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(E.isDragging()&&Y.node.preventDefault()&&t.cancelable&&n&&t.preventDefault(),this.setPointersPositions(t),!(!(E.isDragging()||E.isTransforming())||E.hitOnDragEnabled))return;const a={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(h=>{const c=Je(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(a[c._id])return;a[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=$t(t.type),i=fe(t.type);if(!e)return;this.setPointersPositions(t);const n=this[i+"ClickStartShape"],s=this[i+"ClickEndShape"],a={};let o=!1;this._changedPointerPositions.forEach(l=>{const h=Je(l.id)||this.getIntersection(l);if(h){if(h.releaseCapture(l.id),a[h._id])return;a[h._id]=!0}const c=l.id,d={evt:t,pointerId:c};let u=!1;E["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):Y.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"]&&n&&n===h&&(h._fireAndBubble(e.pointerclick,{...d}),u&&s&&s===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(fi,{evt:t}):this._fire(fi,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const e=this.getIntersection(this.getPointerPosition());e&&e.isListening()?e._fireAndBubble(gi,{evt:t}):this._fire(gi,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const e=Je(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble(Zt,Mi(t)),pe(t.pointerId)}_lostpointercapture(t){pe(t.pointerId)}setPointersPositions(t){const e=this._getContentPosition();let i=null,n=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,s=>{this._pointerPositions.push({id:s.identifier,x:(s.clientX-e.left)/e.scaleX,y:(s.clientY-e.top)/e.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,s=>{this._changedPointerPositions.push({id:s.identifier,x:(s.clientX-e.left)/e.scaleX,y:(s.clientY-e.top)/e.scaleY})})):(i=(t.clientX-e.left)/e.scaleX,n=(t.clientY-e.top)/e.scaleY,this.pointerPos={x:i,y:n},this._pointerPositions=[{x:i,y:n,id:C._getFirstPointerId(t)}],this._changedPointerPositions=[{x:i,y:n,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 Lt({width:this.width(),height:this.height()}),this.bufferHitCanvas=new Ai({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}}je.prototype.nodeType=br;tt(je);m.addGetterSetter(je,"container");E.isBrowser&&document.addEventListener("visibilitychange",()=>{me.forEach(r=>{r.batchDraw()})});const jn="hasShadow",Zn="shadowRGBA",Jn="patternImage",Qn="linearGradient",ts="radialGradient";let Ie;function ti(){return Ie||(Ie=C.createCanvasElement().getContext("2d"),Ie)}const ye={};function Ar(r){const t=this.attrs.fillRule;t?r.fill(t):r.fill()}function Lr(r){r.stroke()}function Mr(r){const t=this.attrs.fillRule;t?r.fill(t):r.fill()}function Rr(r){r.stroke()}function Ir(){this._clearCache(jn)}function Dr(){this._clearCache(Zn)}function Gr(){this._clearCache(Jn)}function Or(){this._clearCache(Qn)}function Br(){this._clearCache(ts)}class k extends _{constructor(t){super(t);let e,i=0;for(;e=C.getHitColor(),!(e&&!(e in ye));)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,ye[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(jn,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(Jn,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const e=ti().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(e&&e.setTransform){const i=new ht;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);e.setTransform(s)}return e}}_getLinearGradient(){return this._getCache(Qn,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const e=ti(),i=this.fillLinearGradientStartPoint(),n=this.fillLinearGradientEndPoint(),s=e.createLinearGradient(i.x,i.y,n.x,n.y);for(let a=0;a<t.length;a+=2)s.addColorStop(t[a],t[a+1]);return s}}_getRadialGradient(){return this._getCache(ts,this.__getRadialGradient)}__getRadialGradient(){const t=this.fillRadialGradientColorStops();if(t){const e=ti(),i=this.fillRadialGradientStartPoint(),n=this.fillRadialGradientEndPoint(),s=e.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),n.x,n.y,this.fillRadialGradientEndRadius());for(let a=0;a<t.length;a+=2)s.addColorStop(t[a],t[a+1]);return s}}getShadowRGBA(){return this._getCache(Zn,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 _.prototype.destroy.call(this),delete ye[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var e;if(!((e=this.attrs.perfectDrawEnabled)!==null&&e!==void 0?e:!0))return!1;const n=t||this.hasFill(),s=this.hasStroke(),a=this.getAbsoluteOpacity()!==1;if(n&&s&&a)return!0;const o=this.hasShadow(),l=this.shadowForStrokeEnabled();return!!(n&&s&&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 n=t.skipTransform,s=t.relativeTo||e&&this.getStage()||void 0,a=this.getSelfRect(),l=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,h=a.width+l,c=a.height+l,d=!t.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,p=d?this.shadowOffsetY():0,g=h+Math.abs(u),y=c+Math.abs(p),T=d&&this.shadowBlur()||0,S=g+T*2,v=y+T*2,b={width:S,height:v,x:-(l/2+T)+Math.min(u,0)+a.x,y:-(l/2+T)+Math.min(p,0)+a.y};return n?b:this._transformedRect(b,s)}drawScene(t,e,i){const n=this.getLayer(),s=t||n.getCanvas(),a=s.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),h=this.hasShadow();let c;const d=e===this;if(!this.isVisible()&&!d)return this;if(o){a.save();const u=this.getAbsoluteTransform(e).getMatrix();return a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(a),a.restore(),this}if(!l)return this;if(a.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 g=this.getAbsoluteTransform(e).getMatrix();p.transform(g[0],g[1],g[2],g[3],g[4],g[5]),l.call(this,p,this),p.restore();const y=u.pixelRatio;h&&a._applyShadow(this),d||(a._applyOpacity(this),a._applyGlobalCompositeOperation(this)),a.drawImage(u._canvas,u.x||0,u.y||0,u.width/y,u.height/y)}else{if(a._applyLineJoin(this),a._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(e).getMatrix();a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),a._applyOpacity(this),a._applyGlobalCompositeOperation(this)}h&&a._applyShadow(this),l.call(this,a,this)}return a.restore(),this}drawHit(t,e,i=!1){if(!this.shouldDrawHit(e,i))return this;const n=this.getLayer(),s=t||n.hitCanvas,a=s&&s.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){a.save();const d=this.getAbsoluteTransform(e).getMatrix();return a.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(a),a.restore(),this}if(!o)return this;if(a.save(),a._applyLineJoin(this),a._applyMiterLimit(this),!(this===e)){const d=this.getAbsoluteTransform(e).getMatrix();a.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,a,this),a.restore(),this}drawHitFromCache(t=0){const e=this._getCanvasCache(),i=this._getCachedSceneCanvas(),n=e.hit,s=n.getContext(),a=n.getWidth(),o=n.getHeight();s.clear(),s.drawImage(i._canvas,0,0,a,o);try{const l=s.getImageData(0,0,a,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;s.putImageData(l,0,0)}catch(l){C.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(t){return Hn(t,this)}setPointerCapture(t){zn(t,this)}releaseCapture(t){pe(t)}}k.prototype._fillFunc=Ar;k.prototype._strokeFunc=Lr;k.prototype._fillFuncHit=Mr;k.prototype._strokeFuncHit=Rr;k.prototype._centroid=!1;k.prototype.nodeType="Shape";tt(k);k.prototype.eventListeners={};k.prototype.on.call(k.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Ir);k.prototype.on.call(k.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Dr);k.prototype.on.call(k.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Gr);k.prototype.on.call(k.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Or);k.prototype.on.call(k.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Br);m.addGetterSetter(k,"stroke",void 0,On());m.addGetterSetter(k,"strokeWidth",2,x());m.addGetterSetter(k,"fillAfterStrokeEnabled",!1);m.addGetterSetter(k,"hitStrokeWidth","auto",Li());m.addGetterSetter(k,"strokeHitEnabled",!0,ft());m.addGetterSetter(k,"perfectDrawEnabled",!0,ft());m.addGetterSetter(k,"shadowForStrokeEnabled",!0,ft());m.addGetterSetter(k,"lineJoin");m.addGetterSetter(k,"lineCap");m.addGetterSetter(k,"miterLimit");m.addGetterSetter(k,"sceneFunc");m.addGetterSetter(k,"hitFunc");m.addGetterSetter(k,"dash");m.addGetterSetter(k,"dashOffset",0,x());m.addGetterSetter(k,"shadowColor",void 0,Vt());m.addGetterSetter(k,"shadowBlur",0,x());m.addGetterSetter(k,"shadowOpacity",1,x());m.addComponentsGetterSetter(k,"shadowOffset",["x","y"]);m.addGetterSetter(k,"shadowOffsetX",0,x());m.addGetterSetter(k,"shadowOffsetY",0,x());m.addGetterSetter(k,"fillPatternImage");m.addGetterSetter(k,"fill",void 0,On());m.addGetterSetter(k,"fillPatternX",0,x());m.addGetterSetter(k,"fillPatternY",0,x());m.addGetterSetter(k,"fillLinearGradientColorStops");m.addGetterSetter(k,"strokeLinearGradientColorStops");m.addGetterSetter(k,"fillRadialGradientStartRadius",0);m.addGetterSetter(k,"fillRadialGradientEndRadius",0);m.addGetterSetter(k,"fillRadialGradientColorStops");m.addGetterSetter(k,"fillPatternRepeat","repeat");m.addGetterSetter(k,"fillEnabled",!0);m.addGetterSetter(k,"strokeEnabled",!0);m.addGetterSetter(k,"shadowEnabled",!0);m.addGetterSetter(k,"dashEnabled",!0);m.addGetterSetter(k,"strokeScaleEnabled",!0);m.addGetterSetter(k,"fillPriority","color");m.addComponentsGetterSetter(k,"fillPatternOffset",["x","y"]);m.addGetterSetter(k,"fillPatternOffsetX",0,x());m.addGetterSetter(k,"fillPatternOffsetY",0,x());m.addComponentsGetterSetter(k,"fillPatternScale",["x","y"]);m.addGetterSetter(k,"fillPatternScaleX",1,x());m.addGetterSetter(k,"fillPatternScaleY",1,x());m.addComponentsGetterSetter(k,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(k,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(k,"fillLinearGradientStartPointX",0);m.addGetterSetter(k,"strokeLinearGradientStartPointX",0);m.addGetterSetter(k,"fillLinearGradientStartPointY",0);m.addGetterSetter(k,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(k,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(k,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(k,"fillLinearGradientEndPointX",0);m.addGetterSetter(k,"strokeLinearGradientEndPointX",0);m.addGetterSetter(k,"fillLinearGradientEndPointY",0);m.addGetterSetter(k,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(k,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(k,"fillRadialGradientStartPointX",0);m.addGetterSetter(k,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(k,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(k,"fillRadialGradientEndPointX",0);m.addGetterSetter(k,"fillRadialGradientEndPointY",0);m.addGetterSetter(k,"fillPatternRotation",0);m.addGetterSetter(k,"fillRule",void 0,Vt());m.backCompat(k,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Hr="beforeDraw",zr="draw",es=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Nr=es.length;class Wt extends ct{constructor(t){super(t),this.canvas=new Lt,this.hitCanvas=new Ai({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(){_.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(!_.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(_.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(_.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 _.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(),_.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 n=0;n<Nr;n++){const s=es[n],a=this._getIntersection({x:t.x+s.x*e,y:t.y+s.y*e}),o=a.shape;if(o)return o;if(i=!!a.antialiased,!a.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,n=i[3];if(n===255){const s=C.getHitColorKey(i[0],i[1],i[2]),a=ye[s];return a?{shape:a}:{antialiased:!0}}else if(n>0)return{antialiased:!0};return{}}drawScene(t,e,i){const n=this.getLayer(),s=t||n&&n.getCanvas();return this._fire(Hr,{node:this}),this.clearBeforeDraw()&&s.getContext().clear(),ct.prototype.drawScene.call(this,s,e,i),this._fire(zr,{node:this}),this}drawHit(t,e){const i=this.getLayer(),n=t||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),ct.prototype.drawHit.call(this,n,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()}}Wt.prototype.nodeType="Layer";tt(Wt);m.addGetterSetter(Wt,"imageSmoothingEnabled",!0);m.addGetterSetter(Wt,"clearBeforeDraw",!0);m.addGetterSetter(Wt,"hitGraphEnabled",!0,ft());class Ri extends Wt{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";tt(Ri);class Qt extends ct{_validateAdd(t){const e=t.getType();e!=="Group"&&e!=="Shape"&&C.throw("You may only add groups and shapes to groups.")}}Qt.prototype.nodeType="Group";tt(Qt);const ei=function(){return zt.performance&&zt.performance.now?function(){return zt.performance.now()}:function(){return new Date().getTime()}}();class dt{constructor(t,e){this.id=dt.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:ei(),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 n=0;n<i;n++)if(e[n]._id===t._id)return!1;return this.layers.push(t),!0}isRunning(){const e=dt.animations,i=e.length;for(let n=0;n<i;n++)if(e[n].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=ei(),dt._addAnimation(this),this}stop(){return dt._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,n=i.length;for(let s=0;s<n;s++)if(i[s].id===e){this.animations.splice(s,1);break}}static _runFrames(){const t={},e=this.animations;for(let i=0;i<e.length;i++){const n=e[i],s=n.layers,a=n.func;n._updateFrameObject(ei());const o=s.length;let l;if(a?l=a.call(n,n.frame)!==!1:l=!0,!!l)for(let h=0;h<o;h++){const c=s[h];c._id!==void 0&&(t[c._id]=c)}}for(const i in t)t.hasOwnProperty(i)&&t[i].batchDraw()}static _animationLoop(){const t=dt;t.animations.length?(t._runFrames(),C.requestAnimFrame(t._animationLoop)):t.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,C.requestAnimFrame(this._animationLoop))}}dt.animations=[];dt.animIdCounter=0;dt.animRunning=!1;const Fr={node:1,duration:1,easing:1,onFinish:1,yoyo:1},Vr=1,qi=2,Ki=3,ji=["fill","stroke","shadowColor"];let Wr=0;class Yr{constructor(t,e,i,n,s,a,o){this.prop=t,this.propFunc=e,this.begin=n,this._pos=n,this.duration=a,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(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=qi,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Ki,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===qi?this.setTime(t):this.state===Ki&&this.setTime(this.duration-t)}pause(){this.state=Vr,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Z{constructor(t){const e=this,i=t.node,n=i._id,s=t.easing||Se.Linear,a=!!t.yoyo;let o,l;typeof t.duration>"u"?o=.3:t.duration===0?o=.001:o=t.duration,this.node=i,this._id=Wr++;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 dt(function(){e.tween.onEnterFrame()},h),this.tween=new Yr(l,function(c){e._tweenFunc(c)},s,0,1,o*1e3,a),this._addListeners(),Z.attrs[n]||(Z.attrs[n]={}),Z.attrs[n][this._id]||(Z.attrs[n][this._id]={}),Z.tweens[n]||(Z.tweens[n]={});for(l in t)Fr[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,n=i._id;let s,a,o,l,h;const c=Z.tweens[n][t];c&&delete Z.attrs[n][c][t];let d=i.getAttr(t);if(C._isArray(e))if(s=[],a=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<a;u++)if(u%2===0)s.push(e[u]-d[u]);else{const p=C.colorToRGBA(d[u]);h=C.colorToRGBA(e[u]),d[u]=p,s.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<a;u++)s.push(e[u]-d[u]);else ji.indexOf(t)!==-1?(d=C.colorToRGBA(d),h=C.colorToRGBA(e),s={r:h.r-d.r,g:h.g-d.g,b:h.b-d.b,a:h.a-d.a}):s=e-d;Z.attrs[n][this._id][t]={start:d,diff:s,end:e,trueEnd:o,trueStart:l},Z.tweens[n][t]=this._id}_tweenFunc(t){const e=this.node,i=Z.attrs[e._id][this._id];let n,s,a,o,l,h,c,d;for(n in i){if(s=i[n],a=s.start,o=s.diff,d=s.end,C._isArray(a))if(l=[],c=Math.max(a.length,d.length),n.indexOf("fill")===0)for(h=0;h<c;h++)h%2===0?l.push((a[h]||0)+o[h]*t):l.push("rgba("+Math.round(a[h].r+o[h].r*t)+","+Math.round(a[h].g+o[h].g*t)+","+Math.round(a[h].b+o[h].b*t)+","+(a[h].a+o[h].a*t)+")");else for(h=0;h<c;h++)l.push((a[h]||0)+o[h]*t);else ji.indexOf(n)!==-1?l="rgba("+Math.round(a.r+o.r*t)+","+Math.round(a.g+o.g*t)+","+Math.round(a.b+o.b*t)+","+(a.a+o.a*t)+")":l=a+o*t;e.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 t=this.node,e=Z.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=Z.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=Z.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const n in i)delete Z.tweens[t][n];delete Z.attrs[t][e],Z.tweens[t]&&(Object.keys(Z.tweens[t]).length===0&&delete Z.tweens[t],Object.keys(Z.attrs[t]).length===0&&delete Z.attrs[t])}}Z.attrs={};Z.tweens={};_.prototype.to=function(r){const t=r.onFinish;r.node=this,r.onFinish=function(){this.destroy(),t&&t()},new Z(r).play()};const Se={BackEaseIn(r,t,e,i){return e*(r/=i)*r*((1.70158+1)*r-1.70158)+t},BackEaseOut(r,t,e,i){return e*((r=r/i-1)*r*((1.70158+1)*r+1.70158)+1)+t},BackEaseInOut(r,t,e,i){let n=1.70158;return(r/=i/2)<1?e/2*(r*r*(((n*=1.525)+1)*r-n))+t:e/2*((r-=2)*r*(((n*=1.525)+1)*r+n)+2)+t},ElasticEaseIn(r,t,e,i,n,s){let a=0;return r===0?t:(r/=i)===1?t+e:(s||(s=i*.3),!n||n<Math.abs(e)?(n=e,a=s/4):a=s/(2*Math.PI)*Math.asin(e/n),-(n*Math.pow(2,10*(r-=1))*Math.sin((r*i-a)*(2*Math.PI)/s))+t)},ElasticEaseOut(r,t,e,i,n,s){let a=0;return r===0?t:(r/=i)===1?t+e:(s||(s=i*.3),!n||n<Math.abs(e)?(n=e,a=s/4):a=s/(2*Math.PI)*Math.asin(e/n),n*Math.pow(2,-10*r)*Math.sin((r*i-a)*(2*Math.PI)/s)+e+t)},ElasticEaseInOut(r,t,e,i,n,s){let a=0;return r===0?t:(r/=i/2)===2?t+e:(s||(s=i*(.3*1.5)),!n||n<Math.abs(e)?(n=e,a=s/4):a=s/(2*Math.PI)*Math.asin(e/n),r<1?-.5*(n*Math.pow(2,10*(r-=1))*Math.sin((r*i-a)*(2*Math.PI)/s))+t:n*Math.pow(2,-10*(r-=1))*Math.sin((r*i-a)*(2*Math.PI)/s)*.5+e+t)},BounceEaseOut(r,t,e,i){return(r/=i)<1/2.75?e*(7.5625*r*r)+t:r<2/2.75?e*(7.5625*(r-=1.5/2.75)*r+.75)+t:r<2.5/2.75?e*(7.5625*(r-=2.25/2.75)*r+.9375)+t:e*(7.5625*(r-=2.625/2.75)*r+.984375)+t},BounceEaseIn(r,t,e,i){return e-Se.BounceEaseOut(i-r,0,e,i)+t},BounceEaseInOut(r,t,e,i){return r<i/2?Se.BounceEaseIn(r*2,0,e,i)*.5+t:Se.BounceEaseOut(r*2-i,0,e,i)*.5+e*.5+t},EaseIn(r,t,e,i){return e*(r/=i)*r+t},EaseOut(r,t,e,i){return-e*(r/=i)*(r-2)+t},EaseInOut(r,t,e,i){return(r/=i/2)<1?e/2*r*r+t:-e/2*(--r*(r-2)-1)+t},StrongEaseIn(r,t,e,i){return e*(r/=i)*r*r*r*r+t},StrongEaseOut(r,t,e,i){return e*((r=r/i-1)*r*r*r*r+1)+t},StrongEaseInOut(r,t,e,i){return(r/=i/2)<1?e/2*r*r*r*r*r+t:e/2*((r-=2)*r*r*r*r+2)+t},Linear(r,t,e,i){return e*r/i+t}},Zi=C._assign(E,{Util:C,Transform:ht,Node:_,Container:ct,Stage:je,stages:me,Layer:Wt,FastLayer:Ri,Group:Qt,DD:Y,Shape:k,shapes:ye,Animation:dt,Tween:Z,Easings:Se,Context:qe,Canvas:Ei});class kt extends k{_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(),n=E.getAngle(i?360-this.angle():this.angle()),s=Math.cos(Math.min(n,Math.PI)),a=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?t:e),c=a*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}}}kt.prototype._centroid=!0;kt.prototype.className="Arc";kt.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];tt(kt);m.addGetterSetter(kt,"innerRadius",0,x());m.addGetterSetter(kt,"outerRadius",0,x());m.addGetterSetter(kt,"angle",0,x());m.addGetterSetter(kt,"clockwise",!1,ft());function pi(r,t,e,i,n,s,a){const o=Math.sqrt(Math.pow(e-r,2)+Math.pow(i-t,2)),l=Math.sqrt(Math.pow(n-e,2)+Math.pow(s-i,2)),h=a*o/(o+l),c=a*l/(o+l),d=e-h*(n-r),u=i-h*(s-t),p=e+c*(n-r),g=i+c*(s-t);return[d,u,p,g]}function Ji(r,t){const e=r.length,i=[];for(let n=2;n<e-2;n+=2){const s=pi(r[n-2],r[n-1],r[n],r[n+1],r[n+2],r[n+3],t);isNaN(s[0])||(i.push(s[0]),i.push(s[1]),i.push(r[n]),i.push(r[n+1]),i.push(s[2]),i.push(s[3]))}return i}function Xr(r){const t=[[r[0],r[2],r[4],r[6]],[r[1],r[3],r[5],r[7]]],e=[];for(const i of t){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],a=-3*i[0]+3*i[1],o=s*s-4*n*a;if(o>=0){const l=Math.sqrt(o);e.push((-s+l)/(2*n)),e.push((-s-l)/(2*n))}}}return e.filter(i=>i>0&&i<1).flatMap(i=>t.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 _t extends k{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,n=this.tension(),s=this.closed(),a=this.bezier();if(!i)return;let o=0;if(t.beginPath(),t.moveTo(e[0],e[1]),n!==0&&i>4){const l=this.getTensionPoints(),h=l.length;for(o=s?0:4,s||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++]);s||t.quadraticCurveTo(l[h-2],l[h-1],e[i-2],e[i-1])}else if(a)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]);s?(t.closePath(),t.fillStrokeShape(this)):t.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():Ji(this.points(),this.tension())}_getTensionPointsClosed(){const t=this.points(),e=t.length,i=this.tension(),n=pi(t[e-2],t[e-1],t[0],t[1],t[2],t[3],i),s=pi(t[e-4],t[e-3],t[e-2],t[e-1],t[0],t[1],i),a=Ji(t,i);return[n[2],n[3]].concat(a).concat([s[0],s[1],t[e-2],t[e-1],s[2],s[3],n[0],n[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],...Xr(this.points()),t[t.length-2],t[t.length-1]]:t=this.points();let e=t[0],i=t[0],n=t[1],s=t[1],a,o;for(let l=0;l<t.length/2;l++)a=t[l*2],o=t[l*2+1],e=Math.min(e,a),i=Math.max(i,a),n=Math.min(n,o),s=Math.max(s,o);return{x:e,y:n,width:i-e,height:s-n}}}_t.prototype.className="Line";_t.prototype._attrsAffectingSize=["points","bezier","tension"];tt(_t);m.addGetterSetter(_t,"closed",!1);m.addGetterSetter(_t,"bezier",!1);m.addGetterSetter(_t,"tension",0,x());m.addGetterSetter(_t,"points",[],or());const Ur=[[],[],[-.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]],$r=[[],[],[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]],qr=[[1],[1,1],[1,2,1],[1,3,3,1]],Qi=(r,t,e)=>{let i,n;const a=e/2;i=0;for(let o=0;o<20;o++)n=a*Ur[20][o]+a,i+=$r[20][o]*Kr(r,t,n);return a*i},tn=(r,t,e)=>{e===void 0&&(e=1);const i=r[0]-2*r[1]+r[2],n=t[0]-2*t[1]+t[2],s=2*r[1]-2*r[0],a=2*t[1]-2*t[0],o=4*(i*i+n*n),l=4*(i*s+n*a),h=s*s+a*a;if(o===0)return e*Math.sqrt(Math.pow(r[2]-r[0],2)+Math.pow(t[2]-t[0],2));const c=l/(2*o),d=h/o,u=e+c,p=d-c*c,g=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+g)/(c+y))):0;return Math.sqrt(o)/2*(u*g-c*y+T)};function Kr(r,t,e){const i=mi(1,e,r),n=mi(1,e,t),s=i*i+n*n;return Math.sqrt(s)}const mi=(r,t,e)=>{const i=e.length-1;let n,s;if(i===0)return 0;if(r===0){s=0;for(let a=0;a<=i;a++)s+=qr[i][a]*Math.pow(1-t,i-a)*Math.pow(t,a)*e[a];return s}else{n=new Array(i);for(let a=0;a<i;a++)n[a]=i*(e[a+1]-e[a]);return mi(r-1,t,n)}},en=(r,t,e)=>{let i=1,n=r/t,s=(r-e(n))/t,a=0;for(;i>.001;){const o=e(n+s),l=Math.abs(r-o)/t;if(l<i)i=l,n+=s;else{const h=e(n-s),c=Math.abs(r-h)/t;c<i?(i=c,n-=s):s/=2}if(a++,a>500)break}return n};class J extends k{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=J.parsePathData(this.data()),this.pathLength=J.getPathLength(this.dataArray)}_sceneFunc(t){const e=this.dataArray;t.beginPath();let i=!1;for(let n=0;n<e.length;n++){const s=e[n].command,a=e[n].points;switch(s){case"L":t.lineTo(a[0],a[1]);break;case"M":t.moveTo(a[0],a[1]);break;case"C":t.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5]);break;case"Q":t.quadraticCurveTo(a[0],a[1],a[2],a[3]);break;case"A":const o=a[0],l=a[1],h=a[2],c=a[3],d=a[4],u=a[5],p=a[6],g=a[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-g),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 g=J.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);t.push(g.x,g.y)}else for(let p=h+u;p<d;p+=u){const g=J.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);t.push(g.x,g.y)}}else if(l.command==="C")for(let h=0;h<=1;h+=.01){const c=J.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],n=t[1],s=t[1],a,o;for(let l=0;l<t.length/2;l++)a=t[l*2],o=t[l*2+1],isNaN(a)||(e=Math.min(e,a),i=Math.max(i,a)),isNaN(o)||(n=Math.min(n,o),s=Math.max(s,o));return{x:e,y:n,width:i-e,height:s-n}}getLength(){return this.pathLength}getPointAtLength(t){return J.getPointAtLengthOfDataArray(t,this.dataArray)}static getLineLength(t,e,i,n){return Math.sqrt((i-t)*(i-t)+(n-e)*(n-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,n=0,s=e.length;if(!s)return null;for(;n<s&&t>e[n].pathLength;)t-=e[n].pathLength,++n;if(n===s)return i=e[n-1].points.slice(-2),{x:i[0],y:i[1]};if(t<.01)return e[n].command==="M"?(i=e[n].points.slice(0,2),{x:i[0],y:i[1]}):{x:e[n].start.x,y:e[n].start.y};const a=e[n],o=a.points;switch(a.command){case"L":return J.getPointOnLine(t,a.start.x,a.start.y,o[0],o[1]);case"C":return J.getPointOnCubicBezier(en(t,J.getPathLength(e),y=>Qi([a.start.x,o[0],o[2],o[4]],[a.start.y,o[1],o[3],o[5]],y)),a.start.x,a.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return J.getPointOnQuadraticBezier(en(t,J.getPathLength(e),y=>tn([a.start.x,o[0],o[2]],[a.start.y,o[1],o[3]],y)),a.start.x,a.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 g=o[4];return g+=u*t/a.pathLength,J.getPointOnEllipticalArc(l,h,c,d,g,p)}return null}static getPointOnLine(t,e,i,n,s,a,o){a=a??e,o=o??i;const l=this.getLineLength(e,i,n,s);if(l<1e-10)return{x:e,y:i};if(n===e)return{x:a,y:o+(s>i?t:-t)};const h=(s-i)/(n-e),c=Math.sqrt(t*t/(1+h*h))*(n<e?-1:1),d=h*c;if(Math.abs(o-i-h*(a-e))<1e-10)return{x:a+c,y:o+d};const u=((a-e)*(n-e)+(o-i)*(s-i))/(l*l),p=e+u*(n-e),g=i+u*(s-i),y=this.getLineLength(a,o,p,g),T=Math.sqrt(t*t-y*y),S=Math.sqrt(T*T/(1+h*h))*(n<e?-1:1),v=h*S;return{x:p+S,y:g+v}}static getPointOnCubicBezier(t,e,i,n,s,a,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 g=l*c(t)+a*d(t)+n*u(t)+e*p(t),y=h*c(t)+o*d(t)+s*u(t)+i*p(t);return{x:g,y}}static getPointOnQuadraticBezier(t,e,i,n,s,a,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=a*l(t)+n*h(t)+e*c(t),u=o*l(t)+s*h(t)+i*c(t);return{x:d,y:u}}static getPointOnEllipticalArc(t,e,i,n,s,a){const o=Math.cos(a),l=Math.sin(a),h={x:i*Math.cos(s),y:n*Math.sin(s)};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 n=e.split("|"),s=[],a=[];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],p=u.charAt(0);for(u=u.slice(1),a.length=0;c=h.exec(u);)a.push(c[0]);let g=[],y=p==="A"||p==="a"?0:-1;for(let T=0,S=a.length;T<S;T++){const v=a[T];if(v==="00"){g.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)){g.push(parseInt(v[0],10)),g.push(parseInt(v[1],10)),g.push(parseFloat(v.slice(2))),y+=3,y>=7&&(y-=7);continue}if(v==="11"||v==="10"||v==="01"){g.push(parseInt(v[0],10)),g.push(parseInt(v[1],10)),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){g.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(v)){g.push(parseInt(v[0],10)),g.push(parseFloat(v.slice(1))),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){g.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}const b=parseFloat(v);isNaN(b)?g.push(0):g.push(b),y+=1,y>=7&&(y-=7)}else{const b=parseFloat(v);isNaN(b)?g.push(0):g.push(b)}}for(;g.length>0&&!isNaN(g[0]);){let T="",S=[];const v=o,b=l;let w,L,P,I,A,G,z,V,B,W;switch(p){case"l":o+=g.shift(),l+=g.shift(),T="L",S.push(o,l);break;case"L":o=g.shift(),l=g.shift(),S.push(o,l);break;case"m":const N=g.shift(),H=g.shift();if(o+=N,l+=H,T="M",s.length>2&&s[s.length-1].command==="z"){for(let M=s.length-2;M>=0;M--)if(s[M].command==="M"){o=s[M].points[0]+N,l=s[M].points[1]+H;break}}S.push(o,l),p="l";break;case"M":o=g.shift(),l=g.shift(),T="M",S.push(o,l),p="L";break;case"h":o+=g.shift(),T="L",S.push(o,l);break;case"H":o=g.shift(),T="L",S.push(o,l);break;case"v":l+=g.shift(),T="L",S.push(o,l);break;case"V":l=g.shift(),T="L",S.push(o,l);break;case"C":S.push(g.shift(),g.shift(),g.shift(),g.shift()),o=g.shift(),l=g.shift(),S.push(o,l);break;case"c":S.push(o+g.shift(),l+g.shift(),o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),T="C",S.push(o,l);break;case"S":L=o,P=l,w=s[s.length-1],w.command==="C"&&(L=o+(o-w.points[2]),P=l+(l-w.points[3])),S.push(L,P,g.shift(),g.shift()),o=g.shift(),l=g.shift(),T="C",S.push(o,l);break;case"s":L=o,P=l,w=s[s.length-1],w.command==="C"&&(L=o+(o-w.points[2]),P=l+(l-w.points[3])),S.push(L,P,o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),T="C",S.push(o,l);break;case"Q":S.push(g.shift(),g.shift()),o=g.shift(),l=g.shift(),S.push(o,l);break;case"q":S.push(o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),T="Q",S.push(o,l);break;case"T":L=o,P=l,w=s[s.length-1],w.command==="Q"&&(L=o+(o-w.points[0]),P=l+(l-w.points[1])),o=g.shift(),l=g.shift(),T="Q",S.push(L,P,o,l);break;case"t":L=o,P=l,w=s[s.length-1],w.command==="Q"&&(L=o+(o-w.points[0]),P=l+(l-w.points[1])),o+=g.shift(),l+=g.shift(),T="Q",S.push(L,P,o,l);break;case"A":I=g.shift(),A=g.shift(),G=g.shift(),z=g.shift(),V=g.shift(),B=o,W=l,o=g.shift(),l=g.shift(),T="A",S=this.convertEndpointToCenterParameterization(B,W,o,l,z,V,I,A,G);break;case"a":I=g.shift(),A=g.shift(),G=g.shift(),z=g.shift(),V=g.shift(),B=o,W=l,o+=g.shift(),l+=g.shift(),T="A",S=this.convertEndpointToCenterParameterization(B,W,o,l,z,V,I,A,G);break}s.push({command:T||p,points:S,start:{x:v,y:b},pathLength:this.calcLength(v,b,T||p,S)})}(p==="z"||p==="Z")&&s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(t,e,i,n){let s,a,o,l;const h=J;switch(i){case"L":return h.getLineLength(t,e,n[0],n[1]);case"C":return Qi([t,n[0],n[2],n[4]],[e,n[1],n[3],n[5]],1);case"Q":return tn([t,n[0],n[2]],[e,n[1],n[3]],1);case"A":s=0;const c=n[4],d=n[5],u=n[4]+d;let p=Math.PI/180;if(Math.abs(c-u)<p&&(p=Math.abs(c-u)),a=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],c,0),d<0)for(l=c-p;l>u;l-=p)o=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],l,0),s+=h.getLineLength(a.x,a.y,o.x,o.y),a=o;else for(l=c+p;l<u;l+=p)o=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],l,0),s+=h.getLineLength(a.x,a.y,o.x,o.y),a=o;return o=h.getPointOnEllipticalArc(n[0],n[1],n[2],n[3],u,0),s+=h.getLineLength(a.x,a.y,o.x,o.y),s}return 0}static convertEndpointToCenterParameterization(t,e,i,n,s,a,o,l,h){const c=h*(Math.PI/180),d=Math.cos(c)*(t-i)/2+Math.sin(c)*(e-n)/2,u=-1*Math.sin(c)*(t-i)/2+Math.cos(c)*(e-n)/2,p=d*d/(o*o)+u*u/(l*l);p>1&&(o*=Math.sqrt(p),l*=Math.sqrt(p));let g=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));s===a&&(g*=-1),isNaN(g)&&(g=0);const y=g*o*u/l,T=g*-l*d/o,S=(t+i)/2+Math.cos(c)*y-Math.sin(c)*T,v=(e+n)/2+Math.sin(c)*y+Math.cos(c)*T,b=function(z){return Math.sqrt(z[0]*z[0]+z[1]*z[1])},w=function(z,V){return(z[0]*V[0]+z[1]*V[1])/(b(z)*b(V))},L=function(z,V){return(z[0]*V[1]<z[1]*V[0]?-1:1)*Math.acos(w(z,V))},P=L([1,0],[(d-y)/o,(u-T)/l]),I=[(d-y)/o,(u-T)/l],A=[(-1*d-y)/o,(-1*u-T)/l];let G=L(I,A);return w(I,A)<=-1&&(G=Math.PI),w(I,A)>=1&&(G=0),a===0&&G>0&&(G=G-2*Math.PI),a===1&&G<0&&(G=G+2*Math.PI),[S,v,o,l,P,G,c,a]}}J.prototype.className="Path";J.prototype._attrsAffectingSize=["data"];tt(J);m.addGetterSetter(J,"data");class Yt extends _t{_sceneFunc(t){super._sceneFunc(t);const e=Math.PI*2,i=this.points();let n=i;const s=this.tension()!==0&&i.length>4;s&&(n=this.getTensionPoints());const a=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]],p=J.calcLength(n[n.length-4],n[n.length-3],"C",u),g=J.getPointOnQuadraticBezier(Math.min(1,1-a/p),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-g.x,h=i[o-1]-g.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(-a,d/2),t.lineTo(-a,-d/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.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]),t.rotate((Math.atan2(-h,-l)+e)%e),t.moveTo(0,0),t.lineTo(-a,d/2),t.lineTo(-a,-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}}}Yt.prototype.className="Arrow";tt(Yt);m.addGetterSetter(Yt,"pointerLength",10,x());m.addGetterSetter(Yt,"pointerWidth",10,x());m.addGetterSetter(Yt,"pointerAtBeginning",!1);m.addGetterSetter(Yt,"pointerAtEnding",!0);class te extends k{_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)}}te.prototype._centroid=!0;te.prototype.className="Circle";te.prototype._attrsAffectingSize=["radius"];tt(te);m.addGetterSetter(te,"radius",0,x());class It extends k{_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)}}It.prototype.className="Ellipse";It.prototype._centroid=!0;It.prototype._attrsAffectingSize=["radiusX","radiusY"];tt(It);m.addComponentsGetterSetter(It,"radius",["x","y"]);m.addGetterSetter(It,"radiusX",0,x());m.addGetterSetter(It,"radiusY",0,x());let gt=class is extends k{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(),n=this.cornerRadius(),s=this.attrs.image;let a;if(s){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?a=[s,this.cropX(),this.cropY(),o,l,0,0,e,i]:a=[s,0,0,e,i]}(this.hasFill()||this.hasStroke()||n)&&(t.beginPath(),n?C.drawRoundedRectPath(t,e,i,n):t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)),s&&(n&&t.clip(),t.drawImage.apply(t,a))}_hitFunc(t){const e=this.width(),i=this.height(),n=this.cornerRadius();t.beginPath(),n?C.drawRoundedRectPath(t,e,i,n):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 n=C.createImageElement();n.onload=function(){const s=new is({image:n});e(s)},n.onerror=i,n.crossOrigin="Anonymous",n.src=t}};gt.prototype.className="Image";gt.prototype._attrsAffectingSize=["image"];tt(gt);m.addGetterSetter(gt,"cornerRadius",0,Ke(4));m.addGetterSetter(gt,"image");m.addComponentsGetterSetter(gt,"crop",["x","y","width","height"]);m.addGetterSetter(gt,"cropX",0,x());m.addGetterSetter(gt,"cropY",0,x());m.addGetterSetter(gt,"cropWidth",0,x());m.addGetterSetter(gt,"cropHeight",0,x());const ns=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],jr="Change.konva",Zr="none",yi="up",Si="right",Ci="down",Ti="left",Jr=ns.length;class Ii extends Qt{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 n=function(){e._sync()};for(i=0;i<Jr;i++)t.on(ns[i]+jr,n)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let t=this.getText(),e=this.getTag(),i,n,s,a,o,l,h;if(t&&e){switch(i=t.width(),n=t.height(),s=e.pointerDirection(),a=e.pointerWidth(),h=e.pointerHeight(),o=0,l=0,s){case yi:o=i/2,l=-1*h;break;case Si:o=i+a,l=n/2;break;case Ci:o=i/2,l=n+h;break;case Ti:o=-1*a,l=n/2;break}e.setAttrs({x:-1*o,y:-1*l,width:i,height:n}),t.setAttrs({x:-1*o,y:-1*l})}}}Ii.prototype.className="Label";tt(Ii);class Xt extends k{_sceneFunc(t){const e=this.width(),i=this.height(),n=this.pointerDirection(),s=this.pointerWidth(),a=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),n===yi&&(t.lineTo((e-s)/2,0),t.lineTo(e/2,-1*a),t.lineTo((e+s)/2,0)),t.lineTo(e-h,0),t.arc(e-h,h,h,Math.PI*3/2,0,!1),n===Si&&(t.lineTo(e,(i-a)/2),t.lineTo(e+s,i/2),t.lineTo(e,(i+a)/2)),t.lineTo(e,i-d),t.arc(e-d,i-d,d,0,Math.PI/2,!1),n===Ci&&(t.lineTo((e+s)/2,i),t.lineTo(e/2,i+a),t.lineTo((e-s)/2,i)),t.lineTo(c,i),t.arc(c,i-c,c,Math.PI/2,Math.PI,!1),n===Ti&&(t.lineTo(0,(i+a)/2),t.lineTo(-1*s,i/2),t.lineTo(0,(i-a)/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(),n=this.pointerHeight(),s=this.pointerDirection(),a=this.width(),o=this.height();return s===yi?(e-=n,o+=n):s===Ci?o+=n:s===Ti?(t-=i*1.5,a+=i):s===Si&&(a+=i*1.5),{x:t,y:e,width:a,height:o}}}Xt.prototype.className="Tag";tt(Xt);m.addGetterSetter(Xt,"pointerDirection",Zr);m.addGetterSetter(Xt,"pointerWidth",0,x());m.addGetterSetter(Xt,"pointerHeight",0,x());m.addGetterSetter(Xt,"cornerRadius",0,Ke(4));class ke extends k{_sceneFunc(t){const e=this.cornerRadius(),i=this.width(),n=this.height();t.beginPath(),e?C.drawRoundedRectPath(t,i,n,e):t.rect(0,0,i,n),t.closePath(),t.fillStrokeShape(this)}}ke.prototype.className="Rect";tt(ke);m.addGetterSetter(ke,"cornerRadius",0,Ke(4));class Dt extends k{_sceneFunc(t){const e=this._getPoints(),i=this.radius(),n=this.sides(),s=this.cornerRadius();if(t.beginPath(),s)C.drawRoundedPolygonPath(t,e,n,i,s);else{t.moveTo(e[0].x,e[0].y);for(let a=1;a<e.length;a++)t.lineTo(e[a].x,e[a].y)}t.closePath(),t.fillStrokeShape(this)}_getPoints(){const t=this.attrs.sides,e=this.attrs.radius||0,i=[];for(let n=0;n<t;n++)i.push({x:e*Math.sin(n*2*Math.PI/t),y:-1*e*Math.cos(n*2*Math.PI/t)});return i}getSelfRect(){const t=this._getPoints();let e=t[0].x,i=t[0].x,n=t[0].y,s=t[0].y;return t.forEach(a=>{e=Math.min(e,a.x),i=Math.max(i,a.x),n=Math.min(n,a.y),s=Math.max(s,a.y)}),{x:e,y:n,width:i-e,height:s-n}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}Dt.prototype.className="RegularPolygon";Dt.prototype._centroid=!0;Dt.prototype._attrsAffectingSize=["radius"];tt(Dt);m.addGetterSetter(Dt,"radius",0,x());m.addGetterSetter(Dt,"sides",0,x());m.addGetterSetter(Dt,"cornerRadius",0,Ke(4));const nn=Math.PI*2;class Ut extends k{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,nn,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),nn,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)}}Ut.prototype.className="Ring";Ut.prototype._centroid=!0;Ut.prototype._attrsAffectingSize=["innerRadius","outerRadius"];tt(Ut);m.addGetterSetter(Ut,"innerRadius",0,x());m.addGetterSetter(Ut,"outerRadius",0,x());class Ct extends k{constructor(t){super(t),this._updated=!0,this.anim=new dt(()=>{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(),n=i*4,s=this.animations()[e],a=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())&&(t.beginPath(),t.rect(0,0,h,c),t.closePath(),t.fillStrokeShape(this)),d)if(a){const u=a[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(),n=i*4,s=this.animations()[e],a=this.frameOffsets(),o=s[n+2],l=s[n+3];if(t.beginPath(),a){const h=a[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(),n=i[e],s=n.length/4;t<s-1?this.frameIndex(t+1):this.frameIndex(0)}}Ct.prototype.className="Sprite";tt(Ct);m.addGetterSetter(Ct,"animation");m.addGetterSetter(Ct,"animations");m.addGetterSetter(Ct,"frameOffsets");m.addGetterSetter(Ct,"image");m.addGetterSetter(Ct,"frameIndex",0,x());m.addGetterSetter(Ct,"frameRate",17,x());m.backCompat(Ct,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Gt extends k{_sceneFunc(t){const e=this.innerRadius(),i=this.outerRadius(),n=this.numPoints();t.beginPath(),t.moveTo(0,0-i);for(let s=1;s<n*2;s++){const a=s%2===0?i:e,o=a*Math.sin(s*Math.PI/n),l=-1*a*Math.cos(s*Math.PI/n);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)}}Gt.prototype.className="Star";Gt.prototype._centroid=!0;Gt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];tt(Gt);m.addGetterSetter(Gt,"numPoints",5,x());m.addGetterSetter(Gt,"innerRadius",0,x());m.addGetterSetter(Gt,"outerRadius",0,x());function Et(r){return[...r].reduce((t,e,i,n)=>{if(new RegExp("\\p{Emoji}","u").test(e)){const s=n[i+1];s&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(s)?(t.push(e+s),n[i+1]=""):t.push(e)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(e+(n[i+1]||""))?t.push(e+n[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 qt="auto",Qr="center",ss="inherit",re="justify",ta="Change.konva",ea="2d",sn="-",rs="left",ia="text",na="Text",sa="top",ra="bottom",rn="middle",as="normal",aa="px ",De=" ",oa="right",an="rtl",la="word",ha="char",on="none",ii="…",os=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],ca=os.length;function da(r){return r.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 ni(){return Ge||(Ge=C.createCanvasElement().getContext(ea),Ge)}function ua(r){r.fillText(this._partialText,this._partialTextX,this._partialTextY)}function fa(r){r.setAttr("miterLimit",2),r.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function ga(r){return r=r||{},!r.fillLinearGradientColorStops&&!r.fillRadialGradientColorStops&&!r.fillPatternImage&&(r.fill=r.fill||"black"),r}class Q extends k{constructor(t){super(ga(t)),this._partialTextX=0,this._partialTextY=0;for(let e=0;e<ca;e++)this.on(os[e]+ta,this._setTextData);this._setTextData()}_sceneFunc(t){var e,i;const n=this.textArr,s=n.length;if(!this.text())return;let a=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,h=this.verticalAlign(),c=this.direction(),d=0,u=this.align(),p=this.getWidth(),g=this.letterSpacing(),y=this.charRenderFunc(),T=this.fill(),S=this.textDecoration(),v=this.underlineOffset(),b=S.indexOf("underline")!==-1,w=S.indexOf("line-through")!==-1,L;c=c===ss?t.direction:c;let P=l/2,I=rn;if(!E.legacyTextRendering){const A=this.measureSize("M");I="alphabetic";const G=(e=A.fontBoundingBoxAscent)!==null&&e!==void 0?e:A.actualBoundingBoxAscent,z=(i=A.fontBoundingBoxDescent)!==null&&i!==void 0?i:A.actualBoundingBoxDescent;P=(G-z)/2+l/2}for(c===an&&t.setAttr("direction",c),t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",I),t.setAttr("textAlign",rs),h===rn?d=(this.getHeight()-s*l-a*2)/2:h===ra&&(d=this.getHeight()-s*l-a*2),t.translate(a,d+a),L=0;L<s;L++){let A=0,G=0;const z=n[L],V=z.text,B=z.width,W=z.lastInParagraph;if(t.save(),u===oa?A+=p-B-a*2:u===Qr&&(A+=(p-B-a*2)/2),b){t.save(),t.beginPath();const H=v??(E.legacyTextRendering?Math.round(o/2):Math.round(o/4)),M=A,j=P+G+H;t.moveTo(M,j);const O=u===re&&!W?p-a*2:B;t.lineTo(M+Math.round(O),j),t.lineWidth=o/15;const q=this._getLinearGradient();t.strokeStyle=q||T,t.stroke(),t.restore()}const N=A;if(c!==an&&(g!==0||u===re||y)){const H=V.split(" ").length-1,M=Et(V);for(let j=0;j<M.length;j++){const O=M[j];if(O===" "&&!W&&u===re&&(A+=(p-a*2-B)/H),this._partialTextX=A,this._partialTextY=P+G,this._partialText=O,y){t.save();const nt=n.slice(0,L).reduce((et,ot)=>et+Et(ot.text).length,0),U=j+nt;y({char:O,index:U,x:A,y:P+G,lineIndex:L,column:j,isLastInLine:W,width:this.measureSize(O).width,context:t})}t.fillStrokeShape(this),y&&t.restore(),A+=this.measureSize(O).width+g}}else g!==0&&t.setAttr("letterSpacing",`${g}px`),this._partialTextX=A,this._partialTextY=P+G,this._partialText=V,t.fillStrokeShape(this);if(w){t.save(),t.beginPath();const H=E.legacyTextRendering?0:-Math.round(o/4),M=N;t.moveTo(M,P+G+H);const j=u===re&&!W?p-a*2:B;t.lineTo(M+Math.round(j),P+G+H),t.lineWidth=o/15;const O=this._getLinearGradient();t.strokeStyle=O||T,t.stroke(),t.restore()}t.restore(),s>1&&(P+=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(ia,e),this}getWidth(){return this.attrs.width===qt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===qt||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,n,s,a,o,l,h,c,d,u;let p=ni(),g=this.fontSize(),y;p.save(),p.font=this._getContextFont(),y=p.measureText(t),p.restore();const T=g/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:(n=y.actualBoundingBoxLeft)!==null&&n!==void 0?n:-7.421875*T,actualBoundingBoxRight:(s=y.actualBoundingBoxRight)!==null&&s!==void 0?s:75.732421875*T,alphabeticBaseline:(a=y.alphabeticBaseline)!==null&&a!==void 0?a: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:g}}_getContextFont(){return this.fontStyle()+De+this.fontVariant()+De+(this.fontSize()+aa)+da(this.fontFamily())}_addTextLine(t){this.align()===re&&(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 ni().measureText(t).width+e*i}_setTextData(){let t=this.text().split(`
|
|
15
|
-
`),e=+this.fontSize(),i=0,n=this.lineHeight()*e,s=this.attrs.width,a=this.attrs.height,o=s!==qt&&s!==void 0,l=a!==qt&&a!==void 0,h=this.padding(),c=s-h*2,d=a-h*2,u=0,p=this.wrap(),g=p!==on,y=p!==ha&&g,T=this.ellipsis();this.textArr=[],ni().font=this._getContextFont();const S=T?this._getTextWidth(ii):0;for(let v=0,b=t.length;v<b;++v){let w=t[v],L=this._getTextWidth(w);if(o&&L>c)for(;w.length>0;){let P=0,I=Et(w).length,A="",G=0;for(;P<I;){const z=P+I>>>1,V=Et(w),B=V.slice(0,z+1).join(""),W=this._getTextWidth(B);(T&&l&&u+n>d?W+S:W)<=c?(P=z+1,A=B,G=W):I=z}if(A){if(y){const B=Et(w),W=Et(A),N=B[W.length],H=N===De||N===sn;let M;if(H&&G<=c)M=W.length;else{const j=W.lastIndexOf(De),O=W.lastIndexOf(sn);M=Math.max(j,O)+1}M>0&&(P=M,A=B.slice(0,P).join(""),G=this._getTextWidth(A))}if(A=A.trimRight(),this._addTextLine(A),i=Math.max(i,G),u+=n,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(w=Et(w).slice(P).join("").trimLeft(),w.length>0&&(L=this._getTextWidth(w),L<=c)){this._addTextLine(w),u+=n,i=Math.max(i,L);break}}else break}else this._addTextLine(w),u+=n,i=Math.max(i,L),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+n>d)break}this.textHeight=e,this.textWidth=i}_shouldHandleEllipsis(t){const e=+this.fontSize(),i=this.lineHeight()*e,n=this.attrs.height,s=n!==qt&&n!==void 0,a=this.padding(),o=n-a*2;return!(this.wrap()!==on)||s&&t+i>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,e=t!==qt&&t!==void 0,i=this.padding(),n=t-i*2,s=this.ellipsis(),a=this.textArr[this.textArr.length-1];!a||!s||(e&&(this._getTextWidth(a.text+ii)<n||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+ii))}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()}}Q.prototype._fillFunc=ua;Q.prototype._strokeFunc=fa;Q.prototype.className=na;Q.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];tt(Q);m.overWriteSetter(Q,"width",Li());m.overWriteSetter(Q,"height",Li());m.addGetterSetter(Q,"direction",ss);m.addGetterSetter(Q,"fontFamily","Arial");m.addGetterSetter(Q,"fontSize",12,x());m.addGetterSetter(Q,"fontStyle",as);m.addGetterSetter(Q,"fontVariant",as);m.addGetterSetter(Q,"padding",0,x());m.addGetterSetter(Q,"align",rs);m.addGetterSetter(Q,"verticalAlign",sa);m.addGetterSetter(Q,"lineHeight",1,x());m.addGetterSetter(Q,"wrap",la);m.addGetterSetter(Q,"ellipsis",!1,ft());m.addGetterSetter(Q,"letterSpacing",0,x());m.addGetterSetter(Q,"text","",Vt());m.addGetterSetter(Q,"textDecoration","");m.addGetterSetter(Q,"underlineOffset",void 0,x());m.addGetterSetter(Q,"charRenderFunc",void 0);const pa="",ls="normal";function hs(r){r.fillText(this.partialText,0,0)}function cs(r){r.strokeText(this.partialText,0,0)}class st extends k{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 J.getPathLength(this.dataArray)}_getPointAtLength(t){if(!this.attrs.data)return null;const e=this.pathLength;return t>e?null:J.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=J.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(),n=this.fontSize(),s=this.glyphInfo,a=e.indexOf("underline")!==-1,o=e.indexOf("line-through")!==-1;a&&t.beginPath();for(let l=0;l<s.length;l++){t.save();const h=s[l].p0;t.translate(h.x,h.y),t.rotate(s[l].rotation),this.partialText=s[l].text,t.fillStrokeShape(this),a&&(l===0&&t.moveTo(0,n/2+1),t.lineTo(s[l].width,n/2+1)),t.restore()}if(a&&(t.strokeStyle=i,t.lineWidth=n/20,t.stroke()),o){t.beginPath();for(let l=0;l<s.length;l++){t.save();const h=s[l].p0;t.translate(h.x,h.y),t.rotate(s[l].rotation),l===0&&t.moveTo(0,0),t.lineTo(s[l].width,0),t.restore()}t.strokeStyle=i,t.lineWidth=n/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 n=e[i].p1;t.lineTo(n.x,n.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 Q.prototype.setText.call(this,t)}_getContextFont(){return Q.prototype._getContextFont.call(this)}_getTextSize(t){const i=this.dummyCanvas.getContext("2d");i.save(),i.font=this._getContextFont();const n=i.measureText(t);return i.restore(),{width:n.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const t=Et(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:n}=this._getTextSize(this.attrs.text);if(this.textWidth=i,this.textHeight=n,this.glyphInfo=[],!this.attrs.data)return null;const s=this.letterSpacing(),a=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*s,0);let h=0;a==="center"&&(h=Math.max(0,this.pathLength/2-l/2)),a==="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 g=e[d].width+s;if(p===" "&&a==="justify"){const w=this.text().split(" ").length-1;g+=(this.pathLength-l)/w}const y=this._getPointAtLength(c+g);if(!y)return;const T=J.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=J.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+=g}}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,n=t[1]||0,s=t[1]||0,a,o;for(let h=0;h<t.length/2;h++)a=t[h*2],o=t[h*2+1],e=Math.min(e,a),i=Math.max(i,a),n=Math.min(n,o),s=Math.max(s,o);const l=this.fontSize();return{x:e-l/2,y:n-l/2,width:i-e+l,height:s-n+l}}destroy(){return C.releaseCanvas(this.dummyCanvas),super.destroy()}}st.prototype._fillFunc=hs;st.prototype._strokeFunc=cs;st.prototype._fillFuncHit=hs;st.prototype._strokeFuncHit=cs;st.prototype.className="TextPath";st.prototype._attrsAffectingSize=["text","fontSize","data"];tt(st);m.addGetterSetter(st,"data");m.addGetterSetter(st,"fontFamily","Arial");m.addGetterSetter(st,"fontSize",12,x());m.addGetterSetter(st,"fontStyle",ls);m.addGetterSetter(st,"align","left");m.addGetterSetter(st,"letterSpacing",0,x());m.addGetterSetter(st,"textBaseline","middle");m.addGetterSetter(st,"fontVariant",ls);m.addGetterSetter(st,"text",pa);m.addGetterSetter(st,"textDecoration","");m.addGetterSetter(st,"kerningFunc",void 0);const ds="tr-konva",ma=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(r=>r+`.${ds}`).join(" "),ln="nodesRect",ya=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Sa={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Ca="ontouchstart"in E._global;function Ta(r,t,e){if(r==="rotater")return e;t+=C.degToRad(Sa[r]||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 Ue=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function va(r){return{x:r.x+r.width/2*Math.cos(r.rotation)+r.height/2*Math.sin(-r.rotation),y:r.y+r.height/2*Math.cos(r.rotation)+r.width/2*Math.sin(r.rotation)}}function us(r,t,e){const i=e.x+(r.x-e.x)*Math.cos(t)-(r.y-e.y)*Math.sin(t),n=e.y+(r.x-e.x)*Math.sin(t)+(r.y-e.y)*Math.cos(t);return{...r,rotation:r.rotation+t,x:i,y:n}}function ba(r,t){const e=va(r);return us(r,t,e)}function wa(r,t,e){let i=t;for(let n=0;n<r.length;n++){const s=E.getAngle(r[n]),a=Math.abs(s-t)%(Math.PI*2);Math.min(a,Math.PI*2-a)<e&&(i=s)}return i}let vi=0;class F extends Qt{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(ma,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 ds+this._id}setNodes(t=[]){this._nodes&&this._nodes.length&&this.detach();const e=t.filter(n=>n.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(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 a=n._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");n.on(a,s)}n.on(ya.map(a=>a+`.${this._getEventNamespace()}`).join(" "),s),n.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(n)}),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 n=t.getAbsolutePosition(),s=n.x-e.x,a=n.y-e.y;this.nodes().forEach(o=>{if(o===t||o.isDragging())return;const l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+s,y:l.y+a}),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(ln),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(ln,this.__getNodeRect)}__getNodeShape(t,e=this.rotation(),i){const n=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=t.getAbsoluteScale(i),a=t.getAbsolutePosition(i),o=n.x*s.x-t.offsetX()*s.x,l=n.y*s.y-t.offsetY()*s.y,h=(E.getAngle(t.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),c={x:a.x+o*Math.cos(h)+l*Math.sin(-h),y:a.y+l*Math.cos(h)+o*Math.sin(h),width:n.width*s.x,height:n.height*s.y,rotation:h};return us(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 g=u.point(p);e.push(g)})});const i=new ht;i.rotate(-E.getAngle(this.rotation()));let n=1/0,s=1/0,a=-1/0,o=-1/0;e.forEach(function(h){const c=i.point(h);n===void 0&&(n=a=c.x,s=o=c.y),n=Math.min(n,c.x),s=Math.min(s,c.y),a=Math.max(a,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:a-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(),Ue.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater")}_createAnchor(t){const e=new ke({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Ca?10:"auto"}),i=this;e.on("mousedown touchstart",function(n){i._handleMouseDown(n)}),e.on("dragstart",n=>{e.stopDrag(),n.cancelBubble=!0}),e.on("dragend",n=>{n.cancelBubble=!0}),e.on("mouseenter",()=>{const n=E.getAngle(this.rotation()),s=this.rotateAnchorCursor(),a=Ta(t,n,s);e.getStage().content&&(e.getStage().content.style.cursor=a),this._cursorChange=!0}),e.on("mouseout",()=>{e.getStage().content&&(e.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(e)}_createBack(){const t=new k({name:"back",width:0,height:0,sceneFunc(e,i){const n=i.getParent(),s=n.padding(),a=i.width(),o=i.height();if(e.beginPath(),e.rect(-s,-s,a+s*2,o+s*2),n.rotateEnabled()&&n.rotateLineVisible()){const l=n.rotateAnchorAngle(),h=n.rotateAnchorOffset(),c=C.degToRad(l),d=Math.sin(c),u=-Math.cos(c),p=a/2,g=o/2;let y=1/0;u<0?y=Math.min(y,-g/u):u>0&&(y=Math.min(y,(o-g)/u)),d<0?y=Math.min(y,-p/d):d>0&&(y=Math.min(y,(a-p)/d));const T=p+d*y,S=g+u*y,v=C._sign(o),b=T+d*h*v,w=S+u*h*v;e.moveTo(T,S),e.lineTo(b,w)}e.fillStrokeShape(i)},hitFunc:(e,i)=>{if(!this.shouldOverdrawWholeArea())return;const n=this.padding();e.beginPath(),e.rect(-n,-n,i.width()+n*2,i.height()+n*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,n=e.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 a=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-a.x,y:o.y-a.y},vi++,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,n;const s=this.findOne("."+this._movingAnchorName),a=s.getStage();a.setPointersPositions(t);const o=a.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,t)),s.setAbsolutePosition(l);const c=s.getAbsolutePosition();if(h.x===c.x&&h.y===c.y)return;if(this._movingAnchorName==="rotater"){const v=this._getNodeRect();e=s.x()-v.width/2,i=-s.y()+v.height/2;const b=E.getAngle(this.rotateAnchorAngle());let w=Math.atan2(-i,e)+Math.PI/2-b;v.height<0&&(w-=Math.PI);const P=E.getAngle(this.rotation())+w,I=E.getAngle(this.rotationSnapTolerance()),G=wa(this.rotationSnaps(),P,I)-v.rotation,z=ba(v,G);this._fitNodesInto(z,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()};n=Math.sqrt(Math.pow(v.x-s.x(),2)+Math.pow(v.y-s.y(),2));const b=this.findOne(".top-left").x()>v.x?-1:1,w=this.findOne(".top-left").y()>v.y?-1:1;e=n*this.cos*b,i=n*this.sin*w,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(s.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()};n=Math.sqrt(Math.pow(s.x()-v.x,2)+Math.pow(v.y-s.y(),2));const b=this.findOne(".top-right").x()<v.x?-1:1,w=this.findOne(".top-right").y()>v.y?-1:1;e=n*this.cos*b,i=n*this.sin*w,this.findOne(".top-right").x(v.x+e),this.findOne(".top-right").y(v.y-i)}var g=s.position();this.findOne(".top-left").y(g.y),this.findOne(".bottom-right").x(g.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 v=p?{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(v.x-s.x(),2)+Math.pow(s.y()-v.y,2));const b=v.x<s.x()?-1:1,w=s.y()<v.y?-1:1;e=n*this.cos*b,i=n*this.sin*w,s.x(v.x-e),s.y(v.y+i)}g=s.position(),this.findOne(".top-left").x(g.x),this.findOne(".bottom-right").y(g.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.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()};n=Math.sqrt(Math.pow(s.x()-v.x,2)+Math.pow(s.y()-v.y,2));const b=this.findOne(".bottom-right").x()<v.x?-1:1,w=this.findOne(".bottom-right").y()<v.y?-1:1;e=n*this.cos*b,i=n*this.sin*w,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"),w=v.x(),L=v.y(),P=this.getWidth()-b.x(),I=this.getHeight()-b.y();b.move({x:-w,y:-L}),v.move({x:P,y:I})}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();vi--,this._fire("transformend",{evt:t,target:i}),(e=this.getLayer())===null||e===void 0||e.batchDraw(),i&&this._nodes.forEach(n=>{var s;n._fire("transformend",{evt:t,target:n}),(s=n.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,e){const i=this._getNodeRect(),n=1;if(C._inRange(t.width,-this.padding()*2-n,n)){this.update();return}if(C._inRange(t.height,-this.padding()*2-n,n)){this.update();return}const s=new ht;if(s.rotate(E.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const u=s.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=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,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const u=s.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=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,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 a=1e7,o=new ht;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/a,i.height/a);const l=new ht,h=t.width/a,c=t.height/a;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 g=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const T=new ht;T.multiply(g.copy().invert()).multiply(d).multiply(g).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,n=e.height,s=this.enabledAnchors(),a=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),h=this.find("._anchor");h.forEach(P=>{P.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:a&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:a&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:a&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:n/2,offsetX:l/2+o,visible:a&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:n/2,offsetX:l/2-o,visible:a&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:n,offsetX:l/2+o,offsetY:l/2-o,visible:a&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:n,offsetY:l/2-o,visible:a&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:n,offsetX:l/2-o,offsetY:l/2-o,visible:a&&s.indexOf("bottom-right")>=0});const c=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=C.degToRad(c),p=Math.sin(u),g=-Math.cos(u),y=i/2,T=n/2;let S=1/0;g<0?S=Math.min(S,-T/g):g>0&&(S=Math.min(S,(n-T)/g)),p<0?S=Math.min(S,-y/p):p>0&&(S=Math.min(S,(i-y)/p));const v=y+p*S,b=T+g*S,w=C._sign(n);this._batchChangeChild(".rotater",{x:v+p*d*w,y:b+g*d*w-o*g,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(P=>P.draggable()),x:0,y:0});const L=this.anchorStyleFunc();L&&h.forEach(P=>{L(P)}),(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=""),Qt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return _.prototype.toObject.call(this)}clone(t){return _.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}F.isTransforming=()=>vi>0;function ka(r){return r instanceof Array||C.warn("enabledAnchors value should be an array"),r instanceof Array&&r.forEach(function(t){Ue.indexOf(t)===-1&&C.warn("Unknown anchor name: "+t+". Available names are: "+Ue.join(", "))}),r||[]}F.prototype.className="Transformer";tt(F);m.addGetterSetter(F,"enabledAnchors",Ue,ka);m.addGetterSetter(F,"flipEnabled",!0,ft());m.addGetterSetter(F,"resizeEnabled",!0);m.addGetterSetter(F,"anchorSize",10,x());m.addGetterSetter(F,"rotateEnabled",!0);m.addGetterSetter(F,"rotateLineVisible",!0);m.addGetterSetter(F,"rotationSnaps",[]);m.addGetterSetter(F,"rotateAnchorOffset",50,x());m.addGetterSetter(F,"rotateAnchorAngle",0,x());m.addGetterSetter(F,"rotateAnchorCursor","crosshair");m.addGetterSetter(F,"rotationSnapTolerance",5,x());m.addGetterSetter(F,"borderEnabled",!0);m.addGetterSetter(F,"anchorStroke","rgb(0, 161, 255)");m.addGetterSetter(F,"anchorStrokeWidth",1,x());m.addGetterSetter(F,"anchorFill","white");m.addGetterSetter(F,"anchorCornerRadius",0,x());m.addGetterSetter(F,"borderStroke","rgb(0, 161, 255)");m.addGetterSetter(F,"borderStrokeWidth",1,x());m.addGetterSetter(F,"borderDash");m.addGetterSetter(F,"keepRatio",!0);m.addGetterSetter(F,"shiftBehavior","default");m.addGetterSetter(F,"centeredScaling",!1);m.addGetterSetter(F,"ignoreStroke",!1);m.addGetterSetter(F,"padding",0,x());m.addGetterSetter(F,"nodes");m.addGetterSetter(F,"node");m.addGetterSetter(F,"boundBoxFunc");m.addGetterSetter(F,"anchorDragBoundFunc");m.addGetterSetter(F,"anchorStyleFunc");m.addGetterSetter(F,"shouldOverdrawWholeArea",!1);m.addGetterSetter(F,"useSingleNodeRotation",!0);m.backCompat(F,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Pt extends k{_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)}}Pt.prototype.className="Wedge";Pt.prototype._centroid=!0;Pt.prototype._attrsAffectingSize=["radius"];tt(Pt);m.addGetterSetter(Pt,"radius",0,x());m.addGetterSetter(Pt,"angle",0,x());m.addGetterSetter(Pt,"clockwise",!1);m.backCompat(Pt,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function hn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const _a=[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],Pa=[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 xa(r,t){const e=r.data,i=r.width,n=r.height;let s,a,o,l,h,c,d,u,p,g,y,T,S,v,b,w,L,P,I,A;const G=t+t+1,z=i-1,V=n-1,B=t+1,W=B*(B+1)/2,N=new hn,H=_a[t],M=Pa[t];let j=null,O=N,q=null,nt=null;for(let U=1;U<G;U++)O=O.next=new hn,U===B&&(j=O);O.next=N,o=a=0;for(let U=0;U<n;U++){T=S=v=b=l=h=c=d=0,u=B*(w=e[a]),p=B*(L=e[a+1]),g=B*(P=e[a+2]),y=B*(I=e[a+3]),l+=W*w,h+=W*L,c+=W*P,d+=W*I,O=N;for(let et=0;et<B;et++)O.r=w,O.g=L,O.b=P,O.a=I,O=O.next;for(let et=1;et<B;et++)s=a+((z<et?z:et)<<2),l+=(O.r=w=e[s])*(A=B-et),h+=(O.g=L=e[s+1])*A,c+=(O.b=P=e[s+2])*A,d+=(O.a=I=e[s+3])*A,T+=w,S+=L,v+=P,b+=I,O=O.next;q=N,nt=j;for(let et=0;et<i;et++)e[a+3]=I=d*H>>M,I!==0?(I=255/I,e[a]=(l*H>>M)*I,e[a+1]=(h*H>>M)*I,e[a+2]=(c*H>>M)*I):e[a]=e[a+1]=e[a+2]=0,l-=u,h-=p,c-=g,d-=y,u-=q.r,p-=q.g,g-=q.b,y-=q.a,s=o+((s=et+t+1)<z?s:z)<<2,T+=q.r=e[s],S+=q.g=e[s+1],v+=q.b=e[s+2],b+=q.a=e[s+3],l+=T,h+=S,c+=v,d+=b,q=q.next,u+=w=nt.r,p+=L=nt.g,g+=P=nt.b,y+=I=nt.a,T-=w,S-=L,v-=P,b-=I,nt=nt.next,a+=4;o+=i}for(let U=0;U<i;U++){S=v=b=T=h=c=d=l=0,a=U<<2,u=B*(w=e[a]),p=B*(L=e[a+1]),g=B*(P=e[a+2]),y=B*(I=e[a+3]),l+=W*w,h+=W*L,c+=W*P,d+=W*I,O=N;for(let ot=0;ot<B;ot++)O.r=w,O.g=L,O.b=P,O.a=I,O=O.next;let et=i;for(let ot=1;ot<=t;ot++)a=et+U<<2,l+=(O.r=w=e[a])*(A=B-ot),h+=(O.g=L=e[a+1])*A,c+=(O.b=P=e[a+2])*A,d+=(O.a=I=e[a+3])*A,T+=w,S+=L,v+=P,b+=I,O=O.next,ot<V&&(et+=i);a=U,q=N,nt=j;for(let ot=0;ot<n;ot++)s=a<<2,e[s+3]=I=d*H>>M,I>0?(I=255/I,e[s]=(l*H>>M)*I,e[s+1]=(h*H>>M)*I,e[s+2]=(c*H>>M)*I):e[s]=e[s+1]=e[s+2]=0,l-=u,h-=p,c-=g,d-=y,u-=q.r,p-=q.g,g-=q.b,y-=q.a,s=U+((s=ot+B)<V?s:V)*i<<2,l+=T+=q.r=e[s],h+=S+=q.g=e[s+1],c+=v+=q.b=e[s+2],d+=b+=q.a=e[s+3],q=q.next,u+=w=nt.r,p+=L=nt.g,g+=P=nt.b,y+=I=nt.a,T-=w,S-=L,v-=P,b-=I,nt=nt.next,a+=i}}const Ea=function(t){const e=Math.round(this.blurRadius());e>0&&xa(t,e)};m.addGetterSetter(_,"blurRadius",0,x(),m.afterSetFilter);const Aa=function(r){const t=this.brightness()*255,e=r.data,i=e.length;for(let n=0;n<i;n+=4)e[n]+=t,e[n+1]+=t,e[n+2]+=t};m.addGetterSetter(_,"brightness",0,x(),m.afterSetFilter);const La=function(r){const t=this.brightness(),e=r.data,i=e.length;for(let n=0;n<i;n+=4)e[n]=Math.min(255,e[n]*t),e[n+1]=Math.min(255,e[n+1]*t),e[n+2]=Math.min(255,e[n+2]*t)},Ma=function(r){const t=Math.pow((this.contrast()+100)/100,2),e=r.data,i=e.length;let n=150,s=150,a=150;for(let o=0;o<i;o+=4)n=e[o],s=e[o+1],a=e[o+2],n/=255,n-=.5,n*=t,n+=.5,n*=255,s/=255,s-=.5,s*=t,s+=.5,s*=255,a/=255,a-=.5,a*=t,a+=.5,a*=255,n=n<0?0:n>255?255:n,s=s<0?0:s>255?255:s,a=a<0?0:a>255?255:a,e[o]=n,e[o+1]=s,e[o+2]=a};m.addGetterSetter(_,"contrast",0,x(),m.afterSetFilter);const Ra=function(r){var t,e,i,n,s,a,o,l,h;const c=r.data,d=r.width,u=r.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)),g=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)),T=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(a=(s=this.embossDirection)===null||s===void 0?void 0:s.call(this))!==null&&a!==void 0?a:"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=g*255,w=T*Math.PI/180,L=Math.cos(w),P=Math.sin(w),I=128/1020*v,A=new Uint8ClampedArray(c),G=new Float32Array(d*u);for(let N=0,H=0;H<c.length;H+=4,N++)G[N]=.2126*A[H]+.7152*A[H+1]+.0722*A[H+2];const z=[-1,0,1,-2,0,2,-1,0,1],V=[-1,-2,-1,0,0,0,1,2,1],B=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],W=N=>N<0?0:N>255?255:N;for(let N=1;N<u-1;N++)for(let H=1;H<d-1;H++){const M=N*d+H;let j=0,O=0;j+=G[M+B[0]]*z[0],O+=G[M+B[0]]*V[0],j+=G[M+B[1]]*z[1],O+=G[M+B[1]]*V[1],j+=G[M+B[2]]*z[2],O+=G[M+B[2]]*V[2],j+=G[M+B[3]]*z[3],O+=G[M+B[3]]*V[3],j+=G[M+B[5]]*z[5],O+=G[M+B[5]]*V[5],j+=G[M+B[6]]*z[6],O+=G[M+B[6]]*V[6],j+=G[M+B[7]]*z[7],O+=G[M+B[7]]*V[7],j+=G[M+B[8]]*z[8],O+=G[M+B[8]]*V[8];const q=L*j+P*O,nt=W(b+q*I),U=M*4;if(S){const et=nt-b;c[U]=W(A[U]+et),c[U+1]=W(A[U+1]+et),c[U+2]=W(A[U+2]+et),c[U+3]=A[U+3]}else c[U]=c[U+1]=c[U+2]=nt,c[U+3]=A[U+3]}for(let N=0;N<d;N++){let H=N*4,M=((u-1)*d+N)*4;c[H]=A[H],c[H+1]=A[H+1],c[H+2]=A[H+2],c[H+3]=A[H+3],c[M]=A[M],c[M+1]=A[M+1],c[M+2]=A[M+2],c[M+3]=A[M+3]}for(let N=1;N<u-1;N++){let H=N*d*4,M=(N*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[M]=A[M],c[M+1]=A[M+1],c[M+2]=A[M+2],c[M+3]=A[M+3]}return r};m.addGetterSetter(_,"embossStrength",.5,x(),m.afterSetFilter);m.addGetterSetter(_,"embossWhiteLevel",.5,x(),m.afterSetFilter);m.addGetterSetter(_,"embossDirection","top-left",void 0,m.afterSetFilter);m.addGetterSetter(_,"embossBlend",!1,void 0,m.afterSetFilter);function si(r,t,e,i,n){const s=e-t,a=n-i;if(s===0)return i+a/2;if(a===0)return i;let o=(r-t)/s;return o=a*o+i,o}const Ia=function(r){const t=r.data,e=t.length;let i=t[0],n=i,s,a=t[1],o=a,l,h=t[2],c=h,d;const u=this.enhance();if(u===0)return;for(let b=0;b<e;b+=4)s=t[b+0],s<i?i=s:s>n&&(n=s),l=t[b+1],l<a?a=l:l>o&&(o=l),d=t[b+2],d<h?h=d:d>c&&(c=d);n===i&&(n=255,i=0),o===a&&(o=255,a=0),c===h&&(c=255,h=0);let p,g,y,T,S,v;if(u>0)p=n+u*(255-n),g=i-u*(i-0),y=o+u*(255-o),T=a-u*(a-0),S=c+u*(255-c),v=h-u*(h-0);else{const b=(n+i)*.5;p=n+u*(n-b),g=i+u*(i-b);const w=(o+a)*.5;y=o+u*(o-w),T=a+u*(a-w);const L=(c+h)*.5;S=c+u*(c-L),v=h+u*(h-L)}for(let b=0;b<e;b+=4)t[b+0]=si(t[b+0],i,n,g,p),t[b+1]=si(t[b+1],a,o,T,y),t[b+2]=si(t[b+2],h,c,v,S)};m.addGetterSetter(_,"enhance",0,x(),m.afterSetFilter);const Da=function(r){const t=r.data,e=t.length;for(let i=0;i<e;i+=4){const n=.34*t[i]+.5*t[i+1]+.16*t[i+2];t[i]=n,t[i+1]=n,t[i+2]=n}};m.addGetterSetter(_,"hue",0,x(),m.afterSetFilter);m.addGetterSetter(_,"saturation",0,x(),m.afterSetFilter);m.addGetterSetter(_,"luminance",0,x(),m.afterSetFilter);const Ga=function(r){const t=r.data,e=t.length,i=1,n=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=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,p=.587*i+.413*o+.035*l,g=.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,w,L;for(let P=0;P<e;P+=4)v=t[P+0],b=t[P+1],w=t[P+2],L=t[P+3],t[P+0]=h*v+c*b+d*w+a,t[P+1]=u*v+p*b+g*w+a,t[P+2]=y*v+T*b+S*w+a,t[P+3]=L},Oa=function(r){const t=r.data,e=t.length,i=Math.pow(2,this.value()),n=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=i*n*Math.cos(s*Math.PI/180),o=i*n*Math.sin(s*Math.PI/180),l=.299*i+.701*a+.167*o,h=.587*i-.587*a+.33*o,c=.114*i-.114*a-.497*o,d=.299*i-.299*a-.328*o,u=.587*i+.413*a+.035*o,p=.114*i-.114*a+.293*o,g=.299*i-.3*a+1.25*o,y=.587*i-.586*a-1.05*o,T=.114*i+.886*a-.2*o;for(let S=0;S<e;S+=4){const v=t[S+0],b=t[S+1],w=t[S+2],L=t[S+3];t[S+0]=l*v+h*b+c*w,t[S+1]=d*v+u*b+p*w,t[S+2]=g*v+y*b+T*w,t[S+3]=L}};m.addGetterSetter(_,"hue",0,x(),m.afterSetFilter);m.addGetterSetter(_,"saturation",0,x(),m.afterSetFilter);m.addGetterSetter(_,"value",0,x(),m.afterSetFilter);const Ba=function(r){const t=r.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]},Ha=function(r,t,e){const i=r.data,n=t.data,s=r.width,a=r.height,o=e.polarCenterX||s/2,l=e.polarCenterY||a/2;let h=Math.sqrt(o*o+l*l),c=s-o,d=a-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const p=a,g=s,y=360/g*Math.PI/180;for(let T=0;T<g;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 w=(d*s+c)*4;const L=i[w+0],P=i[w+1],I=i[w+2],A=i[w+3];w=(T+b*s)*4,n[w+0]=L,n[w+1]=P,n[w+2]=I,n[w+3]=A}}},za=function(r,t,e){const i=r.data,n=t.data,s=r.width,a=r.height,o=e.polarCenterX||s/2,l=e.polarCenterY||a/2;let h=Math.sqrt(o*o+l*l),c=s-o,d=a-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const p=a,g=s,y=0;let T,S;for(c=0;c<s;c+=1)for(d=0;d<a;d+=1){const v=c-o,b=d-l,w=Math.sqrt(v*v+b*b)*p/h;let L=(Math.atan2(b,v)*180/Math.PI+360+y)%360;L=L*g/360,T=Math.floor(L),S=Math.floor(w);let P=(S*s+T)*4;const I=i[P+0],A=i[P+1],G=i[P+2],z=i[P+3];P=(d*s+c)*4,n[P+0]=I,n[P+1]=A,n[P+2]=G,n[P+3]=z}},Na=function(r){const t=r.width,e=r.height;let i,n,s,a,o,l,h,c,d,u,p=Math.round(this.kaleidoscopePower());const g=Math.round(this.kaleidoscopeAngle()),y=Math.floor(t*(g%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),Ha(r,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,w=0,L=b,P=1;for(y+v>t&&(w=b,L=0,P=-1),n=0;n<e;n+=1)for(i=w;i!==L;i+=P)s=Math.round(i+y)%t,d=(t*n+s)*4,o=S.data[d+0],l=S.data[d+1],h=S.data[d+2],c=S.data[d+3],u=(t*n+i)*4,S.data[u+0]=o,S.data[u+1]=l,S.data[u+2]=h,S.data[u+3]=c;for(n=0;n<e;n+=1)for(b=Math.floor(v),a=0;a<p;a+=1){for(i=0;i<b+1;i+=1)d=(t*n+i)*4,o=S.data[d+0],l=S.data[d+1],h=S.data[d+2],c=S.data[d+3],u=(t*n+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}za(S,r,{})};m.addGetterSetter(_,"kaleidoscopePower",2,x(),m.afterSetFilter);m.addGetterSetter(_,"kaleidoscopeAngle",0,x(),m.afterSetFilter);function Oe(r,t,e){let i=(e*r.width+t)*4;const n=[];return n.push(r.data[i++],r.data[i++],r.data[i++],r.data[i++]),n}function ae(r,t){return Math.sqrt(Math.pow(r[0]-t[0],2)+Math.pow(r[1]-t[1],2)+Math.pow(r[2]-t[2],2))}function Fa(r){const t=[0,0,0];for(let e=0;e<r.length;e++)t[0]+=r[e][0],t[1]+=r[e][1],t[2]+=r[e][2];return t[0]/=r.length,t[1]/=r.length,t[2]/=r.length,t}function Va(r,t){const e=Oe(r,0,0),i=Oe(r,r.width-1,0),n=Oe(r,0,r.height-1),s=Oe(r,r.width-1,r.height-1),a=t||10;if(ae(e,i)<a&&ae(i,s)<a&&ae(s,n)<a&&ae(n,e)<a){const o=Fa([i,e,s,n]),l=[];for(let h=0;h<r.width*r.height;h++){const c=ae(o,[r.data[h*4],r.data[h*4+1],r.data[h*4+2]]);l[h]=c<a?0:255}return l}}function Wa(r,t){for(let e=0;e<r.width*r.height;e++)r.data[4*e+3]=t[e]}function Ya(r,t,e){const i=[1,1,1,1,0,1,1,1,1],n=Math.round(Math.sqrt(i.length)),s=Math.floor(n/2),a=[];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<n;d++)for(let u=0;u<n;u++){const p=o+d-s,g=l+u-s;if(p>=0&&p<e&&g>=0&&g<t){const y=p*t+g,T=i[d*n+u];c+=r[y]*T}}a[h]=c===255*8?255:0}return a}function Xa(r,t,e){const i=[1,1,1,1,1,1,1,1,1],n=Math.round(Math.sqrt(i.length)),s=Math.floor(n/2),a=[];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<n;d++)for(let u=0;u<n;u++){const p=o+d-s,g=l+u-s;if(p>=0&&p<e&&g>=0&&g<t){const y=p*t+g,T=i[d*n+u];c+=r[y]*T}}a[h]=c>=255*4?255:0}return a}function Ua(r,t,e){const i=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],n=Math.round(Math.sqrt(i.length)),s=Math.floor(n/2),a=[];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<n;d++)for(let u=0;u<n;u++){const p=o+d-s,g=l+u-s;if(p>=0&&p<e&&g>=0&&g<t){const y=p*t+g,T=i[d*n+u];c+=r[y]*T}}a[h]=c}return a}const $a=function(r){const t=this.threshold();let e=Va(r,t);return e&&(e=Ya(e,r.width,r.height),e=Xa(e,r.width,r.height),e=Ua(e,r.width,r.height),Wa(r,e)),r};m.addGetterSetter(_,"threshold",0,x(),m.afterSetFilter);const qa=function(r){const t=this.noise()*255,e=r.data,i=e.length,n=t/2;for(let s=0;s<i;s+=4)e[s+0]+=n-2*n*Math.random(),e[s+1]+=n-2*n*Math.random(),e[s+2]+=n-2*n*Math.random()};m.addGetterSetter(_,"noise",.2,x(),m.afterSetFilter);const Ka=function(r){let t=Math.ceil(this.pixelSize()),e=r.width,i=r.height,n=Math.ceil(e/t),s=Math.ceil(i/t),a=r.data;if(t<=0){C.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 p=o*t,g=p+t,y=l*t,T=y+t;let S=0;for(let v=p;v<g;v+=1)if(!(v>=e))for(let b=y;b<T;b+=1){if(b>=i)continue;const w=(e*b+v)*4;h+=a[w+0],c+=a[w+1],d+=a[w+2],u+=a[w+3],S+=1}h=h/S,c=c/S,d=d/S,u=u/S;for(let v=p;v<g;v+=1)if(!(v>=e))for(let b=y;b<T;b+=1){if(b>=i)continue;const w=(e*b+v)*4;a[w+0]=h,a[w+1]=c,a[w+2]=d,a[w+3]=u}}};m.addGetterSetter(_,"pixelSize",8,x(),m.afterSetFilter);const ja=function(r){const t=Math.round(this.levels()*254)+1,e=r.data,i=e.length,n=255/t;for(let s=0;s<i;s+=1)e[s]=Math.floor(e[s]/n)*n};m.addGetterSetter(_,"levels",.5,x(),m.afterSetFilter);const Za=function(r){const t=r.data,e=t.length,i=this.red(),n=this.green(),s=this.blue();for(let a=0;a<e;a+=4){const o=(.34*t[a]+.5*t[a+1]+.16*t[a+2])/255;t[a]=o*i,t[a+1]=o*n,t[a+2]=o*s,t[a+3]=t[a+3]}};m.addGetterSetter(_,"red",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)});m.addGetterSetter(_,"green",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)});m.addGetterSetter(_,"blue",0,Gn,m.afterSetFilter);const Ja=function(r){const t=r.data,e=t.length,i=this.red(),n=this.green(),s=this.blue(),a=this.alpha();for(let o=0;o<e;o+=4){const l=1-a;t[o]=i*a+t[o]*l,t[o+1]=n*a+t[o+1]*l,t[o+2]=s*a+t[o+2]*l}};m.addGetterSetter(_,"red",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)});m.addGetterSetter(_,"green",0,function(r){return this._filterUpToDate=!1,r>255?255:r<0?0:Math.round(r)});m.addGetterSetter(_,"blue",0,Gn,m.afterSetFilter);m.addGetterSetter(_,"alpha",1,function(r){return this._filterUpToDate=!1,r>1?1:r<0?0:r});const Qa=function(r){const t=r.data,e=t.length;for(let i=0;i<e;i+=4){const n=t[i+0],s=t[i+1],a=t[i+2];t[i+0]=Math.min(255,n*.393+s*.769+a*.189),t[i+1]=Math.min(255,n*.349+s*.686+a*.168),t[i+2]=Math.min(255,n*.272+s*.534+a*.131)}},to=function(r){const e=r.data;for(let i=0;i<e.length;i+=4){const n=e[i],s=e[i+1],a=e[i+2];.2126*n+.7152*s+.0722*a>=128&&(e[i]=255-n,e[i+1]=255-s,e[i+2]=255-a)}return r},eo=function(r){const t=this.threshold()*255,e=r.data,i=e.length;for(let n=0;n<i;n+=1)e[n]=e[n]<t?0:255};m.addGetterSetter(_,"threshold",.5,x(),m.afterSetFilter);const X=Zi.Util._assign(Zi,{Arc:kt,Arrow:Yt,Circle:te,Ellipse:It,Image:gt,Label:Ii,Tag:Xt,Line:_t,Path:J,Rect:ke,RegularPolygon:Dt,Ring:Ut,Sprite:Ct,Star:Gt,Text:Q,TextPath:st,Transformer:F,Wedge:Pt,Filters:{Blur:Ea,Brightness:La,Brighten:Aa,Contrast:Ma,Emboss:Ra,Enhance:Ia,Grayscale:Da,HSL:Ga,HSV:Oa,Invert:Ba,Kaleidoscope:Na,Mask:$a,Noise:qa,Pixelate:Ka,Posterize:ja,RGB:Za,RGBA:Ja,Sepia:Qa,Solarize:to,Threshold:eo}}),cn={debug:10,info:20,warn:30,error:40},Be={enabled:!0,level:"warn",moduleLevels:{}},dn=400;function io(r,t){return r.moduleLevels[t]??r.level}function Bt(r,t,e){if(!r.enabled)return!1;const i=io(r,e);return cn[t]>=cn[i]}function un(r){if(!r||typeof r!="object")return null;const t="clientX"in r||"clientY"in r,e="deltaX"in r||"deltaY"in r,i="shiftKey"in r||"metaKey"in r||"ctrlKey"in r||"altKey"in r;return!t&&!e&&!i?null:{type:typeof r.type=="string"?r.type:void 0,clientX:typeof r.clientX=="number"?r.clientX:void 0,clientY:typeof r.clientY=="number"?r.clientY:void 0,button:typeof r.button=="number"?r.button:void 0,buttons:typeof r.buttons=="number"?r.buttons:void 0,deltaX:typeof r.deltaX=="number"?r.deltaX:void 0,deltaY:typeof r.deltaY=="number"?r.deltaY:void 0,shiftKey:!!r.shiftKey,metaKey:!!r.metaKey,ctrlKey:!!r.ctrlKey,altKey:!!r.altKey}}function no(r){if(r===void 0)return;const t=un(r);if(t)return t;if(r&&typeof r=="object"&&"evt"in r){const e=un(r.evt);if(e)return{...r,evt:e}}return r}function so(r,t,e,i){const n=no(i);n===void 0?r(`${t} ${e}`):r(`${t} ${e}`,n)}class R{static setConfig(t){if(!t){this.config={...Be};return}this.config={enabled:t.enabled??Be.enabled,level:t.level??Be.level,moduleLevels:t.moduleLevels??{}}}static debug(t,e,i){Bt(this.config,"debug",t)&&this.emit("debug",t,e,i)}static debugLazy(t,e,i){if(!Bt(this.config,"debug",t))return;const n=e(),s=i?i():void 0;this.emit("debug",t,n,s)}static info(t,e,i){Bt(this.config,"info",t)&&this.emit("info",t,e,i)}static infoLazy(t,e,i){if(!Bt(this.config,"info",t))return;const n=e(),s=i?i():void 0;this.emit("info",t,n,s)}static warn(t,e,i){Bt(this.config,"warn",t)&&this.emit("warn",t,e,i)}static warnLazy(t,e,i){if(!Bt(this.config,"warn",t))return;const n=e(),s=i?i():void 0;this.emit("warn",t,n,s)}static error(t,e,i){Bt(this.config,"error",t)&&this.emit("error",t,e,i)}static setDedupeWindowMs(t){this.dedupeWindowMs=Number.isFinite(t)&&t>=0?t:dn}static emit(t,e,i,n){const s=Date.now(),a=`${t}:${e}:${i}`,o=this.dedupeState.get(a);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(a,{lastPrintedAt:s,suppressed:0});const c=`[${t.toUpperCase()}] [${e}]`,d=this.resolveConsoleMethod(t);so(d,c,h,n)}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)}}f(R,"config",{...Be}),f(R,"dedupeWindowMs",dn),f(R,"dedupeState",new Map);class mt{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={}}static renderClipCovers(t,e,i,n,s,a=!1){R.debugLazy("ClipCoverRenderer",()=>"renderClipCovers",()=>({videoSrc:s,coverCount:(e==null?void 0:e.length)??0,coverWidth:i,coverHeight:n}));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(),a||this.requestRender(t);return}const l=this.buildSegmentsDataSync(e,i,n,s);if(l){this.renderSegments(t,l,i,n),a||this.requestRender(t);return}a||(t.destroyChildren(),this.requestRender(t)),this.startRenderJob({coversGroup:t,coverSource:e,coverWidth:i,coverHeight:n,videoSrc:s,version:o})}static async startRenderJob(t){const{coversGroup:e,coverSource:i,coverWidth:n,coverHeight:s,videoSrc:a,version:o}=t,l=await this.buildSegmentsData(i,n,s,a);if(this.isRenderJobCurrent(e,o)){if(this.renderSegments(e,l,n,s),!this.isRenderJobCurrent(e,o)){e.destroyChildren();return}this.requestRender(e)}}static async buildSegmentsData(t,e,i,n){const s=t.length,a=n||t[0]||"",o=await this.getSafeKeyframeDimensions(a,t[0]),l=o.width/o.height,h=i*l,c=l>=1;let d;c?d=Math.min(s,Math.max(1,Math.floor(e/h))):d=Math.min(s,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*(s-1)/(d-1)));const g=[];for(let y=0;y<d;y++){const T=t[p[y]],S=await this.getSafeKeyframeDimensions(a,T),v=S.width/S.height;g.push({coverUrl:T,singleImageWidth:i*v,segmentStartX:y*u,segmentWidth:u})}return g}static buildSegmentsDataSync(t,e,i,n){const s=t.length,a=n||t[0]||"",o=this.getCachedKeyframeDimensions(a,t[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(e/h))):d=Math.min(s,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*(s-1)/(d-1)));const g=[];for(let y=0;y<d;y++){const T=t[p[y]],S=this.getCachedKeyframeDimensions(a,T);if(!S)return null;const v=S.width/S.height;g.push({coverUrl:T,singleImageWidth:i*v,segmentStartX:y*u,segmentWidth:u})}return g}static requestRender(t){var i,n;const e=(i=t.getLayer)==null?void 0:i.call(t);if((n=e==null?void 0:e.getStage)!=null&&n.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,n){t.destroyChildren(),t.clip({x:0,y:0,width:i,height:n});for(const{coverUrl:s,singleImageWidth:a,segmentStartX:o,segmentWidth:l}of e){const h=Math.max(a,.01),c=Math.max(1,Math.ceil(l/h)),d=Math.max(a,.01),u=this.getCachedImage(s),p=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 g=0;g<c;g++){const y=g*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(n),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 n=new Promise(s=>{const a=this.getCachedImage(e);if(a.complete&&a.width>0){const l={width:a.width,height:a.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)};a.onload=()=>{const l={width:a.width,height:a.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},a.onerror=()=>{o(this.DEFAULT_DIMENSIONS)},a.src||(a.src=e)});return this.keyframeDimensionsPromiseCache[i]=n,n}static getCachedKeyframeDimensions(t,e){const i=e||t,n=this.keyframeDimensionsCache[i];if(n!=null&&n.width&&(n!=null&&n.height))return n;const s=this.imageCache[e];if(s!=null&&s.complete&&s.width>0&&s.height>0){const a={width:s.width,height:s.height};return this.keyframeDimensionsCache[i]=a,a}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(a=>{const o=this.imageCache[a];return o&&!o.complete}),n=t.filter(a=>!i.includes(a));let s=0;for(const a of i){if(s>=e)break;delete this.imageCache[a],s++}for(const a of n){if(s>=e)break;delete this.imageCache[a],s++}}}f(mt,"MIN_IMAGE_DISPLAY_WIDTH",24),f(mt,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),f(mt,"MAX_CACHE_SIZE",1e3),f(mt,"DEFAULT_DIMENSIONS",{width:160,height:90}),f(mt,"keyframeDimensionsCache",{}),f(mt,"keyframeDimensionsPromiseCache",{}),f(mt,"imageCache",{});const rt=3,fn=10,ro=8,ao=8,oo=10,ri=4,gn=14,lo=[4,10,14,10,4],pn=[3,7,11,15,11,7,3],Di=28,ho=14,fs=8,co=[4,9,14,9,4];function yt(r,t,e,i,n="#ffffff",s="#000000",a=1){return new X.Rect({x:r,y:t,width:e,height:i,fill:n,stroke:s,strokeWidth:a})}function gs(r,t,e,i=12,n="Arial",s="#000000",a="left",o="top"){return new X.Text({text:r,x:t,y:e,fontSize:i,fontFamily:n,fill:s,align:a,verticalAlign:o})}function wt(r=0,t=0){return new X.Group({x:r,y:t})}function Gi(r,t,e,i){if(i){r.add(new X.Rect({x:0,y:0,width:t,height:e,name:"clip-resize-left",listening:!0})),r.add(new X.Rect({x:0,y:0,width:t,height:e,name:"clip-resize-right",listening:!0}));return}r.add(new X.Rect({x:0,y:0,width:rt,height:e,name:"clip-resize-left"})),r.add(new X.Rect({x:t-rt,y:0,width:rt,height:e,name:"clip-resize-right"}))}function uo(r,t,e,i){const n=r.findOne(".clip-resize-left"),s=r.findOne(".clip-resize-right");return!n||!s?!1:(n.x(0),n.y(0),n.width(rt),n.height(e),s.x(t-rt),s.y(0),s.width(rt),s.height(e),!0)}function ps(r,t,e){return e==="audio"?{background:t?r.clipSelectedBackground||r.audioClipBackground||r.clipBackground:r.audioClipBackground||r.clipBackground,label:t?r.clipSelectedName||r.audioClipText||r.clipName:r.audioClipText||r.clipName,accent:t?r.clipSelectedHandle||r.audioClipAccent||r.clipHandle:r.audioClipAccent||r.clipHandle,coverBackground:r.clipCoverBackground||"#333333"}:{background:t&&r.clipSelectedBackground||r.clipBackground,label:t&&r.clipSelectedName||r.clipName,accent:t&&r.clipSelectedHandle||r.clipHandle,coverBackground:t?r.clipSelectedCoverBackground||r.clipCoverBackground||"#FFF2A0":r.clipCoverBackground||"#FFF2A0"}}function fo(r,t,e,i){const n=yt(0,0,t,e,i.background,"transparent",0);n.cornerRadius(Math.min(4,Math.floor(t/2))),n.name("clip-background"),r.add(n),Gi(r,t,e,!0)}function go(r,t,e){const i=yt(0,0,t.width,t.height,e.background,"transparent",0);i.cornerRadius(4),i.name("clip-background"),r.add(i),Gi(r,t.width,t.height,!1);const n=15,s=t.height-n-4,a=t.width-rt*2,o=wt(rt,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:a,height:s}),r.add(o);const l=yt(0,0,a,s,e.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const h=wt(0,0);h.name("clip-covers-group"),o.add(h),mt.renderClipCovers(h,t.thumbnails??[],a,s,t.videoSrc,t.deferCoverRender);const c=a>=120?Di+fs:0,d=gs(`${t.clipName} ${D.formatDuration(t.duration)}`,rt,t.height-n,10,"Arial",e.label,"left","middle");d.ellipsis(!0),d.width(Math.max(0,a-c)),d.height(n),d.name("clip-label"),r.add(d),c>0&&ms(r,t.width,t.height,e.label,t.hasSeparatedAudio)}function po(r,t,e){const i=r.findOne(".clip-background"),n=r.findOne(".clip-cover-container"),s=r.findOne(".clip-cover-background"),a=r.findOne(".clip-covers-group"),o=r.findOne(".clip-label");if(!i||!n||!s||!a||!o||(i.width(t.width),i.height(t.height),i.fill(e.background),i.stroke("transparent"),i.strokeWidth(0),i.cornerRadius(4),!uo(r,t.width,t.height)))return!1;const l=15,h=t.height-l-4,c=t.width-rt*2;n.x(rt),n.y(2),n.clip({x:0,y:0,width:c,height:h}),s.width(c),s.height(h),s.fill(e.coverBackground),s.cornerRadius(2),mt.renderClipCovers(a,t.thumbnails??[],c,h,t.videoSrc,t.deferCoverRender);const d=c>=120?Di+fs:0;o.text(`${t.clipName} ${D.formatDuration(t.duration)}`),o.x(rt),o.y(t.height-l),o.fill(e.label),o.width(Math.max(0,c-d)),o.height(l),o.ellipsis(!0);const u=r.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&ms(r,t.width,t.height,e.label,t.hasSeparatedAudio),!0}function bi(r,t,e,i,n,s,a){return r.name(n),t.forEach((o,l)=>{const h=yt(l*(s+a),Math.max(0,(e-o)/2),s,o,i,"transparent",0);h.cornerRadius(1),h.name(`${n}-bar-${l}`),r.add(h)}),t.length*s+Math.max(0,t.length-1)*a}function ms(r,t,e,i,n){const s=wt(Math.max(rt,t-rt-Di),Math.max(0,e-15));if(s.name("video-audio-status"),n){const c=wt(0,0);c.name("video-audio-status-separated");const d=yt(0,5,3,3,i,"transparent",0);d.cornerRadius(1.5),d.name("video-audio-status-separated-left-dot"),c.add(d);const u=yt(6,6,16,2,i,"transparent",0);u.cornerRadius(1),u.name("video-audio-status-separated-line"),c.add(u);const p=yt(25,5,3,3,i,"transparent",0);p.cornerRadius(1.5),p.name("video-audio-status-separated-right-dot"),c.add(p),s.add(c),r.add(s);return}const a=wt(2,0);a.name("video-audio-status-active");const o=yt(0,5,3,3,i,"transparent",0);o.cornerRadius(1.5),o.name("video-audio-status-active-left-dot"),a.add(o);const l=wt(5,0);bi(l,co,ho,i,"video-audio-status-active-bars",2,2),a.add(l);const h=yt(25,5,3,3,i,"transparent",0);h.cornerRadius(1.5),h.name("video-audio-status-active-right-dot"),a.add(h),s.add(a),r.add(s)}function mo(r,t,e){const i=yt(0,0,t.width,t.height,e.background,"transparent",0);i.cornerRadius(6),i.name("clip-background"),r.add(i),Gi(r,t.width,t.height,!1);const n=rt+fn,s=Math.max(0,t.width-rt*2-fn*2),a=ro,o=wt(n,a),l=bi(o,lo,14,e.accent,"audio-clip-icon",2,2);r.add(o);const h=n+l+oo,c=Math.max(0,n+s-h),d=3+ri,u=Math.min(pn.length,Math.floor((c+ri)/d));if(u>0){const g=wt(h,a);bi(g,pn.slice(0,u),15,e.accent,"audio-clip-waveform",3,ri),r.add(g)}const p=gs(t.clipName,n,t.height-ao-gn,12,"Arial",e.label,"left","middle");p.ellipsis(!0),p.width(s),p.height(gn),p.name("clip-label"),r.add(p)}function ys(r,t){const e=t.width<=be,i=ps(t.theme,t.isSelected,t.clipType);if(r.destroyChildren(),e){fo(r,t.width,t.height,i);return}if(t.clipType==="audio"){mo(r,t,i);return}go(r,t,i)}function yo(r,t){if(t.width<=be||t.clipType!=="video")return!1;const i=ps(t.theme,t.isSelected,t.clipType);return po(r,t,i)}function So(r,t,e,i,n,s,a,o=!1,l,h,c="video",d=!1,u=!1){const p=wt(r,t);return p.clip({x:0,y:0,width:e,height:i}),ys(p,{width:e,height:i,clipName:n,duration:s,theme:a,isSelected:o,thumbnails:l,videoSrc:h,clipType:c,hasSeparatedAudio:d,deferCoverRender:u}),p}function Co(r,t,e,i,n,s,a=!1,o,l,h="video",c=!1,d=!1){r.clip({x:0,y:0,width:t,height:e});const u={width:t,height:e,clipName:i,duration:n,theme:s??Xe,isSelected:a,thumbnails:o,videoSrc:l,clipType:h,hasSeparatedAudio:c,deferCoverRender:d};yo(r,u)||ys(r,u)}function To(r,t,e,i){return new X.Rect({x:r,y:t,width:e,height:i,stroke:"#50E3C2",strokeWidth:2,dash:[5,5],fillEnabled:!1})}function wi(r,t="#000000",e=1){return new X.Line({points:r,stroke:t,strokeWidth:e,lineCap:"round",lineJoin:"round"})}function vo(r,t,e,i=12,n="Arial",s="#000000",a="left",o="top"){return new X.Text({text:r,x:t,y:e,fontSize:i,fontFamily:n,fill:s,align:a,verticalAlign:o})}function bo(r=0,t=0){return new X.Group({x:r,y:t})}function wo(r,t,e,i,n,s,a,o){const l=o||i,h=a==="major"?l*.6:l*.3,c=wi([t,e,t,e+h],s.timeTick,a==="major"?1:.5);if(c.name("time-tick-line"),r.add(c),a==="major"){const d=e+h+5,u=vo(D.formatTime(n),t,d,10,"Arial",s.timeText,"center");u.name("time-tick-text"),r.add(u)}}function ko(r,t,e,i,n,s){const a=bo(t,e);for(let o=0;o<=i;o+=s)a.add(wi([o,0,o,n],"#E0E0E0",.5));for(let o=0;o<=n;o+=s)a.add(wi([0,o,i,o],"#E0E0E0",.5));r.add(a)}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,n,s="#ffffff",a="#000000",o=1){return new X.Rect({x:t,y:e,width:i,height:n,fill:s,stroke:a,strokeWidth:o})}static createText(t,e,i,n=12,s="Arial",a="#000000",o="left",l="top"){return new X.Text({text:t,x:e,y:i,fontSize:n,fontFamily:s,fill:a,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 n=new X.Group({x:t,y:e}),s=this.createLine([0,0,0,i],"#FF0000",2),a=new X.RegularPolygon({x:0,y:-10,sides:3,radius:5,fill:"#FF0000",rotation:180});return n.add(s),n.add(a),n}static drawTimeTick(t,e,i,n,s,a,o,l){wo(t,e,i,n,s,a,o,l)}static drawGrid(t,e,i,n,s,a){ko(t,e,i,n,s,a)}static clearImageCache(){mt.clearImageCache()}static createClipGroup(t,e,i,n,s,a,o,l=!1,h,c,d="video",u=!1,p=!1){return So(t,e,i,n,s,a,o,l,h,c,d,u,p)}static updateClipGroup(t,e,i,n,s,a,o=!1,l,h,c="video",d=!1,u=!1){Co(t,e,i,n,s,a,o,l,h,c,d,u)}static createSelectionEffect(t,e,i,n){return To(t,e,i,n)}static timeToPixels(t,e){return t/1e3*e}static pixelsToTime(t,e){return t/e*1e3}}f(it,"RESIZE_AREA_WIDTH",3);function _e(r){let t=!1;return typeof window<"u"&&(window.addEventListener("mousemove",r.onPointerMove),window.addEventListener("mouseup",r.onPointerEnd),window.addEventListener("blur",r.onWindowBlur||r.onPointerEnd),t=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",r.onVisibilityChange),t=!0),t}function Pe(r){typeof window<"u"&&(window.removeEventListener("mousemove",r.onPointerMove),window.removeEventListener("mouseup",r.onPointerEnd),window.removeEventListener("blur",r.onWindowBlur||r.onPointerEnd)),typeof document<"u"&&document.removeEventListener("visibilitychange",r.onVisibilityChange)}class _o{constructor(t,e,i,n,s,a){f(this,"stage");f(this,"gridLayer");f(this,"config");f(this,"theme");f(this,"isDragging",!1);f(this,"startDragX",0);f(this,"scrollLeft",0);f(this,"timeScaleHeight",40);f(this,"onTimeChange");f(this,"onZoomChange");f(this,"onScrollChange");f(this,"animationFrameId",null);f(this,"hasBoundGlobalPointerListenersForDrag",!1);f(this,"isScrollbarDragging",!1);f(this,"scrollbarDragStartX",0);f(this,"scrollbarDragStartScrollLeft",0);f(this,"isPointerInsideTimeline",!1);f(this,"lastPointerXInTimeline",null);f(this,"scrollbarHeight",12);f(this,"scrollbarMargin",4);f(this,"handleGlobalPointerMove",t=>{this.isPointerSessionActive()&&this.handlePointerMove(t)});f(this,"handleGlobalPointerEnd",()=>{this.finalizePointerInteraction()});f(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finalizePointerInteraction()});f(this,"leftPadding",at);this.stage=t,this.gridLayer=e,this.onTimeChange=n,this.onZoomChange=s,this.onScrollChange=a,this.config={duration:i.duration||36e5,zoom:i.zoom||lt.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:ve(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:n}=t.evt,s=Math.abs(e)>0;if(n||s){const l=(s?e:i)*1.5,h=this.stage.width(),c=D.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=_e({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Pe({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(),n=Math.max(0,i-e);if(n<=0)return;const s=this.getScrollbarThumbWidth(),a=Math.max(1,e-s),o=t.clientX-this.scrollbarDragStartX,l=this.scrollLeft,h=this.scrollbarDragStartScrollLeft+o/a*n;this.scrollLeft=Math.max(0,Math.min(n,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 n=this.stage.width(),s=D.timeToPixels(this.config.duration,this.config.zoom);this.scrollLeft=Math.max(0,Math.min(s-n,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,n=Math.max(lt.MIN,Math.min(lt.MAX,this.config.zoom*i));if(n!==this.config.zoom){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const s=t.evt.offsetX;this.animateZoom(n,s)}}animateZoom(t,e){const i=this.config.zoom,n=In.DURATION,s=Date.now(),a=this.pixelToTime(e),o=()=>{const l=Date.now()-s,h=Math.min(l/n,1),c=this.easeOutCubic(h),d=i+(t-i)*c,u=D.timeToPixels(a,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 g=D.timeToPixels(a,t),y=Math.max(0,g-(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,n=Date.now(),s=this.stage.width(),a=D.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=e+(t-e)*c;this.scrollLeft=Math.max(0,Math.min(a-s,d)),this.onScrollChange(this.scrollLeft),this.render(),h<1?this.animationFrameId=requestAnimationFrame(o):(this.scrollLeft=Math.max(0,Math.min(a-s,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 D.pixelsToTime(t-this.leftPadding+this.scrollLeft,this.config.zoom)}timeToPixel(t){return D.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 n=it.createRect(0,0,t,e,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 t=this.stage.width(),e=this.stage.height(),i=Math.max(this.timeScaleHeight,e-this.scrollbarHeight-this.scrollbarMargin),n=this.getScrollbarThumbWidth(),s=this.getScrollbarThumbX(n),a=this.gridLayer.findOne(".scrollbar-background");if(a)a.x(0),a.y(i),a.width(t),a.height(this.scrollbarHeight),a.fill(this.theme.scrollbarBackground||"#333333"),a.stroke(this.theme.scrollbarBorder||"#555555"),a.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(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<t);else{const l=it.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<t),this.gridLayer.add(l)}}renderTimeTicks(){const t=this.stage.width(),e=this.scrollLeft,i=this.scrollLeft+t,n=D.pixelsToTime(e,this.config.zoom),s=D.pixelsToTime(i,this.config.zoom),a=D.msToSeconds(n),o=D.msToSeconds(s),l=10,h=a-l,c=o+l,{majorStep:d,minorStep:u}=D.getTickConfig(this.config.zoom),p=D.generateVisibleTicks(h,c,d,u);let g=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),g++)}R.debugLazy("Timeline",()=>`Timeline - scrollLeft: ${this.scrollLeft}px, zoom: ${this.config.zoom}px/s, visible time: ${Math.round(a)}s to ${Math.round(o)}s, ticks: ${p.length} generated, ${g} 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 D.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(),n=Math.max(0,i-e);if(n<=0||t>=e)return 0;const s=e-t;return this.scrollLeft/n*s}jumpScrollbarToPointer(t){const e=this.stage.width(),i=this.getTotalDurationPixels(),n=Math.max(0,i-e);if(n<=0)return;const s=this.getScrollbarThumbWidth(),a=Math.max(1,e-s),l=Math.max(s/2,Math.min(e-s/2,t))-s/2,h=this.scrollLeft;this.scrollLeft=l/a*n,this.render(),this.scrollLeft!==h&&this.onScrollChange(this.scrollLeft)}scrollToTime(t){const e=D.timeToPixels(t,this.config.zoom),i=this.stage.width(),n=Math.max(0,e-i/2);this.setScrollLeft(n),this.onScrollChange(n)}scrollToClip(t){const e=D.timeToPixels(t.startTime,this.config.zoom),n=D.timeToPixels(t.startTime+t.duration,this.config.zoom)-e,s=this.stage.width();let a;n<=s?a=Math.max(0,e-(s-n)/2):a=Math.max(0,e),this.setScrollLeft(a),this.onScrollChange(a)}getStage(){return this.stage}getGridLayer(){return this.gridLayer}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}resize(t,e){this.render()}}const ge=8;function Mt(r,t,e){return it.timeToPixels(r,t)-e+at}function Nt(r,t){const e=it.timeToPixels(r,t);return r<=1e3||e<=be?be:e}function mn(r,t){const e=Mt(r.startTime,r.zoom,r.scrollLeft),i=Nt(r.duration,r.zoom);return e+i>0&&e<t}function Po(r){for(const t of r.clips){const e=Mt(t.startTime,r.zoom,r.scrollLeft),i=Nt(t.duration,r.zoom),n=r.y>=r.trackY&&r.y<=r.trackY+r.trackHeight;if(r.x>=e&&r.x<=e+ge&&n||r.x>=e+i-ge&&r.x<=e+i&&n)return"ew-resize";if(r.x>e+ge&&r.x<e+i-ge&&n)return"pointer"}return"default"}class We{constructor(t,e,i){f(this,"clip");f(this,"onUpdate");f(this,"onSplit");this.clip=xi({...t,endTime:D.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:D.calculateEndTime(t.startTime,t.duration)}}setSelected(t){this.clip={...this.clip,isSelected:t},this.onUpdate(this.clip)}isPointInResizeHandle(t,e,i,n,s,a){const o=Mt(this.clip.startTime,i,a),l=Nt(this.clip.duration,i),h=ge;return e<n||e>n+s?(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 ki(){return{kind:"idle"}}function ai(r){return!!r&&r.kind!=="idle"}function Ce(r){return(r==null?void 0:r.kind)==="draggingMove"||(r==null?void 0:r.kind)==="draggingResizeLeft"||(r==null?void 0:r.kind)==="draggingResizeRight"}function Kt(r){return!r||r.kind==="idle"?null:r.context}function Te(r){return!r||r.kind==="idle"?null:r.kind==="pressed"?r.operation:r.kind==="draggingResizeLeft"?"resize-left":r.kind==="draggingResizeRight"?"resize-right":"move"}function xo(r){const t=Te(r);return t?t==="move"?"grabbing":"ew-resize":null}function He(r,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(r.kind==="idle")return{state:r,effects:{}};if(t.type==="POINTER_MOVE"){const i=Ao(r.context,t,Te(r)||"move");return r.kind==="pressed"?Lo(r.context,t.activationThreshold,t.clientX,t.clientY)?{state:Eo(r.operation,i),effects:{updatePreview:!0}}:{state:{...r,context:i},effects:{}}:{state:{...r,context:i},effects:{updatePreview:!0}}}if(t.type==="SCROLL_LEFT_CHANGED")return{state:r,effects:{updatePreview:Ce(r)}};const e=t.type==="POINTER_UP"&&Ce(r);return{state:ki(),effects:{unbindGlobalListeners:!0,commit:e,cleanup:!0}}}function Eo(r,t){return r==="resize-left"?{kind:"draggingResizeLeft",context:t}:r==="resize-right"?{kind:"draggingResizeRight",context:t}:{kind:"draggingMove",context:t}}function Ao(r,t,e){const i=e==="move";return{...r,lastPointerClientX:t.clientX,lastPointerClientY:t.clientY,dragTargetTrackY:i?t.localY:r.pointerStartY,crossTrackDragOffsetY:i?t.localY-r.pointerStartY:0}}function Lo(r,t,e,i){const n=e-r.pointerStartClientX,s=i-r.pointerStartClientY;return Math.hypot(n,s)>=Math.max(0,t)}const pt=class pt{constructor(t,e,i,n,s,a,o,l,h,c,d,u,p,g,y,T,S,v,b,w,L=pt.DEFAULT_DRAG_ACTIVATION_THRESHOLD,P=!1,I=pt.DEFAULT_CLIP_SNAP_THRESHOLD){f(this,"layer");f(this,"trackGroup");f(this,"dropPreviewGroup",null);f(this,"config");f(this,"theme");f(this,"trackType");f(this,"clips",[]);f(this,"clipGroups",new Map);f(this,"zoom",100);f(this,"scrollLeft",0);f(this,"trackY",0);f(this,"trackHeight",64);f(this,"selectedClip",null);f(this,"hasSelectedClip",!1);f(this,"interactionState",ki());f(this,"isVisualUpdate",!1);f(this,"onClipUpdate");f(this,"onClipAdd");f(this,"onClipRemove");f(this,"onClipSplit");f(this,"onClipSelect");f(this,"onTimeJump");f(this,"onClipOverlap");f(this,"hasBoundGlobalPointerListenersForDrag",!1);f(this,"hasLockedGlobalCursor",!1);f(this,"edgeAutoScrollAnimationFrameId",null);f(this,"onHorizontalDragAutoScroll");f(this,"onClipCrossTrackPreview");f(this,"onClipCrossTrack");f(this,"onClearDropPreview");f(this,"onClearSelection");f(this,"onSnapGuideChange");f(this,"resolveSnapTargetClips");f(this,"dragActivationThreshold");f(this,"enableClipSnap");f(this,"clipSnapThreshold");f(this,"handleGlobalPointerMove",t=>{ai(this.interactionState)&&this.handleDragMove(t)});f(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});f(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});f(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});f(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const t=this.resolveInteractionState();if(!Ce(t)||!this.onHorizontalDragAutoScroll)return;const e=this.layer.getStage(),i=e==null?void 0:e.container(),n=Kt(t);if(!i||!n){this.stopEdgeAutoScroll();return}const s=i.getBoundingClientRect(),a=n.lastPointerClientX-s.left,o=this.calculateHorizontalAutoScrollVelocity(a,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=t,this.config=e,this.theme=o,this.trackType=i,this.zoom=n,this.trackY=s,this.trackHeight=a,this.onClipUpdate=l,this.onClipAdd=h,this.onClipRemove=c,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=p,this.onHorizontalDragAutoScroll=g,this.onClipOverlap=y,this.onClipCrossTrackPreview=T,this.onClipCrossTrack=S,this.onClearDropPreview=v,this.onClearSelection=b,this.onSnapGuideChange=w,this.dragActivationThreshold=Math.max(0,L),this.enableClipSnap=P,this.clipSnapThreshold=Math.max(0,I),this.trackGroup=it.createGroup(0,s),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}initClips(){this.clips=this.config.clips.map(t=>{const e=new We(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);t.name("clip-drop-preview"),t.visible(!1),t.listening(!1);const e=this.trackType==="video"?"rgba(80, 227, 194, 0.18)":"rgba(181, 186, 255, 0.18)",i=this.trackType==="video"?"#50e3c2":"#b5baff",n=it.createRect(0,0,0,0,e,i,1);return n.dash([6,4]),n.cornerRadius(4),n.listening(!1),t.add(n),this.trackGroup.add(t),this.dropPreviewGroup=t,t}showDropPreview(t){const e=this.ensureDropPreviewGroup(),i=e.children[0];if(!i)return;const n=Mt(t.startTime,this.zoom,this.scrollLeft),s=Nt(t.duration,this.zoom);e.x(n),e.y(2),i.width(Math.max(s,1)),i.height(Math.max(this.trackHeight-4,1)),e.visible(n+s>0&&n<this.layer.width()),e.moveToTop()}hideDropPreview(){var t;(t=this.dropPreviewGroup)==null||t.visible(!1)}initEventListeners(){const t=this.layer.getStage();t&&t.on("mouseup",()=>{this.handleClipMouseUp()})}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=_e({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Pe({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 n=i.getBoundingClientRect(),s=t.clientX-n.left,a=Math.max(0,D.pixelsToTime(s-at+this.scrollLeft,this.zoom));this.onTimeJump(a),this.onClearSelection&&this.onClearSelection()}createClipGroup(t){const e=Mt(t.startTime,this.zoom,this.scrollLeft),i=Nt(t.duration,this.zoom),n=2,s=this.trackHeight-4,a=it.createClipGroup(e,n,i,s,t.name,t.duration,this.theme,!1,t.thumbnails,t.src,t.type,!!t.separatedAudioClipId);a.name(`clip-${t.id}`),a.on("click",o=>{this.handleClipClick(t.id,o.evt)}),a.on("mousedown",o=>{this.handleClipMouseDown(t.id,o.evt)}),a.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),a.on("mouseleave",()=>{this.handleClipMouseLeave()}),a.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(a),this.clipGroups.set(t.id,a)}handleClipClick(t,e){if(e.button!==0)return;this.clips.find(n=>n.getClip().id===t)&&this.render()}handleClipMouseDown(t,e){if(e.button!==0)return;this.clips.sort((l,h)=>l.getClip().startTime-h.getClip().startTime);const i=this.clips.map(l=>({...l.getClip()})),n=this.clips.filter(l=>l.getClip().id!==t).map(l=>({...l.getClip()})),a=(this.resolveSnapTargetClips?this.resolveSnapTargetClips():this.clips.map(l=>l.getClip())).filter(l=>l.id!==t).map(l=>({...l})),o=this.clips.find(l=>l.getClip().id===t);if(o){this.applySelectionVisual(t),this.selectedClip=o,this.onClipSelect(o.getClip());const l=this.layer.getStage();if(!l)return;const h=l.container();if(!h)return;const c=h.getBoundingClientRect(),d=e.clientX-c.left,u=e.clientY-c.top;let p;o.isPointInResizeHandle(d,u,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(p=o.getClip().isResizingLeft?"resize-left":"resize-right",o.startResize({x:d,y:u})):(p="move",o.startDrag({x:d,y:u}),this.trackGroup.moveToTop()),this.applyInteractionTransition(He(this.interactionState,{type:"POINTER_DOWN",operation:p,clipId:t,originalClipsState:i,nonDraggedClips:n,snapCandidateClips:a,clientX:e.clientX,clientY:e.clientY,localX:d,localY:u,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 n=i;this.selectedClip.endDrag();const s=He(e,{type:t});this.interactionState=s.state,s.effects.commit&&this.handleClipMoveEnd(n,e),this.layer.batchDraw()}finally{this.interactionState=ki(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}applyInteractionTransition(t){var i;this.interactionState=t.state,this.syncLegacyInteractionMirror(t.state),t.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const e=xo(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()),t.effects.unbindGlobalListeners&&this.unbindGlobalPointerListenersForDrag()}resolveInteractionState(t=this.interactionState){var a;if(ai(t))return t;const e=this,i=(a=this.selectedClip)==null?void 0:a.getClip();if(!(i!=null&&i.id)||!i.isDragging)return t;const n=e.activePointerOperation||(i.isResizingLeft?"resize-left":i.isResizingRight?"resize-right":"move"),s={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?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(t=this.interactionState){const e=this,i=Kt(t);e.hasDragMoved=Ce(t),e.activePointerOperation=Te(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 y,T;const i=this.resolveInteractionState(e),n=this,s=Kt(i)||{clipId:t.id,originalClipsState:Array.isArray(n.originalClipsState)?n.originalClipsState:[t],nonDraggedClips:Array.isArray(n.nonDraggedClips)?n.nonDraggedClips:[],snapCandidateClips:Array.isArray(n.snapCandidateClips)?n.snapCandidateClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:typeof n.dragTargetTrackY=="number"?n.dragTargetTrackY:0,crossTrackDragOffsetY:typeof n.crossTrackDragOffsetY=="number"?n.crossTrackDragOffsetY:0},o=(Te(i)||n.activePointerOperation||"move")==="move";if(o&&this.onClipCrossTrack&&this.config.id){const S=(y=this.clipGroups)==null?void 0:y.get(t.id);S&&S.y(2);const v=s.originalClipsState.find(w=>w.id===t.id)??null;if(this.onClipCrossTrack(t,v,s.dragTargetTrackY,this.config.id))return}const l=(T=this.clipGroups)==null?void 0:T.get(t.id);l&&l.y(2);const h=o?[...s.nonDraggedClips]:[];let c=!1;const d=t.startTime+t.duration;for(const S of h){const v=S.startTime+S.duration;if(t.startTime<v&&d>S.startTime){c=!0;break}}if(o&&c&&this.onClipOverlap&&this.config.id){this.onClipOverlap(t,this.config.id);return}const u=[...s.nonDraggedClips];let p=u.findIndex(S=>S.startTime>=t.startTime);p===-1&&(p=u.length),s.nonDraggedClips.forEach(S=>{S.isSelected=!1});const g={...t,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};u.splice(p,0,g),this.updateAllClips(u),this.buildAndSendUpdates(g,u,s.originalClipsState)}updateAllClips(t){const e=this.clips??[];this.isVisualUpdate=!0,t.forEach(i=>{e.find(s=>s.getClip().id===i.id)&&this.handleClipUpdate(i)}),this.isVisualUpdate=!1,e.sort((i,n)=>i.getClip().startTime-n.getClip().startTime),this.clips=e}buildAndSendUpdates(t,e,i){const n=i.map(s=>{const a=e.find(o=>o.id===s.id);return a&&(s.startTime!==a.startTime||s.duration!==a.duration||s.opacity!==a.opacity)?{clipId:s.id,previousState:s,newState:a}:null}).filter(s=>s!==null);n.length>0&&this.onClipUpdate(t,i.find(s=>s.id===t.id),n)}updateHoverCursor(t,e){const i=this.layer.getStage();if(!i)return;const n=i.container();if(!n||this.isDragSessionActive())return;const s=n.getBoundingClientRect(),a=t-s.left,o=e-s.top;n.style.cursor=Po({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:a,y:o})}isDragSessionActive(){return ai(this.resolveInteractionState())}handleDragMove(t){const e=this.resolveInteractionState(),i=this.layer.getStage(),n=i==null?void 0:i.container();if(!n)return;const s=n.getBoundingClientRect(),a=He(e,{type:"POINTER_MOVE",clientX:t.clientX,clientY:t.clientY,localY:t.clientY-s.top,activationThreshold:this.dragActivationThreshold});this.interactionState=a.state,this.syncLegacyInteractionMirror(a.state),a.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 n=Mt(t.startTime,this.zoom,this.scrollLeft),s=Nt(t.duration,this.zoom);i.x(n),i.visible(mn({startTime:t.startTime,duration:t.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width()));const a=t.isSelected;(t.isDragging||a)&&i.moveToTop(),i.opacity(t.opacity),it.updateClipGroup(i,s,this.trackHeight-4,t.name,t.duration,this.theme,a,t.thumbnails,t.src,t.type,!!t.separatedAudioClipId,e)}}handleClipUpdate(t){var i,n;const e=this.clips.findIndex(s=>s.getClip().id===t.id);if(e!==-1){const s=this.clips[e].getClip(),a={...t,isSelected:this.isVisualUpdate||((i=this.selectedClip)==null?void 0:i.getClip().id)===t.id?t.isSelected:!1};this.clips[e]=new We(a,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this)),((n=this.selectedClip)==null?void 0:n.getClip().id)===t.id&&(this.selectedClip=this.clips[e]),this.updateClipGroup(a);const o=this.clipGroups.get(t.id);o&&o.opacity(a.opacity),this.isVisualUpdate||this.onClipUpdate(a,s),this.layer.batchDraw()}}handleClipSplit(t,e){const i=e-t.startTime,n=t.duration-i,s=t.startTimeAtSource+i,a={...t,duration:i,endTime:e,endTimeAtSource:s},o={...t,id:`${t.id}_split_${Date.now()}`,startTime:e,duration:n,endTime:D.calculateEndTime(e,n),startTimeAtSource:s,endTimeAtSource:t.endTimeAtSource};this.removeClip(t.id),this.addClip(a),this.addClip(o),this.onClipSplit(a,o),this.layer.batchDraw()}addClip(t){if(t.type!==this.trackType){R.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${t.type}`);return}const e={...t,isSelected:!1},i=new We(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(n=>n.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 n=this.clipGroups.get(t);n&&(n.remove(),this.clipGroups.delete(t)),this.onClipRemove(t),this.hideDropPreview(),this.layer.batchDraw()}}updateClip(t,e){const i=this.clips.find(n=>n.getClip().id===t);if(i){const s={...i.getClip(),...e};(e.startTime!==void 0||e.duration!==void 0)&&(s.endTime=s.startTime+s.duration),this.handleClipUpdate(s)}}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(s=>{const a=s.getClip();this.updateClipGroup(a),this.updateClipVisibility(a)});const e=this.resolveInteractionState(),i=Kt(e),n=He(e,{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(t){const e=this.clipGroups.get(t.id);if(e){const i=mn({startTime:t.startTime,duration:t.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width());e.visible(i)}}setTrackY(t){this.trackY=t,this.trackGroup.y(t)}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",n=>{this.handleTrackBackgroundClick(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(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.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===t;e.setSelected(i)})}finally{this.isVisualUpdate=!1}}splitSelectedClip(t){const e=this.clips.find(i=>{const n=i.getClip();return t>=n.startTime&&t<n.endTime});e&&e.split(t)}removeClipGaps(){R.debugLazy("Track",()=>"Removing clip gaps");const t=this.clips.map(i=>i.getClip()).sort((i,n)=>i.startTime-n.startTime);if(t.length===0)return;let e=0;for(let i=0;i<t.length;i++){const n=t[i];if(e-n.startTime<0||i===0){const a=e,o=a+n.duration;this.handleClipUpdate({...n,startTime:a,endTime:o}),e=o}else e=n.startTime+n.duration}}getTrackGroup(){return this.trackGroup}getId(){return this.config.id||"default"}setTrackHeight(t){var e;if(this.trackHeight=t,(e=this.dropPreviewGroup)!=null&&e.visible()){const i=this.dropPreviewGroup.children[0];i==null||i.height(Math.max(this.trackHeight-4,1))}this.clips.forEach(i=>{this.updateClipGroup(i.getClip(),!0)}),this.render(!1)}showClipDropPreview(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=Kt(e);if(Ce(e)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(t){this.resolveSnapTargetClips=t}updateDraggedClipFromPointer(t,e,i){var y,T,S;const n=this.resolveInteractionState(),s=Kt(n),a=Te(n),o=this.layer.getStage();if(!o||!this.selectedClip||!s||!a)return;const l=o.container();if(!l)return;const h=l.getBoundingClientRect(),c=t-h.left,d=e-h.top,u=a==="move";u&&R.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:d,currentTrackId:this.config.id,offsetY:s.crossTrackDragOffsetY}));const p=this.selectedClip.getClip(),g=(y=this.clipGroups)==null?void 0:y.get(p.id);if(g){const v=s.originalClipsState.find(A=>A.id===p.id);if(!v)return;const b=this.buildPreviewClip(p,v,c,s,a);if(!b){this.hideDropPreview(),(T=this.onClearDropPreview)==null||T.call(this),this.updateSnapGuideLine(null);return}const w=b.clip,L=this.applyPreviewClipState(w),P=Mt(w.startTime,this.zoom,this.scrollLeft),I=Nt(w.duration,this.zoom);g.x(P),g.y(2+s.crossTrackDragOffsetY),g.visible(P+I>0&&P<this.layer.width()),L&&(this.updateClipGroup(w),g.y(2+s.crossTrackDragOffsetY)),u&&this.onClipCrossTrackPreview&&this.config.id?this.onClipCrossTrackPreview(w,s.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():this.showDropPreview(w),this.updateSnapGuideLine(b.guideTime)}else this.hideDropPreview(),(S=this.onClearDropPreview)==null||S.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(c,h.width),this.layer.batchDraw()}buildPreviewClip(t,e,i,n,s){const a=i-n.pointerStartX+(this.scrollLeft-n.dragStartScrollLeft),o=D.pixelsToTime(a,this.zoom);let l;return s==="resize-left"||t.isResizingLeft?l=this.buildResizeLeftPreviewClip(t,e,o):s==="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,n.snapCandidateClips),e,n.nonDraggedClips)}constrainResizePreviewToTrackBounds(t,e,i){if(t.clip.isResizingLeft){const n=this.getResizeLeftBoundaryStart(e,i);if(t.clip.startTime>=n)return t;const s=t.clip.endTime,a=s-n;return{clip:{...t.clip,startTime:n,duration:a,endTime:s,startTimeAtSource:e.endTimeAtSource-a,endTimeAtSource:e.endTimeAtSource},guideTime:t.guideTime===n?t.guideTime:null}}if(t.clip.isResizingRight){const n=this.getResizeRightBoundaryEnd(e,i);if(t.clip.startTime+t.clip.duration<=n)return t;const a=n-t.clip.startTime;return{clip:{...t.clip,duration:a,endTime:n,endTimeAtSource:e.startTimeAtSource+a},guideTime:t.guideTime===n?t.guideTime:null}}return t}getResizeLeftBoundaryStart(t,e){let i=0;for(const n of e){if(n.startTime>=t.startTime)continue;const s=n.startTime+n.duration;i=Math.max(i,s)}return i}getResizeRightBoundaryEnd(t,e){let i=Number.POSITIVE_INFINITY;for(const n of e)n.startTime<t.endTime||(i=Math.min(i,n.startTime));return Number.isFinite(i)?i:Number.POSITIVE_INFINITY}buildResizeLeftPreviewClip(t,e,i){const s=Math.max(0,e.startTime+i)-e.startTime,o=Math.max(0,e.startTimeAtSource+i)-e.startTimeAtSource,l=Math.abs(s)<Math.abs(o)?s:o,h=D.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 n=Math.max(1e3,e.duration+i);const s=e.startTimeAtSource,a=Math.min(e.sourceDuration,s+n);return n=a-s,{...t,startTime:e.startTime,duration:n,endTime:e.startTime+n,startTimeAtSource:s,endTimeAtSource:a}}applyClipSnap(t,e,i){if(!this.enableClipSnap||i.length===0)return{clip:t,guideTime:null};const n=i.flatMap(h=>[h.startTime,h.startTime+h.duration]);if(n.length===0)return{clip:t,guideTime:null};const s=D.pixelsToTime(this.clipSnapThreshold,this.zoom),a=t.startTime+t.duration,o=[];if(t.isResizingLeft)for(const h of n){const c=a-h,d=e.endTimeAtSource-c,u=Math.abs(h-t.startTime);u>s||c<1e3||d<0||o.push({clip:{...t,startTime:h,duration:c,endTime:a,startTimeAtSource:d,endTimeAtSource:e.endTimeAtSource},guideTime:h,distance:u})}else if(t.isResizingRight)for(const h of n){const c=h-t.startTime,d=e.startTimeAtSource+c,u=Math.abs(h-a);u>s||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 n){const c=Math.abs(h-t.startTime);c<=s&&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-a);u<=s&&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)}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(pt.AUTO_SCROLL_EDGE_THRESHOLD,e/2),n=pt.AUTO_SCROLL_MAX_SPEED;if(t<=0)return-n;if(t>=e)return n;if(t<i){const s=(i-t)/i;return-Math.max(1,Math.round(s*n))}if(t>e-i){const s=(t-(e-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)}};f(pt,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),f(pt,"DEFAULT_CLIP_SNAP_THRESHOLD",8),f(pt,"AUTO_SCROLL_EDGE_THRESHOLD",48),f(pt,"AUTO_SCROLL_MAX_SPEED",18);let $e=pt;class Mo{constructor(t,e,i,n,s,a){f(this,"layer");f(this,"playheadGroup");f(this,"playheadLine");f(this,"playheadTriangle");f(this,"theme");f(this,"currentTime",0);f(this,"zoom",100);f(this,"scrollLeft",0);f(this,"onTimeChange");f(this,"isDragging",!1);this.layer=t,this.currentTime=e,this.zoom=i,this.theme=s,this.onTimeChange=a,this.playheadGroup=it.createGroup(),this.layer.add(this.playheadGroup),this.playheadLine=it.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 t,e,i;this.playheadGroup.on("mousedown",()=>{this.isDragging=!0}),(t=this.layer.getStage())==null||t.on("mousemove",n=>{this.isDragging&&this.handleMouseMove(n.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 n=i.getBoundingClientRect(),s=t.clientX-n.left,a=D.pixelsToTime(s-at+this.scrollLeft,this.zoom);this.setTime(a)}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=D.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+at;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 Ss{constructor(t,e,i,n){f(this,"container");f(this,"tracks",[]);f(this,"theme");f(this,"width",200);f(this,"timeScaleHeight",40);f(this,"includeTimeScaleSpacer",!0);f(this,"trackList",null);f(this,"onMuteTrack");var s,a,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:((s=t.theme)==null?void 0:s.background)||"#1a1a1a",border:((a=t.theme)==null?void 0:a.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=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(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 n=this.createTrackItem(e,i);t.appendChild(n)}),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"?bt.VIDEO:bt.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=e.toString(),n.dataset.trackId=t.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 a=document.createElement("span");a.className="track-icon",a.textContent=t.type==="video"?"🎬":"🎵",a.style.fontSize="18px",a.style.userSelect="none",s.appendChild(a);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),n.appendChild(s),n.appendChild(o),n}destroy(){this.trackList=null,this.container.innerHTML=""}}const Ro={backgroundColor:"#1e1e1e",borderColor:"#333",textColor:"#e0e0e0",labelColor:"#999",inputBackground:"#2d2d2d",inputBorder:"#444",inputFocusBorder:"#409eff",buttonBackground:"#2d2d2d",buttonBorder:"#444",buttonActiveBackground:"#409eff",buttonActiveBorder:"#409eff",buttonActiveText:"#fff"},$={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"},Io={visual:"画面",audio:"音频"};class Cs{constructor(t){f(this,"container");f(this,"rootElement",null);f(this,"theme");f(this,"onClipUpdate");f(this,"currentClip",null);f(this,"activeTab","visual");f(this,"tabBar",null);f(this,"contentArea",null);f(this,"visualPanel",null);f(this,"audioPanel",null);f(this,"xSlider",null);f(this,"xInput",null);f(this,"ySlider",null);f(this,"yInput",null);f(this,"scaleSlider",null);f(this,"scaleInput",null);f(this,"volumeSlider",null);f(this,"volumeInput",null);this.container=t.container,this.theme=t.theme??Ro,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=$.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=$.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=$.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=$.tabButton,i.textContent=Io[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 n=this.activeTab===e;i.style.backgroundColor=n?"#595A5D":"transparent",i.style.color=n?"#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(`.${$.tabButton}`),e=this.getAvailableTabs();t.forEach((i,n)=>{const a=e[n]===this.activeTab,o=i;o.style.backgroundColor=a?"#595A5D":"transparent",o.style.color=a?"#fff":"#b5b6bf"})}renderContentArea(){this.contentArea=document.createElement("div"),this.contentArea.className=$.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=$.visualPanel;const t=document.createElement("div");t.className=$.section,t.style.marginBottom="16px";const e=document.createElement("div");e.className=$.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=$.section,i.style.borderTop=`1px solid ${this.theme.borderColor}`,i.style.paddingTop="16px";const n=document.createElement("div");n.className=$.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=$.audioPanel;const t=document.createElement("div");t.className=$.section;const e=document.createElement("div");e.className=$.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=$.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,g,y,T,S;const n=document.createElement("div");n.className=$.row,n.style.display="flex",n.style.alignItems="center",n.style.gap="8px",n.style.marginBottom="8px";const s=document.createElement("label");s.className=$.label,s.style.width="16px",s.style.fontSize="13px",s.style.color=this.theme.labelColor,s.textContent=e,n.appendChild(s);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=$.slider,c.min=String(l),c.max=String(h),c.step="0.01",c.value=String(((y=(g=this.currentClip)==null?void 0:g.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)}),n.appendChild(c);const d=document.createElement("input");d.type="number",d.className=$.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)}),n.appendChild(d),i==="x"?(this.xSlider=c,this.xInput=d):(this.ySlider=c,this.yInput=d),t.appendChild(n)}renderPresetGrid(t){const e=document.createElement("div");e.className=$.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(n=>{const s=document.createElement("button");s.className=$.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:a,y:o}=this.calculatePresetPosition(n.x,n.y);this.handleTransformChanges({x:a,y:o})}),e.appendChild(s)}),t.appendChild(e)}calculatePresetPosition(t,e){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},a={top:n,center:.5,bottom:1-n};return{x:s[t],y:a[e]}}renderScaleControl(t){var a,o,l,h;const e=document.createElement("div");e.className=$.row,e.style.display="flex",e.style.alignItems="center",e.style.gap="8px";const i=document.createElement("input");i.type="range",i.className=$.slider,i.min="0.1",i.max="8",i.step="0.1",i.value=String(((o=(a=this.currentClip)==null?void 0:a.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 n=document.createElement("input");n.type="number",n.className=$.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)}),e.appendChild(n);const s=document.createElement("button");s.className=$.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)}),e.appendChild(s),this.scaleSlider=i,this.scaleInput=n,t.appendChild(e)}renderVolumeControl(t){var a,o;const e=document.createElement("div");e.className=$.row,e.style.display="flex",e.style.alignItems="center",e.style.gap="8px";const i=document.createElement("input");i.type="range",i.className=$.slider,i.min="0",i.max="1",i.step="0.01",i.value=String(((a=this.currentClip)==null?void 0:a.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 n=document.createElement("input");n.type="number",n.className=$.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)))}),e.appendChild(n);const s=document.createElement("span");s.style.fontSize="12px",s.style.color=this.theme.labelColor,s.textContent="%",e.appendChild(s),this.volumeSlider=i,this.volumeInput=n,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 s;const t=((s=this.currentClip)==null?void 0:s.visualTransform)??{x:.5,y:.5,scale:1},e=t.scale/2,i=-e,n=1+e;this.updateSliderAndInput(this.xSlider,this.xInput,t.x,i,n),this.updateSliderAndInput(this.ySlider,this.yInput,t.y,i,n),this.scaleSlider&&(this.scaleSlider.value=String(t.scale)),this.scaleInput&&(this.scaleInput.value=String(t.scale))}updateSliderAndInput(t,e,i,n,s){t&&(t.value=String(i),t.min=String(n),t.max=String(s)),e&&(e.value=String(i),e.min=String(n),e.max=String(s))}handleTransformChange(t,e){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(t,e),s={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[t]:i};this.currentClip={...this.currentClip,visualTransform:s},this.updateUIControls(),this.onClipUpdate(this.currentClip.id,{visualTransform:s})}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 yn{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 n=i.getClips().find(s=>s.id===e);if(n)return{clip:n,track:i,trackId:this.resolveTrackId(i)}}return null}findClipAtTime(t,e){for(const i of t){const n=i.getClips().find(s=>e>=s.startTime&&e<s.startTime+s.duration);if(n)return{clip:n,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 n=this.findClipById(i,t);if(!n||!n.trackId)return{status:"missing_source_track",clipId:t,targetTrackId:e};const{clip:s,track:a,trackId:o}=n;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!==s.type?{status:"track_type_mismatch",clipId:t,targetTrackId:e,sourceTrackId:o}:{status:"ready",clip:s,sourceTrack:a,sourceTrackId:o,targetTrack:l,targetTrackId:e}}planTrackPlacement(t,e){var s;const i=t.startTime+t.duration;for(const a of e){if(((s=a.getTrackType)==null?void 0:s.call(a))!==t.type)continue;if(!a.getClips().some(l=>t.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(a);if(l)return{status:"use_existing_track",trackId:l}}}const n=e.filter(a=>{var o;return((o=a.getTrackType)==null?void 0:o.call(a))===t.type}).length+1;return{status:"create_track",trackType:t.type,suggestedTrackName:t.type==="video"?`视频轨道 ${n}`:`音频轨道 ${n}`}}planCrossTrackMove(t,e,i,n,s,a){var g;const o=this.resolveTrackTargetByY(e,n,s,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=a.find(y=>this.resolveTrackId(y)===l);if(!h)return{status:"missing_target_track_view",targetTrackId:l};const c=this.resolveTrackType(h)??((g=s.find(y=>y.id===l))==null?void 0:g.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,n,s);if(d)return{status:"create_track",trackType:t.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=s.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=a.find(w=>this.resolveTrackId(w)===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=a.find(w=>this.resolveTrackId(w)===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,n,s,a){const o=this.planCrossTrackMove(t,e,i,n,s,a);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(lt.MIN,Math.min(lt.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,n){let s=e,a=null,o=null;for(const l of i){const h=l.type==="video"?bt.VIDEO:bt.AUDIO,c=s+h;if(l.type===n&&(a===null&&(a=s),o=c),t>=s&&t<c)return{status:"existing_track",targetTrackId:l.id};s=c}return n==="video"&&a!==null&&t<a?{status:"create_track",insertionPlacement:"top_of_type_region"}:n==="audio"&&o!==null&&t>=o?{status:"create_track",insertionPlacement:"bottom_of_type_region"}:{status:"missing_target_track_by_position"}}resolvePreferredInsertionPlacement(t,e,i,n,s){let a=n;const o=s.map(d=>{const u=a,p=d.type==="video"?bt.VIDEO:bt.AUDIO,g=u+p;return a=g,{id:d.id,type:d.type,role:d.role,startY:u,endY:g,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(n=>n.id===t.id?!1:t.startTime<n.endTime&&i>n.startTime)}}class _i{constructor(t,e,i,n=100){f(this,"state");f(this,"maxHistorySize",100);f(this,"onActionUndo");f(this,"onActionRedo");f(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=n,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:t,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,n,s){return{type:"resize_clip",data:{clipId:t,newDuration:e,newStartTime:i,previousDuration:n,previousStartTime:s},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,n,s,a,o){return{type:"move_clip_between_tracks",data:{clipId:t,sourceTrackId:e,targetTrackId:i,clipBefore:n,clipAfter:s,sourceTrackSnapshot:a,targetTrackSnapshot:o},timestamp:Date.now()}}createSeparateClipAudioAction(t,e,i,n){return{type:"separate_clip_audio",data:{videoClipBefore:t,videoClipAfter:e,audioClip:i,audioTrackId:n},timestamp:Date.now()}}createRestoreClipAudioAction(t,e,i,n){return{type:"restore_clip_audio",data:{videoClipBefore:t,videoClipAfter:e,audioClip:i,audioTrackId:n},timestamp:Date.now()}}}class Sn{constructor(t){this.target=t}executeUndo(t){var e,i;switch(t.type){case"add_clip":this.target.removeClip(t.data.id);break;case"remove_clip":{const n=t.data,s=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();s==null||s.addClip(n),(i=(e=this.target).loadClipThumbnails)==null||i.call(e,n);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 s=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();s==null||s.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);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;default:R.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:t.type})}}executeRedo(t){var e,i;switch(t.type){case"add_clip":{const n=t.data,s=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();s==null||s.addClip(n),(i=(e=this.target).loadClipThumbnails)==null||i.call(e,n);break}case"remove_clip":this.target.removeClip(t.data.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);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;default:R.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:t.type})}}restoreMovedClip(t,e,i){let n=(e==null?void 0:e.id)??null;e&&(n=this.target.ensureTrackFromHistorySnapshot(e)),n&&this.target.moveClipToTrack(t,n),this.target.updateClip(t,i)}}const Do=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId"],Go=new Set(["thumbnails"]);function Oo(r,t){return Object.is(r,t)?!0:r===void 0||t===void 0?!1:typeof r=="object"&&typeof t=="object"?JSON.stringify(r)===JSON.stringify(t):!1}class Cn{constructor(t){this.history=t}recordAddClip(t){const e=this.history.createAddClipAction(t);return this.history.addAction(e),e}recordRemoveClip(t){const e=this.history.createRemoveClipAction(t);return this.history.addAction(e),e}recordClipUpdate(t,e,i){const n=this.createClipUpdateAction(t,e,i);return n?(this.history.addAction(n),n):null}recordSplitClip(t,e){const i={...t,id:t.id.replace("_split_",""),duration:t.duration+e.duration,endTime:e.endTime,endTimeAtSource:e.endTimeAtSource},n=this.history.createSplitClipAction(i,t,e);return this.history.addAction(n),n}recordRemoveGaps(t){if(t.length===0)return null;const e=this.history.createRemoveGapsAction(t);return this.history.addAction(e),e}recordMoveClipBetweenTracks(t,e,i,n,s,a,o){const l=this.history.createMoveClipBetweenTracksAction(t,e,i,n,s,a,o);return this.history.addAction(l),l}recordSeparateClipAudio(t,e,i,n){const s=this.history.createSeparateClipAudioAction(t,e,i,n);return this.history.addAction(s),s}recordRestoreClipAudio(t,e,i,n){const s=this.history.createRestoreClipAudioAction(t,e,i,n);return this.history.addAction(s),s}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 a={},o={};return Do.forEach(h=>{Oo(t[h],e[h])||(a[h]=t[h],o[h]=e[h])}),Object.keys(a).length===0||Object.keys(a).every(h=>Go.has(h))?null:this.history.createUpdateClipAction(t.id,a,o)}}function oi(r){r.notifySelectionChange(),r.emitSelectedClipChangeIfNeeded(),r.handleClipChange()}function Bo(r){var t,e;r.notifySelectionChange(),(t=r.reloadClipThumbnailsIfNeeded)==null||t.call(r),(e=r.checkTrackDurationChange)==null||e.call(r),r.emitSelectedClipChangeIfNeeded(),r.handleClipChange()}function Ho(r,t,e=!1){if(!t||!e||r.type==="audio")return!1;const i=t.duration!==r.duration,n=t.startTimeAtSource!==r.startTimeAtSource||t.endTimeAtSource!==r.endTimeAtSource;return i||n}function zo(r,t){if(r.length===0)return!1;const e=Math.max(...r.map(i=>i.endTime));return t<e}function No(r){return r.currentCanPlay===r.nextCanPlay?r.currentCanPlay:(r.setCanPlay(r.nextCanPlay),r.currentCanPlay&&!r.nextCanPlay&&r.playState==="playing"&&(r.pauseTimeline(),r.setCurrentTime(r.clipEndTime||1)),r.emitCanPlayChange(r.nextCanPlay),r.nextCanPlay)}function Fo(r){const t=!r.id&&r.startTime>0;return{shouldJumpToTime:t,jumpTime:t?r.startTime:null,shouldSelectClip:!!r.id}}function Ye(r){var t;return r.applied?(r.isExecutingHistoryAction||(t=r.recordHistory)==null||t.call(r),r.applyEffects(),!0):!1}function Vo(r){return Ye({applied:r.applied,isExecutingHistoryAction:r.isExecutingHistoryAction,recordHistory:()=>{var t;(t=r.recordMoveClipBetweenTracks)==null||t.call(r,r.clipId,r.sourceTrackId,r.targetTrackId,r.clipBefore,r.clipAfter,r.sourceTrackSnapshot,r.targetTrackSnapshot)},applyEffects:r.applyEffects})}function Wo(r){var t;r.isExecutingHistoryAction||(t=r.recordSplitClip)==null||t.call(r,r.clip1,r.clip2),r.emitClipUpdated(r.clip1),r.emitClipAdded(r.clip2),r.applyEffects()}const li={x:.5,y:.5,scale:1},Yo=.1,Xo=8;function hi(r,t){return typeof r=="number"&&Number.isFinite(r)?r:t}function Uo(r){return Math.min(Xo,Math.max(Yo,r))}function ut(r){return{x:hi(r==null?void 0:r.x,li.x),y:hi(r==null?void 0:r.y,li.y),scale:Uo(hi(r==null?void 0:r.scale,li.scale))}}function Ts(r,t,e=1e-4){const i=ut(r),n=ut(t);return Math.abs(i.x-n.x)<=e&&Math.abs(i.y-n.y)<=e&&Math.abs(i.scale-n.scale)<=e}function vs(r,t){if(r.width<=0||r.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const e=t.width>0?t.width:r.width,i=t.height>0?t.height:r.height,n=e/i,s=r.width/r.height;let a=r.width,o=r.height;n>s?o=a/n:a=o*n;const l=(r.width-a)/2,h=(r.height-o)/2;return{left:l,top:h,width:a,height:o,centerX:l+a/2,centerY:h+o/2}}function Tn(r,t,e){const i=vs(r,t),n=ut(e),s=i.width*n.scale,a=i.height*n.scale,o=r.width*n.x,l=r.height*n.y;return{left:o-s/2,top:l-a/2,width:s,height:a,centerX:o,centerY:l}}function $o(r,t,e,i){const n=ut(r),s=i.width>0?i.width:1,a=i.height>0?i.height:1;return ut({x:n.x+t/s,y:n.y+e/a,scale:n.scale})}function qo(r,t,e,i,n,s){const a=ut(s),o=Math.max(n.width/2,1),l=Math.max(n.height/2,1),h=Math.abs(e-r)/o,c=Math.abs(i-t)/l;return ut({x:a.x,y:a.y,scale:Math.max(h,c)})}function vn(r){if(!r)return 0;const t=Number.parseFloat(r);return Number.isFinite(t)?t:0}class Ko{constructor(t={}){f(this,"frameElement",null);f(this,"overlayElement",null);f(this,"boxElement",null);f(this,"handleElements",new Map);f(this,"handlePointerDownHandlers",new Map);f(this,"state",null);f(this,"interaction",null);f(this,"callbacks");f(this,"boundPointerMove",t=>{this.handleDocumentPointerMove(t)});f(this,"boundPointerUp",()=>{this.finishInteraction(!0)});f(this,"boundVisibilityChange",()=>{var t;(t=this.getDocument())!=null&&t.hidden&&this.finishInteraction(!1)});f(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});f(this,"handleMovePointerDown",t=>{var i,n;const e=t;(e.button??0)!==0||!this.state||((i=e.preventDefault)==null||i.call(e),(n=e.stopPropagation)==null||n.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,n)=>{const s=this.handlePointerDownHandlers.get(n);s&&i.removeEventListener("pointerdown",s)}),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 n=this.getHandlePointerDown(t);i.addEventListener("pointerdown",n),this.handleElements.set(t,i),this.handlePointerDownHandlers.set(t,n),this.boxElement.appendChild(i)}getHandlePointerDown(t){return e=>{var s,a;const i=e;if((i.button??0)!==0||!this.state)return;(s=i.preventDefault)==null||s.call(i),(a=i.stopPropagation)==null||a.call(i);const n=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:n},this.setGlobalCursor(n),this.bindDocumentListeners()}}bindDocumentListeners(){var e,i,n,s,a;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),(n=t.addEventListener)==null||n.call(t,"visibilitychange",this.boundVisibilityChange),(a=(s=globalThis.window)==null?void 0:s.addEventListener)==null||a.call(s,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var e,i,n,s,a;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),(n=t.removeEventListener)==null||n.call(t,"visibilitychange",this.boundVisibilityChange),(a=(s=globalThis.window)==null?void 0:s.removeEventListener)==null||a.call(s,"blur",this.boundWindowBlur))}handleDocumentPointerMove(t){var s,a,o;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const e=t;(s=e.preventDefault)==null||s.call(e);const i=this.toLocalPoint(e);let n=this.interaction.startTransform;if(this.interaction.mode==="move")n=$o(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=qo(l,h,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=n,this.interaction.changed=!Ts(this.interaction.startTransform,n),(o=(a=this.callbacks).onPreviewTransformChange)==null||o.call(a,this.interaction.clipId,n)}finishInteraction(t){var i,n,s,a;const e=this.interaction;if(!e){this.setGlobalCursor(null),this.unbindDocumentListeners();return}t&&e.changed&&((n=(i=this.callbacks).onPreviewTransformCommit)==null||n.call(i,e.clipId,e.nextTransform)),(a=(s=this.callbacks).onPreviewTransformChange)==null||a.call(s,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 n=this.handleElements.get(t);n&&(n.style.left=`${e}px`,n.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:vn(this.frameElement.style.left),top:vn(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 jo(r,t){return!Jt(r.mode)||!t?r:{mode:St.mode,width:t.width,height:t.height}}function Zo(r){return r.getAttribute("src")||r.currentSrc||r.src||""}function bn(r){return typeof HTMLVideoElement<"u"?r instanceof HTMLVideoElement:r.tagName==="VIDEO"}function oe(r){try{r.load()}catch{}}function jt(r){try{r.pause()}catch{}}function Jo(r){var t;try{const e=r.play();(t=e==null?void 0:e.catch)==null||t.call(e,()=>{})}catch{}}function wn(r,t){try{r.currentTime=Math.max(0,t)}catch{}}function ze(r,t){var i;const e=(i=r==null?void 0:r.clip.style)==null?void 0:i[t];return typeof e=="number"&&e>0?e:null}function kn(r){if(!r)return 0;const t=Number.parseFloat(r);return Number.isFinite(t)?t:0}class Qo{constructor(t={},e={}){f(this,"container",null);f(this,"rootElement",null);f(this,"frameElement",null);f(this,"pendingOverlayElement",null);f(this,"pendingOverlayStatusElement",null);f(this,"pendingOverlayDetailElement",null);f(this,"pendingOverlayActionElement",null);f(this,"resizeObserver",null);f(this,"trackSlots",new Map);f(this,"audioContext",null);f(this,"masterGainNode",null);f(this,"isBuffering",!1);f(this,"loadingCount",0);f(this,"selectedClipId",null);f(this,"transientVisualTransform",null);f(this,"callbacks");f(this,"dependencies");f(this,"transformOverlay");f(this,"requestedAspectRatio",{...St});f(this,"resolvedAutoAspectRatio",null);f(this,"aspectRatioProbe",null);f(this,"aspectRatioProbeSrc",null);f(this,"isAspectRatioProbeLoading",!1);f(this,"pendingState",null);this.callbacks=t,this.dependencies=e,this.transformOverlay=new Ko({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,n)=>{var s,a;(a=(s=this.callbacks).onVisualTransformCommit)==null||a.call(s,i,n)}})}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 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 a=document.createElement("div");a.className="timeline-preview-pending-overlay__detail",a.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(a),n.appendChild(o),e.appendChild(n),t.appendChild(e),this.rootElement=e,this.frameElement=i,this.pendingOverlayElement=n,this.pendingOverlayStatusElement=s,this.pendingOverlayDetailElement=a,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,n,s,a;(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&&(jt(this.aspectRatioProbe),this.aspectRatioProbe.src="",oe(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.isAspectRatioProbeLoading=!1,this.audioContext&&((s=(i=(e=this.audioContext).close)==null?void 0:(n=i.call(e)).catch)==null||s.call(n,()=>{}),this.audioContext=null,this.masterGainNode=null),(a=this.rootElement)==null||a.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 s,a;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)),n=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,n.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,jt(l.current.element),this.setSlotVisible(l.current,!1,0),this.preparePreloadSlot(l.preload,n.get(o)||null));this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.selectedClipId&&(this.transientVisualTransform=null),this.refreshVisualLayout(),this.refreshLoadingState(),this.refreshBufferingState(),(a=(s=this.callbacks).onSyncProcessed)==null||a.call(s,t.syncRequestId)}applyAspectRatio(t){this.requestedAspectRatio=At(t),this.updateFrameLayout()}getAspectRatio(){return jo(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}createMediaElement(t,e){const i=this.dependencies.createMediaElement,n=i?i(t,e):document.createElement(t==="video"?"video":"audio");return n.preload=e==="preload"?"auto":"metadata",n.crossOrigin="anonymous",n.loop=!1,n.controls=!1,bn(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(t,e,i){var p,g;const n=this.createMediaElement(e,i),s=e==="video"?document.createElement("div"):null;if(s){const y=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";s.className=`${y} timeline-preview-slot--${t} 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),(p=this.frameElement)==null||p.appendChild(s)}const a={role:i,trackId:t,kind:e,wrapper:s,element:n,attachedClipId:null,attachedSrc:null,entry:null,isActive:!1,isLoading:!1,isBuffering:!1,isSeeking:!1,sourceNode:null,gainNode:null,audioRoutingFailed:!1,cleanup:[]},o=()=>{a.isLoading=!0,this.refreshLoadingState()},l=()=>{a.isLoading=!1,a.isSeeking=!1,a.isBuffering=!1,this.tryResolveAutoAspectRatioFromSlot(a),this.refreshVisualLayout(),this.refreshLoadingState(),this.refreshBufferingState()},h=()=>{a.isBuffering=a.isActive,this.refreshBufferingState()},c=()=>{a.isSeeking=!0,a.isBuffering=a.isActive,this.refreshBufferingState()},d=()=>{a.isSeeking=!1,a.isBuffering=!1,this.refreshBufferingState()},u=()=>{a.isLoading=!1,a.isSeeking=!1,a.isBuffering=!1,this.refreshLoadingState(),this.refreshBufferingState()};return n.addEventListener("loadstart",o),n.addEventListener("loadedmetadata",l),n.addEventListener("canplay",l),n.addEventListener("playing",l),n.addEventListener("waiting",h),n.addEventListener("stalled",h),n.addEventListener("seeking",c),n.addEventListener("seeked",d),n.addEventListener("error",u),a.cleanup.push(()=>n.removeEventListener("loadstart",o),()=>n.removeEventListener("loadedmetadata",l),()=>n.removeEventListener("canplay",l),()=>n.removeEventListener("playing",l),()=>n.removeEventListener("waiting",h),()=>n.removeEventListener("stalled",h),()=>n.removeEventListener("seeking",c),()=>n.removeEventListener("seeked",d),()=>n.removeEventListener("error",u)),e==="audio"&&((g=this.rootElement)==null||g.appendChild(n)),a}destroySlot(t){var e,i,n,s,a;t.cleanup.forEach(o=>o()),jt(t.element),t.element.src="",oe(t.element),(i=(e=t.gainNode)==null?void 0:e.disconnect)==null||i.call(e),(s=(n=t.sourceNode)==null?void 0:n.disconnect)==null||s.call(n),t.gainNode=null,t.sourceNode=null,(a=t.wrapper)==null||a.remove(),t.element.remove()}getTrackSlots(t,e){const i=this.trackSlots.get(t);if(i)return i;const n={current:this.createSlot(t,e,"current"),preload:this.createSlot(t,e,"preload")};return this.trackSlots.set(t,n),n}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,n=t.attachedSrc||Zo(t.element);(t.attachedClipId!==e.clip.id||n!==i)&&(t.attachedClipId=e.clip.id,t.attachedSrc=i,t.isLoading=!0,t.isBuffering=!1,t.element.setAttribute("src",i),oe(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,n){t.isActive=!0,t.entry=e,t.element.playbackRate=i;const s=e.mediaTime/1e3,a=Math.max(.1,i*.15);Math.abs(t.element.currentTime-s)>a&&(t.isSeeking=!0,t.isBuffering=!0,wn(t.element,s),this.refreshBufferingState()),n==="playing"?(this.resumeAudioContext(),Jo(t.element)):jt(t.element),this.setSlotVisible(t,e.hasVisual,1e3-e.trackOrder)}preparePreloadSlot(t,e){if(t.isActive=!1,t.isBuffering=!1,t.isSeeking=!1,!e){jt(t.element),t.entry=null,t.attachedClipId=null,t.attachedSrc=null,t.isLoading=!1,t.element.removeAttribute("src"),oe(t.element),this.setSlotVisible(t,!1,0);return}this.assignClipToSlot(t,e),t.element.playbackRate=1,wn(t.element,e.clip.startTimeAtSource/1e3),jt(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,n;!this.audioContext||this.audioContext.state!=="suspended"||(n=(e=(t=this.audioContext).resume)==null?void 0:(i=e.call(t)).catch)==null||n.call(i,()=>{})}updateFrameLayout(){if(!this.container||!this.frameElement)return;const{width:t,height:e}=this.getAspectRatio(),i=this.container.clientWidth,n=this.container.clientHeight;if(i<=0||n<=0||t<=0||e<=0)return;const s=t/e,a=i/n;let o=i,l=n;s>a?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(t){if(!Jt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!t||!t.hasVisual)return;const e=ze(t,"sys_width"),i=ze(t,"sys_height");if(e&&i){this.handleResolvedAutoAspectRatio(e,i);return}if(this.aspectRatioProbeSrc===t.clip.src)return;const n=this.getAspectRatioProbe();this.aspectRatioProbeSrc=t.clip.src,this.isAspectRatioProbeLoading=!0,this.refreshLoadingState(),n.crossOrigin="anonymous",n.preload="metadata",n.muted=!0,n.src=t.clip.src,oe(n)}getAspectRatioProbe(){var n,s;if(this.aspectRatioProbe)return this.aspectRatioProbe;const t=((s=(n=this.dependencies).createAspectRatioProbe)==null?void 0:s.call(n))||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(!Jt(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,n;t<=0||e<=0||(this.resolvedAutoAspectRatio={width:t,height:e},this.updateFrameLayout(),Jt(this.requestedAspectRatio.mode)&&((n=(i=this.callbacks).onAspectRatioChange)==null||n.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),n=this.getEffectiveVisualTransform(t.entry),s=Tn(e,i,n);t.wrapper.style.left=`${s.left}px`,t.wrapper.style.top=`${s.top}px`,t.wrapper.style.width=`${s.width}px`,t.wrapper.style.height=`${s.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),n=this.getEffectiveVisualTransform(e.entry);return{clipId:e.entry.clip.id,transform:n,frameSize:t,baseRect:vs(t,i),displayRect:Tn(t,i,n)}}return null}getFrameSize(){var i,n,s,a;const t=((i=this.frameElement)==null?void 0:i.clientWidth)??0,e=((n=this.frameElement)==null?void 0:n.clientHeight)??0;return{width:t>0?t:kn((s=this.frameElement)==null?void 0:s.style.width),height:e>0?e:kn((a=this.frameElement)==null?void 0:a.style.height)}}getMediaSize(t,e,i){if(bn(t.element)&&t.element.videoWidth>0&&t.element.videoHeight>0)return{width:t.element.videoWidth,height:t.element.videoHeight};const n=ze(e,"sys_width"),s=ze(e,"sys_height");return n&&s?{width:n,height:s}:{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:ut(t.clip.visualTransform)}}class tl extends Qo{destroy(){this.detach()}}function el(r){return"dom"}const il=36e5,nl=3e5;function bs(r){return r.length===0?0:r.reduce((t,e)=>Math.max(t,e.startTime+e.duration),0)}function ws(r){return Math.max(r+nl,il)}function sl(r){const t=bs(r.clips);return t===r.lastTrackDuration?r.lastTrackDuration:(r.setLastTrackDuration(t),r.setTimelineDuration(ws(t)),r.emitTrackDurationChange(t),t)}class _n{constructor(t={}){f(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(n){R.error("TimelineEventDispatcher",`Error in event listener for ${t}:`,{error:n})}})}clear(){this.listeners.clear()}}function rl(r){return[...r].sort((t,e)=>t.order-e.order)}function al(r){return[...r].sort((t,e)=>t.startTime-e.startTime)}function ci(r,t,e){return{trackId:r.id,trackType:r.type,trackOrder:r.order,clip:t,mediaTime:e,muted:(r.isMuted??!1)||(t.isMuted??!1),kind:r.type,hasVisual:r.type==="video",hasAudio:!0}}class ol{resolveActiveClipsAtTime(t,e){return this.resolvePlaybackPlan(t,e).activeClips}resolvePlaybackPlan(t,e){const i=rl(t),n=[],s=[];let a=null;for(const o of i){const l=al(o.clips),h=l.find(d=>e>=d.startTime&&e<d.endTime);if(h){const d=h.startTimeAtSource+(e-h.startTime);n.push(ci(o,h,d))}const c=l.find(d=>d.startTime>e);if(c&&s.push(ci(o,c,c.startTimeAtSource)),!a&&o.type==="video"){const d=l[0];d&&(a=ci(o,d,d.startTimeAtSource))}}return{activeClips:n,nextClips:s,firstVideoClip:a}}}function ll(r){var e;const t=r.getSelectedClip()||((e=r.findFallbackSelectedClip)==null?void 0:e.call(r))||null;return{clip:t,hasSelectedClip:!!t}}function hl(r){var i;const t=r.resolveSelectedClip(),e=((i=t.clip)==null?void 0:i.id)||null;return e===r.lastSelectedClipId?r.lastSelectedClipId:(r.emitSelectedClipChange(t),e)}function ks(r,t){var e,i,n,s;return((i=(e=r.findById(t))==null?void 0:e.getId)==null?void 0:i.call(e))||((s=(n=r.getLastTrack())==null?void 0:n.getId)==null?void 0:s.call(n))||t}function cl(r){if(r.placement.status==="use_existing_track")return r.trackCollection.addClipToTrack(r.placement.trackId,r.clip);const t=r.createTrack(r.placement.trackType,r.placement.suggestedTrackName),e=ks(r.trackCollection,t);return e?r.trackCollection.addClipToTrack(e,r.clip):!1}function dl(r,t,e){return t.trackId?r.removeClipFromTrack(t.trackId,e):!1}function ul(r){return r.trackCollection.moveClipToTrack(r.command.clip,r.command.sourceTrackId,r.command.targetTrackId)}function fl(r){const t=r.createTrack(r.trackType,r.trackName),e=ks(r.trackCollection,t);return e?r.trackCollection.moveClipToTrack(r.clip,r.currentTrackId,e):!1}function Ht(r){var t,e,i,n;(t=r.checkTrackDurationChange)==null||t.call(r),(e=r.updateCanPlayState)==null||e.call(r),(i=r.updateTrackInfoPanel)==null||i.call(r),(n=r.handleClipChange)==null||n.call(r)}function gl(r){var t,e;r.notifySelectionChange(),(t=r.cleanupEmptyTracks)==null||t.call(r),r.updateTrackInfoPanel(),(e=r.batchDraw)==null||e.call(r),r.syncPreviewSession()}class pl{constructor(){f(this,"panel",null)}init(t){var i,n,s,a;const e=((i=t.theme)==null?void 0:i.background)||"#1a1a1a";this.panel=new Ss({container:t.container,theme:{background:e,border:((n=t.theme)==null?void 0:n.border)||"#333333",text:((s=t.theme)==null?void 0:s.clipName)||"#ffffff",buttonBackground:((a=t.theme)==null?void 0:a.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 Pn{syncCurrentTime(t,e,i,n){t==null||t.setCurrentTime(n),e==null||e.setCurrentTime(n),i.syncCurrentTime(n)}syncZoom(t,e,i,n){t==null||t.setZoom(n),e==null||e.setZoom(n),i.syncZoom(n)}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){if(t.getAll().some(s=>s.updateSelectionVisual)){t.forEach(s=>{var a;(a=s.updateSelectionVisual)==null||a.call(s,e)});return}if(e){let s=null;t.forEach(o=>{var c,d;const l=(c=o.getSelectedClip)==null?void 0:c.call(o);o.getClips().some(u=>u.id===e)&&(s=o),(!l||l.id!==e)&&((d=o.clearSelection)==null||d.call(o))});const a=s==null?void 0:s.selectClip;typeof a=="function"&&a(e);return}t.clearSelection()}findSelectedClip(t){var e;for(const i of t.getAll()){const n=(e=i.getSelectedClip)==null?void 0:e.call(i);if(n)return n}return null}}class xn{constructor(t,e=$e){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,t.dragActivationThreshold,t.enableClipSnap,t.clipSnapThreshold)}}class ml{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 n=this.tracks[i];if(((e=n.getRole)==null?void 0:e.call(n))==="primary"||(typeof n.getClips=="function"?n.getClips():[]).length>0)continue;const[a]=this.tracks.splice(i,1);a&&t.push(a)}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 n;return(n=i.updateClip)==null?void 0:n.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 n=this.findById(e),s=this.findById(i);return!(n!=null&&n.removeClip)||!(s!=null&&s.addClip)?!1:(n.removeClip(t.id),s.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 _s{constructor(t=[]){f(this,"tracks",[]);f(this,"trackCounter",0);this.tracks=[...t],this.trackCounter=this.tracks.length}createTrack(t,e,i,n){this.trackCounter++;const s=e||`${t==="video"?"视频":"音频"}轨道 ${this.trackCounter}`,a=this.tracks.length===0?"primary":"normal",o={id:`track_${Date.now()}_${this.trackCounter}`,type:t,name:s,order:this.tracks.length,role:a,clips:[]};return this.insertTrack(o,i,n),R.debugLazy("TrackManager",()=>`创建轨道: ${s}`,()=>({trackId:o.id,type:t,order:o.order})),o}removeTrack(t){var i;const e=this.tracks.findIndex(n=>n.id===t);return e===-1?(R.warn("TrackManager",`轨道不存在: ${t}`),!1):((i=this.tracks[e])==null?void 0:i.role)==="primary"?(R.warn("TrackManager",`主轨不可删除: ${t}`),!1):(this.tracks.splice(e,1),this.recalculateOrder(),R.debugLazy("TrackManager",()=>`删除轨道: ${t}`),!0)}renameTrack(t,e){const i=this.tracks.find(n=>n.id===t);return i?(i.name=e,R.debugLazy("TrackManager",()=>`重命名轨道: ${t} -> ${e}`),!0):(R.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(n=>n.id===t);return i?(Object.assign(i,e),R.debugLazy("TrackManager",()=>`更新轨道: ${t}`,()=>e),!0):(R.warn("TrackManager",`轨道不存在: ${t}`),!1)}recalculateOrder(){this.tracks.forEach((t,e)=>{t.order=e})}insertTrack(t,e,i){const n=this.tracks.findIndex(a=>a.role==="primary"),s=e??(t.type==="video"?"before_primary":"after_primary");if(n===-1||t.role==="primary"){this.tracks.push(t),this.recalculateOrder();return}if((s==="before_track"||s==="after_track")&&i){const a=this.tracks.findIndex(o=>o.id===i);if(a!==-1){this.tracks.splice(a+(s==="after_track"?1:0),0,t),this.recalculateOrder();return}}if(s==="top_of_type_region"){const a=this.tracks.findIndex(o=>o.type===t.type);if(a!==-1){this.tracks.splice(a,0,t),this.recalculateOrder();return}}if(s==="bottom_of_type_region"){const a=this.tracks.reduce((o,l,h)=>l.type===t.type?h:o,-1);if(a!==-1){this.tracks.splice(a+1,0,t),this.recalculateOrder();return}}s==="before_primary"?this.tracks.splice(n,0,t):this.tracks.splice(n+1,0,t),this.recalculateOrder()}muteTrack(t,e){const i=this.tracks.find(n=>n.id===t);return i?(i.isMuted=e,R.debugLazy("TrackManager",()=>`${e?"静音":"取消静音"}轨道:${t}`),!0):(R.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 Ft(r){return r==="video"?bt.VIDEO:bt.AUDIO}function le(r,t,e){let i=e;for(const n of r){if(n.id===t)break;i+=Ft(n.type)}return i}function En(r,t){return r.reduce((e,i)=>e+Ft(i.type),t)}function yl(r,t){let e=t;return r.map(i=>{const n=Ft(i.type),s={trackId:i.id,y:e,height:n};return e+=n,s})}const Ps=200,xs=8,An="timeline-manager-managed-layout-styles";function Sl(){if(typeof document>"u"||document.getElementById(An))return;const r=document.createElement("style");r.id=An,r.textContent=`
|
|
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=`
|
|
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(r)}function Cl(r,t){Sl();const e=t.leftPanelWidth??Ps,i=t.scrollbarSize??xs;r.innerHTML="",r.classList.add("timeline-manager-root"),r.style.gridTemplateColumns=`${e}px minmax(0, 1fr)`,r.style.gridTemplateRows=`${t.timeScaleHeight}px minmax(0, 1fr)`,r.style.background=t.theme.background;const n=Tt("div");n.className="timeline-manager-header-corner",Ne(n,t.theme),n.style.gridColumn="1",n.style.gridRow="1",n.style.borderBottom=`1px solid ${t.theme.border}`;const s=Tt("div");s.className="timeline-manager-header-viewport",Ne(s,t.theme),s.style.gridColumn="2",s.style.gridRow="1",s.style.borderBottom=`1px solid ${t.theme.border}`,s.style.overflow="hidden";const a=Tt("div");a.className="timeline-manager-header-canvas-host",a.style.width="100%",a.style.height="100%",s.appendChild(a);const o=Tt("div");o.className="timeline-manager-track-info-viewport",Ne(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=Tt("div");l.className="timeline-manager-scroll-viewport timeline-manager-body-viewport",Ne(l,t.theme),l.style.gridColumn="2",l.style.gridRow="2",l.style.overflowX="hidden",l.style.overflowY="auto";const h=Tt("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=Tt("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=Tt("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=Tt("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",r.appendChild(n),r.appendChild(s),r.appendChild(o),r.appendChild(l),r.appendChild(c),r.appendChild(d),r.appendChild(u),{headerCorner:n,headerViewport:s,headerCanvasHost:a,trackInfoViewport:o,bodyViewport:l,bodyCanvasHost:h,verticalScrollbarCanvasHost:c,horizontalScrollbarCanvasHost:d,playheadOverlay:u}}function Tt(r){return document.createElement(r)}function Ne(r,t){r.style.position="relative",r.style.minWidth="0",r.style.minHeight="0",r.style.maxWidth="100%",r.style.boxSizing="border-box",r.style.background=t.background,r.style.color=t.clipName}class Tl{constructor(t){f(this,"currentTime");f(this,"playState");f(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 vl{constructor(){f(this,"selectedClipId",null)}getSelectedClipId(){return this.selectedClipId}setSelectedClipId(t){this.selectedClipId=t}clear(){this.selectedClipId=null}hasSelection(){return this.selectedClipId!==null}}class bl{constructor(t){f(this,"zoom");f(this,"duration");f(this,"scrollLeft");f(this,"scrollTop");f(this,"viewportWidth");f(this,"viewportHeight");f(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 Ln{constructor(t){f(this,"selectionStore");f(this,"playbackStore");f(this,"viewportStore");this.selectionStore=new vl,this.playbackStore=new Tl({currentTime:t.currentTime,playState:t.playState,speed:t.speed}),this.viewportStore=new bl({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 wl{constructor(t,e,i,n,s){f(this,"stage");f(this,"layer");f(this,"onTimeChange");f(this,"onScrollChange");f(this,"config");f(this,"theme");f(this,"scrollLeft",0);f(this,"timeScaleHeight",40);f(this,"isDragging",!1);f(this,"dragStartX",0);f(this,"isPointerInsideTimeline",!1);f(this,"lastPointerXInTimeline",null);f(this,"hasBoundGlobalPointerListenersForDrag",!1);f(this,"handleGlobalPointerMove",t=>{this.isDragging&&this.handlePointerMove(t)});f(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});f(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=t,this.layer=e,this.onTimeChange=n,this.onScrollChange=s,this.config={duration:i.duration||36e5,zoom:i.zoom||lt.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:ve(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=D.timeToPixels(t,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,e-i/2))}scrollToClip(t){const e=D.timeToPixels(t.startTime,this.config.zoom),n=D.timeToPixels(t.startTime+t.duration,this.config.zoom)-e,s=this.stage.width(),a=n<=s?Math.max(0,e-(s-n)/2):Math.max(0,e);this.setScrollLeft(a)}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=_e({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Pe({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),n=this.scrollLeft;this.dragStartX=t.clientX,this.scrollLeft=i,this.render(),n!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(t){return D.pixelsToTime(t-at+this.scrollLeft,this.config.zoom)}timeToPixel(t){return D.timeToPixels(t,this.config.zoom)-this.scrollLeft+at}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 n=it.createRect(0,0,t,e,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 t=this.stage.width(),e=this.scrollLeft,i=this.scrollLeft+t,n=D.pixelsToTime(e,this.config.zoom),s=D.pixelsToTime(i,this.config.zoom),a=D.msToSeconds(n),o=D.msToSeconds(s),{majorStep:l,minorStep:h}=D.getTickConfig(this.config.zoom),c=D.generateVisibleTicks(a-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,D.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(e,t))}}class kl{constructor(t,e,i,n,s,a){f(this,"container");f(this,"lineElement");f(this,"handleElement");f(this,"theme");f(this,"onTimeChange");f(this,"currentTime");f(this,"zoom");f(this,"scrollLeft",0);f(this,"height");f(this,"isDragging",!1);f(this,"hasBoundGlobalPointerListeners",!1);f(this,"handleGlobalPointerMove",t=>{this.isDragging&&this.updateTimeFromClientX(t.clientX)});f(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListeners()});f(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});f(this,"handleMouseDown",t=>{t.preventDefault(),t.stopPropagation(),this.isDragging=!0,this.bindGlobalPointerListeners()});f(this,"handleHandleClick",t=>{t.preventDefault(),t.stopPropagation()});this.container=t,this.currentTime=e,this.zoom=i,this.height=n,this.theme=s,this.onTimeChange=a,this.container.innerHTML="",this.container.style.position="absolute",this.container.style.pointerEvents="none",this.lineElement=document.createElement("div"),this.lineElement.className="timeline-manager-playhead-line",this.lineElement.style.position="absolute",this.lineElement.style.top="0",this.lineElement.style.width="1px",this.lineElement.style.background=this.theme.playhead,this.lineElement.style.pointerEvents="none",this.handleElement=document.createElement("div"),this.handleElement.className="timeline-manager-playhead-handle",this.handleElement.style.position="absolute",this.handleElement.style.top="0",this.handleElement.style.width="18px",this.handleElement.style.height="12px",this.handleElement.style.marginLeft="-9px",this.handleElement.style.background=this.theme.playhead,this.handleElement.style.clipPath="polygon(50% 100%, 0 0, 100% 0)",this.handleElement.style.cursor="ew-resize",this.handleElement.style.pointerEvents="auto",this.container.appendChild(this.lineElement),this.container.appendChild(this.handleElement),this.handleElement.addEventListener("mousedown",this.handleMouseDown),this.handleElement.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.handleElement.removeEventListener("mousedown",this.handleMouseDown),this.handleElement.removeEventListener("click",this.handleHandleClick),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=_e({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Pe({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(t){const e=this.container.getBoundingClientRect(),i=t-e.left,n=D.pixelsToTime(i-at+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,n),"scrub")}render(){const t=D.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+at,e=t>=0&&t<=this.container.clientWidth;this.lineElement.style.display=e?"block":"none",this.handleElement.style.display=e?"block":"none",this.lineElement.style.left=`${t}px`,this.lineElement.style.height=`${this.height}px`,this.handleElement.style.left=`${t}px`}}class Mn{constructor(t){f(this,"container");f(this,"orientation");f(this,"theme");f(this,"onScrollChange");f(this,"leadingInset");f(this,"trailingInset");f(this,"stage");f(this,"layer");f(this,"hitAreaRect");f(this,"thumbRect");f(this,"viewportSize",0);f(this,"contentSize",0);f(this,"scrollOffset",0);f(this,"isDragging",!1);f(this,"dragStartClient",0);f(this,"dragStartOffset",0);f(this,"hasBoundGlobalPointerListeners",!1);f(this,"handleGlobalPointerMove",t=>{this.isDragging&&this.handleDragMove(t)});f(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});f(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});f(this,"handleStageMouseDown",t=>{var n;t.evt.preventDefault();const e=t.target===this.thumbRect||typeof((n=t.target)==null?void 0:n.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()});f(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});f(this,"handleStageMouseEnter",()=>{this.updateCursor()});f(this,"handleStageMouseMove",()=>{this.updateCursor()});f(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=_e({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Pe({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,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),a=Math.max(1,n-s),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/a*o;this.emitScrollChange(l)}jumpToPointer(t){const e=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?t-e.left:t-e.top,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),a=Math.max(1,n-s),o=Math.max(0,Math.min(n,i-this.leadingInset)),l=Math.max(0,Math.min(a,o-s/2)),h=this.getMaxScrollOffset(),c=a<=0?0:l/a*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 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),a=this.leadingInset+this.getThumbPosition(n,s);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(a),this.thumbRect.y(0),this.thumbRect.width(s),this.thumbRect.height(e)):(this.thumbRect.x(0),this.thumbRect.y(a),this.thumbRect.width(t),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(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 n=Math.max(1,t-e);return this.scrollOffset/i*n}}class _l{constructor(){f(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 Pl{constructor(){f(this,"panel",null);f(this,"config",null);f(this,"isInternalUpdate",!1)}init(t){this.config=t;const e=this.convertTheme(t.theme);this.panel=new Cs({container:t.container,theme:e,onClipUpdate:(i,n)=>{this.isInternalUpdate=!0,t.updateClip(i,n),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 xl="2.0.1",El={version:xl},Al=1,Ll=2,Ml=8e3;class Rl{constructor(t={}){f(this,"timeline",null);f(this,"tracks",[]);f(this,"trackManager");f(this,"trackInfoPanelController");f(this,"playhead",null);f(this,"history");f(this,"config");f(this,"eventDispatcher");f(this,"animationFrameId",null);f(this,"lastUpdateTime",0);f(this,"isInitialized",!1);f(this,"stage",null);f(this,"headerStage",null);f(this,"headerLayer",null);f(this,"backgroundLayer",null);f(this,"trackLayer",null);f(this,"snapGuideLayer",null);f(this,"resizeObserver",null);f(this,"rootContainer",null);f(this,"layout",null);f(this,"bodyBackgroundRect",null);f(this,"snapGuideLine",null);f(this,"trackInsertionPreviewLine",null);f(this,"trackInsertionPreviewY",null);f(this,"snapGuideTime",null);f(this,"horizontalScrollbar",null);f(this,"verticalScrollbar",null);f(this,"isExecutingHistoryAction",!1);f(this,"lastTrackDuration",0);f(this,"thumbnailProvider",null);f(this,"canPlay",!1);f(this,"sourceLoadingCount",0);f(this,"timelineStore");f(this,"timelineCommands");f(this,"timelineHistoryExecutor");f(this,"timelineHistoryRecorder");f(this,"timelinePresentationAdapter");f(this,"timelineTrackBridge");f(this,"timelinePlaybackResolver");f(this,"previewSession");f(this,"previewMountContainer",null);f(this,"resolvedPreviewBackend","dom");f(this,"runtimePreviewBackendOverride",null);f(this,"lastSelectedClipId",null);f(this,"previewSourceLoadingCount",0);f(this,"previewBuffering",!1);f(this,"pendingPreviewState",null);f(this,"nextPendingPreviewSyncRequestId",0);f(this,"activePreviewCallbackToken",0);f(this,"previewAspectRatio",{...St});f(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});f(this,"bodyCanvasHostClickListener",t=>{this.handleBodyCanvasHostClick(t)});f(this,"rootWheelListener",t=>{this.handleUnifiedWheel(t)});f(this,"mountManager",new _l);f(this,"pendingDraftData",null);this.config={duration:t.duration||36e5,zoom:t.zoom||lt.MEDIUM,currentTime:t.currentTime||0,playState:t.playState||"paused",container:t.container,theme:ve(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},R.setConfig(this.config.logConfig),R.debug("TimelineManager","日志系统初始化完成",{logConfig:this.config.logConfig}),this.thumbnailProvider=t.thumbnailProvider||null,this.trackInfoPanelController=new pl,this.eventDispatcher=new _n({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 _i(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Cn(this.history),this.timelineHistoryExecutor=new Sn({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 _s,this.timelineStore=new Ln({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new yn(this.timelineStore),this.timelinePresentationAdapter=new Pn,this.timelineTrackBridge=new xn({onClipUpdate:(e,i,n)=>this.handleClipUpdate(e,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)}),t.draftData&&(this.pendingDraftData=t.draftData),this.config.container&&this.init(this.config.container)}getTimelineStore(){var t,e,i,n,s;if(!this.timelineStore){const a=((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=((n=this.config)==null?void 0:n.zoom)||lt.MEDIUM,c=((s=this.config)==null?void 0:s.duration)||36e5;this.timelineStore=new Ln({currentTime:a,playState:o,speed:l,zoom:h,duration:c})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new yn(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new ml(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new Pn),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new xn({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)})),this.timelineTrackBridge}getTimelinePlaybackResolver(){return this.timelinePlaybackResolver||(this.timelinePlaybackResolver=new ol),this.timelinePlaybackResolver}resolveConfiguredPreviewBackend(){return this.runtimePreviewBackendOverride?(this.resolvedPreviewBackend=this.runtimePreviewBackendOverride,this.resolvedPreviewBackend):(this.resolvedPreviewBackend=el(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=At(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 tl(e)}isActivePreviewCallbackToken(t){return t===this.activePreviewCallbackToken}getPreviewSession(){return this.previewSession||(this.previewSession=this.createPreviewBackend()),this.previewSession}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new _n({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 _i(()=>{},()=>{})),this.timelineHistoryRecorder=new Cn(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new Sn({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:lt.MEDIUM,currentTime:0,playState:"paused",theme:ve(),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 n=this.getTimelineStore();n.setViewportWidth(t),n.setViewportHeight(e),n.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,n,s,a;const t=this.getViewportWidth(),e=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(n=this.verticalScrollbar)==null||n.resize(),(s=this.horizontalScrollbar)==null||s.setViewportMetrics(t,this.getHorizontalContentWidth()),(a=this.verticalScrollbar)==null||a.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 D.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,n;const e=this.clampScrollLeft(t);this.setScrollLeftState(e),(i=this.timeline)==null||i.setScrollLeft(e),(n=this.horizontalScrollbar)==null||n.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((a,o)=>a.order-o.order);let i=null,n=null,s=Number.POSITIVE_INFINITY;for(const a of e){if(a.type!=="video")continue;const o=[...a.clips].sort((l,h)=>l.startTime-h.startTime);for(const l of o){const h={trackId:a.id,trackType:a.type,trackOrder:a.order,clip:l,mediaTime:l.startTimeAtSource,muted:(a.isMuted??!1)||(l.isMuted??!1),kind:a.type,hasVisual:!0,hasAudio:!0};i||(i=h);const c=t.get(l.id);c===void 0||c>=s||(n=h,s=c)}}return n||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 n,s,a;if(!((n=this.previewSession)!=null&&n.hasPreview()))return;const t=this.buildPlaybackPlan(),e=this.getAutoAspectRatioClip(),i=At(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}:{}}),(a=(s=this.previewSession).setPendingState)==null||a.call(s,this.buildPreviewPendingState())}beginPendingPreview(t,e="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.clearPendingPreviewTimeout(),this.pendingPreviewState={mode:e,targetTime:t,resumePlayOnReady:i,errorMessage:null,timeoutId:null,awaitingSync:!0,syncRequestId:++this.nextPendingPreviewSyncRequestId}}updatePendingPreviewState(){var i,n,s,a,o,l,h,c;if(!this.pendingPreviewState){(n=(i=this.previewSession)==null?void 0:i.setPendingState)==null||n.call(i,null);return}const t=this.previewSourceLoadingCount>0||this.previewBuffering;if(this.pendingPreviewState.errorMessage){(a=(s=this.previewSession)==null?void 0:s.setPendingState)==null||a.call(s,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()))},Ml)}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(At(this.previewAspectRatio)),this.previewAspectRatio=e.getAspectRatio(),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}}init(t){var e,i,n,s,a;if(this.isInitialized){R.warn("TimelineManager","TimelineManager has already been initialized");return}if(this.rootContainer=t,this.layout=Cl(t,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Ps,scrollbarSize:xs}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(i=(e=this.layout.bodyCanvasHost).addEventListener)==null||i.call(e,"click",this.bodyCanvasHostClickListener),(s=(n=this.rootContainer)==null?void 0:n.addEventListener)==null||s.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.snapGuideLayer=new X.Layer({name:"trackSnapGuideLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.snapGuideLayer),this.timeline=new wl(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new kl(this.layout.playheadOverlay,this.getCurrentTimeState(),this.getZoomState(),this.getTimeScaleHeight()+this.getViewportHeight(),this.config.theme,this.handleTimeChange.bind(this)),this.horizontalScrollbar=new Mn({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:at,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Mn({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:o=>{this.syncScrollTop(o)}}),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()),(a=this.stage)==null||a.batchDraw(),this.pendingDraftData){const o=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(o).catch(l=>{R.error("TimelineManager","Failed to import draft data:",{error:l})})})}}createTrack(t,e,i,n){var c,d;if(!this.trackLayer)return R.error("TimelineManager","Track layer not initialized"),"";const s=this.trackManager.createTrack(t,e,i,n),a=s.id,o=Ft(t),l=this.calculateTrackY(a),h=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:a,clips:[],role:s.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()),this.getTrackCollection().add(h),this.updateAllTrackPositions(),(d=this.stage)==null||d.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),a}removeTrack(t){var n,s,a,o;const e=this.getTrackCollection().findById(t);if(!e)return!1;if(e.getClips().length>0)return R.warn("TimelineManager","Cannot remove track with clips"),!1;if(((n=e.getRole)==null?void 0:n.call(e))==="primary")return R.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(t);return i&&((a=(s=e.getTrackGroup)==null?void 0:s.call(e))==null||a.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){R.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 le(this.trackManager.getTracks(),t,this.getTrackContentTopOffset())}calculateTotalHeight(){return En(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var e,i;const t=yl(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const n of t){const s=this.getTrackCollection().findById(n.trackId);s&&((e=s.setTrackY)==null||e.call(s,n.y),(i=s.setTrackHeight)==null||i.call(s,n.height))}this.updateViewportLayout()}cleanupEmptyTracks(){var e,i,n;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return;const t=this.getTrackCollection().removeEmptyNonPrimaryTracks();if(t.length!==0){for(const s of t){const a=(e=s.getId)==null?void 0:e.call(s);a&&typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(a),(n=(i=s.getTrackGroup)==null?void 0:i.call(s))==null||n.destroy()}this.updateAllTrackPositions()}}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(t=>{var e;return(e=t.clearClipDropPreview)==null?void 0:e.call(t)}),this.hideTrackInsertionPreview()}showClipDropPreview(t,e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(i=>{var n,s,a;if(((n=i.getId)==null?void 0:n.call(i))===e){(s=i.showClipDropPreview)==null||s.call(i,t);return}(a=i.clearClipDropPreview)==null||a.call(i)})}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,n,s;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),t&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const e=((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,e,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(e>0),this.trackInsertionPreviewLine.moveToTop(),t&&((s=this.snapGuideLayer)==null||s.batchDraw())}showTrackInsertionPreview(t,e,i){this.getTrackCollection().forEach(s=>{var a;return(a=s.clearClipDropPreview)==null?void 0:a.call(s)}),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 n=this.trackManager.getTracks(),s=n.find(h=>h.role==="primary"),a=n.find(h=>h.type===t),o=[...n].reverse().find(h=>h.type===t);if((e==="before_track"||e==="after_track")&&i){const h=n.find(c=>c.id===i);if(h){const c=le(n,h.id,this.getTrackContentTopOffset());return e==="before_track"?c:c+Ft(h.type)}}if(e==="top_of_type_region"&&a)return le(n,a.id,this.getTrackContentTopOffset());if(e==="bottom_of_type_region"&&o)return le(n,o.id,this.getTrackContentTopOffset())+Ft(o.type);if(!s)return t==="video"?this.getTrackContentTopOffset():En(n,this.getTrackContentTopOffset());const l=le(n,s.id,this.getTrackContentTopOffset());return t==="video"?l:l+Ft(s.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(),n=Math.max(i,e),s=this.clampScrollLeft(this.getScrollLeftState()),a=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(t,e,n),this.headerStage.width(t),this.timeline.resize(t),this.stage.width(t),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${n}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(s),this.syncScrollTop(a),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 n=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"});n.on("click",s=>{this.handleBodyBackgroundClick(s.evt.offsetX)}),this.bodyBackgroundRect=n,this.backgroundLayer.add(n),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(t){const e=D.pixelsToTime(t-at+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 n,s;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&&((n=this.snapGuideLayer)==null||n.batchDraw());return}const i=Mt(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&&((s=this.snapGuideLayer)==null||s.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 s=this.getPrimaryWheelDelta(e,i);if(s===0)return;t.preventDefault(),this.handleWheelZoom(s,t.clientX);return}if(t.shiftKey||this.isHorizontalWheelGesture(e,i)){const s=this.getHorizontalScrollDelta(e,i,t.shiftKey);if(s===0)return;t.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+s);return}i!==0&&(t.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(t,e,i){if(!Number.isFinite(t)||t===0)return 0;if(e===Al)return t*16;if(e===Ll){const n=i==="x"?this.getViewportWidth():this.getViewportHeight();return t*(n||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 n=Math.abs(e);return n<.5?!0:i>n*1.2}getHorizontalScrollDelta(t,e,i){return i&&Math.abs(e)>=Math.abs(t)?e:t}handleWheelZoom(t,e){const i=this.getZoomState(),n=Math.exp(-t*.002),s=Math.max(lt.MIN,Math.min(lt.MAX,i*n));Math.abs(s-i)<1e-4||this.setZoomCenteredOnTimelinePointer(s,this.getWheelAnchorPointerX(e))}getWheelAnchorPointerX(t){var s;const e=(s=this.layout)==null?void 0:s.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!e||i<=0)return 0;const n=t-e.left;return Math.max(0,Math.min(i,n))}play(){if(this.getPlayStateState()!=="playing"){if(this.pendingPreviewState){R.debugLazy("TimelineManager",()=>"Play blocked by pending preview state");return}if(!this.canPlay){R.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)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(),n=this.getTimelineCommands().setZoom(t);if(!n.changed)return;const s=n.nextValue;if(this.ensureConfigState().zoom=s,this.syncZoomToScene(s),this.refreshScrollbarMetrics(),this.timeline){const a=this.timeline.getScrollLeft(),o=D.timeToPixels(i,e),h=D.timeToPixels(i,s)-o+a;this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft())}this.emitEvent("zoom_change",{zoom:s})}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(),n=this.timeline.getScrollLeft(),s=D.pixelsToTime(e-at+n,i),a=this.getTimelineCommands().setZoom(t);if(!a.changed)return;const o=a.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const h=D.timeToPixels(s,o)-(e-at);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}),R.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:t.id,count:i.length})),!0}}catch(e){R.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 n=await this.addClipInternal(i);e.push(n)}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,n=t.duration,s=t.endTimeAtSource||i+n;let a=t.sourceDuration;if(!a)try{a=await D.getVideoDuration(t.src),a<=0&&(a=s)}catch(u){R.error("TimelineManager","Failed to get video duration:",{error:u}),a=s}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=xi({id:l,type:h,externalId:t.externalId,src:t.src,name:t.name,isMuted:t.isMuted??!1,startTime:e,duration:n,startTimeAtSource:i,endTimeAtSource:s,sourceDuration:a,endTime:e+n,thumbnails:o,style:t.style,visualTransform:t.visualTransform,separatedAudioClipId:t.separatedAudioClipId,separatedFromVideoClipId:t.separatedFromVideoClipId});if(R.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),Ye({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Ht({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{R.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(T){R.warn("TimelineManager","Error loading clip thumbnails:",{error:T})}return c.id}}const u=this.getTimelineCommands().planTrackPlacement(c,this.tracks),p=this.getTrackCollection(),g=cl({clip:c,placement:u,trackCollection:p,createTrack:this.createTrack.bind(this)});Ye({applied:g,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Ht({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}if(this.thumbnailProvider)try{R.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(u){R.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(),Ye({applied:dl(this.getTrackCollection(),e,t),isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(e.clip)},applyEffects:()=>Ht({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this)})}))}updateClip(t,e){this.getTimelineCommands().findClipById(this.tracks,t)&&(this.getTrackCollection().updateClip(t,e),Ht({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),Ht({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitCurrentClip(){const t=this.getCurrentTime(),e=this.getTimelineCommands().findClipAtTime(this.tracks,t);e!=null&&e.track.splitSelectedClip&&(e.track.splitSelectedClip(t),Ht({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var n,s,a;const t=this.getPreviewAspectRatio();let e=t.width,i=t.height;if(Jt(t.mode)&&e===St.width&&i===St.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=(a=o==null?void 0:o.style)==null?void 0:a.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,n,s;const t=this.getResolvedTracksSnapshot().slice().sort((a,o)=>a.order-o.order).map(a=>{const o=a.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"?ut(l.visualTransform):void 0,separatedAudioClipId:l.separatedAudioClipId,separatedFromVideoClipId:l.separatedFromVideoClipId})).sort((l,h)=>l.startTime-h.startTime);return{id:a.id,type:a.type,name:a.name||"未命名轨道",order:a.order,isMuted:a.isMuted??!1,clips:o}}),e=((s=(n=(i=t[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:e,composition:this.getExportComposition(),tracks:t}}async importTimeline(t){if(!t||!t.composition||!t.tracks){R.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 n=new Map,s=[];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&&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,trackId:l},p=await this.addClip(u);n.set(h.id,p)}catch(c){s.push({clipId:h.id,error:c}),R.error("TimelineManager",`Failed to import clip ${h.id}:`,{error:c})}}this.clearHistory();const a={errors:s};this.emitEvent("draft_loaded",a)}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)),n=(Math.max(...t.map(h=>h.endTime))-e)/1e3,s=((l=this.stage)==null?void 0:l.width())||0,a=s-at*2;R.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:n,containerWidth:s,availableWidth:a}));const o=Math.min(a/n,lt.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}),Bo({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}),oi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(t){this.emitEvent("clip_removed",{clipId:t}),oi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(t,e){Ho(t,e,!!this.thumbnailProvider)&&this.loadClipThumbnails(t).catch(i=>{R.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:t.id})})}updateCanPlayState(){var s;const t=this.getClips(),e=this.getCurrentTime(),i=zo(t,e),n=this.canPlay;this.canPlay=No({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:((s=t[t.length-1])==null?void 0:s.endTime)||1,setCanPlay:a=>{this.canPlay=a},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:a=>{this.emitEvent("can_play_change",{canPlay:a})}}),n!==this.canPlay&&R.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:n,newState:this.canPlay}))}handleClipSplit(t,e){Wo({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:()=>oi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(t){const e=Fo(t);e.shouldJumpToTime&&e.jumpTime!==null?(this.setCurrentTime(e.jumpTime),this.emitEvent("clip_selected",{clip:t}),R.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:t.startTime}))):e.shouldSelectClip&&this.selectClip(t.id,t)}handleActionUndo(t){R.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){R.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=hl({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){R.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:t.id,currentTrackId:e}));const i=this.getTrackCollection();if(!i.findById(e))return;const n=t.type,s=this.trackManager.getTracksByType(n).length+1,a=n==="video"?`视频轨道 ${s}`:`音频轨道 ${s}`;fl({clip:t,currentTrackId:e,trackType:n,trackName:a,trackCollection:i,createTrack:this.createTrack.bind(this)}),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(t,e,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return this.showClipDropPreview(t,i),"self";const n=this.trackManager.getTracks(),s=this.getTimelineCommands().planCrossTrackPreview(t,e,i,this.getTrackContentTopOffset(),n,this.tracks);return s.status==="existing_track_placeholder"?(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,n){R.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:t.id,targetTrackY:i,currentTrackId:n}));const s=this.trackManager.getTracks(),a=this.getTimelineCommands().planCrossTrackMove(t,i,n,this.getTrackContentTopOffset(),s,this.tracks);if(a.status==="missing_target_track_by_position")return R.debugLazy("TimelineManager",()=>"未找到目标轨道"),this.clearAllTrackDropPreviews(),!1;if(a.status==="same_track")return R.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(t,n),!1;if(a.status==="missing_target_track_view")return R.warn("TimelineManager","目标轨道不存在",{targetTrackId:a.targetTrackId}),this.clearAllTrackDropPreviews(),!1;if(a.status==="track_type_mismatch")return R.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:a.targetTrackType,clipType:t.type})),this.clearAllTrackDropPreviews(),!1;if(a.status==="move_to_track")return R.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:t.id,targetTrackId:a.targetTrackId})),this.showClipDropPreview(t,a.targetTrackId),this.moveClipToTrackWithHistorySnapshot(t.id,a.targetTrackId,e);R.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:t.id}));const o=this.createTrack(a.trackType,void 0,a.insertionPlacement,a.referenceTrackId);return this.showClipDropPreview(t,o),this.moveClipToTrackWithHistorySnapshot(t.id,o,e)}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(){this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),this.selectedClipId)}selectClip(t,e){var n;const i=e||((n=this.getTimelineCommands().findClipById(this.tracks,t))==null?void 0:n.clip);this.getTimelineCommands().selectClip(t),this.notifySelectionChange(),i&&this.emitEvent("clip_selected",{clip:i}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}clearSelection(){this.getTimelineCommands().clearSelection(),this.notifySelectionChange(),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}scrollToClip(t,e={}){const{selectClip:i=!1,setCurrentTime:n=!1}=e,s=this.getClips().find(a=>a.id===t);!s||!this.timeline||(this.timeline.scrollToClip(s),this.handleScrollChange(this.timeline.getScrollLeft()),n&&this.setCurrentTime(s.startTime),i&&this.selectClip(t))}getSelectedClip(){return this.selectedClipId&&this.getClips().find(t=>t.id===this.selectedClipId)||null}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=At({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,R.debugLazy("TimelineManager",()=>"TimelineManager detached from preview container"))}attachClipConfig(t){const e=new Pl;e.init({container:t,theme:this.config.theme,getSelectedClip:()=>this.getSelectedClip(),updateClip:(s,a)=>{this.updateClip(s,a),this.handleClipChange()}});const i=()=>e.update(),n=(s,a)=>{var l;const o=this.getSelectedClip();o&&((l=a==null?void 0:a.clip)==null?void 0:l.id)===o.id&&e.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),e.destroy()}),e.update(),e}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}getPreviewAspectRatio(){return At(this.previewAspectRatio)}setPreviewAspectRatio(t){var e;this.previewAspectRatio=At({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={...St},(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(){const t=this.getSelectedClip();return t?(this.removeClip(t.id),!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 n=null;this.isExecutingHistoryAction=!0;try{if(n=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}),!n)return null;this.updateClip(t,{isMuted:!0,separatedAudioClipId:n})}finally{this.isExecutingHistoryAction=i}if(!n)return null;const s=this.getClips().find(l=>l.id===t),a=this.getClips().find(l=>l.id===n)??null,o=this.resolveTrackIdByClipId(n);return s?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(e,s,a,o),n):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,n=i?this.getClips().find(l=>l.id===i)??null:null,s=i?this.resolveTrackIdByClipId(i):null,a=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(t,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=a}const o=this.getClips().find(l=>l.id===t);return o?(a||this.getTimelineHistoryRecorder().recordRestoreClipAudio(e,o,n,s),!0):!1}moveClipToTrack(t,e){return this.moveClipToTrackWithHistorySnapshot(t,e,null)}moveClipToTrackWithHistorySnapshot(t,e,i){const n=this.getTimelineCommands().prepareMoveClipToTrack(t,e,this.tracks);if(n.status==="missing_source_track")return R.warn("TimelineManager",`片段不在任何轨道中: ${t}`),!1;if(n.status==="noop")return R.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${t}`),!0;if(n.status==="missing_target_track")return R.warn("TimelineManager",`目标轨道不存在: ${e}`),!1;if(n.status==="track_type_mismatch")return R.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var u,p,g;return{targetTrackType:(p=(u=this.getTrackCollection().findById(e))==null?void 0:u.getTrackType)==null?void 0:p.call(u),clipType:(g=this.getTimelineCommands().findClipById(this.tracks,t))==null?void 0:g.clip.type}}),!1;if(n.status!=="ready")return!1;const{sourceTrackId:s,targetTrackId:a}=n,o=i?{...i}:{...n.clip},l=this.cloneTrackSnapshot(s),h=this.cloneTrackSnapshot(a),c=ul({command:n,trackCollection:this.getTrackCollection()}),d=this.getClips().find(u=>u.id===t)??null;return Vo({applied:c,clipId:t,sourceTrackId:s,targetTrackId:a,clipBefore:o,clipAfter:d??o,sourceTrackSnapshot:l,targetTrackSnapshot:h,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>gl({notifySelectionChange:this.notifySelectionChange.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),batchDraw:()=>{var u;(u=this.stage)==null||u.batchDraw()},syncPreviewSession:this.syncPreviewSession.bind(this)})})?(this.clearAllTrackDropPreviews(),!0):!1}getTrackTotalDuration(){return bs(this.getClips())}destroy(){var t,e,i,n,s,a,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),(n=(e=this.layout)==null?void 0:(i=e.bodyCanvasHost).removeEventListener)==null||n.call(i,"click",this.bodyCanvasHostClickListener),(a=(s=this.rootContainer)==null?void 0:s.removeEventListener)==null||a.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()}addClipToTrack(t,e){return this.registerPreviewAutoAspectRatioClip(e),this.getTrackCollection().addClipToTrack(t,e)?(Ht({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(t){const e=this.getResolvedTracksSnapshot().find(i=>i.id===t);return e?{...e,clips:[...e.clips]}:null}ensureTrackFromHistorySnapshot(t){var h;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((h=this.getTracks()[0])==null?void 0:h.id)??null;const i=[...this.getTracks()].sort((c,d)=>c.order-d.order),n=i.find(c=>c.order>=t.order),s=n?i[i.findIndex(c=>c.id===n.id)-1]??null:i[i.length-1]??null;let a,o;n?(a="before_track",o=n.id):s&&(a="after_track",o=s.id);const l=this.createTrack(t.type,t.name,a,o);return this.muteTrack(l,t.isMuted??!1),l}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=sl({clips:this.getClips(),lastTrackDuration:this.lastTrackDuration,setLastTrackDuration:i=>{this.lastTrackDuration=i},setTimelineDuration:i=>{var n;this.setDurationState(i),(n=this.timeline)==null||n.setDuration(i),this.updateViewportLayout()},emitTrackDurationChange:i=>{this.emitEvent("track_duration_change",{duration:i})}});e!==t&&R.debugLazy("TimelineManager",()=>`Track duration changed: ${e}ms, setting timeline duration to ${ws(e)}ms`)}resolveSelectedClipSnapshot(){return ll({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(a=>a.id===t);if(!i||i.type!=="video")return;const n=ut(i.visualTransform),s=ut(e);Ts(n,s)||this.updateClip(t,{visualTransform:s})}clearAllTracksAndClips(){var i,n,s,a;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);(s=(n=h==null?void 0:h.getTrackGroup)==null?void 0:n.call(h))==null||s.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(),(a=this.stage)==null||a.batchDraw()}}exports.CLIP_LAYER=Ms;exports.Clip=We;exports.ClipConfigPanel=Cs;exports.DEFAULT_CLIP_VIEW_STATE=Rn;exports.DEFAULT_PREVIEW_ASPECT_RATIO=St;exports.HistoryManager=_i;exports.MIN_CLIP_LINE_WIDTH=be;exports.PREVIEW_ASPECT_RATIO_PRESETS=Ls;exports.Playhead=Mo;exports.TIMELINE_LEFT_PADDING=at;exports.TIME_SCALE=Rs;exports.TRACK_HEIGHT=bt;exports.TimeUtils=D;exports.Timeline=_o;exports.TimelineManager=Rl;exports.Track=$e;exports.TrackInfoPanel=Ss;exports.TrackManager=_s;exports.ZOOM_ANIMATION=In;exports.ZOOM_PRESETS=lt;exports.createClipViewState=Dn;exports.createClipWithViewState=xi;exports.defaultDarkTheme=Xe;exports.isAutoPreviewAspectRatioMode=Jt;exports.normalizePreviewAspectRatio=At;exports.normalizePreviewAspectRatioMode=Pi;exports.resolveTheme=ve;
|
|
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;
|