@linker-design-plus/timeline-track 2.0.13 → 2.0.14
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 +3 -0
- package/dist/core/controllers/previewBackend.d.ts +4 -0
- package/dist/core/controllers/timelineKeyboardShortcutsController.d.ts +6 -0
- package/dist/core/controllers/timelinePreviewSession.d.ts +24 -1
- package/dist/core/facade/timelineManager.d.ts +46 -1
- package/dist/core/history/timelineHistoryRecorder.d.ts +1 -0
- package/dist/core/models/types.d.ts +5 -9
- package/dist/index.cjs.js +86 -85
- package/dist/index.d.ts +1 -0
- package/dist/index.es.js +4619 -3416
- package/dist/utils/diagnostics/DiagnosticsCenter.d.ts +47 -0
- package/dist/utils/diagnostics/DiagnosticsPanel.d.ts +13 -0
- package/dist/utils/diagnostics/devConsole.d.ts +8 -0
- package/dist/utils/diagnostics/index.d.ts +4 -0
- package/dist/utils/diagnostics/types.d.ts +173 -0
- package/package.json +1 -1
- package/dist/utils/logging/Logger.d.ts +0 -30
- package/dist/utils/logging/PreviewLoadTraceStore.d.ts +0 -37
- package/dist/utils/logging/index.d.ts +0 -2
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Oa=Object.defineProperty;var Ba=(a,e,t)=>e in a?Oa(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var p=(a,e,t)=>Ba(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const E={transparent:"transparent",white:"#ffffff",black:"#000000",panelSurface:"#0f0f0f",buttonSurface:"#2a2a2a",inputSurface:"#2d2d2d",clipSurface:"#2e2e2e",videoClipBackground:"#1e5679",textClipBackground:"#604c32",audioClipBackground:"#254428",selectedTrackSurface:"#292929",borderStrong:"#333333",borderMedium:"#444444",borderSubtle:"#555555",textPrimary:"#ffffff",textSecondary:"#e0e0e0",textMuted:"#cccccc",textSubtle:"#aaaaaa",textHint:"#999999",textAudio:"#d0d0d0",textInactive:"#b5b6bf",audioClipAccent:"#b8b8c0",accentFocus:"#409eff",accentSelectedBorder:"#50E3C2",clipSelectedBorder:"#ffffff",accentSelectionBox:"#5082e6",accentAction:"#4c8dff",accentDanger:"#dc3545",accentPlayheadGrip:"#8c90ff",accentCoverFallback:"#FFF2A0",accentAudioPreview:"#b5baff",activeTabBackground:"#595A5D",gridLine:"#E0E0E0",playheadMarker:"#FF0000",overlayPreview:"rgba(0, 0, 0, 0.56)",overlayShadow:"rgba(0, 0, 0, 0.22)",overlayTransformHandle:"rgba(80, 227, 194, 0.95)",overlaySelectionBoxFill:"rgba(80, 130, 230, 0.15)",overlayVideoDropPreview:"rgba(80, 227, 194, 0.18)",overlayAudioDropPreview:"rgba(181, 186, 255, 0.18)",overlayHitArea:"rgba(0, 0, 0, 0.001)",sliderFillStart:"#f6f8ff",sliderFillEnd:"#dfe4f2",sliderRoad:"rgba(116, 128, 163, 0.26)",sliderThumbBorder:"rgba(230, 236, 250, 0.96)",sliderThumbGlowStart:"#ffffff",sliderThumbGlowEnd:"#eef2fb",sliderThumbInnerShadow:"rgba(255, 255, 255, 0.92)",sliderThumbShadow:"rgba(8, 24, 56, 0.24)"},Q={background:E.black,border:E.borderStrong,timeTick:E.textSecondary,timeText:E.textSubtle,trackBackground:E.black,trackSelectedBackground:E.selectedTrackSurface,trackBorder:E.borderStrong,clipBackground:E.clipSurface,clipBorder:E.black,clipName:E.textPrimary,clipDuration:E.textMuted,clipHandle:E.textPrimary,clipSelectedBorder:E.clipSelectedBorder,clipCoverBackground:E.borderStrong,audioClipText:E.textAudio,audioClipAccent:E.audioClipAccent,playhead:E.textPrimary,grid:E.borderStrong,snapGuideLineColor:E.accentSelectedBorder,scrollbarBackground:E.borderStrong,scrollbarBorder:E.borderSubtle,scrollbarThumb:E.borderMedium},ge={backgroundColor:"#0f0f0f",borderColor:E.borderStrong,textColor:E.textSecondary,labelColor:E.textHint,inputBackground:E.inputSurface,inputBorder:E.borderMedium,inputFocusBorder:E.accentFocus,buttonBackground:E.inputSurface,buttonBorder:E.borderMedium,buttonActiveBackground:E.accentFocus,buttonActiveBorder:E.accentFocus,buttonActiveText:E.white},be={background:E.panelSurface,border:E.borderStrong,text:E.textPrimary,buttonBackground:E.buttonSurface,buttonHover:"#3a3a3a",buttonDanger:E.accentDanger},fe={background:Q.scrollbarBackground,border:Q.scrollbarBorder,thumb:Q.scrollbarThumb,hitArea:E.overlayHitArea},yt={fill:E.white,stroke:E.black,text:E.black},ve={tabBarBackground:E.buttonSurface,actionBarBackground:E.buttonSurface,activeTabBackground:E.activeTabBackground,activeTabText:E.white,inactiveTabText:E.textInactive,sliderThumbShadow:`0 8px 20px ${E.sliderThumbShadow}`,sliderThumbInnerShadow:`inset 0 1px 1px ${E.sliderThumbInnerShadow}`},Oi={grip:E.accentPlayheadGrip,shadow:E.overlayShadow,marker:E.playheadMarker},ui={background:E.overlayPreview,text:E.white,actionBackground:E.accentAction,actionText:E.white},Ki={border:E.overlayTransformHandle,handleBackground:E.black},Kr={fill:E.overlaySelectionBoxFill,stroke:E.accentSelectionBox},pi={videoFill:E.overlayVideoDropPreview,videoStroke:E.accentSelectedBorder,audioFill:E.overlayAudioDropPreview,audioStroke:E.accentAudioPreview},Zr={line:E.gridLine},ys={fontSize:65,color:"#fff",rotation:0,strokeColor:"#000000",strokeWidth:1,lineHeight:15,paddingX:4};function Tt(a){return{...ys,...a??{}}}const Ss={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},Bi={background:Q.background,border:Q.border,timeTick:Q.timeTick,timeText:Q.timeText,trackBackground:Q.trackBackground,trackSelectedBackground:Q.trackSelectedBackground,trackBorder:Q.trackBorder,clipBackground:Q.clipBackground,clipBorder:Q.clipBorder,clipName:Q.clipName,clipDuration:Q.clipDuration,clipHandle:Q.clipHandle,clipSelectedBorder:Q.clipSelectedBorder,clipCoverBackground:Q.clipCoverBackground,audioClipText:Q.audioClipText,audioClipAccent:Q.audioClipAccent,playhead:Q.playhead,grid:Q.grid,snapGuideLineColor:Q.snapGuideLineColor,snapGuideLineWidth:1,scrollbarBackground:Q.scrollbarBackground,scrollbarBorder:Q.scrollbarBorder,scrollbarThumb:Q.scrollbarThumb};function Qt(a){return a?{...Bi,...a}:{...Bi}}const Br=720,Ee={mode:"auto-first-added-video",width:16,height:9},Ga=[{key:"default",label:"默认",aspectRatio:{...Ee}},{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 Gr(a){return a==="manual"?"manual":"auto-first-added-video"}function Ct(a){return Gr(a)==="auto-first-added-video"}function Ve(a){return{mode:Gr(a==null?void 0:a.mode),width:typeof(a==null?void 0:a.width)=="number"&&a.width>0?a.width:Ee.width,height:typeof(a==null?void 0:a.height)=="number"&&a.height>0?a.height:Ee.height}}function Fr(a,e=Br){const t=Math.max(0,a.width),i=Math.max(0,a.height),r=Math.max(0,e);if(t<=0||i<=0||r<=0)return{width:0,height:0};const n=Math.min(t,i),s=r/n;return{width:Math.round(t*s),height:Math.round(i*s)}}const Fa={DEFAULT:1,ACTIVE:2},ye={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Cs={DURATION:300,EASING:"easeOutCubic"},Ha={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},ue=15,ei=6,Le={TEXT:25,VIDEO:64,AUDIO:48};function vs(a={}){const e=Object.fromEntries(Object.entries(a).filter(([,t])=>t!==void 0));return{...Ss,...e}}function Hr(a,e={}){return{...a,...vs(e)}}class H{static msToSeconds(e){return e/1e3}static secondsToMs(e){return e*1e3}static timeToPixels(e,t){return this.msToSeconds(e)*t}static pixelsToTime(e,t){return this.secondsToMs(e/t)}static formatTime(e){const t=e/1e3,i=Math.floor(t/60),r=Math.floor(t%60),n=Math.floor(e%1e3/10);return`${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}.${n.toString().padStart(2,"0")}`}static formatDuration(e){const t=Math.floor(e/1e3),i=Math.floor(e%1e3/10);return`${t}.${i.toString().padStart(2,"0")}s`}static diffTime(e,t){return Math.abs(e-t)}static isTimeInRange(e,t,i){return e>=t&&e<=i}static clampTime(e,t,i){return Math.max(t,Math.min(i,e))}static calculateEndTime(e,t){return e+t}static getTickConfig(e){let t,i;return e>=1e3?(t=1,i=.1):e>=500?(t=1,i=.5):e>=100?(t=1,i=1):e>=50?(t=5,i=1):e>=10?(t=10,i=2):e>=5?(t=60,i=10):(t=300,i=60),{majorStep:t,minorStep:i}}static generateTimeTicks(e,t=1){const i=[],r=this.msToSeconds(e);for(let n=0;n<=r;n+=t)i.push(this.secondsToMs(n));return i}static generateVisibleTicks(e,t,i,r){const n=[],s=Math.max(0,e);let o=Math.floor(s/i)*i,l=0;const c=100;for(let g=o;g<=t&&(n.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MAJOR}),l++,!(l>=c));g+=i);let h=0;const d=400;let u=Math.floor(s/r)*r;for(let g=u;g<=t&&!(Math.abs(g-Math.round(g/i)*i)>.001&&(n.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MINOR}),h++,h>=d));g+=r);return n.sort((g,f)=>g.time-f.time)}static getVideoDuration(e,t={}){const i=()=>new Promise(r=>{const n=document.createElement("video");n.preload="metadata",n.onloadedmetadata=()=>{n.onloadedmetadata=null,n.onerror=null,r(n.duration*1e3)},n.onerror=()=>{n.onloadedmetadata=null,n.onerror=null,r(0)},n.src=e});return t.registry?t.registry.getDuration(t.cacheKey||e,i,{force:t.force}):i()}}p(H,"TICK_TYPE_MAJOR","major"),p(H,"TICK_TYPE_MINOR","minor");const Na=Math.PI/180;function $a(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const rt=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},D={_global:rt,version:"10.2.0",isBrowser:$a(),isUnminified:/param/.test((function(a){}).toString()),dblClickWindow:400,getAngle(a){return D.angleDeg?a*Na: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 D.DD.isDragging},isTransforming(){var a,e;return(e=(a=D.Transformer)===null||a===void 0?void 0:a.isTransforming())!==null&&e!==void 0?e:!1},isDragReady(){return!!D.DD.node},releaseCanvasOnDestroy:!0,document:rt.document,_injectGlobal(a){typeof rt.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),rt.Konva=a}},ae=a=>{D[a.prototype.getClassName()]=a};D._injectGlobal(D);const za=`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,34 +11,35 @@ or
|
|
|
11
11
|
|
|
12
12
|
bash: npm install skia-canvas
|
|
13
13
|
js: import "konva/skia-backend";
|
|
14
|
-
`,Ur=()=>{if(typeof document>"u")throw new Error(ba)};class Se{constructor(e=[1,0,0,1,0,0]){this.dirty=!1,this.m=e&&e.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new Se(this.m)}copyInto(e){e.m[0]=this.m[0],e.m[1]=this.m[1],e.m[2]=this.m[2],e.m[3]=this.m[3],e.m[4]=this.m[4],e.m[5]=this.m[5]}point(e){const t=this.m;return{x:t[0]*e.x+t[2]*e.y+t[4],y:t[1]*e.x+t[3]*e.y+t[5]}}translate(e,t){return this.m[4]+=this.m[0]*e+this.m[2]*t,this.m[5]+=this.m[1]*e+this.m[3]*t,this}scale(e,t){return this.m[0]*=e,this.m[1]*=e,this.m[2]*=t,this.m[3]*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),r=this.m[0]*t+this.m[2]*i,n=this.m[1]*t+this.m[3]*i,s=this.m[0]*-i+this.m[2]*t,o=this.m[1]*-i+this.m[3]*t;return this.m[0]=r,this.m[1]=n,this.m[2]=s,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(e,t){const i=this.m[0]+this.m[2]*t,r=this.m[1]+this.m[3]*t,n=this.m[2]+this.m[0]*e,s=this.m[3]+this.m[1]*e;return this.m[0]=i,this.m[1]=r,this.m[2]=n,this.m[3]=s,this}multiply(e){const t=this.m[0]*e.m[0]+this.m[2]*e.m[1],i=this.m[1]*e.m[0]+this.m[3]*e.m[1],r=this.m[0]*e.m[2]+this.m[2]*e.m[3],n=this.m[1]*e.m[2]+this.m[3]*e.m[3],s=this.m[0]*e.m[4]+this.m[2]*e.m[5]+this.m[4],o=this.m[1]*e.m[4]+this.m[3]*e.m[5]+this.m[5];return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=n,this.m[4]=s,this.m[5]=o,this}invert(){const e=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),t=this.m[3]*e,i=-this.m[1]*e,r=-this.m[2]*e,n=this.m[0]*e,s=e*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=e*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=n,this.m[4]=s,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const e=this.m[0],t=this.m[1],i=this.m[2],r=this.m[3],n=this.m[4],s=this.m[5],o=e*r-t*i,l={x:n,y:s,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(e!=0||t!=0){const h=Math.sqrt(e*e+t*t);l.rotation=t>0?Math.acos(e/h):-Math.acos(e/h),l.scaleX=h,l.scaleY=o/h,l.skewX=(e*i+t*r)/o,l.skewY=0}else if(i!=0||r!=0){const h=Math.sqrt(i*i+r*r);l.rotation=Math.PI/2-(r>0?Math.acos(-i/h):-Math.acos(i/h)),l.scaleX=o/h,l.scaleY=h,l.skewX=0,l.skewY=(e*i+t*r)/o}return l.rotation=S._getRotation(l.rotation),l}}const wa="[object Array]",ka="[object Number]",xa="[object String]",Pa="[object Boolean]",_a=Math.PI/180,Aa=180/Math.PI,xt="#",Ia="",Ea="0",La="Konva warning: ",Wr="Konva error: ",Ra="rgb(",Ui={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]},Ma=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let hi=[],Pt=null;const Da=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(a){setTimeout(a,16)},S={_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)===wa},_isNumber(a){return Object.prototype.toString.call(a)===ka&&!isNaN(a)&&isFinite(a)},_isString(a){return Object.prototype.toString.call(a)===xa},_isBoolean(a){return Object.prototype.toString.call(a)===Pa},isObject(a){return a instanceof Object},isValidSelector(a){if(typeof a!="string")return!1;const e=a[0];return e==="#"||e==="."||e===e.toUpperCase()},_sign(a){return a===0||a>0?1:-1},requestAnimFrame(a){hi.push(a),hi.length===1&&Da(function(){const e=hi;hi=[],e.forEach(function(t){t()})})},createCanvasElement(){Ur();const a=document.createElement("canvas");try{a.style=a.style||{}}catch{}return a},createImageElement(){return Ur(),document.createElement("img")},_isInDocument(a){for(;a=a.parentNode;)if(a==document)return!0;return!1},_urlToImage(a,e){const t=S.createImageElement();t.onload=function(){e(t)},t.src=a},_rgbToHex(a,e,t){return((1<<24)+(a<<16)+(e<<8)+t).toString(16).slice(1)},_hexToRgb(a){a=a.replace(xt,Ia);const e=parseInt(a,16);return{r:e>>16&255,g:e>>8&255,b:e&255}},getRandomColor(){let a=(Math.random()*16777215<<0).toString(16);for(;a.length<6;)a=Ea+a;return xt+a},isCanvasFarblingActive(){if(Pt!==null)return Pt;if(typeof document>"u")return Pt=!1,!1;const a=this.createCanvasElement();a.width=10,a.height=10;const e=a.getContext("2d",{willReadFrequently:!0});e.clearRect(0,0,10,10),e.fillStyle="#282828",e.fillRect(0,0,10,10);const t=e.getImageData(0,0,10,10).data;let i=!1;for(let r=0;r<100;r++)if(t[r*4]!==40||t[r*4+1]!==40||t[r*4+2]!==40||t[r*4+3]!==255){i=!0;break}return Pt=i,this.releaseCanvas(a),Pt},getHitColor(){const a=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(a):a},getHitColorKey(a,e,t){return this.isCanvasFarblingActive()&&(a=Math.round(a/5)*5,e=Math.round(e/5)*5,t=Math.round(t/5)*5),xt+this._rgbToHex(a,e,t)},getSnappedHexColor(a){const e=this._hexToRgb(a);return xt+this._rgbToHex(Math.round(e.r/5)*5,Math.round(e.g/5)*5,Math.round(e.b/5)*5)},getRGB(a){let e;return a in Ui?(e=Ui[a],{r:e[0],g:e[1],b:e[2]}):a[0]===xt?this._hexToRgb(a.substring(1)):a.substr(0,4)===Ra?(e=Ma.exec(a.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA(a){return a=a||"black",S._namedColorToRBA(a)||S._hex3ColorToRGBA(a)||S._hex4ColorToRGBA(a)||S._hex6ColorToRGBA(a)||S._hex8ColorToRGBA(a)||S._rgbColorToRGBA(a)||S._rgbaColorToRGBA(a)||S._hslColorToRGBA(a)},_namedColorToRBA(a){const e=Ui[a.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(a){if(a.indexOf("rgb(")===0){a=a.match(/rgb\(([^)]+)\)/)[1];const e=a.split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(a){if(a.indexOf("rgba(")===0){a=a.match(/rgba\(([^)]+)\)/)[1];const e=a.split(/ *, */).map((t,i)=>t.slice(-1)==="%"?i===3?parseInt(t)/100:parseInt(t)/100*255:Number(t));return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex8ColorToRGBA(a){if(a[0]==="#"&&a.length===9)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:parseInt(a.slice(7,9),16)/255}},_hex6ColorToRGBA(a){if(a[0]==="#"&&a.length===7)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:1}},_hex4ColorToRGBA(a){if(a[0]==="#"&&a.length===5)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:parseInt(a[4]+a[4],16)/255}},_hex3ColorToRGBA(a){if(a[0]==="#"&&a.length===4)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:1}},_hslColorToRGBA(a){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(a)){const[e,...t]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a),i=Number(t[0])/360,r=Number(t[1])/100,n=Number(t[2])/100;let s,o,l;if(r===0)return l=n*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};n<.5?s=n*(1+r):s=n+r-n*r;const h=2*n-s,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+(s-h)*6*o:2*o<1?l=s:3*o<2?l=h+(s-h)*(2/3-o)*6:l=h,c[d]=l*255;return{r:Math.round(c[0]),g:Math.round(c[1]),b:Math.round(c[2]),a:1}}},haveIntersection(a,e){return!(e.x>a.x+a.width||e.x+e.width<a.x||e.y>a.y+a.height||e.y+e.height<a.y)},cloneObject(a){const e={};for(const t in a)this._isPlainObject(a[t])?e[t]=this.cloneObject(a[t]):this._isArray(a[t])?e[t]=this.cloneArray(a[t]):e[t]=a[t];return e},cloneArray(a){return a.slice(0)},degToRad(a){return a*_a},radToDeg(a){return a*Aa},_degToRad(a){return S.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),S.degToRad(a)},_radToDeg(a){return S.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),S.radToDeg(a)},_getRotation(a){return R.angleDeg?S.radToDeg(a):a},_capitalize(a){return a.charAt(0).toUpperCase()+a.slice(1)},throw(a){throw new Error(Wr+a)},error(a){console.error(Wr+a)},warn(a){R.showWarnings&&console.warn(La+a)},each(a,e){for(const t in a)e(t,a[t])},_inRange(a,e,t){return e<=a&&a<t},_getProjectionToSegment(a,e,t,i,r,n){let s,o,l;const h=(a-t)*(a-t)+(e-i)*(e-i);if(h==0)s=a,o=e,l=(r-t)*(r-t)+(n-i)*(n-i);else{const c=((r-a)*(t-a)+(n-e)*(i-e))/h;c<0?(s=a,o=e,l=(a-r)*(a-r)+(e-n)*(e-n)):c>1?(s=t,o=i,l=(t-r)*(t-r)+(i-n)*(i-n)):(s=a+c*(t-a),o=e+c*(i-e),l=(s-r)*(s-r)+(o-n)*(o-n))}return[s,o,l]},_getProjectionToLine(a,e,t){const i=S.cloneObject(a);let r=Number.MAX_VALUE;return e.forEach(function(n,s){if(!t&&s===e.length-1)return;const o=e[(s+1)%e.length],l=S._getProjectionToSegment(n.x,n.y,o.x,o.y,a.x,a.y),h=l[0],c=l[1],d=l[2];d<r&&(i.x=h,i.y=c,r=d)}),i},_prepareArrayForTween(a,e,t){const i=[],r=[];if(a.length>e.length){const s=e;e=a,a=s}for(let s=0;s<a.length;s+=2)i.push({x:a[s],y:a[s+1]});for(let s=0;s<e.length;s+=2)r.push({x:e[s],y:e[s+1]});const n=[];return r.forEach(function(s){const o=S._getProjectionToLine(s,i,t);n.push(o.x),n.push(o.y)}),n},_prepareToStringify(a){let e;a.visitedByCircularReferenceRemoval=!0;for(const t in a)if(a.hasOwnProperty(t)&&a[t]&&typeof a[t]=="object"){if(e=Object.getOwnPropertyDescriptor(a,t),a[t].visitedByCircularReferenceRemoval||S._isElement(a[t]))if(e.configurable)delete a[t];else return null;else if(S._prepareToStringify(a[t])===null)if(e.configurable)delete a[t];else return null}return delete a.visitedByCircularReferenceRemoval,a},_assign(a,e){for(const t in e)a[t]=e[t];return a},_getFirstPointerId(a){return a.touches?a.changedTouches[0].identifier:a.pointerId||999},releaseCanvas(...a){R.releaseCanvasOnDestroy&&a.forEach(e=>{e.width=0,e.height=0})},drawRoundedRectPath(a,e,t,i){let r=e<0?e:0,n=t<0?t:0;e=Math.abs(e),t=Math.abs(t);let s=0,o=0,l=0,h=0;typeof i=="number"?s=o=l=h=Math.min(i,e/2,t/2):(s=Math.min(i[0]||0,e/2,t/2),o=Math.min(i[1]||0,e/2,t/2),h=Math.min(i[2]||0,e/2,t/2),l=Math.min(i[3]||0,e/2,t/2)),a.moveTo(r+s,n),a.lineTo(r+e-o,n),a.arc(r+e-o,n+o,o,Math.PI*3/2,0,!1),a.lineTo(r+e,n+t-h),a.arc(r+e-h,n+t-h,h,0,Math.PI/2,!1),a.lineTo(r+l,n+t),a.arc(r+l,n+t-l,l,Math.PI/2,Math.PI,!1),a.lineTo(r,n+s),a.arc(r+s,n+s,s,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(a,e,t,i,r){i=Math.abs(i);for(let n=0;n<t;n++){const s=e[(n-1+t)%t],o=e[n],l=e[(n+1)%t],h={x:o.x-s.x,y:o.y-s.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 g;typeof r=="number"?g=r:g=n<r.length?r[n]:0,g=i*Math.cos(Math.PI/t)*Math.min(1,g/i*2);const y={x:h.x/d,y:h.y/d},v={x:c.x/u,y:c.y/u},C={x:o.x-y.x*g,y:o.y-y.y*g},T={x:o.x+v.x*g,y:o.y+v.y*g};n===0?a.moveTo(C.x,C.y):a.lineTo(C.x,C.y),a.arcTo(o.x,o.y,T.x,T.y,g)}}};function Oa(a){const e=[],t=a.length,i=S;for(let r=0;r<t;r++){let n=a[r];i._isNumber(n)?n=Math.round(n*1e3)/1e3:i._isString(n)||(n=n+""),e.push(n)}return e}const Yr=",",Ba="(",Ga=")",Ha="([",Fa="])",$a=";",Na="()",za="=",Xr=["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"],Va=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],Ua=100;let ci=null;function qr(){if(ci!==null)return ci;try{const e=S.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(ci=!1,!1)}catch{return ci=!1,!1}}class Hi{constructor(e){this.canvas=e,R.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let i=this.traceArr,r=i.length,n="",s,o,l,h;for(s=0;s<r;s++)o=i[s],l=o.method,l?(h=o.args,n+=l,e?n+=Na:S._isArray(h[0])?n+=Ha+h.join(Yr)+Fa:(t&&(h=h.map(c=>typeof c=="number"?Math.floor(c):c)),n+=Ba+h.join(Yr)+Ga)):(n+=o.property,e||(n+=za+o.val)),n+=$a;return n}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=Ua&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}_applyMiterLimit(e){const t=e.attrs.miterLimit;t!=null&&this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,i,r,n,s){this._context.arc(e,t,i,r,n,s)}arcTo(e,t,i,r,n){this._context.arcTo(e,t,i,r,n)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,i,r,n,s){this._context.bezierCurveTo(e,t,i,r,n,s)}clearRect(e,t,i,r){this._context.clearRect(e,t,i,r)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const i=arguments;if(i.length===2)return this._context.createImageData(e,t);if(i.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,i,r){return this._context.createLinearGradient(e,t,i,r)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,i,r,n,s){return this._context.createRadialGradient(e,t,i,r,n,s)}drawImage(e,t,i,r,n,s,o,l,h){const c=arguments,d=this._context;c.length===3?d.drawImage(e,t,i):c.length===5?d.drawImage(e,t,i,r,n):c.length===9&&d.drawImage(e,t,i,r,n,s,o,l,h)}ellipse(e,t,i,r,n,s,o,l){this._context.ellipse(e,t,i,r,n,s,o,l)}isPointInPath(e,t,i,r){return i?this._context.isPointInPath(i,e,t,r):this._context.isPointInPath(e,t,r)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,i,r){this._context.fillRect(e,t,i,r)}strokeRect(e,t,i,r){this._context.strokeRect(e,t,i,r)}fillText(e,t,i,r){r?this._context.fillText(e,t,i,r):this._context.fillText(e,t,i)}measureText(e){return this._context.measureText(e)}getImageData(e,t,i,r){return this._context.getImageData(e,t,i,r)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,i,r){this._context.rect(e,t,i,r)}roundRect(e,t,i,r,n){this._context.roundRect(e,t,i,r,n)}putImageData(e,t,i){this._context.putImageData(e,t,i)}quadraticCurveTo(e,t,i,r){this._context.quadraticCurveTo(e,t,i,r)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,i,r,n,s){this._context.setTransform(e,t,i,r,n,s)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,i,r){this._context.strokeText(e,t,i,r)}transform(e,t,i,r,n,s){this._context.transform(e,t,i,r,n,s)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=Xr.length,i=this.setAttr,r,n;const s=function(o){let l=e[o],h;e[o]=function(){return n=Oa(Array.prototype.slice.call(arguments,0)),h=l.apply(e,arguments),e._trace({method:o,args:n}),h}};for(r=0;r<t;r++)s(Xr[r]);e.setAttr=function(){i.apply(e,arguments);const o=arguments[0];let l=arguments[1];(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")&&(l=l/this.canvas.getPixelRatio()),e._trace({property:o,val:l})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}}Va.forEach(function(a){Object.defineProperty(Hi.prototype,a,{get(){return this._context[a]},set(e){this._context[a]=e}})});class Wa extends Hi{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),i=e.getFillPriority();if(t&&i==="color"){this._fillColor(e);return}const r=e.getFillPatternImage();if(r&&i==="pattern"){this._fillPattern(e);return}const n=e.getFillLinearGradientColorStops();if(n&&i==="linear-gradient"){this._fillLinearGradient(e);return}const s=e.getFillRadialGradientColorStops();if(s&&i==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):r?this._fillPattern(e):n?this._fillLinearGradient(e):s&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),i=e.getStrokeLinearGradientEndPoint(),r=e.getStrokeLinearGradientColorStops(),n=this.createLinearGradient(t.x,t.y,i.x,i.y);if(r){for(let s=0;s<r.length;s+=2)n.addColorStop(r[s],r[s+1]);this.setAttr("strokeStyle",n)}}_stroke(e){const t=e.dash(),i=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!i){this.save();const n=this.getCanvas().getPixelRatio();this.setTransform(n,0,0,n,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),i||this.restore()}}_applyShadow(e){var t,i,r;const n=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",s=(i=e.getShadowBlur())!==null&&i!==void 0?i:5,o=(r=e.getShadowOffset())!==null&&r!==void 0?r:{x:0,y:0},l=e.getAbsoluteScale(),h=this.canvas.getPixelRatio(),c=l.x*h,d=l.y*h;this.setAttr("shadowColor",n),this.setAttr("shadowBlur",s*Math.min(Math.abs(c),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*c),this.setAttr("shadowOffsetY",o.y*d)}}class Ya extends Hi{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const n=this.getCanvas().getPixelRatio();this.setTransform(n,0,0,n,0,0)}this._applyLineCap(e);const i=e.hitStrokeWidth(),r=i==="auto"?e.strokeWidth():i;this.setAttr("lineWidth",r),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}}let di;function Xa(){if(di)return di;const a=S.createCanvasElement(),e=a.getContext("2d");return di=function(){const t=R._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),S.releaseCanvas(a),di}class Mr{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||R.pixelRatio||Xa();this.pixelRatio=i,this._canvas=S.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(r){return S.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class Ne extends Mr{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new Wa(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class Dr extends Mr{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new Ya(this),this.setSize(e.width,e.height)}}const Z={get isDragging(){let a=!1;return Z._dragElements.forEach(e=>{e.dragStatus==="dragging"&&(a=!0)}),a},justDragged:!1,get node(){let a;return Z._dragElements.forEach(e=>{a=e.node}),a},_dragElements:new Map,_drag(a){const e=[];Z._dragElements.forEach((t,i)=>{const{node:r}=t,n=r.getStage();n.setPointersPositions(a),t.pointerId===void 0&&(t.pointerId=S._getFirstPointerId(a));const s=n._changedPointerPositions.find(o=>o.id===t.pointerId);if(s){if(t.dragStatus!=="dragging"){const o=r.dragDistance();if(Math.max(Math.abs(s.x-t.startPointerPos.x),Math.abs(s.y-t.startPointerPos.y))<o||(r.startDrag({evt:a}),!r.isDragging()))return}r._setDragPosition(a,t),e.push(r)}}),e.forEach(t=>{t.fire("dragmove",{type:"dragmove",target:t,evt:a},!0)})},_endDragBefore(a){const e=[];Z._dragElements.forEach(t=>{const{node:i}=t,r=i.getStage();if(a&&r.setPointersPositions(a),!r._changedPointerPositions.find(o=>o.id===t.pointerId))return;(t.dragStatus==="dragging"||t.dragStatus==="stopped")&&(Z.justDragged=!0,R._mouseListenClick=!1,R._touchListenClick=!1,R._pointerListenClick=!1,t.dragStatus="stopped");const s=t.node.getLayer()||t.node instanceof R.Stage&&t.node;s&&e.indexOf(s)===-1&&e.push(s)}),e.forEach(t=>{t.draw()})},_endDragAfter(a){Z._dragElements.forEach((e,t)=>{e.dragStatus==="stopped"&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:a},!0),e.dragStatus!=="dragging"&&Z._dragElements.delete(t)})}};R.isBrowser&&(window.addEventListener("mouseup",Z._endDragBefore,!0),window.addEventListener("touchend",Z._endDragBefore,!0),window.addEventListener("touchcancel",Z._endDragBefore,!0),window.addEventListener("mousemove",Z._drag),window.addEventListener("touchmove",Z._drag),window.addEventListener("mouseup",Z._endDragAfter,!1),window.addEventListener("touchend",Z._endDragAfter,!1),window.addEventListener("touchcancel",Z._endDragAfter,!1));function Ue(a){return S._isString(a)?'"'+a+'"':Object.prototype.toString.call(a)==="[object Number]"||S._isBoolean(a)?a:Object.prototype.toString.call(a)}function cs(a){return a>255?255:a<0?0:Math.round(a)}function I(){if(R.isUnminified)return function(a,e){return S._isNumber(a)||S.warn(Ue(a)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),a}}function Fi(a){if(R.isUnminified)return function(e,t){let i=S._isNumber(e),r=S._isArray(e)&&e.length==a;return!i&&!r&&S.warn(Ue(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+a+")"),e}}function Or(){if(R.isUnminified)return function(a,e){return S._isNumber(a)||a==="auto"||S.warn(Ue(a)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),a}}function st(){if(R.isUnminified)return function(a,e){return S._isString(a)||S.warn(Ue(a)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),a}}function ds(){if(R.isUnminified)return function(a,e){const t=S._isString(a),i=Object.prototype.toString.call(a)==="[object CanvasGradient]"||a&&a.addColorStop;return t||i||S.warn(Ue(a)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),a}}function qa(){if(R.isUnminified)return function(a,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&a instanceof t||(S._isArray(a)?a.forEach(function(i){S._isNumber(i)||S.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):S.warn(Ue(a)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),a}}function xe(){if(R.isUnminified)return function(a,e){return a===!0||a===!1||S.warn(Ue(a)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),a}}function ja(a){if(R.isUnminified)return function(e,t){return e==null||S.isObject(e)||S.warn(Ue(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+a),e}}const _t="get",At="set",m={addGetterSetter(a,e,t,i,r){m.addGetter(a,e,t),m.addSetter(a,e,i,r),m.addOverloadedGetterSetter(a,e)},addGetter(a,e,t){const i=_t+S._capitalize(e);a.prototype[i]=a.prototype[i]||function(){const r=this.attrs[e];return r===void 0?t:r}},addSetter(a,e,t,i){const r=At+S._capitalize(e);a.prototype[r]||m.overWriteSetter(a,e,t,i)},overWriteSetter(a,e,t,i){const r=At+S._capitalize(e);a.prototype[r]=function(n){return t&&n!==void 0&&n!==null&&(n=t.call(this,n,e)),this._setAttr(e,n),i&&i.call(this),this}},addComponentsGetterSetter(a,e,t,i,r){const n=t.length,s=S._capitalize,o=_t+s(e),l=At+s(e);a.prototype[o]=function(){const c={};for(let d=0;d<n;d++){const u=t[d];c[u]=this.getAttr(e+s(u))}return c};const h=ja(t);a.prototype[l]=function(c){const d=this.attrs[e];i&&(c=i.call(this,c,e)),h&&h.call(this,c,e);for(const u in c)c.hasOwnProperty(u)&&this._setAttr(e+s(u),c[u]);return c||t.forEach(u=>{this._setAttr(e+s(u),void 0)}),this._fireChangeEvent(e,d,c),r&&r.call(this),this},m.addOverloadedGetterSetter(a,e)},addOverloadedGetterSetter(a,e){const t=S._capitalize(e),i=At+t,r=_t+t;a.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[r]()}},addDeprecatedGetterSetter(a,e,t,i){S.error("Adding deprecated "+e);const r=_t+S._capitalize(e),n=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";a.prototype[r]=function(){S.error(n);const s=this.attrs[e];return s===void 0?t:s},m.addSetter(a,e,i,function(){S.error(n)}),m.addOverloadedGetterSetter(a,e)},backCompat(a,e){S.each(e,function(t,i){const r=a.prototype[i],n=_t+S._capitalize(t),s=At+S._capitalize(t);function o(){r.apply(this,arguments),S.error('"'+t+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}a.prototype[t]=o,a.prototype[n]=o,a.prototype[s]=o})},afterSetFilter(){this._filterUpToDate=!1}};function Ka(a){const e=/(\w+)\(([^)]+)\)/g;let t;for(;(t=e.exec(a))!==null;){const[,i,r]=t;switch(i){case"blur":{const n=parseFloat(r.replace("px",""));return function(s){this.blurRadius(n*.5);const o=R.Filters;o&&o.Blur&&o.Blur.call(this,s)}}case"brightness":{const n=r.includes("%")?parseFloat(r)/100:parseFloat(r);return function(s){this.brightness(n);const o=R.Filters;o&&o.Brightness&&o.Brightness.call(this,s)}}case"contrast":{const n=parseFloat(r);return function(s){const o=100*(Math.sqrt(n)-1);this.contrast(o);const l=R.Filters;l&&l.Contrast&&l.Contrast.call(this,s)}}case"grayscale":return function(n){const s=R.Filters;s&&s.Grayscale&&s.Grayscale.call(this,n)};case"sepia":return function(n){const s=R.Filters;s&&s.Sepia&&s.Sepia.call(this,n)};case"invert":return function(n){const s=R.Filters;s&&s.Invert&&s.Invert.call(this,n)};default:S.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const ki="absoluteOpacity",jr="allEventListeners",Me="absoluteTransform",Kr="absoluteScale",qe="canvas",Za="Change",Ja="children",Qa="konva",lr="listening",eo="mouseenter",to="mouseleave",io="pointerenter",ro="pointerleave",no="touchenter",so="touchleave",Zr="set",Jr="Shape",xi=" ",Qr="stage",He="transform",ao="Stage",hr="visible",oo=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(xi);let lo=1;class A{constructor(e){this._id=lo++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(e),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(e){(e===He||e===Me)&&this._cache.get(e)?this._cache.get(e).dirty=!0:e?this._cache.delete(e):this._cache.clear()}_getCache(e,t){let i=this._cache.get(e);return(i===void 0||(e===He||e===Me)&&i.dirty===!0)&&(i=t.call(this),this._cache.set(e,i)),i}_calculate(e,t,i){if(!this._attachedDepsListeners.get(e)){const r=t.map(n=>n+"Change.konva").join(xi);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(qe)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Me&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(qe)){const{scene:e,filter:t,hit:i}=this._cache.get(qe);S.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(qe)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){const t=e||{};let i={};(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)&&(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let r=Math.ceil(t.width||i.width),n=Math.ceil(t.height||i.height),s=t.pixelRatio,o=t.x===void 0?Math.floor(i.x):t.x,l=t.y===void 0?Math.floor(i.y):t.y,h=t.offset||0,c=t.drawBorder||!1,d=t.hitCanvasPixelRatio||1;if(!r||!n){S.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,g=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=h*2+u,n+=h*2+g,o-=h,l-=h;const f=new Ne({pixelRatio:s,width:r,height:n}),y=new Ne({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),v=new Dr({pixelRatio:d,width:r,height:n}),C=f.getContext(),T=v.getContext(),w=new Ne({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(l),pixelRatio:f.pixelRatio}),b=w.getContext();return v.isCache=!0,f.isCache=!0,this._cache.delete(qe),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),C.save(),T.save(),b.save(),C.translate(-o,-l),T.translate(-o,-l),b.translate(-o,-l),w.x=o,w.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(ki),this._clearSelfAndDescendantCache(Kr),this.drawScene(f,this,w),this.drawHit(v,this),this._isUnderCache=!1,C.restore(),T.restore(),c&&(C.save(),C.beginPath(),C.rect(0,0,r,n),C.closePath(),C.setAttr("strokeStyle","red"),C.setAttr("lineWidth",5),C.stroke(),C.restore()),S.releaseCanvas(w._canvas),this._cache.set(qe,{scene:f,filter:y,hit:v,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(qe)}getClientRect(e){throw new Error('abstract "getClientRect" method call')}_transformedRect(e,t){const i=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}];let r=1/0,n=1/0,s=-1/0,o=-1/0;const l=this.getAbsoluteTransform(t);return i.forEach(function(h){const c=l.point(h);r===void 0&&(r=s=c.x,n=o=c.y),r=Math.min(r,c.x),n=Math.min(n,c.y),s=Math.max(s,c.x),o=Math.max(o,c.y)}),{x:r,y:n,width:s-r,height:o-n}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);const t=this._getCanvasCache();e.translate(t.x,t.y);const i=this._getCachedSceneCanvas(),r=i.pixelRatio;e.drawImage(i._canvas,0,0,i.width/r,i.height/r),e.restore()}_drawCachedHitCanvas(e){const t=this._getCanvasCache(),i=t.hit;e.save(),e.translate(t.x,t.y),e.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),i=t.scene,r=t.filter,n=r.getContext(),s,o,l,h;if(!e||e.length===0)return i;if(this._filterUpToDate)return r;let c=!0;for(let u=0;u<e.length;u++)if(typeof e[u]=="string"&&qr(),typeof e[u]!="string"||!qr()){c=!1;break}const d=i.pixelRatio;if(r.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),c){const u=e.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,r}try{for(s=e.length,n.clear(),n.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),o=n.getImageData(0,0,r.getWidth(),r.getHeight()),l=0;l<s;l++)h=e[l],typeof h=="string"&&(h=Ka(h)),h.call(this,o),n.putImageData(o,0,0)}catch(u){S.error("Unable to apply filter. "+u.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,r}on(e,t){if(this._cache&&this._cache.delete(jr),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(xi);for(let r=0;r<i.length;r++){const s=i[r].split("."),o=s[0],l=s[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:t})}return this}off(e,t){let i=(e||"").split(xi),r=i.length,n,s,o,l,h,c;if(this._cache&&this._cache.delete(jr),!e)for(s in this.eventListeners)this._off(s);for(n=0;n<r;n++)if(o=i[n],l=o.split("."),h=l[0],c=l[1],h)this.eventListeners[h]&&this._off(h,c,t);else for(s in this.eventListeners)this._off(s,c,t);return this}dispatchEvent(e){const t={target:this,type:e.type,evt:e};return this.fire(e.type,t),this}addEventListener(e,t){return this.on(e,function(i){t.call(this,i.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,i){const r=this;this.on(e,function(n){const s=n.target.findAncestors(t,!0,r);for(let o=0;o<s.length;o++)n=S.cloneObject(n),n.currentTarget=s[o],i.call(s[o],n)})}remove(){return this.isDragging()&&this.stopDrag(),Z._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Me),this._clearSelfAndDescendantCache(ki),this._clearSelfAndDescendantCache(Kr),this._clearSelfAndDescendantCache(Qr),this._clearSelfAndDescendantCache(hr),this._clearSelfAndDescendantCache(lr)}_remove(){this._clearCaches();const e=this.getParent();e&&e.children&&(e.children.splice(this.index,1),e._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(e){const t="get"+S._capitalize(e);return S._isFunction(this[t])?this[t]():this.attrs[e]}getAncestors(){let e=this.getParent(),t=[];for(;e;)t.push(e),e=e.getParent();return t}getAttrs(){return this.attrs||{}}setAttrs(e){return this._batchTransformChanges(()=>{let t,i;if(!e)return this;for(t in e)t!==Ja&&(i=Zr+S._capitalize(t),S._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(lr,this._isListening)}_isListening(e){if(!this.listening())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isListening(e):!0}isVisible(){return this._getCache(hr,this._isVisible)}_isVisible(e){if(!this.visible())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isVisible(e):!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);const i=this.getLayer();let r=!1;Z._dragElements.forEach(s=>{s.dragStatus==="dragging"&&(s.node.nodeType==="Stage"||s.node.getLayer()===i)&&(r=!0)});const n=!t&&!R.hitOnDragEnabled&&(r||R.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 e=this.getDepth(),t=this,i=0,r,n,s,o;function l(c){for(r=[],n=c.length,s=0;s<n;s++)o=c[s],i++,o.nodeType!==Jr&&(r=r.concat(o.getChildren().slice())),o._id===t._id&&(s=n);r.length>0&&r[0].getDepth()<=e&&l(r)}const h=this.getStage();return t.nodeType!==ao&&h&&l(h.getChildren()),i}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}_batchTransformChanges(e){this._batchingTransformChange=!0,e(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(He),this._clearSelfAndDescendantCache(Me)),this._needClearTransformCache=!1}setPosition(e){return this._batchTransformChanges(()=>{this.x(e.x),this.y(e.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const e=this.getStage();if(!e)return null;const t=e.getPointerPosition();if(!t)return null;const i=this.getAbsoluteTransform().copy();return i.invert(),i.point(t)}getAbsolutePosition(e){let t=!1,i=this.parent;for(;i;){if(i.isCached()){t=!0;break}i=i.parent}t&&!e&&(e=!0);const r=this.getAbsoluteTransform(e).getMatrix(),n=new Se,s=this.offset();return n.m=r.slice(),n.translate(s.x,s.y),n.getTranslation()}setAbsolutePosition(e){const{x:t,y:i,...r}=this._clearTransform();this.attrs.x=t,this.attrs.y=i,this._clearCache(He);const n=this._getAbsoluteTransform().copy();return n.invert(),n.translate(e.x,e.y),e={x:this.attrs.x+n.getTranslation().x,y:this.attrs.y+n.getTranslation().y},this._setTransform(r),this.setPosition({x:e.x,y:e.y}),this._clearCache(He),this._clearSelfAndDescendantCache(Me),this}_setTransform(e){let t;for(t in e)this.attrs[t]=e[t]}_clearTransform(){const e={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,e}move(e){let t=e.x,i=e.y,r=this.x(),n=this.y();return t!==void 0&&(r+=t),i!==void 0&&(n+=i),this.setPosition({x:r,y:n}),this}_eachAncestorReverse(e,t){let i=[],r=this.getParent(),n,s;if(!(t&&t._id===this._id)){for(i.unshift(this);r&&(!t||r._id!==t._id);)i.unshift(r),r=r.parent;for(n=i.length,s=0;s<n;s++)e(i[s])}}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return S.warn("Node has no parent. moveToTop function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return S.warn("Node has no parent. moveUp function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return S.warn("Node has no parent. moveDown function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return S.warn("Node has no parent. moveToBottom function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(e){if(!this.parent)return S.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&S.warn("Unexpected value "+e+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const t=this.index;return this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(ki,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let e=this.opacity();const t=this.getParent();return t&&!t._isUnderCache&&(e*=t.getAbsoluteOpacity()),e}moveTo(e){return this.getParent()!==e&&(this._remove(),e.add(this)),this}toObject(){let e=this.getAttrs(),t,i,r,n,s;const o={attrs:{},className:this.getClassName()};for(t in e)i=e[t],s=S.isObject(i)&&!S._isPlainObject(i)&&!S._isArray(i),!s&&(r=typeof this[t]=="function"&&this[t],delete e[t],n=r?r.call(this):null,e[t]=i,n!==i&&(o.attrs[t]=i));return S._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,i){const r=[];t&&this._isMatch(e)&&r.push(this);let n=this.parent;for(;n;){if(n===i)return r;n._isMatch(e)&&r.push(n),n=n.parent}return r}isAncestorOf(e){return!1}findAncestor(e,t,i){return this.findAncestors(e,t,i)[0]}_isMatch(e){if(!e)return!1;if(typeof e=="function")return e(this);let t=e.replace(/ /g,"").split(","),i=t.length,r,n;for(r=0;r<i;r++)if(n=t[r],S.isValidSelector(n)||(S.warn('Selector "'+n+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),S.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),S.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 e=this.getParent();return e?e.getLayer():null}getStage(){return this._getCache(Qr,this._getStage)}_getStage(){const e=this.getParent();return e?e.getStage():null}fire(e,t={},i){return t.target=t.target||this,i?this._fireAndBubble(e,t):this._fire(e,t),this}getAbsoluteTransform(e){return e?this._getAbsoluteTransform(e):this._getCache(Me,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new Se,this._eachAncestorReverse(function(i){const r=i.transformsEnabled();r==="all"?t.multiply(i.getTransform()):r==="position"&&t.translate(i.x()-i.offsetX(),i.y()-i.offsetY())},e),t;{t=this._cache.get(Me)||new Se,this.parent?this.parent.getAbsoluteTransform().copyInto(t):t.reset();const i=this.transformsEnabled();if(i==="all")t.multiply(this.getTransform());else if(i==="position"){const r=this.attrs.x||0,n=this.attrs.y||0,s=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(r-s,n-o)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;for(;t;)t._isUnderCache&&(e=t),t=t.getParent();const r=this.getAbsoluteTransform(e).decompose();return{x:r.scaleX,y:r.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache(He,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get(He)||new Se;i.reset();const r=this.x(),n=this.y(),s=R.getAngle(this.rotation()),o=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,l=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,h=this.attrs.skewX||0,c=this.attrs.skewY||0,d=this.attrs.offsetX||0,u=this.attrs.offsetY||0;return(r!==0||n!==0)&&i.translate(r,n),s!==0&&i.rotate(s),(h!==0||c!==0)&&i.skew(h,c),(o!==1||l!==1)&&i.scale(o,l),(d!==0||u!==0)&&i.translate(-1*d,-1*u),i.dirty=!1,i}clone(e){let t=S.cloneObject(this.attrs),i,r,n,s,o;for(i in e)t[i]=e[i];const l=new this.constructor(t);for(i in this.eventListeners)for(r=this.eventListeners[i],n=r.length,s=0;s<n;s++)o=r[s],o.name.indexOf(Qa)<0&&(l.eventListeners[i]||(l.eventListeners[i]=[]),l.eventListeners[i].push(o));return l}_toKonvaCanvas(e){e=e||{};const t=this.getClientRect(),i=this.getStage(),r=e.x!==void 0?e.x:Math.floor(t.x),n=e.y!==void 0?e.y:Math.floor(t.y),s=e.pixelRatio||1,o=new Ne({width:e.width||Math.ceil(t.width)||(i?i.width():0),height:e.height||Math.ceil(t.height)||(i?i.height():0),pixelRatio:s}),l=o.getContext(),h=new Ne({width:o.width/o.pixelRatio+Math.abs(r),height:o.height/o.pixelRatio+Math.abs(n),pixelRatio:o.pixelRatio});return e.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(r||n)&&l.translate(-1*r,-1*n),this.drawScene(o,void 0,h),l.restore(),o}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};const t=e.mimeType||null,i=e.quality||null,r=this._toKonvaCanvas(e).toDataURL(t,i);return e.callback&&e.callback(r),r}toImage(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,S._urlToImage(this.toDataURL(e),function(n){t(n),r==null||r(n)})}catch(r){i(r)}})}toBlob(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,this.toCanvas(e).toBlob(n=>{t(n),r==null||r(n)},e==null?void 0:e.mimeType,e==null?void 0:e.quality)}catch(r){i(r)}})}setSize(e){return this.width(e.width),this.height(e.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():R.dragDistance}_off(e,t,i){let r=this.eventListeners[e],n,s,o;for(n=0;n<r.length;n++)if(s=r[n].name,o=r[n].handler,(s!=="konva"||t==="konva")&&(!t||s===t)&&(!i||i===o)){if(r.splice(n,1),r.length===0){delete this.eventListeners[e];break}n--}}_fireChangeEvent(e,t,i){this._fire(e+Za,{oldVal:t,newVal:i})}addName(e){if(!this.hasName(e)){const t=this.name(),i=t?t+" "+e:e;this.name(i)}return this}hasName(e){if(!e)return!1;const t=this.name();return t?(t||"").split(/\s/g).indexOf(e)!==-1:!1}removeName(e){const t=(this.name()||"").split(/\s/g),i=t.indexOf(e);return i!==-1&&(t.splice(i,1),this.name(t.join(" "))),this}setAttr(e,t){const i=this[Zr+S._capitalize(e)];return S._isFunction(i)?i.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(R.autoDrawEnabled){const e=this.getLayer()||this.getStage();e==null||e.batchDraw()}}_setAttr(e,t){const i=this.attrs[e];i===t&&!S.isObject(t)||(t==null?delete this.attrs[e]:this.attrs[e]=t,this._shouldFireChangeEvents&&this._fireChangeEvent(e,i,t),this._requestDraw())}_setComponentAttr(e,t,i){let r;i!==void 0&&(r=this.attrs[e],r||(this.attrs[e]=this.getAttr(e)),this.attrs[e][t]=i,this._fireChangeEvent(e,r,i))}_fireAndBubble(e,t,i){t&&this.nodeType===Jr&&(t.target=this);const r=[eo,to,io,ro,no,so];if(!(r.indexOf(e)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(e,t);const s=r.indexOf(e)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!s&&(i&&i.parent?this._fireAndBubble.call(this.parent,e,t,i):this._fireAndBubble.call(this.parent,e,t))}}_getProtoListeners(e){var t,i;const{nodeType:r}=this,n=A.protoListenerMap.get(r)||{};let s=n==null?void 0:n[e];if(s===void 0){s=[];let o=Object.getPrototypeOf(this);for(;o;){const l=(i=(t=o.eventListeners)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:[];s.push(...l),o=Object.getPrototypeOf(o)}n[e]=s,A.protoListenerMap.set(r,n)}return s}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;const i=this._getProtoListeners(e);if(i)for(let n=0;n<i.length;n++)i[n].handler.call(this,t);const r=this.eventListeners[e];if(r)for(let n=0;n<r.length;n++)r[n].handler.call(this,t)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){const t=e?e.pointerId:void 0,i=this.getStage(),r=this.getAbsolutePosition();if(!i)return;const n=i._getPointerById(t)||i._changedPointerPositions[0]||r;Z._dragElements.set(this._id,{node:this,startPointerPos:n,offset:{x:n.x-r.x,y:n.y-r.y},dragStatus:"ready",pointerId:t})}startDrag(e,t=!0){Z._dragElements.has(this._id)||this._createDragElement(e);const i=Z._dragElements.get(this._id);i.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:e&&e.evt},t)}_setDragPosition(e,t){const i=this.getStage()._getPointerById(t.pointerId);if(!i)return;let r={x:i.x-t.offset.x,y:i.y-t.offset.y};const n=this.dragBoundFunc();if(n!==void 0){const s=n.call(this,r,e);s?r=s:S.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==r.x||this._lastPos.y!==r.y)&&(this.setAbsolutePosition(r),this._requestDraw()),this._lastPos=r}stopDrag(e){const t=Z._dragElements.get(this._id);t&&(t.dragStatus="stopped"),Z._endDragBefore(e),Z._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=Z._dragElements.get(this._id);return e?e.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(e){if(!(!(e.evt.button!==void 0)||R.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let r=!1;Z._dragElements.forEach(n=>{this.isAncestorOf(n.node)&&(r=!0)}),r||this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=Z._dragElements.get(this._id),i=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";i?this.stopDrag():r&&Z._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(e={x:0,y:0}){const t=this.getStage();if(!t)return!1;const i={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return S.haveIntersection(i,this.getClientRect())}static create(e,t){return S._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let i=A.prototype.getClassName.call(e),r=e.children,n,s,o;t&&(e.attrs.container=t),R[i]||(S.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=R[i];if(n=new l(e.attrs),r)for(s=r.length,o=0;o<s;o++)n.add(A._createNode(r[o]));return n}}A.protoListenerMap=new Map;A.prototype.nodeType="Node";A.prototype._attrsAffectingSize=[];A.prototype.eventListeners={};A.prototype.on.call(A.prototype,oo,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(He),this._clearSelfAndDescendantCache(Me)});A.prototype.on.call(A.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(hr)});A.prototype.on.call(A.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(lr)});A.prototype.on.call(A.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(ki)});const ee=m.addGetterSetter;ee(A,"zIndex");ee(A,"absolutePosition");ee(A,"position");ee(A,"x",0,I());ee(A,"y",0,I());ee(A,"globalCompositeOperation","source-over",st());ee(A,"opacity",1,I());ee(A,"name","",st());ee(A,"id","",st());ee(A,"rotation",0,I());m.addComponentsGetterSetter(A,"scale",["x","y"]);ee(A,"scaleX",1,I());ee(A,"scaleY",1,I());m.addComponentsGetterSetter(A,"skew",["x","y"]);ee(A,"skewX",0,I());ee(A,"skewY",0,I());m.addComponentsGetterSetter(A,"offset",["x","y"]);ee(A,"offsetX",0,I());ee(A,"offsetY",0,I());ee(A,"dragDistance",void 0,I());ee(A,"width",0,I());ee(A,"height",0,I());ee(A,"listening",!0,xe());ee(A,"preventDefault",!0,xe());ee(A,"filters",void 0,function(a){return this._filterUpToDate=!1,a});ee(A,"visible",!0,xe());ee(A,"transformsEnabled","all",st());ee(A,"size");ee(A,"dragBoundFunc");ee(A,"draggable",!1,xe());m.backCompat(A,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class Ce extends A{constructor(){super(...arguments),this.children=[]}getChildren(e){const t=this.children||[];return e?t.filter(e):t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let i=0;i<e.length;i++)this.add(e[i]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const i=[];return this._descendants(r=>{const n=r._isMatch(e);return n&&i.push(r),!!(n&&t)}),i}_descendants(e){let t=!1;const i=this.getChildren();for(const r of i){if(t=e(r),t)return!0;if(r.hasChildren()&&(t=r._descendants(e),t))return!0}return!1}toObject(){const e=A.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=A.prototype.clone.call(this,e);return this.getChildren().forEach(function(i){t.add(i.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(i=>{i.isVisible()&&i.intersects(e)&&t.push(i)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(i){i._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,i){t.index=i}),this._requestDraw()}drawScene(e,t,i){const r=this.getLayer(),n=e||r&&r.getCanvas(),s=n&&n.getContext(),o=this._getCanvasCache(),l=o&&o.scene,h=n&&n.isCache;if(!this.isVisible()&&!h)return this;if(l){s.save();const c=this.getAbsoluteTransform(t).getMatrix();s.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedSceneCanvas(s),s.restore()}else this._drawChildren("drawScene",n,t,i);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const i=this.getLayer(),r=e||i&&i.hitCanvas,n=r&&r.getContext(),s=this._getCanvasCache();if(s&&s.hit){n.save();const l=this.getAbsoluteTransform(t).getMatrix();n.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(n),n.restore()}else this._drawChildren("drawHit",r,t);return this}_drawChildren(e,t,i,r){var n;const s=t&&t.getContext(),o=this.clipWidth(),l=this.clipHeight(),h=this.clipFunc(),c=typeof o=="number"&&typeof l=="number"||h,d=i===this;if(c){s.save();const g=this.getAbsoluteTransform(i);let f=g.getMatrix();s.transform(f[0],f[1],f[2],f[3],f[4],f[5]),s.beginPath();let y;if(h)y=h.call(this,s,this);else{const v=this.clipX(),C=this.clipY();s.rect(v||0,C||0,o,l)}s.clip.apply(s,y),f=g.copy().invert().getMatrix(),s.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";u&&(s.save(),s._applyGlobalCompositeOperation(this)),(n=this.children)===null||n===void 0||n.forEach(function(g){g[e](t,i,r)}),u&&s.restore(),c&&s.restore()}getClientRect(e={}){var t;const i=e.skipTransform,r=e.relativeTo;let n,s,o,l,h={x:1/0,y:1/0,width:0,height:0};const c=this;(t=this.children)===null||t===void 0||t.forEach(function(g){if(!g.visible())return;const f=g.getClientRect({relativeTo:c,skipShadow:e.skipShadow,skipStroke:e.skipStroke});f.width===0&&f.height===0||(n===void 0?(n=f.x,s=f.y,o=f.x+f.width,l=f.y+f.height):(n=Math.min(n,f.x),s=Math.min(s,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 g=0;g<d.length;g++)if(d[g]._isVisible(this)){u=!0;break}return u&&n!==void 0?h={x:n,y:s,width:o-n,height:l-s}:h={x:0,y:0,width:0,height:0},i?h:this._transformedRect(h,r)}}m.addComponentsGetterSetter(Ce,"clip",["x","y","width","height"]);m.addGetterSetter(Ce,"clipX",void 0,I());m.addGetterSetter(Ce,"clipY",void 0,I());m.addGetterSetter(Ce,"clipWidth",void 0,I());m.addGetterSetter(Ce,"clipHeight",void 0,I());m.addGetterSetter(Ce,"clipFunc");const Zt=new Map,us=R._global.PointerEvent!==void 0;function Wi(a){return Zt.get(a)}function Br(a){return{evt:a,pointerId:a.pointerId}}function ps(a,e){return Zt.get(a)===e}function gs(a,e){$t(a),e.getStage()&&(Zt.set(a,e),us&&e._fire("gotpointercapture",Br(new PointerEvent("gotpointercapture"))))}function $t(a,e){const t=Zt.get(a);if(!t)return;const i=t.getStage();i&&i.content,Zt.delete(a),us&&t._fire("lostpointercapture",Br(new PointerEvent("lostpointercapture")))}const ho="Stage",co="string",en="px",uo="mouseout",fs="mouseleave",ms="mouseover",ys="mouseenter",Ss="mousemove",Cs="mousedown",vs="mouseup",Mt="pointermove",Dt="pointerdown",St="pointerup",Ot="pointercancel",po="lostpointercapture",ui="pointerout",Bt="pointerleave",pi="pointerover",gi="pointerenter",cr="contextmenu",Ts="touchstart",bs="touchend",ws="touchmove",ks="touchcancel",dr="wheel",go=5,fo=[[ys,"_pointerenter"],[Cs,"_pointerdown"],[Ss,"_pointermove"],[vs,"_pointerup"],[fs,"_pointerleave"],[Ts,"_pointerdown"],[ws,"_pointermove"],[bs,"_pointerup"],[ks,"_pointercancel"],[ms,"_pointerover"],[dr,"_wheel"],[cr,"_contextmenu"],[Dt,"_pointerdown"],[Mt,"_pointermove"],[St,"_pointerup"],[Ot,"_pointercancel"],[Bt,"_pointerleave"],[po,"_lostpointercapture"]],Yi={mouse:{[ui]:uo,[Bt]:fs,[pi]:ms,[gi]:ys,[Mt]:Ss,[Dt]:Cs,[St]:vs,[Ot]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[ui]:"touchout",[Bt]:"touchleave",[pi]:"touchover",[gi]:"touchenter",[Mt]:ws,[Dt]:Ts,[St]:bs,[Ot]:ks,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[ui]:ui,[Bt]:Bt,[pi]:pi,[gi]:gi,[Mt]:Mt,[Dt]:Dt,[St]:St,[Ot]:Ot,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Gt=a=>a.indexOf("pointer")>=0?"pointer":a.indexOf("touch")>=0?"touch":"mouse",ct=a=>{const e=Gt(a);if(e==="pointer")return R.pointerEventsEnabled&&Yi.pointer;if(e==="touch")return Yi.touch;if(e==="mouse")return Yi.mouse};function tn(a={}){return(a.clipFunc||a.clipWidth||a.clipHeight)&&S.warn("Stage does not support clipping. Please use clip for Layers or Groups."),a}const mo="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);",Nt=[];class $i extends Ce{constructor(e){super(tn(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),Nt.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{tn(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",i=e.getType()==="FastLayer";t||i||S.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const e=this.visible()?"":"none";this.content.style.display=e}setContainer(e){if(typeof e===co){let t;if(e.charAt(0)==="."){const i=e.slice(1);e=document.getElementsByClassName(i)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),Ce.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&S._isInDocument(e)&&this.container().removeChild(e);const t=Nt.indexOf(this);return t>-1&&Nt.splice(t,1),S.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const e=this._pointerPositions[0]||this._changedPointerPositions[0];return e?{x:e.x,y:e.y}:(S.warn(mo),null)}_getPointerById(e){return this._pointerPositions.find(t=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();const t=new Ne({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),i=t.getContext()._context,r=this.children;return(e.x||e.y)&&i.translate(-1*e.x,-1*e.y),r.forEach(function(n){if(!n.isVisible())return;const s=n._toKonvaCanvas(e);i.drawImage(s._canvas,e.x,e.y,s.getWidth()/s.getPixelRatio(),s.getHeight()/s.getPixelRatio())}),t}getIntersection(e){if(!e)return null;const t=this.children,i=t.length,r=i-1;for(let n=r;n>=0;n--){const s=t[n].getIntersection(e);if(s)return s}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+en,this.content.style.height=t+en),this.bufferCanvas.setSize(e,t),this.bufferHitCanvas.setSize(e,t),this.children.forEach(i=>{i.setSize({width:e,height:t}),i.draw()})}add(e,...t){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.add(arguments[r]);return this}super.add(e);const i=this.children.length;return i>go&&S.warn("The stage has "+i+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),R.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return ps(e,this)}setPointerCapture(e){gs(e,this)}releaseCapture(e){$t(e)}getLayers(){return this.children}_bindContentEvents(){R.isBrowser&&fo.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=ct(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=ct(e.type);t&&this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];return t&&!t.getStage()&&(t=null),t}_pointerleave(e){const t=ct(e.type),i=Gt(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(i),n=!(R.isDragging()||R.isTransforming())||R.hitOnDragEnabled;r&&n?(r._fireAndBubble(t.pointerout,{evt:e}),r._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[i+"targetShape"]=null):n&&(this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){const t=ct(e.type),i=Gt(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(n=>{const s=this.getIntersection(n);if(Z.justDragged=!1,R["_"+i+"ListenClick"]=!0,!s||!s.isListening()){this[i+"ClickStartShape"]=void 0;return}R.capturePointerEventsEnabled&&s.setPointerCapture(n.id),this[i+"ClickStartShape"]=s,s._fireAndBubble(t.pointerdown,{evt:e,pointerId:n.id}),r=!0;const o=e.type.indexOf("touch")>=0;s.preventDefault()&&e.cancelable&&o&&e.preventDefault()}),r||this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){const t=ct(e.type),i=Gt(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(R.isDragging()&&Z.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(R.isDragging()||R.isTransforming())||R.hitOnDragEnabled))return;const s={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(h=>{const c=Wi(h.id)||this.getIntersection(h),d=h.id,u={evt:e,pointerId:d},g=l!==c;if(g&&l&&(l._fireAndBubble(t.pointerout,{...u},c),l._fireAndBubble(t.pointerleave,{...u},c)),c){if(s[c._id])return;s[c._id]=!0}c&&c.isListening()?(o=!0,g&&(c._fireAndBubble(t.pointerover,{...u},l),c._fireAndBubble(t.pointerenter,{...u},l),this[i+"targetShape"]=c),c._fireAndBubble(t.pointermove,{...u})):l&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:d}),this[i+"targetShape"]=null)}),o||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=ct(e.type),i=Gt(e.type);if(!t)return;this.setPointersPositions(e);const r=this[i+"ClickStartShape"],n=this[i+"ClickEndShape"],s={};let o=!1;this._changedPointerPositions.forEach(l=>{const h=Wi(l.id)||this.getIntersection(l);if(h){if(h.releaseCapture(l.id),s[h._id])return;s[h._id]=!0}const c=l.id,d={evt:e,pointerId:c};let u=!1;R["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):Z.justDragged||(R["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){R["_"+i+"InDblClickWindow"]=!1},R.dblClickWindow),h&&h.isListening()?(o=!0,this[i+"ClickEndShape"]=h,h._fireAndBubble(t.pointerup,{...d}),R["_"+i+"ListenClick"]&&r&&r===h&&(h._fireAndBubble(t.pointerclick,{...d}),u&&n&&n===h&&h._fireAndBubble(t.pointerdblclick,{...d}))):(this[i+"ClickEndShape"]=null,o||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),R["_"+i+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:c}),u&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:c}))}),o||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),R["_"+i+"ListenClick"]=!1,e.cancelable&&i!=="touch"&&i!=="pointer"&&e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(cr,{evt:e}):this._fire(cr,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(dr,{evt:e}):this._fire(dr,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=Wi(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(St,Br(e)),$t(e.pointerId)}_lostpointercapture(e){$t(e.pointerId)}setPointersPositions(e){const t=this._getContentPosition();let i=null,r=null;e=e||window.event,e.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,n=>{this._pointerPositions.push({id:n.identifier,x:(n.clientX-t.left)/t.scaleX,y:(n.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,n=>{this._changedPointerPositions.push({id:n.identifier,x:(n.clientX-t.left)/t.scaleX,y:(n.clientY-t.top)/t.scaleY})})):(i=(e.clientX-t.left)/t.scaleX,r=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:i,y:r},this._pointerPositions=[{x:i,y:r,id:S._getFirstPointerId(e)}],this._changedPointerPositions=[{x:i,y:r,id:S._getFirstPointerId(e)}])}_setPointerPosition(e){S.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new Ne({width:this.width(),height:this.height()}),this.bufferHitCanvas=new Dr({pixelRatio:1,width:this.width(),height:this.height()}),!R.isBrowser)return;const e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),this._resizeDOM()}cache(){return S.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}}$i.prototype.nodeType=ho;ae($i);m.addGetterSetter($i,"container");R.isBrowser&&document.addEventListener("visibilitychange",()=>{Nt.forEach(a=>{a.batchDraw()})});const xs="hasShadow",Ps="shadowRGBA",_s="patternImage",As="linearGradient",Is="radialGradient";let fi;function Xi(){return fi||(fi=S.createCanvasElement().getContext("2d"),fi)}const zt={};function yo(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function So(a){a.stroke()}function Co(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function vo(a){a.stroke()}function To(){this._clearCache(xs)}function bo(){this._clearCache(Ps)}function wo(){this._clearCache(_s)}function ko(){this._clearCache(As)}function xo(){this._clearCache(Is)}class P extends A{constructor(e){super(e);let t,i=0;for(;t=S.getHitColor(),!(t&&!(t in zt));)if(i++,i>=1e4){S.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=S.getRandomColor();break}this.colorKey=t,zt[t]=this}getContext(){return S.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return S.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(xs,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(_s,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=Xi().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new Se;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(R.getAngle(this.fillPatternRotation())),i.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),i.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const r=i.getMatrix(),n=typeof DOMMatrix>"u"?{a:r[0],b:r[1],c:r[2],d:r[3],e:r[4],f:r[5]}:new DOMMatrix(r);t.setTransform(n)}return t}}_getLinearGradient(){return this._getCache(As,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=Xi(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),n=t.createLinearGradient(i.x,i.y,r.x,r.y);for(let s=0;s<e.length;s+=2)n.addColorStop(e[s],e[s+1]);return n}}_getRadialGradient(){return this._getCache(Is,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=Xi(),i=this.fillRadialGradientStartPoint(),r=this.fillRadialGradientEndPoint(),n=t.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),r.x,r.y,this.fillRadialGradientEndRadius());for(let s=0;s<e.length;s+=2)n.addColorStop(e[s],e[s+1]);return n}}getShadowRGBA(){return this._getCache(Ps,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=S.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const e=this.hitStrokeWidth();return e==="auto"?this.hasStroke():this.strokeEnabled()&&!!e}intersects(e){const t=this.getStage();if(!t)return!1;const i=t.bufferHitCanvas;return i.getContext().clear(),this.drawHit(i,void 0,!0),i.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return A.prototype.destroy.call(this),delete zt[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0?t:!0))return!1;const r=e||this.hasFill(),n=this.hasStroke(),s=this.getAbsoluteOpacity()!==1;if(r&&n&&s)return!0;const o=this.hasShadow(),l=this.shadowForStrokeEnabled();return!!(r&&n&&o&&l)}setStrokeHitEnabled(e){S.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,i=this.getParent();for(;i;){if(i.isCached()){t=!0;break}i=i.getParent()}const r=e.skipTransform,n=e.relativeTo||t&&this.getStage()||void 0,s=this.getSelfRect(),l=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,h=s.width+l,c=s.height+l,d=!e.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,g=d?this.shadowOffsetY():0,f=h+Math.abs(u),y=c+Math.abs(g),v=d&&this.shadowBlur()||0,C=f+v*2,T=y+v*2,w={width:C,height:T,x:-(l/2+v)+Math.min(u,0)+s.x,y:-(l/2+v)+Math.min(g,0)+s.y};return r?w:this._transformedRect(w,n)}drawScene(e,t,i){const r=this.getLayer(),n=e||r.getCanvas(),s=n.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),h=this.hasShadow();let c;const d=t===this;if(!this.isVisible()&&!d)return this;if(o){s.save();const u=this.getAbsoluteTransform(t).getMatrix();return s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(s),s.restore(),this}if(!l)return this;if(s.save(),this._useBufferCanvas()){c=this.getStage();const u=i||c.bufferCanvas,g=u.getContext();i?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,u.width,u.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const f=this.getAbsoluteTransform(t).getMatrix();g.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.call(this,g,this),g.restore();const y=u.pixelRatio;h&&s._applyShadow(this),d||(s._applyOpacity(this),s._applyGlobalCompositeOperation(this)),s.drawImage(u._canvas,u.x||0,u.y||0,u.width/y,u.height/y)}else{if(s._applyLineJoin(this),s._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(t).getMatrix();s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),s._applyOpacity(this),s._applyGlobalCompositeOperation(this)}h&&s._applyShadow(this),l.call(this,s,this)}return s.restore(),this}drawHit(e,t,i=!1){if(!this.shouldDrawHit(t,i))return this;const r=this.getLayer(),n=e||r.hitCanvas,s=n&&n.getContext(),o=this.hitFunc()||this.sceneFunc(),l=this._getCanvasCache(),h=l&&l.hit;if(this.colorKey||S.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){s.save();const d=this.getAbsoluteTransform(t).getMatrix();return s.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(s),s.restore(),this}if(!o)return this;if(s.save(),s._applyLineJoin(this),s._applyMiterLimit(this),!(this===t)){const d=this.getAbsoluteTransform(t).getMatrix();s.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,s,this),s.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),i=this._getCachedSceneCanvas(),r=t.hit,n=r.getContext(),s=r.getWidth(),o=r.getHeight();n.clear(),n.drawImage(i._canvas,0,0,s,o);try{const l=n.getImageData(0,0,s,o),h=l.data,c=h.length,d=S._hexToRgb(this.colorKey);for(let u=0;u<c;u+=4)h[u+3]>e?(h[u]=d.r,h[u+1]=d.g,h[u+2]=d.b,h[u+3]=255):h[u+3]=0;n.putImageData(l,0,0)}catch(l){S.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(e){return ps(e,this)}setPointerCapture(e){gs(e,this)}releaseCapture(e){$t(e)}}P.prototype._fillFunc=yo;P.prototype._strokeFunc=So;P.prototype._fillFuncHit=Co;P.prototype._strokeFuncHit=vo;P.prototype._centroid=!1;P.prototype.nodeType="Shape";ae(P);P.prototype.eventListeners={};P.prototype.on.call(P.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",To);P.prototype.on.call(P.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",bo);P.prototype.on.call(P.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",wo);P.prototype.on.call(P.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",ko);P.prototype.on.call(P.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",xo);m.addGetterSetter(P,"stroke",void 0,ds());m.addGetterSetter(P,"strokeWidth",2,I());m.addGetterSetter(P,"fillAfterStrokeEnabled",!1);m.addGetterSetter(P,"hitStrokeWidth","auto",Or());m.addGetterSetter(P,"strokeHitEnabled",!0,xe());m.addGetterSetter(P,"perfectDrawEnabled",!0,xe());m.addGetterSetter(P,"shadowForStrokeEnabled",!0,xe());m.addGetterSetter(P,"lineJoin");m.addGetterSetter(P,"lineCap");m.addGetterSetter(P,"miterLimit");m.addGetterSetter(P,"sceneFunc");m.addGetterSetter(P,"hitFunc");m.addGetterSetter(P,"dash");m.addGetterSetter(P,"dashOffset",0,I());m.addGetterSetter(P,"shadowColor",void 0,st());m.addGetterSetter(P,"shadowBlur",0,I());m.addGetterSetter(P,"shadowOpacity",1,I());m.addComponentsGetterSetter(P,"shadowOffset",["x","y"]);m.addGetterSetter(P,"shadowOffsetX",0,I());m.addGetterSetter(P,"shadowOffsetY",0,I());m.addGetterSetter(P,"fillPatternImage");m.addGetterSetter(P,"fill",void 0,ds());m.addGetterSetter(P,"fillPatternX",0,I());m.addGetterSetter(P,"fillPatternY",0,I());m.addGetterSetter(P,"fillLinearGradientColorStops");m.addGetterSetter(P,"strokeLinearGradientColorStops");m.addGetterSetter(P,"fillRadialGradientStartRadius",0);m.addGetterSetter(P,"fillRadialGradientEndRadius",0);m.addGetterSetter(P,"fillRadialGradientColorStops");m.addGetterSetter(P,"fillPatternRepeat","repeat");m.addGetterSetter(P,"fillEnabled",!0);m.addGetterSetter(P,"strokeEnabled",!0);m.addGetterSetter(P,"shadowEnabled",!0);m.addGetterSetter(P,"dashEnabled",!0);m.addGetterSetter(P,"strokeScaleEnabled",!0);m.addGetterSetter(P,"fillPriority","color");m.addComponentsGetterSetter(P,"fillPatternOffset",["x","y"]);m.addGetterSetter(P,"fillPatternOffsetX",0,I());m.addGetterSetter(P,"fillPatternOffsetY",0,I());m.addComponentsGetterSetter(P,"fillPatternScale",["x","y"]);m.addGetterSetter(P,"fillPatternScaleX",1,I());m.addGetterSetter(P,"fillPatternScaleY",1,I());m.addComponentsGetterSetter(P,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(P,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(P,"fillLinearGradientStartPointX",0);m.addGetterSetter(P,"strokeLinearGradientStartPointX",0);m.addGetterSetter(P,"fillLinearGradientStartPointY",0);m.addGetterSetter(P,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(P,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(P,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(P,"fillLinearGradientEndPointX",0);m.addGetterSetter(P,"strokeLinearGradientEndPointX",0);m.addGetterSetter(P,"fillLinearGradientEndPointY",0);m.addGetterSetter(P,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(P,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(P,"fillRadialGradientStartPointX",0);m.addGetterSetter(P,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(P,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(P,"fillRadialGradientEndPointX",0);m.addGetterSetter(P,"fillRadialGradientEndPointY",0);m.addGetterSetter(P,"fillPatternRotation",0);m.addGetterSetter(P,"fillRule",void 0,st());m.backCompat(P,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Po="beforeDraw",_o="draw",Es=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Ao=Es.length;class at extends Ce{constructor(e){super(e),this.canvas=new Ne,this.hitCanvas=new Dr({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){A.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!A.prototype.moveUp.call(this))return!1;const t=this.getStage();return!t||!t.content?!1:(t.content.removeChild(this.getNativeCanvasElement()),this.index<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[this.index+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(A.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(A.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return A.prototype.remove.call(this),e&&e.parentNode&&S._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&S.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),A.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){S.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){S.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,S.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,i=!1;for(;;){for(let r=0;r<Ao;r++){const n=Es[r],s=this._getIntersection({x:e.x+n.x*t,y:e.y+n.y*t}),o=s.shape;if(o)return o;if(i=!!s.antialiased,!s.antialiased)break}if(i)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,i=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,r=i[3];if(r===255){const n=S.getHitColorKey(i[0],i[1],i[2]),s=zt[n];return s?{shape:s}:{antialiased:!0}}else if(r>0)return{antialiased:!0};return{}}drawScene(e,t,i){const r=this.getLayer(),n=e||r&&r.getCanvas();return this._fire(Po,{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),Ce.prototype.drawScene.call(this,n,t,i),this._fire(_o,{node:this}),this}drawHit(e,t){const i=this.getLayer(),r=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),Ce.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){S.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return S.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;!!this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return S.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}at.prototype.nodeType="Layer";ae(at);m.addGetterSetter(at,"imageSmoothingEnabled",!0);m.addGetterSetter(at,"clearBeforeDraw",!0);m.addGetterSetter(at,"hitGraphEnabled",!0,xe());class Gr extends at{constructor(e){super(e),this.listening(!1),S.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}Gr.prototype.nodeType="FastLayer";ae(Gr);class Tt extends Ce{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&S.throw("You may only add groups and shapes to groups.")}}Tt.prototype.nodeType="Group";ae(Tt);const qi=function(){return Qe.performance&&Qe.performance.now?function(){return Qe.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:qi(),frameRate:0},this.func=e,this.setLayers(t)}setLayers(e){let t=[];return e&&(t=Array.isArray(e)?e:[e]),this.layers=t,this}getLayers(){return this.layers}addLayer(e){const t=this.layers,i=t.length;for(let r=0;r<i;r++)if(t[r]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){const t=we.animations,i=t.length;for(let r=0;r<i;r++)if(t[r].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=qi(),we._addAnimation(this),this}stop(){return we._removeAnimation(this),this}_updateFrameObject(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(e){this.animations.push(e),this._handleAnimation()}static _removeAnimation(e){const t=e.id,i=this.animations,r=i.length;for(let n=0;n<r;n++)if(i[n].id===t){this.animations.splice(n,1);break}}static _runFrames(){const e={},t=this.animations;for(let i=0;i<t.length;i++){const r=t[i],n=r.layers,s=r.func;r._updateFrameObject(qi());const o=n.length;let l;if(s?l=s.call(r,r.frame)!==!1:l=!0,!!l)for(let h=0;h<o;h++){const c=n[h];c._id!==void 0&&(e[c._id]=c)}}for(const i in e)e.hasOwnProperty(i)&&e[i].batchDraw()}static _animationLoop(){const e=we;e.animations.length?(e._runFrames(),S.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,S.requestAnimFrame(this._animationLoop))}}we.animations=[];we.animIdCounter=0;we.animRunning=!1;const Io={node:1,duration:1,easing:1,onFinish:1,yoyo:1},Eo=1,rn=2,nn=3,sn=["fill","stroke","shadowColor"];let Lo=0;class Ro{constructor(e,t,i,r,n,s,o){this.prop=e,this.propFunc=t,this.begin=r,this._pos=r,this.duration=s,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(e){const t=this[e];t&&t()}setTime(e){e>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():e<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=e,this.update())}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){return e===void 0&&(e=this._time),this.func(e,this.begin,this._change,this.duration)}play(){this.state=rn,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=nn,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const e=this.getTimer()-this._startTime;this.state===rn?this.setTime(e):this.state===nn&&this.setTime(this.duration-e)}pause(){this.state=Eo,this.fire("onPause")}getTimer(){return new Date().getTime()}}class te{constructor(e){const t=this,i=e.node,r=i._id,n=e.easing||Vt.Linear,s=!!e.yoyo;let o,l;typeof e.duration>"u"?o=.3:e.duration===0?o=.001:o=e.duration,this.node=i,this._id=Lo++;const h=i.getLayer()||(i instanceof R.Stage?i.getLayers():null);h||S.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new we(function(){t.tween.onEnterFrame()},h),this.tween=new Ro(l,function(c){t._tweenFunc(c)},n,0,1,o*1e3,s),this._addListeners(),te.attrs[r]||(te.attrs[r]={}),te.attrs[r][this._id]||(te.attrs[r][this._id]={}),te.tweens[r]||(te.tweens[r]={});for(l in e)Io[l]===void 0&&this._addAttr(l,e[l]);this.reset(),this.onFinish=e.onFinish,this.onReset=e.onReset,this.onUpdate=e.onUpdate}_addAttr(e,t){const i=this.node,r=i._id;let n,s,o,l,h;const c=te.tweens[r][e];c&&delete te.attrs[r][c][e];let d=i.getAttr(e);if(S._isArray(t))if(n=[],s=Math.max(t.length,d.length),e==="points"&&t.length!==d.length&&(t.length>d.length?(l=d,d=S._prepareArrayForTween(d,t,i.closed())):(o=t,t=S._prepareArrayForTween(t,d,i.closed()))),e.indexOf("fill")===0)for(let u=0;u<s;u++)if(u%2===0)n.push(t[u]-d[u]);else{const g=S.colorToRGBA(d[u]);h=S.colorToRGBA(t[u]),d[u]=g,n.push({r:h.r-g.r,g:h.g-g.g,b:h.b-g.b,a:h.a-g.a})}else for(let u=0;u<s;u++)n.push(t[u]-d[u]);else sn.indexOf(e)!==-1?(d=S.colorToRGBA(d),h=S.colorToRGBA(t),n={r:h.r-d.r,g:h.g-d.g,b:h.b-d.b,a:h.a-d.a}):n=t-d;te.attrs[r][this._id][e]={start:d,diff:n,end:t,trueEnd:o,trueStart:l},te.tweens[r][e]=this._id}_tweenFunc(e){const t=this.node,i=te.attrs[t._id][this._id];let r,n,s,o,l,h,c,d;for(r in i){if(n=i[r],s=n.start,o=n.diff,d=n.end,S._isArray(s))if(l=[],c=Math.max(s.length,d.length),r.indexOf("fill")===0)for(h=0;h<c;h++)h%2===0?l.push((s[h]||0)+o[h]*e):l.push("rgba("+Math.round(s[h].r+o[h].r*e)+","+Math.round(s[h].g+o[h].g*e)+","+Math.round(s[h].b+o[h].b*e)+","+(s[h].a+o[h].a*e)+")");else for(h=0;h<c;h++)l.push((s[h]||0)+o[h]*e);else sn.indexOf(r)!==-1?l="rgba("+Math.round(s.r+o.r*e)+","+Math.round(s.g+o.g*e)+","+Math.round(s.b+o.b*e)+","+(s.a+o.a*e)+")":l=s+o*e;t.setAttr(r,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const e=this.node,t=te.attrs[e._id][this._id];t.points&&t.points.trueEnd&&e.setAttr("points",t.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const e=this.node,t=te.attrs[e._id][this._id];t.points&&t.points.trueStart&&e.points(t.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(e){return this.tween.seek(e*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const e=this.node._id,t=this._id,i=te.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const r in i)delete te.tweens[e][r];delete te.attrs[e][t],te.tweens[e]&&(Object.keys(te.tweens[e]).length===0&&delete te.tweens[e],Object.keys(te.attrs[e]).length===0&&delete te.attrs[e])}}te.attrs={};te.tweens={};A.prototype.to=function(a){const e=a.onFinish;a.node=this,a.onFinish=function(){this.destroy(),e&&e()},new te(a).play()};const Vt={BackEaseIn(a,e,t,i){return t*(a/=i)*a*((1.70158+1)*a-1.70158)+e},BackEaseOut(a,e,t,i){return t*((a=a/i-1)*a*((1.70158+1)*a+1.70158)+1)+e},BackEaseInOut(a,e,t,i){let r=1.70158;return(a/=i/2)<1?t/2*(a*a*(((r*=1.525)+1)*a-r))+e:t/2*((a-=2)*a*(((r*=1.525)+1)*a+r)+2)+e},ElasticEaseIn(a,e,t,i,r,n){let s=0;return a===0?e:(a/=i)===1?e+t:(n||(n=i*.3),!r||r<Math.abs(t)?(r=t,s=n/4):s=n/(2*Math.PI)*Math.asin(t/r),-(r*Math.pow(2,10*(a-=1))*Math.sin((a*i-s)*(2*Math.PI)/n))+e)},ElasticEaseOut(a,e,t,i,r,n){let s=0;return a===0?e:(a/=i)===1?e+t:(n||(n=i*.3),!r||r<Math.abs(t)?(r=t,s=n/4):s=n/(2*Math.PI)*Math.asin(t/r),r*Math.pow(2,-10*a)*Math.sin((a*i-s)*(2*Math.PI)/n)+t+e)},ElasticEaseInOut(a,e,t,i,r,n){let s=0;return a===0?e:(a/=i/2)===2?e+t:(n||(n=i*(.3*1.5)),!r||r<Math.abs(t)?(r=t,s=n/4):s=n/(2*Math.PI)*Math.asin(t/r),a<1?-.5*(r*Math.pow(2,10*(a-=1))*Math.sin((a*i-s)*(2*Math.PI)/n))+e:r*Math.pow(2,-10*(a-=1))*Math.sin((a*i-s)*(2*Math.PI)/n)*.5+t+e)},BounceEaseOut(a,e,t,i){return(a/=i)<1/2.75?t*(7.5625*a*a)+e:a<2/2.75?t*(7.5625*(a-=1.5/2.75)*a+.75)+e:a<2.5/2.75?t*(7.5625*(a-=2.25/2.75)*a+.9375)+e:t*(7.5625*(a-=2.625/2.75)*a+.984375)+e},BounceEaseIn(a,e,t,i){return t-Vt.BounceEaseOut(i-a,0,t,i)+e},BounceEaseInOut(a,e,t,i){return a<i/2?Vt.BounceEaseIn(a*2,0,t,i)*.5+e:Vt.BounceEaseOut(a*2-i,0,t,i)*.5+t*.5+e},EaseIn(a,e,t,i){return t*(a/=i)*a+e},EaseOut(a,e,t,i){return-t*(a/=i)*(a-2)+e},EaseInOut(a,e,t,i){return(a/=i/2)<1?t/2*a*a+e:-t/2*(--a*(a-2)-1)+e},StrongEaseIn(a,e,t,i){return t*(a/=i)*a*a*a*a+e},StrongEaseOut(a,e,t,i){return t*((a=a/i-1)*a*a*a*a+1)+e},StrongEaseInOut(a,e,t,i){return(a/=i/2)<1?t/2*a*a*a*a*a+e:t/2*((a-=2)*a*a*a*a+2)+e},Linear(a,e,t,i){return t*a/i+e}},an=S._assign(R,{Util:S,Transform:Se,Node:A,Container:Ce,Stage:$i,stages:Nt,Layer:at,FastLayer:Gr,Group:Tt,DD:Z,Shape:P,shapes:zt,Animation:we,Tween:te,Easings:Vt,Context:Hi,Canvas:Mr});class De extends P{_sceneFunc(e){const t=R.getAngle(this.angle()),i=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,i),e.arc(0,0,this.innerRadius(),t,0,!i),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),i=this.clockwise(),r=R.getAngle(i?360-this.angle():this.angle()),n=Math.cos(Math.min(r,Math.PI)),s=1,o=Math.sin(Math.min(Math.max(Math.PI,r),3*Math.PI/2)),l=Math.sin(Math.min(r,Math.PI/2)),h=n*(n>0?e:t),c=s*t,d=o*(o>0?e:t),u=l*(l>0?t:e);return{x:h,y:i?-1*u:d,width:c-h,height:u-d}}}De.prototype._centroid=!0;De.prototype.className="Arc";De.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];ae(De);m.addGetterSetter(De,"innerRadius",0,I());m.addGetterSetter(De,"outerRadius",0,I());m.addGetterSetter(De,"angle",0,I());m.addGetterSetter(De,"clockwise",!1,xe());function ur(a,e,t,i,r,n,s){const o=Math.sqrt(Math.pow(t-a,2)+Math.pow(i-e,2)),l=Math.sqrt(Math.pow(r-t,2)+Math.pow(n-i,2)),h=s*o/(o+l),c=s*l/(o+l),d=t-h*(r-a),u=i-h*(n-e),g=t+c*(r-a),f=i+c*(n-e);return[d,u,g,f]}function on(a,e){const t=a.length,i=[];for(let r=2;r<t-2;r+=2){const n=ur(a[r-2],a[r-1],a[r],a[r+1],a[r+2],a[r+3],e);isNaN(n[0])||(i.push(n[0]),i.push(n[1]),i.push(a[r]),i.push(a[r+1]),i.push(n[2]),i.push(n[3]))}return i}function Mo(a){const e=[[a[0],a[2],a[4],a[6]],[a[1],a[3],a[5],a[7]]],t=[];for(const i of e){const r=-3*i[0]+9*i[1]-9*i[2]+3*i[3];if(r!==0){const n=6*i[0]-12*i[1]+6*i[2],s=-3*i[0]+3*i[1],o=n*n-4*r*s;if(o>=0){const l=Math.sqrt(o);t.push((-n+l)/(2*r)),t.push((-n-l)/(2*r))}}}return t.filter(i=>i>0&&i<1).flatMap(i=>e.map(r=>{const n=1-i;return n*n*n*r[0]+3*n*n*i*r[1]+3*n*i*i*r[2]+i*i*i*r[3]}))}class Oe extends P{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),i=t.length,r=this.tension(),n=this.closed(),s=this.bezier();if(!i)return;let o=0;if(e.beginPath(),e.moveTo(t[0],t[1]),r!==0&&i>4){const l=this.getTensionPoints(),h=l.length;for(o=n?0:4,n||e.quadraticCurveTo(l[0],l[1],l[2],l[3]);o<h-2;)e.bezierCurveTo(l[o++],l[o++],l[o++],l[o++],l[o++],l[o++]);n||e.quadraticCurveTo(l[h-2],l[h-1],t[i-2],t[i-1])}else if(s)for(o=2;o<i;)e.bezierCurveTo(t[o++],t[o++],t[o++],t[o++],t[o++],t[o++]);else for(o=2;o<i;o+=2)e.lineTo(t[o],t[o+1]);n?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():on(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=ur(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),n=ur(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),s=on(e,i);return[r[2],r[3]].concat(s).concat([n[0],n[1],e[t-2],e[t-1],n[2],n[3],r[0],r[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:this.bezier()?e=[e[0],e[1],...Mo(this.points()),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],i=e[0],r=e[1],n=e[1],s,o;for(let l=0;l<e.length/2;l++)s=e[l*2],o=e[l*2+1],t=Math.min(t,s),i=Math.max(i,s),r=Math.min(r,o),n=Math.max(n,o);return{x:t,y:r,width:i-t,height:n-r}}}Oe.prototype.className="Line";Oe.prototype._attrsAffectingSize=["points","bezier","tension"];ae(Oe);m.addGetterSetter(Oe,"closed",!1);m.addGetterSetter(Oe,"bezier",!1);m.addGetterSetter(Oe,"tension",0,I());m.addGetterSetter(Oe,"points",[],qa());const Do=[[],[],[-.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]],Oo=[[],[],[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]],Bo=[[1],[1,1],[1,2,1],[1,3,3,1]],ln=(a,e,t)=>{let i,r;const s=t/2;i=0;for(let o=0;o<20;o++)r=s*Do[20][o]+s,i+=Oo[20][o]*Go(a,e,r);return s*i},hn=(a,e,t)=>{t===void 0&&(t=1);const i=a[0]-2*a[1]+a[2],r=e[0]-2*e[1]+e[2],n=2*a[1]-2*a[0],s=2*e[1]-2*e[0],o=4*(i*i+r*r),l=4*(i*n+r*s),h=n*n+s*s;if(o===0)return t*Math.sqrt(Math.pow(a[2]-a[0],2)+Math.pow(e[2]-e[0],2));const c=l/(2*o),d=h/o,u=t+c,g=d-c*c,f=u*u+g>0?Math.sqrt(u*u+g):0,y=c*c+g>0?Math.sqrt(c*c+g):0,v=c+Math.sqrt(c*c+g)!==0?g*Math.log(Math.abs((u+f)/(c+y))):0;return Math.sqrt(o)/2*(u*f-c*y+v)};function Go(a,e,t){const i=pr(1,t,a),r=pr(1,t,e),n=i*i+r*r;return Math.sqrt(n)}const pr=(a,e,t)=>{const i=t.length-1;let r,n;if(i===0)return 0;if(a===0){n=0;for(let s=0;s<=i;s++)n+=Bo[i][s]*Math.pow(1-e,i-s)*Math.pow(e,s)*t[s];return n}else{r=new Array(i);for(let s=0;s<i;s++)r[s]=i*(t[s+1]-t[s]);return pr(a-1,e,r)}},cn=(a,e,t)=>{let i=1,r=a/e,n=(a-t(r))/e,s=0;for(;i>.001;){const o=t(r+n),l=Math.abs(a-o)/e;if(l<i)i=l,r+=n;else{const h=t(r-n),c=Math.abs(a-h)/e;c<i?(i=c,r-=n):n/=2}if(s++,s>500)break}return r};class ie extends P{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=ie.parsePathData(this.data()),this.pathLength=ie.getPathLength(this.dataArray)}_sceneFunc(e){const t=this.dataArray;e.beginPath();let i=!1;for(let r=0;r<t.length;r++){const n=t[r].command,s=t[r].points;switch(n){case"L":e.lineTo(s[0],s[1]);break;case"M":e.moveTo(s[0],s[1]);break;case"C":e.bezierCurveTo(s[0],s[1],s[2],s[3],s[4],s[5]);break;case"Q":e.quadraticCurveTo(s[0],s[1],s[2],s[3]);break;case"A":const o=s[0],l=s[1],h=s[2],c=s[3],d=s[4],u=s[5],g=s[6],f=s[7],y=h>c?h:c,v=h>c?1:h/c,C=h>c?c/h:1;e.translate(o,l),e.rotate(g),e.scale(v,C),e.arc(0,0,y,d,d+u,1-f),e.scale(1/v,1/C),e.rotate(-g),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const h=l.points[4],c=l.points[5],d=l.points[4]+c;let u=Math.PI/180;if(Math.abs(h-d)<u&&(u=Math.abs(h-d)),c<0)for(let g=h-u;g>d;g-=u){const f=ie.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}else for(let g=h+u;g<d;g+=u){const f=ie.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}}else if(l.command==="C")for(let h=0;h<=1;h+=.01){const c=ie.getPointOnCubicBezier(h,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);e.push(c.x,c.y)}else e=e.concat(l.points)});let t=e[0],i=e[0],r=e[1],n=e[1],s,o;for(let l=0;l<e.length/2;l++)s=e[l*2],o=e[l*2+1],isNaN(s)||(t=Math.min(t,s),i=Math.max(i,s)),isNaN(o)||(r=Math.min(r,o),n=Math.max(n,o));return{x:t,y:r,width:i-t,height:n-r}}getLength(){return this.pathLength}getPointAtLength(e){return ie.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,i,r){return Math.sqrt((i-e)*(i-e)+(r-t)*(r-t))}static getPathLength(e){let t=0;for(let i=0;i<e.length;++i)t+=e[i].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let i,r=0,n=t.length;if(!n)return null;for(;r<n&&e>t[r].pathLength;)e-=t[r].pathLength,++r;if(r===n)return i=t[r-1].points.slice(-2),{x:i[0],y:i[1]};if(e<.01)return t[r].command==="M"?(i=t[r].points.slice(0,2),{x:i[0],y:i[1]}):{x:t[r].start.x,y:t[r].start.y};const s=t[r],o=s.points;switch(s.command){case"L":return ie.getPointOnLine(e,s.start.x,s.start.y,o[0],o[1]);case"C":return ie.getPointOnCubicBezier(cn(e,ie.getPathLength(t),y=>ln([s.start.x,o[0],o[2],o[4]],[s.start.y,o[1],o[3],o[5]],y)),s.start.x,s.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return ie.getPointOnQuadraticBezier(cn(e,ie.getPathLength(t),y=>hn([s.start.x,o[0],o[2]],[s.start.y,o[1],o[3]],y)),s.start.x,s.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],g=o[6];let f=o[4];return f+=u*e/s.pathLength,ie.getPointOnEllipticalArc(l,h,c,d,f,g)}return null}static getPointOnLine(e,t,i,r,n,s,o){s=s??t,o=o??i;const l=this.getLineLength(t,i,r,n);if(l<1e-10)return{x:t,y:i};if(r===t)return{x:s,y:o+(n>i?e:-e)};const h=(n-i)/(r-t),c=Math.sqrt(e*e/(1+h*h))*(r<t?-1:1),d=h*c;if(Math.abs(o-i-h*(s-t))<1e-10)return{x:s+c,y:o+d};const u=((s-t)*(r-t)+(o-i)*(n-i))/(l*l),g=t+u*(r-t),f=i+u*(n-i),y=this.getLineLength(s,o,g,f),v=Math.sqrt(e*e-y*y),C=Math.sqrt(v*v/(1+h*h))*(r<t?-1:1),T=h*C;return{x:g+C,y:f+T}}static getPointOnCubicBezier(e,t,i,r,n,s,o,l,h){function c(v){return v*v*v}function d(v){return 3*v*v*(1-v)}function u(v){return 3*v*(1-v)*(1-v)}function g(v){return(1-v)*(1-v)*(1-v)}const f=l*c(e)+s*d(e)+r*u(e)+t*g(e),y=h*c(e)+o*d(e)+n*u(e)+i*g(e);return{x:f,y}}static getPointOnQuadraticBezier(e,t,i,r,n,s,o){function l(g){return g*g}function h(g){return 2*g*(1-g)}function c(g){return(1-g)*(1-g)}const d=s*l(e)+r*h(e)+t*c(e),u=o*l(e)+n*h(e)+i*c(e);return{x:d,y:u}}static getPointOnEllipticalArc(e,t,i,r,n,s){const o=Math.cos(s),l=Math.sin(s),h={x:i*Math.cos(n),y:r*Math.sin(n)};return{x:e+(h.x*o-h.y*l),y:t+(h.x*l+h.y*o)}}static parsePathData(e){if(!e)return[];let t=e;const i=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(let d=0;d<i.length;d++)t=t.replace(new RegExp(i[d],"g"),"|"+i[d]);const r=t.split("|"),n=[],s=[];let o=0,l=0;const h=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let c;for(let d=1;d<r.length;d++){let u=r[d],g=u.charAt(0);for(u=u.slice(1),s.length=0;c=h.exec(u);)s.push(c[0]);let f=[],y=g==="A"||g==="a"?0:-1;for(let v=0,C=s.length;v<C;v++){const T=s[v];if(T==="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(T)){f.push(parseInt(T[0],10)),f.push(parseInt(T[1],10)),f.push(parseFloat(T.slice(2))),y+=3,y>=7&&(y-=7);continue}if(T==="11"||T==="10"||T==="01"){f.push(parseInt(T[0],10)),f.push(parseInt(T[1],10)),y+=2,y>=7&&(y-=7);continue}if(T==="0"||T==="1"){f.push(parseInt(T,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(T)){f.push(parseInt(T[0],10)),f.push(parseFloat(T.slice(1))),y+=2,y>=7&&(y-=7);continue}if(T==="0"||T==="1"){f.push(parseInt(T,10)),y+=1,y>=7&&(y-=7);continue}}const w=parseFloat(T);isNaN(w)?f.push(0):f.push(w),y+=1,y>=7&&(y-=7)}else{const w=parseFloat(T);isNaN(w)?f.push(0):f.push(w)}}for(;f.length>0&&!isNaN(f[0]);){let v="",C=[];const T=o,w=l;let b,E,x,O,k,L,B,z,G,Y;switch(g){case"l":o+=f.shift(),l+=f.shift(),v="L",C.push(o,l);break;case"L":o=f.shift(),l=f.shift(),C.push(o,l);break;case"m":const V=f.shift(),H=f.shift();if(o+=V,l+=H,v="M",n.length>2&&n[n.length-1].command==="z"){for(let D=n.length-2;D>=0;D--)if(n[D].command==="M"){o=n[D].points[0]+V,l=n[D].points[1]+H;break}}C.push(o,l),g="l";break;case"M":o=f.shift(),l=f.shift(),v="M",C.push(o,l),g="L";break;case"h":o+=f.shift(),v="L",C.push(o,l);break;case"H":o=f.shift(),v="L",C.push(o,l);break;case"v":l+=f.shift(),v="L",C.push(o,l);break;case"V":l=f.shift(),v="L",C.push(o,l);break;case"C":C.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),l=f.shift(),C.push(o,l);break;case"c":C.push(o+f.shift(),l+f.shift(),o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="C",C.push(o,l);break;case"S":E=o,x=l,b=n[n.length-1],b.command==="C"&&(E=o+(o-b.points[2]),x=l+(l-b.points[3])),C.push(E,x,f.shift(),f.shift()),o=f.shift(),l=f.shift(),v="C",C.push(o,l);break;case"s":E=o,x=l,b=n[n.length-1],b.command==="C"&&(E=o+(o-b.points[2]),x=l+(l-b.points[3])),C.push(E,x,o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="C",C.push(o,l);break;case"Q":C.push(f.shift(),f.shift()),o=f.shift(),l=f.shift(),C.push(o,l);break;case"q":C.push(o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="Q",C.push(o,l);break;case"T":E=o,x=l,b=n[n.length-1],b.command==="Q"&&(E=o+(o-b.points[0]),x=l+(l-b.points[1])),o=f.shift(),l=f.shift(),v="Q",C.push(E,x,o,l);break;case"t":E=o,x=l,b=n[n.length-1],b.command==="Q"&&(E=o+(o-b.points[0]),x=l+(l-b.points[1])),o+=f.shift(),l+=f.shift(),v="Q",C.push(E,x,o,l);break;case"A":O=f.shift(),k=f.shift(),L=f.shift(),B=f.shift(),z=f.shift(),G=o,Y=l,o=f.shift(),l=f.shift(),v="A",C=this.convertEndpointToCenterParameterization(G,Y,o,l,B,z,O,k,L);break;case"a":O=f.shift(),k=f.shift(),L=f.shift(),B=f.shift(),z=f.shift(),G=o,Y=l,o+=f.shift(),l+=f.shift(),v="A",C=this.convertEndpointToCenterParameterization(G,Y,o,l,B,z,O,k,L);break}n.push({command:v||g,points:C,start:{x:T,y:w},pathLength:this.calcLength(T,w,v||g,C)})}(g==="z"||g==="Z")&&n.push({command:"z",points:[],start:void 0,pathLength:0})}return n}static calcLength(e,t,i,r){let n,s,o,l;const h=ie;switch(i){case"L":return h.getLineLength(e,t,r[0],r[1]);case"C":return ln([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return hn([e,r[0],r[2]],[t,r[1],r[3]],1);case"A":n=0;const c=r[4],d=r[5],u=r[4]+d;let g=Math.PI/180;if(Math.abs(c-u)<g&&(g=Math.abs(c-u)),s=h.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],c,0),d<0)for(l=c-g;l>u;l-=g)o=h.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=h.getLineLength(s.x,s.y,o.x,o.y),s=o;else for(l=c+g;l<u;l+=g)o=h.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=h.getLineLength(s.x,s.y,o.x,o.y),s=o;return o=h.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],u,0),n+=h.getLineLength(s.x,s.y,o.x,o.y),n}return 0}static convertEndpointToCenterParameterization(e,t,i,r,n,s,o,l,h){const c=h*(Math.PI/180),d=Math.cos(c)*(e-i)/2+Math.sin(c)*(t-r)/2,u=-1*Math.sin(c)*(e-i)/2+Math.cos(c)*(t-r)/2,g=d*d/(o*o)+u*u/(l*l);g>1&&(o*=Math.sqrt(g),l*=Math.sqrt(g));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===s&&(f*=-1),isNaN(f)&&(f=0);const y=f*o*u/l,v=f*-l*d/o,C=(e+i)/2+Math.cos(c)*y-Math.sin(c)*v,T=(t+r)/2+Math.sin(c)*y+Math.cos(c)*v,w=function(B){return Math.sqrt(B[0]*B[0]+B[1]*B[1])},b=function(B,z){return(B[0]*z[0]+B[1]*z[1])/(w(B)*w(z))},E=function(B,z){return(B[0]*z[1]<B[1]*z[0]?-1:1)*Math.acos(b(B,z))},x=E([1,0],[(d-y)/o,(u-v)/l]),O=[(d-y)/o,(u-v)/l],k=[(-1*d-y)/o,(-1*u-v)/l];let L=E(O,k);return b(O,k)<=-1&&(L=Math.PI),b(O,k)>=1&&(L=0),s===0&&L>0&&(L=L-2*Math.PI),s===1&&L<0&&(L=L+2*Math.PI),[C,T,o,l,x,L,c,s]}}ie.prototype.className="Path";ie.prototype._attrsAffectingSize=["data"];ae(ie);m.addGetterSetter(ie,"data");class ot extends Oe{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,i=this.points();let r=i;const n=this.tension()!==0&&i.length>4;n&&(r=this.getTensionPoints());const s=this.pointerLength(),o=i.length;let l,h;if(n){const u=[r[r.length-4],r[r.length-3],r[r.length-2],r[r.length-1],i[o-2],i[o-1]],g=ie.calcLength(r[r.length-4],r[r.length-3],"C",u),f=ie.getPointOnQuadraticBezier(Math.min(1,1-s/g),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)+t)%t,d=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(i[o-2],i[o-1]),e.rotate(c),e.moveTo(0,0),e.lineTo(-s,d/2),e.lineTo(-s,-d/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(i[0],i[1]),n?(l=(r[0]+r[2])/2-i[0],h=(r[1]+r[3])/2-i[1]):(l=i[2]-i[0],h=i[3]-i[1]),e.rotate((Math.atan2(-h,-l)+t)%t),e.moveTo(0,0),e.lineTo(-s,d/2),e.lineTo(-s,-d/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}}ot.prototype.className="Arrow";ae(ot);m.addGetterSetter(ot,"pointerLength",10,I());m.addGetterSetter(ot,"pointerWidth",10,I());m.addGetterSetter(ot,"pointerAtBeginning",!1);m.addGetterSetter(ot,"pointerAtEnding",!0);class kt extends P{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}kt.prototype._centroid=!0;kt.prototype.className="Circle";kt.prototype._attrsAffectingSize=["radius"];ae(kt);m.addGetterSetter(kt,"radius",0,I());class We extends P{_sceneFunc(e){const t=this.radiusX(),i=this.radiusY();e.beginPath(),e.save(),t!==i&&e.scale(1,i/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}We.prototype.className="Ellipse";We.prototype._centroid=!0;We.prototype._attrsAffectingSize=["radiusX","radiusY"];ae(We);m.addComponentsGetterSetter(We,"radius",["x","y"]);m.addGetterSetter(We,"radiusX",0,I());m.addGetterSetter(We,"radiusY",0,I());let Pe=class Ls extends P{constructor(e){super(e),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",t=>{this._removeImageLoad(t.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const e=this.image();e&&e.complete||e&&e.readyState===4||e&&e.addEventListener&&e.addEventListener("load",this._loadListener)}_removeImageLoad(e){e&&e.removeEventListener&&e.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const e=!!this.cornerRadius(),t=this.hasShadow();return e&&t?!0:super._useBufferCanvas(!0)}_sceneFunc(e){const t=this.getWidth(),i=this.getHeight(),r=this.cornerRadius(),n=this.attrs.image;let s;if(n){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?s=[n,this.cropX(),this.cropY(),o,l,0,0,t,i]:s=[n,0,0,t,i]}(this.hasFill()||this.hasStroke()||r)&&(e.beginPath(),r?S.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)),n&&(r&&e.clip(),e.drawImage.apply(e,s))}_hitFunc(e){const t=this.width(),i=this.height(),r=this.cornerRadius();e.beginPath(),r?S.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}getWidth(){var e,t,i;return(i=(e=this.attrs.width)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.width)!==null&&i!==void 0?i:0}getHeight(){var e,t,i;return(i=(e=this.attrs.height)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.height)!==null&&i!==void 0?i:0}static fromURL(e,t,i=null){const r=S.createImageElement();r.onload=function(){const n=new Ls({image:r});t(n)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Pe.prototype.className="Image";Pe.prototype._attrsAffectingSize=["image"];ae(Pe);m.addGetterSetter(Pe,"cornerRadius",0,Fi(4));m.addGetterSetter(Pe,"image");m.addComponentsGetterSetter(Pe,"crop",["x","y","width","height"]);m.addGetterSetter(Pe,"cropX",0,I());m.addGetterSetter(Pe,"cropY",0,I());m.addGetterSetter(Pe,"cropWidth",0,I());m.addGetterSetter(Pe,"cropHeight",0,I());const Rs=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],Ho="Change.konva",Fo="none",gr="up",fr="right",mr="down",yr="left",$o=Rs.length;class Hr extends Tt{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,i;const r=function(){t._sync()};for(i=0;i<$o;i++)e.on(Rs[i]+Ho,r)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),i,r,n,s,o,l,h;if(e&&t){switch(i=e.width(),r=e.height(),n=t.pointerDirection(),s=t.pointerWidth(),h=t.pointerHeight(),o=0,l=0,n){case gr:o=i/2,l=-1*h;break;case fr:o=i+s,l=r/2;break;case mr:o=i/2,l=r+h;break;case yr:o=-1*s,l=r/2;break}t.setAttrs({x:-1*o,y:-1*l,width:i,height:r}),e.setAttrs({x:-1*o,y:-1*l})}}}Hr.prototype.className="Label";ae(Hr);class lt extends P{_sceneFunc(e){const t=this.width(),i=this.height(),r=this.pointerDirection(),n=this.pointerWidth(),s=this.pointerHeight(),o=this.cornerRadius();let l=0,h=0,c=0,d=0;typeof o=="number"?l=h=c=d=Math.min(o,t/2,i/2):(l=Math.min(o[0]||0,t/2,i/2),h=Math.min(o[1]||0,t/2,i/2),d=Math.min(o[2]||0,t/2,i/2),c=Math.min(o[3]||0,t/2,i/2)),e.beginPath(),e.moveTo(l,0),r===gr&&(e.lineTo((t-n)/2,0),e.lineTo(t/2,-1*s),e.lineTo((t+n)/2,0)),e.lineTo(t-h,0),e.arc(t-h,h,h,Math.PI*3/2,0,!1),r===fr&&(e.lineTo(t,(i-s)/2),e.lineTo(t+n,i/2),e.lineTo(t,(i+s)/2)),e.lineTo(t,i-d),e.arc(t-d,i-d,d,0,Math.PI/2,!1),r===mr&&(e.lineTo((t+n)/2,i),e.lineTo(t/2,i+s),e.lineTo((t-n)/2,i)),e.lineTo(c,i),e.arc(c,i-c,c,Math.PI/2,Math.PI,!1),r===yr&&(e.lineTo(0,(i+s)/2),e.lineTo(-1*n,i/2),e.lineTo(0,(i-s)/2)),e.lineTo(0,l),e.arc(l,l,l,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,i=this.pointerWidth(),r=this.pointerHeight(),n=this.pointerDirection(),s=this.width(),o=this.height();return n===gr?(t-=r,o+=r):n===mr?o+=r:n===yr?(e-=i*1.5,s+=i):n===fr&&(s+=i*1.5),{x:e,y:t,width:s,height:o}}}lt.prototype.className="Tag";ae(lt);m.addGetterSetter(lt,"pointerDirection",Fo);m.addGetterSetter(lt,"pointerWidth",0,I());m.addGetterSetter(lt,"pointerHeight",0,I());m.addGetterSetter(lt,"cornerRadius",0,Fi(4));class ri extends P{_sceneFunc(e){const t=this.cornerRadius(),i=this.width(),r=this.height();e.beginPath(),t?S.drawRoundedRectPath(e,i,r,t):e.rect(0,0,i,r),e.closePath(),e.fillStrokeShape(this)}}ri.prototype.className="Rect";ae(ri);m.addGetterSetter(ri,"cornerRadius",0,Fi(4));class Ye extends P{_sceneFunc(e){const t=this._getPoints(),i=this.radius(),r=this.sides(),n=this.cornerRadius();if(e.beginPath(),n)S.drawRoundedPolygonPath(e,t,r,i,n);else{e.moveTo(t[0].x,t[0].y);for(let s=1;s<t.length;s++)e.lineTo(t[s].x,t[s].y)}e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,i=[];for(let r=0;r<e;r++)i.push({x:t*Math.sin(r*2*Math.PI/e),y:-1*t*Math.cos(r*2*Math.PI/e)});return i}getSelfRect(){const e=this._getPoints();let t=e[0].x,i=e[0].x,r=e[0].y,n=e[0].y;return e.forEach(s=>{t=Math.min(t,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),n=Math.max(n,s.y)}),{x:t,y:r,width:i-t,height:n-r}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Ye.prototype.className="RegularPolygon";Ye.prototype._centroid=!0;Ye.prototype._attrsAffectingSize=["radius"];ae(Ye);m.addGetterSetter(Ye,"radius",0,I());m.addGetterSetter(Ye,"sides",0,I());m.addGetterSetter(Ye,"cornerRadius",0,Fi(4));const dn=Math.PI*2;class ht extends P{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,dn,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),dn,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}ht.prototype.className="Ring";ht.prototype._centroid=!0;ht.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(ht);m.addGetterSetter(ht,"innerRadius",0,I());m.addGetterSetter(ht,"outerRadius",0,I());class Re extends P{constructor(e){super(e),this._updated=!0,this.anim=new we(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,n=this.animations()[t],s=this.frameOffsets(),o=n[r+0],l=n[r+1],h=n[r+2],c=n[r+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,h,c),e.closePath(),e.fillStrokeShape(this)),d)if(s){const u=s[t],g=i*2;e.drawImage(d,o,l,h,c,u[g+0],u[g+1],h,c)}else e.drawImage(d,o,l,h,c,0,0,h,c)}_hitFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,n=this.animations()[t],s=this.frameOffsets(),o=n[r+2],l=n[r+3];if(e.beginPath(),s){const h=s[t],c=i*2;e.rect(h[c+0],h[c+1],o,l)}else e.rect(0,0,o,l);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation(),i=this.animations(),r=i[t],n=r.length/4;e<n-1?this.frameIndex(e+1):this.frameIndex(0)}}Re.prototype.className="Sprite";ae(Re);m.addGetterSetter(Re,"animation");m.addGetterSetter(Re,"animations");m.addGetterSetter(Re,"frameOffsets");m.addGetterSetter(Re,"image");m.addGetterSetter(Re,"frameIndex",0,I());m.addGetterSetter(Re,"frameRate",17,I());m.backCompat(Re,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Xe extends P{_sceneFunc(e){const t=this.innerRadius(),i=this.outerRadius(),r=this.numPoints();e.beginPath(),e.moveTo(0,0-i);for(let n=1;n<r*2;n++){const s=n%2===0?i:t,o=s*Math.sin(n*Math.PI/r),l=-1*s*Math.cos(n*Math.PI/r);e.lineTo(o,l)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}Xe.prototype.className="Star";Xe.prototype._centroid=!0;Xe.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(Xe);m.addGetterSetter(Xe,"numPoints",5,I());m.addGetterSetter(Xe,"innerRadius",0,I());m.addGetterSetter(Xe,"outerRadius",0,I());function Fe(a){return[...a].reduce((e,t,i,r)=>{if(new RegExp("\\p{Emoji}","u").test(t)){const n=r[i+1];n&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(n)?(e.push(t+n),r[i+1]=""):e.push(t)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(t+(r[i+1]||""))?e.push(t+r[i+1]):i>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(t)?e[e.length-1]+=t:t&&e.push(t);return e},[])}const dt="auto",No="center",Ms="inherit",It="justify",zo="Change.konva",Vo="2d",un="-",Ds="left",Uo="text",Wo="Text",Yo="top",Xo="bottom",pn="middle",Os="normal",qo="px ",mi=" ",jo="right",gn="rtl",Ko="word",Zo="char",fn="none",ji="…",Bs=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Jo=Bs.length;function Qo(a){return a.split(",").map(e=>{e=e.trim();const t=e.indexOf(" ")>=0,i=e.indexOf('"')>=0||e.indexOf("'")>=0;return t&&!i&&(e=`"${e}"`),e}).join(", ")}let yi;function Ki(){return yi||(yi=S.createCanvasElement().getContext(Vo),yi)}function el(a){a.fillText(this._partialText,this._partialTextX,this._partialTextY)}function tl(a){a.setAttr("miterLimit",2),a.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function il(a){return a=a||{},!a.fillLinearGradientColorStops&&!a.fillRadialGradientColorStops&&!a.fillPatternImage&&(a.fill=a.fill||"black"),a}class re extends P{constructor(e){super(il(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<Jo;t++)this.on(Bs[t]+zo,this._setTextData);this._setTextData()}_sceneFunc(e){var t,i;const r=this.textArr,n=r.length;if(!this.text())return;let s=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,h=this.verticalAlign(),c=this.direction(),d=0,u=this.align(),g=this.getWidth(),f=this.letterSpacing(),y=this.charRenderFunc(),v=this.fill(),C=this.textDecoration(),T=this.underlineOffset(),w=C.indexOf("underline")!==-1,b=C.indexOf("line-through")!==-1,E;c=c===Ms?e.direction:c;let x=l/2,O=pn;if(!R.legacyTextRendering){const k=this.measureSize("M");O="alphabetic";const L=(t=k.fontBoundingBoxAscent)!==null&&t!==void 0?t:k.actualBoundingBoxAscent,B=(i=k.fontBoundingBoxDescent)!==null&&i!==void 0?i:k.actualBoundingBoxDescent;x=(L-B)/2+l/2}for(c===gn&&e.setAttr("direction",c),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",O),e.setAttr("textAlign",Ds),h===pn?d=(this.getHeight()-n*l-s*2)/2:h===Xo&&(d=this.getHeight()-n*l-s*2),e.translate(s,d+s),E=0;E<n;E++){let k=0,L=0;const B=r[E],z=B.text,G=B.width,Y=B.lastInParagraph;if(e.save(),u===jo?k+=g-G-s*2:u===No&&(k+=(g-G-s*2)/2),w){e.save(),e.beginPath();const H=T??(R.legacyTextRendering?Math.round(o/2):Math.round(o/4)),D=k,J=x+L+H;e.moveTo(D,J);const $=u===It&&!Y?g-s*2:G;e.lineTo(D+Math.round($),J),e.lineWidth=o/15;const j=this._getLinearGradient();e.strokeStyle=j||v,e.stroke(),e.restore()}const V=k;if(c!==gn&&(f!==0||u===It||y)){const H=z.split(" ").length-1,D=Fe(z);for(let J=0;J<D.length;J++){const $=D[J];if($===" "&&!Y&&u===It&&(k+=(g-s*2-G)/H),this._partialTextX=k,this._partialTextY=x+L,this._partialText=$,y){e.save();const ne=r.slice(0,E).reduce((oe,pe)=>oe+Fe(pe.text).length,0),W=J+ne;y({char:$,index:W,x:k,y:x+L,lineIndex:E,column:J,isLastInLine:Y,width:this.measureSize($).width,context:e})}e.fillStrokeShape(this),y&&e.restore(),k+=this.measureSize($).width+f}}else f!==0&&e.setAttr("letterSpacing",`${f}px`),this._partialTextX=k,this._partialTextY=x+L,this._partialText=z,e.fillStrokeShape(this);if(b){e.save(),e.beginPath();const H=R.legacyTextRendering?0:-Math.round(o/4),D=V;e.moveTo(D,x+L+H);const J=u===It&&!Y?g-s*2:G;e.lineTo(D+Math.round(J),x+L+H),e.lineWidth=o/15;const $=this._getLinearGradient();e.strokeStyle=$||v,e.stroke(),e.restore()}e.restore(),n>1&&(x+=l)}}_hitFunc(e){const t=this.getWidth(),i=this.getHeight();e.beginPath(),e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=S._isString(e)?e:e==null?"":e+"";return this._setAttr(Uo,t),this}getWidth(){return this.attrs.width===dt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===dt||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return S.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,i,r,n,s,o,l,h,c,d,u;let g=Ki(),f=this.fontSize(),y;g.save(),g.font=this._getContextFont(),y=g.measureText(e),g.restore();const v=f/100;return{actualBoundingBoxAscent:(t=y.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*v,actualBoundingBoxDescent:(i=y.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(r=y.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*v,actualBoundingBoxRight:(n=y.actualBoundingBoxRight)!==null&&n!==void 0?n:75.732421875*v,alphabeticBaseline:(s=y.alphabeticBaseline)!==null&&s!==void 0?s:0,emHeightAscent:(o=y.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(l=y.emHeightDescent)!==null&&l!==void 0?l:-20*v,fontBoundingBoxAscent:(h=y.fontBoundingBoxAscent)!==null&&h!==void 0?h:91*v,fontBoundingBoxDescent:(c=y.fontBoundingBoxDescent)!==null&&c!==void 0?c:21*v,hangingBaseline:(d=y.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*v,ideographicBaseline:(u=y.ideographicBaseline)!==null&&u!==void 0?u:-21*v,width:y.width,height:f}}_getContextFont(){return this.fontStyle()+mi+this.fontVariant()+mi+(this.fontSize()+qo)+Qo(this.fontFamily())}_addTextLine(e){this.align()===It&&(e=e.trim());const i=this._getTextWidth(e);return this.textArr.push({text:e,width:i,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),i=e.length;return Ki().measureText(e).width+t*i}_setTextData(){let e=this.text().split(`
|
|
15
|
-
`),t=+this.fontSize(),i=0,r=this.lineHeight()*t,n=this.attrs.width,s=this.attrs.height,o=n!==dt&&n!==void 0,l=s!==dt&&s!==void 0,h=this.padding(),c=n-h*2,d=s-h*2,u=0,g=this.wrap(),f=g!==fn,y=g!==Zo&&f,v=this.ellipsis();this.textArr=[],Ki().font=this._getContextFont();const C=v?this._getTextWidth(ji):0;for(let T=0,w=e.length;T<w;++T){let b=e[T],E=this._getTextWidth(b);if(o&&E>c)for(;b.length>0;){let x=0,O=Fe(b).length,k="",L=0;for(;x<O;){const B=x+O>>>1,z=Fe(b),G=z.slice(0,B+1).join(""),Y=this._getTextWidth(G);(v&&l&&u+r>d?Y+C:Y)<=c?(x=B+1,k=G,L=Y):O=B}if(k){if(y){const G=Fe(b),Y=Fe(k),V=G[Y.length],H=V===mi||V===un;let D;if(H&&L<=c)D=Y.length;else{const J=Y.lastIndexOf(mi),$=Y.lastIndexOf(un);D=Math.max(J,$)+1}D>0&&(x=D,k=G.slice(0,x).join(""),L=this._getTextWidth(k))}if(k=k.trimRight(),this._addTextLine(k),i=Math.max(i,L),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(b=Fe(b).slice(x).join("").trimLeft(),b.length>0&&(E=this._getTextWidth(b),E<=c)){this._addTextLine(b),u+=r,i=Math.max(i,E);break}}else break}else this._addTextLine(b),u+=r,i=Math.max(i,E),this._shouldHandleEllipsis(u)&&T<w-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),l&&u+r>d)break}this.textHeight=t,this.textWidth=i}_shouldHandleEllipsis(e){const t=+this.fontSize(),i=this.lineHeight()*t,r=this.attrs.height,n=r!==dt&&r!==void 0,s=this.padding(),o=r-s*2;return!(this.wrap()!==fn)||n&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==dt&&e!==void 0,i=this.padding(),r=e-i*2,n=this.ellipsis(),s=this.textArr[this.textArr.length-1];!s||!n||(t&&(this._getTextWidth(s.text+ji)<r||(s.text=s.text.slice(0,s.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(s.text+ji))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t?!0:super._useBufferCanvas()}}re.prototype._fillFunc=el;re.prototype._strokeFunc=tl;re.prototype.className=Wo;re.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];ae(re);m.overWriteSetter(re,"width",Or());m.overWriteSetter(re,"height",Or());m.addGetterSetter(re,"direction",Ms);m.addGetterSetter(re,"fontFamily","Arial");m.addGetterSetter(re,"fontSize",12,I());m.addGetterSetter(re,"fontStyle",Os);m.addGetterSetter(re,"fontVariant",Os);m.addGetterSetter(re,"padding",0,I());m.addGetterSetter(re,"align",Ds);m.addGetterSetter(re,"verticalAlign",Yo);m.addGetterSetter(re,"lineHeight",1,I());m.addGetterSetter(re,"wrap",Ko);m.addGetterSetter(re,"ellipsis",!1,xe());m.addGetterSetter(re,"letterSpacing",0,I());m.addGetterSetter(re,"text","",st());m.addGetterSetter(re,"textDecoration","");m.addGetterSetter(re,"underlineOffset",void 0,I());m.addGetterSetter(re,"charRenderFunc",void 0);const rl="",Gs="normal";function Hs(a){a.fillText(this.partialText,0,0)}function Fs(a){a.strokeText(this.partialText,0,0)}class he extends P{constructor(e){super(e),this.dummyCanvas=S.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 ie.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:ie.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=ie.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),i=this.fill(),r=this.fontSize(),n=this.glyphInfo,s=t.indexOf("underline")!==-1,o=t.indexOf("line-through")!==-1;s&&e.beginPath();for(let l=0;l<n.length;l++){e.save();const h=n[l].p0;e.translate(h.x,h.y),e.rotate(n[l].rotation),this.partialText=n[l].text,e.fillStrokeShape(this),s&&(l===0&&e.moveTo(0,r/2+1),e.lineTo(n[l].width,r/2+1)),e.restore()}if(s&&(e.strokeStyle=i,e.lineWidth=r/20,e.stroke()),o){e.beginPath();for(let l=0;l<n.length;l++){e.save();const h=n[l].p0;e.translate(h.x,h.y),e.rotate(n[l].rotation),l===0&&e.moveTo(0,0),e.lineTo(n[l].width,0),e.restore()}e.strokeStyle=i,e.lineWidth=r/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const i=t[0].p0;e.moveTo(i.x,i.y)}for(let i=0;i<t.length;i++){const r=t[i].p1;e.lineTo(r.x,r.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return S.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return re.prototype.setText.call(this,e)}_getContextFont(){return re.prototype._getContextFont.call(this)}_getTextSize(e){const i=this.dummyCanvas.getContext("2d");i.save(),i.font=this._getContextFont();const r=i.measureText(e);return i.restore(),{width:r.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const e=Fe(this.text()),t=[];let i=0;for(let d=0;d<e.length;d++)t.push({char:e[d],width:this._getTextSize(e[d]).width}),i+=t[d].width;const{height:r}=this._getTextSize(this.attrs.text);if(this.textWidth=i,this.textHeight=r,this.glyphInfo=[],!this.attrs.data)return null;const n=this.letterSpacing(),s=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*n,0);let h=0;s==="center"&&(h=Math.max(0,this.pathLength/2-l/2)),s==="right"&&(h=Math.max(0,this.pathLength-l));let c=h;for(let d=0;d<t.length;d++){const u=this._getPointAtLength(c);if(!u)return;const g=t[d].char;let f=t[d].width+n;if(g===" "&&s==="justify"){const b=this.text().split(" ").length-1;f+=(this.pathLength-l)/b}const y=this._getPointAtLength(c+f);if(!y)return;const v=ie.getLineLength(u.x,u.y,y.x,y.y);let C=0;if(o)try{C=o(t[d-1].char,g)*this.fontSize()}catch{C=0}u.x+=C,y.x+=C,this.textWidth+=C;const T=ie.getPointOnLine(C+v/2,u.x,u.y,y.x,y.y),w=Math.atan2(y.y-u.y,y.x-u.x);this.glyphInfo.push({transposeX:T.x,transposeY:T.y,text:e[d],rotation:w,p0:u,p1:y,width:v}),c+=f}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(h){e.push(h.p0.x),e.push(h.p0.y),e.push(h.p1.x),e.push(h.p1.y)});let t=e[0]||0,i=e[0]||0,r=e[1]||0,n=e[1]||0,s,o;for(let h=0;h<e.length/2;h++)s=e[h*2],o=e[h*2+1],t=Math.min(t,s),i=Math.max(i,s),r=Math.min(r,o),n=Math.max(n,o);const l=this.fontSize();return{x:t-l/2,y:r-l/2,width:i-t+l,height:n-r+l}}destroy(){return S.releaseCanvas(this.dummyCanvas),super.destroy()}}he.prototype._fillFunc=Hs;he.prototype._strokeFunc=Fs;he.prototype._fillFuncHit=Hs;he.prototype._strokeFuncHit=Fs;he.prototype.className="TextPath";he.prototype._attrsAffectingSize=["text","fontSize","data"];ae(he);m.addGetterSetter(he,"data");m.addGetterSetter(he,"fontFamily","Arial");m.addGetterSetter(he,"fontSize",12,I());m.addGetterSetter(he,"fontStyle",Gs);m.addGetterSetter(he,"align","left");m.addGetterSetter(he,"letterSpacing",0,I());m.addGetterSetter(he,"textBaseline","middle");m.addGetterSetter(he,"fontVariant",Gs);m.addGetterSetter(he,"text",rl);m.addGetterSetter(he,"textDecoration","");m.addGetterSetter(he,"kerningFunc",void 0);const $s="tr-konva",nl=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(a=>a+`.${$s}`).join(" "),mn="nodesRect",sl=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],al={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},ol="ontouchstart"in R._global;function ll(a,e,t){if(a==="rotater")return t;e+=S.degToRad(al[a]||0);const i=(S.radToDeg(e)%360+360)%360;return S._inRange(i,315+22.5,360)||S._inRange(i,0,22.5)?"ns-resize":S._inRange(i,45-22.5,45+22.5)?"nesw-resize":S._inRange(i,90-22.5,90+22.5)?"ew-resize":S._inRange(i,135-22.5,135+22.5)?"nwse-resize":S._inRange(i,180-22.5,180+22.5)?"ns-resize":S._inRange(i,225-22.5,225+22.5)?"nesw-resize":S._inRange(i,270-22.5,270+22.5)?"ew-resize":S._inRange(i,315-22.5,315+22.5)?"nwse-resize":(S.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}const Ri=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function hl(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 Ns(a,e,t){const i=t.x+(a.x-t.x)*Math.cos(e)-(a.y-t.y)*Math.sin(e),r=t.y+(a.x-t.x)*Math.sin(e)+(a.y-t.y)*Math.cos(e);return{...a,rotation:a.rotation+e,x:i,y:r}}function cl(a,e){const t=hl(a);return Ns(a,e,t)}function dl(a,e,t){let i=e;for(let r=0;r<a.length;r++){const n=R.getAngle(a[r]),s=Math.abs(n-e)%(Math.PI*2);Math.min(s,Math.PI*2-s)<t&&(i=n)}return i}let Sr=0;class X extends Tt{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(nl,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return S.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return $s+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(r=>r.isAncestorOf(this)?(S.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(r=>{const n=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(r._attrsAffectingSize.length){const s=r._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");r.on(s,n)}r.on(sl.map(s=>s+`.${this._getEventNamespace()}`).join(" "),n),r.on(`absoluteTransformChange.${this._getEventNamespace()}`,n),this._proxyDrag(r)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,i=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(i,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,i=>{if(!t)return;const r=e.getAbsolutePosition(),n=r.x-t.x,s=r.y-t.y;this.nodes().forEach(o=>{if(o===e||o.isDragging())return;const l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+n,y:l.y+s}),o.startDrag(i)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(mn),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(mn,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),i){const r=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),n=e.getAbsoluteScale(i),s=e.getAbsolutePosition(i),o=r.x*n.x-e.offsetX()*n.x,l=r.y*n.y-e.offsetY()*n.y,h=(R.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),c={x:s.x+o*Math.cos(h)+l*Math.sin(-h),y:s.y+l*Math.cos(h)+o*Math.sin(h),width:r.width*n.x,height:r.height*n.y,rotation:h};return Ns(c,-R.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(h=>{const c=h.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:c.x,y:c.y},{x:c.x+c.width,y:c.y},{x:c.x+c.width,y:c.y+c.height},{x:c.x,y:c.y+c.height}],u=h.getAbsoluteTransform();d.forEach(function(g){const f=u.point(g);t.push(f)})});const i=new Se;i.rotate(-R.getAngle(this.rotation()));let r=1/0,n=1/0,s=-1/0,o=-1/0;t.forEach(function(h){const c=i.point(h);r===void 0&&(r=s=c.x,n=o=c.y),r=Math.min(r,c.x),n=Math.min(n,c.y),s=Math.max(s,c.x),o=Math.max(o,c.y)}),i.invert();const l=i.point({x:r,y:n});return{x:l.x,y:l.y,width:s-r,height:o-n,rotation:R.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(),Ri.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new ri({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:ol?10:"auto"}),i=this;t.on("mousedown touchstart",function(r){i._handleMouseDown(r)}),t.on("dragstart",r=>{t.stopDrag(),r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),t.on("mouseenter",()=>{const r=R.getAngle(this.rotation()),n=this.rotateAnchorCursor(),s=ll(e,r,n);t.getStage().content&&(t.getStage().content.style.cursor=s),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new P({name:"back",width:0,height:0,sceneFunc(t,i){const r=i.getParent(),n=r.padding(),s=i.width(),o=i.height();if(t.beginPath(),t.rect(-n,-n,s+n*2,o+n*2),r.rotateEnabled()&&r.rotateLineVisible()){const l=r.rotateAnchorAngle(),h=r.rotateAnchorOffset(),c=S.degToRad(l),d=Math.sin(c),u=-Math.cos(c),g=s/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,-g/d):d>0&&(y=Math.min(y,(s-g)/d));const v=g+d*y,C=f+u*y,T=S._sign(o),w=v+d*h*T,b=C+u*h*T;t.moveTo(v,C),t.lineTo(w,b)}t.fillStrokeShape(i)},hitFunc:(t,i)=>{if(!this.shouldOverdrawWholeArea())return;const r=this.padding();t.beginPath(),t.rect(-r,-r,i.width()+r*2,i.height()+r*2),t.fillStrokeShape(i)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),i=t.width,r=t.height,n=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));this.sin=Math.abs(r/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 s=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-s.x,y:o.y-s.y},Sr++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(l=>{l._fire("transformstart",{evt:e.evt,target:l})})}_handleMouseMove(e){let t,i,r;const n=this.findOne("."+this._movingAnchorName),s=n.getStage();s.setPointersPositions(e);const o=s.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,e)),n.setAbsolutePosition(l);const c=n.getAbsolutePosition();if(h.x===c.x&&h.y===c.y)return;if(this._movingAnchorName==="rotater"){const T=this._getNodeRect();t=n.x()-T.width/2,i=-n.y()+T.height/2;const w=R.getAngle(this.rotateAnchorAngle());let b=Math.atan2(-i,t)+Math.PI/2-w;T.height<0&&(b-=Math.PI);const x=R.getAngle(this.rotation())+b,O=R.getAngle(this.rotationSnapTolerance()),L=dl(this.rotationSnaps(),x,O)-T.rotation,B=cl(T,L);this._fitNodesInto(B,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let g=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(T.x-n.x(),2)+Math.pow(T.y-n.y(),2));const w=this.findOne(".top-left").x()>T.x?-1:1,b=this.findOne(".top-left").y()>T.y?-1:1;t=r*this.cos*w,i=r*this.sin*b,this.findOne(".top-left").x(T.x-t),this.findOne(".top-left").y(T.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(n.y());else if(this._movingAnchorName==="top-right"){if(u){const T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(n.x()-T.x,2)+Math.pow(T.y-n.y(),2));const w=this.findOne(".top-right").x()<T.x?-1:1,b=this.findOne(".top-right").y()>T.y?-1:1;t=r*this.cos*w,i=r*this.sin*b,this.findOne(".top-right").x(T.x+t),this.findOne(".top-right").y(T.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 T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(T.x-n.x(),2)+Math.pow(n.y()-T.y,2));const w=T.x<n.x()?-1:1,b=n.y()<T.y?-1:1;t=r*this.cos*w,i=r*this.sin*b,n.x(T.x-t),n.y(T.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 T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};r=Math.sqrt(Math.pow(n.x()-T.x,2)+Math.pow(n.y()-T.y,2));const w=this.findOne(".bottom-right").x()<T.x?-1:1,b=this.findOne(".bottom-right").y()<T.y?-1:1;t=r*this.cos*w,i=r*this.sin*b,this.findOne(".bottom-right").x(T.x+t),this.findOne(".bottom-right").y(T.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(g=this.centeredScaling()||e.altKey,g){const T=this.findOne(".top-left"),w=this.findOne(".bottom-right"),b=T.x(),E=T.y(),x=this.getWidth()-w.x(),O=this.getHeight()-w.y();w.move({x:-b,y:-E}),T.move({x,y:O})}const y=this.findOne(".top-left").getAbsolutePosition();t=y.x,i=y.y;const v=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),C=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:i,width:v,height:C,rotation:R.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const i=this.getNode();Sr--,this._fire("transformend",{evt:e,target:i}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),i&&this._nodes.forEach(r=>{var n;r._fire("transformend",{evt:e,target:r}),(n=r.getLayer())===null||n===void 0||n.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const i=this._getNodeRect(),r=1;if(S._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(S._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const n=new Se;if(n.rotate(R.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const u=n.point({x:-this.padding()*2,y:0});e.x+=u.x,e.y+=u.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const u=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,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const u=n.point({x:0,y:-this.padding()*2});e.x+=u.x,e.y+=u.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const u=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,e.height+=this.padding()*2}if(this.boundBoxFunc()){const u=this.boundBoxFunc()(i,e);u?e=u:S.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const s=1e7,o=new Se;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/s,i.height/s);const l=new Se,h=e.width/s,c=e.height/s;this.flipEnabled()===!1?(l.translate(e.x,e.y),l.rotate(e.rotation),l.translate(e.width<0?e.width:0,e.height<0?e.height:0),l.scale(Math.abs(h),Math.abs(c))):(l.translate(e.x,e.y),l.rotate(e.rotation),l.scale(h,c));const d=l.multiply(o.invert());this._nodes.forEach(u=>{var g;if(!u.getStage())return;const f=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const v=new Se;v.multiply(f.copy().invert()).multiply(d).multiply(f).multiply(y);const C=v.decompose();u.setAttrs(C),(g=u.getLayer())===null||g===void 0||g.batchDraw()}),this.rotation(S._getRotation(e.rotation)),this._nodes.forEach(u=>{this._fire("transform",{evt:t,target:u}),u._fire("transform",{evt:t,target:u})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(S._getRotation(t.rotation));const i=t.width,r=t.height,n=this.enabledAnchors(),s=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),h=this.find("._anchor");h.forEach(x=>{x.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:s&&n.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:s&&n.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:s&&n.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:l/2+o,visible:s&&n.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:l/2-o,visible:s&&n.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:l/2+o,offsetY:l/2-o,visible:s&&n.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:l/2-o,visible:s&&n.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:l/2-o,offsetY:l/2-o,visible:s&&n.indexOf("bottom-right")>=0});const c=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=S.degToRad(c),g=Math.sin(u),f=-Math.cos(u),y=i/2,v=r/2;let C=1/0;f<0?C=Math.min(C,-v/f):f>0&&(C=Math.min(C,(r-v)/f)),g<0?C=Math.min(C,-y/g):g>0&&(C=Math.min(C,(i-y)/g));const T=y+g*C,w=v+f*C,b=S._sign(r);this._batchChangeChild(".rotater",{x:T+g*d*b,y:w+f*d*b-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(x=>x.draggable()),x:0,y:0});const E=this.anchorStyleFunc();E&&h.forEach(x=>{E(x)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),Tt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return A.prototype.toObject.call(this)}clone(e){return A.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}X.isTransforming=()=>Sr>0;function ul(a){return a instanceof Array||S.warn("enabledAnchors value should be an array"),a instanceof Array&&a.forEach(function(e){Ri.indexOf(e)===-1&&S.warn("Unknown anchor name: "+e+". Available names are: "+Ri.join(", "))}),a||[]}X.prototype.className="Transformer";ae(X);m.addGetterSetter(X,"enabledAnchors",Ri,ul);m.addGetterSetter(X,"flipEnabled",!0,xe());m.addGetterSetter(X,"resizeEnabled",!0);m.addGetterSetter(X,"anchorSize",10,I());m.addGetterSetter(X,"rotateEnabled",!0);m.addGetterSetter(X,"rotateLineVisible",!0);m.addGetterSetter(X,"rotationSnaps",[]);m.addGetterSetter(X,"rotateAnchorOffset",50,I());m.addGetterSetter(X,"rotateAnchorAngle",0,I());m.addGetterSetter(X,"rotateAnchorCursor","crosshair");m.addGetterSetter(X,"rotationSnapTolerance",5,I());m.addGetterSetter(X,"borderEnabled",!0);m.addGetterSetter(X,"anchorStroke","rgb(0, 161, 255)");m.addGetterSetter(X,"anchorStrokeWidth",1,I());m.addGetterSetter(X,"anchorFill","white");m.addGetterSetter(X,"anchorCornerRadius",0,I());m.addGetterSetter(X,"borderStroke","rgb(0, 161, 255)");m.addGetterSetter(X,"borderStrokeWidth",1,I());m.addGetterSetter(X,"borderDash");m.addGetterSetter(X,"keepRatio",!0);m.addGetterSetter(X,"shiftBehavior","default");m.addGetterSetter(X,"centeredScaling",!1);m.addGetterSetter(X,"ignoreStroke",!1);m.addGetterSetter(X,"padding",0,I());m.addGetterSetter(X,"nodes");m.addGetterSetter(X,"node");m.addGetterSetter(X,"boundBoxFunc");m.addGetterSetter(X,"anchorDragBoundFunc");m.addGetterSetter(X,"anchorStyleFunc");m.addGetterSetter(X,"shouldOverdrawWholeArea",!1);m.addGetterSetter(X,"useSingleNodeRotation",!0);m.backCompat(X,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Be extends P{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,R.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Be.prototype.className="Wedge";Be.prototype._centroid=!0;Be.prototype._attrsAffectingSize=["radius"];ae(Be);m.addGetterSetter(Be,"radius",0,I());m.addGetterSetter(Be,"angle",0,I());m.addGetterSetter(Be,"clockwise",!1);m.backCompat(Be,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function yn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const pl=[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],gl=[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 fl(a,e){const t=a.data,i=a.width,r=a.height;let n,s,o,l,h,c,d,u,g,f,y,v,C,T,w,b,E,x,O,k;const L=e+e+1,B=i-1,z=r-1,G=e+1,Y=G*(G+1)/2,V=new yn,H=pl[e],D=gl[e];let J=null,$=V,j=null,ne=null;for(let W=1;W<L;W++)$=$.next=new yn,W===G&&(J=$);$.next=V,o=s=0;for(let W=0;W<r;W++){v=C=T=w=l=h=c=d=0,u=G*(b=t[s]),g=G*(E=t[s+1]),f=G*(x=t[s+2]),y=G*(O=t[s+3]),l+=Y*b,h+=Y*E,c+=Y*x,d+=Y*O,$=V;for(let oe=0;oe<G;oe++)$.r=b,$.g=E,$.b=x,$.a=O,$=$.next;for(let oe=1;oe<G;oe++)n=s+((B<oe?B:oe)<<2),l+=($.r=b=t[n])*(k=G-oe),h+=($.g=E=t[n+1])*k,c+=($.b=x=t[n+2])*k,d+=($.a=O=t[n+3])*k,v+=b,C+=E,T+=x,w+=O,$=$.next;j=V,ne=J;for(let oe=0;oe<i;oe++)t[s+3]=O=d*H>>D,O!==0?(O=255/O,t[s]=(l*H>>D)*O,t[s+1]=(h*H>>D)*O,t[s+2]=(c*H>>D)*O):t[s]=t[s+1]=t[s+2]=0,l-=u,h-=g,c-=f,d-=y,u-=j.r,g-=j.g,f-=j.b,y-=j.a,n=o+((n=oe+e+1)<B?n:B)<<2,v+=j.r=t[n],C+=j.g=t[n+1],T+=j.b=t[n+2],w+=j.a=t[n+3],l+=v,h+=C,c+=T,d+=w,j=j.next,u+=b=ne.r,g+=E=ne.g,f+=x=ne.b,y+=O=ne.a,v-=b,C-=E,T-=x,w-=O,ne=ne.next,s+=4;o+=i}for(let W=0;W<i;W++){C=T=w=v=h=c=d=l=0,s=W<<2,u=G*(b=t[s]),g=G*(E=t[s+1]),f=G*(x=t[s+2]),y=G*(O=t[s+3]),l+=Y*b,h+=Y*E,c+=Y*x,d+=Y*O,$=V;for(let pe=0;pe<G;pe++)$.r=b,$.g=E,$.b=x,$.a=O,$=$.next;let oe=i;for(let pe=1;pe<=e;pe++)s=oe+W<<2,l+=($.r=b=t[s])*(k=G-pe),h+=($.g=E=t[s+1])*k,c+=($.b=x=t[s+2])*k,d+=($.a=O=t[s+3])*k,v+=b,C+=E,T+=x,w+=O,$=$.next,pe<z&&(oe+=i);s=W,j=V,ne=J;for(let pe=0;pe<r;pe++)n=s<<2,t[n+3]=O=d*H>>D,O>0?(O=255/O,t[n]=(l*H>>D)*O,t[n+1]=(h*H>>D)*O,t[n+2]=(c*H>>D)*O):t[n]=t[n+1]=t[n+2]=0,l-=u,h-=g,c-=f,d-=y,u-=j.r,g-=j.g,f-=j.b,y-=j.a,n=W+((n=pe+G)<z?n:z)*i<<2,l+=v+=j.r=t[n],h+=C+=j.g=t[n+1],c+=T+=j.b=t[n+2],d+=w+=j.a=t[n+3],j=j.next,u+=b=ne.r,g+=E=ne.g,f+=x=ne.b,y+=O=ne.a,v-=b,C-=E,T-=x,w-=O,ne=ne.next,s+=i}}const ml=function(e){const t=Math.round(this.blurRadius());t>0&&fl(e,t)};m.addGetterSetter(A,"blurRadius",0,I(),m.afterSetFilter);const yl=function(a){const e=this.brightness()*255,t=a.data,i=t.length;for(let r=0;r<i;r+=4)t[r]+=e,t[r+1]+=e,t[r+2]+=e};m.addGetterSetter(A,"brightness",0,I(),m.afterSetFilter);const Sl=function(a){const e=this.brightness(),t=a.data,i=t.length;for(let r=0;r<i;r+=4)t[r]=Math.min(255,t[r]*e),t[r+1]=Math.min(255,t[r+1]*e),t[r+2]=Math.min(255,t[r+2]*e)},Cl=function(a){const e=Math.pow((this.contrast()+100)/100,2),t=a.data,i=t.length;let r=150,n=150,s=150;for(let o=0;o<i;o+=4)r=t[o],n=t[o+1],s=t[o+2],r/=255,r-=.5,r*=e,r+=.5,r*=255,n/=255,n-=.5,n*=e,n+=.5,n*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,r=r<0?0:r>255?255:r,n=n<0?0:n>255?255:n,s=s<0?0:s>255?255:s,t[o]=r,t[o+1]=n,t[o+2]=s};m.addGetterSetter(A,"contrast",0,I(),m.afterSetFilter);const vl=function(a){var e,t,i,r,n,s,o,l,h;const c=a.data,d=a.width,u=a.height,g=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),f=Math.min(1,Math.max(0,(r=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&r!==void 0?r:.5)),v=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(s=(n=this.embossDirection)===null||n===void 0?void 0:n.call(this))!==null&&s!==void 0?s:"top-left"])!==null&&o!==void 0?o:315,C=!!((h=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&h!==void 0&&h),T=g*10,w=f*255,b=v*Math.PI/180,E=Math.cos(b),x=Math.sin(b),O=128/1020*T,k=new Uint8ClampedArray(c),L=new Float32Array(d*u);for(let V=0,H=0;H<c.length;H+=4,V++)L[V]=.2126*k[H]+.7152*k[H+1]+.0722*k[H+2];const B=[-1,0,1,-2,0,2,-1,0,1],z=[-1,-2,-1,0,0,0,1,2,1],G=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],Y=V=>V<0?0:V>255?255:V;for(let V=1;V<u-1;V++)for(let H=1;H<d-1;H++){const D=V*d+H;let J=0,$=0;J+=L[D+G[0]]*B[0],$+=L[D+G[0]]*z[0],J+=L[D+G[1]]*B[1],$+=L[D+G[1]]*z[1],J+=L[D+G[2]]*B[2],$+=L[D+G[2]]*z[2],J+=L[D+G[3]]*B[3],$+=L[D+G[3]]*z[3],J+=L[D+G[5]]*B[5],$+=L[D+G[5]]*z[5],J+=L[D+G[6]]*B[6],$+=L[D+G[6]]*z[6],J+=L[D+G[7]]*B[7],$+=L[D+G[7]]*z[7],J+=L[D+G[8]]*B[8],$+=L[D+G[8]]*z[8];const j=E*J+x*$,ne=Y(w+j*O),W=D*4;if(C){const oe=ne-w;c[W]=Y(k[W]+oe),c[W+1]=Y(k[W+1]+oe),c[W+2]=Y(k[W+2]+oe),c[W+3]=k[W+3]}else c[W]=c[W+1]=c[W+2]=ne,c[W+3]=k[W+3]}for(let V=0;V<d;V++){let H=V*4,D=((u-1)*d+V)*4;c[H]=k[H],c[H+1]=k[H+1],c[H+2]=k[H+2],c[H+3]=k[H+3],c[D]=k[D],c[D+1]=k[D+1],c[D+2]=k[D+2],c[D+3]=k[D+3]}for(let V=1;V<u-1;V++){let H=V*d*4,D=(V*d+(d-1))*4;c[H]=k[H],c[H+1]=k[H+1],c[H+2]=k[H+2],c[H+3]=k[H+3],c[D]=k[D],c[D+1]=k[D+1],c[D+2]=k[D+2],c[D+3]=k[D+3]}return a};m.addGetterSetter(A,"embossStrength",.5,I(),m.afterSetFilter);m.addGetterSetter(A,"embossWhiteLevel",.5,I(),m.afterSetFilter);m.addGetterSetter(A,"embossDirection","top-left",void 0,m.afterSetFilter);m.addGetterSetter(A,"embossBlend",!1,void 0,m.afterSetFilter);function Zi(a,e,t,i,r){const n=t-e,s=r-i;if(n===0)return i+s/2;if(s===0)return i;let o=(a-e)/n;return o=s*o+i,o}const Tl=function(a){const e=a.data,t=e.length;let i=e[0],r=i,n,s=e[1],o=s,l,h=e[2],c=h,d;const u=this.enhance();if(u===0)return;for(let w=0;w<t;w+=4)n=e[w+0],n<i?i=n:n>r&&(r=n),l=e[w+1],l<s?s=l:l>o&&(o=l),d=e[w+2],d<h?h=d:d>c&&(c=d);r===i&&(r=255,i=0),o===s&&(o=255,s=0),c===h&&(c=255,h=0);let g,f,y,v,C,T;if(u>0)g=r+u*(255-r),f=i-u*(i-0),y=o+u*(255-o),v=s-u*(s-0),C=c+u*(255-c),T=h-u*(h-0);else{const w=(r+i)*.5;g=r+u*(r-w),f=i+u*(i-w);const b=(o+s)*.5;y=o+u*(o-b),v=s+u*(s-b);const E=(c+h)*.5;C=c+u*(c-E),T=h+u*(h-E)}for(let w=0;w<t;w+=4)e[w+0]=Zi(e[w+0],i,r,f,g),e[w+1]=Zi(e[w+1],s,o,v,y),e[w+2]=Zi(e[w+2],h,c,T,C)};m.addGetterSetter(A,"enhance",0,I(),m.afterSetFilter);const bl=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4){const r=.34*e[i]+.5*e[i+1]+.16*e[i+2];e[i]=r,e[i+1]=r,e[i+2]=r}};m.addGetterSetter(A,"hue",0,I(),m.afterSetFilter);m.addGetterSetter(A,"saturation",0,I(),m.afterSetFilter);m.addGetterSetter(A,"luminance",0,I(),m.afterSetFilter);const wl=function(a){const e=a.data,t=e.length,i=1,r=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,s=this.luminance()*127,o=i*r*Math.cos(n*Math.PI/180),l=i*r*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,g=.587*i+.413*o+.035*l,f=.114*i-.114*o+.293*l,y=.299*i-.3*o+1.25*l,v=.587*i-.586*o-1.05*l,C=.114*i+.886*o-.2*l;let T,w,b,E;for(let x=0;x<t;x+=4)T=e[x+0],w=e[x+1],b=e[x+2],E=e[x+3],e[x+0]=h*T+c*w+d*b+s,e[x+1]=u*T+g*w+f*b+s,e[x+2]=y*T+v*w+C*b+s,e[x+3]=E},kl=function(a){const e=a.data,t=e.length,i=Math.pow(2,this.value()),r=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,s=i*r*Math.cos(n*Math.PI/180),o=i*r*Math.sin(n*Math.PI/180),l=.299*i+.701*s+.167*o,h=.587*i-.587*s+.33*o,c=.114*i-.114*s-.497*o,d=.299*i-.299*s-.328*o,u=.587*i+.413*s+.035*o,g=.114*i-.114*s+.293*o,f=.299*i-.3*s+1.25*o,y=.587*i-.586*s-1.05*o,v=.114*i+.886*s-.2*o;for(let C=0;C<t;C+=4){const T=e[C+0],w=e[C+1],b=e[C+2],E=e[C+3];e[C+0]=l*T+h*w+c*b,e[C+1]=d*T+u*w+g*b,e[C+2]=f*T+y*w+v*b,e[C+3]=E}};m.addGetterSetter(A,"hue",0,I(),m.afterSetFilter);m.addGetterSetter(A,"saturation",0,I(),m.afterSetFilter);m.addGetterSetter(A,"value",0,I(),m.afterSetFilter);const xl=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4)e[i]=255-e[i],e[i+1]=255-e[i+1],e[i+2]=255-e[i+2]},Pl=function(a,e,t){const i=a.data,r=e.data,n=a.width,s=a.height,o=t.polarCenterX||n/2,l=t.polarCenterY||s/2;let h=Math.sqrt(o*o+l*l),c=n-o,d=s-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const g=s,f=n,y=360/f*Math.PI/180;for(let v=0;v<f;v+=1){const C=Math.sin(v*y),T=Math.cos(v*y);for(let w=0;w<g;w+=1){c=Math.floor(o+h*w/g*T),d=Math.floor(l+h*w/g*C);let b=(d*n+c)*4;const E=i[b+0],x=i[b+1],O=i[b+2],k=i[b+3];b=(v+w*n)*4,r[b+0]=E,r[b+1]=x,r[b+2]=O,r[b+3]=k}}},_l=function(a,e,t){const i=a.data,r=e.data,n=a.width,s=a.height,o=t.polarCenterX||n/2,l=t.polarCenterY||s/2;let h=Math.sqrt(o*o+l*l),c=n-o,d=s-l;const u=Math.sqrt(c*c+d*d);h=u>h?u:h;const g=s,f=n,y=0;let v,C;for(c=0;c<n;c+=1)for(d=0;d<s;d+=1){const T=c-o,w=d-l,b=Math.sqrt(T*T+w*w)*g/h;let E=(Math.atan2(w,T)*180/Math.PI+360+y)%360;E=E*f/360,v=Math.floor(E),C=Math.floor(b);let x=(C*n+v)*4;const O=i[x+0],k=i[x+1],L=i[x+2],B=i[x+3];x=(d*n+c)*4,r[x+0]=O,r[x+1]=k,r[x+2]=L,r[x+3]=B}},Al=function(a){const e=a.width,t=a.height;let i,r,n,s,o,l,h,c,d,u,g=Math.round(this.kaleidoscopePower());const f=Math.round(this.kaleidoscopeAngle()),y=Math.floor(e*(f%360)/360);if(g<1)return;const v=S.createCanvasElement();v.width=e,v.height=t;const C=v.getContext("2d").getImageData(0,0,e,t);S.releaseCanvas(v),Pl(a,C,{polarCenterX:e/2,polarCenterY:t/2});let T=e/Math.pow(2,g);for(;T<=8;)T=T*2,g-=1;T=Math.ceil(T);let w=T,b=0,E=w,x=1;for(y+T>e&&(b=w,E=0,x=-1),r=0;r<t;r+=1)for(i=b;i!==E;i+=x)n=Math.round(i+y)%e,d=(e*r+n)*4,o=C.data[d+0],l=C.data[d+1],h=C.data[d+2],c=C.data[d+3],u=(e*r+i)*4,C.data[u+0]=o,C.data[u+1]=l,C.data[u+2]=h,C.data[u+3]=c;for(r=0;r<t;r+=1)for(w=Math.floor(T),s=0;s<g;s+=1){for(i=0;i<w+1;i+=1)d=(e*r+i)*4,o=C.data[d+0],l=C.data[d+1],h=C.data[d+2],c=C.data[d+3],u=(e*r+w*2-i-1)*4,C.data[u+0]=o,C.data[u+1]=l,C.data[u+2]=h,C.data[u+3]=c;w*=2}_l(C,a,{})};m.addGetterSetter(A,"kaleidoscopePower",2,I(),m.afterSetFilter);m.addGetterSetter(A,"kaleidoscopeAngle",0,I(),m.afterSetFilter);function Si(a,e,t){let i=(t*a.width+e)*4;const r=[];return r.push(a.data[i++],a.data[i++],a.data[i++],a.data[i++]),r}function Et(a,e){return Math.sqrt(Math.pow(a[0]-e[0],2)+Math.pow(a[1]-e[1],2)+Math.pow(a[2]-e[2],2))}function Il(a){const e=[0,0,0];for(let t=0;t<a.length;t++)e[0]+=a[t][0],e[1]+=a[t][1],e[2]+=a[t][2];return e[0]/=a.length,e[1]/=a.length,e[2]/=a.length,e}function El(a,e){const t=Si(a,0,0),i=Si(a,a.width-1,0),r=Si(a,0,a.height-1),n=Si(a,a.width-1,a.height-1),s=e||10;if(Et(t,i)<s&&Et(i,n)<s&&Et(n,r)<s&&Et(r,t)<s){const o=Il([i,t,n,r]),l=[];for(let h=0;h<a.width*a.height;h++){const c=Et(o,[a.data[h*4],a.data[h*4+1],a.data[h*4+2]]);l[h]=c<s?0:255}return l}}function Ll(a,e){for(let t=0;t<a.width*a.height;t++)a.data[4*t+3]=e[t]}function Rl(a,e,t){const i=[1,1,1,1,0,1,1,1,1],r=Math.round(Math.sqrt(i.length)),n=Math.floor(r/2),s=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const h=o*e+l;let c=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,v=i[d*r+u];c+=a[y]*v}}s[h]=c===255*8?255:0}return s}function Ml(a,e,t){const i=[1,1,1,1,1,1,1,1,1],r=Math.round(Math.sqrt(i.length)),n=Math.floor(r/2),s=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const h=o*e+l;let c=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,v=i[d*r+u];c+=a[y]*v}}s[h]=c>=255*4?255:0}return s}function Dl(a,e,t){const i=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],r=Math.round(Math.sqrt(i.length)),n=Math.floor(r/2),s=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const h=o*e+l;let c=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,v=i[d*r+u];c+=a[y]*v}}s[h]=c}return s}const Ol=function(a){const e=this.threshold();let t=El(a,e);return t&&(t=Rl(t,a.width,a.height),t=Ml(t,a.width,a.height),t=Dl(t,a.width,a.height),Ll(a,t)),a};m.addGetterSetter(A,"threshold",0,I(),m.afterSetFilter);const Bl=function(a){const e=this.noise()*255,t=a.data,i=t.length,r=e/2;for(let n=0;n<i;n+=4)t[n+0]+=r-2*r*Math.random(),t[n+1]+=r-2*r*Math.random(),t[n+2]+=r-2*r*Math.random()};m.addGetterSetter(A,"noise",.2,I(),m.afterSetFilter);const Gl=function(a){let e=Math.ceil(this.pixelSize()),t=a.width,i=a.height,r=Math.ceil(t/e),n=Math.ceil(i/e),s=a.data;if(e<=0){S.error("pixelSize value can not be <= 0");return}for(let o=0;o<r;o+=1)for(let l=0;l<n;l+=1){let h=0,c=0,d=0,u=0;const g=o*e,f=g+e,y=l*e,v=y+e;let C=0;for(let T=g;T<f;T+=1)if(!(T>=t))for(let w=y;w<v;w+=1){if(w>=i)continue;const b=(t*w+T)*4;h+=s[b+0],c+=s[b+1],d+=s[b+2],u+=s[b+3],C+=1}h=h/C,c=c/C,d=d/C,u=u/C;for(let T=g;T<f;T+=1)if(!(T>=t))for(let w=y;w<v;w+=1){if(w>=i)continue;const b=(t*w+T)*4;s[b+0]=h,s[b+1]=c,s[b+2]=d,s[b+3]=u}}};m.addGetterSetter(A,"pixelSize",8,I(),m.afterSetFilter);const Hl=function(a){const e=Math.round(this.levels()*254)+1,t=a.data,i=t.length,r=255/e;for(let n=0;n<i;n+=1)t[n]=Math.floor(t[n]/r)*r};m.addGetterSetter(A,"levels",.5,I(),m.afterSetFilter);const Fl=function(a){const e=a.data,t=e.length,i=this.red(),r=this.green(),n=this.blue();for(let s=0;s<t;s+=4){const o=(.34*e[s]+.5*e[s+1]+.16*e[s+2])/255;e[s]=o*i,e[s+1]=o*r,e[s+2]=o*n,e[s+3]=e[s+3]}};m.addGetterSetter(A,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(A,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(A,"blue",0,cs,m.afterSetFilter);const $l=function(a){const e=a.data,t=e.length,i=this.red(),r=this.green(),n=this.blue(),s=this.alpha();for(let o=0;o<t;o+=4){const l=1-s;e[o]=i*s+e[o]*l,e[o+1]=r*s+e[o+1]*l,e[o+2]=n*s+e[o+2]*l}};m.addGetterSetter(A,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(A,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(A,"blue",0,cs,m.afterSetFilter);m.addGetterSetter(A,"alpha",1,function(a){return this._filterUpToDate=!1,a>1?1:a<0?0:a});const Nl=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4){const r=e[i+0],n=e[i+1],s=e[i+2];e[i+0]=Math.min(255,r*.393+n*.769+s*.189),e[i+1]=Math.min(255,r*.349+n*.686+s*.168),e[i+2]=Math.min(255,r*.272+n*.534+s*.131)}},zl=function(a){const t=a.data;for(let i=0;i<t.length;i+=4){const r=t[i],n=t[i+1],s=t[i+2];.2126*r+.7152*n+.0722*s>=128&&(t[i]=255-r,t[i+1]=255-n,t[i+2]=255-s)}return a},Vl=function(a){const e=this.threshold()*255,t=a.data,i=t.length;for(let r=0;r<i;r+=1)t[r]=t[r]<e?0:255};m.addGetterSetter(A,"threshold",.5,I(),m.afterSetFilter);const q=an.Util._assign(an,{Arc:De,Arrow:ot,Circle:kt,Ellipse:We,Image:Pe,Label:Hr,Tag:lt,Line:Oe,Path:ie,Rect:ri,RegularPolygon:Ye,Ring:ht,Sprite:Re,Star:Xe,Text:re,TextPath:he,Transformer:X,Wedge:Be,Filters:{Blur:ml,Brightness:Sl,Brighten:yl,Contrast:Cl,Emboss:vl,Enhance:Tl,Grayscale:bl,HSL:wl,HSV:kl,Invert:xl,Kaleidoscope:Al,Mask:Ol,Noise:Bl,Pixelate:Gl,Posterize:Hl,RGB:Fl,RGBA:$l,Sepia:Nl,Solarize:zl,Threshold:Vl}}),Sn={debug:10,info:20,warn:30,error:40},Ci={enabled:!0,level:"warn",moduleLevels:{}},Cn=400;function Ul(a,e){return a.moduleLevels[e]??a.level}function je(a,e,t){if(!a.enabled)return!1;const i=Ul(a,t);return Sn[e]>=Sn[i]}function vn(a){if(!a||typeof a!="object")return null;const e="clientX"in a||"clientY"in a,t="deltaX"in a||"deltaY"in a,i="shiftKey"in a||"metaKey"in a||"ctrlKey"in a||"altKey"in a;return!e&&!t&&!i?null:{type:typeof a.type=="string"?a.type:void 0,clientX:typeof a.clientX=="number"?a.clientX:void 0,clientY:typeof a.clientY=="number"?a.clientY:void 0,button:typeof a.button=="number"?a.button:void 0,buttons:typeof a.buttons=="number"?a.buttons:void 0,deltaX:typeof a.deltaX=="number"?a.deltaX:void 0,deltaY:typeof a.deltaY=="number"?a.deltaY:void 0,shiftKey:!!a.shiftKey,metaKey:!!a.metaKey,ctrlKey:!!a.ctrlKey,altKey:!!a.altKey}}function Wl(a){if(a===void 0)return;const e=vn(a);if(e)return e;if(a&&typeof a=="object"&&"evt"in a){const t=vn(a.evt);if(t)return{...a,evt:t}}return a}function Yl(a,e,t,i){const r=Wl(i);r===void 0?a(`${e} ${t}`):a(`${e} ${t}`,r)}class M{static setConfig(e){if(!e){this.config={...Ci};return}this.config={enabled:e.enabled??Ci.enabled,level:e.level??Ci.level,moduleLevels:e.moduleLevels??{}}}static debug(e,t,i){je(this.config,"debug",e)&&this.emit("debug",e,t,i)}static debugLazy(e,t,i){if(!je(this.config,"debug",e))return;const r=t(),n=i?i():void 0;this.emit("debug",e,r,n)}static info(e,t,i){je(this.config,"info",e)&&this.emit("info",e,t,i)}static infoLazy(e,t,i){if(!je(this.config,"info",e))return;const r=t(),n=i?i():void 0;this.emit("info",e,r,n)}static warn(e,t,i){je(this.config,"warn",e)&&this.emit("warn",e,t,i)}static warnLazy(e,t,i){if(!je(this.config,"warn",e))return;const r=t(),n=i?i():void 0;this.emit("warn",e,r,n)}static error(e,t,i){je(this.config,"error",e)&&this.emit("error",e,t,i)}static setDedupeWindowMs(e){this.dedupeWindowMs=Number.isFinite(e)&&e>=0?e:Cn}static emit(e,t,i,r){const n=Date.now(),s=`${e}:${t}:${i}`,o=this.dedupeState.get(s);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(s,{lastPrintedAt:n,suppressed:0});const c=`[${e.toUpperCase()}] [${t}]`,d=this.resolveConsoleMethod(e);Yl(d,c,h,r)}static resolveConsoleMethod(e){return e==="debug"?console.log.bind(console):e==="info"?console.info.bind(console):e==="warn"?console.warn.bind(console):console.error.bind(console)}}p(M,"config",{...Ci}),p(M,"dedupeWindowMs",Cn),p(M,"dedupeState",new Map);const Ht="media-editor-track.preview-load-trace.v1",Xl=18e4,ql=4,jl=20,Kl=40;function Zl(){const a=Math.random().toString(36).slice(2,10);return`preview-${Date.now().toString(36)}-${a}`}function Jl(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function zs(a){if(!a||typeof a!="object")return!1;const e=Object.getPrototypeOf(a);return e===Object.prototype||e===null}function Cr(a,e,t){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean")return a??null;if(typeof a=="bigint")return a.toString();if(a instanceof Error)return{name:a.name,message:a.message,stack:a.stack??null};if(e>=ql)return"[max-depth]";if(Array.isArray(a))return a.slice(0,jl).map(i=>Cr(i,e+1,t));if(typeof a=="object"){if(t.has(a))return"[circular]";if(t.add(a),"tagName"in a&&typeof a.tagName=="string")return{tagName:a.tagName};if(!zs(a))return String(a);const i={};for(const r of Object.keys(a).slice(0,Kl))i[r]=Cr(a[r],e+1,t);return i}return String(a)}function Vs(a){if(!a)return null;const e=Cr(a,0,new WeakSet);return zs(e)?e:{value:e}}function gt(a=[]){return{version:1,currentSessionId:Zl(),updatedAt:Date.now(),entries:a.slice(-400)}}function Us(){try{return typeof globalThis.localStorage<"u"?globalThis.localStorage:null}catch{return null}}function Ql(a){if(!a||typeof a!="object")return null;const e=a;return typeof e.id!="string"||typeof e.sessionId!="string"||typeof e.createdAt!="number"||typeof e.isoTime!="string"||!["debug","info","warn","error"].includes(e.level)||typeof e.event!="string"?null:{id:e.id,sessionId:e.sessionId,createdAt:e.createdAt,isoTime:e.isoTime,perfTimeMs:typeof e.perfTimeMs=="number"?e.perfTimeMs:null,level:e.level,event:e.event,data:Vs(e.data)}}function eh(){const a=Us();if(!a)return gt();try{const e=a.getItem(Ht);if(!e)return gt();const t=JSON.parse(e);if(t.version!==1||!Array.isArray(t.entries))return gt();const i=t.entries.map(r=>Ql(r)).filter(r=>!!r);return{...gt(i),updatedAt:typeof t.updatedAt=="number"?t.updatedAt:Date.now()}}catch{return gt()}}function Tn(a){let e=a.entries.slice(-400);for(;e.length>0;){const t={...a,entries:e};if(JSON.stringify(t).length<=Xl)return t;e=e.slice(Math.ceil(e.length/8))}return{...a,entries:[]}}class th{constructor(){p(this,"state",eh());p(this,"listeners",new Set);var e,t;this.append({level:"info",event:"session.started",data:{href:typeof((e=globalThis.location)==null?void 0:e.href)=="string"?globalThis.location.href:null,userAgent:typeof((t=globalThis.navigator)==null?void 0:t.userAgent)=="string"?globalThis.navigator.userAgent:null}})}getStorageKey(){return Ht}getSnapshot(){return{storageKey:Ht,currentSessionId:this.state.currentSessionId,updatedAt:this.state.updatedAt,entries:[...this.state.entries]}}subscribe(e){return this.listeners.add(e),e(this.getSnapshot()),()=>{this.listeners.delete(e)}}append(e){const t=Date.now(),i={id:`${t}-${Math.random().toString(36).slice(2,8)}`,sessionId:this.state.currentSessionId,createdAt:t,isoTime:new Date(t).toISOString(),perfTimeMs:Jl(),level:e.level,event:e.event,data:Vs(e.data)};return this.state=Tn({...this.state,updatedAt:t,entries:[...this.state.entries,i]}),this.persist(),this.emit(),i}clear(){this.state=gt(),this.persist(),this.emit()}exportJson(e=200){const t=this.getSnapshot();return JSON.stringify({...t,exportedAt:new Date().toISOString(),exportedEntryCount:Math.min(e,t.entries.length),entries:t.entries.slice(-e)},null,2)}persist(){const e=Us();if(e)try{e.setItem(Ht,JSON.stringify(this.state))}catch{this.state=Tn({...this.state,entries:this.state.entries.slice(-Math.max(40,Math.floor(this.state.entries.length/2)))});try{e.setItem(Ht,JSON.stringify(this.state))}catch{}}}emit(){const e=this.getSnapshot();this.listeners.forEach(t=>t(e))}}const ih=new th;class Ae{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={}}static renderClipCovers(e,t,i,r,n,s=!1){M.debugLazy("ClipCoverRenderer",()=>"renderClipCovers",()=>({videoSrc:n,coverCount:(t==null?void 0:t.length)??0,coverWidth:i,coverHeight:r}));const o=(e.getAttr(this.COVER_RENDER_VERSION_KEY)||0)+1;if(e.setAttr(this.COVER_RENDER_VERSION_KEY,o),!t||t.length===0){e.destroyChildren(),s||this.requestRender(e);return}const l=this.buildSegmentsDataSync(t,i,r,n);if(l){this.renderSegments(e,l,i,r),s||this.requestRender(e);return}s||(e.destroyChildren(),this.requestRender(e)),this.startRenderJob({coversGroup:e,coverSource:t,coverWidth:i,coverHeight:r,videoSrc:n,version:o})}static async startRenderJob(e){const{coversGroup:t,coverSource:i,coverWidth:r,coverHeight:n,videoSrc:s,version:o}=e,l=await this.buildSegmentsData(i,r,n,s);if(this.isRenderJobCurrent(t,o)){if(this.renderSegments(t,l,r,n),!this.isRenderJobCurrent(t,o)){t.destroyChildren();return}this.requestRender(t)}}static async buildSegmentsData(e,t,i,r){const n=e.length,s=r||e[0]||"",o=await this.getSafeKeyframeDimensions(s,e[0]),l=o.width/o.height,h=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),c=Math.max(1,Math.ceil(t/h)),d=[];if(c===1)d.push(0);else for(let g=0;g<c;g++)d.push(Math.round(g*(n-1)/(c-1)));const u=[];for(let g=0;g<c;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:h,segmentStartX:g*h,segmentWidth:h})}return u}static buildSegmentsDataSync(e,t,i,r){const n=e.length,s=r||e[0]||"",o=this.getCachedKeyframeDimensions(s,e[0]);if(!o)return null;const l=o.width/o.height,h=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),c=Math.max(1,Math.ceil(t/h)),d=[];if(c===1)d.push(0);else for(let g=0;g<c;g++)d.push(Math.round(g*(n-1)/(c-1)));const u=[];for(let g=0;g<c;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:h,segmentStartX:g*h,segmentWidth:h})}return u}static requestRender(e){var i,r;const t=(i=e.getLayer)==null?void 0:i.call(e);if((r=t==null?void 0:t.getStage)!=null&&r.call(t))try{e.draw(),t.batchDraw()}catch{}}static isRenderJobCurrent(e,t){return e.getAttr(this.COVER_RENDER_VERSION_KEY)===t}static renderSegments(e,t,i,r){e.destroyChildren(),e.clip({x:0,y:0,width:i,height:r});for(const{coverUrl:n,singleImageWidth:s,segmentStartX:o,segmentWidth:l}of t){const h=Math.max(s,.01),c=this.getCachedImage(n),d=new q.Group({x:o,y:0,clip:{x:0,y:0,width:l,height:r},name:"cover-segment"});c.src||(c.src=n);const u=new q.Image({image:c,cornerRadius:2,name:"cover-image"});u.x(0),u.y(0),u.width(h),u.height(r),d.add(u),e.add(d)}}static async getSafeKeyframeDimensions(e,t){try{const i=await this.getKeyframeDimensions(e,t);if(i!=null&&i.width&&(i!=null&&i.height))return i}catch{}return this.DEFAULT_DIMENSIONS}static getKeyframeDimensions(e,t){const i=t||e;if(this.keyframeDimensionsCache[i])return Promise.resolve(this.keyframeDimensionsCache[i]);if(this.keyframeDimensionsPromiseCache[i])return this.keyframeDimensionsPromiseCache[i];const r=new Promise(n=>{const s=this.getCachedImage(t);if(s.complete&&s.width>0){const l={width:s.width,height:s.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)};s.onload=()=>{const l={width:s.width,height:s.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},s.onerror=()=>{o(this.DEFAULT_DIMENSIONS)},s.src||(s.src=t)});return this.keyframeDimensionsPromiseCache[i]=r,r}static getCachedKeyframeDimensions(e,t){const i=t||e,r=this.keyframeDimensionsCache[i];if(r!=null&&r.width&&(r!=null&&r.height))return r;const n=this.imageCache[t];if(n!=null&&n.complete&&n.width>0&&n.height>0){const s={width:n.width,height:n.height};return this.keyframeDimensionsCache[i]=s,s}return null}static getCachedImage(e){const t=this.imageCache[e];if(t)return t;const i=new Image;return this.imageCache[e]=i,this.checkAndTrimCache(),i}static checkAndTrimCache(){const e=Object.keys(this.imageCache);if(e.length<=this.MAX_CACHE_SIZE)return;const t=e.length-this.MAX_CACHE_SIZE,i=e.filter(s=>{const o=this.imageCache[s];return o&&!o.complete}),r=e.filter(s=>!i.includes(s));let n=0;for(const s of i){if(n>=t)break;this.evictCacheKey(s),n++}for(const s of r){if(n>=t)break;this.evictCacheKey(s),n++}}static evictCacheKey(e){delete this.imageCache[e],delete this.keyframeDimensionsCache[e],delete this.keyframeDimensionsPromiseCache[e]}}p(Ae,"MIN_IMAGE_DISPLAY_WIDTH",24),p(Ae,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),p(Ae,"MAX_CACHE_SIZE",1e3),p(Ae,"DEFAULT_DIMENSIONS",{width:160,height:90}),p(Ae,"keyframeDimensionsCache",{}),p(Ae,"keyframeDimensionsPromiseCache",{}),p(Ae,"imageCache",{});const rh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.8437804474494934,2.934130300488281C2.0975289474494936,2.6803818004882816,2.5560352474494934,2.5258255004882812,3.4537861474494935,2.5258255004882812L7.691924847449493,2.5258255004882812C8.589675247449494,2.5258255004882812,9.048181847449493,2.6803818004882816,9.301930747449493,2.934130300488281C9.555688247449494,3.1878788004882814,9.710234947449493,3.6463940004882813,9.710234947449493,4.544136000488281L9.710234947449493,5.154385800488281L9.710234947449493,5.156664400488282L9.710234947449493,8.837531600488282L9.710234947449493,8.839810400488282L9.710234947449493,9.455756700488282C9.710234947449493,10.352920500488281,9.554433147449494,10.811444300488281,9.299509347449494,11.065193200488281C9.045182547449494,11.319528600488281,8.586177147449494,11.474209800488282,7.691924847449493,11.474209800488282L3.4537861474494935,11.474209800488282C2.6371141474494935,11.474209800488282,2.1565246474494932,11.20751000048828,1.8706969474494934,10.86509900048828C1.5731912474494933,10.50867840048828,1.4354756474494934,10.006423900488281,1.4354756474494934,9.455756700488282L1.4354756474494934,4.544136000488281C1.4354756474494934,3.6463940004882813,1.5900319474494935,3.1878788004882814,1.8437804474494934,2.934130300488281ZM9.917876547449493,11.684700500488281C10.391550347449494,11.212192500488282,10.559057547449493,10.52217200048828,10.582387647449494,9.67692760048828L11.516774647449493,10.33260820048828L11.516774647449493,10.33260820048828C11.978190647449493,10.658107800488281,12.521887647449493,10.806299200488281,12.992055647449494,10.562466600488282C13.461642647449493,10.318055200488281,13.653574647449494,9.787735900488281,13.653574647449494,9.222480300488282L13.653574647449494,4.777554700488281C13.653574647449494,4.212299300488281,13.461625647449493,3.6825676004882815,12.992624647449494,3.437568500488281C12.523623647449494,3.1925697004882814,11.980024647449493,3.3384564004882815,11.519194647449494,3.6604486004882815L11.518056647449493,3.661018400488281L10.582387647449494,4.3178380004882815C10.558470047449493,3.475504500488281,10.392209347449493,2.7870953004882812,9.920297947449493,2.315762820488281C9.406961747449493,1.8024266504882813,8.637509647449493,1.6508255004882812,7.691924847449493,1.6508255004882812L3.4537861474494935,1.6508255004882812C2.5082015474494934,1.6508255004882812,1.7387490474494933,1.8024266504882813,1.2254129674494934,2.315762820488281C0.7120767974494934,2.8290989004882814,0.5604756474494934,3.598560200488281,0.5604756474494934,4.544136000488281L0.5604756474494934,9.455756700488282C0.5604756474494934,10.13592340048828,0.7290598274494934,10.86171720048828,1.1986388574494935,11.42521860048828C1.6798959474494934,12.003300500488281,2.4271137474494937,12.349209500488282,3.4537861474494935,12.349209500488282L7.691924847449493,12.349209500488282C8.635176947449493,12.349209500488282,9.403962447449494,12.197448500488282,9.917876547449493,11.684700500488281ZM12.020781647449493,9.61682840048828L10.585234647449493,8.609952000488281L10.585234647449493,5.384101600488281L12.019642647449494,4.377937300488281L12.020212647449494,4.3773675004882815C12.352129647449493,4.145782500488281,12.531874647449493,4.183709400488281,12.587880647449493,4.212877700488281C12.643876647449494,4.242046400488281,12.778574647449494,4.368635700488282,12.778574647449494,4.777554700488281L12.778574647449494,9.222480300488282C12.778574647449494,9.631399600488281,12.643866647449494,9.757436800488282,12.588449647449494,9.786018400488281C12.533620647449494,9.814020200488281,12.354416647449494,9.852481800488281,12.021921647449494,9.617398300488281L12.020781647449493,9.61682840048828ZM3.3313089474494935,3.9374466004882813C3.0898080474494933,3.9374466004882813,2.8938089474494935,4.133445700488281,2.8938089474494935,4.374946600488281C2.8938089474494935,4.616447400488282,3.0898080474494933,4.812446600488281,3.3313089474494935,4.812446600488281L4.815419447449494,4.812446600488281C5.056920347449493,4.812446600488281,5.252919447449494,4.616447400488282,5.252919447449494,4.374946600488281C5.252919447449494,4.133445700488281,5.056920347449493,3.9374466004882813,4.815419447449494,3.9374466004882813L3.3313089474494935,3.9374466004882813Z" fill="#868A9C" fill-opacity="1"/></svg>',nh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="16" height="16" viewBox="0 0 16 16"><path d="M11.206380472434997,2.733718973069763C9.993001372434998,1.991438673069763,8.552978872434998,1.6945722130697631,7.139648772434998,1.8937121730697632C5.7263186724349975,2.092858673069763,4.426350972434998,2.775678773069763,3.4596355724349976,3.825838973069763C2.4930013724349975,4.875998873069763,1.9263509724349976,6.228518873069763,1.8396810724349975,7.652945373069763C1.7596843224349974,9.077412973069762,2.1796875724349976,10.485612273069764,3.0196941724349977,11.637611373069763C3.8597005724349978,12.789678373069764,5.0796712724349975,13.614278373069762,6.459635572434998,13.970879373069764C7.839681072434997,14.327545373069762,9.299641972434998,14.194145373069762,10.593017972434998,13.593478373069763C11.892985472434997,12.992878373069763,12.933024472434997,11.962078373069764,13.552978472434997,10.676812573069764C14.173015472434997,9.391545673069762,14.326335472434998,7.9312790730697635,13.993001472434997,6.544878873069763C13.926350472434997,6.276532073069763,14.093017472434997,6.0061725730697635,14.359700472434998,5.941012273069763C14.626302472434997,5.875851973069763,14.899658472434998,6.040565873069763,14.966308472434998,6.308912673069763C15.353027472434997,7.920145873069763,15.173015472434997,9.617145873069763,14.453044472434998,11.110879373069762C13.732991472434998,12.604545373069763,12.519694472434997,13.802478373069762,11.019694472434997,14.500545373069762C9.513020872434998,15.198611373069763,7.812988672434997,15.353611373069763,6.2063802724349975,14.939145373069763C4.599690772434998,14.524678373069763,3.1930340724349975,13.566345373069764,2.2129720724349973,12.227478373069763C1.2329915724349976,10.888679373069763,0.7530111074349976,9.252079373069764,0.8463542074349976,7.5966790730697635C0.9396973124349975,5.941252573069764,1.5996907924349975,4.369405673069763,2.726318472434998,3.1489456730697634C3.8463543724349973,1.9284919730697632,5.359700572434997,1.134938593069763,6.999674672434997,0.9035053700697632C8.639648772434999,0.6720721230697632,10.312988672434997,1.0170720830697633,11.726318472434997,1.8797255730697633C11.966308472434998,2.023398773069763,12.039714472434998,2.3310454730697634,11.892985472434997,2.5668653730697635C11.753011472434997,2.8026921730697634,11.446370472434998,2.8773921730697634,11.206380472434997,2.733718973069763ZM11.686360472434998,5.413441573069763C11.879639472434997,5.608874673069764,11.879639472434997,5.925454473069763,11.686360472434998,6.1205485730697635L7.2396648724349975,10.559748073069763C7.046305572434997,10.754747773069763,6.7263186724349975,10.754615173069762,6.533040372434997,10.559481973069763L4.312988372434997,8.339814573069763C4.119710372434998,8.144614573069763,4.119710372434998,7.828014773069763,4.312988372434997,7.632747973069764C4.506347772434998,7.437481773069763,4.826334872434998,7.437481773069763,5.019694172434997,7.632747973069764L6.886311872434997,9.499081973069764L10.979655472434997,5.412814473069763C11.173015472434997,5.217727973069763,11.493001472434997,5.218008373069763,11.686360472434998,5.413441573069763Z" fill-rule="evenodd" fill="#24C744" fill-opacity="1"/></svg>',sh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.3164876075,5.2511568456573485C2.7112323875,3.0589928456573485,4.7552132875,1.7354023456573486,6.9998931875,1.7354023456573486C9.2445726875,1.7354023456573486,11.2885531875,3.0589928456573485,12.6832981875,5.2511568456573485C13.0012411875,5.7498953456573485,13.1452941875,6.3880765456573485,13.1452941875,6.9999821456573486C13.1452941875,7.611905345657348,13.0012411875,8.250068445657348,12.6832981875,8.74882484565735C11.2885531875,10.940988745657348,9.2445726875,12.264562345657348,6.9998931875,12.264562345657348C4.7552132875,12.264562345657348,2.7112323875,10.940988745657348,1.3164876075,8.74882484565735C0.9985453175,8.250068445657348,0.8544921875,7.611905345657348,0.8544921875,6.9999821456573486C0.8544921875,6.3880765456573485,0.9985453175,5.749325945657349,1.3164876075,5.2511568456573485ZM6.9998931875,2.6104023456573486C5.1262406875,2.6104023456573486,3.3318786875,3.713480445657349,2.0549823875,5.721323445657349L2.0543771875,5.721323445657349C1.8473052375,6.0456564456573485,1.7294921875,6.509396745657349,1.7294921875,6.9999821456573486C1.7294921875,7.490567445657349,1.8473052375,7.954324945657349,2.0543771875,8.278070645657348L2.0549823875,8.27865814565735C3.3318786875,10.286483045657349,5.1262406875,11.389561845657349,6.9998931875,11.389561845657349C8.8735446875,11.389561845657349,10.6679076875,10.286483045657349,11.9448031875,8.27865814565735L11.9454091875,8.278070645657348C12.1518751875,7.954324945657349,12.2702941875,7.490567445657349,12.2702941875,6.9999821456573486C12.2702941875,6.509396745657349,12.1518751875,6.0456564456573485,11.9454091875,5.721323445657349L11.9448031875,5.721323445657349C10.6679076875,3.713480445657349,8.8735446875,2.6104023456573486,6.9998931875,2.6104023456573486ZM4.4741208875,7.002937045657348C4.4741208875,5.606429845657349,5.6034745875,4.4771115456573485,6.9999641875,4.4771115456573485C8.3964533875,4.4771115456573485,9.5258073875,5.606429845657349,9.5258073875,7.002937045657348C9.5258073875,8.399444345657349,8.3964533875,9.528762545657349,6.9999641875,9.528762545657349C5.6034745875,9.528762545657349,4.4741208875,8.399444345657349,4.4741208875,7.002937045657348ZM6.9999641875,5.3521115456573485C6.0864762875,5.3521115456573485,5.3491210875,6.089431545657349,5.3491210875,7.002937045657348C5.3491210875,7.916442645657349,6.0864762875,8.653762545657349,6.9999641875,8.653762545657349C7.9134516875,8.653762545657349,8.650807387499999,7.916442645657349,8.650807387499999,7.002937045657348C8.650807387499999,6.089431545657349,7.9134516875,5.3521115456573485,6.9999641875,5.3521115456573485Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',ah='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="18" height="18" viewBox="0 0 18 18"><path d="M3.5486246148989866,6.472501117640625C3.7632801848989867,6.361666362640625,4.026926634898987,6.445068359640625,4.138366634898987,6.659741711640625C4.944508744898987,8.214329931640625,6.797759844898987,9.340158931640625,8.999857544898987,9.340158931640625C11.201954944898986,9.340158931640625,13.055775244898987,8.214329931640625,13.861347544898987,6.659741711640625C13.972788544898988,6.445068359640625,14.237040544898987,6.361666362640625,14.451090544898987,6.472501117640625C14.665781544898987,6.583905531640625,14.749770544898986,6.847569761640625,14.638366544898988,7.062243101640625C14.367100544898987,7.584907531640625,14.003692544898987,8.060913131640625,13.566192544898987,8.475074731640625L14.459278544898988,9.368161431640626C14.630177544898986,9.539077731640624,14.630177544898986,9.816164531640625,14.459278544898988,9.987080831640625C14.288344544898987,10.157996931640625,14.011275544898988,10.157996931640625,13.840342544898986,9.987080831640625L12.883701944898986,9.030405531640625C12.378519644898986,9.383328631640625,11.808039344898987,9.667999231640625,11.192590844898987,9.869249831640625L11.502344744898986,11.025413531640625C11.564757944898988,11.258743331640625,11.426508544898986,11.499069231640625,11.193196444898987,11.561500531640625C10.959848544898986,11.623913731640625,10.720092444898988,11.485664331640624,10.657109344898988,11.251747131640624L10.345611244898986,10.087999831640625C9.911600744898987,10.171401731640625,9.460677744898987,10.215158931640625,8.999857544898987,10.215158931640625C8.548365244898987,10.215158931640625,8.107340444898988,10.173164131640625,7.681518244898987,10.093233631640626L7.371195444898987,11.251747131640624C7.308781744898987,11.485664331640624,7.069025444898987,11.623913731640625,6.835108144898987,11.561500531640625C6.6017607448989875,11.499069231640625,6.4635111448989875,11.258743331640625,6.525924544898986,11.025413531640625L6.833363644898987,9.877990731640626C6.192280844898987,9.670900831640624,5.600189044898986,9.374000531640625,5.078094344898987,9.003578231640624L4.095179204898987,9.987080831640625C3.924280764898987,10.157996931640625,3.6471760548989867,10.157996931640625,3.476277614898987,9.987080831640625C3.305343588298987,9.816164531640625,3.305343588298987,9.539077731640624,3.476277614898987,9.368161431640626L4.400873744898987,8.443583031640625C3.9779357348989866,8.036987331640624,3.6256001248989866,7.572072231640625,3.361348427898987,7.062243101640625C3.250513676898987,6.847569761640625,3.3339334728989867,6.583905531640625,3.5486246148989866,6.472501117640625Z" fill="#FFFFFF" fill-opacity="1"/></svg>',oh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path d="M9.217651334374999,1.6159667934375C8.817657434375,1.7239685034375,8.579650834375,2.1349792434375,8.687652634374999,2.5349731234375C8.794677734375,2.9349670234375003,9.205657934375001,3.1719665234375,9.605651834375,3.0649719234374997C14.537658734375,1.7439575234375,19.612670734375,4.6739807234375,20.934661734375,9.6059570234375C22.255676734375,14.5379635234375,19.325652734375,19.6129765234375,14.393676734375,20.9349675234375C9.461669934375,22.2559815234375,4.3866577343749995,19.3259585234375,3.064666734375,14.3939815234375C2.3956604343750003,11.8969725234375,2.816650434375,9.3629761234375,4.036651634375,7.2969665234375C4.246673534375001,6.9399719234375,4.128662134375,6.4799804234375,3.771667434375,6.2699585234375C3.415649434375,6.0589599234375,2.955657934375,6.1779785234375,2.744659434375,6.5339660234375C1.3286743163749999,8.9329834234375,0.8386535643749999,11.8789675234375,1.615661624375,14.7819825234375C3.151672334375,20.5139775234375,9.049652134375,23.9199825234375,14.781677734375,22.3839725234375C20.513671734375,20.8479615234375,23.919677734375,14.9499815234375,22.383666734375,9.2179565234375C20.847656734375,3.4859619234375,14.949676734375,0.07995602343750008,9.217651334374999,1.6159667934375Z" fill="#C9CBD4" fill-opacity="1"/><path d="M16.7496337890625,12C16.7496337890625,14.6270103,14.6266440890625,16.75,11.9996337890625,16.75C9.3736238890625,16.75,7.2496337890625,14.6270103,7.2496337890625,12C7.2496337890625,9.3739901,9.3736238890625,7.25,11.9996337890625,7.25C14.6266440890625,7.25,16.7496337890625,9.3739901,16.7496337890625,12ZM11.9996337890625,15.25C13.7976336890625,15.25,15.2496337890625,13.7979999,15.2496337890625,12C15.2496337890625,10.2020001,13.7976336890625,8.75,11.9996337890625,8.75C10.2016338890625,8.75,8.7496337890625,10.2020001,8.7496337890625,12C8.7496337890625,13.7979999,10.2016338890625,15.25,11.9996337890625,15.25Z" fill="#C9CBD4" fill-opacity="1"/></svg>',lh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M12.594244271484374,3.926410052418518C12.594244271484374,3.9339934524185183,12.594244271484374,3.941576852418518,12.594244271484374,3.949160252418518L12.594244271484374,10.004165252418519L12.594244271484374,10.009998952418519C12.591269271484375,11.254248752418517,11.581520271484376,12.261664752418518,10.336686171484375,12.261664752418518C9.090102671484374,12.261664752418518,8.079185971484375,11.250748752418518,8.079185971484375,10.004165252418519C8.079185971484375,8.757582352418517,9.090102671484374,7.746665552418518,10.336686171484375,7.746665552418518C10.857602071484376,7.746665552418518,11.337102871484374,7.922832152418518,11.719244271484374,8.219165952418518L11.719244271484374,4.510315252418518L5.920881771484375,6.091725952418518L5.920881771484375,11.212248752418517L5.920881771484375,11.217499752418519C5.920881771484375,12.464083752418517,4.909947871484375,13.474998752418518,3.663387771484375,13.474998752418518C2.416787071484375,13.474998752418518,1.405852854251865,12.464082752418518,1.405852854251865,11.217499752418519C1.405852854251865,9.970916352418518,2.416786871484375,8.959999652418517,3.663387771484375,8.959999652418517C4.184269171484376,8.959999652418517,4.663780971484375,9.136166252418517,5.045881971484375,9.432499552418518L5.045881971484375,5.765065352418518C5.045881971484375,5.759809652418518,5.045881971484375,5.754577252418518,5.045881971484375,5.749326852418518L5.045881971484375,3.879142852418518C5.045881971484375,2.9108270524185182,5.645524971484375,2.2224822524185184,6.488441471484375,1.9926605524185181L10.128436071484375,1.000982272418518C10.652911171484375,0.8580656054185181,11.273518571484376,0.8131547724185181,11.781602271484376,1.1106431024185182C12.324102271484374,1.4273930824185181,12.594244271484374,2.0416489524185177,12.594244271484374,2.887488152418518L12.594244271484374,3.926410052418518ZM11.719244271484374,2.887487652418518C11.719244271484374,2.216660252418518,11.514435271484375,1.967576852418518,11.340019271484374,1.866071042418518C11.132935571484374,1.744731902418518,10.796352371484375,1.726076842418518,10.358268771484376,1.845648522418518L6.718304671484375,2.8373209524185183C6.231775271484375,2.969731652418518,5.920881771484375,3.330809252418518,5.920881771484375,3.879142452418518L5.920881771484375,5.184648152418518L11.719244271484374,3.603231552418518L11.719244271484374,2.887487652418518ZM3.663388271484375,12.599998752418518C4.426948071484375,12.599998752418518,5.045882471484375,11.981081752418518,5.045882471484375,11.217499752418519C5.045882471484375,10.453916152418518,4.426948271484375,9.834999652418517,3.663388271484375,9.834999652418517C2.8997932714843753,9.834999652418517,2.280853391484375,10.453916152418518,2.280853391484375,11.217499752418519C2.280853391484375,11.981082752418518,2.899793471484375,12.599998752418518,3.663388271484375,12.599998752418518ZM8.954185971484375,10.004165252418519C8.954185971484375,10.767749452418519,9.573102971484374,11.386664752418518,10.336686171484375,11.386664752418518C11.100269271484375,11.386664752418518,11.719244271484374,10.767748452418518,11.719244271484374,10.004165252418519C11.719244271484374,9.240582152418519,11.100269271484375,8.621665552418518,10.336686171484375,8.621665552418518C9.573102971484374,8.621665552418518,8.954185971484375,9.240582152418519,8.954185971484375,10.004165252418519Z" fill="#868A9C" fill-opacity="1"/></svg>',hh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M11.305803496070862,2.8583284381607053C11.498882496070863,2.713661038160706,11.773050496070862,2.7521666381607055,11.918296496070862,2.9458338381607057C13.720794496070862,5.347419838160706,13.720794496070862,8.652577538160706,11.918296496070862,11.054163138160705C11.773050496070862,11.247830138160706,11.498882496070863,11.286335138160705,11.305803496070862,11.141669138160706C11.112723496070862,10.996414138160706,11.073630496070862,10.722246738160706,11.218307496070862,10.529166838160705C12.787475496070861,8.439078938160705,12.787475496070861,5.5609179381607055,11.218307496070862,3.4708303381607055C11.073630496070862,3.2777506381607058,11.112723496070862,3.0035830381607056,11.305803496070862,2.8583284381607053ZM10.850643496070862,4.404167338160706C10.705398196070862,4.210500138160706,10.431231096070862,4.171994538160705,10.238133096070861,4.316661938160705C10.044466596070862,4.461916538160706,10.005978196070862,4.736083838160706,10.150637296070862,4.929163538160706C11.072313496070862,6.156499038160706,11.072313496070862,7.843498338160706,10.150637296070862,9.070833838160706C10.005978196070862,9.263913738160706,10.044466596070862,9.538080838160706,10.238133096070861,9.683335938160706C10.431231096070862,9.828002538160705,10.705398196070862,9.789497038160706,10.850643496070862,9.595830538160705C12.005633496070862,8.058162338160706,12.005633496070862,5.941834538160705,10.850643496070862,4.404167338160706ZM6.527554596070861,1.3638305381607054C7.564730296070862,0.4561640581607056,9.188140496070861,1.1929142881607055,9.188140496070861,2.5713347381607052L9.188140496070861,11.428662138160705C9.188140496070861,12.807083138160706,7.564730296070862,13.543833138160705,6.527554596070861,12.636166138160705L3.9608915960708617,10.390329938160706C3.934063996070862,10.367000238160706,3.9002226960708617,10.354164738160705,3.8646364960708617,10.354164738160705L2.917307496070862,10.354164738160705C1.7092156960708618,10.354164738160705,0.7298074960708618,9.374747838160706,0.7298074960708618,8.166665238160705L0.7298074960708618,5.8333321381607055C0.7298074960708618,4.6252492381607055,1.7092156960708618,3.6458321381607055,2.917307496070862,3.6458321381607055L3.8646364960708617,3.6458321381607055C3.9002226960708617,3.6458321381607055,3.934063996070862,3.6329969381607055,3.9608915960708617,3.6096674381607055L6.527554596070861,1.3638305381607054ZM8.313140496070861,2.5713347381607052C8.313140496070861,1.9448317881607056,7.575215496070862,1.6099954881607057,7.103891996070862,2.0224125381607054L4.537228696070862,4.268249638160706C4.351145196070862,4.430994638160706,4.111976496070862,4.520831938160706,3.8646364960708617,4.520831938160706L2.917307496070862,4.520831938160706C2.192217496070862,4.520831938160706,1.6048074960708618,5.108250738160706,1.6048074960708618,5.8333321381607055L1.6048074960708618,8.166665238160705C1.6048074960708618,8.891746138160705,2.192217496070862,9.479165638160705,2.917307496070862,9.479165638160705L3.8646364960708617,9.479165638160705C4.111976496070862,9.479165638160705,4.351145196070862,9.569002738160705,4.537228696070862,9.731748238160705L7.103891996070862,11.977584138160706C7.575215496070862,12.390002138160705,8.313140496070861,12.055165138160705,8.313140496070861,11.428662138160705L8.313140496070861,2.5713347381607052Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',ch='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M9.188069328125,2.7498358381607053L9.188069328125,2.5713360381607053C9.188069328125,1.1929155481607057,7.564641028125,0.4561653181607056,6.527501128125,1.3638317881607056L3.960820428125,3.6096686381607057C3.933975228125,3.6329981381607057,3.900151528125,3.6458331381607056,3.864583228125,3.6458331381607056L2.917236328125,3.6458331381607056C1.709162358125,3.6458331381607056,0.729736328125,4.625250238160706,0.729736328125,5.833333138160706L0.729736328125,8.166666138160705C0.729736328125,8.990334138160705,1.1847533881249999,9.707831938160705,1.857309928125,10.080586038160705L2.519968628125,9.417918838160706C1.989151028125,9.249912838160705,1.604736328125,8.752919338160705,1.604736328125,8.166666138160705L1.604736328125,5.833333138160706C1.604736328125,5.108252138160705,2.192164028125,4.520833138160706,2.917236328125,4.520833138160706L3.864583228125,4.520833138160706C4.111887428125,4.520833138160706,4.351074028125,4.4309958381607055,4.537139628125,4.268250538160705L7.103820828125,2.0224138381607055C7.575144328125,1.6099967381607057,8.313069328125,1.9448330381607055,8.313069328125,2.5713360381607053L8.313069328125,3.6248358381607058L9.188069328125,2.7498358381607053Z" fill="#FFFFFF" fill-opacity="1"/><path d="M9.188069388879395,6.8751726150512695L8.313069388879395,7.7501726150512695L8.313069388879395,11.42867231505127C8.313069388879395,12.055175315051269,7.575144088879394,12.39001181505127,7.103820288879394,11.97759441505127L5.493814768879394,10.56883951505127L4.8737382888793945,11.18892481505127L6.5275010888793945,12.63617661505127C7.564640988879395,13.54384331505127,9.188069388879395,12.807092715051269,9.188069388879395,11.42867231505127L9.188069388879395,6.8751726150512695Z" fill="#FFFFFF" fill-opacity="1"/><path d="M10.519225743566894,5.543419959263916C11.048904063566894,6.679164689263916,10.926391243566895,8.038332489263915,10.150583580566895,9.070834589263917C10.005889575566895,9.263914589263916,10.044412931566894,9.538081689263915,10.238062213566895,9.683336689263916C10.431141853566894,9.828003889263915,10.705327033566894,9.789498289263916,10.850555063566894,9.595831389263916C11.887160943566894,8.215666289263917,11.993331543566894,6.369420189263916,11.169067043566894,4.893587589263916L10.519225743566894,5.543419959263916Z" fill="#FFFFFF" fill-opacity="1"/><path d="M11.747202221848145,4.3160754470959475C12.761021631848145,6.290655617095947,12.584853731848145,8.708574817095947,11.218093551848144,10.529159117095947C11.073435149848144,10.722238517095947,11.112528165848145,10.996406117095948,11.305607791848145,11.141660717095947C11.498687411848145,11.286328317095947,11.772872571848145,11.247822717095946,11.918100651848144,11.054155317095947C13.545587731848144,8.886487017095948,13.703704331848144,5.9814896170959475,12.392949131848145,3.6703286170959473L11.747202221848145,4.3160754470959475Z" fill="#FFFFFF" fill-opacity="1"/><path d="M12.5598954921875,2.0591658358917235C12.7307934921875,1.8882496358917238,12.7307934921875,1.6117501858917236,12.5598954921875,1.4408339558917236C12.3889614921875,1.2699177268917237,12.1124624921875,1.2699177268917237,11.9415284921875,1.4408339558917236L1.4415283221875,11.940833335891723C1.2706298831875,12.111750335891724,1.2706298831875,12.388249335891723,1.4415283221875,12.559165335891723C1.6124623421875,12.730081335891724,1.8889617921875002,12.730081335891724,2.0598958121875,12.559165335891723L12.5598954921875,2.0591658358917235Z" fill="#FFFFFF" fill-opacity="1"/></svg>',dh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M3.348292020680237,2.6424992084503174C2.923644920680237,2.6424992084503174,2.578287720680237,2.9849191084503177,2.578287720680237,3.4125035084503175L2.578287720680237,4.474174308450317C2.578287720680237,4.715657508450317,2.382288570680237,4.911674308450317,2.140787720680237,4.911674308450317C1.8992868706802368,4.911674308450317,1.7032877206802368,4.715657508450317,1.7032877206802368,4.474174308450317L1.7032877206802368,3.4125035084503175C1.7032877206802368,2.4984104584503175,2.442957520680237,1.7674992084503174,3.348292020680237,1.7674992084503174L10.651636720680237,1.7674992084503174C11.565124120680236,1.7674992084503174,12.296640720680237,2.5071690084503175,12.296640720680237,3.4125035084503175L12.296640720680237,4.474174308450317C12.296640720680237,4.715657508450317,12.100641720680237,4.911674308450317,11.859140720680237,4.911674308450317C11.617640120680237,4.911674308450317,11.421641020680237,4.715657508450317,11.421641020680237,4.474174308450317L11.421641020680237,3.4125035084503175C11.421641020680237,2.9878386084503177,11.079203220680236,2.6424992084503174,10.651636720680237,2.6424992084503174L7.435114520680237,2.6424992084503174C7.436289420680237,2.657666388450317,7.437464320680236,2.6734210884503176,7.437464320680236,2.6891580184503177L7.437464320680236,11.357500308450318L8.714965420680237,11.357500308450318C8.956466320680237,11.357500308450318,9.152465420680237,11.553499508450317,9.152465420680237,11.795000208450318C9.152465420680237,12.036501208450318,8.956466320680237,12.232500208450318,8.714965420680237,12.232500208450318L5.284962820680237,12.232500208450318C5.043461920680237,12.232500208450318,4.847462820680237,12.036501208450318,4.847462820680237,11.795000208450318C4.847462820680237,11.553499508450317,5.043461920680237,11.357500308450318,5.284962820680237,11.357500308450318L6.562464320680236,11.357500308450318L6.562464320680236,2.6891580184503177C6.562464320680236,2.6734210884503176,6.563033720680237,2.657666388450317,6.564814220680237,2.6424992084503174L3.348292020680237,2.6424992084503174Z" fill="#868A9C" fill-opacity="1"/></svg>',uh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="2" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="4" y="4.5" width="1" height="6" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="6" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="8" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="10" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="12" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="14" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="16" y="6.5" width="1" height="2" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/></svg>',ph='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="2" y="7" width="15" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="4" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="6" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="8" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="10" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="12" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="14" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="16" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/></svg>',gh=new Map([["OmAi-camera",rh],["OmAi-accept",nh],["OmAi-display",sh],["OmAi-hide",ah],["OmAi-loading",oh],["OmAi-music",lh],["OmAi-volume",hh],["OmAi-volume-mute",ch],["OmAi-text",dh],["clip-audio",uh],["clip-without-audio",ph]]),bn=new Map;function Te(a){return gh.get(a)??""}function fh(a){const e=bn.get(a);if(e)return e;const t=Te(a);if(!t)return null;const i=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`,r=typeof Image>"u"?{src:i,complete:!0,naturalWidth:1,addEventListener:()=>{}}:new Image;return"decoding"in r&&(r.decoding="async"),r.src=i,bn.set(a,r),r}const de=3,wn=10,mh=4,yh=6,kn=8,xn=14,vr=10,Sh=12,Pn=4,Ws=1,Mi=28,Ys=8,Tr=19,br=15;function Jt(a,e,t,i,r=_.white,n=_.black,s=1){return new q.Rect({x:a,y:e,width:t,height:i,fill:r,stroke:n,strokeWidth:s})}function Di(a,e,t,i=12,r="Arial",n=_.black,s="left",o="top"){return new q.Text({text:a,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:s,verticalAlign:o})}function bt(a=0,e=0){return new q.Group({x:a,y:e})}function Ni(a,e,t,i){if(i){a.add(new q.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),a.add(new q.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}a.add(new q.Rect({x:0,y:0,width:de,height:t,name:"clip-resize-left"})),a.add(new q.Rect({x:e-de,y:0,width:de,height:t,name:"clip-resize-right"}))}function Ch(a,e,t,i){const r=a.findOne(".clip-resize-left"),n=a.findOne(".clip-resize-right");return!r||!n?!1:(r.x(0),r.y(0),r.width(de),r.height(t),n.x(e-de),n.y(0),n.width(de),n.height(t),!0)}function Xs(a,e,t){const i=e?a.clipSelectedBorder:_.transparent,r=e?Ws:0;return t==="audio"?{background:_.audioClipBackground,label:a.audioClipText||a.clipName,accent:a.audioClipAccent||a.clipHandle,coverBackground:a.clipCoverBackground||Q.clipCoverBackground,border:i,borderWidth:r}:t==="text"?{background:_.textClipBackground,label:a.clipName,accent:a.clipHandle,coverBackground:a.clipCoverBackground||_.accentCoverFallback,border:i,borderWidth:r}:{background:_.videoClipBackground,label:a.clipName,accent:a.clipHandle,coverBackground:a.clipCoverBackground||_.accentCoverFallback,border:i,borderWidth:r}}function vh(a,e,t,i){const r=Jt(0,0,e,t,i.background,i.border,i.borderWidth);r.cornerRadius(Math.min(4,Math.floor(e/2))),r.name("clip-background"),a.add(r),Ni(a,e,t,!0)}function Th(a,e,t){const i=Jt(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),a.add(i),Ni(a,e.width,e.height,!1);const r=15,n=e.height-r-4,s=e.width-de*2,o=bt(de,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:s,height:n}),a.add(o);const l=Jt(0,0,s,n,t.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const h=bt(0,0);h.name("clip-covers-group"),o.add(h),Ae.renderClipCovers(h,e.thumbnails??[],s,n,e.videoSrc,e.deferCoverRender);const c=s>=120?Mi+Ys:0,d=Di(`${e.clipName} ${F.formatDuration(e.duration)}`,de,e.height-r,vr,"Arial",t.label,"left","middle");d.ellipsis(!0),d.width(Math.max(0,s-c)),d.height(r),d.name("clip-label"),a.add(d),c>0&&js(a,e.width,e.height,e.hasSeparatedAudio)}function bh(a,e,t){const i=a.findOne(".clip-background"),r=a.findOne(".clip-cover-container"),n=a.findOne(".clip-cover-background"),s=a.findOne(".clip-covers-group"),o=a.findOne(".clip-label");if(!i||!r||!n||!s||!o||(i.width(e.width),i.height(e.height),i.fill(t.background),i.stroke(t.border),i.strokeWidth(t.borderWidth),i.cornerRadius(4),!Ch(a,e.width,e.height)))return!1;const l=15,h=e.height-l-4,c=e.width-de*2;r.x(de),r.y(2),r.clip({x:0,y:0,width:c,height:h}),n.width(c),n.height(h),n.fill(t.coverBackground),n.cornerRadius(2),Ae.renderClipCovers(s,e.thumbnails??[],c,h,e.videoSrc,e.deferCoverRender);const d=c>=120?Mi+Ys:0;o.text(`${e.clipName} ${F.formatDuration(e.duration)}`),o.x(de),o.y(e.height-l),o.fill(t.label),o.width(Math.max(0,c-d)),o.height(l),o.ellipsis(!0);const u=a.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&js(a,e.width,e.height,e.hasSeparatedAudio),!0}function wh(a,e){e.complete&&e.naturalWidth>0||e.addEventListener("load",()=>{var t,i;(i=(t=a.getLayer)==null?void 0:t.call(a))==null||i.batchDraw()},{once:!0})}function qs(a,e,t,i,r){a.name()||a.name(r);const n=fh(e);if(!n)return 0;const s=new q.Image({x:0,y:0,width:t,height:i,image:n,listening:!1});return s.name(`${r}-image`),a.add(s),wh(a,n),t}function js(a,e,t,i){const r=bt(Math.max(de,e-de-Mi-2),Math.max(0,t-15));r.name("video-audio-status");const n=bt(Math.max(0,Mi-Tr),0),s=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";n.name(s),qs(n,o,Tr,br,`${s}-icon`),r.add(n),a.add(r)}function kh(a,e,t){const i=Jt(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(6),i.name("clip-background"),a.add(i),Ni(a,e.width,e.height,!1);const r=de+wn,n=Math.max(0,e.width-de*2-wn*2),s=mh,o=bt(r,s),l=qs(o,"clip-audio",Tr,br,"audio-clip-icon");a.add(o);const h=r+l+kn,c=Math.max(0,n-l-kn);if(e.audioBadgeText&&c>0){const u=Di(e.audioBadgeText,h,s,vr,"Arial",t.label,"left","middle");u.ellipsis(!0),u.width(c),u.height(br),u.name("audio-clip-badge"),a.add(u)}const d=Di(e.clipName,r,e.height-yh-xn,vr,"Arial",t.label,"left","middle");d.ellipsis(!0),d.width(n),d.height(xn),d.name("clip-label"),a.add(d)}function xh(a,e,t){const i=Jt(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),a.add(i),Ni(a,e.width,e.height,!1);const r=Di(e.clipName,Pn,0,Sh,"Arial",t.label,"left","middle");r.width(Math.max(0,e.width-Pn*2)),r.height(e.height),r.lineHeight(1),r.ellipsis(!0),r.wrap("none"),r.name("clip-label"),a.add(r)}function Ks(a,e){const t=e.width<=Kt,i=Xs(e.theme,e.isSelected,e.clipType);if(a.destroyChildren(),t){vh(a,e.width,e.height,i);return}if(e.clipType==="audio"){kh(a,e,i);return}if(e.clipType==="text"){xh(a,e,i);return}Th(a,e,i)}function Ph(a,e){if(e.width<=Kt||e.clipType!=="video")return!1;const i=Xs(e.theme,e.isSelected,e.clipType);return bh(a,e,i)}function _h(a,e,t,i,r,n,s,o=!1,l,h,c="video",d=!1,u=!1,g){const f=bt(a,e);return f.clip({x:0,y:0,width:t,height:i}),Ks(f,{width:t,height:i,clipName:r,audioBadgeText:g,duration:n,theme:s,isSelected:o,thumbnails:l,videoSrc:h,clipType:c,hasSeparatedAudio:d,deferCoverRender:u}),f}function Ah(a,e,t,i,r,n,s=!1,o,l,h="video",c=!1,d=!1,u){a.clip({x:0,y:0,width:e,height:t});const g={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:n??Li,isSelected:s,thumbnails:o,videoSrc:l,clipType:h,hasSeparatedAudio:c,deferCoverRender:d};Ph(a,g)||Ks(a,g)}function Ih(a,e,t,i){return new q.Rect({x:a,y:e,width:t,height:i,stroke:_.clipSelectedBorder,strokeWidth:Ws,fillEnabled:!1})}function wr(a,e=yt.stroke,t=1){return new q.Line({points:a,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function Eh(a,e,t,i=12,r="Arial",n=yt.text,s="left",o="top"){return new q.Text({text:a,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:s,verticalAlign:o})}function Lh(a=0,e=0){return new q.Group({x:a,y:e})}function Rh(a,e,t,i,r,n,s,o){const l=o||i,h=s==="major"?l*.6:l*.3,c=wr([e,t,e,t+h],n.timeTick,s==="major"?1:.5);if(c.name("time-tick-line"),a.add(c),s==="major"){const d=t+h+5,u=Eh(F.formatTime(r),e,d,10,"Arial",n.timeText,"center");u.name("time-tick-text"),a.add(u)}}function Mh(a,e,t,i,r,n){const s=Lh(e,t);for(let o=0;o<=i;o+=n)s.add(wr([o,0,o,r],Vr.line,.5));for(let o=0;o<=r;o+=n)s.add(wr([0,o,i,o],Vr.line,.5));a.add(s)}class se{static createStage(e,t,i){return new q.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new q.Layer;return t.name(e),t}static createRect(e,t,i,r,n=yt.fill,s=yt.stroke,o=1){return new q.Rect({x:e,y:t,width:i,height:r,fill:n,stroke:s,strokeWidth:o})}static createText(e,t,i,r=12,n="Arial",s=yt.text,o="left",l="top"){return new q.Text({text:e,x:t,y:i,fontSize:r,fontFamily:n,fill:s,align:o,verticalAlign:l})}static createLine(e,t=yt.stroke,i=1){return new q.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new q.Group({x:e,y:t})}static createPlayhead(e,t,i){const r=new q.Group({x:e,y:t}),n=this.createLine([0,0,0,i],Ei.marker,2),s=new q.RegularPolygon({x:0,y:-10,sides:3,radius:5,fill:Ei.marker,rotation:180});return r.add(n),r.add(s),r}static drawTimeTick(e,t,i,r,n,s,o,l){Rh(e,t,i,r,n,s,o,l)}static drawGrid(e,t,i,r,n,s){Mh(e,t,i,r,n,s)}static clearImageCache(){Ae.clearImageCache()}static createClipGroup(e,t,i,r,n,s,o,l=!1,h,c,d="video",u=!1,g=!1,f){return _h(e,t,i,r,n,s,o,l,h,c,d,u,g,f)}static updateClipGroup(e,t,i,r,n,s,o=!1,l,h,c="video",d=!1,u=!1,g){Ah(e,t,i,r,n,s,o,l,h,c,d,u,g)}static createSelectionEffect(e,t,i,r){return Ih(e,t,i,r)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}p(se,"RESIZE_AREA_WIDTH",3);function ni(a){let e=!1;return typeof window<"u"&&(window.addEventListener("mousemove",a.onPointerMove),window.addEventListener("mouseup",a.onPointerEnd),window.addEventListener("blur",a.onWindowBlur||a.onPointerEnd),e=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",a.onVisibilityChange),e=!0),e}function si(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 Dh{constructor(e,t,i,r,n,s){p(this,"stage");p(this,"gridLayer");p(this,"config");p(this,"theme");p(this,"isDragging",!1);p(this,"startDragX",0);p(this,"scrollLeft",0);p(this,"timeScaleHeight",40);p(this,"onTimeChange");p(this,"onZoomChange");p(this,"onScrollChange");p(this,"animationFrameId",null);p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"isScrollbarDragging",!1);p(this,"scrollbarDragStartX",0);p(this,"scrollbarDragStartScrollLeft",0);p(this,"isPointerInsideTimeline",!1);p(this,"lastPointerXInTimeline",null);p(this,"scrollbarHeight",12);p(this,"scrollbarMargin",4);p(this,"handleGlobalPointerMove",e=>{this.isPointerSessionActive()&&this.handlePointerMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.finalizePointerInteraction()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finalizePointerInteraction()});p(this,"leftPadding",ue);this.stage=e,this.gridLayer=t,this.onTimeChange=r,this.onZoomChange=n,this.onScrollChange=s,this.config={duration:i.duration||36e5,zoom:i.zoom||ye.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:jt(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,i.timeScaleHeight&&(this.timeScaleHeight=i.timeScaleHeight),this.initEventListeners(),this.render()}initEventListeners(){this.stage.on("wheel",e=>{e.evt.preventDefault(),this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0;const{deltaX:t,deltaY:i,shiftKey:r}=e.evt,n=Math.abs(t)>0;if(r||n){const l=(n?t:i)*1.5,h=this.stage.width(),c=F.timeToPixels(this.config.duration,this.config.zoom),d=Math.max(0,c-h),u=Math.max(0,Math.min(d,this.scrollLeft+l));u!==this.scrollLeft&&this.animateHorizontalScroll(u)}else Math.abs(i)>0&&this.handleZoom(e)}),this.stage.on("click",e=>{let t=e.target.getLayer();const i=e.target.name()==="scrollbar-background"||e.target.name()==="scrollbar-thumb";t===this.gridLayer&&!i&&this.handleClick(e.evt.offsetX)}),this.stage.on("mousedown",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0;let t=e.target.getLayer(),i=e.target.name()==="scrollbar-background"||e.target.name()==="scrollbar-thumb";t===this.gridLayer&&e.target.name()==="scrollbar-thumb"?(this.isScrollbarDragging=!0,this.scrollbarDragStartX=e.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):t===this.gridLayer&&e.target.name()==="scrollbar-background"?(this.jumpScrollbarToPointer(e.evt.offsetX),this.isScrollbarDragging=!0,this.scrollbarDragStartX=e.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):t===this.gridLayer&&!i&&(this.isDragging=!0,this.startDragX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isPointerSessionActive()&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.finalizePointerInteraction()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=ni({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(si({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}isPointerSessionActive(){return this.isDragging||this.isScrollbarDragging}finalizePointerInteraction(){this.isDragging=!1,this.isScrollbarDragging=!1,this.unbindGlobalPointerListenersForDrag()}handlePointerMove(e){if(this.isScrollbarDragging){const t=this.stage.width(),i=this.getTotalDurationPixels(),r=Math.max(0,i-t);if(r<=0)return;const n=this.getScrollbarThumbWidth(),s=Math.max(1,t-n),o=e.clientX-this.scrollbarDragStartX,l=this.scrollLeft,h=this.scrollbarDragStartScrollLeft+o/s*r;this.scrollLeft=Math.max(0,Math.min(r,h)),this.render(),this.scrollLeft!==l&&this.onScrollChange(this.scrollLeft)}else if(this.isDragging){const t=e.clientX-this.startDragX,i=this.scrollLeft;this.scrollLeft-=t;const r=this.stage.width(),n=F.timeToPixels(this.config.duration,this.config.zoom);this.scrollLeft=Math.max(0,Math.min(n-r,this.scrollLeft)),this.startDragX=e.clientX,this.render(),this.scrollLeft!==i&&this.onScrollChange(this.scrollLeft)}}handleZoom(e){const t=e.evt.deltaY;if(t===0)return;const i=t>0?.5:1.5,r=Math.max(ye.MIN,Math.min(ye.MAX,this.config.zoom*i));if(r!==this.config.zoom){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const n=e.evt.offsetX;this.animateZoom(r,n)}}animateZoom(e,t){const i=this.config.zoom,r=ls.DURATION,n=Date.now(),s=this.pixelToTime(t),o=()=>{const l=Date.now()-n,h=Math.min(l/r,1),c=this.easeOutCubic(h),d=i+(e-i)*c,u=F.timeToPixels(s,d),g=Math.max(0,u-(t-this.leftPadding));if(this.scrollLeft=g,this.config.zoom=d,this.onZoomChange(d),this.onScrollChange(g),this.render(),h<1)this.animationFrameId=requestAnimationFrame(o);else{const f=F.timeToPixels(s,e),y=Math.max(0,f-(t-this.leftPadding));this.config.zoom=e,this.scrollLeft=y,this.onZoomChange(e),this.onScrollChange(y),this.render()}};this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),o()}animateHorizontalScroll(e){const t=this.scrollLeft,i=300,r=Date.now(),n=this.stage.width(),s=F.timeToPixels(this.config.duration,this.config.zoom);this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const o=()=>{const l=Date.now()-r,h=Math.min(l/i,1),c=this.easeOutCubic(h),d=t+(e-t)*c;this.scrollLeft=Math.max(0,Math.min(s-n,d)),this.onScrollChange(this.scrollLeft),this.render(),h<1?this.animationFrameId=requestAnimationFrame(o):(this.scrollLeft=Math.max(0,Math.min(s-n,e)),this.onScrollChange(this.scrollLeft),this.render())};o()}easeOutCubic(e){return 1-Math.pow(1-e,3)}handleClick(e){const t=this.pixelToTime(e);this.setCurrentTime(t)}pixelToTime(e){return F.pixelsToTime(e-this.leftPadding+this.scrollLeft,this.config.zoom)}timeToPixel(e){return F.timeToPixels(e,this.config.zoom)-this.scrollLeft+this.leftPadding}setCurrentTime(e){this.config.currentTime=Math.max(0,e),this.onTimeChange(this.config.currentTime)}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setPlayState(e){this.config.playState=e,this.render()}update(){this.render()}render(){const e=this.stage.width(),t=this.stage.height(),i=this.gridLayer.findOne(".timeline-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const r=se.createRect(0,0,e,t,this.theme.background,this.theme.border,1);r.name("timeline-background"),this.gridLayer.add(r)}this.gridLayer.find(".grid-line").forEach(r=>r.remove()),this.gridLayer.find(".time-tick-line").forEach(r=>r.remove()),this.gridLayer.find(".time-tick-text").forEach(r=>r.remove()),this.renderTimeTicks(),this.renderScrollbar(),this.gridLayer.batchDraw()}renderScrollbar(){const e=this.stage.width(),t=this.stage.height(),i=Math.max(this.timeScaleHeight,t-this.scrollbarHeight-this.scrollbarMargin),r=this.getScrollbarThumbWidth(),n=this.getScrollbarThumbX(r),s=this.gridLayer.findOne(".scrollbar-background");if(s)s.x(0),s.y(i),s.width(e),s.height(this.scrollbarHeight),s.fill(this.theme.scrollbarBackground||fe.background),s.stroke(this.theme.scrollbarBorder||fe.border),s.visible(!0);else{const l=se.createRect(0,i,e,this.scrollbarHeight,this.theme.scrollbarBackground||fe.background,this.theme.scrollbarBorder||fe.border,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(r),o.height(this.scrollbarHeight),o.fill(this.theme.scrollbarThumb||fe.thumb),o.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border),o.visible(r<e);else{const l=se.createRect(n,i,r,this.scrollbarHeight,this.theme.scrollbarThumb||fe.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border,1);l.name("scrollbar-thumb"),l.visible(r<e),this.gridLayer.add(l)}}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,r=F.pixelsToTime(t,this.config.zoom),n=F.pixelsToTime(i,this.config.zoom),s=F.msToSeconds(r),o=F.msToSeconds(n),l=10,h=s-l,c=o+l,{majorStep:d,minorStep:u}=F.getTickConfig(this.config.zoom),g=F.generateVisibleTicks(h,c,d,u);let f=0;const y=20;for(const v of g){const C=this.timeToPixel(v.time);C>=-y&&C<=e+y&&(se.drawTimeTick(this.gridLayer,C,0,this.timeScaleHeight,v.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},v.type,this.timeScaleHeight),f++)}M.debugLazy("Timeline",()=>`Timeline - scrollLeft: ${this.scrollLeft}px, zoom: ${this.config.zoom}px/s, visible time: ${Math.round(s)}s to ${Math.round(o)}s, ticks: ${g.length} generated, ${f} drawn`)}getConfig(){return{...this.config}}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){const t=this.stage.width(),i=this.getTotalDurationPixels();this.scrollLeft=Math.max(0,Math.min(i-t,e)),this.render()}getTotalDurationPixels(){return F.timeToPixels(this.config.duration,this.config.zoom)}getScrollbarThumbWidth(){const e=this.stage.width(),t=this.getTotalDurationPixels();return t<=0||t<=e?e:Math.max(40,e/t*e)}getScrollbarThumbX(e){const t=this.stage.width(),i=this.getTotalDurationPixels(),r=Math.max(0,i-t);if(r<=0||e>=t)return 0;const n=t-e;return this.scrollLeft/r*n}jumpScrollbarToPointer(e){const t=this.stage.width(),i=this.getTotalDurationPixels(),r=Math.max(0,i-t);if(r<=0)return;const n=this.getScrollbarThumbWidth(),s=Math.max(1,t-n),l=Math.max(n/2,Math.min(t-n/2,e))-n/2,h=this.scrollLeft;this.scrollLeft=l/s*r,this.render(),this.scrollLeft!==h&&this.onScrollChange(this.scrollLeft)}scrollToTime(e){const t=F.timeToPixels(e,this.config.zoom),i=this.stage.width(),r=Math.max(0,t-i/2);this.setScrollLeft(r),this.onScrollChange(r)}scrollToClip(e){const t=F.timeToPixels(e.startTime,this.config.zoom),r=F.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,n=this.stage.width();let s;r<=n?s=Math.max(0,t-(n-r)/2):s=Math.max(0,t),this.setScrollLeft(s),this.onScrollChange(s)}getStage(){return this.stage}getGridLayer(){return this.gridLayer}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}resize(e,t){this.render()}}const Ft=8;function me(a,e,t){return se.timeToPixels(a,e)-t+ue}function Ie(a,e){const t=se.timeToPixels(a,e);return a<=1e3||t<=Kt?Kt:t}function Oh(a,e){const t=me(a.startTime,a.zoom,a.scrollLeft),i=Ie(a.duration,a.zoom);return t+i>0&&t<e}function Bh(a){for(const e of a.clips){const t=me(e.startTime,a.zoom,a.scrollLeft),i=Ie(e.duration,a.zoom),r=a.y>=a.trackY&&a.y<=a.trackY+a.trackHeight;if(a.x>=t&&a.x<=t+Ft&&r||a.x>=t+i-Ft&&a.x<=t+i&&r)return"ew-resize";if(a.x>t+Ft&&a.x<t+i-Ft&&r)return"pointer"}return"default"}class Pi{constructor(e,t,i){p(this,"clip");p(this,"onUpdate");p(this,"onSplit");this.clip=Rr({...e,endTime:F.calculateEndTime(e.startTime,e.duration)},{isDragging:e.isDragging,isResizingLeft:e.isResizingLeft,isResizingRight:e.isResizingRight,isSelected:e.isSelected,isResizing:e.isResizing,zIndex:e.zIndex,opacity:e.opacity}),this.onUpdate=t,this.onSplit=i}getClip(){return{...this.clip}}applyPreviewState(e){this.clip={...this.clip,...e,endTime:F.calculateEndTime(e.startTime,e.duration)}}setSelected(e){this.clip={...this.clip,isSelected:e},this.onUpdate(this.clip)}isPointInResizeHandle(e,t,i,r,n,s){const o=me(this.clip.startTime,i,s),l=Ie(this.clip.duration,i),h=Ft;return t<r||t>r+n?(this.setResizeHandleState(!1,!1),!1):e>=o&&e<=o+h?(this.setResizeHandleState(!0,!1),!0):e>=o+l-h&&e<=o+l?(this.setResizeHandleState(!1,!0),!0):(this.setResizeHandleState(!1,!1),!1)}startDrag(e){this.clip={...this.clip,isDragging:!0,isResizing:!1,isResizingLeft:!1,isResizingRight:!1},this.onUpdate(this.clip)}startResize(e){this.clip={...this.clip,isDragging:!0,isResizing:!0},this.onUpdate(this.clip)}endDrag(){this.clip={...this.clip,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1}}split(e){e>this.clip.startTime+1&&e<this.clip.endTime-1&&this.onSplit(this.clip,e)}setResizeHandleState(e,t){this.clip={...this.clip,isResizingLeft:e,isResizingRight:t}}}function Oi(){return{kind:"idle"}}function Ji(a){return!!a&&a.kind!=="idle"}function Ut(a){return(a==null?void 0:a.kind)==="draggingMove"||(a==null?void 0:a.kind)==="draggingResizeLeft"||(a==null?void 0:a.kind)==="draggingResizeRight"}function Ke(a){return!a||a.kind==="idle"||a.kind==="boxSelecting"?null:a.context}function Wt(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 Gh(a){const e=Wt(a);return e?e==="move"?"grabbing":"ew-resize":null}function vi(a,e){if(e.type==="POINTER_DOWN")return{state:{kind:"pressed",operation:e.operation,context:{clipId:e.clipId,originalClipsState:e.originalClipsState,nonDraggedClips:e.nonDraggedClips,snapCandidateClips:e.snapCandidateClips,pointerStartClientX:e.clientX,pointerStartClientY:e.clientY,pointerStartX:e.localX,pointerStartY:e.localY,dragStartScrollLeft:e.scrollLeft,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:e.localY,crossTrackDragOffsetY:0}},effects:{bindGlobalListeners:!0}};if(e.type==="BOX_SELECT_START")return{state:{kind:"boxSelecting",context:{startClientX:e.clientX,startClientY:e.clientY,startLocalX:e.localX,startLocalY:e.localY,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY,additive:e.additive}},effects:{bindGlobalListeners:!0}};if(a.kind==="idle")return{state:a,effects:{}};if(a.kind==="boxSelecting")return e.type==="BOX_SELECT_MOVE"?{state:{kind:"boxSelecting",context:{...a.context,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY}},effects:{updatePreview:!0}}:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP"||e.type==="CANCEL"||e.type==="VISIBILITY_HIDDEN"||e.type==="WINDOW_BLUR"?{state:Oi(),effects:{unbindGlobalListeners:!0,commit:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP",cleanup:!0}}:{state:a,effects:{}};if(e.type==="POINTER_MOVE"){const i=Fh(a.context,e,Wt(a)||"move");return a.kind==="pressed"?$h(a.context,e.activationThreshold,e.clientX,e.clientY)?{state:Hh(a.operation,i),effects:{updatePreview:!0}}:{state:{...a,context:i},effects:{}}:{state:{...a,context:i},effects:{updatePreview:!0}}}if(e.type==="SCROLL_LEFT_CHANGED")return{state:a,effects:{updatePreview:Ut(a)}};const t=e.type==="POINTER_UP"&&Ut(a);return{state:Oi(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function Hh(a,e){return a==="resize-left"?{kind:"draggingResizeLeft",context:e}:a==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function Fh(a,e,t){const i=t==="move";return{...a,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:i?e.localY:a.pointerStartY,crossTrackDragOffsetY:i?e.localY-a.pointerStartY:0}}function $h(a,e,t,i){const r=t-a.pointerStartClientX,n=i-a.pointerStartClientY;return Math.hypot(r,n)>=Math.max(0,e)}const _e=class _e{constructor(e,t,i,r,n,s,o,l,h,c,d,u,g,f,y,v,C,T,w,b,E,x,O,k,L,B=_e.DEFAULT_DRAG_ACTIVATION_THRESHOLD,z=!1,G=_e.DEFAULT_CLIP_SNAP_THRESHOLD){p(this,"layer");p(this,"trackGroup");p(this,"dragOverlayLayer",null);p(this,"dropPreviewGroup",null);p(this,"dropPreviewClips",[]);p(this,"config");p(this,"theme");p(this,"trackType");p(this,"clips",[]);p(this,"clipGroups",new Map);p(this,"zoom",100);p(this,"scrollLeft",0);p(this,"trackY",0);p(this,"trackHeight",64);p(this,"selectedClip",null);p(this,"hasSelectedClip",!1);p(this,"selectedClipIds",new Set);p(this,"multiDragOriginalPositions",new Map);p(this,"promotedClipParents",new Map);p(this,"interactionState",Oi());p(this,"legacyInteractionSnapshot");p(this,"isVisualUpdate",!1);p(this,"onClipUpdate");p(this,"onClipAdd");p(this,"onClipRemove");p(this,"onClipSplit");p(this,"onClipSelect");p(this,"onTimeJump");p(this,"onClipOverlap");p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"hasLockedGlobalCursor",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"onHorizontalDragAutoScroll");p(this,"onClipCrossTrackPreview");p(this,"onClipCrossTrack");p(this,"onClearDropPreview");p(this,"onClearSelection");p(this,"onSnapGuideChange");p(this,"onClipToggleSelection");p(this,"onSetSingleSelection");p(this,"getMultiDragClipIds");p(this,"onMultiDragMove");p(this,"onMultiDragInteractionEnd");p(this,"resolveSnapTargetClips");p(this,"dragActivationThreshold");p(this,"enableClipSnap");p(this,"clipSnapThreshold");p(this,"handleGlobalPointerMove",e=>{Ji(this.interactionState)&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});p(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});p(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const e=this.resolveInteractionState();if(!Ut(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=Ke(e);if(!i||!r){this.stopEdgeAutoScroll();return}const n=i.getBoundingClientRect(),s=r.lastPointerClientX-n.left,o=this.calculateHorizontalAutoScrollVelocity(s,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=e,this.config=t,this.theme=o,this.trackType=i,this.zoom=r,this.trackY=n,this.trackHeight=s,this.onClipUpdate=l,this.onClipAdd=h,this.onClipRemove=c,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=g,this.onHorizontalDragAutoScroll=f,this.onClipOverlap=y,this.onClipCrossTrackPreview=v,this.onClipCrossTrack=C,this.onClearDropPreview=T,this.onClearSelection=w,this.onSnapGuideChange=b,this.onClipToggleSelection=E,this.onSetSingleSelection=x,this.getMultiDragClipIds=O,this.onMultiDragMove=k,this.onMultiDragInteractionEnd=L,this.dragActivationThreshold=Math.max(0,B),this.enableClipSnap=z,this.clipSnapThreshold=Math.max(0,G),this.trackGroup=se.createGroup(0,n),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}get hasDragMoved(){return this.getLegacyInteractionSnapshot().hasDragMoved}set hasDragMoved(e){this.getLegacyInteractionSnapshot().hasDragMoved=e}get activePointerOperation(){return this.getLegacyInteractionSnapshot().activePointerOperation}set activePointerOperation(e){this.getLegacyInteractionSnapshot().activePointerOperation=e}get originalClipsState(){return this.getLegacyInteractionSnapshot().originalClipsState}set originalClipsState(e){this.getLegacyInteractionSnapshot().originalClipsState=Array.isArray(e)?e:[]}get nonDraggedClips(){return this.getLegacyInteractionSnapshot().nonDraggedClips}set nonDraggedClips(e){this.getLegacyInteractionSnapshot().nonDraggedClips=Array.isArray(e)?e:[]}get snapCandidateClips(){return this.getLegacyInteractionSnapshot().snapCandidateClips}set snapCandidateClips(e){this.getLegacyInteractionSnapshot().snapCandidateClips=Array.isArray(e)?e:[]}get dragStartY(){return this.getLegacyInteractionSnapshot().dragStartY}set dragStartY(e){this.getLegacyInteractionSnapshot().dragStartY=typeof e=="number"?e:0}get dragTargetTrackY(){return this.getLegacyInteractionSnapshot().dragTargetTrackY}set dragTargetTrackY(e){this.getLegacyInteractionSnapshot().dragTargetTrackY=typeof e=="number"?e:0}get crossTrackDragOffsetY(){return this.getLegacyInteractionSnapshot().crossTrackDragOffsetY}set crossTrackDragOffsetY(e){this.getLegacyInteractionSnapshot().crossTrackDragOffsetY=typeof e=="number"?e:0}get crossTrackDragStartX(){return this.getLegacyInteractionSnapshot().crossTrackDragStartX}set crossTrackDragStartX(e){this.getLegacyInteractionSnapshot().crossTrackDragStartX=typeof e=="number"?e:0}get dragStartScrollLeft(){return this.getLegacyInteractionSnapshot().dragStartScrollLeft}set dragStartScrollLeft(e){this.getLegacyInteractionSnapshot().dragStartScrollLeft=typeof e=="number"?e:0}get dragGestureStartClientX(){return this.getLegacyInteractionSnapshot().dragGestureStartClientX}set dragGestureStartClientX(e){this.getLegacyInteractionSnapshot().dragGestureStartClientX=typeof e=="number"?e:null}get dragGestureStartClientY(){return this.getLegacyInteractionSnapshot().dragGestureStartClientY}set dragGestureStartClientY(e){this.getLegacyInteractionSnapshot().dragGestureStartClientY=typeof e=="number"?e:null}get lastDragClientX(){return this.getLegacyInteractionSnapshot().lastDragClientX}set lastDragClientX(e){this.getLegacyInteractionSnapshot().lastDragClientX=typeof e=="number"?e:null}get lastDragClientY(){return this.getLegacyInteractionSnapshot().lastDragClientY}set lastDragClientY(e){this.getLegacyInteractionSnapshot().lastDragClientY=typeof e=="number"?e:null}initClips(){this.clips=this.config.clips.map(e=>{const t=new Pi(e,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));return this.createClipGroup(e),t})}getLegacyInteractionSnapshot(){return this.legacyInteractionSnapshot||(this.legacyInteractionSnapshot={hasDragMoved:!1,activePointerOperation:null,originalClipsState:[],nonDraggedClips:[],snapCandidateClips:[],dragStartY:0,dragTargetTrackY:0,crossTrackDragOffsetY:0,crossTrackDragStartX:0,dragStartScrollLeft:0,dragGestureStartClientX:null,dragGestureStartClientY:null,lastDragClientX:null,lastDragClientY:null}),this.legacyInteractionSnapshot}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const e=se.createGroup(0,0);return e.name("clip-drop-preview"),e.visible(!1),e.listening(!1),this.trackGroup.add(e),this.dropPreviewGroup=e,e}createDropPreviewRect(e){const t=this.trackType==="text"?"rgba(96, 76, 51, 0.28)":this.trackType==="video"?li.videoFill:li.audioFill,i=this.trackType==="text"?"#C9CBD4":this.trackType==="video"?li.videoStroke:li.audioStroke,r=me(e.startTime,this.zoom,this.scrollLeft),n=Ie(e.duration,this.zoom),s=se.createRect(r,2,Math.max(n,1),Math.max(this.trackHeight-4,1),t,i,1);return s.dash([6,4]),s.cornerRadius(4),s.listening(!1),s.visible(r+n>0&&r<this.layer.width()),s}showDropPreview(e){const t=this.ensureDropPreviewGroup(),i=Array.isArray(e)?e:[e];this.dropPreviewClips=i.map(n=>({...n})),t.destroyChildren();let r=!1;for(const n of this.dropPreviewClips){const s=this.createDropPreviewRect(n);r=r||s.visible(),t.add(s)}t.x(0),t.y(0),t.visible(r),t.moveToTop()}hideDropPreview(){var e;this.dropPreviewClips=[],(e=this.dropPreviewGroup)==null||e.visible(!1)}initEventListeners(){const e=this.layer.getStage();e&&e.on("mouseup",()=>{this.handleClipMouseUp()})}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=ni({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(si({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}),this.hasBoundGlobalPointerListenersForDrag=!1)}handleTrackBackgroundClick(e){const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=Math.max(0,F.pixelsToTime(n-ue+this.scrollLeft,this.zoom));this.onTimeJump(s),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(e){}getClipDisplayLabel(e){return(e.type==="text"||e.type==="audio"&&e.ttsSourceTextClipId)&&e.textContent||e.name}getClipAudioBadgeText(e){if(!(e.type!=="audio"||!e.ttsSourceTextClipId))return e.name}isSourceBoundClip(e){return e.type!=="text"}updateClipSelection(e,t){const i=this.clips.find(r=>r.getClip().id===e);i&&(this.isVisualUpdate=!0,i.setSelected(t),this.isVisualUpdate=!1,t?this.selectedClipIds.add(e):this.selectedClipIds.delete(e),this.syncSelectionState(e),this.updateClipGroup(i.getClip()),this.render(!1),this.layer.batchDraw())}createClipGroup(e){const t=me(e.startTime,this.zoom,this.scrollLeft),i=Ie(e.duration,this.zoom),r=2,n=this.trackHeight-4,s=se.createClipGroup(t,r,i,n,this.getClipDisplayLabel(e),e.duration,this.theme,!1,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,!1,this.getClipAudioBadgeText(e));s.name(`clip-${e.id}`),s.on("click",o=>{this.handleClipClick(e.id,o.evt)}),s.on("mousedown",o=>{this.handleClipMouseDown(e.id,o.evt)}),s.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),s.on("mouseleave",()=>{this.handleClipMouseLeave()}),s.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(s),this.clipGroups.set(e.id,s)}handleClipClick(e,t){if(t.button!==0)return;this.clips.find(r=>r.getClip().id===e)&&this.render()}handleClipMouseDown(e,t){var c;if(t.button!==0)return;if(t.ctrlKey||t.metaKey){this.onClipToggleSelection&&this.onClipToggleSelection(e);return}const i=(c=this.getMultiDragClipIds)==null?void 0:c.call(this,e),r=i!=null&&i.length>1;if(!r)this.selectedClipIds.clear(),this.selectedClipIds.add(e),this.onSetSingleSelection&&this.onSetSingleSelection(e);else{this.selectedClipIds.clear();for(const d of i)this.selectedClipIds.add(d)}this.clips.sort((d,u)=>d.getClip().startTime-u.getClip().startTime);const n=this.clips.map(d=>({...d.getClip()})),s=this.clips.filter(d=>d.getClip().id!==e).map(d=>({...d.getClip()})),l=(this.resolveSnapTargetClips?this.resolveSnapTargetClips():this.clips.map(d=>d.getClip())).filter(d=>d.id!==e).map(d=>({...d})),h=this.clips.find(d=>d.getClip().id===e);if(h){r||(this.applySelectionVisual(new Set([e])),this.onClipSelect(h.getClip())),this.selectedClip=h;const d=this.layer.getStage();if(!d)return;const u=d.container();if(!u)return;const g=u.getBoundingClientRect(),f=t.clientX-g.left,y=t.clientY-g.top;if(r){this.multiDragOriginalPositions.clear();for(const C of this.selectedClipIds){const T=this.clips.find(w=>w.getClip().id===C);if(T){const w=T.getClip();this.multiDragOriginalPositions.set(C,{startTime:w.startTime,duration:w.duration})}}}let v;h.isPointInResizeHandle(f,y,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(v=h.getClip().isResizingLeft?"resize-left":"resize-right",h.startResize({x:f,y})):(v="move",h.startDrag({x:f,y}),this.trackGroup.moveToTop()),this.applyInteractionTransition(vi(this.interactionState,{type:"POINTER_DOWN",operation:v,clipId:e,originalClipsState:n,nonDraggedClips:s,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:f,localY:y,scrollLeft:this.scrollLeft})),this.render()}}handleClipMouseMove(e){this.updateHoverCursor(e.clientX,e.clientY)}handleTrackBackgroundMouseMove(){if(this.isDragSessionActive())return;const e=this.layer.getStage(),t=e==null?void 0:e.container();t&&(t.style.cursor="default")}handleClipMouseUp(){this.finishPointerInteraction("POINTER_UP")}finishPointerInteraction(e){const t=this.interactionState,i=this.resolveDraggedClipForInteraction(t);try{if(!i)return;const r=i.getClip();if(!r.isDragging)return;i.endDrag();const n=vi(t,{type:e});this.interactionState=n.state,n.effects.commit&&this.handleClipMoveEnd(r,t),this.layer.batchDraw()}finally{this.interactionState=Oi(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}resolveDraggedClipForInteraction(e=this.interactionState){const t=Ke(e);if(t!=null&&t.clipId){const r=this.clips.find(n=>n.getClip().id===t.clipId)??null;if(r)return r}const i=this.clips.find(r=>r.getClip().isDragging)??null;return i||this.selectedClip}applyInteractionTransition(e){var i,r;this.interactionState=e.state,this.syncLegacyInteractionMirror(e.state),e.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const t=Gh(e.state);t&&this.lockPointerCursor(t),e.effects.cleanup&&(this.releasePointerCursor(),this.hideDropPreview(),(i=this.onClearDropPreview)==null||i.call(this),this.updateSnapGuideLine(null),this.stopEdgeAutoScroll(),this.clearClipDragOverlay(),this.multiDragOriginalPositions.size>0&&((r=this.onMultiDragInteractionEnd)==null||r.call(this),this.multiDragOriginalPositions.clear())),e.effects.unbindGlobalListeners&&this.unbindGlobalPointerListenersForDrag()}resolveInteractionState(e=this.interactionState){var s;if(Ji(e))return e;const t=this.getLegacyInteractionSnapshot(),i=(s=this.resolveDraggedClipForInteraction(e))==null?void 0:s.getClip();if(!(i!=null&&i.id)||!i.isDragging)return e;const r=t.activePointerOperation||(i.isResizingLeft?"resize-left":i.isResizingRight?"resize-right":"move"),n={clipId:i.id,originalClipsState:t.originalClipsState,nonDraggedClips:t.nonDraggedClips,snapCandidateClips:t.snapCandidateClips,pointerStartClientX:t.dragGestureStartClientX??0,pointerStartClientY:t.dragGestureStartClientY??0,pointerStartX:t.crossTrackDragStartX,pointerStartY:t.dragStartY,dragStartScrollLeft:t.dragStartScrollLeft||this.scrollLeft,lastPointerClientX:t.lastDragClientX??0,lastPointerClientY:t.lastDragClientY??0,dragTargetTrackY:t.dragTargetTrackY,crossTrackDragOffsetY:t.crossTrackDragOffsetY};return t.hasDragMoved?r==="resize-left"?{kind:"draggingResizeLeft",context:n}:r==="resize-right"?{kind:"draggingResizeRight",context:n}:{kind:"draggingMove",context:n}:{kind:"pressed",operation:r,context:n}}syncLegacyInteractionMirror(e=this.interactionState){const t=this.getLegacyInteractionSnapshot(),i=Ke(e);t.hasDragMoved=Ut(e),t.activePointerOperation=Wt(e),t.originalClipsState=(i==null?void 0:i.originalClipsState)??[],t.nonDraggedClips=(i==null?void 0:i.nonDraggedClips)??[],t.snapCandidateClips=(i==null?void 0:i.snapCandidateClips)??[],t.dragStartY=(i==null?void 0:i.pointerStartY)??0,t.dragTargetTrackY=(i==null?void 0:i.dragTargetTrackY)??0,t.crossTrackDragOffsetY=(i==null?void 0:i.crossTrackDragOffsetY)??0,t.crossTrackDragStartX=(i==null?void 0:i.pointerStartX)??0,t.dragStartScrollLeft=(i==null?void 0:i.dragStartScrollLeft)??0,t.dragGestureStartClientX=(i==null?void 0:i.pointerStartClientX)??null,t.dragGestureStartClientY=(i==null?void 0:i.pointerStartClientY)??null,t.lastDragClientX=(i==null?void 0:i.lastPointerClientX)??null,t.lastDragClientY=(i==null?void 0:i.lastPointerClientY)??null}handleClipMoveEnd(e,t){var v,C,T;const i=this.resolveInteractionState(t),r=this.getLegacyInteractionSnapshot(),n=Ke(i)||{clipId:e.id,originalClipsState:r.originalClipsState.length>0?r.originalClipsState:[e],nonDraggedClips:r.nonDraggedClips,snapCandidateClips:r.snapCandidateClips,dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:r.dragTargetTrackY,crossTrackDragOffsetY:r.crossTrackDragOffsetY},o=(Wt(i)||r.activePointerOperation||"move")==="move",l=o&&this.multiDragOriginalPositions.size>0,h=(v=this.clipGroups)==null?void 0:v.get(e.id);if(h&&h.y(2),l){const w=this.multiDragOriginalPositions.get(e.id),b=w?e.startTime-w.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:e.id,deltaTime:b,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!0})){for(const B of this.selectedClipIds){const z=(C=this.clipGroups)==null?void 0:C.get(B);z==null||z.y(2)}this.multiDragOriginalPositions.clear();return}const E=[],x=[];for(const[L,B]of this.multiDragOriginalPositions){const z=this.clips.find(D=>D.getClip().id===L);if(!z)continue;const G=Math.max(0,B.startTime+b),Y={...z.getClip(),startTime:G,endTime:G+B.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(L)};E.push(Y);const V=n.originalClipsState.find(D=>D.id===L);V&&x.push(V);const H=(T=this.clipGroups)==null?void 0:T.get(L);H&&H.y(2)}const O=[];for(const L of this.clips){const B=L.getClip(),z=E.find(G=>G.id===B.id);z?O.push(z):O.push({...B,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}O.sort((L,B)=>L.startTime-B.startTime),this.isVisualUpdate=!0;for(const L of O)this.clips.find(z=>z.getClip().id===L.id)&&this.handleClipUpdate(L);this.isVisualUpdate=!1;const k=x.map(L=>{const B=E.find(z=>z.id===L.id);return B&&(L.startTime!==B.startTime||L.duration!==B.duration)?{clipId:L.id,previousState:L,newState:B}:null}).filter(L=>L!==null);k.length>0&&this.onClipUpdate(e,x.find(L=>L.id===e.id),k),this.multiDragOriginalPositions.clear();return}if(o&&this.onClipCrossTrack&&this.config.id){const w=n.originalClipsState.find(E=>E.id===e.id)??null;if(this.onClipCrossTrack(e,w,n.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}const c=o?[...n.nonDraggedClips]:[];let d=!1;const u=e.startTime+e.duration;for(const w of c){const b=w.startTime+w.duration;if(e.startTime<b&&u>w.startTime){d=!0;break}}if(o&&d&&this.onClipOverlap&&this.config.id){this.onClipOverlap(e,this.config.id);return}const g=[...n.nonDraggedClips];let f=g.findIndex(w=>w.startTime>=e.startTime);f===-1&&(f=g.length),n.nonDraggedClips.forEach(w=>{w.isSelected=!1});const y={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};g.splice(f,0,y),this.updateAllClips(g),this.buildAndSendUpdates(y,g,n.originalClipsState)}updateAllClips(e){const t=this.clips??[];this.isVisualUpdate=!0,e.forEach(i=>{t.find(n=>n.getClip().id===i.id)&&this.handleClipUpdate(i)}),this.isVisualUpdate=!1,t.sort((i,r)=>i.getClip().startTime-r.getClip().startTime),this.clips=t}buildAndSendUpdates(e,t,i){const r=i.map(n=>{const s=t.find(o=>o.id===n.id);return s&&(n.startTime!==s.startTime||n.duration!==s.duration||n.opacity!==s.opacity)?{clipId:n.id,previousState:n,newState:s}:null}).filter(n=>n!==null);r.length>0&&this.onClipUpdate(e,i.find(n=>n.id===e.id),r)}updateHoverCursor(e,t){const i=this.layer.getStage();if(!i)return;const r=i.container();if(!r||this.isDragSessionActive())return;const n=r.getBoundingClientRect(),s=e-n.left,o=t-n.top;r.style.cursor=Bh({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:s,y:o})}isDragSessionActive(){return Ji(this.resolveInteractionState())}handleDragMove(e){const t=this.resolveInteractionState(),i=this.layer.getStage(),r=i==null?void 0:i.container();if(!r)return;const n=r.getBoundingClientRect(),s=vi(t,{type:"POINTER_MOVE",clientX:e.clientX,clientY:e.clientY,localY:e.clientY-n.top,activationThreshold:this.dragActivationThreshold});this.interactionState=s.state,this.syncLegacyInteractionMirror(s.state),s.effects.updatePreview&&this.updateDraggedClipFromPointer(e.clientX,e.clientY,!0)}handleClipMouseLeave(){if(this.isDragSessionActive())return;const e=this.layer.getStage();e&&e.container()&&(e.container().style.cursor="default")}lockPointerCursor(e){const t=typeof this.layer.getStage=="function"?this.layer.getStage():null,i=t==null?void 0:t.container();i&&(i.style.cursor=e),typeof document<"u"&&document.body&&(document.body.style.cursor=e,this.hasLockedGlobalCursor=!0)}releasePointerCursor(){const e=typeof this.layer.getStage=="function"?this.layer.getStage():null,t=e==null?void 0:e.container();t&&(t.style.cursor="default"),this.hasLockedGlobalCursor&&typeof document<"u"&&document.body&&(document.body.style.cursor="",this.hasLockedGlobalCursor=!1)}updateClipGroup(e,t=!1){const i=this.clipGroups.get(e.id);if(i){const r=Ie(e.duration,this.zoom);this.updateClipViewportState(e);const n=e.isSelected;(e.isDragging||n)&&i.moveToTop(),i.opacity(e.opacity),se.updateClipGroup(i,r,this.trackHeight-4,this.getClipDisplayLabel(e),e.duration,this.theme,n,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,t,this.getClipAudioBadgeText(e))}}handleClipUpdate(e){const t=this.clips.findIndex(i=>i.getClip().id===e.id);if(t!==-1){const i=this.clips[t].getClip(),r={...e,isSelected:this.isVisualUpdate?e.isSelected:this.selectedClipIds.has(e.id)};this.clips[t]=new Pi(r,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this)),this.syncSelectionState(e.id),this.updateClipGroup(r);const n=this.clipGroups.get(e.id);n&&n.opacity(r.opacity),this.isVisualUpdate||this.onClipUpdate(r,i),this.layer.batchDraw()}}handleClipSplit(e,t){const i=t-e.startTime,r=e.duration-i,n=e.startTimeAtSource+i,s={...e,duration:i,endTime:t,endTimeAtSource:n},o={...e,id:`${e.id}_split_${Date.now()}`,startTime:t,duration:r,endTime:F.calculateEndTime(t,r),startTimeAtSource:n,endTimeAtSource:e.endTimeAtSource};this.removeClip(e.id),this.addClip(s),this.addClip(o),this.onClipSplit(s,o),this.layer.batchDraw()}addClip(e){if(e.type!==this.trackType){M.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new Pi(t,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));this.clips.push(i),this.createClipGroup(t),this.onClipAdd(t),this.layer.batchDraw()}removeClip(e){const t=this.clips.findIndex(i=>i.getClip().id===e);if(t!==-1){this.clips.splice(t,1),this.selectedClipIds.delete(e),this.syncSelectionState();const i=this.clipGroups.get(e);i&&(this.getPromotedClipParents().delete(e),i.remove(),this.clipGroups.delete(e)),this.onClipRemove(e),this.hideDropPreview(),this.render(!1),this.layer.batchDraw()}}updateClip(e,t){const i=this.clips.find(r=>r.getClip().id===e);if(i){const n={...i.getClip(),...t};(t.startTime!==void 0||t.duration!==void 0)&&(n.endTime=n.startTime+n.duration),this.handleClipUpdate(n)}}setZoom(e){this.zoom=e,this.clips.forEach(t=>{this.updateClipGroup(t.getClip())}),this.layer.batchDraw()}setCurrentTime(e){this.layer.batchDraw()}setScrollLeft(e){this.scrollLeft=e,this.clips.forEach(n=>{const s=n.getClip();this.updateClipViewportState(s)});const t=this.resolveInteractionState(),i=Ke(t),r=vi(t,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=r.state,this.syncLegacyInteractionMirror(r.state),r.effects.updatePreview&&i&&this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1),this.layer.batchDraw()}updateClipVisibility(e){const t=this.clipGroups.get(e.id);if(t){const i=Oh({startTime:e.startTime,duration:e.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width());t.visible(i)}}updateClipViewportState(e){const t=this.clipGroups.get(e.id);t&&(t.x(me(e.startTime,this.zoom,this.scrollLeft)),this.updateClipVisibility(e))}setTrackY(e){const t=e-this.trackY;this.trackY=e,this.trackGroup.y(e),this.getPromotedClipParents().forEach((i,r)=>{i.baseY=e;const n=this.clipGroups.get(r);n&&n.y(n.y()+t)})}setTrackStackOrder(e){this.trackGroup.zIndex(e)}setDragOverlayLayer(e){this.dragOverlayLayer=e}setClipsDragOverlayActive(e,t){e.forEach(i=>{this.setClipDragOverlayActive(i,t)})}clearClipDragOverlay(){Array.from(this.getPromotedClipParents().keys()).forEach(e=>{this.setClipDragOverlayActive(e,!1)})}getTrackType(){return this.trackType}render(e=!0){const t=this.getTrackBackgroundFill();if(this.trackGroup.children.length===0){const i=se.createRect(0,0,this.layer.width(),this.trackHeight,t,this.theme.trackBorder,1);i.name("track-background"),i.on("click",r=>{this.handleTrackBackgroundClick(r.evt)}),i.on("mousedown",r=>{this.handleTrackBackgroundMouseDown(r.evt)}),i.on("mousemove",()=>{this.handleTrackBackgroundMouseMove()}),i.on("mouseleave",()=>{this.handleClipMouseLeave()}),this.trackGroup.add(i)}else{const i=this.trackGroup.findOne(".track-background");i&&(i.width(this.layer.width()),typeof i.height=="function"&&i.height(this.trackHeight),i.fill(t),i.stroke(this.theme.trackBorder),i.listening()||i.listening(!0))}e&&this.layer.batchDraw()}getTrackBackgroundFill(){return this.hasSelectedClip?this.theme.trackSelectedBackground||Q.trackSelectedBackground:this.theme.trackBackground}getClips(){return this.clips.map(e=>e.getClip())}getPrimarySelectedClip(){return this.selectedClip?this.selectedClip.getClip():null}clearSelection(){this.setSelection([])}setSelection(e,t){const i=new Set(e);this.applySelectionVisual(i),this.selectedClipIds=i,this.syncSelectionState(t??e[0]??void 0),this.render()}applySelectionVisual(e){this.isVisualUpdate=!0;try{this.clips.forEach(t=>{const i=t.getClip().id,r=e.has(i);t.setSelected(r)})}finally{this.isVisualUpdate=!1}}syncSelectionState(e){var s;const t=this.clips.filter(o=>this.selectedClipIds.has(o.getClip().id)),r=t.length>0?t:this.clips.filter(o=>o.getClip().isSelected);if(this.selectedClipIds=new Set(r.map(o=>o.getClip().id)),this.hasSelectedClip=r.length>0,!this.hasSelectedClip){this.selectedClip=null;return}const n=e??((s=this.selectedClip)==null?void 0:s.getClip().id)??null;this.selectedClip=r.find(o=>o.getClip().id===n)??r[r.length-1]??null}splitSelectedClip(e){const t=this.clips.find(i=>{const r=i.getClip();return e>=r.startTime&&e<r.endTime});t&&t.getClip().type!=="text"&&t.split(e)}removeClipGaps(){M.debugLazy("Track",()=>"Removing clip gaps");const e=this.clips.map(i=>i.getClip()).sort((i,r)=>i.startTime-r.startTime);if(e.length===0)return;let t=0;for(let i=0;i<e.length;i++){const r=e[i];if(t-r.startTime<0||i===0){const s=t,o=s+r.duration;this.handleClipUpdate({...r,startTime:s,endTime:o}),t=o}else t=r.startTime+r.duration}}getTrackGroup(){return this.trackGroup}getId(){return this.config.id||"default"}updateClipPosition(e,t,i,r=0){var l;const n=this.clips.find(h=>h.getClip().id===e);if(!n)return;const s=n.getClip(),o=this.clipGroups.get(e);if(i)this.setClipDragOverlayActive(e,!1),this.updateClipPositionFinal(e,t);else if(o){const h=me(t,this.zoom,this.scrollLeft);o.x(h),o.y(this.resolveClipRenderY(e,r)),o.moveToTop(),se.updateClipGroup(o,Ie(s.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(s),s.duration,this.theme,!0,s.thumbnails,s.src,s.type,!!s.separatedAudioClipId,!0,this.getClipAudioBadgeText(s)),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw()}}updateClipPositionFinal(e,t){const i=this.clips.find(s=>s.getClip().id===e);if(!i)return;const r=i.getClip(),n=this.clipGroups.get(e);this.setClipDragOverlayActive(e,!1),n==null||n.y(2),this.isVisualUpdate=!0,this.handleClipUpdate({...r,startTime:t,endTime:t+r.duration}),this.isVisualUpdate=!1}setTrackHeight(e){var t,i;if(this.trackHeight=e,(t=this.dropPreviewGroup)!=null&&t.visible()&&Array.isArray(this.dropPreviewClips)&&this.dropPreviewClips.length>0)this.showDropPreview(this.dropPreviewClips);else if((i=this.dropPreviewGroup)!=null&&i.visible()){const r=this.dropPreviewGroup.children[0];r==null||r.height(Math.max(this.trackHeight-4,1))}this.clips.forEach(r=>{this.updateClipGroup(r.getClip(),!0)}),this.render(!1)}showClipDropPreview(e){this.showDropPreview(e),this.layer.batchDraw()}showClipDropPreviews(e){this.showDropPreview(e),this.layer.batchDraw()}clearClipDropPreview(){this.hideDropPreview(),this.layer.batchDraw()}getRole(){return this.config.role||"normal"}setClipSnapEnabled(e){this.enableClipSnap=e,e||this.updateSnapGuideLine(null);const t=this.resolveInteractionState(),i=Ke(t);if(Ut(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var C,T,w,b,E;const r=this.resolveInteractionState(),n=Ke(r),s=Wt(r),o=this.layer.getStage(),l=this.resolveDraggedClipForInteraction(r);if(!o||!l||!n||!s)return;const h=o.container();if(!h)return;const c=h.getBoundingClientRect(),d=e-c.left,u=t-c.top,g=s==="move",f=g&&this.multiDragOriginalPositions.size>0;g&&M.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:u,currentTrackId:this.config.id,offsetY:n.crossTrackDragOffsetY}));const y=l.getClip(),v=(C=this.clipGroups)==null?void 0:C.get(y.id);if(v){const x=g&&n.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(y.id,x);const O=n.originalClipsState.find(H=>H.id===y.id);if(!O)return;const k=this.buildPreviewClip(y,O,d,n,s);if(!k){this.hideDropPreview(),(T=this.onClearDropPreview)==null||T.call(this),this.updateSnapGuideLine(null);return}const L=k.clip,B=L.startTime-O.startTime,z=this.applyPreviewClipState(l,L),G=me(L.startTime,this.zoom,this.scrollLeft),Y=Ie(L.duration,this.zoom);v.x(G),v.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)),v.visible(G+Y>0&&G<this.layer.width()),z&&(this.updateClipGroup(L),v.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)));let V=!1;if(f){this.onMultiDragMove&&this.config.id&&(V=this.onMultiDragMove({draggedClipId:y.id,deltaTime:B,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[H,D]of this.multiDragOriginalPositions){if(H===y.id)continue;const J=this.clips.find(ne=>ne.getClip().id===H);if(!J)continue;const $=Math.max(0,D.startTime+B),j=(w=this.clipGroups)==null?void 0:w.get(H);if(j){const ne=me($,this.zoom,this.scrollLeft);j.x(ne),j.y(this.resolveClipRenderY(H,n.crossTrackDragOffsetY)),j.visible(ne+Ie(D.duration,this.zoom)>0&&ne<this.layer.width());const W=J.getClip();se.updateClipGroup(j,Ie(W.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(W),W.duration,this.theme,!0,W.thumbnails,W.src,W.type,!!W.separatedAudioClipId,!0,this.getClipAudioBadgeText(W))}}}g&&this.onClipCrossTrackPreview&&this.config.id&&!V?this.onClipCrossTrackPreview(L,n.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():V?this.hideDropPreview():this.showDropPreview(L),this.updateSnapGuideLine(k.guideTime)}else this.hideDropPreview(),(b=this.onClearDropPreview)==null||b.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(d,c.width),this.layer.batchDraw(),(E=this.dragOverlayLayer)==null||E.batchDraw()}buildPreviewClip(e,t,i,r,n){const s=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=F.pixelsToTime(s,this.zoom);let l;return n==="resize-left"||e.isResizingLeft?l=this.buildResizeLeftPreviewClip(e,t,o):n==="resize-right"||e.isResizingRight?l=this.buildResizeRightPreviewClip(e,t,o):l={...e,startTime:Math.max(0,t.startTime+o),endTime:Math.max(0,t.startTime+o)+e.duration},this.constrainResizePreviewToTrackBounds(this.applyClipSnap(l,t,r.snapCandidateClips),t,r.nonDraggedClips)}constrainResizePreviewToTrackBounds(e,t,i){if(e.clip.isResizingLeft){const r=this.getResizeLeftBoundaryStart(t,i);if(e.clip.startTime>=r)return e;const n=e.clip.endTime,s=n-r,o=this.isSourceBoundClip(t)?{startTimeAtSource:t.endTimeAtSource-s,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:s,sourceDuration:s};return{clip:{...e.clip,startTime:r,duration:s,endTime:n,...o},guideTime:e.guideTime===r?e.guideTime:null}}if(e.clip.isResizingRight){const r=this.getResizeRightBoundaryEnd(t,i);if(e.clip.startTime+e.clip.duration<=r)return e;const s=r-e.clip.startTime,o=this.isSourceBoundClip(t)?{endTimeAtSource:t.startTimeAtSource+s}:{startTimeAtSource:0,endTimeAtSource:s,sourceDuration:s};return{clip:{...e.clip,duration:s,endTime:r,...o},guideTime:e.guideTime===r?e.guideTime:null}}return e}getResizeLeftBoundaryStart(e,t){let i=0;for(const r of t){if(r.startTime>=e.startTime)continue;const n=r.startTime+r.duration;i=Math.max(i,n)}return i}getResizeRightBoundaryEnd(e,t){let i=Number.POSITIVE_INFINITY;for(const r of t)r.startTime<e.endTime||(i=Math.min(i,r.startTime));return Number.isFinite(i)?i:Number.POSITIVE_INFINITY}buildResizeLeftPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const g=F.calculateEndTime(t.startTime,t.duration);let f=Math.max(0,t.startTime+i),y=g-f;return y<1e3&&(y=1e3,f=g-y),{...e,startTime:f,duration:y,endTime:f+y,startTimeAtSource:0,endTimeAtSource:y,sourceDuration:y}}const n=Math.max(0,t.startTime+i)-t.startTime,o=Math.max(0,t.startTimeAtSource+i)-t.startTimeAtSource,l=Math.abs(n)<Math.abs(o)?n:o,h=F.calculateEndTime(t.startTime,t.duration);let c=t.startTime+l,d=t.duration-l,u;return d<1e3?(d=1e3,c=h-d,u=t.endTimeAtSource-d):u=t.startTimeAtSource+l,{...e,startTime:c,duration:d,endTime:c+d,startTimeAtSource:u,endTimeAtSource:t.endTimeAtSource}}buildResizeRightPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const o=Math.max(1e3,t.duration+i);return{...e,startTime:t.startTime,duration:o,endTime:t.startTime+o,startTimeAtSource:0,endTimeAtSource:o,sourceDuration:o}}let r=Math.max(1e3,t.duration+i);const n=t.startTimeAtSource,s=Math.min(t.sourceDuration,n+r);return r=s-n,{...e,startTime:t.startTime,duration:r,endTime:t.startTime+r,startTimeAtSource:n,endTimeAtSource:s}}applyClipSnap(e,t,i){if(!this.enableClipSnap||i.length===0)return{clip:e,guideTime:null};const r=i.flatMap(h=>[h.startTime,h.startTime+h.duration]);if(r.length===0)return{clip:e,guideTime:null};const n=F.pixelsToTime(this.clipSnapThreshold,this.zoom),s=e.startTime+e.duration,o=[];if(e.isResizingLeft)for(const h of r){const c=s-h,d=t.endTimeAtSource-c,u=Math.abs(h-e.startTime);u>n||c<1e3||this.isSourceBoundClip(t)&&d<0||o.push({clip:{...e,startTime:h,duration:c,endTime:s,...this.isSourceBoundClip(t)?{startTimeAtSource:d,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:c,sourceDuration:c}},guideTime:h,distance:u})}else if(e.isResizingRight)for(const h of r){const c=h-e.startTime,d=t.startTimeAtSource+c,u=Math.abs(h-s);u>n||c<1e3||this.isSourceBoundClip(t)&&d>t.sourceDuration||o.push({clip:{...e,duration:c,endTime:e.startTime+c,...this.isSourceBoundClip(t)?{endTimeAtSource:d}:{startTimeAtSource:0,endTimeAtSource:c,sourceDuration:c}},guideTime:h,distance:u})}else for(const h of r){const c=Math.abs(h-e.startTime);c<=n&&h>=0&&o.push({clip:{...e,startTime:h,endTime:h+e.duration},guideTime:h,distance:c});const d=h-e.duration,u=Math.abs(h-s);u<=n&&d>=0&&o.push({clip:{...e,startTime:d,endTime:d+e.duration},guideTime:h,distance:u})}if(o.length===0)return{clip:e,guideTime:null};o.sort((h,c)=>h.distance-c.distance);const l=o[0];return{clip:l.clip,guideTime:l.guideTime}}applyPreviewClipState(e,t){return e&&typeof e.applyPreviewState=="function"?(e.applyPreviewState(t),!0):(this.isVisualUpdate=!0,this.handleClipUpdate(t),this.isVisualUpdate=!1,!1)}setClipDragOverlayActive(e,t){var o,l;const i=this.getPromotedClipParents(),r=this.clipGroups.get(e);if(!r){i.delete(e);return}if(!t){const h=i.get(e);if(!h)return;r.remove(),h.parent.add(r);const c=(o=this.clips.find(d=>d.getClip().id===e))==null?void 0:o.getClip();c&&r.x(me(c.startTime,this.zoom,this.scrollLeft)),r.y(2),i.delete(e),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw();return}if(i.has(e)||!this.dragOverlayLayer)return;const n=r.getParent();if(!n)return;const s=r.getAbsolutePosition();i.set(e,{parent:n,baseY:this.trackY}),r.remove(),this.dragOverlayLayer.add(r),r.position(s),r.moveToTop(),this.layer.batchDraw(),this.dragOverlayLayer.batchDraw()}resolveClipRenderY(e,t){const i=this.getPromotedClipParents().get(e);return((i==null?void 0:i.baseY)??0)+2+t}getPromotedClipParents(){return this.promotedClipParents instanceof Map||(this.promotedClipParents=new Map),this.promotedClipParents}updateSnapGuideLine(e){var t;(t=this.onSnapGuideChange)==null||t.call(this,this.enableClipSnap?e:null)}updateEdgeAutoScrollState(e,t){if(this.calculateHorizontalAutoScrollVelocity(e,t)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(_e.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=_e.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const n=(i-e)/i;return-Math.max(1,Math.round(n*r))}if(e>t-i){const n=(e-(t-i))/i;return Math.max(1,Math.round(n*r))}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)}};p(_e,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),p(_e,"DEFAULT_CLIP_SNAP_THRESHOLD",8),p(_e,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(_e,"AUTO_SCROLL_MAX_SPEED",18);let Bi=_e;class Nh{constructor(e,t,i,r,n,s){p(this,"layer");p(this,"playheadGroup");p(this,"playheadLine");p(this,"playheadTriangle");p(this,"theme");p(this,"currentTime",0);p(this,"zoom",100);p(this,"scrollLeft",0);p(this,"onTimeChange");p(this,"isDragging",!1);this.layer=e,this.currentTime=t,this.zoom=i,this.theme=n,this.onTimeChange=s,this.playheadGroup=se.createGroup(),this.layer.add(this.playheadGroup),this.playheadLine=se.createLine([0,0,0,r],this.theme.playhead,1),this.playheadGroup.add(this.playheadLine),this.playheadTriangle=new q.RegularPolygon({x:0,y:5,sides:3,radius:10,fill:this.theme.playhead,rotation:180}),this.playheadGroup.add(this.playheadTriangle),this.initEventListeners(),this.render()}initEventListeners(){var e,t,i;this.playheadGroup.on("mousedown",()=>{this.isDragging=!0}),(e=this.layer.getStage())==null||e.on("mousemove",r=>{this.isDragging&&this.handleMouseMove(r.evt)}),(t=this.layer.getStage())==null||t.on("mouseup",()=>{this.isDragging=!1}),(i=this.layer.getStage())==null||i.on("mouseleave",()=>{this.isDragging=!1})}handleMouseMove(e){if(!this.isDragging)return;const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=F.pixelsToTime(n-ue+this.scrollLeft,this.zoom);this.setTime(s)}setTime(e){this.currentTime=Math.max(0,e),this.onTimeChange(this.currentTime),this.render()}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=e,this.render()}setHeight(e){this.playheadLine.points([0,0,0,e]),this.render()}render(){const e=F.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+ue;this.playheadGroup.x(e),this.playheadGroup.visible(e>=0&&e<=this.layer.width()),this.layer.batchDraw()}getTime(){return this.currentTime}getPlayheadGroup(){return this.playheadGroup}}/**
|
|
14
|
+
`,Jr=()=>{if(typeof document>"u")throw new Error(za)};class Se{constructor(e=[1,0,0,1,0,0]){this.dirty=!1,this.m=e&&e.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new Se(this.m)}copyInto(e){e.m[0]=this.m[0],e.m[1]=this.m[1],e.m[2]=this.m[2],e.m[3]=this.m[3],e.m[4]=this.m[4],e.m[5]=this.m[5]}point(e){const t=this.m;return{x:t[0]*e.x+t[2]*e.y+t[4],y:t[1]*e.x+t[3]*e.y+t[5]}}translate(e,t){return this.m[4]+=this.m[0]*e+this.m[2]*t,this.m[5]+=this.m[1]*e+this.m[3]*t,this}scale(e,t){return this.m[0]*=e,this.m[1]*=e,this.m[2]*=t,this.m[3]*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),r=this.m[0]*t+this.m[2]*i,n=this.m[1]*t+this.m[3]*i,s=this.m[0]*-i+this.m[2]*t,o=this.m[1]*-i+this.m[3]*t;return this.m[0]=r,this.m[1]=n,this.m[2]=s,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(e,t){const i=this.m[0]+this.m[2]*t,r=this.m[1]+this.m[3]*t,n=this.m[2]+this.m[0]*e,s=this.m[3]+this.m[1]*e;return this.m[0]=i,this.m[1]=r,this.m[2]=n,this.m[3]=s,this}multiply(e){const t=this.m[0]*e.m[0]+this.m[2]*e.m[1],i=this.m[1]*e.m[0]+this.m[3]*e.m[1],r=this.m[0]*e.m[2]+this.m[2]*e.m[3],n=this.m[1]*e.m[2]+this.m[3]*e.m[3],s=this.m[0]*e.m[4]+this.m[2]*e.m[5]+this.m[4],o=this.m[1]*e.m[4]+this.m[3]*e.m[5]+this.m[5];return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=n,this.m[4]=s,this.m[5]=o,this}invert(){const e=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),t=this.m[3]*e,i=-this.m[1]*e,r=-this.m[2]*e,n=this.m[0]*e,s=e*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=e*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=n,this.m[4]=s,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const e=this.m[0],t=this.m[1],i=this.m[2],r=this.m[3],n=this.m[4],s=this.m[5],o=e*r-t*i,l={x:n,y:s,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(e!=0||t!=0){const c=Math.sqrt(e*e+t*t);l.rotation=t>0?Math.acos(e/c):-Math.acos(e/c),l.scaleX=c,l.scaleY=o/c,l.skewX=(e*i+t*r)/o,l.skewY=0}else if(i!=0||r!=0){const c=Math.sqrt(i*i+r*r);l.rotation=Math.PI/2-(r>0?Math.acos(-i/c):-Math.acos(i/c)),l.scaleX=o/c,l.scaleY=c,l.skewX=0,l.skewY=(e*i+t*r)/o}return l.rotation=b._getRotation(l.rotation),l}}const Va="[object Array]",Ua="[object Number]",Wa="[object String]",Ya="[object Boolean]",Xa=Math.PI/180,qa=180/Math.PI,Pt="#",ja="",Ka="0",Za="Konva warning: ",Qr="Konva error: ",Ja="rgb(",Zi={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]},Qa=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let gi=[],_t=null;const eo=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(a){setTimeout(a,16)},b={_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)===Va},_isNumber(a){return Object.prototype.toString.call(a)===Ua&&!isNaN(a)&&isFinite(a)},_isString(a){return Object.prototype.toString.call(a)===Wa},_isBoolean(a){return Object.prototype.toString.call(a)===Ya},isObject(a){return a instanceof Object},isValidSelector(a){if(typeof a!="string")return!1;const e=a[0];return e==="#"||e==="."||e===e.toUpperCase()},_sign(a){return a===0||a>0?1:-1},requestAnimFrame(a){gi.push(a),gi.length===1&&eo(function(){const e=gi;gi=[],e.forEach(function(t){t()})})},createCanvasElement(){Jr();const a=document.createElement("canvas");try{a.style=a.style||{}}catch{}return a},createImageElement(){return Jr(),document.createElement("img")},_isInDocument(a){for(;a=a.parentNode;)if(a==document)return!0;return!1},_urlToImage(a,e){const t=b.createImageElement();t.onload=function(){e(t)},t.src=a},_rgbToHex(a,e,t){return((1<<24)+(a<<16)+(e<<8)+t).toString(16).slice(1)},_hexToRgb(a){a=a.replace(Pt,ja);const e=parseInt(a,16);return{r:e>>16&255,g:e>>8&255,b:e&255}},getRandomColor(){let a=(Math.random()*16777215<<0).toString(16);for(;a.length<6;)a=Ka+a;return Pt+a},isCanvasFarblingActive(){if(_t!==null)return _t;if(typeof document>"u")return _t=!1,!1;const a=this.createCanvasElement();a.width=10,a.height=10;const e=a.getContext("2d",{willReadFrequently:!0});e.clearRect(0,0,10,10),e.fillStyle="#282828",e.fillRect(0,0,10,10);const t=e.getImageData(0,0,10,10).data;let i=!1;for(let r=0;r<100;r++)if(t[r*4]!==40||t[r*4+1]!==40||t[r*4+2]!==40||t[r*4+3]!==255){i=!0;break}return _t=i,this.releaseCanvas(a),_t},getHitColor(){const a=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(a):a},getHitColorKey(a,e,t){return this.isCanvasFarblingActive()&&(a=Math.round(a/5)*5,e=Math.round(e/5)*5,t=Math.round(t/5)*5),Pt+this._rgbToHex(a,e,t)},getSnappedHexColor(a){const e=this._hexToRgb(a);return Pt+this._rgbToHex(Math.round(e.r/5)*5,Math.round(e.g/5)*5,Math.round(e.b/5)*5)},getRGB(a){let e;return a in Zi?(e=Zi[a],{r:e[0],g:e[1],b:e[2]}):a[0]===Pt?this._hexToRgb(a.substring(1)):a.substr(0,4)===Ja?(e=Qa.exec(a.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA(a){return a=a||"black",b._namedColorToRBA(a)||b._hex3ColorToRGBA(a)||b._hex4ColorToRGBA(a)||b._hex6ColorToRGBA(a)||b._hex8ColorToRGBA(a)||b._rgbColorToRGBA(a)||b._rgbaColorToRGBA(a)||b._hslColorToRGBA(a)},_namedColorToRBA(a){const e=Zi[a.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(a){if(a.indexOf("rgb(")===0){a=a.match(/rgb\(([^)]+)\)/)[1];const e=a.split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(a){if(a.indexOf("rgba(")===0){a=a.match(/rgba\(([^)]+)\)/)[1];const e=a.split(/ *, */).map((t,i)=>t.slice(-1)==="%"?i===3?parseInt(t)/100:parseInt(t)/100*255:Number(t));return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex8ColorToRGBA(a){if(a[0]==="#"&&a.length===9)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:parseInt(a.slice(7,9),16)/255}},_hex6ColorToRGBA(a){if(a[0]==="#"&&a.length===7)return{r:parseInt(a.slice(1,3),16),g:parseInt(a.slice(3,5),16),b:parseInt(a.slice(5,7),16),a:1}},_hex4ColorToRGBA(a){if(a[0]==="#"&&a.length===5)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:parseInt(a[4]+a[4],16)/255}},_hex3ColorToRGBA(a){if(a[0]==="#"&&a.length===4)return{r:parseInt(a[1]+a[1],16),g:parseInt(a[2]+a[2],16),b:parseInt(a[3]+a[3],16),a:1}},_hslColorToRGBA(a){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(a)){const[e,...t]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(a),i=Number(t[0])/360,r=Number(t[1])/100,n=Number(t[2])/100;let s,o,l;if(r===0)return l=n*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};n<.5?s=n*(1+r):s=n+r-n*r;const c=2*n-s,h=[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=c+(s-c)*6*o:2*o<1?l=s:3*o<2?l=c+(s-c)*(2/3-o)*6:l=c,h[d]=l*255;return{r:Math.round(h[0]),g:Math.round(h[1]),b:Math.round(h[2]),a:1}}},haveIntersection(a,e){return!(e.x>a.x+a.width||e.x+e.width<a.x||e.y>a.y+a.height||e.y+e.height<a.y)},cloneObject(a){const e={};for(const t in a)this._isPlainObject(a[t])?e[t]=this.cloneObject(a[t]):this._isArray(a[t])?e[t]=this.cloneArray(a[t]):e[t]=a[t];return e},cloneArray(a){return a.slice(0)},degToRad(a){return a*Xa},radToDeg(a){return a*qa},_degToRad(a){return b.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),b.degToRad(a)},_radToDeg(a){return b.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),b.radToDeg(a)},_getRotation(a){return D.angleDeg?b.radToDeg(a):a},_capitalize(a){return a.charAt(0).toUpperCase()+a.slice(1)},throw(a){throw new Error(Qr+a)},error(a){console.error(Qr+a)},warn(a){D.showWarnings&&console.warn(Za+a)},each(a,e){for(const t in a)e(t,a[t])},_inRange(a,e,t){return e<=a&&a<t},_getProjectionToSegment(a,e,t,i,r,n){let s,o,l;const c=(a-t)*(a-t)+(e-i)*(e-i);if(c==0)s=a,o=e,l=(r-t)*(r-t)+(n-i)*(n-i);else{const h=((r-a)*(t-a)+(n-e)*(i-e))/c;h<0?(s=a,o=e,l=(a-r)*(a-r)+(e-n)*(e-n)):h>1?(s=t,o=i,l=(t-r)*(t-r)+(i-n)*(i-n)):(s=a+h*(t-a),o=e+h*(i-e),l=(s-r)*(s-r)+(o-n)*(o-n))}return[s,o,l]},_getProjectionToLine(a,e,t){const i=b.cloneObject(a);let r=Number.MAX_VALUE;return e.forEach(function(n,s){if(!t&&s===e.length-1)return;const o=e[(s+1)%e.length],l=b._getProjectionToSegment(n.x,n.y,o.x,o.y,a.x,a.y),c=l[0],h=l[1],d=l[2];d<r&&(i.x=c,i.y=h,r=d)}),i},_prepareArrayForTween(a,e,t){const i=[],r=[];if(a.length>e.length){const s=e;e=a,a=s}for(let s=0;s<a.length;s+=2)i.push({x:a[s],y:a[s+1]});for(let s=0;s<e.length;s+=2)r.push({x:e[s],y:e[s+1]});const n=[];return r.forEach(function(s){const o=b._getProjectionToLine(s,i,t);n.push(o.x),n.push(o.y)}),n},_prepareToStringify(a){let e;a.visitedByCircularReferenceRemoval=!0;for(const t in a)if(a.hasOwnProperty(t)&&a[t]&&typeof a[t]=="object"){if(e=Object.getOwnPropertyDescriptor(a,t),a[t].visitedByCircularReferenceRemoval||b._isElement(a[t]))if(e.configurable)delete a[t];else return null;else if(b._prepareToStringify(a[t])===null)if(e.configurable)delete a[t];else return null}return delete a.visitedByCircularReferenceRemoval,a},_assign(a,e){for(const t in e)a[t]=e[t];return a},_getFirstPointerId(a){return a.touches?a.changedTouches[0].identifier:a.pointerId||999},releaseCanvas(...a){D.releaseCanvasOnDestroy&&a.forEach(e=>{e.width=0,e.height=0})},drawRoundedRectPath(a,e,t,i){let r=e<0?e:0,n=t<0?t:0;e=Math.abs(e),t=Math.abs(t);let s=0,o=0,l=0,c=0;typeof i=="number"?s=o=l=c=Math.min(i,e/2,t/2):(s=Math.min(i[0]||0,e/2,t/2),o=Math.min(i[1]||0,e/2,t/2),c=Math.min(i[2]||0,e/2,t/2),l=Math.min(i[3]||0,e/2,t/2)),a.moveTo(r+s,n),a.lineTo(r+e-o,n),a.arc(r+e-o,n+o,o,Math.PI*3/2,0,!1),a.lineTo(r+e,n+t-c),a.arc(r+e-c,n+t-c,c,0,Math.PI/2,!1),a.lineTo(r+l,n+t),a.arc(r+l,n+t-l,l,Math.PI/2,Math.PI,!1),a.lineTo(r,n+s),a.arc(r+s,n+s,s,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(a,e,t,i,r){i=Math.abs(i);for(let n=0;n<t;n++){const s=e[(n-1+t)%t],o=e[n],l=e[(n+1)%t],c={x:o.x-s.x,y:o.y-s.y},h={x:l.x-o.x,y:l.y-o.y},d=Math.hypot(c.x,c.y),u=Math.hypot(h.x,h.y);let g;typeof r=="number"?g=r:g=n<r.length?r[n]:0,g=i*Math.cos(Math.PI/t)*Math.min(1,g/i*2);const y={x:c.x/d,y:c.y/d},S={x:h.x/u,y:h.y/u},C={x:o.x-y.x*g,y:o.y-y.y*g},T={x:o.x+S.x*g,y:o.y+S.y*g};n===0?a.moveTo(C.x,C.y):a.lineTo(C.x,C.y),a.arcTo(o.x,o.y,T.x,T.y,g)}}};function to(a){const e=[],t=a.length,i=b;for(let r=0;r<t;r++){let n=a[r];i._isNumber(n)?n=Math.round(n*1e3)/1e3:i._isString(n)||(n=n+""),e.push(n)}return e}const en=",",io="(",ro=")",no="([",so="])",ao=";",oo="()",lo="=",tn=["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"],co=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],ho=100;let fi=null;function rn(){if(fi!==null)return fi;try{const e=b.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(fi=!1,!1)}catch{return fi=!1,!1}}class Wi{constructor(e){this.canvas=e,D.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let i=this.traceArr,r=i.length,n="",s,o,l,c;for(s=0;s<r;s++)o=i[s],l=o.method,l?(c=o.args,n+=l,e?n+=oo:b._isArray(c[0])?n+=no+c.join(en)+so:(t&&(c=c.map(h=>typeof h=="number"?Math.floor(h):h)),n+=io+c.join(en)+ro)):(n+=o.property,e||(n+=lo+o.val)),n+=ao;return n}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=ho&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}_applyMiterLimit(e){const t=e.attrs.miterLimit;t!=null&&this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,i,r,n,s){this._context.arc(e,t,i,r,n,s)}arcTo(e,t,i,r,n){this._context.arcTo(e,t,i,r,n)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,i,r,n,s){this._context.bezierCurveTo(e,t,i,r,n,s)}clearRect(e,t,i,r){this._context.clearRect(e,t,i,r)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const i=arguments;if(i.length===2)return this._context.createImageData(e,t);if(i.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,i,r){return this._context.createLinearGradient(e,t,i,r)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,i,r,n,s){return this._context.createRadialGradient(e,t,i,r,n,s)}drawImage(e,t,i,r,n,s,o,l,c){const h=arguments,d=this._context;h.length===3?d.drawImage(e,t,i):h.length===5?d.drawImage(e,t,i,r,n):h.length===9&&d.drawImage(e,t,i,r,n,s,o,l,c)}ellipse(e,t,i,r,n,s,o,l){this._context.ellipse(e,t,i,r,n,s,o,l)}isPointInPath(e,t,i,r){return i?this._context.isPointInPath(i,e,t,r):this._context.isPointInPath(e,t,r)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,i,r){this._context.fillRect(e,t,i,r)}strokeRect(e,t,i,r){this._context.strokeRect(e,t,i,r)}fillText(e,t,i,r){r?this._context.fillText(e,t,i,r):this._context.fillText(e,t,i)}measureText(e){return this._context.measureText(e)}getImageData(e,t,i,r){return this._context.getImageData(e,t,i,r)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,i,r){this._context.rect(e,t,i,r)}roundRect(e,t,i,r,n){this._context.roundRect(e,t,i,r,n)}putImageData(e,t,i){this._context.putImageData(e,t,i)}quadraticCurveTo(e,t,i,r){this._context.quadraticCurveTo(e,t,i,r)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,i,r,n,s){this._context.setTransform(e,t,i,r,n,s)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,i,r){this._context.strokeText(e,t,i,r)}transform(e,t,i,r,n,s){this._context.transform(e,t,i,r,n,s)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=tn.length,i=this.setAttr,r,n;const s=function(o){let l=e[o],c;e[o]=function(){return n=to(Array.prototype.slice.call(arguments,0)),c=l.apply(e,arguments),e._trace({method:o,args:n}),c}};for(r=0;r<t;r++)s(tn[r]);e.setAttr=function(){i.apply(e,arguments);const o=arguments[0];let l=arguments[1];(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")&&(l=l/this.canvas.getPixelRatio()),e._trace({property:o,val:l})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}}co.forEach(function(a){Object.defineProperty(Wi.prototype,a,{get(){return this._context[a]},set(e){this._context[a]=e}})});class uo extends Wi{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),i=e.getFillPriority();if(t&&i==="color"){this._fillColor(e);return}const r=e.getFillPatternImage();if(r&&i==="pattern"){this._fillPattern(e);return}const n=e.getFillLinearGradientColorStops();if(n&&i==="linear-gradient"){this._fillLinearGradient(e);return}const s=e.getFillRadialGradientColorStops();if(s&&i==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):r?this._fillPattern(e):n?this._fillLinearGradient(e):s&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),i=e.getStrokeLinearGradientEndPoint(),r=e.getStrokeLinearGradientColorStops(),n=this.createLinearGradient(t.x,t.y,i.x,i.y);if(r){for(let s=0;s<r.length;s+=2)n.addColorStop(r[s],r[s+1]);this.setAttr("strokeStyle",n)}}_stroke(e){const t=e.dash(),i=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!i){this.save();const n=this.getCanvas().getPixelRatio();this.setTransform(n,0,0,n,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),i||this.restore()}}_applyShadow(e){var t,i,r;const n=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",s=(i=e.getShadowBlur())!==null&&i!==void 0?i:5,o=(r=e.getShadowOffset())!==null&&r!==void 0?r:{x:0,y:0},l=e.getAbsoluteScale(),c=this.canvas.getPixelRatio(),h=l.x*c,d=l.y*c;this.setAttr("shadowColor",n),this.setAttr("shadowBlur",s*Math.min(Math.abs(h),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*h),this.setAttr("shadowOffsetY",o.y*d)}}class po extends Wi{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const n=this.getCanvas().getPixelRatio();this.setTransform(n,0,0,n,0,0)}this._applyLineCap(e);const i=e.hitStrokeWidth(),r=i==="auto"?e.strokeWidth():i;this.setAttr("lineWidth",r),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}}let mi;function go(){if(mi)return mi;const a=b.createCanvasElement(),e=a.getContext("2d");return mi=function(){const t=D._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),b.releaseCanvas(a),mi}class Nr{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||D.pixelRatio||go();this.pixelRatio=i,this._canvas=b.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(r){return b.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class Ue extends Nr{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new uo(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class $r extends Nr{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new po(this),this.setSize(e.width,e.height)}}const Z={get isDragging(){let a=!1;return Z._dragElements.forEach(e=>{e.dragStatus==="dragging"&&(a=!0)}),a},justDragged:!1,get node(){let a;return Z._dragElements.forEach(e=>{a=e.node}),a},_dragElements:new Map,_drag(a){const e=[];Z._dragElements.forEach((t,i)=>{const{node:r}=t,n=r.getStage();n.setPointersPositions(a),t.pointerId===void 0&&(t.pointerId=b._getFirstPointerId(a));const s=n._changedPointerPositions.find(o=>o.id===t.pointerId);if(s){if(t.dragStatus!=="dragging"){const o=r.dragDistance();if(Math.max(Math.abs(s.x-t.startPointerPos.x),Math.abs(s.y-t.startPointerPos.y))<o||(r.startDrag({evt:a}),!r.isDragging()))return}r._setDragPosition(a,t),e.push(r)}}),e.forEach(t=>{t.fire("dragmove",{type:"dragmove",target:t,evt:a},!0)})},_endDragBefore(a){const e=[];Z._dragElements.forEach(t=>{const{node:i}=t,r=i.getStage();if(a&&r.setPointersPositions(a),!r._changedPointerPositions.find(o=>o.id===t.pointerId))return;(t.dragStatus==="dragging"||t.dragStatus==="stopped")&&(Z.justDragged=!0,D._mouseListenClick=!1,D._touchListenClick=!1,D._pointerListenClick=!1,t.dragStatus="stopped");const s=t.node.getLayer()||t.node instanceof D.Stage&&t.node;s&&e.indexOf(s)===-1&&e.push(s)}),e.forEach(t=>{t.draw()})},_endDragAfter(a){Z._dragElements.forEach((e,t)=>{e.dragStatus==="stopped"&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:a},!0),e.dragStatus!=="dragging"&&Z._dragElements.delete(t)})}};D.isBrowser&&(window.addEventListener("mouseup",Z._endDragBefore,!0),window.addEventListener("touchend",Z._endDragBefore,!0),window.addEventListener("touchcancel",Z._endDragBefore,!0),window.addEventListener("mousemove",Z._drag),window.addEventListener("touchmove",Z._drag),window.addEventListener("mouseup",Z._endDragAfter,!1),window.addEventListener("touchend",Z._endDragAfter,!1),window.addEventListener("touchcancel",Z._endDragAfter,!1));function qe(a){return b._isString(a)?'"'+a+'"':Object.prototype.toString.call(a)==="[object Number]"||b._isBoolean(a)?a:Object.prototype.toString.call(a)}function Ts(a){return a>255?255:a<0?0:Math.round(a)}function R(){if(D.isUnminified)return function(a,e){return b._isNumber(a)||b.warn(qe(a)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),a}}function Yi(a){if(D.isUnminified)return function(e,t){let i=b._isNumber(e),r=b._isArray(e)&&e.length==a;return!i&&!r&&b.warn(qe(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+a+")"),e}}function zr(){if(D.isUnminified)return function(a,e){return b._isNumber(a)||a==="auto"||b.warn(qe(a)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),a}}function ct(){if(D.isUnminified)return function(a,e){return b._isString(a)||b.warn(qe(a)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),a}}function bs(){if(D.isUnminified)return function(a,e){const t=b._isString(a),i=Object.prototype.toString.call(a)==="[object CanvasGradient]"||a&&a.addColorStop;return t||i||b.warn(qe(a)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),a}}function fo(){if(D.isUnminified)return function(a,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&a instanceof t||(b._isArray(a)?a.forEach(function(i){b._isNumber(i)||b.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):b.warn(qe(a)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),a}}function xe(){if(D.isUnminified)return function(a,e){return a===!0||a===!1||b.warn(qe(a)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),a}}function mo(a){if(D.isUnminified)return function(e,t){return e==null||b.isObject(e)||b.warn(qe(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+a),e}}const It="get",At="set",m={addGetterSetter(a,e,t,i,r){m.addGetter(a,e,t),m.addSetter(a,e,i,r),m.addOverloadedGetterSetter(a,e)},addGetter(a,e,t){const i=It+b._capitalize(e);a.prototype[i]=a.prototype[i]||function(){const r=this.attrs[e];return r===void 0?t:r}},addSetter(a,e,t,i){const r=At+b._capitalize(e);a.prototype[r]||m.overWriteSetter(a,e,t,i)},overWriteSetter(a,e,t,i){const r=At+b._capitalize(e);a.prototype[r]=function(n){return t&&n!==void 0&&n!==null&&(n=t.call(this,n,e)),this._setAttr(e,n),i&&i.call(this),this}},addComponentsGetterSetter(a,e,t,i,r){const n=t.length,s=b._capitalize,o=It+s(e),l=At+s(e);a.prototype[o]=function(){const h={};for(let d=0;d<n;d++){const u=t[d];h[u]=this.getAttr(e+s(u))}return h};const c=mo(t);a.prototype[l]=function(h){const d=this.attrs[e];i&&(h=i.call(this,h,e)),c&&c.call(this,h,e);for(const u in h)h.hasOwnProperty(u)&&this._setAttr(e+s(u),h[u]);return h||t.forEach(u=>{this._setAttr(e+s(u),void 0)}),this._fireChangeEvent(e,d,h),r&&r.call(this),this},m.addOverloadedGetterSetter(a,e)},addOverloadedGetterSetter(a,e){const t=b._capitalize(e),i=At+t,r=It+t;a.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[r]()}},addDeprecatedGetterSetter(a,e,t,i){b.error("Adding deprecated "+e);const r=It+b._capitalize(e),n=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";a.prototype[r]=function(){b.error(n);const s=this.attrs[e];return s===void 0?t:s},m.addSetter(a,e,i,function(){b.error(n)}),m.addOverloadedGetterSetter(a,e)},backCompat(a,e){b.each(e,function(t,i){const r=a.prototype[i],n=It+b._capitalize(t),s=At+b._capitalize(t);function o(){r.apply(this,arguments),b.error('"'+t+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}a.prototype[t]=o,a.prototype[n]=o,a.prototype[s]=o})},afterSetFilter(){this._filterUpToDate=!1}};function yo(a){const e=/(\w+)\(([^)]+)\)/g;let t;for(;(t=e.exec(a))!==null;){const[,i,r]=t;switch(i){case"blur":{const n=parseFloat(r.replace("px",""));return function(s){this.blurRadius(n*.5);const o=D.Filters;o&&o.Blur&&o.Blur.call(this,s)}}case"brightness":{const n=r.includes("%")?parseFloat(r)/100:parseFloat(r);return function(s){this.brightness(n);const o=D.Filters;o&&o.Brightness&&o.Brightness.call(this,s)}}case"contrast":{const n=parseFloat(r);return function(s){const o=100*(Math.sqrt(n)-1);this.contrast(o);const l=D.Filters;l&&l.Contrast&&l.Contrast.call(this,s)}}case"grayscale":return function(n){const s=D.Filters;s&&s.Grayscale&&s.Grayscale.call(this,n)};case"sepia":return function(n){const s=D.Filters;s&&s.Sepia&&s.Sepia.call(this,n)};case"invert":return function(n){const s=D.Filters;s&&s.Invert&&s.Invert.call(this,n)};default:b.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Ai="absoluteOpacity",nn="allEventListeners",De="absoluteTransform",sn="absoluteScale",Je="canvas",So="Change",Co="children",vo="konva",fr="listening",To="mouseenter",bo="mouseleave",wo="pointerenter",ko="pointerleave",xo="touchenter",Po="touchleave",an="set",on="Shape",Ei=" ",ln="stage",$e="transform",_o="Stage",mr="visible",Io=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Ei);let Ao=1;class L{constructor(e){this._id=Ao++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(e),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(e){(e===$e||e===De)&&this._cache.get(e)?this._cache.get(e).dirty=!0:e?this._cache.delete(e):this._cache.clear()}_getCache(e,t){let i=this._cache.get(e);return(i===void 0||(e===$e||e===De)&&i.dirty===!0)&&(i=t.call(this),this._cache.set(e,i)),i}_calculate(e,t,i){if(!this._attachedDepsListeners.get(e)){const r=t.map(n=>n+"Change.konva").join(Ei);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(Je)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===De&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(Je)){const{scene:e,filter:t,hit:i}=this._cache.get(Je);b.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(Je)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){const t=e||{};let i={};(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)&&(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let r=Math.ceil(t.width||i.width),n=Math.ceil(t.height||i.height),s=t.pixelRatio,o=t.x===void 0?Math.floor(i.x):t.x,l=t.y===void 0?Math.floor(i.y):t.y,c=t.offset||0,h=t.drawBorder||!1,d=t.hitCanvasPixelRatio||1;if(!r||!n){b.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,g=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=c*2+u,n+=c*2+g,o-=c,l-=c;const f=new Ue({pixelRatio:s,width:r,height:n}),y=new Ue({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),S=new $r({pixelRatio:d,width:r,height:n}),C=f.getContext(),T=S.getContext(),v=new Ue({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(l),pixelRatio:f.pixelRatio}),w=v.getContext();return S.isCache=!0,f.isCache=!0,this._cache.delete(Je),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),C.save(),T.save(),w.save(),C.translate(-o,-l),T.translate(-o,-l),w.translate(-o,-l),v.x=o,v.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Ai),this._clearSelfAndDescendantCache(sn),this.drawScene(f,this,v),this.drawHit(S,this),this._isUnderCache=!1,C.restore(),T.restore(),h&&(C.save(),C.beginPath(),C.rect(0,0,r,n),C.closePath(),C.setAttr("strokeStyle","red"),C.setAttr("lineWidth",5),C.stroke(),C.restore()),b.releaseCanvas(v._canvas),this._cache.set(Je,{scene:f,filter:y,hit:S,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(Je)}getClientRect(e){throw new Error('abstract "getClientRect" method call')}_transformedRect(e,t){const i=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}];let r=1/0,n=1/0,s=-1/0,o=-1/0;const l=this.getAbsoluteTransform(t);return i.forEach(function(c){const h=l.point(c);r===void 0&&(r=s=h.x,n=o=h.y),r=Math.min(r,h.x),n=Math.min(n,h.y),s=Math.max(s,h.x),o=Math.max(o,h.y)}),{x:r,y:n,width:s-r,height:o-n}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);const t=this._getCanvasCache();e.translate(t.x,t.y);const i=this._getCachedSceneCanvas(),r=i.pixelRatio;e.drawImage(i._canvas,0,0,i.width/r,i.height/r),e.restore()}_drawCachedHitCanvas(e){const t=this._getCanvasCache(),i=t.hit;e.save(),e.translate(t.x,t.y),e.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),i=t.scene,r=t.filter,n=r.getContext(),s,o,l,c;if(!e||e.length===0)return i;if(this._filterUpToDate)return r;let h=!0;for(let u=0;u<e.length;u++)if(typeof e[u]=="string"&&rn(),typeof e[u]!="string"||!rn()){h=!1;break}const d=i.pixelRatio;if(r.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),h){const u=e.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,r}try{for(s=e.length,n.clear(),n.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),o=n.getImageData(0,0,r.getWidth(),r.getHeight()),l=0;l<s;l++)c=e[l],typeof c=="string"&&(c=yo(c)),c.call(this,o),n.putImageData(o,0,0)}catch(u){b.error("Unable to apply filter. "+u.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,r}on(e,t){if(this._cache&&this._cache.delete(nn),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Ei);for(let r=0;r<i.length;r++){const s=i[r].split("."),o=s[0],l=s[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:t})}return this}off(e,t){let i=(e||"").split(Ei),r=i.length,n,s,o,l,c,h;if(this._cache&&this._cache.delete(nn),!e)for(s in this.eventListeners)this._off(s);for(n=0;n<r;n++)if(o=i[n],l=o.split("."),c=l[0],h=l[1],c)this.eventListeners[c]&&this._off(c,h,t);else for(s in this.eventListeners)this._off(s,h,t);return this}dispatchEvent(e){const t={target:this,type:e.type,evt:e};return this.fire(e.type,t),this}addEventListener(e,t){return this.on(e,function(i){t.call(this,i.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,i){const r=this;this.on(e,function(n){const s=n.target.findAncestors(t,!0,r);for(let o=0;o<s.length;o++)n=b.cloneObject(n),n.currentTarget=s[o],i.call(s[o],n)})}remove(){return this.isDragging()&&this.stopDrag(),Z._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(De),this._clearSelfAndDescendantCache(Ai),this._clearSelfAndDescendantCache(sn),this._clearSelfAndDescendantCache(ln),this._clearSelfAndDescendantCache(mr),this._clearSelfAndDescendantCache(fr)}_remove(){this._clearCaches();const e=this.getParent();e&&e.children&&(e.children.splice(this.index,1),e._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(e){const t="get"+b._capitalize(e);return b._isFunction(this[t])?this[t]():this.attrs[e]}getAncestors(){let e=this.getParent(),t=[];for(;e;)t.push(e),e=e.getParent();return t}getAttrs(){return this.attrs||{}}setAttrs(e){return this._batchTransformChanges(()=>{let t,i;if(!e)return this;for(t in e)t!==Co&&(i=an+b._capitalize(t),b._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(fr,this._isListening)}_isListening(e){if(!this.listening())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isListening(e):!0}isVisible(){return this._getCache(mr,this._isVisible)}_isVisible(e){if(!this.visible())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isVisible(e):!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);const i=this.getLayer();let r=!1;Z._dragElements.forEach(s=>{s.dragStatus==="dragging"&&(s.node.nodeType==="Stage"||s.node.getLayer()===i)&&(r=!0)});const n=!t&&!D.hitOnDragEnabled&&(r||D.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 e=this.getDepth(),t=this,i=0,r,n,s,o;function l(h){for(r=[],n=h.length,s=0;s<n;s++)o=h[s],i++,o.nodeType!==on&&(r=r.concat(o.getChildren().slice())),o._id===t._id&&(s=n);r.length>0&&r[0].getDepth()<=e&&l(r)}const c=this.getStage();return t.nodeType!==_o&&c&&l(c.getChildren()),i}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}_batchTransformChanges(e){this._batchingTransformChange=!0,e(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache($e),this._clearSelfAndDescendantCache(De)),this._needClearTransformCache=!1}setPosition(e){return this._batchTransformChanges(()=>{this.x(e.x),this.y(e.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const e=this.getStage();if(!e)return null;const t=e.getPointerPosition();if(!t)return null;const i=this.getAbsoluteTransform().copy();return i.invert(),i.point(t)}getAbsolutePosition(e){let t=!1,i=this.parent;for(;i;){if(i.isCached()){t=!0;break}i=i.parent}t&&!e&&(e=!0);const r=this.getAbsoluteTransform(e).getMatrix(),n=new Se,s=this.offset();return n.m=r.slice(),n.translate(s.x,s.y),n.getTranslation()}setAbsolutePosition(e){const{x:t,y:i,...r}=this._clearTransform();this.attrs.x=t,this.attrs.y=i,this._clearCache($e);const n=this._getAbsoluteTransform().copy();return n.invert(),n.translate(e.x,e.y),e={x:this.attrs.x+n.getTranslation().x,y:this.attrs.y+n.getTranslation().y},this._setTransform(r),this.setPosition({x:e.x,y:e.y}),this._clearCache($e),this._clearSelfAndDescendantCache(De),this}_setTransform(e){let t;for(t in e)this.attrs[t]=e[t]}_clearTransform(){const e={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,e}move(e){let t=e.x,i=e.y,r=this.x(),n=this.y();return t!==void 0&&(r+=t),i!==void 0&&(n+=i),this.setPosition({x:r,y:n}),this}_eachAncestorReverse(e,t){let i=[],r=this.getParent(),n,s;if(!(t&&t._id===this._id)){for(i.unshift(this);r&&(!t||r._id!==t._id);)i.unshift(r),r=r.parent;for(n=i.length,s=0;s<n;s++)e(i[s])}}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return b.warn("Node has no parent. moveToTop function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return b.warn("Node has no parent. moveUp function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return b.warn("Node has no parent. moveDown function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return b.warn("Node has no parent. moveToBottom function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(e){if(!this.parent)return b.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&b.warn("Unexpected value "+e+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const t=this.index;return this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(Ai,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let e=this.opacity();const t=this.getParent();return t&&!t._isUnderCache&&(e*=t.getAbsoluteOpacity()),e}moveTo(e){return this.getParent()!==e&&(this._remove(),e.add(this)),this}toObject(){let e=this.getAttrs(),t,i,r,n,s;const o={attrs:{},className:this.getClassName()};for(t in e)i=e[t],s=b.isObject(i)&&!b._isPlainObject(i)&&!b._isArray(i),!s&&(r=typeof this[t]=="function"&&this[t],delete e[t],n=r?r.call(this):null,e[t]=i,n!==i&&(o.attrs[t]=i));return b._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,i){const r=[];t&&this._isMatch(e)&&r.push(this);let n=this.parent;for(;n;){if(n===i)return r;n._isMatch(e)&&r.push(n),n=n.parent}return r}isAncestorOf(e){return!1}findAncestor(e,t,i){return this.findAncestors(e,t,i)[0]}_isMatch(e){if(!e)return!1;if(typeof e=="function")return e(this);let t=e.replace(/ /g,"").split(","),i=t.length,r,n;for(r=0;r<i;r++)if(n=t[r],b.isValidSelector(n)||(b.warn('Selector "'+n+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),b.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),b.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 e=this.getParent();return e?e.getLayer():null}getStage(){return this._getCache(ln,this._getStage)}_getStage(){const e=this.getParent();return e?e.getStage():null}fire(e,t={},i){return t.target=t.target||this,i?this._fireAndBubble(e,t):this._fire(e,t),this}getAbsoluteTransform(e){return e?this._getAbsoluteTransform(e):this._getCache(De,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new Se,this._eachAncestorReverse(function(i){const r=i.transformsEnabled();r==="all"?t.multiply(i.getTransform()):r==="position"&&t.translate(i.x()-i.offsetX(),i.y()-i.offsetY())},e),t;{t=this._cache.get(De)||new Se,this.parent?this.parent.getAbsoluteTransform().copyInto(t):t.reset();const i=this.transformsEnabled();if(i==="all")t.multiply(this.getTransform());else if(i==="position"){const r=this.attrs.x||0,n=this.attrs.y||0,s=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(r-s,n-o)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;for(;t;)t._isUnderCache&&(e=t),t=t.getParent();const r=this.getAbsoluteTransform(e).decompose();return{x:r.scaleX,y:r.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache($e,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get($e)||new Se;i.reset();const r=this.x(),n=this.y(),s=D.getAngle(this.rotation()),o=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,l=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,c=this.attrs.skewX||0,h=this.attrs.skewY||0,d=this.attrs.offsetX||0,u=this.attrs.offsetY||0;return(r!==0||n!==0)&&i.translate(r,n),s!==0&&i.rotate(s),(c!==0||h!==0)&&i.skew(c,h),(o!==1||l!==1)&&i.scale(o,l),(d!==0||u!==0)&&i.translate(-1*d,-1*u),i.dirty=!1,i}clone(e){let t=b.cloneObject(this.attrs),i,r,n,s,o;for(i in e)t[i]=e[i];const l=new this.constructor(t);for(i in this.eventListeners)for(r=this.eventListeners[i],n=r.length,s=0;s<n;s++)o=r[s],o.name.indexOf(vo)<0&&(l.eventListeners[i]||(l.eventListeners[i]=[]),l.eventListeners[i].push(o));return l}_toKonvaCanvas(e){e=e||{};const t=this.getClientRect(),i=this.getStage(),r=e.x!==void 0?e.x:Math.floor(t.x),n=e.y!==void 0?e.y:Math.floor(t.y),s=e.pixelRatio||1,o=new Ue({width:e.width||Math.ceil(t.width)||(i?i.width():0),height:e.height||Math.ceil(t.height)||(i?i.height():0),pixelRatio:s}),l=o.getContext(),c=new Ue({width:o.width/o.pixelRatio+Math.abs(r),height:o.height/o.pixelRatio+Math.abs(n),pixelRatio:o.pixelRatio});return e.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(r||n)&&l.translate(-1*r,-1*n),this.drawScene(o,void 0,c),l.restore(),o}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};const t=e.mimeType||null,i=e.quality||null,r=this._toKonvaCanvas(e).toDataURL(t,i);return e.callback&&e.callback(r),r}toImage(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,b._urlToImage(this.toDataURL(e),function(n){t(n),r==null||r(n)})}catch(r){i(r)}})}toBlob(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,this.toCanvas(e).toBlob(n=>{t(n),r==null||r(n)},e==null?void 0:e.mimeType,e==null?void 0:e.quality)}catch(r){i(r)}})}setSize(e){return this.width(e.width),this.height(e.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():D.dragDistance}_off(e,t,i){let r=this.eventListeners[e],n,s,o;for(n=0;n<r.length;n++)if(s=r[n].name,o=r[n].handler,(s!=="konva"||t==="konva")&&(!t||s===t)&&(!i||i===o)){if(r.splice(n,1),r.length===0){delete this.eventListeners[e];break}n--}}_fireChangeEvent(e,t,i){this._fire(e+So,{oldVal:t,newVal:i})}addName(e){if(!this.hasName(e)){const t=this.name(),i=t?t+" "+e:e;this.name(i)}return this}hasName(e){if(!e)return!1;const t=this.name();return t?(t||"").split(/\s/g).indexOf(e)!==-1:!1}removeName(e){const t=(this.name()||"").split(/\s/g),i=t.indexOf(e);return i!==-1&&(t.splice(i,1),this.name(t.join(" "))),this}setAttr(e,t){const i=this[an+b._capitalize(e)];return b._isFunction(i)?i.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(D.autoDrawEnabled){const e=this.getLayer()||this.getStage();e==null||e.batchDraw()}}_setAttr(e,t){const i=this.attrs[e];i===t&&!b.isObject(t)||(t==null?delete this.attrs[e]:this.attrs[e]=t,this._shouldFireChangeEvents&&this._fireChangeEvent(e,i,t),this._requestDraw())}_setComponentAttr(e,t,i){let r;i!==void 0&&(r=this.attrs[e],r||(this.attrs[e]=this.getAttr(e)),this.attrs[e][t]=i,this._fireChangeEvent(e,r,i))}_fireAndBubble(e,t,i){t&&this.nodeType===on&&(t.target=this);const r=[To,bo,wo,ko,xo,Po];if(!(r.indexOf(e)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(e,t);const s=r.indexOf(e)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!s&&(i&&i.parent?this._fireAndBubble.call(this.parent,e,t,i):this._fireAndBubble.call(this.parent,e,t))}}_getProtoListeners(e){var t,i;const{nodeType:r}=this,n=L.protoListenerMap.get(r)||{};let s=n==null?void 0:n[e];if(s===void 0){s=[];let o=Object.getPrototypeOf(this);for(;o;){const l=(i=(t=o.eventListeners)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:[];s.push(...l),o=Object.getPrototypeOf(o)}n[e]=s,L.protoListenerMap.set(r,n)}return s}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;const i=this._getProtoListeners(e);if(i)for(let n=0;n<i.length;n++)i[n].handler.call(this,t);const r=this.eventListeners[e];if(r)for(let n=0;n<r.length;n++)r[n].handler.call(this,t)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){const t=e?e.pointerId:void 0,i=this.getStage(),r=this.getAbsolutePosition();if(!i)return;const n=i._getPointerById(t)||i._changedPointerPositions[0]||r;Z._dragElements.set(this._id,{node:this,startPointerPos:n,offset:{x:n.x-r.x,y:n.y-r.y},dragStatus:"ready",pointerId:t})}startDrag(e,t=!0){Z._dragElements.has(this._id)||this._createDragElement(e);const i=Z._dragElements.get(this._id);i.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:e&&e.evt},t)}_setDragPosition(e,t){const i=this.getStage()._getPointerById(t.pointerId);if(!i)return;let r={x:i.x-t.offset.x,y:i.y-t.offset.y};const n=this.dragBoundFunc();if(n!==void 0){const s=n.call(this,r,e);s?r=s:b.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==r.x||this._lastPos.y!==r.y)&&(this.setAbsolutePosition(r),this._requestDraw()),this._lastPos=r}stopDrag(e){const t=Z._dragElements.get(this._id);t&&(t.dragStatus="stopped"),Z._endDragBefore(e),Z._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=Z._dragElements.get(this._id);return e?e.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(e){if(!(!(e.evt.button!==void 0)||D.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let r=!1;Z._dragElements.forEach(n=>{this.isAncestorOf(n.node)&&(r=!0)}),r||this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=Z._dragElements.get(this._id),i=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";i?this.stopDrag():r&&Z._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(e={x:0,y:0}){const t=this.getStage();if(!t)return!1;const i={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return b.haveIntersection(i,this.getClientRect())}static create(e,t){return b._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let i=L.prototype.getClassName.call(e),r=e.children,n,s,o;t&&(e.attrs.container=t),D[i]||(b.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=D[i];if(n=new l(e.attrs),r)for(s=r.length,o=0;o<s;o++)n.add(L._createNode(r[o]));return n}}L.protoListenerMap=new Map;L.prototype.nodeType="Node";L.prototype._attrsAffectingSize=[];L.prototype.eventListeners={};L.prototype.on.call(L.prototype,Io,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache($e),this._clearSelfAndDescendantCache(De)});L.prototype.on.call(L.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(mr)});L.prototype.on.call(L.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(fr)});L.prototype.on.call(L.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Ai)});const ee=m.addGetterSetter;ee(L,"zIndex");ee(L,"absolutePosition");ee(L,"position");ee(L,"x",0,R());ee(L,"y",0,R());ee(L,"globalCompositeOperation","source-over",ct());ee(L,"opacity",1,R());ee(L,"name","",ct());ee(L,"id","",ct());ee(L,"rotation",0,R());m.addComponentsGetterSetter(L,"scale",["x","y"]);ee(L,"scaleX",1,R());ee(L,"scaleY",1,R());m.addComponentsGetterSetter(L,"skew",["x","y"]);ee(L,"skewX",0,R());ee(L,"skewY",0,R());m.addComponentsGetterSetter(L,"offset",["x","y"]);ee(L,"offsetX",0,R());ee(L,"offsetY",0,R());ee(L,"dragDistance",void 0,R());ee(L,"width",0,R());ee(L,"height",0,R());ee(L,"listening",!0,xe());ee(L,"preventDefault",!0,xe());ee(L,"filters",void 0,function(a){return this._filterUpToDate=!1,a});ee(L,"visible",!0,xe());ee(L,"transformsEnabled","all",ct());ee(L,"size");ee(L,"dragBoundFunc");ee(L,"draggable",!1,xe());m.backCompat(L,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class Ce extends L{constructor(){super(...arguments),this.children=[]}getChildren(e){const t=this.children||[];return e?t.filter(e):t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let i=0;i<e.length;i++)this.add(e[i]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const i=[];return this._descendants(r=>{const n=r._isMatch(e);return n&&i.push(r),!!(n&&t)}),i}_descendants(e){let t=!1;const i=this.getChildren();for(const r of i){if(t=e(r),t)return!0;if(r.hasChildren()&&(t=r._descendants(e),t))return!0}return!1}toObject(){const e=L.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=L.prototype.clone.call(this,e);return this.getChildren().forEach(function(i){t.add(i.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(i=>{i.isVisible()&&i.intersects(e)&&t.push(i)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(i){i._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,i){t.index=i}),this._requestDraw()}drawScene(e,t,i){const r=this.getLayer(),n=e||r&&r.getCanvas(),s=n&&n.getContext(),o=this._getCanvasCache(),l=o&&o.scene,c=n&&n.isCache;if(!this.isVisible()&&!c)return this;if(l){s.save();const h=this.getAbsoluteTransform(t).getMatrix();s.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(s),s.restore()}else this._drawChildren("drawScene",n,t,i);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const i=this.getLayer(),r=e||i&&i.hitCanvas,n=r&&r.getContext(),s=this._getCanvasCache();if(s&&s.hit){n.save();const l=this.getAbsoluteTransform(t).getMatrix();n.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(n),n.restore()}else this._drawChildren("drawHit",r,t);return this}_drawChildren(e,t,i,r){var n;const s=t&&t.getContext(),o=this.clipWidth(),l=this.clipHeight(),c=this.clipFunc(),h=typeof o=="number"&&typeof l=="number"||c,d=i===this;if(h){s.save();const g=this.getAbsoluteTransform(i);let f=g.getMatrix();s.transform(f[0],f[1],f[2],f[3],f[4],f[5]),s.beginPath();let y;if(c)y=c.call(this,s,this);else{const S=this.clipX(),C=this.clipY();s.rect(S||0,C||0,o,l)}s.clip.apply(s,y),f=g.copy().invert().getMatrix(),s.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";u&&(s.save(),s._applyGlobalCompositeOperation(this)),(n=this.children)===null||n===void 0||n.forEach(function(g){g[e](t,i,r)}),u&&s.restore(),h&&s.restore()}getClientRect(e={}){var t;const i=e.skipTransform,r=e.relativeTo;let n,s,o,l,c={x:1/0,y:1/0,width:0,height:0};const h=this;(t=this.children)===null||t===void 0||t.forEach(function(g){if(!g.visible())return;const f=g.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});f.width===0&&f.height===0||(n===void 0?(n=f.x,s=f.y,o=f.x+f.width,l=f.y+f.height):(n=Math.min(n,f.x),s=Math.min(s,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 g=0;g<d.length;g++)if(d[g]._isVisible(this)){u=!0;break}return u&&n!==void 0?c={x:n,y:s,width:o-n,height:l-s}:c={x:0,y:0,width:0,height:0},i?c:this._transformedRect(c,r)}}m.addComponentsGetterSetter(Ce,"clip",["x","y","width","height"]);m.addGetterSetter(Ce,"clipX",void 0,R());m.addGetterSetter(Ce,"clipY",void 0,R());m.addGetterSetter(Ce,"clipWidth",void 0,R());m.addGetterSetter(Ce,"clipHeight",void 0,R());m.addGetterSetter(Ce,"clipFunc");const ti=new Map,ws=D._global.PointerEvent!==void 0;function Ji(a){return ti.get(a)}function Vr(a){return{evt:a,pointerId:a.pointerId}}function ks(a,e){return ti.get(a)===e}function xs(a,e){Vt(a),e.getStage()&&(ti.set(a,e),ws&&e._fire("gotpointercapture",Vr(new PointerEvent("gotpointercapture"))))}function Vt(a,e){const t=ti.get(a);if(!t)return;const i=t.getStage();i&&i.content,ti.delete(a),ws&&t._fire("lostpointercapture",Vr(new PointerEvent("lostpointercapture")))}const Eo="Stage",Lo="string",cn="px",Ro="mouseout",Ps="mouseleave",_s="mouseover",Is="mouseenter",As="mousemove",Es="mousedown",Ls="mouseup",Gt="pointermove",Ft="pointerdown",St="pointerup",Ht="pointercancel",Do="lostpointercapture",yi="pointerout",Nt="pointerleave",Si="pointerover",Ci="pointerenter",yr="contextmenu",Rs="touchstart",Ds="touchend",Ms="touchmove",Os="touchcancel",Sr="wheel",Mo=5,Oo=[[Is,"_pointerenter"],[Es,"_pointerdown"],[As,"_pointermove"],[Ls,"_pointerup"],[Ps,"_pointerleave"],[Rs,"_pointerdown"],[Ms,"_pointermove"],[Ds,"_pointerup"],[Os,"_pointercancel"],[_s,"_pointerover"],[Sr,"_wheel"],[yr,"_contextmenu"],[Ft,"_pointerdown"],[Gt,"_pointermove"],[St,"_pointerup"],[Ht,"_pointercancel"],[Nt,"_pointerleave"],[Do,"_lostpointercapture"]],Qi={mouse:{[yi]:Ro,[Nt]:Ps,[Si]:_s,[Ci]:Is,[Gt]:As,[Ft]:Es,[St]:Ls,[Ht]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[yi]:"touchout",[Nt]:"touchleave",[Si]:"touchover",[Ci]:"touchenter",[Gt]:Ms,[Ft]:Rs,[St]:Ds,[Ht]:Os,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[yi]:yi,[Nt]:Nt,[Si]:Si,[Ci]:Ci,[Gt]:Gt,[Ft]:Ft,[St]:St,[Ht]:Ht,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},$t=a=>a.indexOf("pointer")>=0?"pointer":a.indexOf("touch")>=0?"touch":"mouse",gt=a=>{const e=$t(a);if(e==="pointer")return D.pointerEventsEnabled&&Qi.pointer;if(e==="touch")return Qi.touch;if(e==="mouse")return Qi.mouse};function hn(a={}){return(a.clipFunc||a.clipWidth||a.clipHeight)&&b.warn("Stage does not support clipping. Please use clip for Layers or Groups."),a}const Bo="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);",Ut=[];class Xi extends Ce{constructor(e){super(hn(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),Ut.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{hn(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",i=e.getType()==="FastLayer";t||i||b.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const e=this.visible()?"":"none";this.content.style.display=e}setContainer(e){if(typeof e===Lo){let t;if(e.charAt(0)==="."){const i=e.slice(1);e=document.getElementsByClassName(i)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),Ce.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&b._isInDocument(e)&&this.container().removeChild(e);const t=Ut.indexOf(this);return t>-1&&Ut.splice(t,1),b.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const e=this._pointerPositions[0]||this._changedPointerPositions[0];return e?{x:e.x,y:e.y}:(b.warn(Bo),null)}_getPointerById(e){return this._pointerPositions.find(t=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();const t=new Ue({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),i=t.getContext()._context,r=this.children;return(e.x||e.y)&&i.translate(-1*e.x,-1*e.y),r.forEach(function(n){if(!n.isVisible())return;const s=n._toKonvaCanvas(e);i.drawImage(s._canvas,e.x,e.y,s.getWidth()/s.getPixelRatio(),s.getHeight()/s.getPixelRatio())}),t}getIntersection(e){if(!e)return null;const t=this.children,i=t.length,r=i-1;for(let n=r;n>=0;n--){const s=t[n].getIntersection(e);if(s)return s}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+cn,this.content.style.height=t+cn),this.bufferCanvas.setSize(e,t),this.bufferHitCanvas.setSize(e,t),this.children.forEach(i=>{i.setSize({width:e,height:t}),i.draw()})}add(e,...t){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.add(arguments[r]);return this}super.add(e);const i=this.children.length;return i>Mo&&b.warn("The stage has "+i+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),D.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return ks(e,this)}setPointerCapture(e){xs(e,this)}releaseCapture(e){Vt(e)}getLayers(){return this.children}_bindContentEvents(){D.isBrowser&&Oo.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=gt(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=gt(e.type);t&&this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];return t&&!t.getStage()&&(t=null),t}_pointerleave(e){const t=gt(e.type),i=$t(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(i),n=!(D.isDragging()||D.isTransforming())||D.hitOnDragEnabled;r&&n?(r._fireAndBubble(t.pointerout,{evt:e}),r._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[i+"targetShape"]=null):n&&(this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){const t=gt(e.type),i=$t(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(n=>{const s=this.getIntersection(n);if(Z.justDragged=!1,D["_"+i+"ListenClick"]=!0,!s||!s.isListening()){this[i+"ClickStartShape"]=void 0;return}D.capturePointerEventsEnabled&&s.setPointerCapture(n.id),this[i+"ClickStartShape"]=s,s._fireAndBubble(t.pointerdown,{evt:e,pointerId:n.id}),r=!0;const o=e.type.indexOf("touch")>=0;s.preventDefault()&&e.cancelable&&o&&e.preventDefault()}),r||this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){const t=gt(e.type),i=$t(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(D.isDragging()&&Z.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(D.isDragging()||D.isTransforming())||D.hitOnDragEnabled))return;const s={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(c=>{const h=Ji(c.id)||this.getIntersection(c),d=c.id,u={evt:e,pointerId:d},g=l!==h;if(g&&l&&(l._fireAndBubble(t.pointerout,{...u},h),l._fireAndBubble(t.pointerleave,{...u},h)),h){if(s[h._id])return;s[h._id]=!0}h&&h.isListening()?(o=!0,g&&(h._fireAndBubble(t.pointerover,{...u},l),h._fireAndBubble(t.pointerenter,{...u},l),this[i+"targetShape"]=h),h._fireAndBubble(t.pointermove,{...u})):l&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:d}),this[i+"targetShape"]=null)}),o||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=gt(e.type),i=$t(e.type);if(!t)return;this.setPointersPositions(e);const r=this[i+"ClickStartShape"],n=this[i+"ClickEndShape"],s={};let o=!1;this._changedPointerPositions.forEach(l=>{const c=Ji(l.id)||this.getIntersection(l);if(c){if(c.releaseCapture(l.id),s[c._id])return;s[c._id]=!0}const h=l.id,d={evt:e,pointerId:h};let u=!1;D["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):Z.justDragged||(D["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){D["_"+i+"InDblClickWindow"]=!1},D.dblClickWindow),c&&c.isListening()?(o=!0,this[i+"ClickEndShape"]=c,c._fireAndBubble(t.pointerup,{...d}),D["_"+i+"ListenClick"]&&r&&r===c&&(c._fireAndBubble(t.pointerclick,{...d}),u&&n&&n===c&&c._fireAndBubble(t.pointerdblclick,{...d}))):(this[i+"ClickEndShape"]=null,o||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),D["_"+i+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:h}),u&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:h}))}),o||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),D["_"+i+"ListenClick"]=!1,e.cancelable&&i!=="touch"&&i!=="pointer"&&e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(yr,{evt:e}):this._fire(yr,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Sr,{evt:e}):this._fire(Sr,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=Ji(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(St,Vr(e)),Vt(e.pointerId)}_lostpointercapture(e){Vt(e.pointerId)}setPointersPositions(e){const t=this._getContentPosition();let i=null,r=null;e=e||window.event,e.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,n=>{this._pointerPositions.push({id:n.identifier,x:(n.clientX-t.left)/t.scaleX,y:(n.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,n=>{this._changedPointerPositions.push({id:n.identifier,x:(n.clientX-t.left)/t.scaleX,y:(n.clientY-t.top)/t.scaleY})})):(i=(e.clientX-t.left)/t.scaleX,r=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:i,y:r},this._pointerPositions=[{x:i,y:r,id:b._getFirstPointerId(e)}],this._changedPointerPositions=[{x:i,y:r,id:b._getFirstPointerId(e)}])}_setPointerPosition(e){b.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new Ue({width:this.width(),height:this.height()}),this.bufferHitCanvas=new $r({pixelRatio:1,width:this.width(),height:this.height()}),!D.isBrowser)return;const e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),this._resizeDOM()}cache(){return b.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}}Xi.prototype.nodeType=Eo;ae(Xi);m.addGetterSetter(Xi,"container");D.isBrowser&&document.addEventListener("visibilitychange",()=>{Ut.forEach(a=>{a.batchDraw()})});const Bs="hasShadow",Gs="shadowRGBA",Fs="patternImage",Hs="linearGradient",Ns="radialGradient";let vi;function er(){return vi||(vi=b.createCanvasElement().getContext("2d"),vi)}const Wt={};function Go(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function Fo(a){a.stroke()}function Ho(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function No(a){a.stroke()}function $o(){this._clearCache(Bs)}function zo(){this._clearCache(Gs)}function Vo(){this._clearCache(Fs)}function Uo(){this._clearCache(Hs)}function Wo(){this._clearCache(Ns)}class _ extends L{constructor(e){super(e);let t,i=0;for(;t=b.getHitColor(),!(t&&!(t in Wt));)if(i++,i>=1e4){b.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=b.getRandomColor();break}this.colorKey=t,Wt[t]=this}getContext(){return b.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return b.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(Bs,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(Fs,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=er().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new Se;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(D.getAngle(this.fillPatternRotation())),i.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),i.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const r=i.getMatrix(),n=typeof DOMMatrix>"u"?{a:r[0],b:r[1],c:r[2],d:r[3],e:r[4],f:r[5]}:new DOMMatrix(r);t.setTransform(n)}return t}}_getLinearGradient(){return this._getCache(Hs,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=er(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),n=t.createLinearGradient(i.x,i.y,r.x,r.y);for(let s=0;s<e.length;s+=2)n.addColorStop(e[s],e[s+1]);return n}}_getRadialGradient(){return this._getCache(Ns,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=er(),i=this.fillRadialGradientStartPoint(),r=this.fillRadialGradientEndPoint(),n=t.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),r.x,r.y,this.fillRadialGradientEndRadius());for(let s=0;s<e.length;s+=2)n.addColorStop(e[s],e[s+1]);return n}}getShadowRGBA(){return this._getCache(Gs,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=b.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const e=this.hitStrokeWidth();return e==="auto"?this.hasStroke():this.strokeEnabled()&&!!e}intersects(e){const t=this.getStage();if(!t)return!1;const i=t.bufferHitCanvas;return i.getContext().clear(),this.drawHit(i,void 0,!0),i.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return L.prototype.destroy.call(this),delete Wt[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0?t:!0))return!1;const r=e||this.hasFill(),n=this.hasStroke(),s=this.getAbsoluteOpacity()!==1;if(r&&n&&s)return!0;const o=this.hasShadow(),l=this.shadowForStrokeEnabled();return!!(r&&n&&o&&l)}setStrokeHitEnabled(e){b.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,i=this.getParent();for(;i;){if(i.isCached()){t=!0;break}i=i.getParent()}const r=e.skipTransform,n=e.relativeTo||t&&this.getStage()||void 0,s=this.getSelfRect(),l=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,c=s.width+l,h=s.height+l,d=!e.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,g=d?this.shadowOffsetY():0,f=c+Math.abs(u),y=h+Math.abs(g),S=d&&this.shadowBlur()||0,C=f+S*2,T=y+S*2,v={width:C,height:T,x:-(l/2+S)+Math.min(u,0)+s.x,y:-(l/2+S)+Math.min(g,0)+s.y};return r?v:this._transformedRect(v,n)}drawScene(e,t,i){const r=this.getLayer(),n=e||r.getCanvas(),s=n.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),c=this.hasShadow();let h;const d=t===this;if(!this.isVisible()&&!d)return this;if(o){s.save();const u=this.getAbsoluteTransform(t).getMatrix();return s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(s),s.restore(),this}if(!l)return this;if(s.save(),this._useBufferCanvas()){h=this.getStage();const u=i||h.bufferCanvas,g=u.getContext();i?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,u.width,u.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const f=this.getAbsoluteTransform(t).getMatrix();g.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.call(this,g,this),g.restore();const y=u.pixelRatio;c&&s._applyShadow(this),d||(s._applyOpacity(this),s._applyGlobalCompositeOperation(this)),s.drawImage(u._canvas,u.x||0,u.y||0,u.width/y,u.height/y)}else{if(s._applyLineJoin(this),s._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(t).getMatrix();s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),s._applyOpacity(this),s._applyGlobalCompositeOperation(this)}c&&s._applyShadow(this),l.call(this,s,this)}return s.restore(),this}drawHit(e,t,i=!1){if(!this.shouldDrawHit(t,i))return this;const r=this.getLayer(),n=e||r.hitCanvas,s=n&&n.getContext(),o=this.hitFunc()||this.sceneFunc(),l=this._getCanvasCache(),c=l&&l.hit;if(this.colorKey||b.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()"),c){s.save();const d=this.getAbsoluteTransform(t).getMatrix();return s.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(s),s.restore(),this}if(!o)return this;if(s.save(),s._applyLineJoin(this),s._applyMiterLimit(this),!(this===t)){const d=this.getAbsoluteTransform(t).getMatrix();s.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,s,this),s.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),i=this._getCachedSceneCanvas(),r=t.hit,n=r.getContext(),s=r.getWidth(),o=r.getHeight();n.clear(),n.drawImage(i._canvas,0,0,s,o);try{const l=n.getImageData(0,0,s,o),c=l.data,h=c.length,d=b._hexToRgb(this.colorKey);for(let u=0;u<h;u+=4)c[u+3]>e?(c[u]=d.r,c[u+1]=d.g,c[u+2]=d.b,c[u+3]=255):c[u+3]=0;n.putImageData(l,0,0)}catch(l){b.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(e){return ks(e,this)}setPointerCapture(e){xs(e,this)}releaseCapture(e){Vt(e)}}_.prototype._fillFunc=Go;_.prototype._strokeFunc=Fo;_.prototype._fillFuncHit=Ho;_.prototype._strokeFuncHit=No;_.prototype._centroid=!1;_.prototype.nodeType="Shape";ae(_);_.prototype.eventListeners={};_.prototype.on.call(_.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",$o);_.prototype.on.call(_.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",zo);_.prototype.on.call(_.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Vo);_.prototype.on.call(_.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Uo);_.prototype.on.call(_.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Wo);m.addGetterSetter(_,"stroke",void 0,bs());m.addGetterSetter(_,"strokeWidth",2,R());m.addGetterSetter(_,"fillAfterStrokeEnabled",!1);m.addGetterSetter(_,"hitStrokeWidth","auto",zr());m.addGetterSetter(_,"strokeHitEnabled",!0,xe());m.addGetterSetter(_,"perfectDrawEnabled",!0,xe());m.addGetterSetter(_,"shadowForStrokeEnabled",!0,xe());m.addGetterSetter(_,"lineJoin");m.addGetterSetter(_,"lineCap");m.addGetterSetter(_,"miterLimit");m.addGetterSetter(_,"sceneFunc");m.addGetterSetter(_,"hitFunc");m.addGetterSetter(_,"dash");m.addGetterSetter(_,"dashOffset",0,R());m.addGetterSetter(_,"shadowColor",void 0,ct());m.addGetterSetter(_,"shadowBlur",0,R());m.addGetterSetter(_,"shadowOpacity",1,R());m.addComponentsGetterSetter(_,"shadowOffset",["x","y"]);m.addGetterSetter(_,"shadowOffsetX",0,R());m.addGetterSetter(_,"shadowOffsetY",0,R());m.addGetterSetter(_,"fillPatternImage");m.addGetterSetter(_,"fill",void 0,bs());m.addGetterSetter(_,"fillPatternX",0,R());m.addGetterSetter(_,"fillPatternY",0,R());m.addGetterSetter(_,"fillLinearGradientColorStops");m.addGetterSetter(_,"strokeLinearGradientColorStops");m.addGetterSetter(_,"fillRadialGradientStartRadius",0);m.addGetterSetter(_,"fillRadialGradientEndRadius",0);m.addGetterSetter(_,"fillRadialGradientColorStops");m.addGetterSetter(_,"fillPatternRepeat","repeat");m.addGetterSetter(_,"fillEnabled",!0);m.addGetterSetter(_,"strokeEnabled",!0);m.addGetterSetter(_,"shadowEnabled",!0);m.addGetterSetter(_,"dashEnabled",!0);m.addGetterSetter(_,"strokeScaleEnabled",!0);m.addGetterSetter(_,"fillPriority","color");m.addComponentsGetterSetter(_,"fillPatternOffset",["x","y"]);m.addGetterSetter(_,"fillPatternOffsetX",0,R());m.addGetterSetter(_,"fillPatternOffsetY",0,R());m.addComponentsGetterSetter(_,"fillPatternScale",["x","y"]);m.addGetterSetter(_,"fillPatternScaleX",1,R());m.addGetterSetter(_,"fillPatternScaleY",1,R());m.addComponentsGetterSetter(_,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(_,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(_,"fillLinearGradientStartPointX",0);m.addGetterSetter(_,"strokeLinearGradientStartPointX",0);m.addGetterSetter(_,"fillLinearGradientStartPointY",0);m.addGetterSetter(_,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(_,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(_,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(_,"fillLinearGradientEndPointX",0);m.addGetterSetter(_,"strokeLinearGradientEndPointX",0);m.addGetterSetter(_,"fillLinearGradientEndPointY",0);m.addGetterSetter(_,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(_,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(_,"fillRadialGradientStartPointX",0);m.addGetterSetter(_,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(_,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(_,"fillRadialGradientEndPointX",0);m.addGetterSetter(_,"fillRadialGradientEndPointY",0);m.addGetterSetter(_,"fillPatternRotation",0);m.addGetterSetter(_,"fillRule",void 0,ct());m.backCompat(_,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Yo="beforeDraw",Xo="draw",$s=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],qo=$s.length;class ht extends Ce{constructor(e){super(e),this.canvas=new Ue,this.hitCanvas=new $r({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){L.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!L.prototype.moveUp.call(this))return!1;const t=this.getStage();return!t||!t.content?!1:(t.content.removeChild(this.getNativeCanvasElement()),this.index<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[this.index+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(L.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(L.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return L.prototype.remove.call(this),e&&e.parentNode&&b._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),L.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){b.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){b.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,b.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,i=!1;for(;;){for(let r=0;r<qo;r++){const n=$s[r],s=this._getIntersection({x:e.x+n.x*t,y:e.y+n.y*t}),o=s.shape;if(o)return o;if(i=!!s.antialiased,!s.antialiased)break}if(i)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,i=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,r=i[3];if(r===255){const n=b.getHitColorKey(i[0],i[1],i[2]),s=Wt[n];return s?{shape:s}:{antialiased:!0}}else if(r>0)return{antialiased:!0};return{}}drawScene(e,t,i){const r=this.getLayer(),n=e||r&&r.getCanvas();return this._fire(Yo,{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),Ce.prototype.drawScene.call(this,n,t,i),this._fire(Xo,{node:this}),this}drawHit(e,t){const i=this.getLayer(),r=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),Ce.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;!!this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return b.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}ht.prototype.nodeType="Layer";ae(ht);m.addGetterSetter(ht,"imageSmoothingEnabled",!0);m.addGetterSetter(ht,"clearBeforeDraw",!0);m.addGetterSetter(ht,"hitGraphEnabled",!0,xe());class Ur extends ht{constructor(e){super(e),this.listening(!1),b.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}Ur.prototype.nodeType="FastLayer";ae(Ur);class bt extends Ce{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to groups.")}}bt.prototype.nodeType="Group";ae(bt);const tr=function(){return rt.performance&&rt.performance.now?function(){return rt.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:tr(),frameRate:0},this.func=e,this.setLayers(t)}setLayers(e){let t=[];return e&&(t=Array.isArray(e)?e:[e]),this.layers=t,this}getLayers(){return this.layers}addLayer(e){const t=this.layers,i=t.length;for(let r=0;r<i;r++)if(t[r]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){const t=we.animations,i=t.length;for(let r=0;r<i;r++)if(t[r].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=tr(),we._addAnimation(this),this}stop(){return we._removeAnimation(this),this}_updateFrameObject(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(e){this.animations.push(e),this._handleAnimation()}static _removeAnimation(e){const t=e.id,i=this.animations,r=i.length;for(let n=0;n<r;n++)if(i[n].id===t){this.animations.splice(n,1);break}}static _runFrames(){const e={},t=this.animations;for(let i=0;i<t.length;i++){const r=t[i],n=r.layers,s=r.func;r._updateFrameObject(tr());const o=n.length;let l;if(s?l=s.call(r,r.frame)!==!1:l=!0,!!l)for(let c=0;c<o;c++){const h=n[c];h._id!==void 0&&(e[h._id]=h)}}for(const i in e)e.hasOwnProperty(i)&&e[i].batchDraw()}static _animationLoop(){const e=we;e.animations.length?(e._runFrames(),b.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,b.requestAnimFrame(this._animationLoop))}}we.animations=[];we.animIdCounter=0;we.animRunning=!1;const jo={node:1,duration:1,easing:1,onFinish:1,yoyo:1},Ko=1,dn=2,un=3,pn=["fill","stroke","shadowColor"];let Zo=0;class Jo{constructor(e,t,i,r,n,s,o){this.prop=e,this.propFunc=t,this.begin=r,this._pos=r,this.duration=s,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(e){const t=this[e];t&&t()}setTime(e){e>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():e<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=e,this.update())}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){return e===void 0&&(e=this._time),this.func(e,this.begin,this._change,this.duration)}play(){this.state=dn,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=un,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const e=this.getTimer()-this._startTime;this.state===dn?this.setTime(e):this.state===un&&this.setTime(this.duration-e)}pause(){this.state=Ko,this.fire("onPause")}getTimer(){return new Date().getTime()}}class te{constructor(e){const t=this,i=e.node,r=i._id,n=e.easing||Yt.Linear,s=!!e.yoyo;let o,l;typeof e.duration>"u"?o=.3:e.duration===0?o=.001:o=e.duration,this.node=i,this._id=Zo++;const c=i.getLayer()||(i instanceof D.Stage?i.getLayers():null);c||b.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new we(function(){t.tween.onEnterFrame()},c),this.tween=new Jo(l,function(h){t._tweenFunc(h)},n,0,1,o*1e3,s),this._addListeners(),te.attrs[r]||(te.attrs[r]={}),te.attrs[r][this._id]||(te.attrs[r][this._id]={}),te.tweens[r]||(te.tweens[r]={});for(l in e)jo[l]===void 0&&this._addAttr(l,e[l]);this.reset(),this.onFinish=e.onFinish,this.onReset=e.onReset,this.onUpdate=e.onUpdate}_addAttr(e,t){const i=this.node,r=i._id;let n,s,o,l,c;const h=te.tweens[r][e];h&&delete te.attrs[r][h][e];let d=i.getAttr(e);if(b._isArray(t))if(n=[],s=Math.max(t.length,d.length),e==="points"&&t.length!==d.length&&(t.length>d.length?(l=d,d=b._prepareArrayForTween(d,t,i.closed())):(o=t,t=b._prepareArrayForTween(t,d,i.closed()))),e.indexOf("fill")===0)for(let u=0;u<s;u++)if(u%2===0)n.push(t[u]-d[u]);else{const g=b.colorToRGBA(d[u]);c=b.colorToRGBA(t[u]),d[u]=g,n.push({r:c.r-g.r,g:c.g-g.g,b:c.b-g.b,a:c.a-g.a})}else for(let u=0;u<s;u++)n.push(t[u]-d[u]);else pn.indexOf(e)!==-1?(d=b.colorToRGBA(d),c=b.colorToRGBA(t),n={r:c.r-d.r,g:c.g-d.g,b:c.b-d.b,a:c.a-d.a}):n=t-d;te.attrs[r][this._id][e]={start:d,diff:n,end:t,trueEnd:o,trueStart:l},te.tweens[r][e]=this._id}_tweenFunc(e){const t=this.node,i=te.attrs[t._id][this._id];let r,n,s,o,l,c,h,d;for(r in i){if(n=i[r],s=n.start,o=n.diff,d=n.end,b._isArray(s))if(l=[],h=Math.max(s.length,d.length),r.indexOf("fill")===0)for(c=0;c<h;c++)c%2===0?l.push((s[c]||0)+o[c]*e):l.push("rgba("+Math.round(s[c].r+o[c].r*e)+","+Math.round(s[c].g+o[c].g*e)+","+Math.round(s[c].b+o[c].b*e)+","+(s[c].a+o[c].a*e)+")");else for(c=0;c<h;c++)l.push((s[c]||0)+o[c]*e);else pn.indexOf(r)!==-1?l="rgba("+Math.round(s.r+o.r*e)+","+Math.round(s.g+o.g*e)+","+Math.round(s.b+o.b*e)+","+(s.a+o.a*e)+")":l=s+o*e;t.setAttr(r,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const e=this.node,t=te.attrs[e._id][this._id];t.points&&t.points.trueEnd&&e.setAttr("points",t.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const e=this.node,t=te.attrs[e._id][this._id];t.points&&t.points.trueStart&&e.points(t.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(e){return this.tween.seek(e*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const e=this.node._id,t=this._id,i=te.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const r in i)delete te.tweens[e][r];delete te.attrs[e][t],te.tweens[e]&&(Object.keys(te.tweens[e]).length===0&&delete te.tweens[e],Object.keys(te.attrs[e]).length===0&&delete te.attrs[e])}}te.attrs={};te.tweens={};L.prototype.to=function(a){const e=a.onFinish;a.node=this,a.onFinish=function(){this.destroy(),e&&e()},new te(a).play()};const Yt={BackEaseIn(a,e,t,i){return t*(a/=i)*a*((1.70158+1)*a-1.70158)+e},BackEaseOut(a,e,t,i){return t*((a=a/i-1)*a*((1.70158+1)*a+1.70158)+1)+e},BackEaseInOut(a,e,t,i){let r=1.70158;return(a/=i/2)<1?t/2*(a*a*(((r*=1.525)+1)*a-r))+e:t/2*((a-=2)*a*(((r*=1.525)+1)*a+r)+2)+e},ElasticEaseIn(a,e,t,i,r,n){let s=0;return a===0?e:(a/=i)===1?e+t:(n||(n=i*.3),!r||r<Math.abs(t)?(r=t,s=n/4):s=n/(2*Math.PI)*Math.asin(t/r),-(r*Math.pow(2,10*(a-=1))*Math.sin((a*i-s)*(2*Math.PI)/n))+e)},ElasticEaseOut(a,e,t,i,r,n){let s=0;return a===0?e:(a/=i)===1?e+t:(n||(n=i*.3),!r||r<Math.abs(t)?(r=t,s=n/4):s=n/(2*Math.PI)*Math.asin(t/r),r*Math.pow(2,-10*a)*Math.sin((a*i-s)*(2*Math.PI)/n)+t+e)},ElasticEaseInOut(a,e,t,i,r,n){let s=0;return a===0?e:(a/=i/2)===2?e+t:(n||(n=i*(.3*1.5)),!r||r<Math.abs(t)?(r=t,s=n/4):s=n/(2*Math.PI)*Math.asin(t/r),a<1?-.5*(r*Math.pow(2,10*(a-=1))*Math.sin((a*i-s)*(2*Math.PI)/n))+e:r*Math.pow(2,-10*(a-=1))*Math.sin((a*i-s)*(2*Math.PI)/n)*.5+t+e)},BounceEaseOut(a,e,t,i){return(a/=i)<1/2.75?t*(7.5625*a*a)+e:a<2/2.75?t*(7.5625*(a-=1.5/2.75)*a+.75)+e:a<2.5/2.75?t*(7.5625*(a-=2.25/2.75)*a+.9375)+e:t*(7.5625*(a-=2.625/2.75)*a+.984375)+e},BounceEaseIn(a,e,t,i){return t-Yt.BounceEaseOut(i-a,0,t,i)+e},BounceEaseInOut(a,e,t,i){return a<i/2?Yt.BounceEaseIn(a*2,0,t,i)*.5+e:Yt.BounceEaseOut(a*2-i,0,t,i)*.5+t*.5+e},EaseIn(a,e,t,i){return t*(a/=i)*a+e},EaseOut(a,e,t,i){return-t*(a/=i)*(a-2)+e},EaseInOut(a,e,t,i){return(a/=i/2)<1?t/2*a*a+e:-t/2*(--a*(a-2)-1)+e},StrongEaseIn(a,e,t,i){return t*(a/=i)*a*a*a*a+e},StrongEaseOut(a,e,t,i){return t*((a=a/i-1)*a*a*a*a+1)+e},StrongEaseInOut(a,e,t,i){return(a/=i/2)<1?t/2*a*a*a*a*a+e:t/2*((a-=2)*a*a*a*a+2)+e},Linear(a,e,t,i){return t*a/i+e}},gn=b._assign(D,{Util:b,Transform:Se,Node:L,Container:Ce,Stage:Xi,stages:Ut,Layer:ht,FastLayer:Ur,Group:bt,DD:Z,Shape:_,shapes:Wt,Animation:we,Tween:te,Easings:Yt,Context:Wi,Canvas:Nr});class Me extends _{_sceneFunc(e){const t=D.getAngle(this.angle()),i=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,i),e.arc(0,0,this.innerRadius(),t,0,!i),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),i=this.clockwise(),r=D.getAngle(i?360-this.angle():this.angle()),n=Math.cos(Math.min(r,Math.PI)),s=1,o=Math.sin(Math.min(Math.max(Math.PI,r),3*Math.PI/2)),l=Math.sin(Math.min(r,Math.PI/2)),c=n*(n>0?e:t),h=s*t,d=o*(o>0?e:t),u=l*(l>0?t:e);return{x:c,y:i?-1*u:d,width:h-c,height:u-d}}}Me.prototype._centroid=!0;Me.prototype.className="Arc";Me.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];ae(Me);m.addGetterSetter(Me,"innerRadius",0,R());m.addGetterSetter(Me,"outerRadius",0,R());m.addGetterSetter(Me,"angle",0,R());m.addGetterSetter(Me,"clockwise",!1,xe());function Cr(a,e,t,i,r,n,s){const o=Math.sqrt(Math.pow(t-a,2)+Math.pow(i-e,2)),l=Math.sqrt(Math.pow(r-t,2)+Math.pow(n-i,2)),c=s*o/(o+l),h=s*l/(o+l),d=t-c*(r-a),u=i-c*(n-e),g=t+h*(r-a),f=i+h*(n-e);return[d,u,g,f]}function fn(a,e){const t=a.length,i=[];for(let r=2;r<t-2;r+=2){const n=Cr(a[r-2],a[r-1],a[r],a[r+1],a[r+2],a[r+3],e);isNaN(n[0])||(i.push(n[0]),i.push(n[1]),i.push(a[r]),i.push(a[r+1]),i.push(n[2]),i.push(n[3]))}return i}function Qo(a){const e=[[a[0],a[2],a[4],a[6]],[a[1],a[3],a[5],a[7]]],t=[];for(const i of e){const r=-3*i[0]+9*i[1]-9*i[2]+3*i[3];if(r!==0){const n=6*i[0]-12*i[1]+6*i[2],s=-3*i[0]+3*i[1],o=n*n-4*r*s;if(o>=0){const l=Math.sqrt(o);t.push((-n+l)/(2*r)),t.push((-n-l)/(2*r))}}}return t.filter(i=>i>0&&i<1).flatMap(i=>e.map(r=>{const n=1-i;return n*n*n*r[0]+3*n*n*i*r[1]+3*n*i*i*r[2]+i*i*i*r[3]}))}class Oe extends _{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),i=t.length,r=this.tension(),n=this.closed(),s=this.bezier();if(!i)return;let o=0;if(e.beginPath(),e.moveTo(t[0],t[1]),r!==0&&i>4){const l=this.getTensionPoints(),c=l.length;for(o=n?0:4,n||e.quadraticCurveTo(l[0],l[1],l[2],l[3]);o<c-2;)e.bezierCurveTo(l[o++],l[o++],l[o++],l[o++],l[o++],l[o++]);n||e.quadraticCurveTo(l[c-2],l[c-1],t[i-2],t[i-1])}else if(s)for(o=2;o<i;)e.bezierCurveTo(t[o++],t[o++],t[o++],t[o++],t[o++],t[o++]);else for(o=2;o<i;o+=2)e.lineTo(t[o],t[o+1]);n?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():fn(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=Cr(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),n=Cr(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),s=fn(e,i);return[r[2],r[3]].concat(s).concat([n[0],n[1],e[t-2],e[t-1],n[2],n[3],r[0],r[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:this.bezier()?e=[e[0],e[1],...Qo(this.points()),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],i=e[0],r=e[1],n=e[1],s,o;for(let l=0;l<e.length/2;l++)s=e[l*2],o=e[l*2+1],t=Math.min(t,s),i=Math.max(i,s),r=Math.min(r,o),n=Math.max(n,o);return{x:t,y:r,width:i-t,height:n-r}}}Oe.prototype.className="Line";Oe.prototype._attrsAffectingSize=["points","bezier","tension"];ae(Oe);m.addGetterSetter(Oe,"closed",!1);m.addGetterSetter(Oe,"bezier",!1);m.addGetterSetter(Oe,"tension",0,R());m.addGetterSetter(Oe,"points",[],fo());const el=[[],[],[-.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]],tl=[[],[],[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]],il=[[1],[1,1],[1,2,1],[1,3,3,1]],mn=(a,e,t)=>{let i,r;const s=t/2;i=0;for(let o=0;o<20;o++)r=s*el[20][o]+s,i+=tl[20][o]*rl(a,e,r);return s*i},yn=(a,e,t)=>{t===void 0&&(t=1);const i=a[0]-2*a[1]+a[2],r=e[0]-2*e[1]+e[2],n=2*a[1]-2*a[0],s=2*e[1]-2*e[0],o=4*(i*i+r*r),l=4*(i*n+r*s),c=n*n+s*s;if(o===0)return t*Math.sqrt(Math.pow(a[2]-a[0],2)+Math.pow(e[2]-e[0],2));const h=l/(2*o),d=c/o,u=t+h,g=d-h*h,f=u*u+g>0?Math.sqrt(u*u+g):0,y=h*h+g>0?Math.sqrt(h*h+g):0,S=h+Math.sqrt(h*h+g)!==0?g*Math.log(Math.abs((u+f)/(h+y))):0;return Math.sqrt(o)/2*(u*f-h*y+S)};function rl(a,e,t){const i=vr(1,t,a),r=vr(1,t,e),n=i*i+r*r;return Math.sqrt(n)}const vr=(a,e,t)=>{const i=t.length-1;let r,n;if(i===0)return 0;if(a===0){n=0;for(let s=0;s<=i;s++)n+=il[i][s]*Math.pow(1-e,i-s)*Math.pow(e,s)*t[s];return n}else{r=new Array(i);for(let s=0;s<i;s++)r[s]=i*(t[s+1]-t[s]);return vr(a-1,e,r)}},Sn=(a,e,t)=>{let i=1,r=a/e,n=(a-t(r))/e,s=0;for(;i>.001;){const o=t(r+n),l=Math.abs(a-o)/e;if(l<i)i=l,r+=n;else{const c=t(r-n),h=Math.abs(a-c)/e;h<i?(i=h,r-=n):n/=2}if(s++,s>500)break}return r};class ie extends _{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=ie.parsePathData(this.data()),this.pathLength=ie.getPathLength(this.dataArray)}_sceneFunc(e){const t=this.dataArray;e.beginPath();let i=!1;for(let r=0;r<t.length;r++){const n=t[r].command,s=t[r].points;switch(n){case"L":e.lineTo(s[0],s[1]);break;case"M":e.moveTo(s[0],s[1]);break;case"C":e.bezierCurveTo(s[0],s[1],s[2],s[3],s[4],s[5]);break;case"Q":e.quadraticCurveTo(s[0],s[1],s[2],s[3]);break;case"A":const o=s[0],l=s[1],c=s[2],h=s[3],d=s[4],u=s[5],g=s[6],f=s[7],y=c>h?c:h,S=c>h?1:c/h,C=c>h?h/c:1;e.translate(o,l),e.rotate(g),e.scale(S,C),e.arc(0,0,y,d,d+u,1-f),e.scale(1/S,1/C),e.rotate(-g),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const c=l.points[4],h=l.points[5],d=l.points[4]+h;let u=Math.PI/180;if(Math.abs(c-d)<u&&(u=Math.abs(c-d)),h<0)for(let g=c-u;g>d;g-=u){const f=ie.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}else for(let g=c+u;g<d;g+=u){const f=ie.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}}else if(l.command==="C")for(let c=0;c<=1;c+=.01){const h=ie.getPointOnCubicBezier(c,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);e.push(h.x,h.y)}else e=e.concat(l.points)});let t=e[0],i=e[0],r=e[1],n=e[1],s,o;for(let l=0;l<e.length/2;l++)s=e[l*2],o=e[l*2+1],isNaN(s)||(t=Math.min(t,s),i=Math.max(i,s)),isNaN(o)||(r=Math.min(r,o),n=Math.max(n,o));return{x:t,y:r,width:i-t,height:n-r}}getLength(){return this.pathLength}getPointAtLength(e){return ie.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,i,r){return Math.sqrt((i-e)*(i-e)+(r-t)*(r-t))}static getPathLength(e){let t=0;for(let i=0;i<e.length;++i)t+=e[i].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let i,r=0,n=t.length;if(!n)return null;for(;r<n&&e>t[r].pathLength;)e-=t[r].pathLength,++r;if(r===n)return i=t[r-1].points.slice(-2),{x:i[0],y:i[1]};if(e<.01)return t[r].command==="M"?(i=t[r].points.slice(0,2),{x:i[0],y:i[1]}):{x:t[r].start.x,y:t[r].start.y};const s=t[r],o=s.points;switch(s.command){case"L":return ie.getPointOnLine(e,s.start.x,s.start.y,o[0],o[1]);case"C":return ie.getPointOnCubicBezier(Sn(e,ie.getPathLength(t),y=>mn([s.start.x,o[0],o[2],o[4]],[s.start.y,o[1],o[3],o[5]],y)),s.start.x,s.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return ie.getPointOnQuadraticBezier(Sn(e,ie.getPathLength(t),y=>yn([s.start.x,o[0],o[2]],[s.start.y,o[1],o[3]],y)),s.start.x,s.start.y,o[0],o[1],o[2],o[3]);case"A":const l=o[0],c=o[1],h=o[2],d=o[3],u=o[5],g=o[6];let f=o[4];return f+=u*e/s.pathLength,ie.getPointOnEllipticalArc(l,c,h,d,f,g)}return null}static getPointOnLine(e,t,i,r,n,s,o){s=s??t,o=o??i;const l=this.getLineLength(t,i,r,n);if(l<1e-10)return{x:t,y:i};if(r===t)return{x:s,y:o+(n>i?e:-e)};const c=(n-i)/(r-t),h=Math.sqrt(e*e/(1+c*c))*(r<t?-1:1),d=c*h;if(Math.abs(o-i-c*(s-t))<1e-10)return{x:s+h,y:o+d};const u=((s-t)*(r-t)+(o-i)*(n-i))/(l*l),g=t+u*(r-t),f=i+u*(n-i),y=this.getLineLength(s,o,g,f),S=Math.sqrt(e*e-y*y),C=Math.sqrt(S*S/(1+c*c))*(r<t?-1:1),T=c*C;return{x:g+C,y:f+T}}static getPointOnCubicBezier(e,t,i,r,n,s,o,l,c){function h(S){return S*S*S}function d(S){return 3*S*S*(1-S)}function u(S){return 3*S*(1-S)*(1-S)}function g(S){return(1-S)*(1-S)*(1-S)}const f=l*h(e)+s*d(e)+r*u(e)+t*g(e),y=c*h(e)+o*d(e)+n*u(e)+i*g(e);return{x:f,y}}static getPointOnQuadraticBezier(e,t,i,r,n,s,o){function l(g){return g*g}function c(g){return 2*g*(1-g)}function h(g){return(1-g)*(1-g)}const d=s*l(e)+r*c(e)+t*h(e),u=o*l(e)+n*c(e)+i*h(e);return{x:d,y:u}}static getPointOnEllipticalArc(e,t,i,r,n,s){const o=Math.cos(s),l=Math.sin(s),c={x:i*Math.cos(n),y:r*Math.sin(n)};return{x:e+(c.x*o-c.y*l),y:t+(c.x*l+c.y*o)}}static parsePathData(e){if(!e)return[];let t=e;const i=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(let d=0;d<i.length;d++)t=t.replace(new RegExp(i[d],"g"),"|"+i[d]);const r=t.split("|"),n=[],s=[];let o=0,l=0;const c=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let h;for(let d=1;d<r.length;d++){let u=r[d],g=u.charAt(0);for(u=u.slice(1),s.length=0;h=c.exec(u);)s.push(h[0]);let f=[],y=g==="A"||g==="a"?0:-1;for(let S=0,C=s.length;S<C;S++){const T=s[S];if(T==="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(T)){f.push(parseInt(T[0],10)),f.push(parseInt(T[1],10)),f.push(parseFloat(T.slice(2))),y+=3,y>=7&&(y-=7);continue}if(T==="11"||T==="10"||T==="01"){f.push(parseInt(T[0],10)),f.push(parseInt(T[1],10)),y+=2,y>=7&&(y-=7);continue}if(T==="0"||T==="1"){f.push(parseInt(T,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(T)){f.push(parseInt(T[0],10)),f.push(parseFloat(T.slice(1))),y+=2,y>=7&&(y-=7);continue}if(T==="0"||T==="1"){f.push(parseInt(T,10)),y+=1,y>=7&&(y-=7);continue}}const v=parseFloat(T);isNaN(v)?f.push(0):f.push(v),y+=1,y>=7&&(y-=7)}else{const v=parseFloat(T);isNaN(v)?f.push(0):f.push(v)}}for(;f.length>0&&!isNaN(f[0]);){let S="",C=[];const T=o,v=l;let w,x,P,M,I,A,k,$,B,Y;switch(g){case"l":o+=f.shift(),l+=f.shift(),S="L",C.push(o,l);break;case"L":o=f.shift(),l=f.shift(),C.push(o,l);break;case"m":const V=f.shift(),F=f.shift();if(o+=V,l+=F,S="M",n.length>2&&n[n.length-1].command==="z"){for(let O=n.length-2;O>=0;O--)if(n[O].command==="M"){o=n[O].points[0]+V,l=n[O].points[1]+F;break}}C.push(o,l),g="l";break;case"M":o=f.shift(),l=f.shift(),S="M",C.push(o,l),g="L";break;case"h":o+=f.shift(),S="L",C.push(o,l);break;case"H":o=f.shift(),S="L",C.push(o,l);break;case"v":l+=f.shift(),S="L",C.push(o,l);break;case"V":l=f.shift(),S="L",C.push(o,l);break;case"C":C.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),l=f.shift(),C.push(o,l);break;case"c":C.push(o+f.shift(),l+f.shift(),o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),S="C",C.push(o,l);break;case"S":x=o,P=l,w=n[n.length-1],w.command==="C"&&(x=o+(o-w.points[2]),P=l+(l-w.points[3])),C.push(x,P,f.shift(),f.shift()),o=f.shift(),l=f.shift(),S="C",C.push(o,l);break;case"s":x=o,P=l,w=n[n.length-1],w.command==="C"&&(x=o+(o-w.points[2]),P=l+(l-w.points[3])),C.push(x,P,o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),S="C",C.push(o,l);break;case"Q":C.push(f.shift(),f.shift()),o=f.shift(),l=f.shift(),C.push(o,l);break;case"q":C.push(o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),S="Q",C.push(o,l);break;case"T":x=o,P=l,w=n[n.length-1],w.command==="Q"&&(x=o+(o-w.points[0]),P=l+(l-w.points[1])),o=f.shift(),l=f.shift(),S="Q",C.push(x,P,o,l);break;case"t":x=o,P=l,w=n[n.length-1],w.command==="Q"&&(x=o+(o-w.points[0]),P=l+(l-w.points[1])),o+=f.shift(),l+=f.shift(),S="Q",C.push(x,P,o,l);break;case"A":M=f.shift(),I=f.shift(),A=f.shift(),k=f.shift(),$=f.shift(),B=o,Y=l,o=f.shift(),l=f.shift(),S="A",C=this.convertEndpointToCenterParameterization(B,Y,o,l,k,$,M,I,A);break;case"a":M=f.shift(),I=f.shift(),A=f.shift(),k=f.shift(),$=f.shift(),B=o,Y=l,o+=f.shift(),l+=f.shift(),S="A",C=this.convertEndpointToCenterParameterization(B,Y,o,l,k,$,M,I,A);break}n.push({command:S||g,points:C,start:{x:T,y:v},pathLength:this.calcLength(T,v,S||g,C)})}(g==="z"||g==="Z")&&n.push({command:"z",points:[],start:void 0,pathLength:0})}return n}static calcLength(e,t,i,r){let n,s,o,l;const c=ie;switch(i){case"L":return c.getLineLength(e,t,r[0],r[1]);case"C":return mn([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return yn([e,r[0],r[2]],[t,r[1],r[3]],1);case"A":n=0;const h=r[4],d=r[5],u=r[4]+d;let g=Math.PI/180;if(Math.abs(h-u)<g&&(g=Math.abs(h-u)),s=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),d<0)for(l=h-g;l>u;l-=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=c.getLineLength(s.x,s.y,o.x,o.y),s=o;else for(l=h+g;l<u;l+=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=c.getLineLength(s.x,s.y,o.x,o.y),s=o;return o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],u,0),n+=c.getLineLength(s.x,s.y,o.x,o.y),n}return 0}static convertEndpointToCenterParameterization(e,t,i,r,n,s,o,l,c){const h=c*(Math.PI/180),d=Math.cos(h)*(e-i)/2+Math.sin(h)*(t-r)/2,u=-1*Math.sin(h)*(e-i)/2+Math.cos(h)*(t-r)/2,g=d*d/(o*o)+u*u/(l*l);g>1&&(o*=Math.sqrt(g),l*=Math.sqrt(g));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===s&&(f*=-1),isNaN(f)&&(f=0);const y=f*o*u/l,S=f*-l*d/o,C=(e+i)/2+Math.cos(h)*y-Math.sin(h)*S,T=(t+r)/2+Math.sin(h)*y+Math.cos(h)*S,v=function(k){return Math.sqrt(k[0]*k[0]+k[1]*k[1])},w=function(k,$){return(k[0]*$[0]+k[1]*$[1])/(v(k)*v($))},x=function(k,$){return(k[0]*$[1]<k[1]*$[0]?-1:1)*Math.acos(w(k,$))},P=x([1,0],[(d-y)/o,(u-S)/l]),M=[(d-y)/o,(u-S)/l],I=[(-1*d-y)/o,(-1*u-S)/l];let A=x(M,I);return w(M,I)<=-1&&(A=Math.PI),w(M,I)>=1&&(A=0),s===0&&A>0&&(A=A-2*Math.PI),s===1&&A<0&&(A=A+2*Math.PI),[C,T,o,l,P,A,h,s]}}ie.prototype.className="Path";ie.prototype._attrsAffectingSize=["data"];ae(ie);m.addGetterSetter(ie,"data");class dt extends Oe{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,i=this.points();let r=i;const n=this.tension()!==0&&i.length>4;n&&(r=this.getTensionPoints());const s=this.pointerLength(),o=i.length;let l,c;if(n){const u=[r[r.length-4],r[r.length-3],r[r.length-2],r[r.length-1],i[o-2],i[o-1]],g=ie.calcLength(r[r.length-4],r[r.length-3],"C",u),f=ie.getPointOnQuadraticBezier(Math.min(1,1-s/g),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-f.x,c=i[o-1]-f.y}else l=i[o-2]-i[o-4],c=i[o-1]-i[o-3];const h=(Math.atan2(c,l)+t)%t,d=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(i[o-2],i[o-1]),e.rotate(h),e.moveTo(0,0),e.lineTo(-s,d/2),e.lineTo(-s,-d/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(i[0],i[1]),n?(l=(r[0]+r[2])/2-i[0],c=(r[1]+r[3])/2-i[1]):(l=i[2]-i[0],c=i[3]-i[1]),e.rotate((Math.atan2(-c,-l)+t)%t),e.moveTo(0,0),e.lineTo(-s,d/2),e.lineTo(-s,-d/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}}dt.prototype.className="Arrow";ae(dt);m.addGetterSetter(dt,"pointerLength",10,R());m.addGetterSetter(dt,"pointerWidth",10,R());m.addGetterSetter(dt,"pointerAtBeginning",!1);m.addGetterSetter(dt,"pointerAtEnding",!0);class xt extends _{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}xt.prototype._centroid=!0;xt.prototype.className="Circle";xt.prototype._attrsAffectingSize=["radius"];ae(xt);m.addGetterSetter(xt,"radius",0,R());class je extends _{_sceneFunc(e){const t=this.radiusX(),i=this.radiusY();e.beginPath(),e.save(),t!==i&&e.scale(1,i/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}je.prototype.className="Ellipse";je.prototype._centroid=!0;je.prototype._attrsAffectingSize=["radiusX","radiusY"];ae(je);m.addComponentsGetterSetter(je,"radius",["x","y"]);m.addGetterSetter(je,"radiusX",0,R());m.addGetterSetter(je,"radiusY",0,R());let Pe=class zs extends _{constructor(e){super(e),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",t=>{this._removeImageLoad(t.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const e=this.image();e&&e.complete||e&&e.readyState===4||e&&e.addEventListener&&e.addEventListener("load",this._loadListener)}_removeImageLoad(e){e&&e.removeEventListener&&e.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const e=!!this.cornerRadius(),t=this.hasShadow();return e&&t?!0:super._useBufferCanvas(!0)}_sceneFunc(e){const t=this.getWidth(),i=this.getHeight(),r=this.cornerRadius(),n=this.attrs.image;let s;if(n){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?s=[n,this.cropX(),this.cropY(),o,l,0,0,t,i]:s=[n,0,0,t,i]}(this.hasFill()||this.hasStroke()||r)&&(e.beginPath(),r?b.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)),n&&(r&&e.clip(),e.drawImage.apply(e,s))}_hitFunc(e){const t=this.width(),i=this.height(),r=this.cornerRadius();e.beginPath(),r?b.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}getWidth(){var e,t,i;return(i=(e=this.attrs.width)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.width)!==null&&i!==void 0?i:0}getHeight(){var e,t,i;return(i=(e=this.attrs.height)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.height)!==null&&i!==void 0?i:0}static fromURL(e,t,i=null){const r=b.createImageElement();r.onload=function(){const n=new zs({image:r});t(n)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Pe.prototype.className="Image";Pe.prototype._attrsAffectingSize=["image"];ae(Pe);m.addGetterSetter(Pe,"cornerRadius",0,Yi(4));m.addGetterSetter(Pe,"image");m.addComponentsGetterSetter(Pe,"crop",["x","y","width","height"]);m.addGetterSetter(Pe,"cropX",0,R());m.addGetterSetter(Pe,"cropY",0,R());m.addGetterSetter(Pe,"cropWidth",0,R());m.addGetterSetter(Pe,"cropHeight",0,R());const Vs=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],nl="Change.konva",sl="none",Tr="up",br="right",wr="down",kr="left",al=Vs.length;class Wr extends bt{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,i;const r=function(){t._sync()};for(i=0;i<al;i++)e.on(Vs[i]+nl,r)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),i,r,n,s,o,l,c;if(e&&t){switch(i=e.width(),r=e.height(),n=t.pointerDirection(),s=t.pointerWidth(),c=t.pointerHeight(),o=0,l=0,n){case Tr:o=i/2,l=-1*c;break;case br:o=i+s,l=r/2;break;case wr:o=i/2,l=r+c;break;case kr:o=-1*s,l=r/2;break}t.setAttrs({x:-1*o,y:-1*l,width:i,height:r}),e.setAttrs({x:-1*o,y:-1*l})}}}Wr.prototype.className="Label";ae(Wr);class ut extends _{_sceneFunc(e){const t=this.width(),i=this.height(),r=this.pointerDirection(),n=this.pointerWidth(),s=this.pointerHeight(),o=this.cornerRadius();let l=0,c=0,h=0,d=0;typeof o=="number"?l=c=h=d=Math.min(o,t/2,i/2):(l=Math.min(o[0]||0,t/2,i/2),c=Math.min(o[1]||0,t/2,i/2),d=Math.min(o[2]||0,t/2,i/2),h=Math.min(o[3]||0,t/2,i/2)),e.beginPath(),e.moveTo(l,0),r===Tr&&(e.lineTo((t-n)/2,0),e.lineTo(t/2,-1*s),e.lineTo((t+n)/2,0)),e.lineTo(t-c,0),e.arc(t-c,c,c,Math.PI*3/2,0,!1),r===br&&(e.lineTo(t,(i-s)/2),e.lineTo(t+n,i/2),e.lineTo(t,(i+s)/2)),e.lineTo(t,i-d),e.arc(t-d,i-d,d,0,Math.PI/2,!1),r===wr&&(e.lineTo((t+n)/2,i),e.lineTo(t/2,i+s),e.lineTo((t-n)/2,i)),e.lineTo(h,i),e.arc(h,i-h,h,Math.PI/2,Math.PI,!1),r===kr&&(e.lineTo(0,(i+s)/2),e.lineTo(-1*n,i/2),e.lineTo(0,(i-s)/2)),e.lineTo(0,l),e.arc(l,l,l,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,i=this.pointerWidth(),r=this.pointerHeight(),n=this.pointerDirection(),s=this.width(),o=this.height();return n===Tr?(t-=r,o+=r):n===wr?o+=r:n===kr?(e-=i*1.5,s+=i):n===br&&(s+=i*1.5),{x:e,y:t,width:s,height:o}}}ut.prototype.className="Tag";ae(ut);m.addGetterSetter(ut,"pointerDirection",sl);m.addGetterSetter(ut,"pointerWidth",0,R());m.addGetterSetter(ut,"pointerHeight",0,R());m.addGetterSetter(ut,"cornerRadius",0,Yi(4));class li extends _{_sceneFunc(e){const t=this.cornerRadius(),i=this.width(),r=this.height();e.beginPath(),t?b.drawRoundedRectPath(e,i,r,t):e.rect(0,0,i,r),e.closePath(),e.fillStrokeShape(this)}}li.prototype.className="Rect";ae(li);m.addGetterSetter(li,"cornerRadius",0,Yi(4));class Ke extends _{_sceneFunc(e){const t=this._getPoints(),i=this.radius(),r=this.sides(),n=this.cornerRadius();if(e.beginPath(),n)b.drawRoundedPolygonPath(e,t,r,i,n);else{e.moveTo(t[0].x,t[0].y);for(let s=1;s<t.length;s++)e.lineTo(t[s].x,t[s].y)}e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,i=[];for(let r=0;r<e;r++)i.push({x:t*Math.sin(r*2*Math.PI/e),y:-1*t*Math.cos(r*2*Math.PI/e)});return i}getSelfRect(){const e=this._getPoints();let t=e[0].x,i=e[0].x,r=e[0].y,n=e[0].y;return e.forEach(s=>{t=Math.min(t,s.x),i=Math.max(i,s.x),r=Math.min(r,s.y),n=Math.max(n,s.y)}),{x:t,y:r,width:i-t,height:n-r}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Ke.prototype.className="RegularPolygon";Ke.prototype._centroid=!0;Ke.prototype._attrsAffectingSize=["radius"];ae(Ke);m.addGetterSetter(Ke,"radius",0,R());m.addGetterSetter(Ke,"sides",0,R());m.addGetterSetter(Ke,"cornerRadius",0,Yi(4));const Cn=Math.PI*2;class pt extends _{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,Cn,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),Cn,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}pt.prototype.className="Ring";pt.prototype._centroid=!0;pt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(pt);m.addGetterSetter(pt,"innerRadius",0,R());m.addGetterSetter(pt,"outerRadius",0,R());class Re extends _{constructor(e){super(e),this._updated=!0,this.anim=new we(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,n=this.animations()[t],s=this.frameOffsets(),o=n[r+0],l=n[r+1],c=n[r+2],h=n[r+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,c,h),e.closePath(),e.fillStrokeShape(this)),d)if(s){const u=s[t],g=i*2;e.drawImage(d,o,l,c,h,u[g+0],u[g+1],c,h)}else e.drawImage(d,o,l,c,h,0,0,c,h)}_hitFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,n=this.animations()[t],s=this.frameOffsets(),o=n[r+2],l=n[r+3];if(e.beginPath(),s){const c=s[t],h=i*2;e.rect(c[h+0],c[h+1],o,l)}else e.rect(0,0,o,l);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation(),i=this.animations(),r=i[t],n=r.length/4;e<n-1?this.frameIndex(e+1):this.frameIndex(0)}}Re.prototype.className="Sprite";ae(Re);m.addGetterSetter(Re,"animation");m.addGetterSetter(Re,"animations");m.addGetterSetter(Re,"frameOffsets");m.addGetterSetter(Re,"image");m.addGetterSetter(Re,"frameIndex",0,R());m.addGetterSetter(Re,"frameRate",17,R());m.backCompat(Re,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Ze extends _{_sceneFunc(e){const t=this.innerRadius(),i=this.outerRadius(),r=this.numPoints();e.beginPath(),e.moveTo(0,0-i);for(let n=1;n<r*2;n++){const s=n%2===0?i:t,o=s*Math.sin(n*Math.PI/r),l=-1*s*Math.cos(n*Math.PI/r);e.lineTo(o,l)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}Ze.prototype.className="Star";Ze.prototype._centroid=!0;Ze.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(Ze);m.addGetterSetter(Ze,"numPoints",5,R());m.addGetterSetter(Ze,"innerRadius",0,R());m.addGetterSetter(Ze,"outerRadius",0,R());function ze(a){return[...a].reduce((e,t,i,r)=>{if(new RegExp("\\p{Emoji}","u").test(t)){const n=r[i+1];n&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(n)?(e.push(t+n),r[i+1]=""):e.push(t)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(t+(r[i+1]||""))?e.push(t+r[i+1]):i>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(t)?e[e.length-1]+=t:t&&e.push(t);return e},[])}const ft="auto",ol="center",Us="inherit",Et="justify",ll="Change.konva",cl="2d",vn="-",Ws="left",hl="text",dl="Text",ul="top",pl="bottom",Tn="middle",Ys="normal",gl="px ",Ti=" ",fl="right",bn="rtl",ml="word",yl="char",wn="none",ir="…",Xs=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Sl=Xs.length;function Cl(a){return a.split(",").map(e=>{e=e.trim();const t=e.indexOf(" ")>=0,i=e.indexOf('"')>=0||e.indexOf("'")>=0;return t&&!i&&(e=`"${e}"`),e}).join(", ")}let bi;function rr(){return bi||(bi=b.createCanvasElement().getContext(cl),bi)}function vl(a){a.fillText(this._partialText,this._partialTextX,this._partialTextY)}function Tl(a){a.setAttr("miterLimit",2),a.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function bl(a){return a=a||{},!a.fillLinearGradientColorStops&&!a.fillRadialGradientColorStops&&!a.fillPatternImage&&(a.fill=a.fill||"black"),a}class re extends _{constructor(e){super(bl(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<Sl;t++)this.on(Xs[t]+ll,this._setTextData);this._setTextData()}_sceneFunc(e){var t,i;const r=this.textArr,n=r.length;if(!this.text())return;let s=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,c=this.verticalAlign(),h=this.direction(),d=0,u=this.align(),g=this.getWidth(),f=this.letterSpacing(),y=this.charRenderFunc(),S=this.fill(),C=this.textDecoration(),T=this.underlineOffset(),v=C.indexOf("underline")!==-1,w=C.indexOf("line-through")!==-1,x;h=h===Us?e.direction:h;let P=l/2,M=Tn;if(!D.legacyTextRendering){const I=this.measureSize("M");M="alphabetic";const A=(t=I.fontBoundingBoxAscent)!==null&&t!==void 0?t:I.actualBoundingBoxAscent,k=(i=I.fontBoundingBoxDescent)!==null&&i!==void 0?i:I.actualBoundingBoxDescent;P=(A-k)/2+l/2}for(h===bn&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",M),e.setAttr("textAlign",Ws),c===Tn?d=(this.getHeight()-n*l-s*2)/2:c===pl&&(d=this.getHeight()-n*l-s*2),e.translate(s,d+s),x=0;x<n;x++){let I=0,A=0;const k=r[x],$=k.text,B=k.width,Y=k.lastInParagraph;if(e.save(),u===fl?I+=g-B-s*2:u===ol&&(I+=(g-B-s*2)/2),v){e.save(),e.beginPath();const F=T??(D.legacyTextRendering?Math.round(o/2):Math.round(o/4)),O=I,J=P+A+F;e.moveTo(O,J);const N=u===Et&&!Y?g-s*2:B;e.lineTo(O+Math.round(N),J),e.lineWidth=o/15;const j=this._getLinearGradient();e.strokeStyle=j||S,e.stroke(),e.restore()}const V=I;if(h!==bn&&(f!==0||u===Et||y)){const F=$.split(" ").length-1,O=ze($);for(let J=0;J<O.length;J++){const N=O[J];if(N===" "&&!Y&&u===Et&&(I+=(g-s*2-B)/F),this._partialTextX=I,this._partialTextY=P+A,this._partialText=N,y){e.save();const ne=r.slice(0,x).reduce((oe,pe)=>oe+ze(pe.text).length,0),W=J+ne;y({char:N,index:W,x:I,y:P+A,lineIndex:x,column:J,isLastInLine:Y,width:this.measureSize(N).width,context:e})}e.fillStrokeShape(this),y&&e.restore(),I+=this.measureSize(N).width+f}}else f!==0&&e.setAttr("letterSpacing",`${f}px`),this._partialTextX=I,this._partialTextY=P+A,this._partialText=$,e.fillStrokeShape(this);if(w){e.save(),e.beginPath();const F=D.legacyTextRendering?0:-Math.round(o/4),O=V;e.moveTo(O,P+A+F);const J=u===Et&&!Y?g-s*2:B;e.lineTo(O+Math.round(J),P+A+F),e.lineWidth=o/15;const N=this._getLinearGradient();e.strokeStyle=N||S,e.stroke(),e.restore()}e.restore(),n>1&&(P+=l)}}_hitFunc(e){const t=this.getWidth(),i=this.getHeight();e.beginPath(),e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=b._isString(e)?e:e==null?"":e+"";return this._setAttr(hl,t),this}getWidth(){return this.attrs.width===ft||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===ft||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return b.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,i,r,n,s,o,l,c,h,d,u;let g=rr(),f=this.fontSize(),y;g.save(),g.font=this._getContextFont(),y=g.measureText(e),g.restore();const S=f/100;return{actualBoundingBoxAscent:(t=y.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*S,actualBoundingBoxDescent:(i=y.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(r=y.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*S,actualBoundingBoxRight:(n=y.actualBoundingBoxRight)!==null&&n!==void 0?n:75.732421875*S,alphabeticBaseline:(s=y.alphabeticBaseline)!==null&&s!==void 0?s:0,emHeightAscent:(o=y.emHeightAscent)!==null&&o!==void 0?o:100*S,emHeightDescent:(l=y.emHeightDescent)!==null&&l!==void 0?l:-20*S,fontBoundingBoxAscent:(c=y.fontBoundingBoxAscent)!==null&&c!==void 0?c:91*S,fontBoundingBoxDescent:(h=y.fontBoundingBoxDescent)!==null&&h!==void 0?h:21*S,hangingBaseline:(d=y.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*S,ideographicBaseline:(u=y.ideographicBaseline)!==null&&u!==void 0?u:-21*S,width:y.width,height:f}}_getContextFont(){return this.fontStyle()+Ti+this.fontVariant()+Ti+(this.fontSize()+gl)+Cl(this.fontFamily())}_addTextLine(e){this.align()===Et&&(e=e.trim());const i=this._getTextWidth(e);return this.textArr.push({text:e,width:i,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),i=e.length;return rr().measureText(e).width+t*i}_setTextData(){let e=this.text().split(`
|
|
15
|
+
`),t=+this.fontSize(),i=0,r=this.lineHeight()*t,n=this.attrs.width,s=this.attrs.height,o=n!==ft&&n!==void 0,l=s!==ft&&s!==void 0,c=this.padding(),h=n-c*2,d=s-c*2,u=0,g=this.wrap(),f=g!==wn,y=g!==yl&&f,S=this.ellipsis();this.textArr=[],rr().font=this._getContextFont();const C=S?this._getTextWidth(ir):0;for(let T=0,v=e.length;T<v;++T){let w=e[T],x=this._getTextWidth(w);if(o&&x>h)for(;w.length>0;){let P=0,M=ze(w).length,I="",A=0;for(;P<M;){const k=P+M>>>1,$=ze(w),B=$.slice(0,k+1).join(""),Y=this._getTextWidth(B);(S&&l&&u+r>d?Y+C:Y)<=h?(P=k+1,I=B,A=Y):M=k}if(I){if(y){const B=ze(w),Y=ze(I),V=B[Y.length],F=V===Ti||V===vn;let O;if(F&&A<=h)O=Y.length;else{const J=Y.lastIndexOf(Ti),N=Y.lastIndexOf(vn);O=Math.max(J,N)+1}O>0&&(P=O,I=B.slice(0,P).join(""),A=this._getTextWidth(I))}if(I=I.trimRight(),this._addTextLine(I),i=Math.max(i,A),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(w=ze(w).slice(P).join("").trimLeft(),w.length>0&&(x=this._getTextWidth(w),x<=h)){this._addTextLine(w),u+=r,i=Math.max(i,x);break}}else break}else this._addTextLine(w),u+=r,i=Math.max(i,x),this._shouldHandleEllipsis(u)&&T<v-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),l&&u+r>d)break}this.textHeight=t,this.textWidth=i}_shouldHandleEllipsis(e){const t=+this.fontSize(),i=this.lineHeight()*t,r=this.attrs.height,n=r!==ft&&r!==void 0,s=this.padding(),o=r-s*2;return!(this.wrap()!==wn)||n&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==ft&&e!==void 0,i=this.padding(),r=e-i*2,n=this.ellipsis(),s=this.textArr[this.textArr.length-1];!s||!n||(t&&(this._getTextWidth(s.text+ir)<r||(s.text=s.text.slice(0,s.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(s.text+ir))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t?!0:super._useBufferCanvas()}}re.prototype._fillFunc=vl;re.prototype._strokeFunc=Tl;re.prototype.className=dl;re.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];ae(re);m.overWriteSetter(re,"width",zr());m.overWriteSetter(re,"height",zr());m.addGetterSetter(re,"direction",Us);m.addGetterSetter(re,"fontFamily","Arial");m.addGetterSetter(re,"fontSize",12,R());m.addGetterSetter(re,"fontStyle",Ys);m.addGetterSetter(re,"fontVariant",Ys);m.addGetterSetter(re,"padding",0,R());m.addGetterSetter(re,"align",Ws);m.addGetterSetter(re,"verticalAlign",ul);m.addGetterSetter(re,"lineHeight",1,R());m.addGetterSetter(re,"wrap",ml);m.addGetterSetter(re,"ellipsis",!1,xe());m.addGetterSetter(re,"letterSpacing",0,R());m.addGetterSetter(re,"text","",ct());m.addGetterSetter(re,"textDecoration","");m.addGetterSetter(re,"underlineOffset",void 0,R());m.addGetterSetter(re,"charRenderFunc",void 0);const wl="",qs="normal";function js(a){a.fillText(this.partialText,0,0)}function Ks(a){a.strokeText(this.partialText,0,0)}class ce extends _{constructor(e){super(e),this.dummyCanvas=b.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 ie.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:ie.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=ie.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),i=this.fill(),r=this.fontSize(),n=this.glyphInfo,s=t.indexOf("underline")!==-1,o=t.indexOf("line-through")!==-1;s&&e.beginPath();for(let l=0;l<n.length;l++){e.save();const c=n[l].p0;e.translate(c.x,c.y),e.rotate(n[l].rotation),this.partialText=n[l].text,e.fillStrokeShape(this),s&&(l===0&&e.moveTo(0,r/2+1),e.lineTo(n[l].width,r/2+1)),e.restore()}if(s&&(e.strokeStyle=i,e.lineWidth=r/20,e.stroke()),o){e.beginPath();for(let l=0;l<n.length;l++){e.save();const c=n[l].p0;e.translate(c.x,c.y),e.rotate(n[l].rotation),l===0&&e.moveTo(0,0),e.lineTo(n[l].width,0),e.restore()}e.strokeStyle=i,e.lineWidth=r/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const i=t[0].p0;e.moveTo(i.x,i.y)}for(let i=0;i<t.length;i++){const r=t[i].p1;e.lineTo(r.x,r.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return b.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return re.prototype.setText.call(this,e)}_getContextFont(){return re.prototype._getContextFont.call(this)}_getTextSize(e){const i=this.dummyCanvas.getContext("2d");i.save(),i.font=this._getContextFont();const r=i.measureText(e);return i.restore(),{width:r.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const e=ze(this.text()),t=[];let i=0;for(let d=0;d<e.length;d++)t.push({char:e[d],width:this._getTextSize(e[d]).width}),i+=t[d].width;const{height:r}=this._getTextSize(this.attrs.text);if(this.textWidth=i,this.textHeight=r,this.glyphInfo=[],!this.attrs.data)return null;const n=this.letterSpacing(),s=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*n,0);let c=0;s==="center"&&(c=Math.max(0,this.pathLength/2-l/2)),s==="right"&&(c=Math.max(0,this.pathLength-l));let h=c;for(let d=0;d<t.length;d++){const u=this._getPointAtLength(h);if(!u)return;const g=t[d].char;let f=t[d].width+n;if(g===" "&&s==="justify"){const w=this.text().split(" ").length-1;f+=(this.pathLength-l)/w}const y=this._getPointAtLength(h+f);if(!y)return;const S=ie.getLineLength(u.x,u.y,y.x,y.y);let C=0;if(o)try{C=o(t[d-1].char,g)*this.fontSize()}catch{C=0}u.x+=C,y.x+=C,this.textWidth+=C;const T=ie.getPointOnLine(C+S/2,u.x,u.y,y.x,y.y),v=Math.atan2(y.y-u.y,y.x-u.x);this.glyphInfo.push({transposeX:T.x,transposeY:T.y,text:e[d],rotation:v,p0:u,p1:y,width:S}),h+=f}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,i=e[0]||0,r=e[1]||0,n=e[1]||0,s,o;for(let c=0;c<e.length/2;c++)s=e[c*2],o=e[c*2+1],t=Math.min(t,s),i=Math.max(i,s),r=Math.min(r,o),n=Math.max(n,o);const l=this.fontSize();return{x:t-l/2,y:r-l/2,width:i-t+l,height:n-r+l}}destroy(){return b.releaseCanvas(this.dummyCanvas),super.destroy()}}ce.prototype._fillFunc=js;ce.prototype._strokeFunc=Ks;ce.prototype._fillFuncHit=js;ce.prototype._strokeFuncHit=Ks;ce.prototype.className="TextPath";ce.prototype._attrsAffectingSize=["text","fontSize","data"];ae(ce);m.addGetterSetter(ce,"data");m.addGetterSetter(ce,"fontFamily","Arial");m.addGetterSetter(ce,"fontSize",12,R());m.addGetterSetter(ce,"fontStyle",qs);m.addGetterSetter(ce,"align","left");m.addGetterSetter(ce,"letterSpacing",0,R());m.addGetterSetter(ce,"textBaseline","middle");m.addGetterSetter(ce,"fontVariant",qs);m.addGetterSetter(ce,"text",wl);m.addGetterSetter(ce,"textDecoration","");m.addGetterSetter(ce,"kerningFunc",void 0);const Zs="tr-konva",kl=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(a=>a+`.${Zs}`).join(" "),kn="nodesRect",xl=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Pl={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},_l="ontouchstart"in D._global;function Il(a,e,t){if(a==="rotater")return t;e+=b.degToRad(Pl[a]||0);const i=(b.radToDeg(e)%360+360)%360;return b._inRange(i,315+22.5,360)||b._inRange(i,0,22.5)?"ns-resize":b._inRange(i,45-22.5,45+22.5)?"nesw-resize":b._inRange(i,90-22.5,90+22.5)?"ew-resize":b._inRange(i,135-22.5,135+22.5)?"nwse-resize":b._inRange(i,180-22.5,180+22.5)?"ns-resize":b._inRange(i,225-22.5,225+22.5)?"nesw-resize":b._inRange(i,270-22.5,270+22.5)?"ew-resize":b._inRange(i,315-22.5,315+22.5)?"nwse-resize":(b.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}const Gi=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function Al(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 Js(a,e,t){const i=t.x+(a.x-t.x)*Math.cos(e)-(a.y-t.y)*Math.sin(e),r=t.y+(a.x-t.x)*Math.sin(e)+(a.y-t.y)*Math.cos(e);return{...a,rotation:a.rotation+e,x:i,y:r}}function El(a,e){const t=Al(a);return Js(a,e,t)}function Ll(a,e,t){let i=e;for(let r=0;r<a.length;r++){const n=D.getAngle(a[r]),s=Math.abs(n-e)%(Math.PI*2);Math.min(s,Math.PI*2-s)<t&&(i=n)}return i}let xr=0;class X extends bt{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(kl,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return b.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return Zs+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(r=>r.isAncestorOf(this)?(b.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(r=>{const n=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(r._attrsAffectingSize.length){const s=r._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");r.on(s,n)}r.on(xl.map(s=>s+`.${this._getEventNamespace()}`).join(" "),n),r.on(`absoluteTransformChange.${this._getEventNamespace()}`,n),this._proxyDrag(r)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,i=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(i,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,i=>{if(!t)return;const r=e.getAbsolutePosition(),n=r.x-t.x,s=r.y-t.y;this.nodes().forEach(o=>{if(o===e||o.isDragging())return;const l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+n,y:l.y+s}),o.startDrag(i)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(kn),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(kn,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),i){const r=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),n=e.getAbsoluteScale(i),s=e.getAbsolutePosition(i),o=r.x*n.x-e.offsetX()*n.x,l=r.y*n.y-e.offsetY()*n.y,c=(D.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),h={x:s.x+o*Math.cos(c)+l*Math.sin(-c),y:s.y+l*Math.cos(c)+o*Math.sin(c),width:r.width*n.x,height:r.height*n.y,rotation:c};return Js(h,-D.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(c=>{const h=c.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:h.x,y:h.y},{x:h.x+h.width,y:h.y},{x:h.x+h.width,y:h.y+h.height},{x:h.x,y:h.y+h.height}],u=c.getAbsoluteTransform();d.forEach(function(g){const f=u.point(g);t.push(f)})});const i=new Se;i.rotate(-D.getAngle(this.rotation()));let r=1/0,n=1/0,s=-1/0,o=-1/0;t.forEach(function(c){const h=i.point(c);r===void 0&&(r=s=h.x,n=o=h.y),r=Math.min(r,h.x),n=Math.min(n,h.y),s=Math.max(s,h.x),o=Math.max(o,h.y)}),i.invert();const l=i.point({x:r,y:n});return{x:l.x,y:l.y,width:s-r,height:o-n,rotation:D.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(),Gi.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new li({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:_l?10:"auto"}),i=this;t.on("mousedown touchstart",function(r){i._handleMouseDown(r)}),t.on("dragstart",r=>{t.stopDrag(),r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),t.on("mouseenter",()=>{const r=D.getAngle(this.rotation()),n=this.rotateAnchorCursor(),s=Il(e,r,n);t.getStage().content&&(t.getStage().content.style.cursor=s),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new _({name:"back",width:0,height:0,sceneFunc(t,i){const r=i.getParent(),n=r.padding(),s=i.width(),o=i.height();if(t.beginPath(),t.rect(-n,-n,s+n*2,o+n*2),r.rotateEnabled()&&r.rotateLineVisible()){const l=r.rotateAnchorAngle(),c=r.rotateAnchorOffset(),h=b.degToRad(l),d=Math.sin(h),u=-Math.cos(h),g=s/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,-g/d):d>0&&(y=Math.min(y,(s-g)/d));const S=g+d*y,C=f+u*y,T=b._sign(o),v=S+d*c*T,w=C+u*c*T;t.moveTo(S,C),t.lineTo(v,w)}t.fillStrokeShape(i)},hitFunc:(t,i)=>{if(!this.shouldOverdrawWholeArea())return;const r=this.padding();t.beginPath(),t.rect(-r,-r,i.width()+r*2,i.height()+r*2),t.fillStrokeShape(i)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),i=t.width,r=t.height,n=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));this.sin=Math.abs(r/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 s=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-s.x,y:o.y-s.y},xr++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(l=>{l._fire("transformstart",{evt:e.evt,target:l})})}_handleMouseMove(e){let t,i,r;const n=this.findOne("."+this._movingAnchorName),s=n.getStage();s.setPointersPositions(e);const o=s.getPointerPosition();let l={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const c=n.getAbsolutePosition();this.anchorDragBoundFunc()&&(l=this.anchorDragBoundFunc()(c,l,e)),n.setAbsolutePosition(l);const h=n.getAbsolutePosition();if(c.x===h.x&&c.y===h.y)return;if(this._movingAnchorName==="rotater"){const T=this._getNodeRect();t=n.x()-T.width/2,i=-n.y()+T.height/2;const v=D.getAngle(this.rotateAnchorAngle());let w=Math.atan2(-i,t)+Math.PI/2-v;T.height<0&&(w-=Math.PI);const P=D.getAngle(this.rotation())+w,M=D.getAngle(this.rotationSnapTolerance()),A=Ll(this.rotationSnaps(),P,M)-T.rotation,k=El(T,A);this._fitNodesInto(k,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let g=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(T.x-n.x(),2)+Math.pow(T.y-n.y(),2));const v=this.findOne(".top-left").x()>T.x?-1:1,w=this.findOne(".top-left").y()>T.y?-1:1;t=r*this.cos*v,i=r*this.sin*w,this.findOne(".top-left").x(T.x-t),this.findOne(".top-left").y(T.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(n.y());else if(this._movingAnchorName==="top-right"){if(u){const T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(n.x()-T.x,2)+Math.pow(T.y-n.y(),2));const v=this.findOne(".top-right").x()<T.x?-1:1,w=this.findOne(".top-right").y()>T.y?-1:1;t=r*this.cos*v,i=r*this.sin*w,this.findOne(".top-right").x(T.x+t),this.findOne(".top-right").y(T.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 T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(T.x-n.x(),2)+Math.pow(n.y()-T.y,2));const v=T.x<n.x()?-1:1,w=n.y()<T.y?-1:1;t=r*this.cos*v,i=r*this.sin*w,n.x(T.x-t),n.y(T.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 T=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};r=Math.sqrt(Math.pow(n.x()-T.x,2)+Math.pow(n.y()-T.y,2));const v=this.findOne(".bottom-right").x()<T.x?-1:1,w=this.findOne(".bottom-right").y()<T.y?-1:1;t=r*this.cos*v,i=r*this.sin*w,this.findOne(".bottom-right").x(T.x+t),this.findOne(".bottom-right").y(T.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(g=this.centeredScaling()||e.altKey,g){const T=this.findOne(".top-left"),v=this.findOne(".bottom-right"),w=T.x(),x=T.y(),P=this.getWidth()-v.x(),M=this.getHeight()-v.y();v.move({x:-w,y:-x}),T.move({x:P,y:M})}const y=this.findOne(".top-left").getAbsolutePosition();t=y.x,i=y.y;const S=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),C=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:i,width:S,height:C,rotation:D.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const i=this.getNode();xr--,this._fire("transformend",{evt:e,target:i}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),i&&this._nodes.forEach(r=>{var n;r._fire("transformend",{evt:e,target:r}),(n=r.getLayer())===null||n===void 0||n.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const i=this._getNodeRect(),r=1;if(b._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(b._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const n=new Se;if(n.rotate(D.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const u=n.point({x:-this.padding()*2,y:0});e.x+=u.x,e.y+=u.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const u=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,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const u=n.point({x:0,y:-this.padding()*2});e.x+=u.x,e.y+=u.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const u=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,e.height+=this.padding()*2}if(this.boundBoxFunc()){const u=this.boundBoxFunc()(i,e);u?e=u:b.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const s=1e7,o=new Se;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/s,i.height/s);const l=new Se,c=e.width/s,h=e.height/s;this.flipEnabled()===!1?(l.translate(e.x,e.y),l.rotate(e.rotation),l.translate(e.width<0?e.width:0,e.height<0?e.height:0),l.scale(Math.abs(c),Math.abs(h))):(l.translate(e.x,e.y),l.rotate(e.rotation),l.scale(c,h));const d=l.multiply(o.invert());this._nodes.forEach(u=>{var g;if(!u.getStage())return;const f=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const S=new Se;S.multiply(f.copy().invert()).multiply(d).multiply(f).multiply(y);const C=S.decompose();u.setAttrs(C),(g=u.getLayer())===null||g===void 0||g.batchDraw()}),this.rotation(b._getRotation(e.rotation)),this._nodes.forEach(u=>{this._fire("transform",{evt:t,target:u}),u._fire("transform",{evt:t,target:u})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(b._getRotation(t.rotation));const i=t.width,r=t.height,n=this.enabledAnchors(),s=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),c=this.find("._anchor");c.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:s&&n.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:s&&n.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:s&&n.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:l/2+o,visible:s&&n.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:l/2-o,visible:s&&n.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:l/2+o,offsetY:l/2-o,visible:s&&n.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:l/2-o,visible:s&&n.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:l/2-o,offsetY:l/2-o,visible:s&&n.indexOf("bottom-right")>=0});const h=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=b.degToRad(h),g=Math.sin(u),f=-Math.cos(u),y=i/2,S=r/2;let C=1/0;f<0?C=Math.min(C,-S/f):f>0&&(C=Math.min(C,(r-S)/f)),g<0?C=Math.min(C,-y/g):g>0&&(C=Math.min(C,(i-y)/g));const T=y+g*C,v=S+f*C,w=b._sign(r);this._batchChangeChild(".rotater",{x:T+g*d*w,y:v+f*d*w-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(P=>P.draggable()),x:0,y:0});const x=this.anchorStyleFunc();x&&c.forEach(P=>{x(P)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),bt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return L.prototype.toObject.call(this)}clone(e){return L.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}X.isTransforming=()=>xr>0;function Rl(a){return a instanceof Array||b.warn("enabledAnchors value should be an array"),a instanceof Array&&a.forEach(function(e){Gi.indexOf(e)===-1&&b.warn("Unknown anchor name: "+e+". Available names are: "+Gi.join(", "))}),a||[]}X.prototype.className="Transformer";ae(X);m.addGetterSetter(X,"enabledAnchors",Gi,Rl);m.addGetterSetter(X,"flipEnabled",!0,xe());m.addGetterSetter(X,"resizeEnabled",!0);m.addGetterSetter(X,"anchorSize",10,R());m.addGetterSetter(X,"rotateEnabled",!0);m.addGetterSetter(X,"rotateLineVisible",!0);m.addGetterSetter(X,"rotationSnaps",[]);m.addGetterSetter(X,"rotateAnchorOffset",50,R());m.addGetterSetter(X,"rotateAnchorAngle",0,R());m.addGetterSetter(X,"rotateAnchorCursor","crosshair");m.addGetterSetter(X,"rotationSnapTolerance",5,R());m.addGetterSetter(X,"borderEnabled",!0);m.addGetterSetter(X,"anchorStroke","rgb(0, 161, 255)");m.addGetterSetter(X,"anchorStrokeWidth",1,R());m.addGetterSetter(X,"anchorFill","white");m.addGetterSetter(X,"anchorCornerRadius",0,R());m.addGetterSetter(X,"borderStroke","rgb(0, 161, 255)");m.addGetterSetter(X,"borderStrokeWidth",1,R());m.addGetterSetter(X,"borderDash");m.addGetterSetter(X,"keepRatio",!0);m.addGetterSetter(X,"shiftBehavior","default");m.addGetterSetter(X,"centeredScaling",!1);m.addGetterSetter(X,"ignoreStroke",!1);m.addGetterSetter(X,"padding",0,R());m.addGetterSetter(X,"nodes");m.addGetterSetter(X,"node");m.addGetterSetter(X,"boundBoxFunc");m.addGetterSetter(X,"anchorDragBoundFunc");m.addGetterSetter(X,"anchorStyleFunc");m.addGetterSetter(X,"shouldOverdrawWholeArea",!1);m.addGetterSetter(X,"useSingleNodeRotation",!0);m.backCompat(X,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Be extends _{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,D.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Be.prototype.className="Wedge";Be.prototype._centroid=!0;Be.prototype._attrsAffectingSize=["radius"];ae(Be);m.addGetterSetter(Be,"radius",0,R());m.addGetterSetter(Be,"angle",0,R());m.addGetterSetter(Be,"clockwise",!1);m.backCompat(Be,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function xn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Dl=[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],Ml=[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 Ol(a,e){const t=a.data,i=a.width,r=a.height;let n,s,o,l,c,h,d,u,g,f,y,S,C,T,v,w,x,P,M,I;const A=e+e+1,k=i-1,$=r-1,B=e+1,Y=B*(B+1)/2,V=new xn,F=Dl[e],O=Ml[e];let J=null,N=V,j=null,ne=null;for(let W=1;W<A;W++)N=N.next=new xn,W===B&&(J=N);N.next=V,o=s=0;for(let W=0;W<r;W++){S=C=T=v=l=c=h=d=0,u=B*(w=t[s]),g=B*(x=t[s+1]),f=B*(P=t[s+2]),y=B*(M=t[s+3]),l+=Y*w,c+=Y*x,h+=Y*P,d+=Y*M,N=V;for(let oe=0;oe<B;oe++)N.r=w,N.g=x,N.b=P,N.a=M,N=N.next;for(let oe=1;oe<B;oe++)n=s+((k<oe?k:oe)<<2),l+=(N.r=w=t[n])*(I=B-oe),c+=(N.g=x=t[n+1])*I,h+=(N.b=P=t[n+2])*I,d+=(N.a=M=t[n+3])*I,S+=w,C+=x,T+=P,v+=M,N=N.next;j=V,ne=J;for(let oe=0;oe<i;oe++)t[s+3]=M=d*F>>O,M!==0?(M=255/M,t[s]=(l*F>>O)*M,t[s+1]=(c*F>>O)*M,t[s+2]=(h*F>>O)*M):t[s]=t[s+1]=t[s+2]=0,l-=u,c-=g,h-=f,d-=y,u-=j.r,g-=j.g,f-=j.b,y-=j.a,n=o+((n=oe+e+1)<k?n:k)<<2,S+=j.r=t[n],C+=j.g=t[n+1],T+=j.b=t[n+2],v+=j.a=t[n+3],l+=S,c+=C,h+=T,d+=v,j=j.next,u+=w=ne.r,g+=x=ne.g,f+=P=ne.b,y+=M=ne.a,S-=w,C-=x,T-=P,v-=M,ne=ne.next,s+=4;o+=i}for(let W=0;W<i;W++){C=T=v=S=c=h=d=l=0,s=W<<2,u=B*(w=t[s]),g=B*(x=t[s+1]),f=B*(P=t[s+2]),y=B*(M=t[s+3]),l+=Y*w,c+=Y*x,h+=Y*P,d+=Y*M,N=V;for(let pe=0;pe<B;pe++)N.r=w,N.g=x,N.b=P,N.a=M,N=N.next;let oe=i;for(let pe=1;pe<=e;pe++)s=oe+W<<2,l+=(N.r=w=t[s])*(I=B-pe),c+=(N.g=x=t[s+1])*I,h+=(N.b=P=t[s+2])*I,d+=(N.a=M=t[s+3])*I,S+=w,C+=x,T+=P,v+=M,N=N.next,pe<$&&(oe+=i);s=W,j=V,ne=J;for(let pe=0;pe<r;pe++)n=s<<2,t[n+3]=M=d*F>>O,M>0?(M=255/M,t[n]=(l*F>>O)*M,t[n+1]=(c*F>>O)*M,t[n+2]=(h*F>>O)*M):t[n]=t[n+1]=t[n+2]=0,l-=u,c-=g,h-=f,d-=y,u-=j.r,g-=j.g,f-=j.b,y-=j.a,n=W+((n=pe+B)<$?n:$)*i<<2,l+=S+=j.r=t[n],c+=C+=j.g=t[n+1],h+=T+=j.b=t[n+2],d+=v+=j.a=t[n+3],j=j.next,u+=w=ne.r,g+=x=ne.g,f+=P=ne.b,y+=M=ne.a,S-=w,C-=x,T-=P,v-=M,ne=ne.next,s+=i}}const Bl=function(e){const t=Math.round(this.blurRadius());t>0&&Ol(e,t)};m.addGetterSetter(L,"blurRadius",0,R(),m.afterSetFilter);const Gl=function(a){const e=this.brightness()*255,t=a.data,i=t.length;for(let r=0;r<i;r+=4)t[r]+=e,t[r+1]+=e,t[r+2]+=e};m.addGetterSetter(L,"brightness",0,R(),m.afterSetFilter);const Fl=function(a){const e=this.brightness(),t=a.data,i=t.length;for(let r=0;r<i;r+=4)t[r]=Math.min(255,t[r]*e),t[r+1]=Math.min(255,t[r+1]*e),t[r+2]=Math.min(255,t[r+2]*e)},Hl=function(a){const e=Math.pow((this.contrast()+100)/100,2),t=a.data,i=t.length;let r=150,n=150,s=150;for(let o=0;o<i;o+=4)r=t[o],n=t[o+1],s=t[o+2],r/=255,r-=.5,r*=e,r+=.5,r*=255,n/=255,n-=.5,n*=e,n+=.5,n*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,r=r<0?0:r>255?255:r,n=n<0?0:n>255?255:n,s=s<0?0:s>255?255:s,t[o]=r,t[o+1]=n,t[o+2]=s};m.addGetterSetter(L,"contrast",0,R(),m.afterSetFilter);const Nl=function(a){var e,t,i,r,n,s,o,l,c;const h=a.data,d=a.width,u=a.height,g=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),f=Math.min(1,Math.max(0,(r=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&r!==void 0?r:.5)),S=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(s=(n=this.embossDirection)===null||n===void 0?void 0:n.call(this))!==null&&s!==void 0?s:"top-left"])!==null&&o!==void 0?o:315,C=!!((c=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&c!==void 0&&c),T=g*10,v=f*255,w=S*Math.PI/180,x=Math.cos(w),P=Math.sin(w),M=128/1020*T,I=new Uint8ClampedArray(h),A=new Float32Array(d*u);for(let V=0,F=0;F<h.length;F+=4,V++)A[V]=.2126*I[F]+.7152*I[F+1]+.0722*I[F+2];const k=[-1,0,1,-2,0,2,-1,0,1],$=[-1,-2,-1,0,0,0,1,2,1],B=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],Y=V=>V<0?0:V>255?255:V;for(let V=1;V<u-1;V++)for(let F=1;F<d-1;F++){const O=V*d+F;let J=0,N=0;J+=A[O+B[0]]*k[0],N+=A[O+B[0]]*$[0],J+=A[O+B[1]]*k[1],N+=A[O+B[1]]*$[1],J+=A[O+B[2]]*k[2],N+=A[O+B[2]]*$[2],J+=A[O+B[3]]*k[3],N+=A[O+B[3]]*$[3],J+=A[O+B[5]]*k[5],N+=A[O+B[5]]*$[5],J+=A[O+B[6]]*k[6],N+=A[O+B[6]]*$[6],J+=A[O+B[7]]*k[7],N+=A[O+B[7]]*$[7],J+=A[O+B[8]]*k[8],N+=A[O+B[8]]*$[8];const j=x*J+P*N,ne=Y(v+j*M),W=O*4;if(C){const oe=ne-v;h[W]=Y(I[W]+oe),h[W+1]=Y(I[W+1]+oe),h[W+2]=Y(I[W+2]+oe),h[W+3]=I[W+3]}else h[W]=h[W+1]=h[W+2]=ne,h[W+3]=I[W+3]}for(let V=0;V<d;V++){let F=V*4,O=((u-1)*d+V)*4;h[F]=I[F],h[F+1]=I[F+1],h[F+2]=I[F+2],h[F+3]=I[F+3],h[O]=I[O],h[O+1]=I[O+1],h[O+2]=I[O+2],h[O+3]=I[O+3]}for(let V=1;V<u-1;V++){let F=V*d*4,O=(V*d+(d-1))*4;h[F]=I[F],h[F+1]=I[F+1],h[F+2]=I[F+2],h[F+3]=I[F+3],h[O]=I[O],h[O+1]=I[O+1],h[O+2]=I[O+2],h[O+3]=I[O+3]}return a};m.addGetterSetter(L,"embossStrength",.5,R(),m.afterSetFilter);m.addGetterSetter(L,"embossWhiteLevel",.5,R(),m.afterSetFilter);m.addGetterSetter(L,"embossDirection","top-left",void 0,m.afterSetFilter);m.addGetterSetter(L,"embossBlend",!1,void 0,m.afterSetFilter);function nr(a,e,t,i,r){const n=t-e,s=r-i;if(n===0)return i+s/2;if(s===0)return i;let o=(a-e)/n;return o=s*o+i,o}const $l=function(a){const e=a.data,t=e.length;let i=e[0],r=i,n,s=e[1],o=s,l,c=e[2],h=c,d;const u=this.enhance();if(u===0)return;for(let v=0;v<t;v+=4)n=e[v+0],n<i?i=n:n>r&&(r=n),l=e[v+1],l<s?s=l:l>o&&(o=l),d=e[v+2],d<c?c=d:d>h&&(h=d);r===i&&(r=255,i=0),o===s&&(o=255,s=0),h===c&&(h=255,c=0);let g,f,y,S,C,T;if(u>0)g=r+u*(255-r),f=i-u*(i-0),y=o+u*(255-o),S=s-u*(s-0),C=h+u*(255-h),T=c-u*(c-0);else{const v=(r+i)*.5;g=r+u*(r-v),f=i+u*(i-v);const w=(o+s)*.5;y=o+u*(o-w),S=s+u*(s-w);const x=(h+c)*.5;C=h+u*(h-x),T=c+u*(c-x)}for(let v=0;v<t;v+=4)e[v+0]=nr(e[v+0],i,r,f,g),e[v+1]=nr(e[v+1],s,o,S,y),e[v+2]=nr(e[v+2],c,h,T,C)};m.addGetterSetter(L,"enhance",0,R(),m.afterSetFilter);const zl=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4){const r=.34*e[i]+.5*e[i+1]+.16*e[i+2];e[i]=r,e[i+1]=r,e[i+2]=r}};m.addGetterSetter(L,"hue",0,R(),m.afterSetFilter);m.addGetterSetter(L,"saturation",0,R(),m.afterSetFilter);m.addGetterSetter(L,"luminance",0,R(),m.afterSetFilter);const Vl=function(a){const e=a.data,t=e.length,i=1,r=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,s=this.luminance()*127,o=i*r*Math.cos(n*Math.PI/180),l=i*r*Math.sin(n*Math.PI/180),c=.299*i+.701*o+.167*l,h=.587*i-.587*o+.33*l,d=.114*i-.114*o-.497*l,u=.299*i-.299*o-.328*l,g=.587*i+.413*o+.035*l,f=.114*i-.114*o+.293*l,y=.299*i-.3*o+1.25*l,S=.587*i-.586*o-1.05*l,C=.114*i+.886*o-.2*l;let T,v,w,x;for(let P=0;P<t;P+=4)T=e[P+0],v=e[P+1],w=e[P+2],x=e[P+3],e[P+0]=c*T+h*v+d*w+s,e[P+1]=u*T+g*v+f*w+s,e[P+2]=y*T+S*v+C*w+s,e[P+3]=x},Ul=function(a){const e=a.data,t=e.length,i=Math.pow(2,this.value()),r=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,s=i*r*Math.cos(n*Math.PI/180),o=i*r*Math.sin(n*Math.PI/180),l=.299*i+.701*s+.167*o,c=.587*i-.587*s+.33*o,h=.114*i-.114*s-.497*o,d=.299*i-.299*s-.328*o,u=.587*i+.413*s+.035*o,g=.114*i-.114*s+.293*o,f=.299*i-.3*s+1.25*o,y=.587*i-.586*s-1.05*o,S=.114*i+.886*s-.2*o;for(let C=0;C<t;C+=4){const T=e[C+0],v=e[C+1],w=e[C+2],x=e[C+3];e[C+0]=l*T+c*v+h*w,e[C+1]=d*T+u*v+g*w,e[C+2]=f*T+y*v+S*w,e[C+3]=x}};m.addGetterSetter(L,"hue",0,R(),m.afterSetFilter);m.addGetterSetter(L,"saturation",0,R(),m.afterSetFilter);m.addGetterSetter(L,"value",0,R(),m.afterSetFilter);const Wl=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4)e[i]=255-e[i],e[i+1]=255-e[i+1],e[i+2]=255-e[i+2]},Yl=function(a,e,t){const i=a.data,r=e.data,n=a.width,s=a.height,o=t.polarCenterX||n/2,l=t.polarCenterY||s/2;let c=Math.sqrt(o*o+l*l),h=n-o,d=s-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const g=s,f=n,y=360/f*Math.PI/180;for(let S=0;S<f;S+=1){const C=Math.sin(S*y),T=Math.cos(S*y);for(let v=0;v<g;v+=1){h=Math.floor(o+c*v/g*T),d=Math.floor(l+c*v/g*C);let w=(d*n+h)*4;const x=i[w+0],P=i[w+1],M=i[w+2],I=i[w+3];w=(S+v*n)*4,r[w+0]=x,r[w+1]=P,r[w+2]=M,r[w+3]=I}}},Xl=function(a,e,t){const i=a.data,r=e.data,n=a.width,s=a.height,o=t.polarCenterX||n/2,l=t.polarCenterY||s/2;let c=Math.sqrt(o*o+l*l),h=n-o,d=s-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const g=s,f=n,y=0;let S,C;for(h=0;h<n;h+=1)for(d=0;d<s;d+=1){const T=h-o,v=d-l,w=Math.sqrt(T*T+v*v)*g/c;let x=(Math.atan2(v,T)*180/Math.PI+360+y)%360;x=x*f/360,S=Math.floor(x),C=Math.floor(w);let P=(C*n+S)*4;const M=i[P+0],I=i[P+1],A=i[P+2],k=i[P+3];P=(d*n+h)*4,r[P+0]=M,r[P+1]=I,r[P+2]=A,r[P+3]=k}},ql=function(a){const e=a.width,t=a.height;let i,r,n,s,o,l,c,h,d,u,g=Math.round(this.kaleidoscopePower());const f=Math.round(this.kaleidoscopeAngle()),y=Math.floor(e*(f%360)/360);if(g<1)return;const S=b.createCanvasElement();S.width=e,S.height=t;const C=S.getContext("2d").getImageData(0,0,e,t);b.releaseCanvas(S),Yl(a,C,{polarCenterX:e/2,polarCenterY:t/2});let T=e/Math.pow(2,g);for(;T<=8;)T=T*2,g-=1;T=Math.ceil(T);let v=T,w=0,x=v,P=1;for(y+T>e&&(w=v,x=0,P=-1),r=0;r<t;r+=1)for(i=w;i!==x;i+=P)n=Math.round(i+y)%e,d=(e*r+n)*4,o=C.data[d+0],l=C.data[d+1],c=C.data[d+2],h=C.data[d+3],u=(e*r+i)*4,C.data[u+0]=o,C.data[u+1]=l,C.data[u+2]=c,C.data[u+3]=h;for(r=0;r<t;r+=1)for(v=Math.floor(T),s=0;s<g;s+=1){for(i=0;i<v+1;i+=1)d=(e*r+i)*4,o=C.data[d+0],l=C.data[d+1],c=C.data[d+2],h=C.data[d+3],u=(e*r+v*2-i-1)*4,C.data[u+0]=o,C.data[u+1]=l,C.data[u+2]=c,C.data[u+3]=h;v*=2}Xl(C,a,{})};m.addGetterSetter(L,"kaleidoscopePower",2,R(),m.afterSetFilter);m.addGetterSetter(L,"kaleidoscopeAngle",0,R(),m.afterSetFilter);function wi(a,e,t){let i=(t*a.width+e)*4;const r=[];return r.push(a.data[i++],a.data[i++],a.data[i++],a.data[i++]),r}function Lt(a,e){return Math.sqrt(Math.pow(a[0]-e[0],2)+Math.pow(a[1]-e[1],2)+Math.pow(a[2]-e[2],2))}function jl(a){const e=[0,0,0];for(let t=0;t<a.length;t++)e[0]+=a[t][0],e[1]+=a[t][1],e[2]+=a[t][2];return e[0]/=a.length,e[1]/=a.length,e[2]/=a.length,e}function Kl(a,e){const t=wi(a,0,0),i=wi(a,a.width-1,0),r=wi(a,0,a.height-1),n=wi(a,a.width-1,a.height-1),s=e||10;if(Lt(t,i)<s&&Lt(i,n)<s&&Lt(n,r)<s&&Lt(r,t)<s){const o=jl([i,t,n,r]),l=[];for(let c=0;c<a.width*a.height;c++){const h=Lt(o,[a.data[c*4],a.data[c*4+1],a.data[c*4+2]]);l[c]=h<s?0:255}return l}}function Zl(a,e){for(let t=0;t<a.width*a.height;t++)a.data[4*t+3]=e[t]}function Jl(a,e,t){const i=[1,1,1,1,0,1,1,1,1],r=Math.round(Math.sqrt(i.length)),n=Math.floor(r/2),s=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,S=i[d*r+u];h+=a[y]*S}}s[c]=h===255*8?255:0}return s}function Ql(a,e,t){const i=[1,1,1,1,1,1,1,1,1],r=Math.round(Math.sqrt(i.length)),n=Math.floor(r/2),s=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,S=i[d*r+u];h+=a[y]*S}}s[c]=h>=255*4?255:0}return s}function ec(a,e,t){const i=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],r=Math.round(Math.sqrt(i.length)),n=Math.floor(r/2),s=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,S=i[d*r+u];h+=a[y]*S}}s[c]=h}return s}const tc=function(a){const e=this.threshold();let t=Kl(a,e);return t&&(t=Jl(t,a.width,a.height),t=Ql(t,a.width,a.height),t=ec(t,a.width,a.height),Zl(a,t)),a};m.addGetterSetter(L,"threshold",0,R(),m.afterSetFilter);const ic=function(a){const e=this.noise()*255,t=a.data,i=t.length,r=e/2;for(let n=0;n<i;n+=4)t[n+0]+=r-2*r*Math.random(),t[n+1]+=r-2*r*Math.random(),t[n+2]+=r-2*r*Math.random()};m.addGetterSetter(L,"noise",.2,R(),m.afterSetFilter);const rc=function(a){let e=Math.ceil(this.pixelSize()),t=a.width,i=a.height,r=Math.ceil(t/e),n=Math.ceil(i/e),s=a.data;if(e<=0){b.error("pixelSize value can not be <= 0");return}for(let o=0;o<r;o+=1)for(let l=0;l<n;l+=1){let c=0,h=0,d=0,u=0;const g=o*e,f=g+e,y=l*e,S=y+e;let C=0;for(let T=g;T<f;T+=1)if(!(T>=t))for(let v=y;v<S;v+=1){if(v>=i)continue;const w=(t*v+T)*4;c+=s[w+0],h+=s[w+1],d+=s[w+2],u+=s[w+3],C+=1}c=c/C,h=h/C,d=d/C,u=u/C;for(let T=g;T<f;T+=1)if(!(T>=t))for(let v=y;v<S;v+=1){if(v>=i)continue;const w=(t*v+T)*4;s[w+0]=c,s[w+1]=h,s[w+2]=d,s[w+3]=u}}};m.addGetterSetter(L,"pixelSize",8,R(),m.afterSetFilter);const nc=function(a){const e=Math.round(this.levels()*254)+1,t=a.data,i=t.length,r=255/e;for(let n=0;n<i;n+=1)t[n]=Math.floor(t[n]/r)*r};m.addGetterSetter(L,"levels",.5,R(),m.afterSetFilter);const sc=function(a){const e=a.data,t=e.length,i=this.red(),r=this.green(),n=this.blue();for(let s=0;s<t;s+=4){const o=(.34*e[s]+.5*e[s+1]+.16*e[s+2])/255;e[s]=o*i,e[s+1]=o*r,e[s+2]=o*n,e[s+3]=e[s+3]}};m.addGetterSetter(L,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(L,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(L,"blue",0,Ts,m.afterSetFilter);const ac=function(a){const e=a.data,t=e.length,i=this.red(),r=this.green(),n=this.blue(),s=this.alpha();for(let o=0;o<t;o+=4){const l=1-s;e[o]=i*s+e[o]*l,e[o+1]=r*s+e[o+1]*l,e[o+2]=n*s+e[o+2]*l}};m.addGetterSetter(L,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(L,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(L,"blue",0,Ts,m.afterSetFilter);m.addGetterSetter(L,"alpha",1,function(a){return this._filterUpToDate=!1,a>1?1:a<0?0:a});const oc=function(a){const e=a.data,t=e.length;for(let i=0;i<t;i+=4){const r=e[i+0],n=e[i+1],s=e[i+2];e[i+0]=Math.min(255,r*.393+n*.769+s*.189),e[i+1]=Math.min(255,r*.349+n*.686+s*.168),e[i+2]=Math.min(255,r*.272+n*.534+s*.131)}},lc=function(a){const t=a.data;for(let i=0;i<t.length;i+=4){const r=t[i],n=t[i+1],s=t[i+2];.2126*r+.7152*n+.0722*s>=128&&(t[i]=255-r,t[i+1]=255-n,t[i+2]=255-s)}return a},cc=function(a){const e=this.threshold()*255,t=a.data,i=t.length;for(let r=0;r<i;r+=1)t[r]=t[r]<e?0:255};m.addGetterSetter(L,"threshold",.5,R(),m.afterSetFilter);const q=gn.Util._assign(gn,{Arc:Me,Arrow:dt,Circle:xt,Ellipse:je,Image:Pe,Label:Wr,Tag:ut,Line:Oe,Path:ie,Rect:li,RegularPolygon:Ke,Ring:pt,Sprite:Re,Star:Ze,Text:re,TextPath:ce,Transformer:X,Wedge:Be,Filters:{Blur:Bl,Brightness:Fl,Brighten:Gl,Contrast:Hl,Emboss:Nl,Enhance:$l,Grayscale:zl,HSL:Vl,HSV:Ul,Invert:Wl,Kaleidoscope:ql,Mask:tc,Noise:ic,Pixelate:rc,Posterize:nc,RGB:sc,RGBA:ac,Sepia:oc,Solarize:lc,Threshold:cc}}),Qs="media-editor-track.diagnostics.v1",Pr="media-editor-track.diagnostics.failure-window.v1",ea="media-editor-track-diagnostics",Ye="snapshots",ta="state",ia="latest-failure-window",ii=1,Yr=1,Pn=40,hc=48,dc=250,_n=20,uc=100,pc=new Set(["pending-preview.begin","preview.sync.requested","media.seeking","media.seeked"]),In={debug:10,info:20,warn:30,error:40},Ge={enabled:!0,persist:!0,storageQuotaMb:10,maxSessions:20,maxHotEvents:500,includeFullSourceUrl:!0,enablePanel:!1,consoleSeverityThreshold:"warn"};function An(a){return`${a}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function gc(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function ra(a){if(!a||typeof a!="object")return!1;const e=Object.getPrototypeOf(a);return e===Object.prototype||e===null}function vt(a,e,t){if(a==null||typeof a=="string"||typeof a=="number"||typeof a=="boolean")return a??null;if(typeof a=="bigint")return a.toString();if(a instanceof Error)return{name:a.name,message:a.message,stack:a.stack??null,cause:vt(a.cause,e+1,t)};if(e>=4)return"[max-depth]";if(Array.isArray(a))return a.slice(0,40).map(i=>vt(i,e+1,t));if(typeof a=="object"){if(t.has(a))return"[circular]";if(t.add(a),"tagName"in a&&typeof a.tagName=="string")return{tagName:a.tagName};if(!ra(a))return String(a);const i={};for(const r of Object.keys(a).slice(0,60))i[r]=vt(a[r],e+1,t);return i}return String(a)}function Fi(a){if(!a)return null;const e=vt(a,0,new WeakSet);return ra(e)?e:{value:e}}function fc(a){return Fi(a)}function Rt(a){return typeof a=="number"&&Number.isFinite(a)?a:null}function ki(a){return typeof a=="string"&&a.length>0?a:null}function mc(){var i,r,n,s,o;const a=typeof navigator<"u"?navigator:null,e={platform:ki(a==null?void 0:a.platform),hardwareConcurrency:Rt(a==null?void 0:a.hardwareConcurrency),deviceMemory:Rt(a==null?void 0:a.deviceMemory),maxTouchPoints:Rt(a==null?void 0:a.maxTouchPoints),language:ki(a==null?void 0:a.language),languages:Array.isArray(a==null?void 0:a.languages)?a.languages.filter(l=>typeof l=="string"):null},t={online:typeof(a==null?void 0:a.onLine)=="boolean"?a.onLine:null,effectiveType:ki((i=a==null?void 0:a.connection)==null?void 0:i.effectiveType),downlinkMbps:Rt((r=a==null?void 0:a.connection)==null?void 0:r.downlink),rttMs:Rt((n=a==null?void 0:a.connection)==null?void 0:n.rtt),saveData:typeof((s=a==null?void 0:a.connection)==null?void 0:s.saveData)=="boolean"?a.connection.saveData:null,connectionType:ki((o=a==null?void 0:a.connection)==null?void 0:o.type)};return{hardware:e,network:t}}function En(a,e={}){const t=mc(),i=Fi(a??null);return{...i??{},hardware:t.hardware,network:t.network,environmentCapturedAt:e.capturedAt??(i==null?void 0:i.environmentCapturedAt)??null,environmentExportedAt:e.exportedAt??(i==null?void 0:i.environmentExportedAt)??null}}function yc(a){return a?a instanceof Error?{name:a.name,message:a.message,stack:a.stack??null,cause:vt(a.cause,1,new WeakSet)}:{name:null,message:typeof a=="string"?a:String(a),stack:null,cause:vt(a,1,new WeakSet)}:null}function Xt(){return{totalEvents:0,severityCounts:{debug:0,info:0,warn:0,error:0},categoryCounts:{session:0,resource:0,playback:0,runtime:0,recovery:0,"ui-trigger":0},failureCount:0,lastFailureEvent:null}}function Sc(a){const e=a??Xt();return{totalEvents:e.totalEvents,severityCounts:{debug:e.severityCounts.debug,info:e.severityCounts.info,warn:e.severityCounts.warn,error:e.severityCounts.error},categoryCounts:{session:e.categoryCounts.session,resource:e.categoryCounts.resource,playback:e.categoryCounts.playback,runtime:e.categoryCounts.runtime,recovery:e.categoryCounts.recovery,"ui-trigger":e.categoryCounts["ui-trigger"]},failureCount:e.failureCount,lastFailureEvent:e.lastFailureEvent?{...e.lastFailureEvent}:null}}function na(a){const e=Xt();return a.forEach(t=>{e.totalEvents+=1,e.severityCounts[t.severity]+=1,e.categoryCounts[t.category]+=1,t.severity==="error"&&(e.failureCount+=1,e.lastFailureEvent={eventId:t.eventId,eventName:t.eventName,timestamp:t.timestamp,isoTime:t.isoTime,message:t.message,trackId:t.trackId,clipId:t.clipId,syncRequestId:t.syncRequestId,playbackAttemptId:t.playbackAttemptId})}),e}function Ln(a){return Sc(a.summary)}function Cc(a){return{sequence:a.sequence,timestamp:a.timestamp,isoTime:a.isoTime,severity:a.severity,category:a.category,eventName:a.eventName,message:a.message,syncRequestId:a.syncRequestId,playbackAttemptId:a.playbackAttemptId,trackId:a.trackId,clipId:a.clipId,extra:a.extra,error:a.error}}function vc(a,e){a.totalEvents+=1,a.severityCounts[e.severity]+=1,a.categoryCounts[e.category]+=1,e.severity==="error"&&(a.failureCount+=1,a.lastFailureEvent={eventId:e.eventId,eventName:e.eventName,timestamp:e.timestamp,isoTime:e.isoTime,message:e.message,trackId:e.trackId,clipId:e.clipId,syncRequestId:e.syncRequestId,playbackAttemptId:e.playbackAttemptId})}function Tc(a){return{enabled:(a==null?void 0:a.enabled)??Ge.enabled,persist:(a==null?void 0:a.persist)??Ge.persist,storageQuotaMb:(a==null?void 0:a.storageQuotaMb)??Ge.storageQuotaMb,maxSessions:Math.max(1,(a==null?void 0:a.maxSessions)??Ge.maxSessions),maxHotEvents:Math.max(20,(a==null?void 0:a.maxHotEvents)??Ge.maxHotEvents),includeFullSourceUrl:(a==null?void 0:a.includeFullSourceUrl)??Ge.includeFullSourceUrl,enablePanel:(a==null?void 0:a.enablePanel)??Ge.enablePanel,consoleSeverityThreshold:(a==null?void 0:a.consoleSeverityThreshold)??Ge.consoleSeverityThreshold}}function bc(){try{if(typeof globalThis.localStorage>"u")return null;const a=globalThis.localStorage.getItem(Qs);if(!a)return null;const e=JSON.parse(a);return(e==null?void 0:e.version)!==ii||!Array.isArray(e.sessions)?null:e}catch{return null}}function wc(){try{if(typeof globalThis.localStorage>"u")return null;const a=globalThis.localStorage.getItem(Pr);if(!a)return null;const e=JSON.parse(a);return(e==null?void 0:e.version)!==Yr||typeof e.sessionId!="string"||typeof e.failureEventId!="string"||!Array.isArray(e.events)?null:e}catch{return null}}function sa(a){const e=Array.isArray(a.events)?a.events:[];return{...a,updatedAt:a.updatedAt||a.startedAt,events:e,summary:na(e)}}function Dt(a,e){const t=a.slice(-e.maxSessions).map(r=>{const n=r.events.slice(-e.maxHotEvents);return sa({...r,events:n,updatedAt:r.updatedAt||r.startedAt})}),i=Math.max(2e5,Math.floor(e.storageQuotaMb*1024*1024));for(;t.length>0&&JSON.stringify({version:ii,sessions:t}).length>i;)t.shift();return t}async function kc(a){return aa(ta,a)}async function xc(a){return aa(ia,a)}async function aa(a,e){if(typeof indexedDB>"u")return!1;try{const t=await new Promise((i,r)=>{const n=indexedDB.open(ea,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(Ye)||s.createObjectStore(Ye)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)});return await new Promise((i,r)=>{const n=t.transaction(Ye,"readwrite");n.objectStore(Ye).put(e,a),n.oncomplete=()=>i(),n.onerror=()=>r(n.error),n.onabort=()=>r(n.error)}),t.close(),!0}catch{return!1}}async function Pc(){const a=await oa(ta);return a&&typeof a=="object"&&"version"in a&&a.version===ii&&"sessions"in a&&Array.isArray(a.sessions)?a:null}async function _c(){const a=await oa(ia);return a&&typeof a=="object"&&"version"in a&&a.version===Yr&&"sessionId"in a&&typeof a.sessionId=="string"&&"failureEventId"in a&&typeof a.failureEventId=="string"&&"events"in a&&Array.isArray(a.events)?a:null}async function oa(a){if(typeof indexedDB>"u")return null;try{const e=await new Promise((i,r)=>{const n=indexedDB.open(ea,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(Ye)||s.createObjectStore(Ye)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)}),t=await new Promise((i,r)=>{const o=e.transaction(Ye,"readonly").objectStore(Ye).get(a);o.onsuccess=()=>i(o.result??null),o.onerror=()=>r(o.error)});return e.close(),t}catch{return null}}function Ic(a,e){return!a&&!e?null:{...a??{},...e??{}}}class la{constructor(e){p(this,"config");p(this,"listeners",new Set);p(this,"liveListeners",new Map);p(this,"state");p(this,"currentSessionId",null);p(this,"latestFailureWindow");p(this,"activeFailureCapture",null);p(this,"notifyTimeoutId",null);p(this,"persistTimeoutId",null);this.config=Tc(e);const t=bc();this.latestFailureWindow=wc(),this.state={version:ii,sessions:Dt((t==null?void 0:t.sessions)??[],this.config)},this.restoreIndexedDbState()}startSession(e){const t=new Date().toISOString(),i={sessionId:An("diag-session"),startedAt:Date.now(),updatedAt:Date.now(),metadata:En(e,{capturedAt:t}),sequence:0,events:[],summary:Xt()};return this.currentSessionId=i.sessionId,this.state.sessions=Dt([...this.state.sessions,i],this.config),this.emit({severity:"info",category:"session",eventName:"session.started",message:"Diagnostic session started",extra:i.metadata??void 0}),this.getSnapshot()}getCurrentSessionId(){return this.currentSessionId}emit(e){if(!this.config.enabled)return null;const t=this.ensureCurrentSession();if(!t)return null;const i=Date.now();t.updatedAt=i;const r=this.findCoalescedEvent(t,e,i);if(r)return this.updateCoalescedEvent(r,e,i),this.schedulePersist(),this.scheduleNotify(),r;t.sequence+=1;const n=this.createEvent(t,e,i,t.sequence);return t.events.push(n),vc(t.summary,n),this.trimSessionEvents(t),this.captureFailureWindow(t,n),this.state.sessions=Dt(this.state.sessions,this.config),this.emitToConsole(n),this.schedulePersist(),this.scheduleNotify(),n}subscribe(e){return this.listeners.add(e),e(this.getSnapshot()),()=>{this.listeners.delete(e)}}subscribeLive(e,t=_n){const i=Math.max(1,t);return this.liveListeners.set(e,i),e(this.getLiveSnapshot(this.currentSessionId,i)),()=>{this.liveListeners.delete(e)}}getSnapshot(e=this.currentSessionId){const t=this.resolveSession(e);return{sessionId:t.sessionId,startedAt:t.startedAt,updatedAt:t.updatedAt,metadata:t.metadata,events:[...t.events],summary:Ln(t)}}getLiveSnapshot(e=this.currentSessionId,t=_n){const i=this.resolveSession(e),r=Math.max(1,t);return{sessionId:i.sessionId,startedAt:i.startedAt,updatedAt:i.updatedAt,metadata:i.metadata,summary:Ln(i),recentEvents:i.events.slice(-r).map(n=>Cc(n))}}exportPackage(e={}){var c;const t=this.getSnapshot(e.sessionId??this.currentSessionId),i=Math.max(1,e.recentFailureContext??40),r=Math.max(1,e.recentEventsFallback??200),n=new Date().toISOString(),{failureWindow:s,failureWindowSource:o}=this.resolveExportFailureWindow(t,i,r),l=En(t.metadata,{capturedAt:((c=t.metadata)==null?void 0:c.environmentCapturedAt)??null,exportedAt:n});return{exportedAt:n,session:{sessionId:t.sessionId,startedAt:t.startedAt,updatedAt:t.updatedAt,metadata:l,summary:t.summary},rawEvents:t.events,failureWindow:s,failureWindowSource:o}}clear(e=!0){var t,i;if(this.clearScheduledTasks(),e&&this.currentSessionId){this.state.sessions=this.state.sessions.filter(r=>r.sessionId!==this.currentSessionId),((t=this.latestFailureWindow)==null?void 0:t.sessionId)===this.currentSessionId&&(this.latestFailureWindow=null),((i=this.activeFailureCapture)==null?void 0:i.sessionId)===this.currentSessionId&&(this.activeFailureCapture=null),this.currentSessionId=null,this.persistNow(),this.notifyNow();return}this.state.sessions=[],this.latestFailureWindow=null,this.activeFailureCapture=null,this.currentSessionId=null,this.persistNow(),this.notifyNow()}ensureCurrentSession(){return this.currentSessionId||this.startSession(),this.state.sessions.find(e=>e.sessionId===this.currentSessionId)??null}resolveSession(e=this.currentSessionId){return(e?this.state.sessions.find(t=>t.sessionId===e):null)??this.state.sessions[this.state.sessions.length-1]??{sessionId:"diagnostics-empty",startedAt:Date.now(),updatedAt:Date.now(),metadata:null,sequence:0,events:[],summary:Xt()}}createEvent(e,t,i,r,n=An("diag-event")){return{eventId:n,sessionId:e.sessionId,sequence:r,timestamp:i,isoTime:new Date(i).toISOString(),perfTimeMs:gc(),severity:t.severity,category:t.category,eventName:t.eventName,message:t.message??t.eventName,syncRequestId:t.syncRequestId??null,playbackAttemptId:t.playbackAttemptId??null,previewBackend:t.previewBackend??null,trackId:t.trackId??null,clipId:t.clipId??null,slotKey:t.slotKey??null,sourceUrl:this.normalizeUrl(t.sourceUrl),desiredSourceUrl:this.normalizeUrl(t.desiredSourceUrl),actualSourceUrl:this.normalizeUrl(t.actualSourceUrl),mediaState:Fi(t.mediaState),runtimeState:fc(t.runtimeState),error:yc(t.error),extra:Fi(t.extra)}}trimSessionEvents(e){const t=e.events.length-this.config.maxHotEvents;t<=0||(e.events=e.events.slice(t),e.summary=na(e.events))}findCoalescedEvent(e,t,i){if(!pc.has(t.eventName)||t.severity==="warn"||t.severity==="error")return null;const r=this.buildEventIdentity(t);for(let n=e.events.length-1;n>=0;n-=1){const s=e.events[n];if(i-s.timestamp>uc)break;if(this.areEventIdentitiesEqual(r,s))return s}return null}buildEventIdentity(e){const t=e.eventName==="preview.sync.requested"||e.eventName==="pending-preview.begin"?null:e.syncRequestId??null;return{eventName:e.eventName,playbackAttemptId:e.playbackAttemptId??null,trackId:e.trackId??null,clipId:e.clipId??null,slotKey:e.slotKey??null,syncRequestId:t}}areEventIdentitiesEqual(e,t){const i=t.eventName==="preview.sync.requested"||t.eventName==="pending-preview.begin"?null:t.syncRequestId;return e.eventName===t.eventName&&e.playbackAttemptId===t.playbackAttemptId&&e.trackId===t.trackId&&e.clipId===t.clipId&&e.slotKey===t.slotKey&&e.syncRequestId===i}updateCoalescedEvent(e,t,i){const r=this.createEvent({sessionId:e.sessionId,startedAt:i,updatedAt:i,metadata:null,sequence:e.sequence,events:[],summary:Xt()},t,i,e.sequence,e.eventId);Object.assign(e,r)}normalizeUrl(e){if(!e)return null;if(this.config.includeFullSourceUrl)return e;try{const t=new URL(e,typeof location<"u"?location.href:"https://localhost");return`${t.origin}${t.pathname}`}catch{return e.split("?")[0]||e}}emitToConsole(e){if(In[e.severity]<In[this.config.consoleSeverityThreshold]||e.severity!=="warn"&&e.severity!=="error")return;(e.severity==="error"?console.error.bind(console):console.warn.bind(console))(`[Diagnostics:${e.severity}] ${e.eventName}`,{message:e.message,sessionId:e.sessionId,playbackAttemptId:e.playbackAttemptId,syncRequestId:e.syncRequestId,trackId:e.trackId,clipId:e.clipId,error:e.error,extra:e.extra})}scheduleNotify(){this.notifyTimeoutId||(this.notifyTimeoutId=setTimeout(()=>{this.notifyTimeoutId=null,this.notifyNow()},hc))}notifyNow(){if(this.listeners.size>0){const e=this.getSnapshot();this.listeners.forEach(t=>t(e))}this.liveListeners.size>0&&this.liveListeners.forEach((e,t)=>{t(this.getLiveSnapshot(this.currentSessionId,e))})}schedulePersist(){this.config.persist&&(this.persistTimeoutId||(this.persistTimeoutId=setTimeout(()=>{this.persistTimeoutId=null,this.persistNow()},dc)))}persistNow(){if(!this.config.persist)return;const e={version:ii,sessions:Dt(this.state.sessions,this.config)};if(this.state=e,typeof indexedDB>"u"){this.persistToLocalStorage(e);return}Promise.all([kc(e),xc(this.latestFailureWindow)]).then(([t,i])=>{if(!(t&&i))try{this.persistToLocalStorage(t?null:e,i?void 0:this.latestFailureWindow)}catch{}})}clearScheduledTasks(){this.notifyTimeoutId&&(clearTimeout(this.notifyTimeoutId),this.notifyTimeoutId=null),this.persistTimeoutId&&(clearTimeout(this.persistTimeoutId),this.persistTimeoutId=null)}async restoreIndexedDbState(){var i,r;if(!this.config.persist)return;const[e,t]=await Promise.all([Pc(),_c()]);if((i=e==null?void 0:e.sessions)!=null&&i.length){const n=new Map;[...this.state.sessions,...e.sessions].forEach(s=>{const o=sa(s),l=n.get(o.sessionId);(!l||l.updatedAt<o.updatedAt)&&n.set(o.sessionId,o)}),this.state.sessions=Dt(Array.from(n.values()).sort((s,o)=>s.startedAt-o.startedAt),this.config)}t&&(!this.latestFailureWindow||t.updatedAt>=this.latestFailureWindow.updatedAt)&&(this.latestFailureWindow=t),((r=e==null?void 0:e.sessions)!=null&&r.length||t)&&this.notifyNow()}captureFailureWindow(e,t){if(t.severity==="error"&&(this.activeFailureCapture={sessionId:e.sessionId,failureEventId:t.eventId,remainingAfterEvents:Pn}),!this.activeFailureCapture||this.activeFailureCapture.sessionId!==e.sessionId)return;const i=this.buildFailureWindow(e,this.activeFailureCapture.failureEventId);i.length&&(this.latestFailureWindow={version:Yr,sessionId:e.sessionId,updatedAt:t.timestamp,failureEventId:this.activeFailureCapture.failureEventId,events:i},t.eventId!==this.activeFailureCapture.failureEventId&&(this.activeFailureCapture.remainingAfterEvents-=1),this.activeFailureCapture.remainingAfterEvents<=0&&(this.activeFailureCapture=null))}buildFailureWindow(e,t,i=Pn){const r=e.events.findIndex(n=>n.eventId===t);return r<0?[]:e.events.slice(Math.max(0,r-i),Math.min(e.events.length,r+i+1))}resolveExportFailureWindow(e,t,i){var o;const r=e.events.map((l,c)=>({event:l,index:c})).filter(({event:l})=>l.severity==="error"),n=r.length>0?r[r.length-1]:null,s=n?e.events.slice(Math.max(0,n.index-t),Math.min(e.events.length,n.index+t+1)):[];return n?{failureWindow:s,failureWindowSource:"live"}:((o=this.latestFailureWindow)==null?void 0:o.sessionId)===e.sessionId&&this.latestFailureWindow.events.length>0?{failureWindow:[...this.latestFailureWindow.events],failureWindowSource:"persisted"}:{failureWindow:e.events.slice(-i),failureWindowSource:"recent-events"}}persistToLocalStorage(e,t=this.latestFailureWindow){if(!(typeof globalThis.localStorage>"u")&&(e&&globalThis.localStorage.setItem(Qs,JSON.stringify(e)),t!==void 0)){if(t){globalThis.localStorage.setItem(Pr,JSON.stringify(t));return}globalThis.localStorage.removeItem(Pr)}}}function ca(a,e){return Ic(a,e)}function Ac(a){const e=[`${a.sequence}.`,`[${a.severity}]`,a.eventName];return a.clipId&&e.push(`clip=${a.clipId}`),a.trackId&&e.push(`track=${a.trackId}`),a.message&&e.push(`msg=${a.message}`),e.join(" ")}class ha{constructor(e){p(this,"container",null);p(this,"summaryElement",null);p(this,"failureElement",null);p(this,"eventListElement",null);p(this,"unsubscribe",null);this.diagnostics=e}mount(e){if(this.container)return;const t=document.createElement("div");t.className="timeline-diagnostics-panel",t.style.position="absolute",t.style.right="16px",t.style.bottom="16px",t.style.zIndex="5000",t.style.width="320px",t.style.maxHeight="280px",t.style.padding="12px",t.style.borderRadius="10px",t.style.border="1px solid rgba(255,255,255,0.12)",t.style.background="rgba(10, 12, 20, 0.9)",t.style.color="#F2F4F7",t.style.fontSize="12px",t.style.lineHeight="1.5",t.style.backdropFilter="blur(8px)",t.style.boxShadow="0 12px 36px rgba(0, 0, 0, 0.28)";const i=document.createElement("div");i.textContent="Diagnostics",i.style.fontWeight="700",i.style.marginBottom="8px";const r=document.createElement("div");r.style.opacity="0.9",r.style.marginBottom="8px";const n=document.createElement("div");n.style.marginBottom="8px",n.style.color="#FFD6D6";const s=document.createElement("div");s.style.display="flex",s.style.gap="8px",s.style.marginBottom="8px";const o=document.createElement("button");o.textContent="导出诊断包",o.style.flex="1",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.border="0",o.style.cursor="pointer",o.style.background="#F4B740",o.style.color="#1A1A1A",o.addEventListener("click",()=>{const h=this.diagnostics.exportPackage(),d=new Blob([JSON.stringify(h,null,2)],{type:"application/json"}),u=URL.createObjectURL(d),g=document.createElement("a");g.href=u,g.download=`timeline-diagnostics-${h.session.sessionId}.json`,g.click(),URL.revokeObjectURL(u)});const l=document.createElement("button");l.textContent="清空",l.style.padding="6px 10px",l.style.borderRadius="8px",l.style.border="1px solid rgba(255,255,255,0.18)",l.style.cursor="pointer",l.style.background="transparent",l.style.color="#F2F4F7",l.addEventListener("click",()=>{this.diagnostics.clear(!0),this.diagnostics.startSession()}),s.appendChild(o),s.appendChild(l);const c=document.createElement("pre");c.style.margin="0",c.style.padding="8px",c.style.borderRadius="8px",c.style.background="rgba(255,255,255,0.06)",c.style.overflow="auto",c.style.maxHeight="140px",c.style.whiteSpace="pre-wrap",c.style.wordBreak="break-word",t.appendChild(i),t.appendChild(r),t.appendChild(n),t.appendChild(s),t.appendChild(c),e.appendChild(t),this.container=t,this.summaryElement=r,this.failureElement=n,this.eventListElement=c,this.unsubscribe=this.diagnostics.subscribeLive(h=>{this.render(h)},8)}destroy(){var e,t;(e=this.unsubscribe)==null||e.call(this),this.unsubscribe=null,(t=this.container)==null||t.remove(),this.container=null,this.summaryElement=null,this.failureElement=null,this.eventListElement=null}render(e){if(!this.summaryElement||!this.failureElement||!this.eventListElement)return;this.summaryElement.textContent=`session=${e.sessionId} events=${e.summary.totalEvents} errors=${e.summary.failureCount}`;const t=e.summary.lastFailureEvent;this.failureElement.textContent=t?`最近失败: ${t.eventName}${t.clipId?` / ${t.clipId}`:""}`:"最近失败: 无",this.eventListElement.textContent=e.recentEvents.map(i=>Ac(i)).join(`
|
|
16
|
+
`)}}function Rn(a,e,t,i){const r=`[${a.toUpperCase()}] [${e}]`;if(i===void 0){console[a](`${r} ${t}`);return}console[a](`${r} ${t}`,i)}const G={debug(a,e,t){},debugLazy(a,e,t){},warn(a,e,t){Rn("warn",a,e,t)},error(a,e,t){Rn("error",a,e,t)}};class Ie{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={}}static renderClipCovers(e,t,i,r,n,s=!1){G.debugLazy("ClipCoverRenderer",()=>"renderClipCovers",()=>({videoSrc:n,coverCount:(t==null?void 0:t.length)??0,coverWidth:i,coverHeight:r}));const o=(e.getAttr(this.COVER_RENDER_VERSION_KEY)||0)+1;if(e.setAttr(this.COVER_RENDER_VERSION_KEY,o),!t||t.length===0){e.destroyChildren(),s||this.requestRender(e);return}const l=this.buildSegmentsDataSync(t,i,r,n);if(l){this.renderSegments(e,l,i,r),s||this.requestRender(e);return}s||(e.destroyChildren(),this.requestRender(e)),this.startRenderJob({coversGroup:e,coverSource:t,coverWidth:i,coverHeight:r,videoSrc:n,version:o})}static async startRenderJob(e){const{coversGroup:t,coverSource:i,coverWidth:r,coverHeight:n,videoSrc:s,version:o}=e,l=await this.buildSegmentsData(i,r,n,s);if(this.isRenderJobCurrent(t,o)){if(this.renderSegments(t,l,r,n),!this.isRenderJobCurrent(t,o)){t.destroyChildren();return}this.requestRender(t)}}static async buildSegmentsData(e,t,i,r){const n=e.length,s=r||e[0]||"",o=await this.getSafeKeyframeDimensions(s,e[0]),l=o.width/o.height,c=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),h=Math.max(1,Math.ceil(t/c)),d=[];if(h===1)d.push(0);else for(let g=0;g<h;g++)d.push(Math.round(g*(n-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static buildSegmentsDataSync(e,t,i,r){const n=e.length,s=r||e[0]||"",o=this.getCachedKeyframeDimensions(s,e[0]);if(!o)return null;const l=o.width/o.height,c=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),h=Math.max(1,Math.ceil(t/c)),d=[];if(h===1)d.push(0);else for(let g=0;g<h;g++)d.push(Math.round(g*(n-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static requestRender(e){var i,r;const t=(i=e.getLayer)==null?void 0:i.call(e);if((r=t==null?void 0:t.getStage)!=null&&r.call(t))try{e.draw(),t.batchDraw()}catch{}}static isRenderJobCurrent(e,t){return e.getAttr(this.COVER_RENDER_VERSION_KEY)===t}static renderSegments(e,t,i,r){e.destroyChildren(),e.clip({x:0,y:0,width:i,height:r});for(const{coverUrl:n,singleImageWidth:s,segmentStartX:o,segmentWidth:l}of t){const c=Math.max(s,.01),h=this.getCachedImage(n),d=new q.Group({x:o,y:0,clip:{x:0,y:0,width:l,height:r},name:"cover-segment"});h.src||(h.src=n);const u=new q.Image({image:h,cornerRadius:2,name:"cover-image"});u.x(0),u.y(0),u.width(c),u.height(r),d.add(u),e.add(d)}}static async getSafeKeyframeDimensions(e,t){try{const i=await this.getKeyframeDimensions(e,t);if(i!=null&&i.width&&(i!=null&&i.height))return i}catch{}return this.DEFAULT_DIMENSIONS}static getKeyframeDimensions(e,t){const i=t||e;if(this.keyframeDimensionsCache[i])return Promise.resolve(this.keyframeDimensionsCache[i]);if(this.keyframeDimensionsPromiseCache[i])return this.keyframeDimensionsPromiseCache[i];const r=new Promise(n=>{const s=this.getCachedImage(t);if(s.complete&&s.width>0){const l={width:s.width,height:s.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)};s.onload=()=>{const l={width:s.width,height:s.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},s.onerror=()=>{o(this.DEFAULT_DIMENSIONS)},s.src||(s.src=t)});return this.keyframeDimensionsPromiseCache[i]=r,r}static getCachedKeyframeDimensions(e,t){const i=t||e,r=this.keyframeDimensionsCache[i];if(r!=null&&r.width&&(r!=null&&r.height))return r;const n=this.imageCache[t];if(n!=null&&n.complete&&n.width>0&&n.height>0){const s={width:n.width,height:n.height};return this.keyframeDimensionsCache[i]=s,s}return null}static getCachedImage(e){const t=this.imageCache[e];if(t)return t;const i=new Image;return this.imageCache[e]=i,this.checkAndTrimCache(),i}static checkAndTrimCache(){const e=Object.keys(this.imageCache);if(e.length<=this.MAX_CACHE_SIZE)return;const t=e.length-this.MAX_CACHE_SIZE,i=e.filter(s=>{const o=this.imageCache[s];return o&&!o.complete}),r=e.filter(s=>!i.includes(s));let n=0;for(const s of i){if(n>=t)break;this.evictCacheKey(s),n++}for(const s of r){if(n>=t)break;this.evictCacheKey(s),n++}}static evictCacheKey(e){delete this.imageCache[e],delete this.keyframeDimensionsCache[e],delete this.keyframeDimensionsPromiseCache[e]}}p(Ie,"MIN_IMAGE_DISPLAY_WIDTH",24),p(Ie,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),p(Ie,"MAX_CACHE_SIZE",1e3),p(Ie,"DEFAULT_DIMENSIONS",{width:160,height:90}),p(Ie,"keyframeDimensionsCache",{}),p(Ie,"keyframeDimensionsPromiseCache",{}),p(Ie,"imageCache",{});const Ec='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.8437804474494934,2.934130300488281C2.0975289474494936,2.6803818004882816,2.5560352474494934,2.5258255004882812,3.4537861474494935,2.5258255004882812L7.691924847449493,2.5258255004882812C8.589675247449494,2.5258255004882812,9.048181847449493,2.6803818004882816,9.301930747449493,2.934130300488281C9.555688247449494,3.1878788004882814,9.710234947449493,3.6463940004882813,9.710234947449493,4.544136000488281L9.710234947449493,5.154385800488281L9.710234947449493,5.156664400488282L9.710234947449493,8.837531600488282L9.710234947449493,8.839810400488282L9.710234947449493,9.455756700488282C9.710234947449493,10.352920500488281,9.554433147449494,10.811444300488281,9.299509347449494,11.065193200488281C9.045182547449494,11.319528600488281,8.586177147449494,11.474209800488282,7.691924847449493,11.474209800488282L3.4537861474494935,11.474209800488282C2.6371141474494935,11.474209800488282,2.1565246474494932,11.20751000048828,1.8706969474494934,10.86509900048828C1.5731912474494933,10.50867840048828,1.4354756474494934,10.006423900488281,1.4354756474494934,9.455756700488282L1.4354756474494934,4.544136000488281C1.4354756474494934,3.6463940004882813,1.5900319474494935,3.1878788004882814,1.8437804474494934,2.934130300488281ZM9.917876547449493,11.684700500488281C10.391550347449494,11.212192500488282,10.559057547449493,10.52217200048828,10.582387647449494,9.67692760048828L11.516774647449493,10.33260820048828L11.516774647449493,10.33260820048828C11.978190647449493,10.658107800488281,12.521887647449493,10.806299200488281,12.992055647449494,10.562466600488282C13.461642647449493,10.318055200488281,13.653574647449494,9.787735900488281,13.653574647449494,9.222480300488282L13.653574647449494,4.777554700488281C13.653574647449494,4.212299300488281,13.461625647449493,3.6825676004882815,12.992624647449494,3.437568500488281C12.523623647449494,3.1925697004882814,11.980024647449493,3.3384564004882815,11.519194647449494,3.6604486004882815L11.518056647449493,3.661018400488281L10.582387647449494,4.3178380004882815C10.558470047449493,3.475504500488281,10.392209347449493,2.7870953004882812,9.920297947449493,2.315762820488281C9.406961747449493,1.8024266504882813,8.637509647449493,1.6508255004882812,7.691924847449493,1.6508255004882812L3.4537861474494935,1.6508255004882812C2.5082015474494934,1.6508255004882812,1.7387490474494933,1.8024266504882813,1.2254129674494934,2.315762820488281C0.7120767974494934,2.8290989004882814,0.5604756474494934,3.598560200488281,0.5604756474494934,4.544136000488281L0.5604756474494934,9.455756700488282C0.5604756474494934,10.13592340048828,0.7290598274494934,10.86171720048828,1.1986388574494935,11.42521860048828C1.6798959474494934,12.003300500488281,2.4271137474494937,12.349209500488282,3.4537861474494935,12.349209500488282L7.691924847449493,12.349209500488282C8.635176947449493,12.349209500488282,9.403962447449494,12.197448500488282,9.917876547449493,11.684700500488281ZM12.020781647449493,9.61682840048828L10.585234647449493,8.609952000488281L10.585234647449493,5.384101600488281L12.019642647449494,4.377937300488281L12.020212647449494,4.3773675004882815C12.352129647449493,4.145782500488281,12.531874647449493,4.183709400488281,12.587880647449493,4.212877700488281C12.643876647449494,4.242046400488281,12.778574647449494,4.368635700488282,12.778574647449494,4.777554700488281L12.778574647449494,9.222480300488282C12.778574647449494,9.631399600488281,12.643866647449494,9.757436800488282,12.588449647449494,9.786018400488281C12.533620647449494,9.814020200488281,12.354416647449494,9.852481800488281,12.021921647449494,9.617398300488281L12.020781647449493,9.61682840048828ZM3.3313089474494935,3.9374466004882813C3.0898080474494933,3.9374466004882813,2.8938089474494935,4.133445700488281,2.8938089474494935,4.374946600488281C2.8938089474494935,4.616447400488282,3.0898080474494933,4.812446600488281,3.3313089474494935,4.812446600488281L4.815419447449494,4.812446600488281C5.056920347449493,4.812446600488281,5.252919447449494,4.616447400488282,5.252919447449494,4.374946600488281C5.252919447449494,4.133445700488281,5.056920347449493,3.9374466004882813,4.815419447449494,3.9374466004882813L3.3313089474494935,3.9374466004882813Z" fill="#868A9C" fill-opacity="1"/></svg>',Lc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="16" height="16" viewBox="0 0 16 16"><path d="M11.206380472434997,2.733718973069763C9.993001372434998,1.991438673069763,8.552978872434998,1.6945722130697631,7.139648772434998,1.8937121730697632C5.7263186724349975,2.092858673069763,4.426350972434998,2.775678773069763,3.4596355724349976,3.825838973069763C2.4930013724349975,4.875998873069763,1.9263509724349976,6.228518873069763,1.8396810724349975,7.652945373069763C1.7596843224349974,9.077412973069762,2.1796875724349976,10.485612273069764,3.0196941724349977,11.637611373069763C3.8597005724349978,12.789678373069764,5.0796712724349975,13.614278373069762,6.459635572434998,13.970879373069764C7.839681072434997,14.327545373069762,9.299641972434998,14.194145373069762,10.593017972434998,13.593478373069763C11.892985472434997,12.992878373069763,12.933024472434997,11.962078373069764,13.552978472434997,10.676812573069764C14.173015472434997,9.391545673069762,14.326335472434998,7.9312790730697635,13.993001472434997,6.544878873069763C13.926350472434997,6.276532073069763,14.093017472434997,6.0061725730697635,14.359700472434998,5.941012273069763C14.626302472434997,5.875851973069763,14.899658472434998,6.040565873069763,14.966308472434998,6.308912673069763C15.353027472434997,7.920145873069763,15.173015472434997,9.617145873069763,14.453044472434998,11.110879373069762C13.732991472434998,12.604545373069763,12.519694472434997,13.802478373069762,11.019694472434997,14.500545373069762C9.513020872434998,15.198611373069763,7.812988672434997,15.353611373069763,6.2063802724349975,14.939145373069763C4.599690772434998,14.524678373069763,3.1930340724349975,13.566345373069764,2.2129720724349973,12.227478373069763C1.2329915724349976,10.888679373069763,0.7530111074349976,9.252079373069764,0.8463542074349976,7.5966790730697635C0.9396973124349975,5.941252573069764,1.5996907924349975,4.369405673069763,2.726318472434998,3.1489456730697634C3.8463543724349973,1.9284919730697632,5.359700572434997,1.134938593069763,6.999674672434997,0.9035053700697632C8.639648772434999,0.6720721230697632,10.312988672434997,1.0170720830697633,11.726318472434997,1.8797255730697633C11.966308472434998,2.023398773069763,12.039714472434998,2.3310454730697634,11.892985472434997,2.5668653730697635C11.753011472434997,2.8026921730697634,11.446370472434998,2.8773921730697634,11.206380472434997,2.733718973069763ZM11.686360472434998,5.413441573069763C11.879639472434997,5.608874673069764,11.879639472434997,5.925454473069763,11.686360472434998,6.1205485730697635L7.2396648724349975,10.559748073069763C7.046305572434997,10.754747773069763,6.7263186724349975,10.754615173069762,6.533040372434997,10.559481973069763L4.312988372434997,8.339814573069763C4.119710372434998,8.144614573069763,4.119710372434998,7.828014773069763,4.312988372434997,7.632747973069764C4.506347772434998,7.437481773069763,4.826334872434998,7.437481773069763,5.019694172434997,7.632747973069764L6.886311872434997,9.499081973069764L10.979655472434997,5.412814473069763C11.173015472434997,5.217727973069763,11.493001472434997,5.218008373069763,11.686360472434998,5.413441573069763Z" fill-rule="evenodd" fill="#24C744" fill-opacity="1"/></svg>',Rc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.3164876075,5.2511568456573485C2.7112323875,3.0589928456573485,4.7552132875,1.7354023456573486,6.9998931875,1.7354023456573486C9.2445726875,1.7354023456573486,11.2885531875,3.0589928456573485,12.6832981875,5.2511568456573485C13.0012411875,5.7498953456573485,13.1452941875,6.3880765456573485,13.1452941875,6.9999821456573486C13.1452941875,7.611905345657348,13.0012411875,8.250068445657348,12.6832981875,8.74882484565735C11.2885531875,10.940988745657348,9.2445726875,12.264562345657348,6.9998931875,12.264562345657348C4.7552132875,12.264562345657348,2.7112323875,10.940988745657348,1.3164876075,8.74882484565735C0.9985453175,8.250068445657348,0.8544921875,7.611905345657348,0.8544921875,6.9999821456573486C0.8544921875,6.3880765456573485,0.9985453175,5.749325945657349,1.3164876075,5.2511568456573485ZM6.9998931875,2.6104023456573486C5.1262406875,2.6104023456573486,3.3318786875,3.713480445657349,2.0549823875,5.721323445657349L2.0543771875,5.721323445657349C1.8473052375,6.0456564456573485,1.7294921875,6.509396745657349,1.7294921875,6.9999821456573486C1.7294921875,7.490567445657349,1.8473052375,7.954324945657349,2.0543771875,8.278070645657348L2.0549823875,8.27865814565735C3.3318786875,10.286483045657349,5.1262406875,11.389561845657349,6.9998931875,11.389561845657349C8.8735446875,11.389561845657349,10.6679076875,10.286483045657349,11.9448031875,8.27865814565735L11.9454091875,8.278070645657348C12.1518751875,7.954324945657349,12.2702941875,7.490567445657349,12.2702941875,6.9999821456573486C12.2702941875,6.509396745657349,12.1518751875,6.0456564456573485,11.9454091875,5.721323445657349L11.9448031875,5.721323445657349C10.6679076875,3.713480445657349,8.8735446875,2.6104023456573486,6.9998931875,2.6104023456573486ZM4.4741208875,7.002937045657348C4.4741208875,5.606429845657349,5.6034745875,4.4771115456573485,6.9999641875,4.4771115456573485C8.3964533875,4.4771115456573485,9.5258073875,5.606429845657349,9.5258073875,7.002937045657348C9.5258073875,8.399444345657349,8.3964533875,9.528762545657349,6.9999641875,9.528762545657349C5.6034745875,9.528762545657349,4.4741208875,8.399444345657349,4.4741208875,7.002937045657348ZM6.9999641875,5.3521115456573485C6.0864762875,5.3521115456573485,5.3491210875,6.089431545657349,5.3491210875,7.002937045657348C5.3491210875,7.916442645657349,6.0864762875,8.653762545657349,6.9999641875,8.653762545657349C7.9134516875,8.653762545657349,8.650807387499999,7.916442645657349,8.650807387499999,7.002937045657348C8.650807387499999,6.089431545657349,7.9134516875,5.3521115456573485,6.9999641875,5.3521115456573485Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',Dc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="18" height="18" viewBox="0 0 18 18"><path d="M3.5486246148989866,6.472501117640625C3.7632801848989867,6.361666362640625,4.026926634898987,6.445068359640625,4.138366634898987,6.659741711640625C4.944508744898987,8.214329931640625,6.797759844898987,9.340158931640625,8.999857544898987,9.340158931640625C11.201954944898986,9.340158931640625,13.055775244898987,8.214329931640625,13.861347544898987,6.659741711640625C13.972788544898988,6.445068359640625,14.237040544898987,6.361666362640625,14.451090544898987,6.472501117640625C14.665781544898987,6.583905531640625,14.749770544898986,6.847569761640625,14.638366544898988,7.062243101640625C14.367100544898987,7.584907531640625,14.003692544898987,8.060913131640625,13.566192544898987,8.475074731640625L14.459278544898988,9.368161431640626C14.630177544898986,9.539077731640624,14.630177544898986,9.816164531640625,14.459278544898988,9.987080831640625C14.288344544898987,10.157996931640625,14.011275544898988,10.157996931640625,13.840342544898986,9.987080831640625L12.883701944898986,9.030405531640625C12.378519644898986,9.383328631640625,11.808039344898987,9.667999231640625,11.192590844898987,9.869249831640625L11.502344744898986,11.025413531640625C11.564757944898988,11.258743331640625,11.426508544898986,11.499069231640625,11.193196444898987,11.561500531640625C10.959848544898986,11.623913731640625,10.720092444898988,11.485664331640624,10.657109344898988,11.251747131640624L10.345611244898986,10.087999831640625C9.911600744898987,10.171401731640625,9.460677744898987,10.215158931640625,8.999857544898987,10.215158931640625C8.548365244898987,10.215158931640625,8.107340444898988,10.173164131640625,7.681518244898987,10.093233631640626L7.371195444898987,11.251747131640624C7.308781744898987,11.485664331640624,7.069025444898987,11.623913731640625,6.835108144898987,11.561500531640625C6.6017607448989875,11.499069231640625,6.4635111448989875,11.258743331640625,6.525924544898986,11.025413531640625L6.833363644898987,9.877990731640626C6.192280844898987,9.670900831640624,5.600189044898986,9.374000531640625,5.078094344898987,9.003578231640624L4.095179204898987,9.987080831640625C3.924280764898987,10.157996931640625,3.6471760548989867,10.157996931640625,3.476277614898987,9.987080831640625C3.305343588298987,9.816164531640625,3.305343588298987,9.539077731640624,3.476277614898987,9.368161431640626L4.400873744898987,8.443583031640625C3.9779357348989866,8.036987331640624,3.6256001248989866,7.572072231640625,3.361348427898987,7.062243101640625C3.250513676898987,6.847569761640625,3.3339334728989867,6.583905531640625,3.5486246148989866,6.472501117640625Z" fill="#FFFFFF" fill-opacity="1"/></svg>',Mc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path d="M9.217651334374999,1.6159667934375C8.817657434375,1.7239685034375,8.579650834375,2.1349792434375,8.687652634374999,2.5349731234375C8.794677734375,2.9349670234375003,9.205657934375001,3.1719665234375,9.605651834375,3.0649719234374997C14.537658734375,1.7439575234375,19.612670734375,4.6739807234375,20.934661734375,9.6059570234375C22.255676734375,14.5379635234375,19.325652734375,19.6129765234375,14.393676734375,20.9349675234375C9.461669934375,22.2559815234375,4.3866577343749995,19.3259585234375,3.064666734375,14.3939815234375C2.3956604343750003,11.8969725234375,2.816650434375,9.3629761234375,4.036651634375,7.2969665234375C4.246673534375001,6.9399719234375,4.128662134375,6.4799804234375,3.771667434375,6.2699585234375C3.415649434375,6.0589599234375,2.955657934375,6.1779785234375,2.744659434375,6.5339660234375C1.3286743163749999,8.9329834234375,0.8386535643749999,11.8789675234375,1.615661624375,14.7819825234375C3.151672334375,20.5139775234375,9.049652134375,23.9199825234375,14.781677734375,22.3839725234375C20.513671734375,20.8479615234375,23.919677734375,14.9499815234375,22.383666734375,9.2179565234375C20.847656734375,3.4859619234375,14.949676734375,0.07995602343750008,9.217651334374999,1.6159667934375Z" fill="#C9CBD4" fill-opacity="1"/><path d="M16.7496337890625,12C16.7496337890625,14.6270103,14.6266440890625,16.75,11.9996337890625,16.75C9.3736238890625,16.75,7.2496337890625,14.6270103,7.2496337890625,12C7.2496337890625,9.3739901,9.3736238890625,7.25,11.9996337890625,7.25C14.6266440890625,7.25,16.7496337890625,9.3739901,16.7496337890625,12ZM11.9996337890625,15.25C13.7976336890625,15.25,15.2496337890625,13.7979999,15.2496337890625,12C15.2496337890625,10.2020001,13.7976336890625,8.75,11.9996337890625,8.75C10.2016338890625,8.75,8.7496337890625,10.2020001,8.7496337890625,12C8.7496337890625,13.7979999,10.2016338890625,15.25,11.9996337890625,15.25Z" fill="#C9CBD4" fill-opacity="1"/></svg>',Oc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M12.594244271484374,3.926410052418518C12.594244271484374,3.9339934524185183,12.594244271484374,3.941576852418518,12.594244271484374,3.949160252418518L12.594244271484374,10.004165252418519L12.594244271484374,10.009998952418519C12.591269271484375,11.254248752418517,11.581520271484376,12.261664752418518,10.336686171484375,12.261664752418518C9.090102671484374,12.261664752418518,8.079185971484375,11.250748752418518,8.079185971484375,10.004165252418519C8.079185971484375,8.757582352418517,9.090102671484374,7.746665552418518,10.336686171484375,7.746665552418518C10.857602071484376,7.746665552418518,11.337102871484374,7.922832152418518,11.719244271484374,8.219165952418518L11.719244271484374,4.510315252418518L5.920881771484375,6.091725952418518L5.920881771484375,11.212248752418517L5.920881771484375,11.217499752418519C5.920881771484375,12.464083752418517,4.909947871484375,13.474998752418518,3.663387771484375,13.474998752418518C2.416787071484375,13.474998752418518,1.405852854251865,12.464082752418518,1.405852854251865,11.217499752418519C1.405852854251865,9.970916352418518,2.416786871484375,8.959999652418517,3.663387771484375,8.959999652418517C4.184269171484376,8.959999652418517,4.663780971484375,9.136166252418517,5.045881971484375,9.432499552418518L5.045881971484375,5.765065352418518C5.045881971484375,5.759809652418518,5.045881971484375,5.754577252418518,5.045881971484375,5.749326852418518L5.045881971484375,3.879142852418518C5.045881971484375,2.9108270524185182,5.645524971484375,2.2224822524185184,6.488441471484375,1.9926605524185181L10.128436071484375,1.000982272418518C10.652911171484375,0.8580656054185181,11.273518571484376,0.8131547724185181,11.781602271484376,1.1106431024185182C12.324102271484374,1.4273930824185181,12.594244271484374,2.0416489524185177,12.594244271484374,2.887488152418518L12.594244271484374,3.926410052418518ZM11.719244271484374,2.887487652418518C11.719244271484374,2.216660252418518,11.514435271484375,1.967576852418518,11.340019271484374,1.866071042418518C11.132935571484374,1.744731902418518,10.796352371484375,1.726076842418518,10.358268771484376,1.845648522418518L6.718304671484375,2.8373209524185183C6.231775271484375,2.969731652418518,5.920881771484375,3.330809252418518,5.920881771484375,3.879142452418518L5.920881771484375,5.184648152418518L11.719244271484374,3.603231552418518L11.719244271484374,2.887487652418518ZM3.663388271484375,12.599998752418518C4.426948071484375,12.599998752418518,5.045882471484375,11.981081752418518,5.045882471484375,11.217499752418519C5.045882471484375,10.453916152418518,4.426948271484375,9.834999652418517,3.663388271484375,9.834999652418517C2.8997932714843753,9.834999652418517,2.280853391484375,10.453916152418518,2.280853391484375,11.217499752418519C2.280853391484375,11.981082752418518,2.899793471484375,12.599998752418518,3.663388271484375,12.599998752418518ZM8.954185971484375,10.004165252418519C8.954185971484375,10.767749452418519,9.573102971484374,11.386664752418518,10.336686171484375,11.386664752418518C11.100269271484375,11.386664752418518,11.719244271484374,10.767748452418518,11.719244271484374,10.004165252418519C11.719244271484374,9.240582152418519,11.100269271484375,8.621665552418518,10.336686171484375,8.621665552418518C9.573102971484374,8.621665552418518,8.954185971484375,9.240582152418519,8.954185971484375,10.004165252418519Z" fill="#868A9C" fill-opacity="1"/></svg>',Bc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M11.305803496070862,2.8583284381607053C11.498882496070863,2.713661038160706,11.773050496070862,2.7521666381607055,11.918296496070862,2.9458338381607057C13.720794496070862,5.347419838160706,13.720794496070862,8.652577538160706,11.918296496070862,11.054163138160705C11.773050496070862,11.247830138160706,11.498882496070863,11.286335138160705,11.305803496070862,11.141669138160706C11.112723496070862,10.996414138160706,11.073630496070862,10.722246738160706,11.218307496070862,10.529166838160705C12.787475496070861,8.439078938160705,12.787475496070861,5.5609179381607055,11.218307496070862,3.4708303381607055C11.073630496070862,3.2777506381607058,11.112723496070862,3.0035830381607056,11.305803496070862,2.8583284381607053ZM10.850643496070862,4.404167338160706C10.705398196070862,4.210500138160706,10.431231096070862,4.171994538160705,10.238133096070861,4.316661938160705C10.044466596070862,4.461916538160706,10.005978196070862,4.736083838160706,10.150637296070862,4.929163538160706C11.072313496070862,6.156499038160706,11.072313496070862,7.843498338160706,10.150637296070862,9.070833838160706C10.005978196070862,9.263913738160706,10.044466596070862,9.538080838160706,10.238133096070861,9.683335938160706C10.431231096070862,9.828002538160705,10.705398196070862,9.789497038160706,10.850643496070862,9.595830538160705C12.005633496070862,8.058162338160706,12.005633496070862,5.941834538160705,10.850643496070862,4.404167338160706ZM6.527554596070861,1.3638305381607054C7.564730296070862,0.4561640581607056,9.188140496070861,1.1929142881607055,9.188140496070861,2.5713347381607052L9.188140496070861,11.428662138160705C9.188140496070861,12.807083138160706,7.564730296070862,13.543833138160705,6.527554596070861,12.636166138160705L3.9608915960708617,10.390329938160706C3.934063996070862,10.367000238160706,3.9002226960708617,10.354164738160705,3.8646364960708617,10.354164738160705L2.917307496070862,10.354164738160705C1.7092156960708618,10.354164738160705,0.7298074960708618,9.374747838160706,0.7298074960708618,8.166665238160705L0.7298074960708618,5.8333321381607055C0.7298074960708618,4.6252492381607055,1.7092156960708618,3.6458321381607055,2.917307496070862,3.6458321381607055L3.8646364960708617,3.6458321381607055C3.9002226960708617,3.6458321381607055,3.934063996070862,3.6329969381607055,3.9608915960708617,3.6096674381607055L6.527554596070861,1.3638305381607054ZM8.313140496070861,2.5713347381607052C8.313140496070861,1.9448317881607056,7.575215496070862,1.6099954881607057,7.103891996070862,2.0224125381607054L4.537228696070862,4.268249638160706C4.351145196070862,4.430994638160706,4.111976496070862,4.520831938160706,3.8646364960708617,4.520831938160706L2.917307496070862,4.520831938160706C2.192217496070862,4.520831938160706,1.6048074960708618,5.108250738160706,1.6048074960708618,5.8333321381607055L1.6048074960708618,8.166665238160705C1.6048074960708618,8.891746138160705,2.192217496070862,9.479165638160705,2.917307496070862,9.479165638160705L3.8646364960708617,9.479165638160705C4.111976496070862,9.479165638160705,4.351145196070862,9.569002738160705,4.537228696070862,9.731748238160705L7.103891996070862,11.977584138160706C7.575215496070862,12.390002138160705,8.313140496070861,12.055165138160705,8.313140496070861,11.428662138160705L8.313140496070861,2.5713347381607052Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',Gc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M9.188069328125,2.7498358381607053L9.188069328125,2.5713360381607053C9.188069328125,1.1929155481607057,7.564641028125,0.4561653181607056,6.527501128125,1.3638317881607056L3.960820428125,3.6096686381607057C3.933975228125,3.6329981381607057,3.900151528125,3.6458331381607056,3.864583228125,3.6458331381607056L2.917236328125,3.6458331381607056C1.709162358125,3.6458331381607056,0.729736328125,4.625250238160706,0.729736328125,5.833333138160706L0.729736328125,8.166666138160705C0.729736328125,8.990334138160705,1.1847533881249999,9.707831938160705,1.857309928125,10.080586038160705L2.519968628125,9.417918838160706C1.989151028125,9.249912838160705,1.604736328125,8.752919338160705,1.604736328125,8.166666138160705L1.604736328125,5.833333138160706C1.604736328125,5.108252138160705,2.192164028125,4.520833138160706,2.917236328125,4.520833138160706L3.864583228125,4.520833138160706C4.111887428125,4.520833138160706,4.351074028125,4.4309958381607055,4.537139628125,4.268250538160705L7.103820828125,2.0224138381607055C7.575144328125,1.6099967381607057,8.313069328125,1.9448330381607055,8.313069328125,2.5713360381607053L8.313069328125,3.6248358381607058L9.188069328125,2.7498358381607053Z" fill="#FFFFFF" fill-opacity="1"/><path d="M9.188069388879395,6.8751726150512695L8.313069388879395,7.7501726150512695L8.313069388879395,11.42867231505127C8.313069388879395,12.055175315051269,7.575144088879394,12.39001181505127,7.103820288879394,11.97759441505127L5.493814768879394,10.56883951505127L4.8737382888793945,11.18892481505127L6.5275010888793945,12.63617661505127C7.564640988879395,13.54384331505127,9.188069388879395,12.807092715051269,9.188069388879395,11.42867231505127L9.188069388879395,6.8751726150512695Z" fill="#FFFFFF" fill-opacity="1"/><path d="M10.519225743566894,5.543419959263916C11.048904063566894,6.679164689263916,10.926391243566895,8.038332489263915,10.150583580566895,9.070834589263917C10.005889575566895,9.263914589263916,10.044412931566894,9.538081689263915,10.238062213566895,9.683336689263916C10.431141853566894,9.828003889263915,10.705327033566894,9.789498289263916,10.850555063566894,9.595831389263916C11.887160943566894,8.215666289263917,11.993331543566894,6.369420189263916,11.169067043566894,4.893587589263916L10.519225743566894,5.543419959263916Z" fill="#FFFFFF" fill-opacity="1"/><path d="M11.747202221848145,4.3160754470959475C12.761021631848145,6.290655617095947,12.584853731848145,8.708574817095947,11.218093551848144,10.529159117095947C11.073435149848144,10.722238517095947,11.112528165848145,10.996406117095948,11.305607791848145,11.141660717095947C11.498687411848145,11.286328317095947,11.772872571848145,11.247822717095946,11.918100651848144,11.054155317095947C13.545587731848144,8.886487017095948,13.703704331848144,5.9814896170959475,12.392949131848145,3.6703286170959473L11.747202221848145,4.3160754470959475Z" fill="#FFFFFF" fill-opacity="1"/><path d="M12.5598954921875,2.0591658358917235C12.7307934921875,1.8882496358917238,12.7307934921875,1.6117501858917236,12.5598954921875,1.4408339558917236C12.3889614921875,1.2699177268917237,12.1124624921875,1.2699177268917237,11.9415284921875,1.4408339558917236L1.4415283221875,11.940833335891723C1.2706298831875,12.111750335891724,1.2706298831875,12.388249335891723,1.4415283221875,12.559165335891723C1.6124623421875,12.730081335891724,1.8889617921875002,12.730081335891724,2.0598958121875,12.559165335891723L12.5598954921875,2.0591658358917235Z" fill="#FFFFFF" fill-opacity="1"/></svg>',Fc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M3.348292020680237,2.6424992084503174C2.923644920680237,2.6424992084503174,2.578287720680237,2.9849191084503177,2.578287720680237,3.4125035084503175L2.578287720680237,4.474174308450317C2.578287720680237,4.715657508450317,2.382288570680237,4.911674308450317,2.140787720680237,4.911674308450317C1.8992868706802368,4.911674308450317,1.7032877206802368,4.715657508450317,1.7032877206802368,4.474174308450317L1.7032877206802368,3.4125035084503175C1.7032877206802368,2.4984104584503175,2.442957520680237,1.7674992084503174,3.348292020680237,1.7674992084503174L10.651636720680237,1.7674992084503174C11.565124120680236,1.7674992084503174,12.296640720680237,2.5071690084503175,12.296640720680237,3.4125035084503175L12.296640720680237,4.474174308450317C12.296640720680237,4.715657508450317,12.100641720680237,4.911674308450317,11.859140720680237,4.911674308450317C11.617640120680237,4.911674308450317,11.421641020680237,4.715657508450317,11.421641020680237,4.474174308450317L11.421641020680237,3.4125035084503175C11.421641020680237,2.9878386084503177,11.079203220680236,2.6424992084503174,10.651636720680237,2.6424992084503174L7.435114520680237,2.6424992084503174C7.436289420680237,2.657666388450317,7.437464320680236,2.6734210884503176,7.437464320680236,2.6891580184503177L7.437464320680236,11.357500308450318L8.714965420680237,11.357500308450318C8.956466320680237,11.357500308450318,9.152465420680237,11.553499508450317,9.152465420680237,11.795000208450318C9.152465420680237,12.036501208450318,8.956466320680237,12.232500208450318,8.714965420680237,12.232500208450318L5.284962820680237,12.232500208450318C5.043461920680237,12.232500208450318,4.847462820680237,12.036501208450318,4.847462820680237,11.795000208450318C4.847462820680237,11.553499508450317,5.043461920680237,11.357500308450318,5.284962820680237,11.357500308450318L6.562464320680236,11.357500308450318L6.562464320680236,2.6891580184503177C6.562464320680236,2.6734210884503176,6.563033720680237,2.657666388450317,6.564814220680237,2.6424992084503174L3.348292020680237,2.6424992084503174Z" fill="#868A9C" fill-opacity="1"/></svg>',Hc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="2" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="4" y="4.5" width="1" height="6" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="6" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="8" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="10" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="12" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="14" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="16" y="6.5" width="1" height="2" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/></svg>',Nc='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="2" y="7" width="15" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="4" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="6" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="8" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="10" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="12" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="14" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="16" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/></svg>',$c=new Map([["OmAi-camera",Ec],["OmAi-accept",Lc],["OmAi-display",Rc],["OmAi-hide",Dc],["OmAi-loading",Mc],["OmAi-music",Oc],["OmAi-volume",Bc],["OmAi-volume-mute",Gc],["OmAi-text",Fc],["clip-audio",Hc],["clip-without-audio",Nc]]),Dn=new Map;function Te(a){return $c.get(a)??""}function zc(a){const e=Dn.get(a);if(e)return e;const t=Te(a);if(!t)return null;const i=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`,r=typeof Image>"u"?{src:i,complete:!0,naturalWidth:1,addEventListener:()=>{}}:new Image;return"decoding"in r&&(r.decoding="async"),r.src=i,Dn.set(a,r),r}const de=3,Mn=10,Vc=4,Uc=6,On=8,Bn=14,_r=10,Wc=12,Gn=4,da=1,Hi=28,ua=8,Ir=19,Ar=15;function ri(a,e,t,i,r=E.white,n=E.black,s=1){return new q.Rect({x:a,y:e,width:t,height:i,fill:r,stroke:n,strokeWidth:s})}function Ni(a,e,t,i=12,r="Arial",n=E.black,s="left",o="top"){return new q.Text({text:a,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:s,verticalAlign:o})}function wt(a=0,e=0){return new q.Group({x:a,y:e})}function qi(a,e,t,i){if(i){a.add(new q.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),a.add(new q.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}a.add(new q.Rect({x:0,y:0,width:de,height:t,name:"clip-resize-left"})),a.add(new q.Rect({x:e-de,y:0,width:de,height:t,name:"clip-resize-right"}))}function Yc(a,e,t,i){const r=a.findOne(".clip-resize-left"),n=a.findOne(".clip-resize-right");return!r||!n?!1:(r.x(0),r.y(0),r.width(de),r.height(t),n.x(e-de),n.y(0),n.width(de),n.height(t),!0)}function pa(a,e,t){const i=e?a.clipSelectedBorder:E.transparent,r=e?da:0;return t==="audio"?{background:E.audioClipBackground,label:a.audioClipText||a.clipName,accent:a.audioClipAccent||a.clipHandle,coverBackground:a.clipCoverBackground||Q.clipCoverBackground,border:i,borderWidth:r}:t==="text"?{background:E.textClipBackground,label:a.clipName,accent:a.clipHandle,coverBackground:a.clipCoverBackground||E.accentCoverFallback,border:i,borderWidth:r}:{background:E.videoClipBackground,label:a.clipName,accent:a.clipHandle,coverBackground:a.clipCoverBackground||E.accentCoverFallback,border:i,borderWidth:r}}function Xc(a,e,t,i){const r=ri(0,0,e,t,i.background,i.border,i.borderWidth);r.cornerRadius(Math.min(4,Math.floor(e/2))),r.name("clip-background"),a.add(r),qi(a,e,t,!0)}function qc(a,e,t){const i=ri(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),a.add(i),qi(a,e.width,e.height,!1);const r=15,n=e.height-r-4,s=e.width-de*2,o=wt(de,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:s,height:n}),a.add(o);const l=ri(0,0,s,n,t.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const c=wt(0,0);c.name("clip-covers-group"),o.add(c),Ie.renderClipCovers(c,e.thumbnails??[],s,n,e.videoSrc,e.deferCoverRender);const h=s>=120?Hi+ua:0,d=Ni(`${e.clipName} ${H.formatDuration(e.duration)}`,de,e.height-r,_r,"Arial",t.label,"left","middle");d.ellipsis(!0),d.width(Math.max(0,s-h)),d.height(r),d.name("clip-label"),a.add(d),h>0&&fa(a,e.width,e.height,e.hasSeparatedAudio)}function jc(a,e,t){const i=a.findOne(".clip-background"),r=a.findOne(".clip-cover-container"),n=a.findOne(".clip-cover-background"),s=a.findOne(".clip-covers-group"),o=a.findOne(".clip-label");if(!i||!r||!n||!s||!o||(i.width(e.width),i.height(e.height),i.fill(t.background),i.stroke(t.border),i.strokeWidth(t.borderWidth),i.cornerRadius(4),!Yc(a,e.width,e.height)))return!1;const l=15,c=e.height-l-4,h=e.width-de*2;r.x(de),r.y(2),r.clip({x:0,y:0,width:h,height:c}),n.width(h),n.height(c),n.fill(t.coverBackground),n.cornerRadius(2),Ie.renderClipCovers(s,e.thumbnails??[],h,c,e.videoSrc,e.deferCoverRender);const d=h>=120?Hi+ua:0;o.text(`${e.clipName} ${H.formatDuration(e.duration)}`),o.x(de),o.y(e.height-l),o.fill(t.label),o.width(Math.max(0,h-d)),o.height(l),o.ellipsis(!0);const u=a.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&fa(a,e.width,e.height,e.hasSeparatedAudio),!0}function Kc(a,e){e.complete&&e.naturalWidth>0||e.addEventListener("load",()=>{var t,i;(i=(t=a.getLayer)==null?void 0:t.call(a))==null||i.batchDraw()},{once:!0})}function ga(a,e,t,i,r){a.name()||a.name(r);const n=zc(e);if(!n)return 0;const s=new q.Image({x:0,y:0,width:t,height:i,image:n,listening:!1});return s.name(`${r}-image`),a.add(s),Kc(a,n),t}function fa(a,e,t,i){const r=wt(Math.max(de,e-de-Hi-2),Math.max(0,t-15));r.name("video-audio-status");const n=wt(Math.max(0,Hi-Ir),0),s=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";n.name(s),ga(n,o,Ir,Ar,`${s}-icon`),r.add(n),a.add(r)}function Zc(a,e,t){const i=ri(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(6),i.name("clip-background"),a.add(i),qi(a,e.width,e.height,!1);const r=de+Mn,n=Math.max(0,e.width-de*2-Mn*2),s=Vc,o=wt(r,s),l=ga(o,"clip-audio",Ir,Ar,"audio-clip-icon");a.add(o);const c=r+l+On,h=Math.max(0,n-l-On);if(e.audioBadgeText&&h>0){const u=Ni(e.audioBadgeText,c,s,_r,"Arial",t.label,"left","middle");u.ellipsis(!0),u.width(h),u.height(Ar),u.name("audio-clip-badge"),a.add(u)}const d=Ni(e.clipName,r,e.height-Uc-Bn,_r,"Arial",t.label,"left","middle");d.ellipsis(!0),d.width(n),d.height(Bn),d.name("clip-label"),a.add(d)}function Jc(a,e,t){const i=ri(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),a.add(i),qi(a,e.width,e.height,!1);const r=Ni(e.clipName,Gn,0,Wc,"Arial",t.label,"left","middle");r.width(Math.max(0,e.width-Gn*2)),r.height(e.height),r.lineHeight(1),r.ellipsis(!0),r.wrap("none"),r.name("clip-label"),a.add(r)}function ma(a,e){const t=e.width<=ei,i=pa(e.theme,e.isSelected,e.clipType);if(a.destroyChildren(),t){Xc(a,e.width,e.height,i);return}if(e.clipType==="audio"){Zc(a,e,i);return}if(e.clipType==="text"){Jc(a,e,i);return}qc(a,e,i)}function Qc(a,e){if(e.width<=ei||e.clipType!=="video")return!1;const i=pa(e.theme,e.isSelected,e.clipType);return jc(a,e,i)}function eh(a,e,t,i,r,n,s,o=!1,l,c,h="video",d=!1,u=!1,g){const f=wt(a,e);return f.clip({x:0,y:0,width:t,height:i}),ma(f,{width:t,height:i,clipName:r,audioBadgeText:g,duration:n,theme:s,isSelected:o,thumbnails:l,videoSrc:c,clipType:h,hasSeparatedAudio:d,deferCoverRender:u}),f}function th(a,e,t,i,r,n,s=!1,o,l,c="video",h=!1,d=!1,u){a.clip({x:0,y:0,width:e,height:t});const g={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:n??Bi,isSelected:s,thumbnails:o,videoSrc:l,clipType:c,hasSeparatedAudio:h,deferCoverRender:d};Qc(a,g)||ma(a,g)}function ih(a,e,t,i){return new q.Rect({x:a,y:e,width:t,height:i,stroke:E.clipSelectedBorder,strokeWidth:da,fillEnabled:!1})}function Er(a,e=yt.stroke,t=1){return new q.Line({points:a,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function rh(a,e,t,i=12,r="Arial",n=yt.text,s="left",o="top"){return new q.Text({text:a,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:s,verticalAlign:o})}function nh(a=0,e=0){return new q.Group({x:a,y:e})}function sh(a,e,t,i,r,n,s,o){const l=o||i,c=s==="major"?l*.6:l*.3,h=Er([e,t,e,t+c],n.timeTick,s==="major"?1:.5);if(h.name("time-tick-line"),a.add(h),s==="major"){const d=t+c+5,u=rh(H.formatTime(r),e,d,10,"Arial",n.timeText,"center");u.name("time-tick-text"),a.add(u)}}function ah(a,e,t,i,r,n){const s=nh(e,t);for(let o=0;o<=i;o+=n)s.add(Er([o,0,o,r],Zr.line,.5));for(let o=0;o<=r;o+=n)s.add(Er([0,o,i,o],Zr.line,.5));a.add(s)}class se{static createStage(e,t,i){return new q.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new q.Layer;return t.name(e),t}static createRect(e,t,i,r,n=yt.fill,s=yt.stroke,o=1){return new q.Rect({x:e,y:t,width:i,height:r,fill:n,stroke:s,strokeWidth:o})}static createText(e,t,i,r=12,n="Arial",s=yt.text,o="left",l="top"){return new q.Text({text:e,x:t,y:i,fontSize:r,fontFamily:n,fill:s,align:o,verticalAlign:l})}static createLine(e,t=yt.stroke,i=1){return new q.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new q.Group({x:e,y:t})}static createPlayhead(e,t,i){const r=new q.Group({x:e,y:t}),n=this.createLine([0,0,0,i],Oi.marker,2),s=new q.RegularPolygon({x:0,y:-10,sides:3,radius:5,fill:Oi.marker,rotation:180});return r.add(n),r.add(s),r}static drawTimeTick(e,t,i,r,n,s,o,l){sh(e,t,i,r,n,s,o,l)}static drawGrid(e,t,i,r,n,s){ah(e,t,i,r,n,s)}static clearImageCache(){Ie.clearImageCache()}static createClipGroup(e,t,i,r,n,s,o,l=!1,c,h,d="video",u=!1,g=!1,f){return eh(e,t,i,r,n,s,o,l,c,h,d,u,g,f)}static updateClipGroup(e,t,i,r,n,s,o=!1,l,c,h="video",d=!1,u=!1,g){th(e,t,i,r,n,s,o,l,c,h,d,u,g)}static createSelectionEffect(e,t,i,r){return ih(e,t,i,r)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}p(se,"RESIZE_AREA_WIDTH",3);function ci(a){let e=!1;return typeof window<"u"&&(window.addEventListener("mousemove",a.onPointerMove),window.addEventListener("mouseup",a.onPointerEnd),window.addEventListener("blur",a.onWindowBlur||a.onPointerEnd),e=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",a.onVisibilityChange),e=!0),e}function hi(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 oh{constructor(e,t,i,r,n,s){p(this,"stage");p(this,"gridLayer");p(this,"config");p(this,"theme");p(this,"isDragging",!1);p(this,"startDragX",0);p(this,"scrollLeft",0);p(this,"timeScaleHeight",40);p(this,"onTimeChange");p(this,"onZoomChange");p(this,"onScrollChange");p(this,"animationFrameId",null);p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"isScrollbarDragging",!1);p(this,"scrollbarDragStartX",0);p(this,"scrollbarDragStartScrollLeft",0);p(this,"isPointerInsideTimeline",!1);p(this,"lastPointerXInTimeline",null);p(this,"scrollbarHeight",12);p(this,"scrollbarMargin",4);p(this,"handleGlobalPointerMove",e=>{this.isPointerSessionActive()&&this.handlePointerMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.finalizePointerInteraction()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finalizePointerInteraction()});p(this,"leftPadding",ue);this.stage=e,this.gridLayer=t,this.onTimeChange=r,this.onZoomChange=n,this.onScrollChange=s,this.config={duration:i.duration||36e5,zoom:i.zoom||ye.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Qt(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,i.timeScaleHeight&&(this.timeScaleHeight=i.timeScaleHeight),this.initEventListeners(),this.render()}initEventListeners(){this.stage.on("wheel",e=>{e.evt.preventDefault(),this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0;const{deltaX:t,deltaY:i,shiftKey:r}=e.evt,n=Math.abs(t)>0;if(r||n){const l=(n?t:i)*1.5,c=this.stage.width(),h=H.timeToPixels(this.config.duration,this.config.zoom),d=Math.max(0,h-c),u=Math.max(0,Math.min(d,this.scrollLeft+l));u!==this.scrollLeft&&this.animateHorizontalScroll(u)}else Math.abs(i)>0&&this.handleZoom(e)}),this.stage.on("click",e=>{let t=e.target.getLayer();const i=e.target.name()==="scrollbar-background"||e.target.name()==="scrollbar-thumb";t===this.gridLayer&&!i&&this.handleClick(e.evt.offsetX)}),this.stage.on("mousedown",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0;let t=e.target.getLayer(),i=e.target.name()==="scrollbar-background"||e.target.name()==="scrollbar-thumb";t===this.gridLayer&&e.target.name()==="scrollbar-thumb"?(this.isScrollbarDragging=!0,this.scrollbarDragStartX=e.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):t===this.gridLayer&&e.target.name()==="scrollbar-background"?(this.jumpScrollbarToPointer(e.evt.offsetX),this.isScrollbarDragging=!0,this.scrollbarDragStartX=e.evt.clientX,this.scrollbarDragStartScrollLeft=this.scrollLeft,this.bindGlobalPointerListenersForDrag()):t===this.gridLayer&&!i&&(this.isDragging=!0,this.startDragX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isPointerSessionActive()&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.finalizePointerInteraction()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=ci({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(hi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}isPointerSessionActive(){return this.isDragging||this.isScrollbarDragging}finalizePointerInteraction(){this.isDragging=!1,this.isScrollbarDragging=!1,this.unbindGlobalPointerListenersForDrag()}handlePointerMove(e){if(this.isScrollbarDragging){const t=this.stage.width(),i=this.getTotalDurationPixels(),r=Math.max(0,i-t);if(r<=0)return;const n=this.getScrollbarThumbWidth(),s=Math.max(1,t-n),o=e.clientX-this.scrollbarDragStartX,l=this.scrollLeft,c=this.scrollbarDragStartScrollLeft+o/s*r;this.scrollLeft=Math.max(0,Math.min(r,c)),this.render(),this.scrollLeft!==l&&this.onScrollChange(this.scrollLeft)}else if(this.isDragging){const t=e.clientX-this.startDragX,i=this.scrollLeft;this.scrollLeft-=t;const r=this.stage.width(),n=H.timeToPixels(this.config.duration,this.config.zoom);this.scrollLeft=Math.max(0,Math.min(n-r,this.scrollLeft)),this.startDragX=e.clientX,this.render(),this.scrollLeft!==i&&this.onScrollChange(this.scrollLeft)}}handleZoom(e){const t=e.evt.deltaY;if(t===0)return;const i=t>0?.5:1.5,r=Math.max(ye.MIN,Math.min(ye.MAX,this.config.zoom*i));if(r!==this.config.zoom){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const n=e.evt.offsetX;this.animateZoom(r,n)}}animateZoom(e,t){const i=this.config.zoom,r=Cs.DURATION,n=Date.now(),s=this.pixelToTime(t),o=()=>{const l=Date.now()-n,c=Math.min(l/r,1),h=this.easeOutCubic(c),d=i+(e-i)*h,u=H.timeToPixels(s,d),g=Math.max(0,u-(t-this.leftPadding));if(this.scrollLeft=g,this.config.zoom=d,this.onZoomChange(d),this.onScrollChange(g),this.render(),c<1)this.animationFrameId=requestAnimationFrame(o);else{const f=H.timeToPixels(s,e),y=Math.max(0,f-(t-this.leftPadding));this.config.zoom=e,this.scrollLeft=y,this.onZoomChange(e),this.onScrollChange(y),this.render()}};this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),o()}animateHorizontalScroll(e){const t=this.scrollLeft,i=300,r=Date.now(),n=this.stage.width(),s=H.timeToPixels(this.config.duration,this.config.zoom);this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null);const o=()=>{const l=Date.now()-r,c=Math.min(l/i,1),h=this.easeOutCubic(c),d=t+(e-t)*h;this.scrollLeft=Math.max(0,Math.min(s-n,d)),this.onScrollChange(this.scrollLeft),this.render(),c<1?this.animationFrameId=requestAnimationFrame(o):(this.scrollLeft=Math.max(0,Math.min(s-n,e)),this.onScrollChange(this.scrollLeft),this.render())};o()}easeOutCubic(e){return 1-Math.pow(1-e,3)}handleClick(e){const t=this.pixelToTime(e);this.setCurrentTime(t)}pixelToTime(e){return H.pixelsToTime(e-this.leftPadding+this.scrollLeft,this.config.zoom)}timeToPixel(e){return H.timeToPixels(e,this.config.zoom)-this.scrollLeft+this.leftPadding}setCurrentTime(e){this.config.currentTime=Math.max(0,e),this.onTimeChange(this.config.currentTime)}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setPlayState(e){this.config.playState=e,this.render()}update(){this.render()}render(){const e=this.stage.width(),t=this.stage.height(),i=this.gridLayer.findOne(".timeline-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const r=se.createRect(0,0,e,t,this.theme.background,this.theme.border,1);r.name("timeline-background"),this.gridLayer.add(r)}this.gridLayer.find(".grid-line").forEach(r=>r.remove()),this.gridLayer.find(".time-tick-line").forEach(r=>r.remove()),this.gridLayer.find(".time-tick-text").forEach(r=>r.remove()),this.renderTimeTicks(),this.renderScrollbar(),this.gridLayer.batchDraw()}renderScrollbar(){const e=this.stage.width(),t=this.stage.height(),i=Math.max(this.timeScaleHeight,t-this.scrollbarHeight-this.scrollbarMargin),r=this.getScrollbarThumbWidth(),n=this.getScrollbarThumbX(r),s=this.gridLayer.findOne(".scrollbar-background");if(s)s.x(0),s.y(i),s.width(e),s.height(this.scrollbarHeight),s.fill(this.theme.scrollbarBackground||fe.background),s.stroke(this.theme.scrollbarBorder||fe.border),s.visible(!0);else{const l=se.createRect(0,i,e,this.scrollbarHeight,this.theme.scrollbarBackground||fe.background,this.theme.scrollbarBorder||fe.border,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(r),o.height(this.scrollbarHeight),o.fill(this.theme.scrollbarThumb||fe.thumb),o.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border),o.visible(r<e);else{const l=se.createRect(n,i,r,this.scrollbarHeight,this.theme.scrollbarThumb||fe.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border,1);l.name("scrollbar-thumb"),l.visible(r<e),this.gridLayer.add(l)}}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,r=H.pixelsToTime(t,this.config.zoom),n=H.pixelsToTime(i,this.config.zoom),s=H.msToSeconds(r),o=H.msToSeconds(n),l=10,c=s-l,h=o+l,{majorStep:d,minorStep:u}=H.getTickConfig(this.config.zoom),g=H.generateVisibleTicks(c,h,d,u);let f=0;const y=20;for(const S of g){const C=this.timeToPixel(S.time);C>=-y&&C<=e+y&&(se.drawTimeTick(this.gridLayer,C,0,this.timeScaleHeight,S.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},S.type,this.timeScaleHeight),f++)}G.debugLazy("Timeline",()=>`Timeline - scrollLeft: ${this.scrollLeft}px, zoom: ${this.config.zoom}px/s, visible time: ${Math.round(s)}s to ${Math.round(o)}s, ticks: ${g.length} generated, ${f} drawn`)}getConfig(){return{...this.config}}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){const t=this.stage.width(),i=this.getTotalDurationPixels();this.scrollLeft=Math.max(0,Math.min(i-t,e)),this.render()}getTotalDurationPixels(){return H.timeToPixels(this.config.duration,this.config.zoom)}getScrollbarThumbWidth(){const e=this.stage.width(),t=this.getTotalDurationPixels();return t<=0||t<=e?e:Math.max(40,e/t*e)}getScrollbarThumbX(e){const t=this.stage.width(),i=this.getTotalDurationPixels(),r=Math.max(0,i-t);if(r<=0||e>=t)return 0;const n=t-e;return this.scrollLeft/r*n}jumpScrollbarToPointer(e){const t=this.stage.width(),i=this.getTotalDurationPixels(),r=Math.max(0,i-t);if(r<=0)return;const n=this.getScrollbarThumbWidth(),s=Math.max(1,t-n),l=Math.max(n/2,Math.min(t-n/2,e))-n/2,c=this.scrollLeft;this.scrollLeft=l/s*r,this.render(),this.scrollLeft!==c&&this.onScrollChange(this.scrollLeft)}scrollToTime(e){const t=H.timeToPixels(e,this.config.zoom),i=this.stage.width(),r=Math.max(0,t-i/2);this.setScrollLeft(r),this.onScrollChange(r)}scrollToClip(e){const t=H.timeToPixels(e.startTime,this.config.zoom),r=H.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,n=this.stage.width();let s;r<=n?s=Math.max(0,t-(n-r)/2):s=Math.max(0,t),this.setScrollLeft(s),this.onScrollChange(s)}getStage(){return this.stage}getGridLayer(){return this.gridLayer}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}resize(e,t){this.render()}}const zt=8;function me(a,e,t){return se.timeToPixels(a,e)-t+ue}function Ae(a,e){const t=se.timeToPixels(a,e);return a<=1e3||t<=ei?ei:t}function lh(a,e){const t=me(a.startTime,a.zoom,a.scrollLeft),i=Ae(a.duration,a.zoom);return t+i>0&&t<e}function ch(a){for(const e of a.clips){const t=me(e.startTime,a.zoom,a.scrollLeft),i=Ae(e.duration,a.zoom),r=a.y>=a.trackY&&a.y<=a.trackY+a.trackHeight;if(a.x>=t&&a.x<=t+zt&&r||a.x>=t+i-zt&&a.x<=t+i&&r)return"ew-resize";if(a.x>t+zt&&a.x<t+i-zt&&r)return"pointer"}return"default"}class Li{constructor(e,t,i){p(this,"clip");p(this,"onUpdate");p(this,"onSplit");this.clip=Hr({...e,endTime:H.calculateEndTime(e.startTime,e.duration)},{isDragging:e.isDragging,isResizingLeft:e.isResizingLeft,isResizingRight:e.isResizingRight,isSelected:e.isSelected,isResizing:e.isResizing,zIndex:e.zIndex,opacity:e.opacity}),this.onUpdate=t,this.onSplit=i}getClip(){return{...this.clip}}applyPreviewState(e){this.clip={...this.clip,...e,endTime:H.calculateEndTime(e.startTime,e.duration)}}setSelected(e){this.clip={...this.clip,isSelected:e},this.onUpdate(this.clip)}isPointInResizeHandle(e,t,i,r,n,s){const o=me(this.clip.startTime,i,s),l=Ae(this.clip.duration,i),c=zt;return t<r||t>r+n?(this.setResizeHandleState(!1,!1),!1):e>=o&&e<=o+c?(this.setResizeHandleState(!0,!1),!0):e>=o+l-c&&e<=o+l?(this.setResizeHandleState(!1,!0),!0):(this.setResizeHandleState(!1,!1),!1)}startDrag(e){this.clip={...this.clip,isDragging:!0,isResizing:!1,isResizingLeft:!1,isResizingRight:!1},this.onUpdate(this.clip)}startResize(e){this.clip={...this.clip,isDragging:!0,isResizing:!0},this.onUpdate(this.clip)}endDrag(){this.clip={...this.clip,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1}}split(e){e>this.clip.startTime+1&&e<this.clip.endTime-1&&this.onSplit(this.clip,e)}setResizeHandleState(e,t){this.clip={...this.clip,isResizingLeft:e,isResizingRight:t}}}function $i(){return{kind:"idle"}}function sr(a){return!!a&&a.kind!=="idle"}function qt(a){return(a==null?void 0:a.kind)==="draggingMove"||(a==null?void 0:a.kind)==="draggingResizeLeft"||(a==null?void 0:a.kind)==="draggingResizeRight"}function Qe(a){return!a||a.kind==="idle"||a.kind==="boxSelecting"?null:a.context}function jt(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 hh(a){const e=jt(a);return e?e==="move"?"grabbing":"ew-resize":null}function xi(a,e){if(e.type==="POINTER_DOWN")return{state:{kind:"pressed",operation:e.operation,context:{clipId:e.clipId,originalClipsState:e.originalClipsState,nonDraggedClips:e.nonDraggedClips,snapCandidateClips:e.snapCandidateClips,pointerStartClientX:e.clientX,pointerStartClientY:e.clientY,pointerStartX:e.localX,pointerStartY:e.localY,dragStartScrollLeft:e.scrollLeft,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:e.localY,crossTrackDragOffsetY:0}},effects:{bindGlobalListeners:!0}};if(e.type==="BOX_SELECT_START")return{state:{kind:"boxSelecting",context:{startClientX:e.clientX,startClientY:e.clientY,startLocalX:e.localX,startLocalY:e.localY,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY,additive:e.additive}},effects:{bindGlobalListeners:!0}};if(a.kind==="idle")return{state:a,effects:{}};if(a.kind==="boxSelecting")return e.type==="BOX_SELECT_MOVE"?{state:{kind:"boxSelecting",context:{...a.context,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY}},effects:{updatePreview:!0}}:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP"||e.type==="CANCEL"||e.type==="VISIBILITY_HIDDEN"||e.type==="WINDOW_BLUR"?{state:$i(),effects:{unbindGlobalListeners:!0,commit:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP",cleanup:!0}}:{state:a,effects:{}};if(e.type==="POINTER_MOVE"){const i=uh(a.context,e,jt(a)||"move");return a.kind==="pressed"?ph(a.context,e.activationThreshold,e.clientX,e.clientY)?{state:dh(a.operation,i),effects:{updatePreview:!0}}:{state:{...a,context:i},effects:{}}:{state:{...a,context:i},effects:{updatePreview:!0}}}if(e.type==="SCROLL_LEFT_CHANGED")return{state:a,effects:{updatePreview:qt(a)}};const t=e.type==="POINTER_UP"&&qt(a);return{state:$i(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function dh(a,e){return a==="resize-left"?{kind:"draggingResizeLeft",context:e}:a==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function uh(a,e,t){const i=t==="move";return{...a,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:i?e.localY:a.pointerStartY,crossTrackDragOffsetY:i?e.localY-a.pointerStartY:0}}function ph(a,e,t,i){const r=t-a.pointerStartClientX,n=i-a.pointerStartClientY;return Math.hypot(r,n)>=Math.max(0,e)}const _e=class _e{constructor(e,t,i,r,n,s,o,l,c,h,d,u,g,f,y,S,C,T,v,w,x,P,M,I,A,k=_e.DEFAULT_DRAG_ACTIVATION_THRESHOLD,$=!1,B=_e.DEFAULT_CLIP_SNAP_THRESHOLD){p(this,"layer");p(this,"trackGroup");p(this,"dragOverlayLayer",null);p(this,"dropPreviewGroup",null);p(this,"dropPreviewClips",[]);p(this,"config");p(this,"theme");p(this,"trackType");p(this,"clips",[]);p(this,"clipGroups",new Map);p(this,"zoom",100);p(this,"scrollLeft",0);p(this,"trackY",0);p(this,"trackHeight",64);p(this,"selectedClip",null);p(this,"hasSelectedClip",!1);p(this,"selectedClipIds",new Set);p(this,"multiDragOriginalPositions",new Map);p(this,"promotedClipParents",new Map);p(this,"interactionState",$i());p(this,"legacyInteractionSnapshot");p(this,"isVisualUpdate",!1);p(this,"onClipUpdate");p(this,"onClipAdd");p(this,"onClipRemove");p(this,"onClipSplit");p(this,"onClipSelect");p(this,"onTimeJump");p(this,"onClipOverlap");p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"hasLockedGlobalCursor",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"onHorizontalDragAutoScroll");p(this,"onClipCrossTrackPreview");p(this,"onClipCrossTrack");p(this,"onClearDropPreview");p(this,"onClearSelection");p(this,"onSnapGuideChange");p(this,"onClipToggleSelection");p(this,"onSetSingleSelection");p(this,"getMultiDragClipIds");p(this,"onMultiDragMove");p(this,"onMultiDragInteractionEnd");p(this,"resolveSnapTargetClips");p(this,"dragActivationThreshold");p(this,"enableClipSnap");p(this,"clipSnapThreshold");p(this,"handleGlobalPointerMove",e=>{sr(this.interactionState)&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});p(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});p(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const e=this.resolveInteractionState();if(!qt(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=Qe(e);if(!i||!r){this.stopEdgeAutoScroll();return}const n=i.getBoundingClientRect(),s=r.lastPointerClientX-n.left,o=this.calculateHorizontalAutoScrollVelocity(s,n.width);if(o===0){this.stopEdgeAutoScroll();return}const l=this.scrollLeft,c=this.onHorizontalDragAutoScroll(this.scrollLeft+o),h=typeof c=="number"?c:this.scrollLeft;if(Math.abs(h-l)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.layer=e,this.config=t,this.theme=o,this.trackType=i,this.zoom=r,this.trackY=n,this.trackHeight=s,this.onClipUpdate=l,this.onClipAdd=c,this.onClipRemove=h,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=g,this.onHorizontalDragAutoScroll=f,this.onClipOverlap=y,this.onClipCrossTrackPreview=S,this.onClipCrossTrack=C,this.onClearDropPreview=T,this.onClearSelection=v,this.onSnapGuideChange=w,this.onClipToggleSelection=x,this.onSetSingleSelection=P,this.getMultiDragClipIds=M,this.onMultiDragMove=I,this.onMultiDragInteractionEnd=A,this.dragActivationThreshold=Math.max(0,k),this.enableClipSnap=$,this.clipSnapThreshold=Math.max(0,B),this.trackGroup=se.createGroup(0,n),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}get hasDragMoved(){return this.getLegacyInteractionSnapshot().hasDragMoved}set hasDragMoved(e){this.getLegacyInteractionSnapshot().hasDragMoved=e}get activePointerOperation(){return this.getLegacyInteractionSnapshot().activePointerOperation}set activePointerOperation(e){this.getLegacyInteractionSnapshot().activePointerOperation=e}get originalClipsState(){return this.getLegacyInteractionSnapshot().originalClipsState}set originalClipsState(e){this.getLegacyInteractionSnapshot().originalClipsState=Array.isArray(e)?e:[]}get nonDraggedClips(){return this.getLegacyInteractionSnapshot().nonDraggedClips}set nonDraggedClips(e){this.getLegacyInteractionSnapshot().nonDraggedClips=Array.isArray(e)?e:[]}get snapCandidateClips(){return this.getLegacyInteractionSnapshot().snapCandidateClips}set snapCandidateClips(e){this.getLegacyInteractionSnapshot().snapCandidateClips=Array.isArray(e)?e:[]}get dragStartY(){return this.getLegacyInteractionSnapshot().dragStartY}set dragStartY(e){this.getLegacyInteractionSnapshot().dragStartY=typeof e=="number"?e:0}get dragTargetTrackY(){return this.getLegacyInteractionSnapshot().dragTargetTrackY}set dragTargetTrackY(e){this.getLegacyInteractionSnapshot().dragTargetTrackY=typeof e=="number"?e:0}get crossTrackDragOffsetY(){return this.getLegacyInteractionSnapshot().crossTrackDragOffsetY}set crossTrackDragOffsetY(e){this.getLegacyInteractionSnapshot().crossTrackDragOffsetY=typeof e=="number"?e:0}get crossTrackDragStartX(){return this.getLegacyInteractionSnapshot().crossTrackDragStartX}set crossTrackDragStartX(e){this.getLegacyInteractionSnapshot().crossTrackDragStartX=typeof e=="number"?e:0}get dragStartScrollLeft(){return this.getLegacyInteractionSnapshot().dragStartScrollLeft}set dragStartScrollLeft(e){this.getLegacyInteractionSnapshot().dragStartScrollLeft=typeof e=="number"?e:0}get dragGestureStartClientX(){return this.getLegacyInteractionSnapshot().dragGestureStartClientX}set dragGestureStartClientX(e){this.getLegacyInteractionSnapshot().dragGestureStartClientX=typeof e=="number"?e:null}get dragGestureStartClientY(){return this.getLegacyInteractionSnapshot().dragGestureStartClientY}set dragGestureStartClientY(e){this.getLegacyInteractionSnapshot().dragGestureStartClientY=typeof e=="number"?e:null}get lastDragClientX(){return this.getLegacyInteractionSnapshot().lastDragClientX}set lastDragClientX(e){this.getLegacyInteractionSnapshot().lastDragClientX=typeof e=="number"?e:null}get lastDragClientY(){return this.getLegacyInteractionSnapshot().lastDragClientY}set lastDragClientY(e){this.getLegacyInteractionSnapshot().lastDragClientY=typeof e=="number"?e:null}initClips(){this.clips=this.config.clips.map(e=>{const t=new Li(e,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));return this.createClipGroup(e),t})}getLegacyInteractionSnapshot(){return this.legacyInteractionSnapshot||(this.legacyInteractionSnapshot={hasDragMoved:!1,activePointerOperation:null,originalClipsState:[],nonDraggedClips:[],snapCandidateClips:[],dragStartY:0,dragTargetTrackY:0,crossTrackDragOffsetY:0,crossTrackDragStartX:0,dragStartScrollLeft:0,dragGestureStartClientX:null,dragGestureStartClientY:null,lastDragClientX:null,lastDragClientY:null}),this.legacyInteractionSnapshot}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const e=se.createGroup(0,0);return e.name("clip-drop-preview"),e.visible(!1),e.listening(!1),this.trackGroup.add(e),this.dropPreviewGroup=e,e}createDropPreviewRect(e){const t=this.trackType==="text"?"rgba(96, 76, 51, 0.28)":this.trackType==="video"?pi.videoFill:pi.audioFill,i=this.trackType==="text"?"#C9CBD4":this.trackType==="video"?pi.videoStroke:pi.audioStroke,r=me(e.startTime,this.zoom,this.scrollLeft),n=Ae(e.duration,this.zoom),s=se.createRect(r,2,Math.max(n,1),Math.max(this.trackHeight-4,1),t,i,1);return s.dash([6,4]),s.cornerRadius(4),s.listening(!1),s.visible(r+n>0&&r<this.layer.width()),s}showDropPreview(e){const t=this.ensureDropPreviewGroup(),i=Array.isArray(e)?e:[e];this.dropPreviewClips=i.map(n=>({...n})),t.destroyChildren();let r=!1;for(const n of this.dropPreviewClips){const s=this.createDropPreviewRect(n);r=r||s.visible(),t.add(s)}t.x(0),t.y(0),t.visible(r),t.moveToTop()}hideDropPreview(){var e;this.dropPreviewClips=[],(e=this.dropPreviewGroup)==null||e.visible(!1)}initEventListeners(){const e=this.layer.getStage();e&&e.on("mouseup",()=>{this.handleClipMouseUp()})}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=ci({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(hi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}),this.hasBoundGlobalPointerListenersForDrag=!1)}handleTrackBackgroundClick(e){const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=Math.max(0,H.pixelsToTime(n-ue+this.scrollLeft,this.zoom));this.onTimeJump(s),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(e){}getClipDisplayLabel(e){return(e.type==="text"||e.type==="audio"&&e.ttsSourceTextClipId)&&e.textContent||e.name}getClipAudioBadgeText(e){if(!(e.type!=="audio"||!e.ttsSourceTextClipId))return e.name}isSourceBoundClip(e){return e.type!=="text"}updateClipSelection(e,t){const i=this.clips.find(r=>r.getClip().id===e);i&&(this.isVisualUpdate=!0,i.setSelected(t),this.isVisualUpdate=!1,t?this.selectedClipIds.add(e):this.selectedClipIds.delete(e),this.syncSelectionState(e),this.updateClipGroup(i.getClip()),this.render(!1),this.layer.batchDraw())}createClipGroup(e){const t=me(e.startTime,this.zoom,this.scrollLeft),i=Ae(e.duration,this.zoom),r=2,n=this.trackHeight-4,s=se.createClipGroup(t,r,i,n,this.getClipDisplayLabel(e),e.duration,this.theme,!1,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,!1,this.getClipAudioBadgeText(e));s.name(`clip-${e.id}`),s.on("click",o=>{this.handleClipClick(e.id,o.evt)}),s.on("mousedown",o=>{this.handleClipMouseDown(e.id,o.evt)}),s.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),s.on("mouseleave",()=>{this.handleClipMouseLeave()}),s.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(s),this.clipGroups.set(e.id,s)}handleClipClick(e,t){if(t.button!==0)return;this.clips.find(r=>r.getClip().id===e)&&this.render()}handleClipMouseDown(e,t){var h;if(t.button!==0)return;if(t.ctrlKey||t.metaKey){this.onClipToggleSelection&&this.onClipToggleSelection(e);return}const i=(h=this.getMultiDragClipIds)==null?void 0:h.call(this,e),r=i!=null&&i.length>1;if(!r)this.selectedClipIds.clear(),this.selectedClipIds.add(e),this.onSetSingleSelection&&this.onSetSingleSelection(e);else{this.selectedClipIds.clear();for(const d of i)this.selectedClipIds.add(d)}this.clips.sort((d,u)=>d.getClip().startTime-u.getClip().startTime);const n=this.clips.map(d=>({...d.getClip()})),s=this.clips.filter(d=>d.getClip().id!==e).map(d=>({...d.getClip()})),l=(this.resolveSnapTargetClips?this.resolveSnapTargetClips():this.clips.map(d=>d.getClip())).filter(d=>d.id!==e).map(d=>({...d})),c=this.clips.find(d=>d.getClip().id===e);if(c){r||(this.applySelectionVisual(new Set([e])),this.onClipSelect(c.getClip())),this.selectedClip=c;const d=this.layer.getStage();if(!d)return;const u=d.container();if(!u)return;const g=u.getBoundingClientRect(),f=t.clientX-g.left,y=t.clientY-g.top;if(r){this.multiDragOriginalPositions.clear();for(const C of this.selectedClipIds){const T=this.clips.find(v=>v.getClip().id===C);if(T){const v=T.getClip();this.multiDragOriginalPositions.set(C,{startTime:v.startTime,duration:v.duration})}}}let S;c.isPointInResizeHandle(f,y,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(S=c.getClip().isResizingLeft?"resize-left":"resize-right",c.startResize({x:f,y})):(S="move",c.startDrag({x:f,y}),this.trackGroup.moveToTop()),this.applyInteractionTransition(xi(this.interactionState,{type:"POINTER_DOWN",operation:S,clipId:e,originalClipsState:n,nonDraggedClips:s,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:f,localY:y,scrollLeft:this.scrollLeft})),this.render()}}handleClipMouseMove(e){this.updateHoverCursor(e.clientX,e.clientY)}handleTrackBackgroundMouseMove(){if(this.isDragSessionActive())return;const e=this.layer.getStage(),t=e==null?void 0:e.container();t&&(t.style.cursor="default")}handleClipMouseUp(){this.finishPointerInteraction("POINTER_UP")}finishPointerInteraction(e){const t=this.interactionState,i=this.resolveDraggedClipForInteraction(t);try{if(!i)return;const r=i.getClip();if(!r.isDragging)return;i.endDrag();const n=xi(t,{type:e});this.interactionState=n.state,n.effects.commit&&this.handleClipMoveEnd(r,t),this.layer.batchDraw()}finally{this.interactionState=$i(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}resolveDraggedClipForInteraction(e=this.interactionState){const t=Qe(e);if(t!=null&&t.clipId){const r=this.clips.find(n=>n.getClip().id===t.clipId)??null;if(r)return r}const i=this.clips.find(r=>r.getClip().isDragging)??null;return i||this.selectedClip}applyInteractionTransition(e){var i,r;this.interactionState=e.state,this.syncLegacyInteractionMirror(e.state),e.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const t=hh(e.state);t&&this.lockPointerCursor(t),e.effects.cleanup&&(this.releasePointerCursor(),this.hideDropPreview(),(i=this.onClearDropPreview)==null||i.call(this),this.updateSnapGuideLine(null),this.stopEdgeAutoScroll(),this.clearClipDragOverlay(),this.multiDragOriginalPositions.size>0&&((r=this.onMultiDragInteractionEnd)==null||r.call(this),this.multiDragOriginalPositions.clear())),e.effects.unbindGlobalListeners&&this.unbindGlobalPointerListenersForDrag()}resolveInteractionState(e=this.interactionState){var s;if(sr(e))return e;const t=this.getLegacyInteractionSnapshot(),i=(s=this.resolveDraggedClipForInteraction(e))==null?void 0:s.getClip();if(!(i!=null&&i.id)||!i.isDragging)return e;const r=t.activePointerOperation||(i.isResizingLeft?"resize-left":i.isResizingRight?"resize-right":"move"),n={clipId:i.id,originalClipsState:t.originalClipsState,nonDraggedClips:t.nonDraggedClips,snapCandidateClips:t.snapCandidateClips,pointerStartClientX:t.dragGestureStartClientX??0,pointerStartClientY:t.dragGestureStartClientY??0,pointerStartX:t.crossTrackDragStartX,pointerStartY:t.dragStartY,dragStartScrollLeft:t.dragStartScrollLeft||this.scrollLeft,lastPointerClientX:t.lastDragClientX??0,lastPointerClientY:t.lastDragClientY??0,dragTargetTrackY:t.dragTargetTrackY,crossTrackDragOffsetY:t.crossTrackDragOffsetY};return t.hasDragMoved?r==="resize-left"?{kind:"draggingResizeLeft",context:n}:r==="resize-right"?{kind:"draggingResizeRight",context:n}:{kind:"draggingMove",context:n}:{kind:"pressed",operation:r,context:n}}syncLegacyInteractionMirror(e=this.interactionState){const t=this.getLegacyInteractionSnapshot(),i=Qe(e);t.hasDragMoved=qt(e),t.activePointerOperation=jt(e),t.originalClipsState=(i==null?void 0:i.originalClipsState)??[],t.nonDraggedClips=(i==null?void 0:i.nonDraggedClips)??[],t.snapCandidateClips=(i==null?void 0:i.snapCandidateClips)??[],t.dragStartY=(i==null?void 0:i.pointerStartY)??0,t.dragTargetTrackY=(i==null?void 0:i.dragTargetTrackY)??0,t.crossTrackDragOffsetY=(i==null?void 0:i.crossTrackDragOffsetY)??0,t.crossTrackDragStartX=(i==null?void 0:i.pointerStartX)??0,t.dragStartScrollLeft=(i==null?void 0:i.dragStartScrollLeft)??0,t.dragGestureStartClientX=(i==null?void 0:i.pointerStartClientX)??null,t.dragGestureStartClientY=(i==null?void 0:i.pointerStartClientY)??null,t.lastDragClientX=(i==null?void 0:i.lastPointerClientX)??null,t.lastDragClientY=(i==null?void 0:i.lastPointerClientY)??null}handleClipMoveEnd(e,t){var S,C,T;const i=this.resolveInteractionState(t),r=this.getLegacyInteractionSnapshot(),n=Qe(i)||{clipId:e.id,originalClipsState:r.originalClipsState.length>0?r.originalClipsState:[e],nonDraggedClips:r.nonDraggedClips,snapCandidateClips:r.snapCandidateClips,dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:r.dragTargetTrackY,crossTrackDragOffsetY:r.crossTrackDragOffsetY},o=(jt(i)||r.activePointerOperation||"move")==="move",l=o&&this.multiDragOriginalPositions.size>0,c=(S=this.clipGroups)==null?void 0:S.get(e.id);if(c&&c.y(2),l){const v=this.multiDragOriginalPositions.get(e.id),w=v?e.startTime-v.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:e.id,deltaTime:w,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!0})){for(const k of this.selectedClipIds){const $=(C=this.clipGroups)==null?void 0:C.get(k);$==null||$.y(2)}this.multiDragOriginalPositions.clear();return}const x=[],P=[];for(const[A,k]of this.multiDragOriginalPositions){const $=this.clips.find(O=>O.getClip().id===A);if(!$)continue;const B=Math.max(0,k.startTime+w),Y={...$.getClip(),startTime:B,endTime:B+k.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(A)};x.push(Y);const V=n.originalClipsState.find(O=>O.id===A);V&&P.push(V);const F=(T=this.clipGroups)==null?void 0:T.get(A);F&&F.y(2)}const M=[];for(const A of this.clips){const k=A.getClip(),$=x.find(B=>B.id===k.id);$?M.push($):M.push({...k,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}M.sort((A,k)=>A.startTime-k.startTime),this.isVisualUpdate=!0;for(const A of M)this.clips.find($=>$.getClip().id===A.id)&&this.handleClipUpdate(A);this.isVisualUpdate=!1;const I=P.map(A=>{const k=x.find($=>$.id===A.id);return k&&(A.startTime!==k.startTime||A.duration!==k.duration)?{clipId:A.id,previousState:A,newState:k}:null}).filter(A=>A!==null);I.length>0&&this.onClipUpdate(e,P.find(A=>A.id===e.id),I),this.multiDragOriginalPositions.clear();return}if(o&&this.onClipCrossTrack&&this.config.id){const v=n.originalClipsState.find(x=>x.id===e.id)??null;if(this.onClipCrossTrack(e,v,n.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}const h=o?[...n.nonDraggedClips]:[];let d=!1;const u=e.startTime+e.duration;for(const v of h){const w=v.startTime+v.duration;if(e.startTime<w&&u>v.startTime){d=!0;break}}if(o&&d&&this.onClipOverlap&&this.config.id){this.onClipOverlap(e,this.config.id);return}const g=[...n.nonDraggedClips];let f=g.findIndex(v=>v.startTime>=e.startTime);f===-1&&(f=g.length),n.nonDraggedClips.forEach(v=>{v.isSelected=!1});const y={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};g.splice(f,0,y),this.updateAllClips(g),this.buildAndSendUpdates(y,g,n.originalClipsState)}updateAllClips(e){const t=this.clips??[];this.isVisualUpdate=!0,e.forEach(i=>{t.find(n=>n.getClip().id===i.id)&&this.handleClipUpdate(i)}),this.isVisualUpdate=!1,t.sort((i,r)=>i.getClip().startTime-r.getClip().startTime),this.clips=t}buildAndSendUpdates(e,t,i){const r=i.map(n=>{const s=t.find(o=>o.id===n.id);return s&&(n.startTime!==s.startTime||n.duration!==s.duration||n.opacity!==s.opacity)?{clipId:n.id,previousState:n,newState:s}:null}).filter(n=>n!==null);r.length>0&&this.onClipUpdate(e,i.find(n=>n.id===e.id),r)}updateHoverCursor(e,t){const i=this.layer.getStage();if(!i)return;const r=i.container();if(!r||this.isDragSessionActive())return;const n=r.getBoundingClientRect(),s=e-n.left,o=t-n.top;r.style.cursor=ch({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:s,y:o})}isDragSessionActive(){return sr(this.resolveInteractionState())}handleDragMove(e){const t=this.resolveInteractionState(),i=this.layer.getStage(),r=i==null?void 0:i.container();if(!r)return;const n=r.getBoundingClientRect(),s=xi(t,{type:"POINTER_MOVE",clientX:e.clientX,clientY:e.clientY,localY:e.clientY-n.top,activationThreshold:this.dragActivationThreshold});this.interactionState=s.state,this.syncLegacyInteractionMirror(s.state),s.effects.updatePreview&&this.updateDraggedClipFromPointer(e.clientX,e.clientY,!0)}handleClipMouseLeave(){if(this.isDragSessionActive())return;const e=this.layer.getStage();e&&e.container()&&(e.container().style.cursor="default")}lockPointerCursor(e){const t=typeof this.layer.getStage=="function"?this.layer.getStage():null,i=t==null?void 0:t.container();i&&(i.style.cursor=e),typeof document<"u"&&document.body&&(document.body.style.cursor=e,this.hasLockedGlobalCursor=!0)}releasePointerCursor(){const e=typeof this.layer.getStage=="function"?this.layer.getStage():null,t=e==null?void 0:e.container();t&&(t.style.cursor="default"),this.hasLockedGlobalCursor&&typeof document<"u"&&document.body&&(document.body.style.cursor="",this.hasLockedGlobalCursor=!1)}updateClipGroup(e,t=!1){const i=this.clipGroups.get(e.id);if(i){const r=Ae(e.duration,this.zoom);this.updateClipViewportState(e);const n=e.isSelected;(e.isDragging||n)&&i.moveToTop(),i.opacity(e.opacity),se.updateClipGroup(i,r,this.trackHeight-4,this.getClipDisplayLabel(e),e.duration,this.theme,n,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,t,this.getClipAudioBadgeText(e))}}handleClipUpdate(e){const t=this.clips.findIndex(i=>i.getClip().id===e.id);if(t!==-1){const i=this.clips[t].getClip(),r={...e,isSelected:this.isVisualUpdate?e.isSelected:this.selectedClipIds.has(e.id)};this.clips[t]=new Li(r,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this)),this.syncSelectionState(e.id),this.updateClipGroup(r);const n=this.clipGroups.get(e.id);n&&n.opacity(r.opacity),this.isVisualUpdate||this.onClipUpdate(r,i),this.layer.batchDraw()}}handleClipSplit(e,t){const i=t-e.startTime,r=e.duration-i,n=e.startTimeAtSource+i,s={...e,duration:i,endTime:t,endTimeAtSource:n},o={...e,id:`${e.id}_split_${Date.now()}`,startTime:t,duration:r,endTime:H.calculateEndTime(t,r),startTimeAtSource:n,endTimeAtSource:e.endTimeAtSource};this.removeClip(e.id),this.addClip(s),this.addClip(o),this.onClipSplit(s,o),this.layer.batchDraw()}addClip(e){if(e.type!==this.trackType){G.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new Li(t,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));this.clips.push(i),this.createClipGroup(t),this.onClipAdd(t),this.layer.batchDraw()}removeClip(e){const t=this.clips.findIndex(i=>i.getClip().id===e);if(t!==-1){this.clips.splice(t,1),this.selectedClipIds.delete(e),this.syncSelectionState();const i=this.clipGroups.get(e);i&&(this.getPromotedClipParents().delete(e),i.remove(),this.clipGroups.delete(e)),this.onClipRemove(e),this.hideDropPreview(),this.render(!1),this.layer.batchDraw()}}updateClip(e,t){const i=this.clips.find(r=>r.getClip().id===e);if(i){const n={...i.getClip(),...t};(t.startTime!==void 0||t.duration!==void 0)&&(n.endTime=n.startTime+n.duration),this.handleClipUpdate(n)}}setZoom(e){this.zoom=e,this.clips.forEach(t=>{this.updateClipGroup(t.getClip())}),this.layer.batchDraw()}setCurrentTime(e){this.layer.batchDraw()}setScrollLeft(e){this.scrollLeft=e,this.clips.forEach(n=>{const s=n.getClip();this.updateClipViewportState(s)});const t=this.resolveInteractionState(),i=Qe(t),r=xi(t,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=r.state,this.syncLegacyInteractionMirror(r.state),r.effects.updatePreview&&i&&this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1),this.layer.batchDraw()}updateClipVisibility(e){const t=this.clipGroups.get(e.id);if(t){const i=lh({startTime:e.startTime,duration:e.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width());t.visible(i)}}updateClipViewportState(e){const t=this.clipGroups.get(e.id);t&&(t.x(me(e.startTime,this.zoom,this.scrollLeft)),this.updateClipVisibility(e))}setTrackY(e){const t=e-this.trackY;this.trackY=e,this.trackGroup.y(e),this.getPromotedClipParents().forEach((i,r)=>{i.baseY=e;const n=this.clipGroups.get(r);n&&n.y(n.y()+t)})}setTrackStackOrder(e){this.trackGroup.zIndex(e)}setDragOverlayLayer(e){this.dragOverlayLayer=e}setClipsDragOverlayActive(e,t){e.forEach(i=>{this.setClipDragOverlayActive(i,t)})}clearClipDragOverlay(){Array.from(this.getPromotedClipParents().keys()).forEach(e=>{this.setClipDragOverlayActive(e,!1)})}getTrackType(){return this.trackType}render(e=!0){const t=this.getTrackBackgroundFill();if(this.trackGroup.children.length===0){const i=se.createRect(0,0,this.layer.width(),this.trackHeight,t,this.theme.trackBorder,1);i.name("track-background"),i.on("click",r=>{this.handleTrackBackgroundClick(r.evt)}),i.on("mousedown",r=>{this.handleTrackBackgroundMouseDown(r.evt)}),i.on("mousemove",()=>{this.handleTrackBackgroundMouseMove()}),i.on("mouseleave",()=>{this.handleClipMouseLeave()}),this.trackGroup.add(i)}else{const i=this.trackGroup.findOne(".track-background");i&&(i.width(this.layer.width()),typeof i.height=="function"&&i.height(this.trackHeight),i.fill(t),i.stroke(this.theme.trackBorder),i.listening()||i.listening(!0))}e&&this.layer.batchDraw()}getTrackBackgroundFill(){return this.hasSelectedClip?this.theme.trackSelectedBackground||Q.trackSelectedBackground:this.theme.trackBackground}getClips(){return this.clips.map(e=>e.getClip())}getPrimarySelectedClip(){return this.selectedClip?this.selectedClip.getClip():null}clearSelection(){this.setSelection([])}setSelection(e,t){const i=new Set(e);this.applySelectionVisual(i),this.selectedClipIds=i,this.syncSelectionState(t??e[0]??void 0),this.render()}applySelectionVisual(e){this.isVisualUpdate=!0;try{this.clips.forEach(t=>{const i=t.getClip().id,r=e.has(i);t.setSelected(r)})}finally{this.isVisualUpdate=!1}}syncSelectionState(e){var s;const t=this.clips.filter(o=>this.selectedClipIds.has(o.getClip().id)),r=t.length>0?t:this.clips.filter(o=>o.getClip().isSelected);if(this.selectedClipIds=new Set(r.map(o=>o.getClip().id)),this.hasSelectedClip=r.length>0,!this.hasSelectedClip){this.selectedClip=null;return}const n=e??((s=this.selectedClip)==null?void 0:s.getClip().id)??null;this.selectedClip=r.find(o=>o.getClip().id===n)??r[r.length-1]??null}splitSelectedClip(e){const t=this.clips.find(i=>{const r=i.getClip();return e>=r.startTime&&e<r.endTime});t&&t.getClip().type!=="text"&&t.split(e)}removeClipGaps(){G.debugLazy("Track",()=>"Removing clip gaps");const e=this.clips.map(i=>i.getClip()).sort((i,r)=>i.startTime-r.startTime);if(e.length===0)return;let t=0;for(let i=0;i<e.length;i++){const r=e[i];if(t-r.startTime<0||i===0){const s=t,o=s+r.duration;this.handleClipUpdate({...r,startTime:s,endTime:o}),t=o}else t=r.startTime+r.duration}}getTrackGroup(){return this.trackGroup}getId(){return this.config.id||"default"}updateClipPosition(e,t,i,r=0){var l;const n=this.clips.find(c=>c.getClip().id===e);if(!n)return;const s=n.getClip(),o=this.clipGroups.get(e);if(i)this.setClipDragOverlayActive(e,!1),this.updateClipPositionFinal(e,t);else if(o){const c=me(t,this.zoom,this.scrollLeft);o.x(c),o.y(this.resolveClipRenderY(e,r)),o.moveToTop(),se.updateClipGroup(o,Ae(s.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(s),s.duration,this.theme,!0,s.thumbnails,s.src,s.type,!!s.separatedAudioClipId,!0,this.getClipAudioBadgeText(s)),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw()}}updateClipPositionFinal(e,t){const i=this.clips.find(s=>s.getClip().id===e);if(!i)return;const r=i.getClip(),n=this.clipGroups.get(e);this.setClipDragOverlayActive(e,!1),n==null||n.y(2),this.isVisualUpdate=!0,this.handleClipUpdate({...r,startTime:t,endTime:t+r.duration}),this.isVisualUpdate=!1}setTrackHeight(e){var t,i;if(this.trackHeight=e,(t=this.dropPreviewGroup)!=null&&t.visible()&&Array.isArray(this.dropPreviewClips)&&this.dropPreviewClips.length>0)this.showDropPreview(this.dropPreviewClips);else if((i=this.dropPreviewGroup)!=null&&i.visible()){const r=this.dropPreviewGroup.children[0];r==null||r.height(Math.max(this.trackHeight-4,1))}this.clips.forEach(r=>{this.updateClipGroup(r.getClip(),!0)}),this.render(!1)}showClipDropPreview(e){this.showDropPreview(e),this.layer.batchDraw()}showClipDropPreviews(e){this.showDropPreview(e),this.layer.batchDraw()}clearClipDropPreview(){this.hideDropPreview(),this.layer.batchDraw()}getRole(){return this.config.role||"normal"}setClipSnapEnabled(e){this.enableClipSnap=e,e||this.updateSnapGuideLine(null);const t=this.resolveInteractionState(),i=Qe(t);if(qt(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var C,T,v,w,x;const r=this.resolveInteractionState(),n=Qe(r),s=jt(r),o=this.layer.getStage(),l=this.resolveDraggedClipForInteraction(r);if(!o||!l||!n||!s)return;const c=o.container();if(!c)return;const h=c.getBoundingClientRect(),d=e-h.left,u=t-h.top,g=s==="move",f=g&&this.multiDragOriginalPositions.size>0;g&&G.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:u,currentTrackId:this.config.id,offsetY:n.crossTrackDragOffsetY}));const y=l.getClip(),S=(C=this.clipGroups)==null?void 0:C.get(y.id);if(S){const P=g&&n.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(y.id,P);const M=n.originalClipsState.find(F=>F.id===y.id);if(!M)return;const I=this.buildPreviewClip(y,M,d,n,s);if(!I){this.hideDropPreview(),(T=this.onClearDropPreview)==null||T.call(this),this.updateSnapGuideLine(null);return}const A=I.clip,k=A.startTime-M.startTime,$=this.applyPreviewClipState(l,A),B=me(A.startTime,this.zoom,this.scrollLeft),Y=Ae(A.duration,this.zoom);S.x(B),S.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)),S.visible(B+Y>0&&B<this.layer.width()),$&&(this.updateClipGroup(A),S.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)));let V=!1;if(f){this.onMultiDragMove&&this.config.id&&(V=this.onMultiDragMove({draggedClipId:y.id,deltaTime:k,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[F,O]of this.multiDragOriginalPositions){if(F===y.id)continue;const J=this.clips.find(ne=>ne.getClip().id===F);if(!J)continue;const N=Math.max(0,O.startTime+k),j=(v=this.clipGroups)==null?void 0:v.get(F);if(j){const ne=me(N,this.zoom,this.scrollLeft);j.x(ne),j.y(this.resolveClipRenderY(F,n.crossTrackDragOffsetY)),j.visible(ne+Ae(O.duration,this.zoom)>0&&ne<this.layer.width());const W=J.getClip();se.updateClipGroup(j,Ae(W.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(W),W.duration,this.theme,!0,W.thumbnails,W.src,W.type,!!W.separatedAudioClipId,!0,this.getClipAudioBadgeText(W))}}}g&&this.onClipCrossTrackPreview&&this.config.id&&!V?this.onClipCrossTrackPreview(A,n.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():V?this.hideDropPreview():this.showDropPreview(A),this.updateSnapGuideLine(I.guideTime)}else this.hideDropPreview(),(w=this.onClearDropPreview)==null||w.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(d,h.width),this.layer.batchDraw(),(x=this.dragOverlayLayer)==null||x.batchDraw()}buildPreviewClip(e,t,i,r,n){const s=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=H.pixelsToTime(s,this.zoom);let l;return n==="resize-left"||e.isResizingLeft?l=this.buildResizeLeftPreviewClip(e,t,o):n==="resize-right"||e.isResizingRight?l=this.buildResizeRightPreviewClip(e,t,o):l={...e,startTime:Math.max(0,t.startTime+o),endTime:Math.max(0,t.startTime+o)+e.duration},this.constrainResizePreviewToTrackBounds(this.applyClipSnap(l,t,r.snapCandidateClips),t,r.nonDraggedClips)}constrainResizePreviewToTrackBounds(e,t,i){if(e.clip.isResizingLeft){const r=this.getResizeLeftBoundaryStart(t,i);if(e.clip.startTime>=r)return e;const n=e.clip.endTime,s=n-r,o=this.isSourceBoundClip(t)?{startTimeAtSource:t.endTimeAtSource-s,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:s,sourceDuration:s};return{clip:{...e.clip,startTime:r,duration:s,endTime:n,...o},guideTime:e.guideTime===r?e.guideTime:null}}if(e.clip.isResizingRight){const r=this.getResizeRightBoundaryEnd(t,i);if(e.clip.startTime+e.clip.duration<=r)return e;const s=r-e.clip.startTime,o=this.isSourceBoundClip(t)?{endTimeAtSource:t.startTimeAtSource+s}:{startTimeAtSource:0,endTimeAtSource:s,sourceDuration:s};return{clip:{...e.clip,duration:s,endTime:r,...o},guideTime:e.guideTime===r?e.guideTime:null}}return e}getResizeLeftBoundaryStart(e,t){let i=0;for(const r of t){if(r.startTime>=e.startTime)continue;const n=r.startTime+r.duration;i=Math.max(i,n)}return i}getResizeRightBoundaryEnd(e,t){let i=Number.POSITIVE_INFINITY;for(const r of t)r.startTime<e.endTime||(i=Math.min(i,r.startTime));return Number.isFinite(i)?i:Number.POSITIVE_INFINITY}buildResizeLeftPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const g=H.calculateEndTime(t.startTime,t.duration);let f=Math.max(0,t.startTime+i),y=g-f;return y<1e3&&(y=1e3,f=g-y),{...e,startTime:f,duration:y,endTime:f+y,startTimeAtSource:0,endTimeAtSource:y,sourceDuration:y}}const n=Math.max(0,t.startTime+i)-t.startTime,o=Math.max(0,t.startTimeAtSource+i)-t.startTimeAtSource,l=Math.abs(n)<Math.abs(o)?n:o,c=H.calculateEndTime(t.startTime,t.duration);let h=t.startTime+l,d=t.duration-l,u;return d<1e3?(d=1e3,h=c-d,u=t.endTimeAtSource-d):u=t.startTimeAtSource+l,{...e,startTime:h,duration:d,endTime:h+d,startTimeAtSource:u,endTimeAtSource:t.endTimeAtSource}}buildResizeRightPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const o=Math.max(1e3,t.duration+i);return{...e,startTime:t.startTime,duration:o,endTime:t.startTime+o,startTimeAtSource:0,endTimeAtSource:o,sourceDuration:o}}let r=Math.max(1e3,t.duration+i);const n=t.startTimeAtSource,s=Math.min(t.sourceDuration,n+r);return r=s-n,{...e,startTime:t.startTime,duration:r,endTime:t.startTime+r,startTimeAtSource:n,endTimeAtSource:s}}applyClipSnap(e,t,i){if(!this.enableClipSnap||i.length===0)return{clip:e,guideTime:null};const r=i.flatMap(c=>[c.startTime,c.startTime+c.duration]);if(r.length===0)return{clip:e,guideTime:null};const n=H.pixelsToTime(this.clipSnapThreshold,this.zoom),s=e.startTime+e.duration,o=[];if(e.isResizingLeft)for(const c of r){const h=s-c,d=t.endTimeAtSource-h,u=Math.abs(c-e.startTime);u>n||h<1e3||this.isSourceBoundClip(t)&&d<0||o.push({clip:{...e,startTime:c,duration:h,endTime:s,...this.isSourceBoundClip(t)?{startTimeAtSource:d,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:h,sourceDuration:h}},guideTime:c,distance:u})}else if(e.isResizingRight)for(const c of r){const h=c-e.startTime,d=t.startTimeAtSource+h,u=Math.abs(c-s);u>n||h<1e3||this.isSourceBoundClip(t)&&d>t.sourceDuration||o.push({clip:{...e,duration:h,endTime:e.startTime+h,...this.isSourceBoundClip(t)?{endTimeAtSource:d}:{startTimeAtSource:0,endTimeAtSource:h,sourceDuration:h}},guideTime:c,distance:u})}else for(const c of r){const h=Math.abs(c-e.startTime);h<=n&&c>=0&&o.push({clip:{...e,startTime:c,endTime:c+e.duration},guideTime:c,distance:h});const d=c-e.duration,u=Math.abs(c-s);u<=n&&d>=0&&o.push({clip:{...e,startTime:d,endTime:d+e.duration},guideTime:c,distance:u})}if(o.length===0)return{clip:e,guideTime:null};o.sort((c,h)=>c.distance-h.distance);const l=o[0];return{clip:l.clip,guideTime:l.guideTime}}applyPreviewClipState(e,t){return e&&typeof e.applyPreviewState=="function"?(e.applyPreviewState(t),!0):(this.isVisualUpdate=!0,this.handleClipUpdate(t),this.isVisualUpdate=!1,!1)}setClipDragOverlayActive(e,t){var o,l;const i=this.getPromotedClipParents(),r=this.clipGroups.get(e);if(!r){i.delete(e);return}if(!t){const c=i.get(e);if(!c)return;r.remove(),c.parent.add(r);const h=(o=this.clips.find(d=>d.getClip().id===e))==null?void 0:o.getClip();h&&r.x(me(h.startTime,this.zoom,this.scrollLeft)),r.y(2),i.delete(e),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw();return}if(i.has(e)||!this.dragOverlayLayer)return;const n=r.getParent();if(!n)return;const s=r.getAbsolutePosition();i.set(e,{parent:n,baseY:this.trackY}),r.remove(),this.dragOverlayLayer.add(r),r.position(s),r.moveToTop(),this.layer.batchDraw(),this.dragOverlayLayer.batchDraw()}resolveClipRenderY(e,t){const i=this.getPromotedClipParents().get(e);return((i==null?void 0:i.baseY)??0)+2+t}getPromotedClipParents(){return this.promotedClipParents instanceof Map||(this.promotedClipParents=new Map),this.promotedClipParents}updateSnapGuideLine(e){var t;(t=this.onSnapGuideChange)==null||t.call(this,this.enableClipSnap?e:null)}updateEdgeAutoScrollState(e,t){if(this.calculateHorizontalAutoScrollVelocity(e,t)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(_e.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=_e.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const n=(i-e)/i;return-Math.max(1,Math.round(n*r))}if(e>t-i){const n=(e-(t-i))/i;return Math.max(1,Math.round(n*r))}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)}};p(_e,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),p(_e,"DEFAULT_CLIP_SNAP_THRESHOLD",8),p(_e,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(_e,"AUTO_SCROLL_MAX_SPEED",18);let zi=_e;class gh{constructor(e,t,i,r,n,s){p(this,"layer");p(this,"playheadGroup");p(this,"playheadLine");p(this,"playheadTriangle");p(this,"theme");p(this,"currentTime",0);p(this,"zoom",100);p(this,"scrollLeft",0);p(this,"onTimeChange");p(this,"isDragging",!1);this.layer=e,this.currentTime=t,this.zoom=i,this.theme=n,this.onTimeChange=s,this.playheadGroup=se.createGroup(),this.layer.add(this.playheadGroup),this.playheadLine=se.createLine([0,0,0,r],this.theme.playhead,1),this.playheadGroup.add(this.playheadLine),this.playheadTriangle=new q.RegularPolygon({x:0,y:5,sides:3,radius:10,fill:this.theme.playhead,rotation:180}),this.playheadGroup.add(this.playheadTriangle),this.initEventListeners(),this.render()}initEventListeners(){var e,t,i;this.playheadGroup.on("mousedown",()=>{this.isDragging=!0}),(e=this.layer.getStage())==null||e.on("mousemove",r=>{this.isDragging&&this.handleMouseMove(r.evt)}),(t=this.layer.getStage())==null||t.on("mouseup",()=>{this.isDragging=!1}),(i=this.layer.getStage())==null||i.on("mouseleave",()=>{this.isDragging=!1})}handleMouseMove(e){if(!this.isDragging)return;const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=H.pixelsToTime(n-ue+this.scrollLeft,this.zoom);this.setTime(s)}setTime(e){this.currentTime=Math.max(0,e),this.onTimeChange(this.currentTime),this.render()}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=e,this.render()}setHeight(e){this.playheadLine.points([0,0,0,e]),this.render()}render(){const e=H.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+ue;this.playheadGroup.x(e),this.playheadGroup.visible(e>=0&&e<=this.layer.width()),this.layer.batchDraw()}getTime(){return this.currentTime}getPlayheadGroup(){return this.playheadGroup}}/**
|
|
16
17
|
* @license
|
|
17
18
|
* Copyright 2019 Google LLC
|
|
18
19
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
19
|
-
*/const
|
|
20
|
+
*/const Ri=globalThis,Xr=Ri.ShadowRoot&&(Ri.ShadyCSS===void 0||Ri.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ya=Symbol(),Fn=new WeakMap;let fh=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==ya)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Xr&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=Fn.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Fn.set(t,e))}return e}toString(){return this.cssText}};const mh=a=>new fh(typeof a=="string"?a:a+"",void 0,ya),yh=(a,e)=>{if(Xr)a.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),r=Ri.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,a.appendChild(i)}},Hn=Xr?a=>a:a=>a instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return mh(t)})(a):a;/**
|
|
20
21
|
* @license
|
|
21
22
|
* Copyright 2017 Google LLC
|
|
22
23
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
23
|
-
*/const{is:
|
|
24
|
+
*/const{is:Sh,defineProperty:Ch,getOwnPropertyDescriptor:vh,getOwnPropertyNames:Th,getOwnPropertySymbols:bh,getPrototypeOf:wh}=Object,Xe=globalThis,Nn=Xe.trustedTypes,kh=Nn?Nn.emptyScript:"",ar=Xe.reactiveElementPolyfillSupport,Kt=(a,e)=>a,Lr={toAttribute(a,e){switch(e){case Boolean:a=a?kh:null;break;case Object:case Array:a=a==null?a:JSON.stringify(a)}return a},fromAttribute(a,e){let t=a;switch(e){case Boolean:t=a!==null;break;case Number:t=a===null?null:Number(a);break;case Object:case Array:try{t=JSON.parse(a)}catch{t=null}}return t}},Sa=(a,e)=>!Sh(a,e),$n={attribute:!0,type:String,converter:Lr,reflect:!1,useDefault:!1,hasChanged:Sa};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Xe.litPropertyMetadata??(Xe.litPropertyMetadata=new WeakMap);let mt=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=$n){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(e,i,t);r!==void 0&&Ch(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){const{get:r,set:n}=vh(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:r,set(s){const o=r==null?void 0:r.call(this);n==null||n.call(this,s),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??$n}static _$Ei(){if(this.hasOwnProperty(Kt("elementProperties")))return;const e=wh(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Kt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Kt("properties"))){const t=this.properties,i=[...Th(t),...bh(t)];for(const r of i)this.createProperty(r,t[r])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[i,r]of t)this.elementProperties.set(i,r)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const r=this._$Eu(t,i);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const r of i)t.unshift(Hn(r))}else e!==void 0&&t.push(Hn(e));return t}static _$Eu(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return yh(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostConnected)==null?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostDisconnected)==null?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){var n;const i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===!0){const s=(((n=i.converter)==null?void 0:n.toAttribute)!==void 0?i.converter:Lr).toAttribute(t,i.type);this._$Em=e,s==null?this.removeAttribute(r):this.setAttribute(r,s),this._$Em=null}}_$AK(e,t){var n,s;const i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const o=i.getPropertyOptions(r),l=typeof o.converter=="function"?{fromAttribute:o.converter}:((n=o.converter)==null?void 0:n.fromAttribute)!==void 0?o.converter:Lr;this._$Em=r;const c=l.fromAttribute(t,o.type);this[r]=c??((s=this._$Ej)==null?void 0:s.get(r))??c,this._$Em=null}}requestUpdate(e,t,i,r=!1,n){var s;if(e!==void 0){const o=this.constructor;if(r===!1&&(n=this[e]),i??(i=o.getPropertyOptions(e)),!((i.hasChanged??Sa)(n,t)||i.useDefault&&i.reflect&&n===((s=this._$Ej)==null?void 0:s.get(e))&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:r,wrapped:n},s){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,s??t??this[e]),n!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),r===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[n,s]of this._$Ep)this[n]=s;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[n,s]of r){const{wrapped:o}=s,l=this[n];o!==!0||this._$AL.has(n)||l===void 0||this.C(n,void 0,s,l)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(i=this._$EO)==null||i.forEach(r=>{var n;return(n=r.hostUpdate)==null?void 0:n.call(r)}),this.update(t)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(i=>{var r;return(r=i.hostUpdated)==null?void 0:r.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};mt.elementStyles=[],mt.shadowRootOptions={mode:"open"},mt[Kt("elementProperties")]=new Map,mt[Kt("finalized")]=new Map,ar==null||ar({ReactiveElement:mt}),(Xe.reactiveElementVersions??(Xe.reactiveElementVersions=[])).push("2.1.2");/**
|
|
24
25
|
* @license
|
|
25
26
|
* Copyright 2017 Google LLC
|
|
26
27
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
27
|
-
*/const
|
|
28
|
-
\f\r]`,
|
|
29
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),
|
|
28
|
+
*/const Zt=globalThis,zn=a=>a,Vi=Zt.trustedTypes,Vn=Vi?Vi.createPolicy("lit-html",{createHTML:a=>a}):void 0,Ca="$lit$",We=`lit$${Math.random().toFixed(9).slice(2)}$`,va="?"+We,xh=`<${va}>`,ot=document,ni=()=>ot.createComment(""),si=a=>a===null||typeof a!="object"&&typeof a!="function",qr=Array.isArray,Ph=a=>qr(a)||typeof(a==null?void 0:a[Symbol.iterator])=="function",or=`[
|
|
29
|
+
\f\r]`,Mt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Un=/-->/g,Wn=/>/g,et=RegExp(`>|${or}(?:([^\\s"'>=/]+)(${or}*=${or}*(?:[^
|
|
30
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),Yn=/'/g,Xn=/"/g,Ta=/^(?:script|style|textarea|title)$/i,_h=a=>(e,...t)=>({_$litType$:a,strings:e,values:t}),K=_h(1),lt=Symbol.for("lit-noChange"),le=Symbol.for("lit-nothing"),qn=new WeakMap,nt=ot.createTreeWalker(ot,129);function ba(a,e){if(!qr(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return Vn!==void 0?Vn.createHTML(e):e}const Ih=(a,e)=>{const t=a.length-1,i=[];let r,n=e===2?"<svg>":e===3?"<math>":"",s=Mt;for(let o=0;o<t;o++){const l=a[o];let c,h,d=-1,u=0;for(;u<l.length&&(s.lastIndex=u,h=s.exec(l),h!==null);)u=s.lastIndex,s===Mt?h[1]==="!--"?s=Un:h[1]!==void 0?s=Wn:h[2]!==void 0?(Ta.test(h[2])&&(r=RegExp("</"+h[2],"g")),s=et):h[3]!==void 0&&(s=et):s===et?h[0]===">"?(s=r??Mt,d=-1):h[1]===void 0?d=-2:(d=s.lastIndex-h[2].length,c=h[1],s=h[3]===void 0?et:h[3]==='"'?Xn:Yn):s===Xn||s===Yn?s=et:s===Un||s===Wn?s=Mt:(s=et,r=void 0);const g=s===et&&a[o+1].startsWith("/>")?" ":"";n+=s===Mt?l+xh:d>=0?(i.push(c),l.slice(0,d)+Ca+l.slice(d)+We+g):l+We+(d===-2?o:g)}return[ba(a,n+(a[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class ai{constructor({strings:e,_$litType$:t},i){let r;this.parts=[];let n=0,s=0;const o=e.length-1,l=this.parts,[c,h]=Ih(e,t);if(this.el=ai.createElement(c,i),nt.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=nt.nextNode())!==null&&l.length<o;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(Ca)){const u=h[s++],g=r.getAttribute(d).split(We),f=/([.?@])?(.*)/.exec(u);l.push({type:1,index:n,name:f[2],strings:g,ctor:f[1]==="."?Eh:f[1]==="?"?Lh:f[1]==="@"?Rh:ji}),r.removeAttribute(d)}else d.startsWith(We)&&(l.push({type:6,index:n}),r.removeAttribute(d));if(Ta.test(r.tagName)){const d=r.textContent.split(We),u=d.length-1;if(u>0){r.textContent=Vi?Vi.emptyScript:"";for(let g=0;g<u;g++)r.append(d[g],ni()),nt.nextNode(),l.push({type:2,index:++n});r.append(d[u],ni())}}}else if(r.nodeType===8)if(r.data===va)l.push({type:2,index:n});else{let d=-1;for(;(d=r.data.indexOf(We,d+1))!==-1;)l.push({type:7,index:n}),d+=We.length-1}n++}}static createElement(e,t){const i=ot.createElement("template");return i.innerHTML=e,i}}function kt(a,e,t=a,i){var s,o;if(e===lt)return e;let r=i!==void 0?(s=t._$Co)==null?void 0:s[i]:t._$Cl;const n=si(e)?void 0:e._$litDirective$;return(r==null?void 0:r.constructor)!==n&&((o=r==null?void 0:r._$AO)==null||o.call(r,!1),n===void 0?r=void 0:(r=new n(a),r._$AT(a,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=r:t._$Cl=r),r!==void 0&&(e=kt(a,r._$AS(a,e.values),r,i)),e}class Ah{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,r=((e==null?void 0:e.creationScope)??ot).importNode(t,!0);nt.currentNode=r;let n=nt.nextNode(),s=0,o=0,l=i[0];for(;l!==void 0;){if(s===l.index){let c;l.type===2?c=new di(n,n.nextSibling,this,e):l.type===1?c=new l.ctor(n,l.name,l.strings,this,e):l.type===6&&(c=new Dh(n,this,e)),this._$AV.push(c),l=i[++o]}s!==(l==null?void 0:l.index)&&(n=nt.nextNode(),s++)}return nt.currentNode=ot,r}p(e){let t=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class di{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,i,r){this.type=2,this._$AH=le,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=r,this._$Cv=(r==null?void 0:r.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=kt(this,e,t),si(e)?e===le||e==null||e===""?(this._$AH!==le&&this._$AR(),this._$AH=le):e!==this._$AH&&e!==lt&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Ph(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==le&&si(this._$AH)?this._$AA.nextSibling.data=e:this.T(ot.createTextNode(e)),this._$AH=e}$(e){var n;const{values:t,_$litType$:i}=e,r=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=ai.createElement(ba(i.h,i.h[0]),this.options)),i);if(((n=this._$AH)==null?void 0:n._$AD)===r)this._$AH.p(t);else{const s=new Ah(r,this),o=s.u(this.options);s.p(t),this.T(o),this._$AH=s}}_$AC(e){let t=qn.get(e.strings);return t===void 0&&qn.set(e.strings,t=new ai(e)),t}k(e){qr(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,r=0;for(const n of e)r===t.length?t.push(i=new di(this.O(ni()),this.O(ni()),this,this.options)):i=t[r],i._$AI(n),r++;r<t.length&&(this._$AR(i&&i._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,t);e!==this._$AB;){const r=zn(e).nextSibling;zn(e).remove(),e=r}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class ji{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,r,n){this.type=1,this._$AH=le,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=n,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=le}_$AI(e,t=this,i,r){const n=this.strings;let s=!1;if(n===void 0)e=kt(this,e,t,0),s=!si(e)||e!==this._$AH&&e!==lt,s&&(this._$AH=e);else{const o=e;let l,c;for(e=n[0],l=0;l<n.length-1;l++)c=kt(this,o[i+l],t,l),c===lt&&(c=this._$AH[l]),s||(s=!si(c)||c!==this._$AH[l]),c===le?e=le:e!==le&&(e+=(c??"")+n[l+1]),this._$AH[l]=c}s&&!r&&this.j(e)}j(e){e===le?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Eh extends ji{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===le?void 0:e}}class Lh extends ji{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==le)}}class Rh extends ji{constructor(e,t,i,r,n){super(e,t,i,r,n),this.type=5}_$AI(e,t=this){if((e=kt(this,e,t,0)??le)===lt)return;const i=this._$AH,r=e===le&&i!==le||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,n=e!==le&&(i===le||r);r&&this.element.removeEventListener(this.name,this,i),n&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class Dh{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){kt(this,e)}}const lr=Zt.litHtmlPolyfillSupport;lr==null||lr(ai,di),(Zt.litHtmlVersions??(Zt.litHtmlVersions=[])).push("3.3.2");const oi=(a,e,t)=>{const i=(t==null?void 0:t.renderBefore)??e;let r=i._$litPart$;if(r===void 0){const n=(t==null?void 0:t.renderBefore)??null;i._$litPart$=r=new di(e.insertBefore(ni(),n),n,void 0,t??{})}return r._$AI(a),r};/**
|
|
30
31
|
* @license
|
|
31
32
|
* Copyright 2017 Google LLC
|
|
32
33
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
33
|
-
*/const
|
|
34
|
+
*/const at=globalThis;let Di=class extends mt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t;const e=super.createRenderRoot();return(t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=oi(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return lt}};var ms;Di._$litElement$=!0,Di.finalized=!0,(ms=at.litElementHydrateSupport)==null||ms.call(at,{LitElement:Di});const cr=at.litElementPolyfillSupport;cr==null||cr({LitElement:Di});(at.litElementVersions??(at.litElementVersions=[])).push("4.2.2");/**
|
|
34
35
|
* @license
|
|
35
36
|
* Copyright 2017 Google LLC
|
|
36
37
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
37
|
-
*/const
|
|
38
|
+
*/const Mh={CHILD:2},Oh=a=>(...e)=>({_$litDirective$:a,values:e});class Bh{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
|
|
38
39
|
* @license
|
|
39
40
|
* Copyright 2017 Google LLC
|
|
40
41
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
41
|
-
*/class
|
|
42
|
+
*/class Rr extends Bh{constructor(e){if(super(e),this.it=le,e.type!==Mh.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===le||e==null)return this._t=void 0,this.it=e;if(e===lt)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}}Rr.directiveName="unsafeHTML",Rr.resultType=1;const Jt=Oh(Rr);class wa{constructor(){p(this,"container",null);p(this,"viewModel",null)}mount(e){this.container=e,this.renderCurrent()}update(e){this.viewModel=e,this.renderCurrent()}destroy(){this.container&&oi(le,this.container),this.container=null,this.viewModel=null}get mountedContainer(){return this.container}afterRender(e,t){}renderCurrent(){!this.container||!this.viewModel||(oi(this.renderTemplate(this.viewModel),this.container),this.afterRender(this.container,this.viewModel))}}class Gh extends wa{renderTemplate(e){const{theme:t,tracks:i,scrollTop:r,timeScaleHeight:n,includeTimeScaleSpacer:s,onMuteTrack:o,icons:l}=e;return K`
|
|
42
43
|
<style>
|
|
43
44
|
.track-info-item:hover {
|
|
44
45
|
background: ${t.buttonHover};
|
|
@@ -53,9 +54,9 @@ js: import "konva/skia-backend";
|
|
|
53
54
|
class="track-info-list"
|
|
54
55
|
style=${`will-change:transform;transform:translateY(-${Math.max(0,r)}px);`}
|
|
55
56
|
>
|
|
56
|
-
${i.map((h
|
|
57
|
+
${i.map((c,h)=>this.renderTrackItem(c,h,t,o,l))}
|
|
57
58
|
</div>
|
|
58
|
-
`}renderTrackItem(e,t,i,r,n){const s=e.type==="text"?Le.TEXT:e.type==="video"?Le.VIDEO:Le.AUDIO,o=e.type==="text"?n.textTrack:e.type==="video"?n.videoTrack:n.audioTrack,l=e.type==="text"?e.isMuted?n.hide:n.display:e.isMuted?n.volumeMuted:n.volume,
|
|
59
|
+
`}renderTrackItem(e,t,i,r,n){const s=e.type==="text"?Le.TEXT:e.type==="video"?Le.VIDEO:Le.AUDIO,o=e.type==="text"?n.textTrack:e.type==="video"?n.videoTrack:n.audioTrack,l=e.type==="text"?e.isMuted?n.hide:n.display:e.isMuted?n.volumeMuted:n.volume,c=e.type==="text"?e.isMuted?"显示文本轨":"隐藏文本轨":e.isMuted?"取消静音":"静音";return K`
|
|
59
60
|
<div
|
|
60
61
|
class="track-info-item"
|
|
61
62
|
data-index=${String(t)}
|
|
@@ -67,21 +68,21 @@ js: import "konva/skia-backend";
|
|
|
67
68
|
class="track-icon"
|
|
68
69
|
style="user-select:none;display:flex;align-items:center;justify-content:center;"
|
|
69
70
|
>
|
|
70
|
-
${o?
|
|
71
|
+
${o?Jt(this.resizeSvg(o,18)):e.type==="text"?"T":e.type==="video"?"🎬":"🎵"}
|
|
71
72
|
</span>
|
|
72
73
|
</div>
|
|
73
74
|
<div style="display:flex;align-items:center;gap:4px;">
|
|
74
75
|
<button
|
|
75
76
|
class="track-mute-btn"
|
|
76
|
-
title=${
|
|
77
|
+
title=${c}
|
|
77
78
|
style=${["background:transparent","border:none",`color:${i.text}`,"padding:4px","border-radius:4px","cursor:pointer","font-size:14px","transition:background-color 0.15s ease","display:flex","align-items:center","justify-content:center"].join(";")}
|
|
78
|
-
@click=${
|
|
79
|
+
@click=${h=>{h.stopPropagation(),r==null||r(e.id,!e.isMuted)}}
|
|
79
80
|
>
|
|
80
|
-
${l?
|
|
81
|
+
${l?Jt(this.resizeSvg(l,14)):e.isMuted?"🔇":"🔊"}
|
|
81
82
|
</button>
|
|
82
83
|
</div>
|
|
83
84
|
</div>
|
|
84
|
-
`}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class
|
|
85
|
+
`}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class ka{constructor(e,t,i,r){p(this,"container");p(this,"tracks",[]);p(this,"theme");p(this,"width",200);p(this,"timeScaleHeight",40);p(this,"includeTimeScaleSpacer",!0);p(this,"scrollTop",0);p(this,"renderer",new Gh);p(this,"iconCache",new Map);p(this,"onMuteTrack");var n,s,o,l,c,h;this.container=e.container,this.width=e.width||200,this.timeScaleHeight=e.timeScaleHeight||40,this.includeTimeScaleSpacer=e.includeTimeScaleSpacer??!0,this.theme={background:((n=e.theme)==null?void 0:n.background)||be.background,border:((s=e.theme)==null?void 0:s.border)||be.border,text:((o=e.theme)==null?void 0:o.text)||be.text,buttonBackground:((l=e.theme)==null?void 0:l.buttonBackground)||be.buttonBackground,buttonHover:((c=e.theme)==null?void 0:c.buttonHover)||be.buttonHover,buttonDanger:((h=e.theme)==null?void 0:h.buttonDanger)||be.buttonDanger},this.onMuteTrack=r,this.iconCache.set("OmAi-camera",Te("OmAi-camera")),this.iconCache.set("OmAi-display",Te("OmAi-display")),this.iconCache.set("OmAi-hide",Te("OmAi-hide")),this.iconCache.set("OmAi-music",Te("OmAi-music")),this.iconCache.set("OmAi-text",Te("OmAi-text")),this.iconCache.set("OmAi-volume",Te("OmAi-volume")),this.iconCache.set("OmAi-volume-mute",Te("OmAi-volume-mute")),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.renderer.mount(this.container),this.render()}setTracks(e){this.tracks=[...e],this.render()}getTracks(){return[...this.tracks]}render(){this.renderer.update({tracks:this.tracks,scrollTop:this.scrollTop,theme:this.theme,timeScaleHeight:this.timeScaleHeight,includeTimeScaleSpacer:this.includeTimeScaleSpacer,onMuteTrack:this.onMuteTrack,icons:{textTrack:this.iconCache.get("OmAi-text")??"",videoTrack:this.iconCache.get("OmAi-camera")??"",audioTrack:this.iconCache.get("OmAi-music")??"",display:this.iconCache.get("OmAi-display")??"",hide:this.iconCache.get("OmAi-hide")??"",volume:this.iconCache.get("OmAi-volume")??"",volumeMuted:this.iconCache.get("OmAi-volume-mute")??""}})}setScrollTop(e){this.scrollTop=Math.max(0,e),this.render()}destroy(){this.renderer.destroy(),this.container.innerHTML=""}}const Fh={visual:"画面",audio:"音频",text:"文本",voice:"音色"},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",textPanel:"clip-config-text-panel",voicePanel:"clip-config-voice-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",textarea:"clip-config-textarea",colorInput:"clip-config-color-input",presetGrid:"clip-config-preset-grid",presetButton:"clip-config-preset-button",resetButton:"clip-config-reset-button",emptyState:"clip-config-empty-state",filterGroup:"clip-config-filter-group",filterButton:"clip-config-filter-button",voiceCardGrid:"clip-config-voice-grid",voiceCard:"clip-config-voice-card",voiceCardAvatar:"clip-config-voice-avatar",voiceCardMeta:"clip-config-voice-meta",voiceCardTitle:"clip-config-voice-title",voiceCardSubtitle:"clip-config-voice-subtitle",voiceCardCheck:"clip-config-voice-check",voiceCardPreviewBadge:"clip-config-voice-preview-badge",voiceCheckbox:"clip-config-voice-checkbox",primaryButton:"clip-config-primary-button",errorText:"clip-config-error-text",voiceLoadingOverlay:"clip-config-voice-loading-overlay",voiceLoadingCard:"clip-config-voice-loading-card",voiceLoadingIcon:"clip-config-voice-loading-icon",voiceLoadingText:"clip-config-voice-loading-text"};class Hh extends wa{renderTemplate(e){const{clip:t,theme:i,emptyStateIconSvg:r}=e;return K`
|
|
85
86
|
<style>
|
|
86
87
|
@keyframes clip-config-voice-loading-spin {
|
|
87
88
|
from { transform: rotate(0deg); }
|
|
@@ -141,7 +142,7 @@ js: import "konva/skia-backend";
|
|
|
141
142
|
border-radius: 50%;
|
|
142
143
|
appearance: none;
|
|
143
144
|
-webkit-appearance: none;
|
|
144
|
-
background: radial-gradient(circle at 32% 30%, ${
|
|
145
|
+
background: radial-gradient(circle at 32% 30%, ${E.sliderThumbGlowStart} 0%, ${E.sliderThumbGlowEnd} 74%);
|
|
145
146
|
box-shadow:
|
|
146
147
|
var(--clip-slider-thumb-shadow),
|
|
147
148
|
${ve.sliderThumbInnerShadow};
|
|
@@ -164,33 +165,33 @@ js: import "konva/skia-backend";
|
|
|
164
165
|
height: 9px;
|
|
165
166
|
border: 1px solid var(--clip-slider-thumb-border);
|
|
166
167
|
border-radius: 50%;
|
|
167
|
-
background: radial-gradient(circle at 32% 30%, ${
|
|
168
|
+
background: radial-gradient(circle at 32% 30%, ${E.sliderThumbGlowStart} 0%, ${E.sliderThumbGlowEnd} 74%);
|
|
168
169
|
box-shadow:
|
|
169
170
|
var(--clip-slider-thumb-shadow),
|
|
170
171
|
${ve.sliderThumbInnerShadow};
|
|
171
172
|
}
|
|
172
173
|
</style>
|
|
173
|
-
<div class=${
|
|
174
|
+
<div class=${z.container} style=${this.getContainerStyle(i)}>
|
|
174
175
|
${t?this.renderPanel(e):this.renderEmptyState(i,r)}
|
|
175
176
|
</div>
|
|
176
177
|
${this.renderVoiceLoadingOverlay(e)}
|
|
177
178
|
`}renderVoiceLoadingOverlay(e){return e.isVoiceLoadingOverlayVisible?K`
|
|
178
179
|
<div
|
|
179
|
-
class=${
|
|
180
|
+
class=${z.voiceLoadingOverlay}
|
|
180
181
|
style=${["position:fixed","inset:0","display:flex","align-items:center","justify-content:center","background:rgba(0,0,0,0.45)","z-index:9999","animation-fill-mode:forwards",`animation:${e.isVoiceLoadingOverlayExiting?"clip-config-voice-loading-overlay-exit 180ms ease":"clip-config-voice-loading-overlay-enter 180ms ease"}`].join(";")}
|
|
181
182
|
>
|
|
182
183
|
<div
|
|
183
|
-
class=${
|
|
184
|
+
class=${z.voiceLoadingCard}
|
|
184
185
|
style=${["width:160px","height:160px","border-radius:32px","background:#2d2d2d","display:flex","flex-direction:column","align-items:center","justify-content:center","gap:24px","box-shadow:0 24px 48px rgba(0,0,0,0.32)","animation-fill-mode:forwards",`animation:${e.isVoiceLoadingOverlayExiting?"clip-config-voice-loading-card-exit 180ms ease":"clip-config-voice-loading-card-enter 180ms ease"}`].join(";")}
|
|
185
186
|
>
|
|
186
187
|
<div
|
|
187
|
-
class=${
|
|
188
|
+
class=${z.voiceLoadingIcon}
|
|
188
189
|
style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;animation:clip-config-voice-loading-spin 1s linear infinite;"
|
|
189
190
|
>
|
|
190
|
-
${e.loadingIconSvg?
|
|
191
|
+
${e.loadingIconSvg?Jt(this.resizeSvg(e.loadingIconSvg,24)):"⟳"}
|
|
191
192
|
</div>
|
|
192
193
|
<div
|
|
193
|
-
class=${
|
|
194
|
+
class=${z.voiceLoadingText}
|
|
194
195
|
style="font-size:14px;line-height:24px;color:#c9cbd4;"
|
|
195
196
|
>
|
|
196
197
|
配音生成中...
|
|
@@ -199,18 +200,18 @@ js: import "konva/skia-backend";
|
|
|
199
200
|
</div>
|
|
200
201
|
`:null}renderEmptyState(e,t){return K`
|
|
201
202
|
<div
|
|
202
|
-
class=${
|
|
203
|
+
class=${z.emptyState}
|
|
203
204
|
style=${`text-align:center;padding:40px 20px;color:${e.labelColor};`}
|
|
204
205
|
>
|
|
205
206
|
<div style="margin-bottom:8px;display:flex;align-items:center;justify-content:center;">
|
|
206
|
-
${t?
|
|
207
|
+
${t?Jt(this.resizeSvg(t,14)):"🎬"}
|
|
207
208
|
</div>
|
|
208
209
|
<div style="font-size:13px;">请选择一个片段</div>
|
|
209
210
|
</div>
|
|
210
211
|
`}renderPanel(e){const t=this.getAvailableTabs(e.clip);return K`
|
|
211
212
|
${t.length>1?this.renderTabBar(e,t):null}
|
|
212
213
|
<div
|
|
213
|
-
class=${
|
|
214
|
+
class=${z.content}
|
|
214
215
|
style="padding:12px;flex:1;overflow-y:auto;min-height:0;"
|
|
215
216
|
>
|
|
216
217
|
${t.includes("visual")?this.renderVisualPanel(e):null}
|
|
@@ -221,22 +222,22 @@ js: import "konva/skia-backend";
|
|
|
221
222
|
${this.renderActionBar(e)}
|
|
222
223
|
`}renderTabBar(e,t){return K`
|
|
223
224
|
<div
|
|
224
|
-
class=${
|
|
225
|
+
class=${z.tabBar}
|
|
225
226
|
style=${`display:flex;gap:12px;padding:4px;background-color:${ve.tabBarBackground};border-radius:4px 4px 0 0;height:32px;`}
|
|
226
227
|
>
|
|
227
228
|
${t.map(i=>{const r=e.activeTab===i;return K`
|
|
228
229
|
<button
|
|
229
|
-
class=${
|
|
230
|
-
style=${["line-height:22px","padding:0 6px","border:none","cursor:pointer","font-size:13px","font-family:inherit","transition:background-color 0.15s, color 0.15s",`background-color:${r?ve.activeTabBackground:
|
|
230
|
+
class=${z.tabButton}
|
|
231
|
+
style=${["line-height:22px","padding:0 6px","border:none","cursor:pointer","font-size:13px","font-family:inherit","transition:background-color 0.15s, color 0.15s",`background-color:${r?ve.activeTabBackground:E.transparent}`,`color:${r?ve.activeTabText:ve.inactiveTabText}`,"border-radius:4px"].join(";")}
|
|
231
232
|
@click=${()=>e.callbacks.onTabChange(i)}
|
|
232
233
|
>
|
|
233
|
-
${
|
|
234
|
+
${Fh[i]}
|
|
234
235
|
</button>
|
|
235
236
|
`})}
|
|
236
237
|
</div>
|
|
237
238
|
`}renderActionBar(e){const t=e.activeTab==="voice"&&this.supportsVoicePanel(e.clip);return K`
|
|
238
239
|
<div
|
|
239
|
-
class=${
|
|
240
|
+
class=${z.actionBar}
|
|
240
241
|
style=${[`border-top:1px solid ${e.theme.borderColor}`,"border-radius:0 0 4px 4px","min-height:32px",`background-color:${ve.actionBarBackground}`,"padding:8px 10px"].join(";")}
|
|
241
242
|
>
|
|
242
243
|
${t?this.renderVoiceActionBar(e):null}
|
|
@@ -244,7 +245,7 @@ js: import "konva/skia-backend";
|
|
|
244
245
|
`}renderVoiceActionBar(e){const t=e.clip,i=!e.selectedVoiceId,r=(t==null?void 0:t.type)==="audio"?"配音随文本更新":"本次生成后随文本更新",n=(t==null?void 0:t.type)==="audio"?"变换音色":"生成配音";return K`
|
|
245
246
|
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
|
|
246
247
|
<label
|
|
247
|
-
class=${
|
|
248
|
+
class=${z.voiceCheckbox}
|
|
248
249
|
style="display:flex;align-items:center;gap:8px;cursor:pointer;"
|
|
249
250
|
>
|
|
250
251
|
<input
|
|
@@ -255,7 +256,7 @@ js: import "konva/skia-backend";
|
|
|
255
256
|
<span style=${`font-size:12px;color:${e.theme.textColor};`}>${r}</span>
|
|
256
257
|
</label>
|
|
257
258
|
<button
|
|
258
|
-
class=${
|
|
259
|
+
class=${z.primaryButton}
|
|
259
260
|
style=${["padding:8px 14px","border:none","border-radius:8px","font-size:12px","cursor:pointer","transition:opacity 0.15s",`background:${i?e.theme.buttonBackground:ve.activeTabBackground}`,`color:${i?e.theme.labelColor:e.theme.buttonActiveText}`,i?"opacity:0.7":"opacity:1"].join(";")}
|
|
260
261
|
?disabled=${i}
|
|
261
262
|
@click=${()=>{e.callbacks.onGenerateVoice()}}
|
|
@@ -264,12 +265,12 @@ js: import "konva/skia-backend";
|
|
|
264
265
|
</button>
|
|
265
266
|
</div>
|
|
266
267
|
`}renderVisualPanel(e){const t=e.activeTab==="visual"?"block":"none";return K`
|
|
267
|
-
<div class=${
|
|
268
|
+
<div class=${z.visualPanel} style=${`display:${t};`}>
|
|
268
269
|
${this.renderPositionSection(e)}
|
|
269
270
|
${this.renderScaleSection(e)}
|
|
270
271
|
</div>
|
|
271
272
|
`}renderPositionSection(e){return K`
|
|
272
|
-
<div class=${
|
|
273
|
+
<div class=${z.section} style="margin-bottom:16px;">
|
|
273
274
|
${this.renderSectionTitle("位置",e.theme)}
|
|
274
275
|
${this.renderPositionControl(e,"X","x")}
|
|
275
276
|
${this.renderPositionControl(e,"Y","y")}
|
|
@@ -277,15 +278,15 @@ js: import "konva/skia-backend";
|
|
|
277
278
|
</div>
|
|
278
279
|
`}renderScaleSection(e){const t=this.getTransform(e.clip);return K`
|
|
279
280
|
<div
|
|
280
|
-
class=${
|
|
281
|
+
class=${z.section}
|
|
281
282
|
style=${`border-top:1px solid ${e.theme.borderColor};padding-top:16px;`}
|
|
282
283
|
>
|
|
283
284
|
${this.renderSectionTitle("缩放",e.theme)}
|
|
284
|
-
<div class=${
|
|
285
|
+
<div class=${z.row} style="display:flex;align-items:center;gap:8px;">
|
|
285
286
|
${this.renderRangeInput({min:"0.1",max:"8",step:"0.1",value:String(t.scale),onInput:i=>e.callbacks.onTransformChange("scale",i)})}
|
|
286
287
|
${this.renderNumberInput(e.theme,{min:"0.1",max:"8",step:"0.1",value:String(t.scale),onChange:i=>e.callbacks.onTransformChange("scale",i)})}
|
|
287
288
|
<button
|
|
288
|
-
class=${
|
|
289
|
+
class=${z.resetButton}
|
|
289
290
|
style=${["padding:4px 8px",`border:1px solid ${e.theme.buttonBorder}`,"border-radius:4px",`background:${e.theme.buttonBackground}`,"font-size:11px","cursor:pointer",`color:${e.theme.textColor}`].join(";")}
|
|
290
291
|
@click=${()=>e.callbacks.onTransformChange("scale",1)}
|
|
291
292
|
>
|
|
@@ -294,22 +295,22 @@ js: import "konva/skia-backend";
|
|
|
294
295
|
</div>
|
|
295
296
|
</div>
|
|
296
297
|
`}renderAudioPanel(e){var r;const t=e.activeTab==="audio"?"block":"none",i=((r=e.clip)==null?void 0:r.volume)??1;return K`
|
|
297
|
-
<div class=${
|
|
298
|
-
<div class=${
|
|
298
|
+
<div class=${z.audioPanel} style=${`display:${t};`}>
|
|
299
|
+
<div class=${z.section}>
|
|
299
300
|
${this.renderSectionTitle("音量",e.theme)}
|
|
300
|
-
<div class=${
|
|
301
|
+
<div class=${z.row} style="display:flex;align-items:center;gap:8px;">
|
|
301
302
|
${this.renderRangeInput({min:"0",max:"1",step:"0.01",value:String(i),onInput:n=>e.callbacks.onVolumeChange(n)})}
|
|
302
303
|
${this.renderNumberInput(e.theme,{min:"0",max:"100",step:"1",value:String(Math.round(i*100)),onChange:n=>e.callbacks.onVolumeChange(n/100)})}
|
|
303
304
|
<span style=${`font-size:12px;color:${e.theme.labelColor};`}>%</span>
|
|
304
305
|
</div>
|
|
305
306
|
</div>
|
|
306
307
|
</div>
|
|
307
|
-
`}renderTextPanel(e){const t=e.clip,i=this.getTransform(t),r=
|
|
308
|
-
<div class=${
|
|
309
|
-
<div class=${
|
|
308
|
+
`}renderTextPanel(e){const t=e.clip,i=this.getTransform(t),r=Tt(t==null?void 0:t.textStyle),n=e.activeTab==="text"?"block":"none";return K`
|
|
309
|
+
<div class=${z.textPanel} style=${`display:${n};`}>
|
|
310
|
+
<div class=${z.section} style="margin-bottom:16px;">
|
|
310
311
|
${this.renderSectionTitle("文本",e.theme)}
|
|
311
312
|
<textarea
|
|
312
|
-
class=${
|
|
313
|
+
class=${z.textarea}
|
|
313
314
|
rows="5"
|
|
314
315
|
.value=${e.textDraftContent}
|
|
315
316
|
style=${["width:100%","box-sizing:border-box","padding:12px",`border:1px solid ${e.theme.inputBorder}`,"border-radius:8px","resize:none","font-size:13px","font-family:inherit",`background-color:${e.theme.inputBackground}`,`color:${e.theme.textColor}`].join(";")}
|
|
@@ -317,46 +318,46 @@ js: import "konva/skia-backend";
|
|
|
317
318
|
@blur=${()=>e.callbacks.onTextContentCommit()}
|
|
318
319
|
></textarea>
|
|
319
320
|
</div>
|
|
320
|
-
<div class=${
|
|
321
|
+
<div class=${z.section} style="margin-bottom:16px;">
|
|
321
322
|
${this.renderSectionTitle("字号",e.theme)}
|
|
322
|
-
<div class=${
|
|
323
|
+
<div class=${z.row} style="display:flex;align-items:center;gap:8px;">
|
|
323
324
|
${this.renderRangeInput({min:"5",max:"300",step:"1",value:String(r.fontSize),onInput:s=>e.callbacks.onTextStyleChange("fontSize",s)})}
|
|
324
325
|
${this.renderNumberInput(e.theme,{min:"5",max:"300",step:"1",value:String(r.fontSize),onChange:s=>e.callbacks.onTextStyleChange("fontSize",s)})}
|
|
325
326
|
</div>
|
|
326
327
|
</div>
|
|
327
|
-
<div class=${
|
|
328
|
+
<div class=${z.section} style="margin-bottom:16px;">
|
|
328
329
|
${this.renderSectionTitle("颜色",e.theme)}
|
|
329
330
|
<input
|
|
330
331
|
type="color"
|
|
331
|
-
class=${
|
|
332
|
+
class=${z.colorInput}
|
|
332
333
|
.value=${r.color}
|
|
333
334
|
style=${["width:108px","height:48px","padding:4px",`border:1px solid ${e.theme.inputBorder}`,"border-radius:8px",`background-color:${e.theme.inputBackground}`].join(";")}
|
|
334
335
|
@input=${s=>e.callbacks.onTextStyleChange("color",s.target.value)}
|
|
335
336
|
/>
|
|
336
337
|
</div>
|
|
337
|
-
<div class=${
|
|
338
|
+
<div class=${z.section} style="margin-bottom:16px;">
|
|
338
339
|
${this.renderSectionTitle("位置",e.theme)}
|
|
339
|
-
<div class=${
|
|
340
|
+
<div class=${z.row} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:12px;">
|
|
340
341
|
${this.renderLabeledNumberInput(e,"X",i.x,s=>e.callbacks.onTextStyleChange("x",s),"0.01","0","1")}
|
|
341
342
|
${this.renderLabeledNumberInput(e,"Y",i.y,s=>e.callbacks.onTextStyleChange("y",s),"0.01","0","1")}
|
|
342
343
|
</div>
|
|
343
344
|
</div>
|
|
344
|
-
<div class=${
|
|
345
|
+
<div class=${z.section}>
|
|
345
346
|
${this.renderSectionTitle("旋转",e.theme)}
|
|
346
|
-
<div class=${
|
|
347
|
+
<div class=${z.row} style="max-width:220px;">
|
|
347
348
|
${this.renderLabeledNumberInput(e,"角度",r.rotation,s=>e.callbacks.onTextStyleChange("rotation",s),"1")}
|
|
348
349
|
</div>
|
|
349
350
|
</div>
|
|
350
351
|
</div>
|
|
351
352
|
`}renderVoicePanel(e){const t=e.activeTab==="voice"?"block":"none",i=[{key:"女",label:"女声"},{key:"男",label:"男声"},{key:"普通话",label:"普通话"},{key:"粤语",label:"粤语"}],r=e.voiceCatalog.filter(n=>!e.activeVoiceFilterTag||n.tags.includes(e.activeVoiceFilterTag));return K`
|
|
352
|
-
<div class=${
|
|
353
|
-
<div class=${
|
|
354
|
-
<div class=${
|
|
353
|
+
<div class=${z.voicePanel} style=${`display:${t};`}>
|
|
354
|
+
<div class=${z.section} style="margin-bottom:16px;">
|
|
355
|
+
<div class=${z.filterGroup} style="display:flex;gap:8px;flex-wrap:wrap;">
|
|
355
356
|
${i.map(n=>this.renderFilterButton(e,n.key,n.label,e.activeVoiceFilterTag===n.key,()=>e.callbacks.onVoiceFilterChange(n.key)))}
|
|
356
357
|
</div>
|
|
357
358
|
</div>
|
|
358
|
-
<div class=${
|
|
359
|
-
<div class=${
|
|
359
|
+
<div class=${z.section}>
|
|
360
|
+
<div class=${z.voiceCardGrid} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px;">
|
|
360
361
|
${r.map(n=>this.renderVoiceCard(e,n))}
|
|
361
362
|
</div>
|
|
362
363
|
${r.length===0?K`
|
|
@@ -366,8 +367,8 @@ js: import "konva/skia-backend";
|
|
|
366
367
|
`:null}
|
|
367
368
|
${e.voiceErrorMessage?K`
|
|
368
369
|
<div
|
|
369
|
-
class=${
|
|
370
|
-
style=${`padding-top:12px;font-size:12px;color:${
|
|
370
|
+
class=${z.errorText}
|
|
371
|
+
style=${`padding-top:12px;font-size:12px;color:${E.accentDanger};`}
|
|
371
372
|
>
|
|
372
373
|
${e.voiceErrorMessage}
|
|
373
374
|
</div>
|
|
@@ -376,7 +377,7 @@ js: import "konva/skia-backend";
|
|
|
376
377
|
</div>
|
|
377
378
|
`}renderFilterButton(e,t,i,r,n){return K`
|
|
378
379
|
<button
|
|
379
|
-
class=${
|
|
380
|
+
class=${z.filterButton}
|
|
380
381
|
style=${["padding:6px 12px","border:none","border-radius:999px","cursor:pointer","font-size:12px",`background:${r?ve.activeTabBackground:e.theme.buttonBackground}`,`color:${r?e.theme.buttonActiveText:e.theme.textColor}`].join(";")}
|
|
381
382
|
data-key=${t}
|
|
382
383
|
@click=${n}
|
|
@@ -385,33 +386,33 @@ js: import "konva/skia-backend";
|
|
|
385
386
|
</button>
|
|
386
387
|
`}renderVoiceCard(e,t){const i=e.selectedVoiceId===t.id,r=e.previewingVoiceId===t.id,n=t.avatar;return K`
|
|
387
388
|
<button
|
|
388
|
-
class=${
|
|
389
|
+
class=${z.voiceCard}
|
|
389
390
|
style=${["position:relative","display:flex","align-items:center","gap:12px","width:100%","padding:8px","border-radius:12px","text-align:left","cursor:pointer","border:none",`outline:${i?`1px solid ${e.theme.buttonActiveBorder}`:"none"}`,`background:${i?ve.activeTabBackground:e.theme.buttonBackground}`,`color:${e.theme.textColor}`].join(";")}
|
|
390
391
|
@click=${()=>e.callbacks.onVoiceSelect(t.id)}
|
|
391
392
|
>
|
|
392
393
|
<div
|
|
393
|
-
class=${
|
|
394
|
-
style=${["width:32px","height:32px","border-radius:8px","flex-shrink:0","display:flex","align-items:center","justify-content:center",`background:${n?`url(${n}) center / cover no-repeat`:"linear-gradient(135deg, #6c7080 0%, #424656 100%)"}`,`color:${
|
|
394
|
+
class=${z.voiceCardAvatar}
|
|
395
|
+
style=${["width:32px","height:32px","border-radius:8px","flex-shrink:0","display:flex","align-items:center","justify-content:center",`background:${n?`url(${n}) center / cover no-repeat`:"linear-gradient(135deg, #6c7080 0%, #424656 100%)"}`,`color:${E.white}`,"font-size:18px","font-weight:600"].join(";")}
|
|
395
396
|
>
|
|
396
397
|
${n?"":t.name.slice(0,1)}
|
|
397
398
|
</div>
|
|
398
|
-
<div class=${
|
|
399
|
+
<div class=${z.voiceCardMeta} style="flex:1;min-width:0;">
|
|
399
400
|
<div
|
|
400
|
-
class=${
|
|
401
|
-
style=${["display:flex","align-items:center","gap:6px","padding-right:24px","font-size:14px",`color:${
|
|
401
|
+
class=${z.voiceCardTitle}
|
|
402
|
+
style=${["display:flex","align-items:center","gap:6px","padding-right:24px","font-size:14px",`color:${E.white}`,"white-space:nowrap","overflow:hidden","text-overflow:ellipsis"].join(";")}
|
|
402
403
|
>
|
|
403
404
|
<span style="overflow:hidden;text-overflow:ellipsis;">${t.name}</span>
|
|
404
405
|
${r?K`
|
|
405
406
|
<span
|
|
406
|
-
class=${
|
|
407
|
-
style=${["display:inline-flex","align-items:center","justify-content:center","flex-shrink:0","padding:1px 6px","border-radius:999px","font-size:10px","line-height:16px",`background:${
|
|
407
|
+
class=${z.voiceCardPreviewBadge}
|
|
408
|
+
style=${["display:inline-flex","align-items:center","justify-content:center","flex-shrink:0","padding:1px 6px","border-radius:999px","font-size:10px","line-height:16px",`background:${E.white}`,`color:${ve.activeTabBackground}`].join(";")}
|
|
408
409
|
>
|
|
409
410
|
试听中
|
|
410
411
|
</span>
|
|
411
412
|
`:null}
|
|
412
413
|
</div>
|
|
413
414
|
<div
|
|
414
|
-
class=${
|
|
415
|
+
class=${z.voiceCardSubtitle}
|
|
415
416
|
style=${`padding-top: 2px;font-size:10px;color:${e.theme.labelColor};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`}
|
|
416
417
|
>
|
|
417
418
|
${t.lang} · ${t.emotion}
|
|
@@ -419,20 +420,20 @@ js: import "konva/skia-backend";
|
|
|
419
420
|
</div>
|
|
420
421
|
${i?K`
|
|
421
422
|
<div
|
|
422
|
-
class=${
|
|
423
|
+
class=${z.voiceCardCheck}
|
|
423
424
|
style="position:absolute;top:50%;right:8px;transform:translateY(-42%);"
|
|
424
425
|
>
|
|
425
|
-
${e.selectedIconSvg?
|
|
426
|
+
${e.selectedIconSvg?Jt(this.resizeSvg(e.selectedIconSvg,20)):"✓"}
|
|
426
427
|
</div>
|
|
427
428
|
`:null}
|
|
428
429
|
</button>
|
|
429
430
|
`}renderPositionControl(e,t,i){const r=this.getTransform(e.clip),n=r.scale/2,s=-n,o=1+n;return K`
|
|
430
431
|
<div
|
|
431
|
-
class=${
|
|
432
|
+
class=${z.row}
|
|
432
433
|
style="display:flex;align-items:center;gap:8px;margin-bottom:8px;"
|
|
433
434
|
>
|
|
434
435
|
<label
|
|
435
|
-
class=${
|
|
436
|
+
class=${z.label}
|
|
436
437
|
style=${`width:16px;font-size:13px;color:${e.theme.labelColor};`}
|
|
437
438
|
>
|
|
438
439
|
${t}
|
|
@@ -442,12 +443,12 @@ js: import "konva/skia-backend";
|
|
|
442
443
|
</div>
|
|
443
444
|
`}renderPresetGrid(e){const t=[{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"}];return K`
|
|
444
445
|
<div
|
|
445
|
-
class=${
|
|
446
|
+
class=${z.presetGrid}
|
|
446
447
|
style="display:grid;grid-template-columns:repeat(3, 1fr);gap:4px;"
|
|
447
448
|
>
|
|
448
449
|
${t.map(i=>K`
|
|
449
450
|
<button
|
|
450
|
-
class=${
|
|
451
|
+
class=${z.presetButton}
|
|
451
452
|
style=${["padding:6px",`border:1px solid ${e.theme.buttonBorder}`,"border-radius:4px",`background:${e.theme.buttonBackground}`,"font-size:11px","cursor:pointer",`color:${e.theme.textColor}`].join(";")}
|
|
452
453
|
@click=${()=>{const{x:r,y:n}=this.calculatePresetPosition(e.clip,i.x,i.y);e.callbacks.onPresetSelect(r,n)}}
|
|
453
454
|
>
|
|
@@ -457,7 +458,7 @@ js: import "konva/skia-backend";
|
|
|
457
458
|
</div>
|
|
458
459
|
`}renderSectionTitle(e,t){return K`
|
|
459
460
|
<div
|
|
460
|
-
class=${
|
|
461
|
+
class=${z.sectionTitle}
|
|
461
462
|
style=${`font-size:12px;color:${t.labelColor};margin-bottom:8px;text-transform:uppercase;`}
|
|
462
463
|
>
|
|
463
464
|
${e}
|
|
@@ -465,7 +466,7 @@ js: import "konva/skia-backend";
|
|
|
465
466
|
`}renderRangeInput(e){return K`
|
|
466
467
|
<input
|
|
467
468
|
type="range"
|
|
468
|
-
class=${
|
|
469
|
+
class=${z.slider}
|
|
469
470
|
min=${e.min}
|
|
470
471
|
max=${e.max}
|
|
471
472
|
step=${e.step}
|
|
@@ -476,7 +477,7 @@ js: import "konva/skia-backend";
|
|
|
476
477
|
`}renderNumberInput(e,t){return K`
|
|
477
478
|
<input
|
|
478
479
|
type="number"
|
|
479
|
-
class=${
|
|
480
|
+
class=${z.input}
|
|
480
481
|
min=${t.min}
|
|
481
482
|
max=${t.max}
|
|
482
483
|
step=${t.step}
|
|
@@ -489,7 +490,7 @@ js: import "konva/skia-backend";
|
|
|
489
490
|
<span style=${`min-width:18px;font-size:13px;color:${e.theme.labelColor};`}>${t}</span>
|
|
490
491
|
${this.renderNumberInput(e.theme,{min:s,max:o,step:n,value:String(i),onChange:r})}
|
|
491
492
|
</label>
|
|
492
|
-
`}getContainerStyle(e){return[`background-color:${e.backgroundColor}`,"border-radius:4px",`color:${e.textColor}`,'font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size:13px","display:flex","flex-direction:column","overflow:hidden","height:100%",`--clip-slider-fill-start:${_.sliderFillStart}`,`--clip-slider-fill-end:${_.sliderFillEnd}`,`--clip-slider-road:${_.sliderRoad}`,`--clip-slider-thumb-border:${_.sliderThumbBorder}`,`--clip-slider-thumb-shadow:${ve.sliderThumbShadow}`].join(";")}getSliderStyle(e,t,i){const r=Number(e||0),n=Number(t||100),s=Number(i||0),o=n-r,l=o<=0?0:(s-r)/o*100;return["flex:1","min-width:0",`--clip-slider-progress:${Math.max(0,Math.min(100,l))}%`].join(";")}getAvailableTabs(e){return e?e.type==="text"?["text","voice"]:e.type==="audio"?e.ttsSourceTextClipId?["audio","voice"]:["audio"]:["visual","audio"]:[]}supportsVoicePanel(e){return!!e&&(e.type==="text"||e.type==="audio"&&!!e.ttsSourceTextClipId)}getTransform(e){return(e==null?void 0:e.visualTransform)??{x:.5,y:.5,scale:1}}calculatePresetPosition(e,t,i){const n=this.getTransform(e).scale/2,s={left:n,center:.5,right:1-n},o={top:n,center:.5,bottom:1-n};return{x:s[t],y:o[i]}}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}const pc={...ge};class sa{constructor(e){p(this,"container");p(this,"theme");p(this,"renderer",new uc);p(this,"onClipUpdate");p(this,"onGenerateVoice");p(this,"voiceCatalog");p(this,"currentClip",null);p(this,"activeTab","visual");p(this,"iconCache",new Map);p(this,"pendingPreferredTab",null);p(this,"selectedVoiceId",null);p(this,"activeVoiceFilterTag",null);p(this,"textDraftContent","");p(this,"followTextUpdates",!1);p(this,"voiceLoadingBusyCount",0);p(this,"isVoiceLoadingOverlayRendered",!1);p(this,"isVoiceLoadingOverlayExiting",!1);p(this,"voiceLoadingOverlayHideTimer",null);p(this,"voiceErrorMessage",null);p(this,"voicePreviewAudio",null);p(this,"previewingVoiceId",null);p(this,"handleVoicePreviewEnded",()=>{this.stopVoicePreview()});this.container=e.container,this.theme=e.theme??pc,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",Te("OmAi-camera")),this.iconCache.set("OmAi-accept",Te("OmAi-accept")),this.iconCache.set("OmAi-loading",Te("OmAi-loading")),this.iconCache.set("OmAi-text",Te("OmAi-text")),this.renderer.mount(this.container),this.render()}setClip(e){var n;const t=((n=this.currentClip)==null?void 0:n.id)??null,i=(e==null?void 0:e.id)??null,r=t!==i;r&&this.stopVoicePreview(!1),this.currentClip=e,r?(this.voiceErrorMessage=null,this.textDraftContent=(e==null?void 0:e.textContent)??(e==null?void 0:e.name)??"",this.syncVoiceStateForClip(e)):(e==null?void 0:e.type)==="text"?this.textDraftContent=e.textContent??e.name??"":(e==null?void 0:e.type)==="audio"&&e.ttsSourceTextClipId?(this.followTextUpdates=e.ttsFollowTextUpdates??!1,e.ttsVoiceId&&(this.selectedVoiceId=e.ttsVoiceId),this.ensureVoiceFilters()):e||this.resetVoiceState(),this.syncActiveTab(e),this.render()}setPreferredTab(e){this.pendingPreferredTab=e}setVoiceGenerationBusy(e){if(this.voiceLoadingBusyCount=Math.max(0,this.voiceLoadingBusyCount+(e?1:-1)),this.voiceLoadingBusyCount>0){this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.isVoiceLoadingOverlayRendered=!0,this.isVoiceLoadingOverlayExiting=!1,this.render();return}if(!this.isVoiceLoadingOverlayRendered){this.render();return}this.isVoiceLoadingOverlayExiting=!0,this.voiceLoadingOverlayHideTimer!==null&&window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=window.setTimeout(()=>{this.isVoiceLoadingOverlayRendered=!1,this.isVoiceLoadingOverlayExiting=!1,this.voiceLoadingOverlayHideTimer=null,this.render()},180),this.render()}destroy(){this.stopVoicePreview(!1),this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.renderer.destroy()}render(){this.renderer.update({clip:this.currentClip,activeTab:this.activeTab,theme:this.theme,emptyStateIconSvg:this.iconCache.get("OmAi-camera")??"",loadingIconSvg:this.iconCache.get("OmAi-loading")??"",selectedIconSvg:this.iconCache.get("OmAi-accept")??"",textDraftContent:this.textDraftContent,voiceCatalog:this.voiceCatalog,selectedVoiceId:this.selectedVoiceId,previewingVoiceId:this.previewingVoiceId,activeVoiceFilterTag:this.activeVoiceFilterTag,followTextUpdates:this.followTextUpdates,isVoiceLoadingOverlayVisible:this.isVoiceLoadingOverlayRendered,isVoiceLoadingOverlayExiting:this.isVoiceLoadingOverlayExiting,voiceErrorMessage:this.voiceErrorMessage,callbacks:{onTabChange:e=>{this.activeTab=e,this.render()},onTransformChange:(e,t)=>{this.handleTransformChange(e,t)},onPresetSelect:(e,t)=>{this.handleTransformChanges({x:e,y:t})},onVolumeChange:e=>{this.handleVolumeChange(e)},onTextContentInput:e=>{this.handleTextContentInput(e)},onTextContentCommit:()=>{this.handleTextContentCommit()},onTextStyleChange:(e,t)=>{this.handleTextStyleChange(e,t)},onVoiceFilterChange:e=>{this.handleVoiceFilterChange(e)},onVoiceSelect:e=>{this.handleVoiceSelect(e)},onVoiceFollowTextUpdatesChange:e=>{this.handleVoiceFollowTextUpdatesChange(e)},onGenerateVoice:async()=>{await this.handleGenerateVoice()}}})}getAvailableTabs(e=this.currentClip){return e?e.type==="text"?["text","voice"]:e.type==="audio"?e.ttsSourceTextClipId?["audio","voice"]:["audio"]:["visual","audio"]:[]}resetVoiceState(){this.selectedVoiceId=null,this.activeVoiceFilterTag=null,this.followTextUpdates=!1,this.stopVoicePreview(!1)}syncVoiceStateForClip(e){if(!e||!this.supportsVoicePanel(e)){this.resetVoiceState();return}const i=(e.type==="audio"&&e.ttsVoiceId?this.voiceCatalog.find(r=>r.id===e.ttsVoiceId)??null:null)??this.voiceCatalog[0]??null;this.selectedVoiceId=(i==null?void 0:i.id)??null,this.activeVoiceFilterTag=this.resolveDefaultVoiceFilterTag(i),this.followTextUpdates=e.type==="audio"?e.ttsFollowTextUpdates??!1:!1,this.ensureVoiceFilters()}syncActiveTab(e){const t=this.getAvailableTabs(e);if(!e||t.length===0){this.activeTab="visual",this.pendingPreferredTab=null;return}if(this.pendingPreferredTab&&t.includes(this.pendingPreferredTab)){this.activeTab=this.pendingPreferredTab,this.pendingPreferredTab=null;return}t.includes(this.activeTab)||(this.activeTab=t[0],this.pendingPreferredTab=null)}supportsVoicePanel(e){return!!e&&(e.type==="text"||e.type==="audio"&&!!e.ttsSourceTextClipId)}resolveDefaultVoiceFilterTag(e){return e?e.tags.includes("男")?"男":e.tags.includes("女")?"女":e.tags.includes("普通话")?"普通话":e.tags.includes("粤语")?"粤语":null:null}getVisibleVoiceOptions(){return this.voiceCatalog.filter(e=>!this.activeVoiceFilterTag||e.tags.includes(this.activeVoiceFilterTag))}ensureVoiceFilters(){if(this.voiceCatalog.length===0){this.resetVoiceState();return}if(!this.getVisibleVoiceOptions().some(t=>t.id===this.selectedVoiceId)){const t=this.voiceCatalog.find(i=>!this.activeVoiceFilterTag||i.tags.includes(this.activeVoiceFilterTag))??this.voiceCatalog[0]??null;this.selectedVoiceId=(t==null?void 0:t.id)??null}}handleVoiceFilterChange(e){const t=e==="男"||e==="女"||e==="普通话"||e==="粤语"?e:null;this.activeVoiceFilterTag=this.activeVoiceFilterTag===t?null:t,this.ensureVoiceFilters(),this.render()}async handleVoiceSelect(e){const t=this.voiceCatalog.find(r=>r.id===e)??null,i=this.previewingVoiceId===e;if(this.selectedVoiceId=e,this.voiceErrorMessage=null,this.render(),!(t!=null&&t.audiofile)){this.stopVoicePreview();return}if(i){this.stopVoicePreview();return}await this.playVoicePreview(t)}handleVoiceFollowTextUpdatesChange(e){var t;this.followTextUpdates=e,((t=this.currentClip)==null?void 0:t.type)==="audio"&&this.currentClip.ttsSourceTextClipId&&this.onClipUpdate&&(this.currentClip={...this.currentClip,ttsFollowTextUpdates:e},this.onClipUpdate(this.currentClip.id,{ttsFollowTextUpdates:e})),this.render()}async handleGenerateVoice(){if(!this.currentClip||!this.onGenerateVoice)return;const e=this.voiceCatalog.find(t=>t.id===this.selectedVoiceId);if(!e){this.voiceErrorMessage="请选择一个音色",this.render();return}this.voiceErrorMessage=null,this.render();try{await this.onGenerateVoice(this.currentClip,e,this.followTextUpdates)}catch(t){this.voiceErrorMessage=t instanceof Error?t.message:"音色生成失败"}this.render()}handleVolumeChange(e){if(!this.currentClip||!this.onClipUpdate)return;const t=Math.max(0,Math.min(1,e));this.currentClip={...this.currentClip,volume:t},this.render(),this.onClipUpdate(this.currentClip.id,{volume:t})}clampValue(e,t){return e==="scale"?Math.max(.1,Math.min(8,t)):t}handleTransformChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(e,t),n={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:i};this.currentClip={...this.currentClip,visualTransform:n},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:n})}handleTransformChanges(e){if(!this.currentClip||!this.onClipUpdate)return;const i={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1}};e.x!==void 0&&(i.x=this.clampValue("x",e.x)),e.y!==void 0&&(i.y=this.clampValue("y",e.y)),e.scale!==void 0&&(i.scale=this.clampValue("scale",e.scale)),this.currentClip={...this.currentClip,visualTransform:i},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:i})}stopVoicePreview(e=!0){if(this.voicePreviewAudio){this.voicePreviewAudio.removeEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio.pause();try{this.voicePreviewAudio.currentTime=0}catch{}this.voicePreviewAudio=null}if(this.previewingVoiceId!==null){this.previewingVoiceId=null,e&&this.render();return}e&&this.render()}async playVoicePreview(e){if(!e.audiofile)return;this.stopVoicePreview(!1);const t=new Audio(e.audiofile);t.preload="auto",t.addEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio=t,this.previewingVoiceId=e.id,this.render();try{await t.play()}catch(i){this.voicePreviewAudio===t&&(this.stopVoicePreview(!1),this.voiceErrorMessage=i instanceof Error?i.message:"试听播放失败",this.render())}}handleTextContentInput(e){this.textDraftContent=e,this.render()}handleTextContentCommit(){if(!this.currentClip||!this.onClipUpdate)return;const e=this.textDraftContent,t=this.currentClip.textContent??this.currentClip.name??"";e!==t&&(this.currentClip={...this.currentClip,textContent:e},this.render(),this.onClipUpdate(this.currentClip.id,{textContent:e}))}handleTextStyleChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;if(e==="x"||e==="y"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;const o={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:Math.max(0,Math.min(1,n))};this.currentClip={...this.currentClip,visualTransform:o},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:o});return}const r={...vt(this.currentClip.textStyle)};if(e==="fontSize"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.fontSize=Math.max(5,Math.min(300,n))}else if(e==="rotation"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.rotation=n}else r.color=String(t);this.currentClip={...this.currentClip,textStyle:r},this.render(),this.onClipUpdate(this.currentClip.id,{textStyle:r})}}function gc(a){return a==="text"?"文本":a==="video"?"视频":"音频"}function Hn(a){return a==="text"?Le.TEXT:a==="video"?Le.VIDEO:Le.AUDIO}class Fn{constructor(e){this.timelineStore=e}selectClip(e){return this.updateSelection(e)}clearSelection(){return this.updateSelection(null)}findClipById(e,t){for(const i of e){const r=i.getClips().find(n=>n.id===t);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}findClipAtTime(e,t){for(const i of e){const r=i.getClips().find(n=>t>=n.startTime&&t<n.startTime+n.duration);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}prepareRemoveClip(e,t){const i=this.findClipById(t,e);return i?{exists:!0,clip:i.clip,trackId:i.trackId,shouldClearSelection:this.timelineStore.getPrimarySelectedClipId()===e}:{exists:!1,clip:null,trackId:null,shouldClearSelection:!1}}prepareMoveClipToTrack(e,t,i){var c;const r=this.findClipById(i,e);if(!r||!r.trackId)return{status:"missing_source_track",clipId:e,targetTrackId:t};const{clip:n,track:s,trackId:o}=r;if(o===t)return{status:"noop",clipId:e,sourceTrackId:o,targetTrackId:t};const l=i.find(d=>this.resolveTrackId(d)===t);if(!l)return{status:"missing_target_track",clipId:e,targetTrackId:t,sourceTrackId:o};const h=(c=l.getTrackType)==null?void 0:c.call(l);return h&&h!==n.type?{status:"track_type_mismatch",clipId:e,targetTrackId:t,sourceTrackId:o}:{status:"ready",clip:n,sourceTrack:s,sourceTrackId:o,targetTrack:l,targetTrackId:t}}planTrackPlacement(e,t){var n;const i=e.startTime+e.duration;for(const s of t){if(((n=s.getTrackType)==null?void 0:n.call(s))!==e.type)continue;if(!s.getClips().some(l=>e.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(s);if(l)return{status:"use_existing_track",trackId:l}}}const r=t.filter(s=>{var o;return((o=s.getTrackType)==null?void 0:o.call(s))===e.type}).length+1;return{status:"create_track",trackType:e.type,suggestedTrackName:`${gc(e.type)}轨道 ${r}`,insertionPlacement:e.type==="text"||e.type==="video"?"top_of_type_region":"bottom_of_type_region"}}planCrossTrackMove(e,t,i,r,n,s){var f;const o=this.resolveTrackTargetByY(t,r,n,e.type);if(o.status==="create_track")return{status:"create_track",trackType:e.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const h=s.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!==e.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:c};if(!this.hasOverlapOnTrack(e,h))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(e.type,l,t,r,n);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=n.filter(y=>y.type===e.type).map(y=>y.id),g=u.indexOf(l);for(let y=1;y<=u.length;y+=1){const v=g-y;if(v>=0){const T=u[v],w=s.find(b=>this.resolveTrackId(b)===T);if(w&&!this.hasOverlapOnTrack(e,w))return{status:"move_to_track",targetTrackId:T}}const C=g+y;if(C<u.length){const T=u[C],w=s.find(b=>this.resolveTrackId(b)===T);if(w&&!this.hasOverlapOnTrack(e,w))return{status:"move_to_track",targetTrackId:T}}}return{status:"create_track",trackType:e.type,insertionPlacement:e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary"}}planCrossTrackPreview(e,t,i,r,n,s){const o=this.planCrossTrackMove(e,t,i,r,n,s);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(e){const t=Math.max(0,e);return this.updateCurrentTime(t)}setZoom(e){const t=Math.max(ye.MIN,Math.min(ye.MAX,e));return this.updateZoom(t)}setSpeed(e){const t=Math.max(.1,Math.min(10,e));return this.updateSpeed(t)}updateSelection(e){const t=this.timelineStore.getPrimarySelectedClipId();return t===e?{previousClipId:t,nextClipId:e,changed:!1}:(e===null?this.timelineStore.clearSelection():this.timelineStore.setPrimarySelectedClipId(e),{previousClipId:t,nextClipId:e,changed:!0})}updateCurrentTime(e){const t=this.timelineStore.getCurrentTime();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setCurrentTime(e),{previousValue:t,nextValue:e,changed:!0})}updateZoom(e){const t=this.timelineStore.getZoom();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setZoom(e),{previousValue:t,nextValue:e,changed:!0})}updateSpeed(e){const t=this.timelineStore.getSpeed();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setSpeed(e),{previousValue:t,nextValue:e,changed:!0})}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}resolveTrackType(e){return typeof e.getTrackType=="function"?e.getTrackType():e.type??null}resolveTrackTargetByY(e,t,i,r){let n=t,s=null,o=null;for(const l of i){const h=Hn(l.type),c=n+h;if(l.type===r&&(s===null&&(s=n),o=c),e>=n&&e<c)return{status:"existing_track",targetTrackId:l.id};n=c}return r==="text"&&s!==null&&e<s?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="video"&&s!==null&&e<s?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="audio"&&o!==null&&e>=o?{status:"create_track",insertionPlacement:"bottom_of_type_region"}:{status:"missing_target_track_by_position"}}resolvePreferredInsertionPlacement(e,t,i,r,n){let s=r;const o=n.map(d=>{const u=s,g=Hn(d.type),f=u+g;return s=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:g}}).filter(d=>d.type===e),l=o.findIndex(d=>d.id===t);if(l===-1)return null;const h=o[l],c=Math.min(12,Math.max(6,Math.floor(h.height/4)));return h.role==="primary"?{insertionPlacement:e==="text"||e==="video"?"before_track":"after_track",referenceTrackId:t}:l<o.length-1&&i>=h.endY-c?{insertionPlacement:"after_track",referenceTrackId:t}:{insertionPlacement:"before_track",referenceTrackId:t}}hasOverlapOnTrack(e,t){const i=e.startTime+e.duration;return t.getClips().some(r=>r.id===e.id?!1:e.startTime<r.endTime&&i>r.startTime)}}class Pr{constructor(e,t,i,r=100){p(this,"state");p(this,"maxHistorySize",100);p(this,"onActionUndo");p(this,"onActionRedo");p(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=r,this.onActionUndo=e,this.onActionRedo=t,this.onHistoryChange=i}addAction(e){this.state.past.length>=this.maxHistorySize&&this.state.past.shift(),this.state.past.push({...e,timestamp:Date.now()}),this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}undo(){if(this.state.past.length===0)return!1;const e=this.state.past.pop();return this.state.future.push(e),this.onActionUndo(e),this.onHistoryChange&&this.onHistoryChange(),!0}redo(){if(this.state.future.length===0)return!1;const e=this.state.future.pop();return this.state.past.push(e),this.onActionRedo(e),this.onHistoryChange&&this.onHistoryChange(),!0}clear(){this.state.past=[],this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}canUndo(){return this.state.past.length>0}canRedo(){return this.state.future.length>0}getState(){return{...this.state}}createAddClipAction(e){return{type:"add_clip",data:e,timestamp:Date.now()}}createRemoveClipAction(e){return{type:"remove_clip",data:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null},timestamp:Date.now()}}createRemoveClipActionWithTrackSnapshot(e,t,i,r=null){return{type:"remove_clip",data:{clip:e,sourceTrackId:t,sourceTrackSnapshot:i,sourceTrackRestoreAnchor:r},timestamp:Date.now()}}createUpdateClipAction(e,t,i){return{type:"update_clip",data:{clipId:e,updates:t,previousState:i},timestamp:Date.now()}}createSplitClipAction(e,t,i){return{type:"split_clip",data:{originalClip:e,clip1:t,clip2:i},timestamp:Date.now()}}createMoveClipAction(e,t,i){return{type:"move_clip",data:{clipId:e,newStartTime:t,previousStartTime:i},timestamp:Date.now()}}createResizeClipAction(e,t,i,r,n){return{type:"resize_clip",data:{clipId:e,newDuration:t,newStartTime:i,previousDuration:r,previousStartTime:n},timestamp:Date.now()}}createSetTimeAction(e,t){return{type:"set_time",data:{newTime:e,previousTime:t},timestamp:Date.now()}}createRemoveGapsAction(e){return{type:"remove_gaps",data:{clipsBefore:e},timestamp:Date.now()}}createMultiClipUpdateAction(e){return{type:"multi_clip_update",data:{clipUpdates:e},timestamp:Date.now()}}createMoveClipBetweenTracksAction(e,t,i,r,n,s,o){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:r,clipAfter:n,sourceTrackSnapshot:s,targetTrackSnapshot:o},timestamp:Date.now()}}createSeparateClipAudioAction(e,t,i,r){return{type:"separate_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createRestoreClipAudioAction(e,t,i,r){return{type:"restore_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createCompoundAction(e,t){return{type:"compound",data:{actions:e,...t?{label:t}:{}},timestamp:Date.now()}}}class $n{constructor(e){this.target=e}executeUndo(e){this.executeUndoInternal(e,new Map)}executeRedo(e){this.executeRedoInternal(e,new Map)}executeUndoInternal(e,t){var i,r;switch(e.type){case"add_clip":this.target.removeClip(e.data.id);break;case"remove_clip":{const n=this.normalizeRemoveClipActionData(e.data);let s=!1;const o=this.resolveTrackIdForHistorySnapshot(n.sourceTrackSnapshot,n.sourceTrackId,t,n.sourceTrackRestoreAnchor);if(o&&(s=this.target.addClipToTrack(o,n.clip)),!s){const l=this.target.findTrackByClipId(n.clip.id)||this.target.getDefaultTrack();l==null||l.addClip(n.clip)}(r=(i=this.target).loadClipThumbnails)==null||r.call(i,n.clip);break}case"update_clip":this.target.updateClip(e.data.clipId,e.data.previousState);break;case"split_clip":{this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id);const n=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack();n==null||n.addClip(e.data.originalClip);break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.previousStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.previousDuration,startTime:e.data.previousStartTime});break;case"remove_gaps":this.target.getClips().forEach(n=>this.target.removeClip(n.id)),e.data.clipsBefore.forEach(n=>{const s=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();s==null||s.addClip(n)});break;case"multi_clip_update":e.data.clipUpdates.forEach(n=>{this.target.updateClip(n.clipId,n.previousState)});break;case"move_clip_between_tracks":this.restoreMovedClip(e.data.clipId,e.data.sourceTrackSnapshot,e.data.clipBefore,t);break;case"separate_clip_audio":e.data.audioClip&&this.target.removeClip(e.data.audioClip.id),this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"compound":[...e.data.actions].reverse().forEach(n=>{this.executeUndoInternal(n,t)});break;default:M.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:e.type})}}executeRedoInternal(e,t){var i,r;switch(e.type){case"add_clip":{const n=e.data,s=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();s==null||s.addClip(n),(r=(i=this.target).loadClipThumbnails)==null||r.call(i,n);break}case"remove_clip":this.target.removeClip(e.data.clip.id);break;case"update_clip":this.target.updateClip(e.data.clipId,e.data.updates);break;case"split_clip":{this.target.removeClip(e.data.originalClip.id);const n=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack();n==null||n.addClip(e.data.clip1),n==null||n.addClip(e.data.clip2);break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.newStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.newDuration,startTime:e.data.newStartTime});break;case"remove_gaps":this.target.removeClipGaps();break;case"multi_clip_update":e.data.clipUpdates.forEach(n=>{this.target.updateClip(n.clipId,n.newState)});break;case"move_clip_between_tracks":this.restoreMovedClip(e.data.clipId,e.data.targetTrackSnapshot,e.data.clipAfter,t);break;case"separate_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter),e.data.audioClip&&e.data.audioTrackId&&this.target.addClipToTrack(e.data.audioTrackId,e.data.audioClip);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter);break;case"compound":e.data.actions.forEach(n=>{this.executeRedoInternal(n,t)});break;default:M.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:e.type})}}restoreMovedClip(e,t,i,r){const n=this.resolveTrackIdForHistorySnapshot(t,(t==null?void 0:t.id)??null,r,null);n&&this.target.moveClipToTrack(e,n),this.target.updateClip(e,i)}normalizeRemoveClipActionData(e){return"clip"in e?e:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null}}resolveTrackIdForHistorySnapshot(e,t,i,r){const n=(e==null?void 0:e.id)??t??null;if(n){const o=i.get(n);if(o)return o}if(!e)return t;const s=this.target.ensureTrackFromHistorySnapshot(e,this.resolveRestoreAnchor(r,i))??t;return n&&s&&i.set(n,s),s}resolveRestoreAnchor(e,t){return e?{previousTrackId:e.previousTrackId?t.get(e.previousTrackId)??e.previousTrackId:null,nextTrackId:e.nextTrackId?t.get(e.nextTrackId)??e.nextTrackId:null}:null}}const fc=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],mc=new Set(["thumbnails"]);function yc(a,e){return Object.is(a,e)?!0:a===void 0||e===void 0?!1:typeof a=="object"&&typeof e=="object"?JSON.stringify(a)===JSON.stringify(e):!1}class Nn{constructor(e){this.history=e}recordAddClip(e){const t=this.history.createAddClipAction(e);return this.history.addAction(t),t}createRemoveClipAction(e,t=null,i=null,r=null){return t||i?this.history.createRemoveClipActionWithTrackSnapshot(e,t,i,r):this.history.createRemoveClipAction(e)}recordRemoveClip(e,t=null,i=null,r=null){const n=this.createRemoveClipAction(e,t,i,r);return this.history.addAction(n),n}recordClipUpdate(e,t,i){const r=this.createClipUpdateAction(e,t,i);return r?(this.history.addAction(r),r):null}recordSplitClip(e,t){const i={...e,id:e.id.replace("_split_",""),duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},r=this.history.createSplitClipAction(i,e,t);return this.history.addAction(r),r}recordRemoveGaps(e){if(e.length===0)return null;const t=this.history.createRemoveGapsAction(e);return this.history.addAction(t),t}recordMoveClipBetweenTracks(e,t,i,r,n,s,o){const l=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,s,o);return this.history.addAction(l),l}recordSeparateClipAudio(e,t,i,r){const n=this.history.createSeparateClipAudioAction(e,t,i,r);return this.history.addAction(n),n}recordRestoreClipAudio(e,t,i,r){const n=this.history.createRestoreClipAudioAction(e,t,i,r);return this.history.addAction(n),n}createSeparateClipAudioAction(e,t,i,r){return this.history.createSeparateClipAudioAction(e,t,i,r)}createRestoreClipAudioAction(e,t,i,r){return this.history.createRestoreClipAudioAction(e,t,i,r)}recordCompoundAction(e,t){if(e.length===0)return null;const i=this.history.createCompoundAction(e,t);return this.history.addAction(i),i}createClipUpdateAction(e,t,i){if(i&&i.length>0)return this.history.createMultiClipUpdateAction(i);if(!t)return null;if(t.startTime!==e.startTime&&t.duration===e.duration)return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);if(t.duration!==e.duration)return this.history.createResizeClipAction(e.id,e.duration,e.startTime,t.duration,t.startTime);const s={},o={};return fc.forEach(h=>{yc(e[h],t[h])||(s[h]=e[h],o[h]=t[h])}),Object.keys(s).length===0||Object.keys(s).every(h=>mc.has(h))?null:this.history.createUpdateClipAction(e.id,s,o)}}function Ti(a){var e;a.notifySelectionChange(),(e=a.emitSelectionChangeEvent)==null||e.call(a),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function Sc(a){var e,t,i;a.notifySelectionChange(),(e=a.emitSelectionChangeEvent)==null||e.call(a),(t=a.reloadClipThumbnailsIfNeeded)==null||t.call(a),(i=a.checkTrackDurationChange)==null||i.call(a),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function Cc(a,e,t=!1){if(!e||!t||a.type==="audio")return!1;const i=e.duration!==a.duration,r=e.startTimeAtSource!==a.startTimeAtSource||e.endTimeAtSource!==a.endTimeAtSource;return i||r}function vc(a,e){if(a.length===0)return!1;const t=Math.max(...a.map(i=>i.endTime));return e<t}function Tc(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 bc(a){const e=!a.id&&a.startTime>0;return{shouldJumpToTime:e,jumpTime:e?a.startTime:null,shouldSelectClip:!!a.id}}function Ii(a){var e;return a.applied?(a.isExecutingHistoryAction||(e=a.recordHistory)==null||e.call(a),a.applyEffects(),!0):!1}function wc(a){return Ii({applied:a.applied,isExecutingHistoryAction:a.isExecutingHistoryAction,recordHistory:()=>{var e;(e=a.recordMoveClipBetweenTracks)==null||e.call(a,a.clipId,a.sourceTrackId,a.targetTrackId,a.clipBefore,a.clipAfter,a.sourceTrackSnapshot,a.targetTrackSnapshot)},applyEffects:a.applyEffects})}function kc(a){var e;a.isExecutingHistoryAction||(e=a.recordSplitClip)==null||e.call(a,a.clip1,a.clip2),a.emitClipUpdated(a.clip1),a.emitClipAdded(a.clip2),a.applyEffects()}class xc{constructor(e){p(this,"container",null);p(this,"statusElement",null);p(this,"detailElement",null);p(this,"actionElement",null);p(this,"onRetry");this.onRetry=e}mount(e){this.container=e,this.container.className="timeline-preview-pending-overlay",this.container.style.position="absolute",this.container.style.inset="0",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="center",this.container.style.flexDirection="column",this.container.style.gap="8px",this.container.style.background=oi.background,this.container.style.color=oi.text,this.container.style.fontSize="13px",this.container.style.zIndex="2000";const t=document.createElement("div");t.className="timeline-preview-pending-overlay__status",t.style.fontWeight="600";const i=document.createElement("div");i.className="timeline-preview-pending-overlay__detail",i.style.opacity="0.88";const r=document.createElement("button");r.className="timeline-preview-pending-overlay__action",r.style.display="none",r.style.padding="6px 12px",r.style.border="0",r.style.borderRadius="6px",r.style.cursor="pointer",r.style.background=oi.actionBackground,r.style.color=oi.actionText,r.textContent="刷新重试",r.addEventListener("click",this.onRetry),this.container.appendChild(t),this.container.appendChild(i),this.container.appendChild(r),this.statusElement=t,this.detailElement=i,this.actionElement=r}update(e){if(!this.container||!this.statusElement||!this.detailElement||!this.actionElement)return;const{pendingState:t,runtimeState:i}=e;if(!t){this.container.style.display="none",this.actionElement.style.display="none";return}if(this.container.style.display="flex",t.errorMessage||i.phase==="failed"){this.statusElement.textContent="资源加载异常",this.detailElement.textContent=t.errorMessage||i.errorMessage||"资源加载异常,请刷新重试",this.actionElement.style.display="inline-flex";return}const r=t.loadingPending>0||i.loadingCount>0;this.statusElement.textContent=r?"资源加载中…":"正在缓冲预览…",this.detailElement.textContent=r?`目标时间 ${Math.round(t.targetTime)}ms,待加载资源 ${Math.max(t.loadingPending,i.loadingCount)} 个`:`目标时间 ${Math.round(t.targetTime)}ms,等待媒体可播放`,this.actionElement.style.display="none"}destroy(){var e,t;(e=this.actionElement)==null||e.removeEventListener("click",this.onRetry),(t=this.container)==null||t.remove(),this.container=null,this.statusElement=null,this.detailElement=null,this.actionElement=null}}const rr={x:.5,y:.5,scale:1},Pc=.1,_c=8;function nr(a,e){return typeof a=="number"&&Number.isFinite(a)?a:e}function Ac(a){return Math.min(_c,Math.max(Pc,a))}function ke(a){return{x:nr(a==null?void 0:a.x,rr.x),y:nr(a==null?void 0:a.y,rr.y),scale:Ac(nr(a==null?void 0:a.scale,rr.scale))}}function Nr(a,e,t=1e-4){const i=ke(a),r=ke(e);return Math.abs(i.x-r.x)<=t&&Math.abs(i.y-r.y)<=t&&Math.abs(i.scale-r.scale)<=t}function aa(a,e){if(a.width<=0||a.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const t=e.width>0?e.width:a.width,i=e.height>0?e.height:a.height,r=t/i,n=a.width/a.height;let s=a.width,o=a.height;r>n?o=s/r:s=o*r;const l=(a.width-s)/2,h=(a.height-o)/2;return{left:l,top:h,width:s,height:o,centerX:l+s/2,centerY:h+o/2}}function zn(a,e,t){const i=aa(a,e),r=ke(t),n=i.width*r.scale,s=i.height*r.scale,o=a.width*r.x,l=a.height*r.y;return{left:o-n/2,top:l-s/2,width:n,height:s,centerX:o,centerY:l}}function oa(a,e,t,i){const r=ke(a),n=i.width>0?i.width:1,s=i.height>0?i.height:1;return ke({x:r.x+e/n,y:r.y+t/s,scale:r.scale})}function Ic(a,e,t,i,r,n){const s=ke(n),o=Math.max(r.width/2,1),l=Math.max(r.height/2,1),h=Math.abs(t-a)/o,c=Math.abs(i-e)/l;return ke({x:s.x,y:s.y,scale:Math.max(h,c)})}function Vn(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}class Ec{constructor(e={}){p(this,"frameElement",null);p(this,"overlayElement",null);p(this,"boxElement",null);p(this,"handleElements",new Map);p(this,"handlePointerDownHandlers",new Map);p(this,"state",null);p(this,"interaction",null);p(this,"callbacks");p(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});p(this,"boundPointerUp",()=>{this.finishInteraction(!0)});p(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});p(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});p(this,"handleMovePointerDown",e=>{var i,r;const t=e;(t.button??0)!==0||!this.state||((i=t.preventDefault)==null||i.call(t),(r=t.stopPropagation)==null||r.call(t),this.interaction={clipId:this.state.clipId,mode:"move",pointerStart:this.toLocalPoint(t),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing"},this.setGlobalCursor("grabbing"),this.bindDocumentListeners())});this.callbacks=e}attach(e){if(this.frameElement===e&&this.overlayElement){this.render();return}this.detach(),this.frameElement=e;const t=document.createElement("div");t.className="timeline-preview-transform-overlay",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="3000";const i=document.createElement("div");i.className="timeline-preview-transform-box",i.style.position="absolute",i.style.display="none",i.style.boxSizing="border-box",i.style.border=`1px solid ${Vi.border}`,i.style.cursor="grab",i.style.pointerEvents="auto",i.style.userSelect="none",i.addEventListener("pointerdown",this.handleMovePointerDown),t.appendChild(i),this.overlayElement=t,this.boxElement=i,this.createHandle("top-left","nwse-resize"),this.createHandle("top-right","nesw-resize"),this.createHandle("bottom-right","nwse-resize"),this.createHandle("bottom-left","nesw-resize"),e.appendChild(t),this.render()}detach(){var e,t;this.finishInteraction(!1),(e=this.boxElement)==null||e.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,r)=>{const n=this.handlePointerDownHandlers.get(r);n&&i.removeEventListener("pointerdown",n)}),this.handleElements.clear(),this.handlePointerDownHandlers.clear(),(t=this.overlayElement)==null||t.remove(),this.overlayElement=null,this.boxElement=null,this.frameElement=null,this.state=null}sync(e){if(!e){this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==e.clipId&&this.finishInteraction(!1),this.state=e,this.render()}createHandle(e,t){if(!this.boxElement)return;const i=document.createElement("div");i.className=`timeline-preview-transform-handle timeline-preview-transform-handle--${e}`,i.style.position="absolute",i.style.width="10px",i.style.height="10px",i.style.border=`1px solid ${Vi.border}`,i.style.background=Vi.handleBackground,i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=t,i.style.boxSizing="border-box",i.style.transform="translate(-50%, -50%)";const r=this.getHandlePointerDown(e);i.addEventListener("pointerdown",r),this.handleElements.set(e,i),this.handlePointerDownHandlers.set(e,r),this.boxElement.appendChild(i)}getHandlePointerDown(e){return t=>{var n,s;const i=t;if((i.button??0)!==0||!this.state)return;(n=i.preventDefault)==null||n.call(i),(s=i.stopPropagation)==null||s.call(i);const r=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize";this.interaction={clipId:this.state.clipId,mode:"scale",pointerStart:this.toLocalPoint(i),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:r},this.setGlobalCursor(r),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,r,n,s;const e=this.getDocument();e&&((t=e.addEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.addEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.addEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(s=(n=globalThis.window)==null?void 0:n.addEventListener)==null||s.call(n,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,r,n,s;const e=this.getDocument();e&&((t=e.removeEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.removeEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.removeEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(s=(n=globalThis.window)==null?void 0:n.removeEventListener)==null||s.call(n,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var n,s,o;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const t=e;(n=t.preventDefault)==null||n.call(t);const i=this.toLocalPoint(t);let r=this.interaction.startTransform;if(this.interaction.mode==="move")r=oa(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;r=Ic(l,h,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!Nr(this.interaction.startTransform,r),(o=(s=this.callbacks).onPreviewTransformChange)==null||o.call(s,this.interaction.clipId,r)}finishInteraction(e){var i,r,n,s;const t=this.interaction;if(!t){this.setGlobalCursor(null),this.unbindDocumentListeners();return}e&&t.changed&&((r=(i=this.callbacks).onPreviewTransformCommit)==null||r.call(i,t.clipId,t.nextTransform)),(s=(n=this.callbacks).onPreviewTransformChange)==null||s.call(n,t.clipId,null),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners()}render(){if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none");return}const{displayRect:e}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${e.left}px`,this.boxElement.style.top=`${e.top}px`,this.boxElement.style.width=`${e.width}px`,this.boxElement.style.height=`${e.height}px`,this.positionHandle("top-left",0,0),this.positionHandle("top-right",e.width,0),this.positionHandle("bottom-right",e.width,e.height),this.positionHandle("bottom-left",0,e.height)}positionHandle(e,t,i){const r=this.handleElements.get(e);r&&(r.style.left=`${t}px`,r.style.top=`${i}px`)}toLocalPoint(e){const t=this.getFrameBounds();return{x:(e.clientX??0)-t.left,y:(e.clientY??0)-t.top}}getFrameBounds(){var t,i;if(!this.frameElement)return{left:0,top:0,width:0,height:0};const e=(i=(t=this.frameElement).getBoundingClientRect)==null?void 0:i.call(t);return e&&Number.isFinite(e.width)&&Number.isFinite(e.height)?{left:e.left,top:e.top,width:e.width,height:e.height}:{left:Vn(this.frameElement.style.left),top:Vn(this.frameElement.style.top),width:this.frameElement.clientWidth,height:this.frameElement.clientHeight}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}setGlobalCursor(e){var i;const t=(i=this.getDocument())==null?void 0:i.body;t&&(t.style.cursor=e||"")}}const Lc=0,Rc=2,Mc=250,Dc=2,Oc=120,Un="Arial, sans-serif";function Bc(a,e){const t=Math.max(0,Math.round(a));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let n=-t;n<=t;n+=1)n===0&&r===0||i.push(`${n}px ${r}px 0 ${e}`);return i.join(", ")}function la(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function sr(a){return`"${la(a)}"`}function Gc(a){return Lr(a,Ir)}function Hc(a,e){return!Ct(a.mode)||!e?a:{mode:Ee.mode,width:e.width,height:e.height}}function mt(a){return a.getAttribute("src")||a.currentSrc||a.src||""}function Wn(a){return typeof HTMLVideoElement<"u"?a instanceof HTMLVideoElement:a.tagName==="VIDEO"}function ut(a){try{a.load()}catch{}}function pt(a){try{a.pause()}catch{}}function Fc(a){var e;try{const t=a.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function Yn(a,e){try{a.currentTime=Math.max(0,e)}catch{}}function bi(a,e){var i;const t=(i=a==null?void 0:a.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function Xn(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}function $c(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function ce(a){return{tsMs:$c(),currentTime:Number.isFinite(a.currentTime)?Number(a.currentTime.toFixed(3)):null,currentSrc:mt(a)||null,readyState:typeof a.readyState=="number"?a.readyState:null,networkState:typeof a.networkState=="number"?a.networkState:null,paused:typeof a.paused=="boolean"?a.paused:null,ended:typeof a.ended=="boolean"?a.ended:null}}function Nc(a){return`${a.clip.id}:${Math.floor(a.mediaTime/Mc)}`}function zc(a,e){const t=a.indexOf("#"),i=t>=0?a.slice(t):"",r=t>=0?a.slice(0,t):a,n=r.indexOf("?"),s=n>=0?r.slice(0,n):r,o=n>=0?r.slice(n+1):"",l=new URLSearchParams(o);l.set("trackid",e);const h=l.toString();return`${s}${h?`?${h}`:""}${i}`}function Je(a){return typeof(a==null?void 0:a.then)=="function"}function Vc(a,e){var t;return((t=a.entry)==null?void 0:t.clip.id)===e}function Uc(a,e){const t=a.activeClips.filter(o=>o.trackType!=="text"),i=a.nextClips.filter(o=>o.trackType!=="text"),r=new Map(t.map(o=>[o.trackId,o])),n=new Map(i.map(o=>[o.trackId,o])),s=new Map;return e.forEach(o=>{s.set(o.trackId,{kind:o.kind,order:o.order})}),t.forEach(o=>{s.set(o.trackId,{kind:o.trackType,order:o.trackOrder})}),i.forEach(o=>{s.set(o.trackId,{kind:o.trackType,order:o.trackOrder})}),Array.from(s.entries()).map(([o,l])=>{const h=r.get(o)||null,c=n.get(o)||null;return{trackId:o,kind:l.kind,order:l.order,current:{role:"current",entry:h,playState:a.playState,speed:a.speed,visible:!!(h!=null&&h.hasVisual),zIndex:h?1e3-h.trackOrder:0,syncRequestId:a.syncRequestId},preload:{role:"preload",entry:c,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:a.syncRequestId}}}).sort((o,l)=>o.order-l.order)}class Wc{constructor(e={},t={}){p(this,"container",null);p(this,"rootElement",null);p(this,"frameElement",null);p(this,"textOverlayRoot",null);p(this,"pendingOverlayElement",null);p(this,"pendingOverlayRenderer");p(this,"resizeObserver",null);p(this,"trackSlots",new Map);p(this,"textPreviewEntries",new Map);p(this,"audioContext",null);p(this,"masterGainNode",null);p(this,"loadingCount",0);p(this,"isBuffering",!1);p(this,"bufferingVisibleTimeoutId",null);p(this,"lastRuntimeSignature",null);p(this,"lastRuntimeState",{phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]});p(this,"lastSettledSyncRequestId",null);p(this,"primarySelectedClipId",null);p(this,"transientVisualTransform",null);p(this,"textPreviewDragState",null);p(this,"textPreviewFontStyleElement",null);p(this,"textPreviewFontSignature",null);p(this,"textPreviewFontLoadState","idle");p(this,"textPreviewFontLoadToken",0);p(this,"callbacks");p(this,"dependencies");p(this,"transformOverlay");p(this,"boundTextPreviewPointerMove",e=>{this.handleTextPreviewPointerMove(e)});p(this,"boundTextPreviewPointerUp",()=>{this.finishTextPreviewDrag(!0)});p(this,"boundTextPreviewVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishTextPreviewDrag(!1)});p(this,"boundTextPreviewWindowBlur",()=>{this.finishTextPreviewDrag(!1)});p(this,"requestedAspectRatio",{...Ee});p(this,"resolvedAutoAspectRatio",null);p(this,"aspectRatioProbe",null);p(this,"aspectRatioProbeSrc",null);p(this,"aspectRatioProbeResolveToken",0);p(this,"isAspectRatioProbeLoading",!1);p(this,"pendingState",null);p(this,"activeSyncRequestId");p(this,"isSyncProjecting",!1);this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new xc(()=>{var i,r;(r=(i=this.callbacks).onPendingPreviewRetry)==null||r.call(i)}),this.transformOverlay=new Ec({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,r)=>{var n,s;(s=(n=this.callbacks).onVisualTransformCommit)==null||s.call(n,i,r)}})}logLoadTrace(e,t,i){ih.append({level:e,event:t,data:{syncRequestId:this.activeSyncRequestId??null,...i}})}buildSlotTraceData(e,t){var i;return{trackId:e.trackId,role:e.role,kind:e.kind,clipId:((i=e.entry)==null?void 0:i.clip.id)??null,desiredSource:e.desiredSource,actualSource:mt(e.element)||null,phase:e.phase,retryCount:e.retryCount,...t}}hasPreview(){return!!this.container}attach(e){if(this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e;const t=document.createElement("div");t.className=this.dependencies.rootClassName??"timeline-preview-root",t.style.position="relative",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden";const i=document.createElement("div");i.className=this.dependencies.frameClassName??"timeline-preview-frame",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.overflow="hidden",i.style.background=_.black,t.appendChild(i);const r=document.createElement("div");r.className="timeline-preview-text-layer",r.style.position="absolute",r.style.inset="0",r.style.pointerEvents="none",r.style.zIndex="2000",i.appendChild(r);const n=document.createElement("div");t.appendChild(n),this.pendingOverlayRenderer.mount(n),e.appendChild(t),this.rootElement=t,this.frameElement=i,this.textOverlayRoot=r,this.pendingOverlayElement=n,this.transformOverlay.attach(i),this.ensureTextPreviewFontReady(),this.logLoadTrace("info","preview.attach",{containerWidth:e.clientWidth,containerHeight:e.clientHeight}),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(e)),this.updateFrameLayout(),this.refreshPendingOverlay(),this.refreshRuntimeState()}detach(){var e,t,i,r,n,s;this.logLoadTrace("info","preview.detach",{slotCount:this.trackSlots.size}),(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,this.transformOverlay.detach(),this.finishTextPreviewDrag(!1),this.pendingOverlayRenderer.destroy();for(const o of this.trackSlots.values())this.destroySlot(o.current),this.destroySlot(o.preload);this.trackSlots.clear(),this.clearTextPreviewEntries(),this.resetTextPreviewFontState(),this.aspectRatioProbe&&(pt(this.aspectRatioProbe),this.aspectRatioProbe.src="",ut(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.aspectRatioProbeResolveToken+=1,this.isAspectRatioProbeLoading=!1,this.audioContext&&((n=(i=(t=this.audioContext).close)==null?void 0:(r=i.call(t)).catch)==null||n.call(r,()=>{}),this.audioContext=null,this.masterGainNode=null),(s=this.rootElement)==null||s.remove(),this.rootElement=null,this.frameElement=null,this.textOverlayRoot=null,this.pendingOverlayElement=null,this.container=null,this.primarySelectedClipId=null,this.transientVisualTransform=null,this.pendingState=null,this.activeSyncRequestId=void 0,this.isSyncProjecting=!1,this.loadingCount=0,this.isBuffering=!1,this.clearBufferingVisibleTimeout(),this.lastRuntimeSignature=null,this.lastSettledSyncRequestId=null,this.lastRuntimeState={phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]},this.refreshPendingOverlay(),this.refreshRuntimeState()}setPendingState(e){this.pendingState=e,this.refreshPendingOverlay()}sync(e){if(!this.rootElement||!this.frameElement)return;this.primarySelectedClipId=e.primarySelectedClipId??null,this.activeSyncRequestId=e.syncRequestId,this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.textPreviewDragState&&this.textPreviewDragState.clipId!==this.primarySelectedClipId&&this.finishTextPreviewDrag(!1),this.maybeResolveAutoAspectRatio(e.autoAspectRatioClip),this.syncTextPreviewEntries(e.activeClips.filter(s=>s.trackType==="text"));const t=Array.from(this.trackSlots.entries()).map(([s,o],l)=>{var h,c;return{trackId:s,kind:o.current.kind,order:((h=o.current.entry)==null?void 0:h.trackOrder)??((c=o.preload.entry)==null?void 0:c.trackOrder)??1e4+l}}),n=Uc(e,t).map(s=>this.applyTrackPlan(s)).filter(s=>Je(s));if(this.isSyncProjecting=n.length>0,this.refreshVisualLayout(),this.refreshRuntimeState(),n.length===0){this.refreshVisualLayout(),this.refreshRuntimeState();return}Promise.all(n).then(()=>{this.activeSyncRequestId===e.syncRequestId&&(this.isSyncProjecting=!1,this.refreshVisualLayout(),this.refreshRuntimeState())}).catch(s=>{this.logLoadTrace("error","preview.sync.failed",{syncRequestId:e.syncRequestId??null,error:s}),M.warn("TimelinePreviewSession","preview sync failed",{error:s,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=$e(e),this.updateFrameLayout()}getAspectRatio(){return Hc(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}createMediaElement(e,t){const i=this.dependencies.createMediaElement,r=i?i(e,t):document.createElement(e==="video"?"video":"audio");return r.preload=t==="preload"?"auto":"metadata",r.crossOrigin="anonymous",r.loop=!1,r.controls=!1,Wn(r)?(r.playsInline=!0,r.disablePictureInPicture=!0,r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.objectFit="fill",r.style.background=_.black,r.style.pointerEvents="none"):r.style.display="none",r}createSlot(e,t,i){var T,w;const r=this.createMediaElement(t,i),n=t==="video"?document.createElement("div"):null;if(n){const b=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";n.className=`${b} timeline-preview-slot--${e} timeline-preview-slot--${i}`,n.style.position="absolute",n.style.overflow="hidden",n.style.background=_.black,n.style.pointerEvents="none",n.style.display="none",n.appendChild(r),(T=this.frameElement)==null||T.appendChild(n)}const s={role:i,trackId:e,kind:t,wrapper:n,element:r,entry:null,desiredSource:null,requestedPlayState:"paused",isActive:!1,isLoading:!1,isBuffering:!1,isSeeking:!1,phase:"idle",errorMessage:null,retryCount:0,recoveryKey:null,sourceNode:null,gainNode:null,audioRoutingFailed:!1,consecutiveStalledCount:0,forceRecover:!1,resolveToken:0,applyToken:0,cleanup:[]},o=()=>{s.isLoading=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=null,s.consecutiveStalledCount=0,s.entry?s.phase=s.isActive?"active":"primed":s.phase="idle",this.tryResolveAutoAspectRatioFromSlot(s),this.refreshVisualLayout(),this.refreshRuntimeState()},l=()=>{var b;if(!s.entry){s.isLoading=!1,s.phase="idle",this.refreshRuntimeState();return}this.logLoadTrace("info","media.loadstart",this.buildSlotTraceData(s,ce(s.element))),M.debug("TimelinePreviewSession","media event: loadstart",{trackId:s.trackId,role:s.role,clipId:((b=s.entry)==null?void 0:b.clip.id)??null,phase:s.phase,...ce(s.element)}),s.isLoading=!0,s.phase!=="recovering"&&(s.phase="binding"),this.refreshRuntimeState()},h=b=>{var E;this.logLoadTrace("info",`media.${b.type}`,this.buildSlotTraceData(s,ce(s.element))),M.debug("TimelinePreviewSession","media event: ready",{trackId:s.trackId,role:s.role,clipId:((E=s.entry)==null?void 0:E.clip.id)??null,eventType:b.type,phase:s.phase,...ce(s.element)}),o()},c=()=>{var b;this.logLoadTrace("warn","media.waiting",this.buildSlotTraceData(s,{active:s.isActive,...ce(s.element)})),M.debug("TimelinePreviewSession","media event: waiting",{trackId:s.trackId,role:s.role,clipId:((b=s.entry)==null?void 0:b.clip.id)??null,active:s.isActive,phase:s.phase,...ce(s.element)}),s.isBuffering=s.isActive&&!s.element.paused,this.refreshRuntimeState()},d=()=>{var b;this.logLoadTrace("warn","media.stalled",this.buildSlotTraceData(s,{active:s.isActive,...ce(s.element)})),M.debug("TimelinePreviewSession","media event: stalled",{trackId:s.trackId,role:s.role,clipId:((b=s.entry)==null?void 0:b.clip.id)??null,active:s.isActive,phase:s.phase,...ce(s.element)}),s.isBuffering=s.isActive&&!s.element.paused,s.consecutiveStalledCount+=1,this.refreshRuntimeState(),s.isActive&&s.consecutiveStalledCount>=Dc&&this.recoverSlot(s,"stalled")},u=()=>{var b;if(!s.entry){s.isSeeking=!1,s.phase="idle",this.refreshRuntimeState();return}this.logLoadTrace("debug","media.seeking",this.buildSlotTraceData(s,{active:s.isActive,...ce(s.element)})),M.debug("TimelinePreviewSession","media event: seeking",{trackId:s.trackId,role:s.role,clipId:((b=s.entry)==null?void 0:b.clip.id)??null,active:s.isActive,phase:s.phase,...ce(s.element)}),s.isSeeking=!0,this.refreshRuntimeState()},g=()=>{var b;this.logLoadTrace("debug","media.seeked",this.buildSlotTraceData(s,ce(s.element))),M.debug("TimelinePreviewSession","media event: seeked",{trackId:s.trackId,role:s.role,clipId:((b=s.entry)==null?void 0:b.clip.id)??null,phase:s.phase,...ce(s.element)}),s.isSeeking=!1,s.isBuffering=!1,s.entry&&s.phase!=="failed"&&(s.phase=s.isActive?"active":"primed"),this.refreshRuntimeState()},f=b=>{var E;this.logLoadTrace(b==="error"?"error":"warn",`media.${b}`,this.buildSlotTraceData(s,{error:s.element.error?{code:s.element.error.code,message:s.element.error.message}:null,...ce(s.element)})),M.warn("TimelinePreviewSession",`media event: ${b}`,{trackId:s.trackId,role:s.role,clipId:((E=s.entry)==null?void 0:E.clip.id)??null,phase:s.phase,error:s.element.error?{code:s.element.error.code,message:s.element.error.message}:null,...ce(s.element)}),s.forceRecover=!0,s.isLoading=!1,s.isSeeking=!1,s.isBuffering=!1,this.refreshRuntimeState(),this.recoverSlot(s,b)},y=()=>f("abort"),v=()=>f("emptied"),C=()=>f("error");return r.addEventListener("loadstart",l),r.addEventListener("loadedmetadata",h),r.addEventListener("canplay",h),r.addEventListener("playing",h),r.addEventListener("waiting",c),r.addEventListener("stalled",d),r.addEventListener("seeking",u),r.addEventListener("seeked",g),r.addEventListener("abort",y),r.addEventListener("emptied",v),r.addEventListener("error",C),s.cleanup.push(()=>r.removeEventListener("loadstart",l),()=>r.removeEventListener("loadedmetadata",h),()=>r.removeEventListener("canplay",h),()=>r.removeEventListener("playing",h),()=>r.removeEventListener("waiting",c),()=>r.removeEventListener("stalled",d),()=>r.removeEventListener("seeking",u),()=>r.removeEventListener("seeked",g),()=>r.removeEventListener("abort",y),()=>r.removeEventListener("emptied",v),()=>r.removeEventListener("error",C)),t==="audio"&&((w=this.rootElement)==null||w.appendChild(r)),s}destroySlot(e){var t,i,r,n,s;e.resolveToken+=1,e.applyToken+=1,e.cleanup.forEach(o=>o()),pt(e.element),e.element.removeAttribute("src"),ut(e.element),(i=(t=e.gainNode)==null?void 0:t.disconnect)==null||i.call(t),(n=(r=e.sourceNode)==null?void 0:r.disconnect)==null||n.call(r),e.gainNode=null,e.sourceNode=null,(s=e.wrapper)==null||s.remove(),e.element.remove()}getTrackSlots(e,t){const i=this.trackSlots.get(e);if(i&&i.current.kind===t&&i.preload.kind===t)return i;i&&(this.destroySlot(i.current),this.destroySlot(i.preload),this.trackSlots.delete(e));const r={current:this.createSlot(e,t,"current"),preload:this.createSlot(e,t,"preload")};return this.trackSlots.set(e,r),r}swapTrackSlots(e){const t=this.trackSlots.get(e);t&&(t.current.role="preload",t.preload.role="current",this.trackSlots.set(e,{current:t.preload,preload:t.current}))}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);e.current.entry&&Vc(t.preload,e.current.entry.clip.id)&&(this.swapTrackSlots(e.trackId),t=this.getTrackSlots(e.trackId,e.kind));const i=this.applySlotTarget(t.current,e.current),r=this.applySlotTarget(t.preload,e.preload);if(Je(i)||Je(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=mt(e.element)||null;if(e.entry=t.entry,e.requestedPlayState=t.playState,e.isActive=t.role==="current"&&!!t.entry,e.errorMessage=t.entry?e.errorMessage:null,e.isBuffering=t.entry?e.isBuffering:!1,e.isSeeking=t.entry?e.isSeeking:!1,e.consecutiveStalledCount=t.entry?e.consecutiveStalledCount:0,!t.entry){(r||n)&&this.logLoadTrace("info","slot.cleared",this.buildSlotTraceData(e,{previousClipId:(r==null?void 0:r.clip.id)??null,previousSource:n})),pt(e.element),e.desiredSource=null,e.errorMessage=null,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.retryCount=0,e.recoveryKey=null,e.forceRecover=!1,e.element.removeAttribute("src"),ut(e.element),e.phase="idle",this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}const s=this.resolveDesiredSource(e,t.entry,i);if(Je(s))return s.then(o=>{if(!(!o||!this.isCurrentRequest(e,i,t.entry))){if(e.desiredSource=o,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,o))return Promise.resolve(this.recoverSlot(e,"reconcile",t,i)).then(()=>{});e.forceRecover=!1,e.retryCount=0,e.recoveryKey=null,this.applyResolvedSlotState(e,t)}});if(!(!s||!this.isCurrentRequest(e,i,t.entry))){if(e.desiredSource=s,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,s))return this.recoverSlot(e,"reconcile",t,i);e.forceRecover=!1,e.retryCount=0,e.recoveryKey=null,this.applyResolvedSlotState(e,t)}}resolveDesiredSource(e,t,i){const r=this.dependencies.previewSourceResolver,n=this.dependencies.sourceMediaRegistry;if(!r)return this.decorateSlotSourceUrl(e,t.clip.src);try{const s=n?n.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>r(t.clip)):r(t.clip);if(Je(s)){e.resolveToken+=1;const o=e.resolveToken;return e.phase="binding",e.isLoading=!0,this.logLoadTrace("info","source.resolve.pending",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,requestToken:i,resolveToken:o})),this.refreshRuntimeState(),s.then(l=>o!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:l?(this.logLoadTrace("info","source.resolve.resolved",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,resolvedUrl:l.url,mimeType:l.mimeType,mediaKind:l.kind})),this.decorateSlotSourceUrl(e,l.url)):(this.logLoadTrace("warn","source.resolve.missing",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(l=>(this.logLoadTrace("error","source.resolve.failed",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,error:l})),M.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:l}),this.failSlot(e,t,"预览源解析失败"),null))}return s?(this.logLoadTrace("info","source.resolve.resolved",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,resolvedUrl:s.url,mimeType:s.mimeType,mediaKind:s.kind})),this.decorateSlotSourceUrl(e,s.url)):(this.logLoadTrace("warn","source.resolve.missing",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)}catch(s){return this.logLoadTrace("error","source.resolve.failed",this.buildSlotTraceData(e,{clipId:t.clip.id,source:t.clip.src,error:s})),M.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:s}),this.failSlot(e,t,"预览源解析失败"),null}}decorateSlotSourceUrl(e,t){return e.kind!=="video"||!t?t:zc(t,e.trackId)}slotNeedsRecovery(e,t){const i=mt(e.element);return!!(e.forceRecover||!i||i!==t||(typeof e.element.networkState=="number"?e.element.networkState:null)===Lc)}recoverSlot(e,t,i,r){const n=i??(e.entry?{role:e.role,entry:e.entry,playState:e.requestedPlayState,speed:e.isActive&&e.element.playbackRate||1,visible:e.isActive&&!!e.entry.hasVisual,zIndex:e.entry?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null);if(!e.entry||!n||r!==void 0&&!this.isCurrentRequest(e,r,e.entry))return;const s=e.desiredSource??this.resolveDesiredSource(e,e.entry,e.applyToken);if(Je(s))return s.then(o=>{o&&this.finishSlotRecovery(e,t,n,o,r)});s&&this.finishSlotRecovery(e,t,n,s,r)}finishSlotRecovery(e,t,i,r,n){if(!e.entry)return;const s=Nc(e.entry);if(e.recoveryKey===s){if(e.retryCount>=Rc){this.failSlot(e,e.entry,"媒体恢复失败,请刷新重试");return}e.retryCount+=1}else e.recoveryKey=s,e.retryCount=1;e.phase="recovering",e.errorMessage=null,e.forceRecover=!1,e.isLoading=!0,e.isBuffering=e.isActive&&i.playState==="playing",e.isSeeking=!1,e.consecutiveStalledCount=0,this.refreshRuntimeState(),this.logLoadTrace(t==="reconcile"?"info":"warn","slot.recover",this.buildSlotTraceData(e,{reason:t,desiredSource:r,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState})),M.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:r,...ce(e.element)});const l=!!mt(e.element)||t!=="reconcile"||e.retryCount>1;pt(e.element),l&&(e.element.removeAttribute("src"),ut(e.element)),e.element.setAttribute("src",r),ut(e.element),this.logLoadTrace("info","source.assigned",this.buildSlotTraceData(e,{reason:t,desiredSource:r,hardReset:l})),!(n!==void 0&&!this.isCurrentRequest(e,n,e.entry))&&this.applyResolvedSlotState(e,i)}applyResolvedSlotState(e,t){t.entry&&(e.errorMessage=null,e.element.playbackRate=t.role==="current"?t.speed:1,t.role==="current"?this.syncCurrentSlot(e,t.entry,t.speed,t.playState):this.preparePreloadSlot(e,t.entry),!e.isLoading&&!e.isSeeking&&e.phase!=="failed"&&(e.phase=e.isActive?"active":"primed"),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState())}isCurrentRequest(e,t,i){var r;return e.applyToken===t&&((r=e.entry)==null?void 0:r.clip.id)===i.clip.id}failSlot(e,t,i){e.phase="failed",e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.errorMessage=i,e.forceRecover=!1,this.logLoadTrace("error","slot.failed",this.buildSlotTraceData(e,{clipId:t.clip.id,errorMessage:i})),M.warn("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,...ce(e.element)}),this.refreshRuntimeState()}configureAudioRouting(e,t){const i=Math.max(0,Math.min(1,t.clip.volume??1)),r=t.muted?0:i;if(!t.hasAudio){e.element.muted=!0,e.element.volume=0;return}const n=this.getAudioContext();if(!n||e.audioRoutingFailed){e.element.muted=t.muted,e.element.volume=r;return}if(!e.sourceNode||!e.gainNode)try{e.sourceNode=n.createMediaElementSource(e.element),e.gainNode=n.createGain(),e.sourceNode.connect(e.gainNode),e.gainNode.connect(this.getMasterGainNode(n))}catch{e.audioRoutingFailed=!0,e.element.muted=t.muted,e.element.volume=r;return}e.element.muted=!1,e.element.volume=1,e.gainNode.gain.value=r}syncCurrentSlot(e,t,i,r){e.isActive=!0,e.entry=t,e.element.playbackRate=i;const n=t.mediaTime/1e3,s=Math.max(.1,i*.15);Math.abs(e.element.currentTime-n)>s&&(M.debug("TimelinePreviewSession","seek current slot",{trackId:e.trackId,role:e.role,clipId:t.clip.id,playState:r,speed:i,fromSeconds:Number(e.element.currentTime.toFixed(3)),toSeconds:Number(n.toFixed(3)),deltaSeconds:Number(Math.abs(e.element.currentTime-n).toFixed(3)),thresholdSeconds:Number(s.toFixed(3)),...ce(e.element)}),e.isSeeking=!0,Yn(e.element,n)),r==="playing"?(this.resumeAudioContext(),Fc(e.element)):pt(e.element),this.setSlotVisible(e,t.hasVisual,1e3-t.trackOrder)}preparePreloadSlot(e,t){e.isActive=!1,e.isBuffering=!1,e.isSeeking=!1,e.entry=t,e.element.playbackRate=1,M.debug("TimelinePreviewSession","prime preload slot seek",{trackId:e.trackId,role:e.role,clipId:t.clip.id,toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3)),...ce(e.element)}),Yn(e.element,t.clip.startTimeAtSource/1e3),pt(e.element),this.setSlotVisible(e,!1,0)}setSlotVisible(e,t,i){if(e.kind!=="video"||!e.wrapper){e.element.style.display="none";return}e.wrapper.style.display=t?"block":"none",e.wrapper.style.zIndex=String(i),e.wrapper.style.pointerEvents="none",e.element.style.display=t?"block":"none",e.element.style.zIndex=String(i)}getAudioContext(){if(this.audioContext)return this.audioContext;const e=this.dependencies.createAudioContext;if(e)return this.audioContext=e(),this.audioContext;if(typeof window>"u")return null;const t=window.AudioContext||window.webkitAudioContext;return t?(this.audioContext=new t,this.audioContext):null}getMasterGainNode(e){if(this.masterGainNode)return this.masterGainNode;const t=e.createGain();return t.gain.value=1,t.connect(e.destination),this.masterGainNode=t,t}resumeAudioContext(){var e,t,i,r;!this.audioContext||this.audioContext.state!=="suspended"||(r=(t=(e=this.audioContext).resume)==null?void 0:(i=t.call(e)).catch)==null||r.call(i,()=>{})}updateFrameLayout(){if(!this.container||!this.frameElement)return;const{width:e,height:t}=this.getAspectRatio(),i=this.container.clientWidth,r=this.container.clientHeight;if(i<=0||r<=0||e<=0||t<=0)return;const n=e/t,s=i/r;let o=i,l=r;n>s?l=i/n:o=r*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=`${(r-l)/2}px`,this.refreshVisualLayout()}maybeResolveAutoAspectRatio(e){if(!Ct(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=bi(e,"sys_width"),i=bi(e,"sys_height");if(t&&i){this.handleResolvedAutoAspectRatio(t,i);return}if(this.aspectRatioProbeSrc===e.clip.id)return;const r=++this.aspectRatioProbeResolveToken;(async()=>{const s=await this.resolveAspectRatioProbeSource(e,r);if(!s||r!==this.aspectRatioProbeResolveToken)return;const o=this.getAspectRatioProbe();this.aspectRatioProbeSrc=e.clip.id,this.isAspectRatioProbeLoading=!0,this.logLoadTrace("info","aspect-ratio.probe.start",{clipId:e.clip.id,source:s}),this.refreshRuntimeState(),o.crossOrigin="anonymous",o.preload="metadata",o.muted=!0,o.src=s,ut(o)})().catch(()=>{})}async resolveAspectRatioProbeSource(e,t){const i=this.dependencies.previewSourceResolver,r=this.dependencies.sourceMediaRegistry;if(!i)return e.clip.src;const n=r?r.getPreviewSource(this.buildPreviewSourceCacheKey(e.clip),()=>i(e.clip)):i(e.clip);if(!Je(n))return(n==null?void 0:n.url)??null;this.isAspectRatioProbeLoading=!0,this.refreshRuntimeState();const s=await n;return t!==this.aspectRatioProbeResolveToken?null:(s==null?void 0:s.url)??null}buildPreviewSourceCacheKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src}getAspectRatioProbe(){var r,n;if(this.aspectRatioProbe)return this.aspectRatioProbe;const e=((n=(r=this.dependencies).createAspectRatioProbe)==null?void 0:n.call(r))||document.createElement("video"),t=()=>{this.isAspectRatioProbeLoading=!1,this.logLoadTrace("info","aspect-ratio.probe.loadedmetadata",{clipId:this.aspectRatioProbeSrc,videoWidth:e.videoWidth,videoHeight:e.videoHeight}),this.refreshRuntimeState(),e.videoWidth>0&&e.videoHeight>0&&this.handleResolvedAutoAspectRatio(e.videoWidth,e.videoHeight)},i=()=>{this.isAspectRatioProbeLoading=!1,this.logLoadTrace("warn","aspect-ratio.probe.error",{clipId:this.aspectRatioProbeSrc,currentSrc:e.currentSrc||e.src||null}),this.refreshRuntimeState()};return e.addEventListener("loadedmetadata",t),e.addEventListener("error",i),this.aspectRatioProbe=e,e}tryResolveAutoAspectRatioFromSlot(e){if(!Ct(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const t=e.element;t.videoWidth>0&&t.videoHeight>0&&this.handleResolvedAutoAspectRatio(t.videoWidth,t.videoHeight)}handleResolvedAutoAspectRatio(e,t){var i,r;e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),Ct(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var y,v,C,T,w,b,E;const e=[];let t=this.isAspectRatioProbeLoading?1:0,i=!1,r=null,n=!1,s=!1,o=!1,l=!1,h=!1,c=!1;for(const{current:x,preload:O}of this.trackSlots.values())for(const k of[x,O]){const L=mt(k.element)||null;e.push({trackId:k.trackId,role:k.role,kind:k.kind,clipId:((y=k.entry)==null?void 0:y.clip.id)??null,desiredSource:k.desiredSource,actualSource:L,phase:k.phase,retryCount:k.retryCount,errorMessage:k.errorMessage}),k.phase!=="idle"&&(n=!0),k.entry&&k.phase!=="idle"&&k.phase!=="failed"&&(o=!0),(k.isLoading||k.phase==="binding"||k.phase==="recovering")&&(t+=1),k.isBuffering&&(h=!0),k.phase==="failed"&&(s=!0),k.phase==="failed"&&!r&&(r=k.errorMessage||"资源加载异常,请刷新重试"),k.isActive&&k.entry&&(k.isSeeking||k.phase!=="active"&&k.phase!=="failed")&&(l=!0),k.role==="current"&&k.isActive&&k.entry&&k.phase==="active"&&!k.isLoading&&!k.isSeeking&&!k.isBuffering&&(c=!0)}i=h&&!c;let d="idle";this.activeSyncRequestId!==void 0&&this.isSyncProjecting?d="awaiting-sync":s&&!o?d="failed":t>0||i||l?d="awaiting-media":n&&(d="ready"),d!=="failed"&&(r=null),this.loadingCount!==t&&(this.loadingCount=t,(C=(v=this.callbacks).onSourceLoadingChange)==null||C.call(v,t)),this.syncVisibleBufferingState(i);const u={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:d,loadingCount:t,isBuffering:i,errorMessage:r,slots:e},g=this.lastRuntimeState,f=JSON.stringify(u);f!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=f,this.lastRuntimeState=u,(g.phase!==u.phase||g.loadingCount!==u.loadingCount||g.isBuffering!==u.isBuffering||g.errorMessage!==u.errorMessage)&&this.logLoadTrace(u.phase==="failed"?"error":"info","runtime.state",{previousPhase:g.phase,phase:u.phase,loadingCount:u.loadingCount,isBuffering:u.isBuffering,errorMessage:u.errorMessage,slots:u.slots.map(x=>({trackId:x.trackId,role:x.role,clipId:x.clipId,phase:x.phase,retryCount:x.retryCount}))}),(w=(T=this.callbacks).onRuntimeStateChange)==null||w.call(T,u)),(d==="ready"||d==="failed")&&u.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==u.syncRequestId&&(this.lastSettledSyncRequestId=u.syncRequestId,(E=(b=this.callbacks).onSyncProcessed)==null||E.call(b,u.syncRequestId)),this.refreshPendingOverlay()}syncVisibleBufferingState(e){var t,i;if(e){if(this.isBuffering||this.bufferingVisibleTimeoutId)return;this.bufferingVisibleTimeoutId=setTimeout(()=>{var r,n;this.bufferingVisibleTimeoutId=null,!this.isBuffering&&(this.isBuffering=!0,(n=(r=this.callbacks).onBufferingStateChange)==null||n.call(r,!0))},Oc);return}this.clearBufferingVisibleTimeout(),this.isBuffering&&(this.isBuffering=!1,(i=(t=this.callbacks).onBufferingStateChange)==null||i.call(t,!1))}clearBufferingVisibleTimeout(){this.bufferingVisibleTimeoutId&&(clearTimeout(this.bufferingVisibleTimeoutId),this.bufferingVisibleTimeoutId=null)}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.lastRuntimeState})}handlePreviewTransformChange(e,t){var i;if(!t){((i=this.transientVisualTransform)==null?void 0:i.clipId)===e&&(this.transientVisualTransform=null,this.refreshVisualLayout());return}this.transientVisualTransform={clipId:e,transform:t},this.refreshVisualLayout()}refreshVisualLayout(){for(const{current:e,preload:t}of this.trackSlots.values())this.refreshSlotVisualLayout(e),this.refreshSlotVisualLayout(t);this.refreshTextPreviewLayout(),this.transformOverlay.sync(this.buildSelectedOverlayState())}syncTextPreviewEntries(e){this.ensureTextPreviewFontReady();const t=e.filter(r=>!r.muted&&r.hasVisual).sort((r,n)=>r.trackOrder-n.trackOrder),i=new Set(t.map(r=>r.clip.id));for(const[r]of this.textPreviewEntries)i.has(r)||this.removeTextPreviewEntry(r);t.forEach(r=>{var h;const n=this.textPreviewEntries.get(r.clip.id);if(n){n.entry=r,this.applyTextPreviewEntry(n);return}const s=document.createElement("div");s.className="timeline-preview-text-entry",s.style.position="absolute",s.style.left="0",s.style.top="0",s.style.transformOrigin="center center",s.style.whiteSpace="pre",s.style.wordBreak="normal",s.style.overflowWrap="normal",s.style.pointerEvents="none",s.style.userSelect="none";const o=this.createTextPreviewPointerDownHandler(r.clip.id);s.addEventListener("pointerdown",o),(h=this.textOverlayRoot)==null||h.appendChild(s);const l={entry:r,element:s,handlePointerDown:o};this.textPreviewEntries.set(r.clip.id,l),this.applyTextPreviewEntry(l)}),this.refreshTextPreviewInteractionState()}clearTextPreviewEntries(){for(const e of Array.from(this.textPreviewEntries.keys()))this.removeTextPreviewEntry(e)}removeTextPreviewEntry(e){var i;const t=this.textPreviewEntries.get(e);t&&(((i=this.textPreviewDragState)==null?void 0:i.clipId)===e&&this.finishTextPreviewDrag(!1),t.element.removeEventListener("pointerdown",t.handlePointerDown),t.element.remove(),this.textPreviewEntries.delete(e))}applyTextPreviewEntry(e){const t=vt(e.entry.clip.textStyle),i=e.entry.clip.textContent||e.entry.clip.name||"";e.element.textContent=i,e.element.style.color=t.color,e.element.style.fontFamily=this.getTextPreviewFontFamily(),e.element.style.fontSize=`${t.fontSize}px`,e.element.style.lineHeight=`${t.lineHeight}px`,e.element.style.textShadow=Bc(t.strokeWidth,t.strokeColor),e.element.style.padding=`0 ${t.paddingX}px`,e.element.style.textAlign="left",e.element.style.zIndex=String(2e3-e.entry.trackOrder)}refreshTextPreviewLayout(){const e=this.getFrameSize();if(e.width<=0||e.height<=0)return;const t=this.getTextPreviewBaselineMetrics(e);for(const i of this.textPreviewEntries.values()){const r=this.getEffectiveVisualTransform(i.entry),n=vt(i.entry.clip.textStyle).rotation;i.element.style.left=`${e.width*r.x}px`,i.element.style.top=`${e.height*r.y}px`,i.element.style.transform=["translate(-50%, -50%)",`scale(${t.scale*r.scale})`,`rotate(${n}deg)`].join(" ")}}refreshTextPreviewEntries(){for(const e of this.textPreviewEntries.values())this.applyTextPreviewEntry(e);this.refreshTextPreviewLayout(),this.refreshTextPreviewInteractionState()}createTextPreviewPointerDownHandler(e){return t=>{var s,o;const i=t;if((i.button??0)!==0||this.primarySelectedClipId!==e)return;this.textPreviewDragState&&this.finishTextPreviewDrag(!1);const r=this.textPreviewEntries.get(e);if(!r)return;(s=i.preventDefault)==null||s.call(i),(o=i.stopPropagation)==null||o.call(i);const n=this.getEffectiveVisualTransform(r.entry);this.textPreviewDragState={clipId:e,pointerStart:this.toFrameLocalPoint(i),startTransform:n,nextTransform:n,changed:!1},this.bindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}}bindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.addEventListener("pointermove",this.boundTextPreviewPointerMove),e.addEventListener("pointerup",this.boundTextPreviewPointerUp),e.addEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.addEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}unbindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.removeEventListener("pointermove",this.boundTextPreviewPointerMove),e.removeEventListener("pointerup",this.boundTextPreviewPointerUp),e.removeEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.removeEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}handleTextPreviewPointerMove(e){var o;const t=this.textPreviewDragState;if(!t)return;if(!this.textPreviewEntries.get(t.clipId)){this.finishTextPreviewDrag(!1);return}const r=e;(o=r.preventDefault)==null||o.call(r);const n=this.toFrameLocalPoint(r),s=oa(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=s,t.changed=!Nr(t.startTransform,s),this.handlePreviewTransformChange(t.clipId,s),this.refreshTextPreviewInteractionState()}finishTextPreviewDrag(e){var i,r;const t=this.textPreviewDragState;if(!t){this.unbindTextPreviewDocumentListeners();return}e&&t.changed&&((r=(i=this.callbacks).onVisualTransformCommit)==null||r.call(i,t.clipId,t.nextTransform)),this.handlePreviewTransformChange(t.clipId,null),this.textPreviewDragState=null,this.unbindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}refreshTextPreviewInteractionState(){var e;for(const t of this.textPreviewEntries.values()){const i=t.entry.clip.id===this.primarySelectedClipId,r=t.entry.clip.id===((e=this.textPreviewDragState)==null?void 0:e.clipId);t.element.style.pointerEvents=i?"auto":"none",t.element.style.cursor=i?r?"grabbing":"grab":"default"}}getTextPreviewFontConfig(){const e=this.dependencies.textPreviewFont;return!(e!=null&&e.fontName)||!e.fontSourceUrl?null:e}getTextPreviewFontFamily(){const e=this.getTextPreviewFontConfig();return!e||this.textPreviewFontLoadState==="failed"?Un:`${sr(e.fontName)}, ${Un}`}ensureTextPreviewFontReady(){const e=this.getTextPreviewFontConfig();if(!e||!this.rootElement||typeof document>"u")return;const t=`${e.fontName}::${e.fontSourceUrl}`;if(this.textPreviewFontSignature!==t){this.resetTextPreviewFontState();const n=document.createElement("style");n.textContent=["@font-face {",`font-family: ${sr(e.fontName)};`,`src: url("${la(e.fontSourceUrl)}");`,"font-display: swap;","}"].join(""),this.rootElement.appendChild(n),this.textPreviewFontStyleElement=n,this.textPreviewFontSignature=t,this.textPreviewFontLoadState="idle"}const i=document.fonts;if(typeof(i==null?void 0:i.load)!="function"||this.textPreviewFontLoadState==="loading"||this.textPreviewFontLoadState==="loaded")return;const r=++this.textPreviewFontLoadToken;this.textPreviewFontLoadState="loading",Promise.resolve(i.load(`1em ${sr(e.fontName)}`)).then(()=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="loaded",this.refreshTextPreviewEntries())}).catch(n=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="failed",M.warn("TimelinePreviewSession","Failed to load text preview font",{fontName:e.fontName,fontSourceUrl:e.fontSourceUrl,error:n}),this.refreshTextPreviewEntries())})}resetTextPreviewFontState(){var e;this.textPreviewFontLoadToken+=1,this.textPreviewFontLoadState="idle",this.textPreviewFontSignature=null,(e=this.textPreviewFontStyleElement)==null||e.remove(),this.textPreviewFontStyleElement=null}refreshSlotVisualLayout(e){if(e.kind!=="video"||!e.wrapper||!e.entry||!this.frameElement)return;const t=this.getFrameSize();if(t.width<=0||t.height<=0)return;const i=this.getMediaSize(e,e.entry,t),r=this.getEffectiveVisualTransform(e.entry),n=zn(t,i,r);e.wrapper.style.left=`${n.left}px`,e.wrapper.style.top=`${n.top}px`,e.wrapper.style.width=`${n.width}px`,e.wrapper.style.height=`${n.height}px`}buildSelectedOverlayState(){if(!this.primarySelectedClipId)return null;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return null;for(const{current:t}of this.trackSlots.values()){if(t.kind!=="video"||!t.isActive||!t.entry||t.entry.clip.id!==this.primarySelectedClipId)continue;const i=this.getMediaSize(t,t.entry,e),r=this.getEffectiveVisualTransform(t.entry);return{clipId:t.entry.clip.id,transform:r,frameSize:e,baseRect:aa(e,i),displayRect:zn(e,i,r)}}return null}getFrameSize(){var i,r,n,s;const e=((i=this.frameElement)==null?void 0:i.clientWidth)??0,t=((r=this.frameElement)==null?void 0:r.clientHeight)??0;return{width:e>0?e:Xn((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:Xn((s=this.frameElement)==null?void 0:s.style.height)}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}toFrameLocalPoint(e){var i;const t=(i=this.frameElement)==null?void 0:i.getBoundingClientRect();return{x:(e.clientX??0)-((t==null?void 0:t.left)??0),y:(e.clientY??0)-((t==null?void 0:t.top)??0)}}getTextPreviewBaselineMetrics(e){const t=Gc(this.getAspectRatio());return t.width<=0||t.height<=0||e.width<=0||e.height<=0?{width:t.width,height:t.height,scale:1}:{width:t.width,height:t.height,scale:Math.min(e.width/t.width,e.height/t.height)}}getMediaSize(e,t,i){if(Wn(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=bi(t,"sys_width"),n=bi(t,"sys_height");return r&&n?{width:r,height:n}:{width:i.width,height:i.height}}getEffectiveVisualTransform(e){var t;return((t=this.transientVisualTransform)==null?void 0:t.clipId)===e.clip.id?this.transientVisualTransform.transform:ke(e.clip.visualTransform)}}class Yc extends Wc{constructor(e={}){super(e.callbacks,{previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont,sourceMediaRegistry:e.sourceMediaRegistry,rootClassName:e.rootClassName,frameClassName:e.frameClassName,slotClassNamePrefix:e.slotClassNamePrefix})}destroy(){this.detach()}}function Xc(a){return"dom"}const qc=36e5,jc=3e5;function _r(a){return a.length===0?0:a.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function qn(a){return _r(a)}function jn(a){return Math.max(a+jc,qc)}class Kn{constructor(e={}){p(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(r){M.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function Kc(a){return[...a].sort((e,t)=>e.order-t.order)}function Zc(a){return[...a].sort((e,t)=>e.startTime-t.startTime)}function ar(a,e,t){const i=a.type==="video"||a.type==="text",r=a.type!=="text";return{trackId:a.id,trackType:a.type,trackOrder:a.order,clip:e,mediaTime:t,muted:(a.isMuted??!1)||(e.isMuted??!1),kind:a.type,hasVisual:i,hasAudio:r}}class Jc{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t){const i=Kc(e),r=[],n=[];let s=null;for(const o of i){const l=Zc(o.clips),h=l.find(d=>t>=d.startTime&&t<d.endTime);if(h){const d=h.startTimeAtSource+(t-h.startTime);r.push(ar(o,h,d))}const c=l.find(d=>d.startTime>t);if(c&&n.push(ar(o,c,c.startTimeAtSource)),!s&&o.type==="video"){const d=l[0];d&&(s=ar(o,d,d.startTimeAtSource))}}return{activeClips:r,nextClips:n,firstVideoClip:s}}}class Qc{constructor(e){p(this,"options");p(this,"_previewSession");p(this,"_previewMountContainer",null);p(this,"_resolvedPreviewBackend","dom");p(this,"_runtimePreviewBackendOverride",null);p(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const ed=8e3,td=1e3;class id{constructor(e){p(this,"callbacks");p(this,"pendingTimeoutMs");p(this,"failedOverlayDelayMs");p(this,"_previewSourceLoadingCount",0);p(this,"_previewBuffering",!1);p(this,"_previewAwaitingMedia",!1);p(this,"_pendingPreviewState",null);p(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.pendingTimeoutMs=e.pendingTimeoutMs??ed,this.failedOverlayDelayMs=e.failedOverlayDelayMs??td}get previewSourceLoadingCount(){return this._previewSourceLoadingCount}set previewSourceLoadingCount(e){this._previewSourceLoadingCount=Math.max(0,e)}get previewBuffering(){return this._previewBuffering}set previewBuffering(e){this._previewBuffering=e}get pendingPreviewState(){return this._pendingPreviewState}set pendingPreviewState(e){this._pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this._nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this._nextPendingPreviewSyncRequestId=Math.max(0,e)}handleBufferingStateChange(e){this._previewBuffering=e,this.callbacks.emitBufferingStateChange(e),this.updatePendingPreviewState()}handleSourceLoadingChange(e){this._previewSourceLoadingCount=Math.max(0,e),this.callbacks.emitSourceLoadingStateChange(),this.updatePendingPreviewState()}handleRuntimeStateChange(e){const t=Math.max(0,e.loadingCount),i=this._previewBuffering!==e.isBuffering,r=this._previewSourceLoadingCount!==t;this._previewAwaitingMedia=e.phase==="awaiting-media",this._previewBuffering=e.isBuffering,this._previewSourceLoadingCount=t,this._pendingPreviewState&&e.syncRequestId===this._pendingPreviewState.syncRequestId&&((e.phase==="awaiting-media"||e.phase==="ready"||e.phase==="failed")&&(this._pendingPreviewState.awaitingSync=!1),e.phase==="failed"?this.scheduleFailedOverlay(e.errorMessage||"资源加载异常,请刷新重试"):(this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.errorMessage=null)),i&&this.callbacks.emitBufferingStateChange(e.isBuffering),r&&this.callbacks.emitSourceLoadingStateChange(),this.updatePendingPreviewState()}markSyncProcessed(e){this._pendingPreviewState&&e===this._pendingPreviewState.syncRequestId&&(this._pendingPreviewState.awaitingSync=!1),this.updatePendingPreviewState()}beginPendingPreview(e,t,i){this.clearPendingPreviewTimeout(),this._pendingPreviewState={mode:t,targetTime:e,resumePlayOnReady:i,errorMessage:null,timeoutId:null,failedTimeoutId:null,pendingFailedMessage:null,awaitingSync:!0,syncRequestId:++this._nextPendingPreviewSyncRequestId}}buildPreviewPendingState(){return!this._pendingPreviewState||this._pendingPreviewState.mode==="scrub"?null:{mode:this._pendingPreviewState.mode,targetTime:this._pendingPreviewState.targetTime,loadingPending:this._previewSourceLoadingCount,isBuffering:this._previewAwaitingMedia||this._previewBuffering,errorMessage:this._pendingPreviewState.errorMessage}}updatePendingPreviewState(){if(!this._pendingPreviewState){this.callbacks.applyPendingState(null);return}const e=this._previewSourceLoadingCount>0||this._previewAwaitingMedia;if(this._pendingPreviewState.errorMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.pendingFailedMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.awaitingSync){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(e){this.ensurePendingPreviewTimeout(),this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const t=this._pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),t&&this.callbacks.resumePlayback()}retryPendingPreview(){this._pendingPreviewState&&(this._pendingPreviewState.errorMessage=null,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.awaitingSync=!0,this._pendingPreviewState.syncRequestId=++this._nextPendingPreviewSyncRequestId,this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this.callbacks.requestPreviewSync())}clearPendingPreviewState(){this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this._pendingPreviewState=null,this.callbacks.applyPendingState(null)}resetPreviewRuntimeState(){const e=this._previewBuffering,t=this._previewSourceLoadingCount!==0;this._previewBuffering=!1,this._previewAwaitingMedia=!1,this._previewSourceLoadingCount=0,e&&this.callbacks.emitBufferingStateChange(!1),t&&this.callbacks.emitSourceLoadingStateChange()}ensurePendingPreviewTimeout(){if(!this._pendingPreviewState||this._pendingPreviewState.mode==="scrub"||this._pendingPreviewState.timeoutId!==null)return;const e=this._pendingPreviewState.syncRequestId;this._pendingPreviewState.timeoutId=setTimeout(()=>{!this._pendingPreviewState||this._pendingPreviewState.syncRequestId!==e||(this._pendingPreviewState.errorMessage="资源加载异常,请刷新重试",this.clearPendingPreviewTimeout(),this.callbacks.applyPendingState(this.buildPreviewPendingState()))},this.pendingTimeoutMs)}clearPendingPreviewTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.timeoutId&&(clearTimeout(this._pendingPreviewState.timeoutId),this._pendingPreviewState.timeoutId=null)}scheduleFailedOverlay(e){if(!this._pendingPreviewState||this._pendingPreviewState.errorMessage===e||this._pendingPreviewState.pendingFailedMessage===e&&this._pendingPreviewState.failedTimeoutId)return;this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=e;const t=this._pendingPreviewState.syncRequestId;this._pendingPreviewState.failedTimeoutId=setTimeout(()=>{!this._pendingPreviewState||this._pendingPreviewState.syncRequestId!==t||(this._pendingPreviewState.errorMessage=e,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.failedTimeoutId=null,this.callbacks.applyPendingState(this.buildPreviewPendingState()))},this.failedOverlayDelayMs)}clearFailedOverlayTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.failedTimeoutId&&(clearTimeout(this._pendingPreviewState.failedTimeoutId),this._pendingPreviewState.failedTimeoutId=null)}}const rd=["togglePlay","deleteSelectedClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],nd={togglePlay:["Space"],deleteSelectedClips:["Delete","Backspace"],toggleSelectedClipsAudio:["Mod+Alt+A"],splitCurrentClip:["Mod+B"],undo:["Mod+Z"],redo:["Mod+Shift+Z","Ctrl+Y"]};function sd(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function ad(a){const e=a.trim();if(!e)return null;const t=e.toLowerCase();return t==="space"||t==="spacebar"?"Space":t==="delete"?"Delete":t==="backspace"?"Backspace":/^[a-z]$/i.test(e)?`Key${e.toUpperCase()}`:/^key[a-z]$/i.test(e)?`Key${e.slice(-1).toUpperCase()}`:/^[0-9]$/.test(e)?`Digit${e}`:/^digit[0-9]$/i.test(e)?`Digit${e.slice(-1)}`:null}function od(a,e,t){const i=e.split("+").map(h=>h.trim()).filter(h=>h.length>0);if(i.length===0)return null;let r=null,n=!1,s=!1,o=!1,l=!1;for(const h of i)switch(h.toLowerCase()){case"mod":t?o=!0:s=!0;break;case"alt":case"option":n=!0;break;case"ctrl":case"control":s=!0;break;case"cmd":case"command":case"meta":o=!0;break;case"shift":l=!0;break;default:{const c=ad(h);if(!c||r)return null;r=c}}return r?{action:a,code:r,altKey:n,ctrlKey:s,metaKey:o,shiftKey:l}:null}function ld(a){if(!(a instanceof HTMLElement))return!1;if(a.isContentEditable)return!0;const e=a.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:!!a.closest('[contenteditable=""], [contenteditable="true"], input, textarea, select')}function hd(a,e){return a.code===e.code&&a.altKey===e.altKey&&a.ctrlKey===e.ctrlKey&&a.metaKey===e.metaKey&&a.shiftKey===e.shiftKey}function cd(a,e){return a===!1||(a==null?void 0:a.enabled)===!1?[]:rd.flatMap(t=>{var n;const i=(n=a==null?void 0:a.bindings)==null?void 0:n[t];return(i===void 0?nd[t]:Array.isArray(i)?i:[i]).map(s=>od(t,s,e)).filter(s=>s!==null)})}class dd{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??sd();e.root,this.callbacks=e.callbacks,this.bindings=cd(e.config,t),this.enabled=e.config!==!1&&((i=e.config)==null?void 0:i.enabled)!==!1&&this.bindings.length>0}init(){var e,t;this.enabled&&((t=(e=globalThis.window)==null?void 0:e.addEventListener)==null||t.call(e,"keydown",this.keydownListener))}destroy(){var e,t;(t=(e=globalThis.window)==null?void 0:e.removeEventListener)==null||t.call(e,"keydown",this.keydownListener)}handleKeydown(e){if(ld(e.target))return;const t=this.bindings.find(i=>hd(e,i));t&&(e.preventDefault(),e.stopPropagation(),this.dispatchAction(t.action))}dispatchAction(e){switch(e){case"togglePlay":this.callbacks.togglePlay();return;case"deleteSelectedClips":this.callbacks.canDeleteSelectedClips()&&this.callbacks.deleteSelectedClips();return;case"toggleSelectedClipsAudio":this.callbacks.canToggleSelectedClipsAudio()&&this.callbacks.toggleSelectedClipsAudio();return;case"splitCurrentClip":this.callbacks.canSplitSelectedClip()&&this.callbacks.splitCurrentClip();return;case"undo":this.callbacks.undo();return;case"redo":this.callbacks.redo();return}}}function ha(a){var t;const e=a.getPrimarySelectedClip()||((t=a.findFallbackSelectedClip)==null?void 0:t.call(a))||null;return{clip:e,hasSelectedClip:!!e}}function ud(a){const e=ha(a),t=a.getSelectedClipIds(),i=a.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:a.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function pd(a){var i;const e=a.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===a.lastSelectedClipId?a.lastSelectedClipId:(a.emitSelectedClipChange(e),t)}function ca(a,e){var t,i,r,n;return((i=(t=a.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((n=(r=a.getLastTrack())==null?void 0:r.getId)==null?void 0:n.call(r))||e}function gd(a){if(a.placement.status==="use_existing_track")return a.trackCollection.addClipToTrack(a.placement.trackId,a.clip);const e=a.createTrack(a.placement.trackType,a.placement.suggestedTrackName,a.placement.insertionPlacement),t=ca(a.trackCollection,e);return t?a.trackCollection.addClipToTrack(t,a.clip):!1}function Zn(a,e,t){return e.trackId?a.removeClipFromTrack(e.trackId,t):!1}function fd(a){return a.trackCollection.moveClipToTrack(a.command.clip,a.command.sourceTrackId,a.command.targetTrackId)}function md(a){const e=a.createTrack(a.trackType,a.trackName),t=ca(a.trackCollection,e);return t?a.trackCollection.moveClipToTrack(a.clip,a.currentTrackId,t):!1}function Ge(a){var e,t,i,r,n;(e=a.checkTrackDurationChange)==null||e.call(a),(t=a.updateCanPlayState)==null||t.call(a),(i=a.updateTrackInfoPanel)==null||i.call(a),(r=a.handleClipChange)==null||r.call(a),(n=a.cleanupEmptyTracks)==null||n.call(a)}function yd(a){var e,t;a.notifySelectionChange(),(e=a.cleanupEmptyTracks)==null||e.call(a),a.updateTrackInfoPanel(),(t=a.batchDraw)==null||t.call(a),a.syncPreviewSession()}class Sd{constructor(){p(this,"panel",null)}init(e){var i,r,n,s;const t=((i=e.theme)==null?void 0:i.background)||be.background;this.panel=new na({container:e.container,theme:{background:t,border:((r=e.theme)==null?void 0:r.border)||be.border,text:((n=e.theme)==null?void 0:n.clipName)||be.text,buttonBackground:((s=e.theme)==null?void 0:s.clipBackground)||be.buttonBackground,buttonHover:be.buttonHover,buttonDanger:be.buttonDanger},width:200,timeScaleHeight:e.timeScaleHeight||40,includeTimeScaleSpacer:e.includeTimeScaleSpacer},e.onRenameTrack,e.onRemoveTrack,e.onMuteTrack)}hasPanel(){return!!this.panel}update(e){var t;(t=this.panel)==null||t.setTracks(e)}setScrollTop(e){var t;(t=this.panel)==null||t.setScrollTop(e)}destroy(){var e;(e=this.panel)==null||e.destroy(),this.panel=null}}class Jn{syncCurrentTime(e,t,i,r){e==null||e.setCurrentTime(r),t==null||t.setCurrentTime(r),i.syncCurrentTime(r)}syncZoom(e,t,i,r){e==null||e.setZoom(r),t==null||t.setZoom(r),i.syncZoom(r)}syncScrollLeft(e,t,i){e==null||e.setScrollLeft(i),t.syncScrollLeft(i)}syncScrollTop(e,t,i){e==null||e.setScrollTop(i),t==null||t.setScrollTop(i)}syncSelection(e,t){e.syncSelection(t,t[0]??null)}findSelectedClip(e){return e.findPrimarySelectedClip()}}function Cd(a){return!!a&&typeof a.then=="function"}class or{constructor(){p(this,"durationCache",new Map);p(this,"thumbnailCache",new Map);p(this,"previewSourceCache",new Map)}static buildSourceKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src||""}static buildThumbnailKey(e){return[this.buildSourceKey(e),e.type,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}getDuration(e,t,i={}){const r=this.durationCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(typeof(r==null?void 0:r.value)=="number")return Promise.resolve(r.value)}const n=t().then(s=>(this.durationCache.set(e,{value:s,promise:null}),s)).catch(s=>{throw this.durationCache.delete(e),s});return this.durationCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeDuration(e,t){this.durationCache.set(e,{value:t,promise:null})}getThumbnails(e,t,i={}){const r=this.thumbnailCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.value)return Promise.resolve(r.value)}const n=t().then(s=>(this.thumbnailCache.set(e,{value:s,promise:null}),s)).catch(s=>{throw this.thumbnailCache.delete(e),s});return this.thumbnailCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeThumbnails(e,t){this.thumbnailCache.set(e,{value:t,promise:null})}clearThumbnailCache(){this.thumbnailCache.clear()}getPreviewSource(e,t,i={}){const r=this.previewSourceCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.resolved)return r.value}const n=t();if(!Cd(n))return this.previewSourceCache.set(e,{value:n,promise:null,resolved:!0}),n;const s=n.then(o=>(this.previewSourceCache.set(e,{value:o,promise:null,resolved:!0}),o)).catch(o=>{throw this.previewSourceCache.delete(e),o});return this.previewSourceCache.set(e,{value:(r==null?void 0:r.value)??null,promise:s,resolved:!1}),s}primePreviewSource(e,t){this.previewSourceCache.set(e,{value:t,promise:null,resolved:!0})}}class Qn{constructor(e,t=Bi){this.handlers=e,this.TrackCtor=t}createTrack(e){return new this.TrackCtor(e.layer,e.config,e.trackType,e.zoom,e.trackY,e.trackHeight,e.theme,this.handlers.onClipUpdate,this.handlers.onClipAdd,this.handlers.onClipRemove,this.handlers.onClipSplit,this.handlers.onClipSelect,this.handlers.onTimeJump,this.handlers.onHorizontalDragAutoScroll,this.handlers.onClipOverlap,this.handlers.onClipCrossTrackPreview,this.handlers.onClipCrossTrack,this.handlers.onClearDropPreview,this.handlers.onClearSelection,this.handlers.onSnapGuideChange,this.handlers.onClipToggleSelection,this.handlers.onSetSingleSelection,this.handlers.getMultiDragClipIds,this.handlers.onMultiDragMove,this.handlers.onMultiDragInteractionEnd,e.dragActivationThreshold,e.enableClipSnap,e.clipSnapThreshold)}}class vd{constructor(e){this.tracks=e}getAll(){return this.tracks}getDefaultTrack(){return this.tracks[0]||null}getPrimaryTrack(){return this.tracks.find(e=>{var t;return((t=e.getRole)==null?void 0:t.call(e))==="primary"})||this.getDefaultTrack()}getLastTrack(){return this.tracks.length>0?this.tracks[this.tracks.length-1]:null}add(e){this.tracks.push(e)}findById(e){return this.tracks.find(t=>this.resolveTrackId(t)===e)||null}removeById(e){const t=this.findIndexById(e);if(t===-1)return null;const[i]=this.tracks.splice(t,1);return i||null}removeEmptyNonPrimaryTracks(){var t;const e=[];for(let i=this.tracks.length-1;i>=0;i-=1){const r=this.tracks[i];if(((t=r.getRole)==null?void 0:t.call(r))==="primary"||(typeof r.getClips=="function"?r.getClips():[]).length>0)continue;const[s]=this.tracks.splice(i,1);s&&e.push(s)}return e.reverse()}findTrackByClipId(e){return this.tracks.find(t=>t.getClips().some(i=>i.id===e))||null}getAllClips(){return this.tracks.flatMap(e=>e.getClips())}syncCurrentTime(e){this.tracks.forEach(t=>{var i;return(i=t.setCurrentTime)==null?void 0:i.call(t,e)})}syncZoom(e){this.tracks.forEach(t=>{var i;return(i=t.setZoom)==null?void 0:i.call(t,e)})}syncScrollLeft(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollLeft)==null?void 0:i.call(t,e)})}syncScrollTop(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollTop)==null?void 0:i.call(t,e)})}updateClip(e,t){this.tracks.forEach(i=>{var r;return(r=i.updateClip)==null?void 0:r.call(i,e,t)})}removeClip(e){this.tracks.forEach(t=>{var i;return(i=t.removeClip)==null?void 0:i.call(t,e)})}addClipToTrack(e,t){const i=this.findById(e);return i!=null&&i.addClip?(i.addClip(t),!0):!1}removeClipFromTrack(e,t){const i=this.findById(e);return i!=null&&i.removeClip?(i.removeClip(t),!0):!1}moveClipToTrack(e,t,i){if(t===i)return!0;const r=this.findById(t),n=this.findById(i);return!(r!=null&&r.removeClip)||!(n!=null&&n.addClip)?!1:(r.removeClip(e.id),n.addClip(e),!0)}removeClipGaps(){this.tracks.forEach(e=>{var t;return(t=e.removeClipGaps)==null?void 0:t.call(e)})}clearSelection(){this.tracks.forEach(e=>{var t;return(t=e.clearSelection)==null?void 0:t.call(e)})}syncSelection(e,t=e[0]??null){this.tracks.forEach(i=>{var r;(r=i.setSelection)==null||r.call(i,e,t)})}findPrimarySelectedClip(){var e;for(const t of this.tracks){const i=(e=t.getPrimarySelectedClip)==null?void 0:e.call(t);if(i)return i}return null}forEach(e){this.tracks.forEach(e)}findIndexById(e){return this.tracks.findIndex(t=>this.resolveTrackId(t)===e)}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}function Td(a){return a==="text"?"文本":a==="video"?"视频":"音频"}function wi(a){return a==="text"?0:a==="video"?1:2}class da{constructor(e=[]){p(this,"tracks",[]);p(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,r,n){this.trackCounter++;const s=t||`${Td(e)}轨道 ${this.trackCounter}`,o=n??(this.tracks.length===0?"primary":"normal");o==="primary"&&this.tracks.forEach(h=>{h.role==="primary"&&(h.role="normal")});const l={id:`track_${Date.now()}_${this.trackCounter}`,type:e,name:s,order:this.tracks.length,role:o,clips:[]};return this.insertTrack(l,i,r),M.debugLazy("TrackManager",()=>`创建轨道: ${s}`,()=>({trackId:l.id,type:e,order:l.order})),l}removeTrack(e){var i;const t=this.tracks.findIndex(r=>r.id===e);return t===-1?(M.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(M.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),M.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,M.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(M.warn("TrackManager",`轨道不存在: ${e}`),!1)}getTracks(){return[...this.tracks]}getTrack(e){return this.tracks.find(t=>t.id===e)}getTracksByType(e){return this.tracks.filter(t=>t.type===e)}updateTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(Object.assign(i,t),M.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(M.warn("TrackManager",`轨道不存在: ${e}`),!1)}recalculateOrder(){this.tracks.forEach((e,t)=>{e.order=t})}insertTrack(e,t,i){const r=this.tracks.findIndex(s=>s.role==="primary"),n=t??(e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary");if(r===-1||e.role==="primary"){this.tracks.push(e),this.recalculateOrder();return}if((n==="before_track"||n==="after_track")&&i){const s=this.tracks.findIndex(o=>o.id===i);if(s!==-1){this.tracks.splice(s+(n==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(n==="top_of_type_region"){const s=this.tracks.findIndex(l=>l.type===e.type);if(s!==-1){this.tracks.splice(s,0,e),this.recalculateOrder();return}const o=this.tracks.findIndex(l=>wi(l.type)>wi(e.type));if(o!==-1){this.tracks.splice(o,0,e),this.recalculateOrder();return}}if(n==="bottom_of_type_region"){const s=this.tracks.reduce((l,h,c)=>h.type===e.type?c:l,-1);if(s!==-1){this.tracks.splice(s+1,0,e),this.recalculateOrder();return}const o=this.tracks.reduce((l,h,c)=>wi(h.type)<=wi(e.type)?c:l,-1);if(o!==-1){this.tracks.splice(o+1,0,e),this.recalculateOrder();return}}n==="before_primary"?this.tracks.splice(r,0,e):this.tracks.splice(r+1,0,e),this.recalculateOrder()}muteTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.isMuted=t,M.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(M.warn("TrackManager",`轨道不存在:${e}`),!1)}isTrackMuted(e){const t=this.tracks.find(i=>i.id===e);return(t==null?void 0:t.isMuted)??!1}clearAllTracks(){this.tracks=[],this.trackCounter=0,M.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}function tt(a){return a==="text"?Le.TEXT:a==="video"?Le.VIDEO:Le.AUDIO}function Rt(a,e,t){let i=t;for(const r of a){if(r.id===e)break;i+=tt(r.type)}return i}function es(a,e){return a.reduce((t,i)=>t+tt(i.type),e)}function bd(a,e){let t=e;return a.map(i=>{const r=tt(i.type),n={trackId:i.id,y:t,height:r};return t+=r,n})}class wd{constructor(){p(this,"container",null)}mount(e,t){return this.container=e,ii(this.renderTemplate(t),e),e.classList.add("timeline-manager-root"),e.style.gridTemplateColumns=`${t.leftPanelWidth}px minmax(0, 1fr)`,e.style.gridTemplateRows=`${t.timeScaleHeight}px minmax(0, 1fr)`,e.style.background=t.theme.background,{headerCorner:this.requireElement(e,'[data-layout-role="header-corner"]'),headerViewport:this.requireElement(e,'[data-layout-role="header-viewport"]'),headerCanvasHost:this.requireElement(e,'[data-layout-role="header-canvas-host"]'),trackInfoViewport:this.requireElement(e,'[data-layout-role="track-info-viewport"]'),bodyViewport:this.requireElement(e,'[data-layout-role="body-viewport"]'),bodyCanvasHost:this.requireElement(e,'[data-layout-role="body-canvas-host"]'),verticalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="vertical-scrollbar-host"]'),horizontalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="horizontal-scrollbar-host"]'),playheadOverlay:this.requireElement(e,'[data-layout-role="playhead-overlay"]')}}destroy(){this.container&&ii(null,this.container),this.container=null}renderTemplate(e){const{theme:t,timeScaleHeight:i,leftPanelWidth:r,scrollbarSize:n}=e,s=["position:relative","min-width:0","min-height:0","max-width:100%","box-sizing:border-box",`background:${t.background}`,`color:${t.clipName}`].join(";");return K`
|
|
493
|
+
`}getContainerStyle(e){return[`background-color:${e.backgroundColor}`,"border-radius:4px",`color:${e.textColor}`,'font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size:13px","display:flex","flex-direction:column","overflow:hidden","height:100%",`--clip-slider-fill-start:${E.sliderFillStart}`,`--clip-slider-fill-end:${E.sliderFillEnd}`,`--clip-slider-road:${E.sliderRoad}`,`--clip-slider-thumb-border:${E.sliderThumbBorder}`,`--clip-slider-thumb-shadow:${ve.sliderThumbShadow}`].join(";")}getSliderStyle(e,t,i){const r=Number(e||0),n=Number(t||100),s=Number(i||0),o=n-r,l=o<=0?0:(s-r)/o*100;return["flex:1","min-width:0",`--clip-slider-progress:${Math.max(0,Math.min(100,l))}%`].join(";")}getAvailableTabs(e){return e?e.type==="text"?["text","voice"]:e.type==="audio"?e.ttsSourceTextClipId?["audio","voice"]:["audio"]:["visual","audio"]:[]}supportsVoicePanel(e){return!!e&&(e.type==="text"||e.type==="audio"&&!!e.ttsSourceTextClipId)}getTransform(e){return(e==null?void 0:e.visualTransform)??{x:.5,y:.5,scale:1}}calculatePresetPosition(e,t,i){const n=this.getTransform(e).scale/2,s={left:n,center:.5,right:1-n},o={top:n,center:.5,bottom:1-n};return{x:s[t],y:o[i]}}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}const Nh={...ge};class xa{constructor(e){p(this,"container");p(this,"theme");p(this,"renderer",new Hh);p(this,"onClipUpdate");p(this,"onGenerateVoice");p(this,"voiceCatalog");p(this,"currentClip",null);p(this,"activeTab","visual");p(this,"iconCache",new Map);p(this,"pendingPreferredTab",null);p(this,"selectedVoiceId",null);p(this,"activeVoiceFilterTag",null);p(this,"textDraftContent","");p(this,"followTextUpdates",!1);p(this,"voiceLoadingBusyCount",0);p(this,"isVoiceLoadingOverlayRendered",!1);p(this,"isVoiceLoadingOverlayExiting",!1);p(this,"voiceLoadingOverlayHideTimer",null);p(this,"voiceErrorMessage",null);p(this,"voicePreviewAudio",null);p(this,"previewingVoiceId",null);p(this,"handleVoicePreviewEnded",()=>{this.stopVoicePreview()});this.container=e.container,this.theme=e.theme??Nh,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",Te("OmAi-camera")),this.iconCache.set("OmAi-accept",Te("OmAi-accept")),this.iconCache.set("OmAi-loading",Te("OmAi-loading")),this.iconCache.set("OmAi-text",Te("OmAi-text")),this.renderer.mount(this.container),this.render()}setClip(e){var n;const t=((n=this.currentClip)==null?void 0:n.id)??null,i=(e==null?void 0:e.id)??null,r=t!==i;r&&this.stopVoicePreview(!1),this.currentClip=e,r?(this.voiceErrorMessage=null,this.textDraftContent=(e==null?void 0:e.textContent)??(e==null?void 0:e.name)??"",this.syncVoiceStateForClip(e)):(e==null?void 0:e.type)==="text"?this.textDraftContent=e.textContent??e.name??"":(e==null?void 0:e.type)==="audio"&&e.ttsSourceTextClipId?(this.followTextUpdates=e.ttsFollowTextUpdates??!1,e.ttsVoiceId&&(this.selectedVoiceId=e.ttsVoiceId),this.ensureVoiceFilters()):e||this.resetVoiceState(),this.syncActiveTab(e),this.render()}setPreferredTab(e){this.pendingPreferredTab=e}setVoiceGenerationBusy(e){if(this.voiceLoadingBusyCount=Math.max(0,this.voiceLoadingBusyCount+(e?1:-1)),this.voiceLoadingBusyCount>0){this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.isVoiceLoadingOverlayRendered=!0,this.isVoiceLoadingOverlayExiting=!1,this.render();return}if(!this.isVoiceLoadingOverlayRendered){this.render();return}this.isVoiceLoadingOverlayExiting=!0,this.voiceLoadingOverlayHideTimer!==null&&window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=window.setTimeout(()=>{this.isVoiceLoadingOverlayRendered=!1,this.isVoiceLoadingOverlayExiting=!1,this.voiceLoadingOverlayHideTimer=null,this.render()},180),this.render()}destroy(){this.stopVoicePreview(!1),this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.renderer.destroy()}render(){this.renderer.update({clip:this.currentClip,activeTab:this.activeTab,theme:this.theme,emptyStateIconSvg:this.iconCache.get("OmAi-camera")??"",loadingIconSvg:this.iconCache.get("OmAi-loading")??"",selectedIconSvg:this.iconCache.get("OmAi-accept")??"",textDraftContent:this.textDraftContent,voiceCatalog:this.voiceCatalog,selectedVoiceId:this.selectedVoiceId,previewingVoiceId:this.previewingVoiceId,activeVoiceFilterTag:this.activeVoiceFilterTag,followTextUpdates:this.followTextUpdates,isVoiceLoadingOverlayVisible:this.isVoiceLoadingOverlayRendered,isVoiceLoadingOverlayExiting:this.isVoiceLoadingOverlayExiting,voiceErrorMessage:this.voiceErrorMessage,callbacks:{onTabChange:e=>{this.activeTab=e,this.render()},onTransformChange:(e,t)=>{this.handleTransformChange(e,t)},onPresetSelect:(e,t)=>{this.handleTransformChanges({x:e,y:t})},onVolumeChange:e=>{this.handleVolumeChange(e)},onTextContentInput:e=>{this.handleTextContentInput(e)},onTextContentCommit:()=>{this.handleTextContentCommit()},onTextStyleChange:(e,t)=>{this.handleTextStyleChange(e,t)},onVoiceFilterChange:e=>{this.handleVoiceFilterChange(e)},onVoiceSelect:e=>{this.handleVoiceSelect(e)},onVoiceFollowTextUpdatesChange:e=>{this.handleVoiceFollowTextUpdatesChange(e)},onGenerateVoice:async()=>{await this.handleGenerateVoice()}}})}getAvailableTabs(e=this.currentClip){return e?e.type==="text"?["text","voice"]:e.type==="audio"?e.ttsSourceTextClipId?["audio","voice"]:["audio"]:["visual","audio"]:[]}resetVoiceState(){this.selectedVoiceId=null,this.activeVoiceFilterTag=null,this.followTextUpdates=!1,this.stopVoicePreview(!1)}syncVoiceStateForClip(e){if(!e||!this.supportsVoicePanel(e)){this.resetVoiceState();return}const i=(e.type==="audio"&&e.ttsVoiceId?this.voiceCatalog.find(r=>r.id===e.ttsVoiceId)??null:null)??this.voiceCatalog[0]??null;this.selectedVoiceId=(i==null?void 0:i.id)??null,this.activeVoiceFilterTag=this.resolveDefaultVoiceFilterTag(i),this.followTextUpdates=e.type==="audio"?e.ttsFollowTextUpdates??!1:!1,this.ensureVoiceFilters()}syncActiveTab(e){const t=this.getAvailableTabs(e);if(!e||t.length===0){this.activeTab="visual",this.pendingPreferredTab=null;return}if(this.pendingPreferredTab&&t.includes(this.pendingPreferredTab)){this.activeTab=this.pendingPreferredTab,this.pendingPreferredTab=null;return}t.includes(this.activeTab)||(this.activeTab=t[0],this.pendingPreferredTab=null)}supportsVoicePanel(e){return!!e&&(e.type==="text"||e.type==="audio"&&!!e.ttsSourceTextClipId)}resolveDefaultVoiceFilterTag(e){return e?e.tags.includes("男")?"男":e.tags.includes("女")?"女":e.tags.includes("普通话")?"普通话":e.tags.includes("粤语")?"粤语":null:null}getVisibleVoiceOptions(){return this.voiceCatalog.filter(e=>!this.activeVoiceFilterTag||e.tags.includes(this.activeVoiceFilterTag))}ensureVoiceFilters(){if(this.voiceCatalog.length===0){this.resetVoiceState();return}if(!this.getVisibleVoiceOptions().some(t=>t.id===this.selectedVoiceId)){const t=this.voiceCatalog.find(i=>!this.activeVoiceFilterTag||i.tags.includes(this.activeVoiceFilterTag))??this.voiceCatalog[0]??null;this.selectedVoiceId=(t==null?void 0:t.id)??null}}handleVoiceFilterChange(e){const t=e==="男"||e==="女"||e==="普通话"||e==="粤语"?e:null;this.activeVoiceFilterTag=this.activeVoiceFilterTag===t?null:t,this.ensureVoiceFilters(),this.render()}async handleVoiceSelect(e){const t=this.voiceCatalog.find(r=>r.id===e)??null,i=this.previewingVoiceId===e;if(this.selectedVoiceId=e,this.voiceErrorMessage=null,this.render(),!(t!=null&&t.audiofile)){this.stopVoicePreview();return}if(i){this.stopVoicePreview();return}await this.playVoicePreview(t)}handleVoiceFollowTextUpdatesChange(e){var t;this.followTextUpdates=e,((t=this.currentClip)==null?void 0:t.type)==="audio"&&this.currentClip.ttsSourceTextClipId&&this.onClipUpdate&&(this.currentClip={...this.currentClip,ttsFollowTextUpdates:e},this.onClipUpdate(this.currentClip.id,{ttsFollowTextUpdates:e})),this.render()}async handleGenerateVoice(){if(!this.currentClip||!this.onGenerateVoice)return;const e=this.voiceCatalog.find(t=>t.id===this.selectedVoiceId);if(!e){this.voiceErrorMessage="请选择一个音色",this.render();return}this.voiceErrorMessage=null,this.render();try{await this.onGenerateVoice(this.currentClip,e,this.followTextUpdates)}catch(t){this.voiceErrorMessage=t instanceof Error?t.message:"音色生成失败"}this.render()}handleVolumeChange(e){if(!this.currentClip||!this.onClipUpdate)return;const t=Math.max(0,Math.min(1,e));this.currentClip={...this.currentClip,volume:t},this.render(),this.onClipUpdate(this.currentClip.id,{volume:t})}clampValue(e,t){return e==="scale"?Math.max(.1,Math.min(8,t)):t}handleTransformChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(e,t),n={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:i};this.currentClip={...this.currentClip,visualTransform:n},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:n})}handleTransformChanges(e){if(!this.currentClip||!this.onClipUpdate)return;const i={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1}};e.x!==void 0&&(i.x=this.clampValue("x",e.x)),e.y!==void 0&&(i.y=this.clampValue("y",e.y)),e.scale!==void 0&&(i.scale=this.clampValue("scale",e.scale)),this.currentClip={...this.currentClip,visualTransform:i},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:i})}stopVoicePreview(e=!0){if(this.voicePreviewAudio){this.voicePreviewAudio.removeEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio.pause();try{this.voicePreviewAudio.currentTime=0}catch{}this.voicePreviewAudio=null}if(this.previewingVoiceId!==null){this.previewingVoiceId=null,e&&this.render();return}e&&this.render()}async playVoicePreview(e){if(!e.audiofile)return;this.stopVoicePreview(!1);const t=new Audio(e.audiofile);t.preload="auto",t.addEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio=t,this.previewingVoiceId=e.id,this.render();try{await t.play()}catch(i){this.voicePreviewAudio===t&&(this.stopVoicePreview(!1),this.voiceErrorMessage=i instanceof Error?i.message:"试听播放失败",this.render())}}handleTextContentInput(e){this.textDraftContent=e,this.render()}handleTextContentCommit(){if(!this.currentClip||!this.onClipUpdate)return;const e=this.textDraftContent,t=this.currentClip.textContent??this.currentClip.name??"";e!==t&&(this.currentClip={...this.currentClip,textContent:e},this.render(),this.onClipUpdate(this.currentClip.id,{textContent:e}))}handleTextStyleChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;if(e==="x"||e==="y"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;const o={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:Math.max(0,Math.min(1,n))};this.currentClip={...this.currentClip,visualTransform:o},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:o});return}const r={...Tt(this.currentClip.textStyle)};if(e==="fontSize"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.fontSize=Math.max(5,Math.min(300,n))}else if(e==="rotation"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.rotation=n}else r.color=String(t);this.currentClip={...this.currentClip,textStyle:r},this.render(),this.onClipUpdate(this.currentClip.id,{textStyle:r})}}function $h(a){return a==="text"?"文本":a==="video"?"视频":"音频"}function jn(a){return a==="text"?Le.TEXT:a==="video"?Le.VIDEO:Le.AUDIO}class Kn{constructor(e){this.timelineStore=e}selectClip(e){return this.updateSelection(e)}clearSelection(){return this.updateSelection(null)}findClipById(e,t){for(const i of e){const r=i.getClips().find(n=>n.id===t);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}findClipAtTime(e,t){for(const i of e){const r=i.getClips().find(n=>t>=n.startTime&&t<n.startTime+n.duration);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}prepareRemoveClip(e,t){const i=this.findClipById(t,e);return i?{exists:!0,clip:i.clip,trackId:i.trackId,shouldClearSelection:this.timelineStore.getPrimarySelectedClipId()===e}:{exists:!1,clip:null,trackId:null,shouldClearSelection:!1}}prepareMoveClipToTrack(e,t,i){var h;const r=this.findClipById(i,e);if(!r||!r.trackId)return{status:"missing_source_track",clipId:e,targetTrackId:t};const{clip:n,track:s,trackId:o}=r;if(o===t)return{status:"noop",clipId:e,sourceTrackId:o,targetTrackId:t};const l=i.find(d=>this.resolveTrackId(d)===t);if(!l)return{status:"missing_target_track",clipId:e,targetTrackId:t,sourceTrackId:o};const c=(h=l.getTrackType)==null?void 0:h.call(l);return c&&c!==n.type?{status:"track_type_mismatch",clipId:e,targetTrackId:t,sourceTrackId:o}:{status:"ready",clip:n,sourceTrack:s,sourceTrackId:o,targetTrack:l,targetTrackId:t}}planTrackPlacement(e,t){var n;const i=e.startTime+e.duration;for(const s of t){if(((n=s.getTrackType)==null?void 0:n.call(s))!==e.type)continue;if(!s.getClips().some(l=>e.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(s);if(l)return{status:"use_existing_track",trackId:l}}}const r=t.filter(s=>{var o;return((o=s.getTrackType)==null?void 0:o.call(s))===e.type}).length+1;return{status:"create_track",trackType:e.type,suggestedTrackName:`${$h(e.type)}轨道 ${r}`,insertionPlacement:e.type==="text"||e.type==="video"?"top_of_type_region":"bottom_of_type_region"}}planCrossTrackMove(e,t,i,r,n,s){var f;const o=this.resolveTrackTargetByY(t,r,n,e.type);if(o.status==="create_track")return{status:"create_track",trackType:e.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const c=s.find(y=>this.resolveTrackId(y)===l);if(!c)return{status:"missing_target_track_view",targetTrackId:l};const h=this.resolveTrackType(c)??((f=n.find(y=>y.id===l))==null?void 0:f.type)??null;if(h!==e.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:h};if(!this.hasOverlapOnTrack(e,c))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(e.type,l,t,r,n);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=n.filter(y=>y.type===e.type).map(y=>y.id),g=u.indexOf(l);for(let y=1;y<=u.length;y+=1){const S=g-y;if(S>=0){const T=u[S],v=s.find(w=>this.resolveTrackId(w)===T);if(v&&!this.hasOverlapOnTrack(e,v))return{status:"move_to_track",targetTrackId:T}}const C=g+y;if(C<u.length){const T=u[C],v=s.find(w=>this.resolveTrackId(w)===T);if(v&&!this.hasOverlapOnTrack(e,v))return{status:"move_to_track",targetTrackId:T}}}return{status:"create_track",trackType:e.type,insertionPlacement:e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary"}}planCrossTrackPreview(e,t,i,r,n,s){const o=this.planCrossTrackMove(e,t,i,r,n,s);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(e){const t=Math.max(0,e);return this.updateCurrentTime(t)}setZoom(e){const t=Math.max(ye.MIN,Math.min(ye.MAX,e));return this.updateZoom(t)}setSpeed(e){const t=Math.max(.1,Math.min(10,e));return this.updateSpeed(t)}updateSelection(e){const t=this.timelineStore.getPrimarySelectedClipId();return t===e?{previousClipId:t,nextClipId:e,changed:!1}:(e===null?this.timelineStore.clearSelection():this.timelineStore.setPrimarySelectedClipId(e),{previousClipId:t,nextClipId:e,changed:!0})}updateCurrentTime(e){const t=this.timelineStore.getCurrentTime();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setCurrentTime(e),{previousValue:t,nextValue:e,changed:!0})}updateZoom(e){const t=this.timelineStore.getZoom();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setZoom(e),{previousValue:t,nextValue:e,changed:!0})}updateSpeed(e){const t=this.timelineStore.getSpeed();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setSpeed(e),{previousValue:t,nextValue:e,changed:!0})}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}resolveTrackType(e){return typeof e.getTrackType=="function"?e.getTrackType():e.type??null}resolveTrackTargetByY(e,t,i,r){let n=t,s=null,o=null;for(const l of i){const c=jn(l.type),h=n+c;if(l.type===r&&(s===null&&(s=n),o=h),e>=n&&e<h)return{status:"existing_track",targetTrackId:l.id};n=h}return r==="text"&&s!==null&&e<s?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="video"&&s!==null&&e<s?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="audio"&&o!==null&&e>=o?{status:"create_track",insertionPlacement:"bottom_of_type_region"}:{status:"missing_target_track_by_position"}}resolvePreferredInsertionPlacement(e,t,i,r,n){let s=r;const o=n.map(d=>{const u=s,g=jn(d.type),f=u+g;return s=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:g}}).filter(d=>d.type===e),l=o.findIndex(d=>d.id===t);if(l===-1)return null;const c=o[l],h=Math.min(12,Math.max(6,Math.floor(c.height/4)));return c.role==="primary"?{insertionPlacement:e==="text"||e==="video"?"before_track":"after_track",referenceTrackId:t}:l<o.length-1&&i>=c.endY-h?{insertionPlacement:"after_track",referenceTrackId:t}:{insertionPlacement:"before_track",referenceTrackId:t}}hasOverlapOnTrack(e,t){const i=e.startTime+e.duration;return t.getClips().some(r=>r.id===e.id?!1:e.startTime<r.endTime&&i>r.startTime)}}class Dr{constructor(e,t,i,r=100){p(this,"state");p(this,"maxHistorySize",100);p(this,"onActionUndo");p(this,"onActionRedo");p(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=r,this.onActionUndo=e,this.onActionRedo=t,this.onHistoryChange=i}addAction(e){this.state.past.length>=this.maxHistorySize&&this.state.past.shift(),this.state.past.push({...e,timestamp:Date.now()}),this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}undo(){if(this.state.past.length===0)return!1;const e=this.state.past.pop();return this.state.future.push(e),this.onActionUndo(e),this.onHistoryChange&&this.onHistoryChange(),!0}redo(){if(this.state.future.length===0)return!1;const e=this.state.future.pop();return this.state.past.push(e),this.onActionRedo(e),this.onHistoryChange&&this.onHistoryChange(),!0}clear(){this.state.past=[],this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}canUndo(){return this.state.past.length>0}canRedo(){return this.state.future.length>0}getState(){return{...this.state}}createAddClipAction(e){return{type:"add_clip",data:e,timestamp:Date.now()}}createRemoveClipAction(e){return{type:"remove_clip",data:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null},timestamp:Date.now()}}createRemoveClipActionWithTrackSnapshot(e,t,i,r=null){return{type:"remove_clip",data:{clip:e,sourceTrackId:t,sourceTrackSnapshot:i,sourceTrackRestoreAnchor:r},timestamp:Date.now()}}createUpdateClipAction(e,t,i){return{type:"update_clip",data:{clipId:e,updates:t,previousState:i},timestamp:Date.now()}}createSplitClipAction(e,t,i){return{type:"split_clip",data:{originalClip:e,clip1:t,clip2:i},timestamp:Date.now()}}createMoveClipAction(e,t,i){return{type:"move_clip",data:{clipId:e,newStartTime:t,previousStartTime:i},timestamp:Date.now()}}createResizeClipAction(e,t,i,r,n){return{type:"resize_clip",data:{clipId:e,newDuration:t,newStartTime:i,previousDuration:r,previousStartTime:n},timestamp:Date.now()}}createSetTimeAction(e,t){return{type:"set_time",data:{newTime:e,previousTime:t},timestamp:Date.now()}}createRemoveGapsAction(e){return{type:"remove_gaps",data:{clipsBefore:e},timestamp:Date.now()}}createMultiClipUpdateAction(e){return{type:"multi_clip_update",data:{clipUpdates:e},timestamp:Date.now()}}createMoveClipBetweenTracksAction(e,t,i,r,n,s,o){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:r,clipAfter:n,sourceTrackSnapshot:s,targetTrackSnapshot:o},timestamp:Date.now()}}createSeparateClipAudioAction(e,t,i,r){return{type:"separate_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createRestoreClipAudioAction(e,t,i,r){return{type:"restore_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createCompoundAction(e,t){return{type:"compound",data:{actions:e,...t?{label:t}:{}},timestamp:Date.now()}}}class Zn{constructor(e){this.target=e}executeUndo(e){this.executeUndoInternal(e,new Map)}executeRedo(e){this.executeRedoInternal(e,new Map)}executeUndoInternal(e,t){var i,r;switch(e.type){case"add_clip":this.target.removeClip(e.data.id);break;case"remove_clip":{const n=this.normalizeRemoveClipActionData(e.data);let s=!1;const o=this.resolveTrackIdForHistorySnapshot(n.sourceTrackSnapshot,n.sourceTrackId,t,n.sourceTrackRestoreAnchor);if(o&&(s=this.target.addClipToTrack(o,n.clip)),!s){const l=this.target.findTrackByClipId(n.clip.id)||this.target.getDefaultTrack();l==null||l.addClip(n.clip)}(r=(i=this.target).loadClipThumbnails)==null||r.call(i,n.clip);break}case"update_clip":this.target.updateClip(e.data.clipId,e.data.previousState);break;case"split_clip":{this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id);const n=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack();n==null||n.addClip(e.data.originalClip);break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.previousStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.previousDuration,startTime:e.data.previousStartTime});break;case"remove_gaps":this.target.getClips().forEach(n=>this.target.removeClip(n.id)),e.data.clipsBefore.forEach(n=>{const s=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();s==null||s.addClip(n)});break;case"multi_clip_update":e.data.clipUpdates.forEach(n=>{this.target.updateClip(n.clipId,n.previousState)});break;case"move_clip_between_tracks":this.restoreMovedClip(e.data.clipId,e.data.sourceTrackSnapshot,e.data.clipBefore,t);break;case"separate_clip_audio":e.data.audioClip&&this.target.removeClip(e.data.audioClip.id),this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"compound":[...e.data.actions].reverse().forEach(n=>{this.executeUndoInternal(n,t)});break;default:G.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:e.type})}}executeRedoInternal(e,t){var i,r;switch(e.type){case"add_clip":{const n=e.data,s=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();s==null||s.addClip(n),(r=(i=this.target).loadClipThumbnails)==null||r.call(i,n);break}case"remove_clip":this.target.removeClip(e.data.clip.id);break;case"update_clip":this.target.updateClip(e.data.clipId,e.data.updates);break;case"split_clip":{this.target.removeClip(e.data.originalClip.id);const n=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack();n==null||n.addClip(e.data.clip1),n==null||n.addClip(e.data.clip2);break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.newStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.newDuration,startTime:e.data.newStartTime});break;case"remove_gaps":this.target.removeClipGaps();break;case"multi_clip_update":e.data.clipUpdates.forEach(n=>{this.target.updateClip(n.clipId,n.newState)});break;case"move_clip_between_tracks":this.restoreMovedClip(e.data.clipId,e.data.targetTrackSnapshot,e.data.clipAfter,t);break;case"separate_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter),e.data.audioClip&&e.data.audioTrackId&&this.target.addClipToTrack(e.data.audioTrackId,e.data.audioClip);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter);break;case"compound":e.data.actions.forEach(n=>{this.executeRedoInternal(n,t)});break;default:G.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:e.type})}}restoreMovedClip(e,t,i,r){const n=this.resolveTrackIdForHistorySnapshot(t,(t==null?void 0:t.id)??null,r,null);n&&this.target.moveClipToTrack(e,n),this.target.updateClip(e,i)}normalizeRemoveClipActionData(e){return"clip"in e?e:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null}}resolveTrackIdForHistorySnapshot(e,t,i,r){const n=(e==null?void 0:e.id)??t??null;if(n){const o=i.get(n);if(o)return o}if(!e)return t;const s=this.target.ensureTrackFromHistorySnapshot(e,this.resolveRestoreAnchor(r,i))??t;return n&&s&&i.set(n,s),s}resolveRestoreAnchor(e,t){return e?{previousTrackId:e.previousTrackId?t.get(e.previousTrackId)??e.previousTrackId:null,nextTrackId:e.nextTrackId?t.get(e.nextTrackId)??e.nextTrackId:null}:null}}const zh=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],Vh=new Set(["thumbnails"]);function Uh(a,e){return Object.is(a,e)?!0:a===void 0||e===void 0?!1:typeof a=="object"&&typeof e=="object"?JSON.stringify(a)===JSON.stringify(e):!1}class Jn{constructor(e){this.history=e}createAddClipAction(e){return this.history.createAddClipAction(e)}recordAddClip(e){const t=this.history.createAddClipAction(e);return this.history.addAction(t),t}createRemoveClipAction(e,t=null,i=null,r=null){return t||i?this.history.createRemoveClipActionWithTrackSnapshot(e,t,i,r):this.history.createRemoveClipAction(e)}recordRemoveClip(e,t=null,i=null,r=null){const n=this.createRemoveClipAction(e,t,i,r);return this.history.addAction(n),n}recordClipUpdate(e,t,i){const r=this.createClipUpdateAction(e,t,i);return r?(this.history.addAction(r),r):null}recordSplitClip(e,t){const i={...e,id:e.id.replace("_split_",""),duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},r=this.history.createSplitClipAction(i,e,t);return this.history.addAction(r),r}recordRemoveGaps(e){if(e.length===0)return null;const t=this.history.createRemoveGapsAction(e);return this.history.addAction(t),t}recordMoveClipBetweenTracks(e,t,i,r,n,s,o){const l=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,s,o);return this.history.addAction(l),l}recordSeparateClipAudio(e,t,i,r){const n=this.history.createSeparateClipAudioAction(e,t,i,r);return this.history.addAction(n),n}recordRestoreClipAudio(e,t,i,r){const n=this.history.createRestoreClipAudioAction(e,t,i,r);return this.history.addAction(n),n}createSeparateClipAudioAction(e,t,i,r){return this.history.createSeparateClipAudioAction(e,t,i,r)}createRestoreClipAudioAction(e,t,i,r){return this.history.createRestoreClipAudioAction(e,t,i,r)}recordCompoundAction(e,t){if(e.length===0)return null;const i=this.history.createCompoundAction(e,t);return this.history.addAction(i),i}createClipUpdateAction(e,t,i){if(i&&i.length>0)return this.history.createMultiClipUpdateAction(i);if(!t)return null;if(t.startTime!==e.startTime&&t.duration===e.duration)return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);if(t.duration!==e.duration)return this.history.createResizeClipAction(e.id,e.duration,e.startTime,t.duration,t.startTime);const s={},o={};return zh.forEach(c=>{Uh(e[c],t[c])||(s[c]=e[c],o[c]=t[c])}),Object.keys(s).length===0||Object.keys(s).every(c=>Vh.has(c))?null:this.history.createUpdateClipAction(e.id,s,o)}}function Pi(a){var e;a.notifySelectionChange(),(e=a.emitSelectionChangeEvent)==null||e.call(a),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function Wh(a){var e,t,i;a.notifySelectionChange(),(e=a.emitSelectionChangeEvent)==null||e.call(a),(t=a.reloadClipThumbnailsIfNeeded)==null||t.call(a),(i=a.checkTrackDurationChange)==null||i.call(a),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function Yh(a,e,t=!1){if(!e||!t||a.type==="audio")return!1;const i=e.duration!==a.duration,r=e.startTimeAtSource!==a.startTimeAtSource||e.endTimeAtSource!==a.endTimeAtSource;return i||r}function Xh(a,e){if(a.length===0)return!1;const t=Math.max(...a.map(i=>i.endTime));return e<t}function qh(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 jh(a){const e=!a.id&&a.startTime>0;return{shouldJumpToTime:e,jumpTime:e?a.startTime:null,shouldSelectClip:!!a.id}}function Mi(a){var e;return a.applied?(a.isExecutingHistoryAction||(e=a.recordHistory)==null||e.call(a),a.applyEffects(),!0):!1}function Kh(a){return Mi({applied:a.applied,isExecutingHistoryAction:a.isExecutingHistoryAction,recordHistory:()=>{var e;(e=a.recordMoveClipBetweenTracks)==null||e.call(a,a.clipId,a.sourceTrackId,a.targetTrackId,a.clipBefore,a.clipAfter,a.sourceTrackSnapshot,a.targetTrackSnapshot)},applyEffects:a.applyEffects})}function Zh(a){var e;a.isExecutingHistoryAction||(e=a.recordSplitClip)==null||e.call(a,a.clip1,a.clip2),a.emitClipUpdated(a.clip1),a.emitClipAdded(a.clip2),a.applyEffects()}class Jh{constructor(e){p(this,"container",null);p(this,"statusElement",null);p(this,"detailElement",null);p(this,"actionElement",null);p(this,"onRetry");this.onRetry=e}mount(e){this.container=e,this.container.className="timeline-preview-pending-overlay",this.container.style.position="absolute",this.container.style.inset="0",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="center",this.container.style.flexDirection="column",this.container.style.gap="8px",this.container.style.background=ui.background,this.container.style.color=ui.text,this.container.style.fontSize="13px",this.container.style.zIndex="2000";const t=document.createElement("div");t.className="timeline-preview-pending-overlay__status",t.style.fontWeight="600";const i=document.createElement("div");i.className="timeline-preview-pending-overlay__detail",i.style.opacity="0.88";const r=document.createElement("button");r.className="timeline-preview-pending-overlay__action",r.style.display="none",r.style.padding="6px 12px",r.style.border="0",r.style.borderRadius="6px",r.style.cursor="pointer",r.style.background=ui.actionBackground,r.style.color=ui.actionText,r.textContent="刷新重试",r.addEventListener("click",this.onRetry),this.container.appendChild(t),this.container.appendChild(i),this.container.appendChild(r),this.statusElement=t,this.detailElement=i,this.actionElement=r}update(e){if(!this.container||!this.statusElement||!this.detailElement||!this.actionElement)return;const{pendingState:t,runtimeState:i}=e;if(!t){this.container.style.display="none",this.actionElement.style.display="none";return}if(this.container.style.display="flex",t.errorMessage||i.phase==="failed"){this.statusElement.textContent="资源加载异常",this.detailElement.textContent=t.errorMessage||i.errorMessage||"资源加载异常,请刷新重试",this.actionElement.style.display="inline-flex";return}const r=t.loadingPending>0||i.loadingCount>0;this.statusElement.textContent=r?"资源加载中…":"正在缓冲预览…",this.detailElement.textContent=r?`目标时间 ${Math.round(t.targetTime)}ms,待加载资源 ${Math.max(t.loadingPending,i.loadingCount)} 个`:`目标时间 ${Math.round(t.targetTime)}ms,等待媒体可播放`,this.actionElement.style.display="none"}destroy(){var e,t;(e=this.actionElement)==null||e.removeEventListener("click",this.onRetry),(t=this.container)==null||t.remove(),this.container=null,this.statusElement=null,this.detailElement=null,this.actionElement=null}}const hr={x:.5,y:.5,scale:1},Qh=.1,ed=8;function dr(a,e){return typeof a=="number"&&Number.isFinite(a)?a:e}function td(a){return Math.min(ed,Math.max(Qh,a))}function ke(a){return{x:dr(a==null?void 0:a.x,hr.x),y:dr(a==null?void 0:a.y,hr.y),scale:td(dr(a==null?void 0:a.scale,hr.scale))}}function jr(a,e,t=1e-4){const i=ke(a),r=ke(e);return Math.abs(i.x-r.x)<=t&&Math.abs(i.y-r.y)<=t&&Math.abs(i.scale-r.scale)<=t}function Pa(a,e){if(a.width<=0||a.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const t=e.width>0?e.width:a.width,i=e.height>0?e.height:a.height,r=t/i,n=a.width/a.height;let s=a.width,o=a.height;r>n?o=s/r:s=o*r;const l=(a.width-s)/2,c=(a.height-o)/2;return{left:l,top:c,width:s,height:o,centerX:l+s/2,centerY:c+o/2}}function Qn(a,e,t){const i=Pa(a,e),r=ke(t),n=i.width*r.scale,s=i.height*r.scale,o=a.width*r.x,l=a.height*r.y;return{left:o-n/2,top:l-s/2,width:n,height:s,centerX:o,centerY:l}}function _a(a,e,t,i){const r=ke(a),n=i.width>0?i.width:1,s=i.height>0?i.height:1;return ke({x:r.x+e/n,y:r.y+t/s,scale:r.scale})}function id(a,e,t,i,r,n){const s=ke(n),o=Math.max(r.width/2,1),l=Math.max(r.height/2,1),c=Math.abs(t-a)/o,h=Math.abs(i-e)/l;return ke({x:s.x,y:s.y,scale:Math.max(c,h)})}function es(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}class rd{constructor(e={}){p(this,"frameElement",null);p(this,"overlayElement",null);p(this,"boxElement",null);p(this,"handleElements",new Map);p(this,"handlePointerDownHandlers",new Map);p(this,"state",null);p(this,"interaction",null);p(this,"callbacks");p(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});p(this,"boundPointerUp",()=>{this.finishInteraction(!0)});p(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});p(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});p(this,"handleMovePointerDown",e=>{var i,r;const t=e;(t.button??0)!==0||!this.state||((i=t.preventDefault)==null||i.call(t),(r=t.stopPropagation)==null||r.call(t),this.interaction={clipId:this.state.clipId,mode:"move",pointerStart:this.toLocalPoint(t),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing"},this.setGlobalCursor("grabbing"),this.bindDocumentListeners())});this.callbacks=e}attach(e){if(this.frameElement===e&&this.overlayElement){this.render();return}this.detach(),this.frameElement=e;const t=document.createElement("div");t.className="timeline-preview-transform-overlay",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="3000";const i=document.createElement("div");i.className="timeline-preview-transform-box",i.style.position="absolute",i.style.display="none",i.style.boxSizing="border-box",i.style.border=`1px solid ${Ki.border}`,i.style.cursor="grab",i.style.pointerEvents="auto",i.style.userSelect="none",i.addEventListener("pointerdown",this.handleMovePointerDown),t.appendChild(i),this.overlayElement=t,this.boxElement=i,this.createHandle("top-left","nwse-resize"),this.createHandle("top-right","nesw-resize"),this.createHandle("bottom-right","nwse-resize"),this.createHandle("bottom-left","nesw-resize"),e.appendChild(t),this.render()}detach(){var e,t;this.finishInteraction(!1),(e=this.boxElement)==null||e.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,r)=>{const n=this.handlePointerDownHandlers.get(r);n&&i.removeEventListener("pointerdown",n)}),this.handleElements.clear(),this.handlePointerDownHandlers.clear(),(t=this.overlayElement)==null||t.remove(),this.overlayElement=null,this.boxElement=null,this.frameElement=null,this.state=null}sync(e){if(!e){this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==e.clipId&&this.finishInteraction(!1),this.state=e,this.render()}createHandle(e,t){if(!this.boxElement)return;const i=document.createElement("div");i.className=`timeline-preview-transform-handle timeline-preview-transform-handle--${e}`,i.style.position="absolute",i.style.width="10px",i.style.height="10px",i.style.border=`1px solid ${Ki.border}`,i.style.background=Ki.handleBackground,i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=t,i.style.boxSizing="border-box",i.style.transform="translate(-50%, -50%)";const r=this.getHandlePointerDown(e);i.addEventListener("pointerdown",r),this.handleElements.set(e,i),this.handlePointerDownHandlers.set(e,r),this.boxElement.appendChild(i)}getHandlePointerDown(e){return t=>{var n,s;const i=t;if((i.button??0)!==0||!this.state)return;(n=i.preventDefault)==null||n.call(i),(s=i.stopPropagation)==null||s.call(i);const r=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize";this.interaction={clipId:this.state.clipId,mode:"scale",pointerStart:this.toLocalPoint(i),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:r},this.setGlobalCursor(r),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,r,n,s;const e=this.getDocument();e&&((t=e.addEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.addEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.addEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(s=(n=globalThis.window)==null?void 0:n.addEventListener)==null||s.call(n,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,r,n,s;const e=this.getDocument();e&&((t=e.removeEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.removeEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.removeEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(s=(n=globalThis.window)==null?void 0:n.removeEventListener)==null||s.call(n,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var n,s,o;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const t=e;(n=t.preventDefault)==null||n.call(t);const i=this.toLocalPoint(t);let r=this.interaction.startTransform;if(this.interaction.mode==="move")r=_a(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,c=this.interaction.startTransform.y*this.interaction.frameSize.height;r=id(l,c,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!jr(this.interaction.startTransform,r),(o=(s=this.callbacks).onPreviewTransformChange)==null||o.call(s,this.interaction.clipId,r)}finishInteraction(e){var i,r,n,s;const t=this.interaction;if(!t){this.setGlobalCursor(null),this.unbindDocumentListeners();return}e&&t.changed&&((r=(i=this.callbacks).onPreviewTransformCommit)==null||r.call(i,t.clipId,t.nextTransform)),(s=(n=this.callbacks).onPreviewTransformChange)==null||s.call(n,t.clipId,null),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners()}render(){if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none");return}const{displayRect:e}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${e.left}px`,this.boxElement.style.top=`${e.top}px`,this.boxElement.style.width=`${e.width}px`,this.boxElement.style.height=`${e.height}px`,this.positionHandle("top-left",0,0),this.positionHandle("top-right",e.width,0),this.positionHandle("bottom-right",e.width,e.height),this.positionHandle("bottom-left",0,e.height)}positionHandle(e,t,i){const r=this.handleElements.get(e);r&&(r.style.left=`${t}px`,r.style.top=`${i}px`)}toLocalPoint(e){const t=this.getFrameBounds();return{x:(e.clientX??0)-t.left,y:(e.clientY??0)-t.top}}getFrameBounds(){var t,i;if(!this.frameElement)return{left:0,top:0,width:0,height:0};const e=(i=(t=this.frameElement).getBoundingClientRect)==null?void 0:i.call(t);return e&&Number.isFinite(e.width)&&Number.isFinite(e.height)?{left:e.left,top:e.top,width:e.width,height:e.height}:{left:es(this.frameElement.style.left),top:es(this.frameElement.style.top),width:this.frameElement.clientWidth,height:this.frameElement.clientHeight}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}setGlobalCursor(e){var i;const t=(i=this.getDocument())==null?void 0:i.body;t&&(t.style.cursor=e||"")}}const nd=0,sd=2,ad=250,od=2,ld=120,ts="Arial, sans-serif";function cd(a,e){const t=Math.max(0,Math.round(a));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let n=-t;n<=t;n+=1)n===0&&r===0||i.push(`${n}px ${r}px 0 ${e}`);return i.join(", ")}function Ia(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function ur(a){return`"${Ia(a)}"`}function hd(a){return Fr(a,Br)}function dd(a,e){return!Ct(a.mode)||!e?a:{mode:Ee.mode,width:e.width,height:e.height}}function it(a){return a.getAttribute("src")||a.currentSrc||a.src||""}function Ui(a){return typeof HTMLVideoElement<"u"?a instanceof HTMLVideoElement:a.tagName==="VIDEO"}function Fe(a){try{a.load()}catch{}}function He(a){try{a.pause()}catch{}}function ud(a){var e;try{const t=a.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function is(a,e){try{a.currentTime=Math.max(0,e)}catch{}}function _i(a,e){var i;const t=(i=a==null?void 0:a.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function rs(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}function pd(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function gd(a){const e=a.buffered;if(!e||typeof e.length!="number"||e.length<=0)return null;try{return Number(e.end(e.length-1).toFixed(3))}catch{return null}}function he(a){return{tsMs:pd(),currentTime:Number.isFinite(a.currentTime)?Number(a.currentTime.toFixed(3)):null,duration:Number.isFinite(a.duration)?Number(a.duration.toFixed(3)):null,currentSrc:it(a)||null,readyState:typeof a.readyState=="number"?a.readyState:null,networkState:typeof a.networkState=="number"?a.networkState:null,paused:typeof a.paused=="boolean"?a.paused:null,ended:typeof a.ended=="boolean"?a.ended:null,playbackRate:typeof a.playbackRate=="number"?Number(a.playbackRate.toFixed(3)):null,bufferedEnd:gd(a),videoWidth:Ui(a)?a.videoWidth:null,videoHeight:Ui(a)?a.videoHeight:null,error:a.error?{code:typeof a.error.code=="number"?a.error.code:null,message:a.error.message??null}:null}}function fd(a,e,t){const i=e||a.clip.src||"";switch(t){case"abort":case"emptied":return`${a.clip.id}:${i}:${t}`;case"error":case"reconcile":case"stalled":return`${a.clip.id}:${i}:${Math.floor(a.mediaTime/ad)}`;default:return`${a.clip.id}:${i}`}}function tt(a){return typeof(a==null?void 0:a.then)=="function"}function md(a,e){var t;return((t=a.entry)==null?void 0:t.clip.id)===e}function yd(a,e){var u;const t=a.activeClips.filter(g=>g.trackType!=="text"),i=a.nextClips.filter(g=>g.trackType!=="text"),r=a.interactionMode??"steady",n=new Map(t.map(g=>[g.trackId,g])),s=new Map(i.map(g=>[g.trackId,g])),o=new Map,l=t.filter(g=>g.trackType==="video"&&g.hasVisual).sort((g,f)=>g.trackOrder-f.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(g,f)=>!s.has(g)||r!=="steady"&&c?!1:c?a.playState==="playing"&&f==="video"&&g===h:a.playState!=="playing"||t.length<=1;return e.forEach(g=>{o.set(g.trackId,{kind:g.kind,order:g.order})}),t.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),i.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),Array.from(o.entries()).map(([g,f])=>{const y=n.get(g)||null,S=d(g,f.kind)&&s.get(g)||null;return{trackId:g,kind:f.kind,order:f.order,current:{role:"current",entry:y,playState:a.playState,speed:a.speed,visible:!!(y!=null&&y.hasVisual),zIndex:y?1e3-y.trackOrder:0,syncRequestId:a.syncRequestId},preload:{role:"preload",entry:S,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:a.syncRequestId}}}).sort((g,f)=>g.order-f.order)}class Sd{constructor(e={},t={}){p(this,"container",null);p(this,"rootElement",null);p(this,"frameElement",null);p(this,"textOverlayRoot",null);p(this,"pendingOverlayElement",null);p(this,"pendingOverlayRenderer");p(this,"resizeObserver",null);p(this,"trackSlots",new Map);p(this,"textPreviewEntries",new Map);p(this,"audioContext",null);p(this,"masterGainNode",null);p(this,"loadingCount",0);p(this,"isBuffering",!1);p(this,"bufferingVisibleTimeoutId",null);p(this,"lastRuntimeSignature",null);p(this,"lastRuntimeState",{phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]});p(this,"lastSettledSyncRequestId",null);p(this,"primarySelectedClipId",null);p(this,"transientVisualTransform",null);p(this,"textPreviewDragState",null);p(this,"textPreviewFontStyleElement",null);p(this,"textPreviewFontSignature",null);p(this,"textPreviewFontLoadState","idle");p(this,"textPreviewFontLoadToken",0);p(this,"callbacks");p(this,"dependencies");p(this,"transformOverlay");p(this,"boundTextPreviewPointerMove",e=>{this.handleTextPreviewPointerMove(e)});p(this,"boundTextPreviewPointerUp",()=>{this.finishTextPreviewDrag(!0)});p(this,"boundTextPreviewVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishTextPreviewDrag(!1)});p(this,"boundTextPreviewWindowBlur",()=>{this.finishTextPreviewDrag(!1)});p(this,"requestedAspectRatio",{...Ee});p(this,"resolvedAutoAspectRatio",null);p(this,"aspectRatioProbe",null);p(this,"aspectRatioProbeSrc",null);p(this,"aspectRatioProbeResolveToken",0);p(this,"isAspectRatioProbeLoading",!1);p(this,"pendingState",null);p(this,"activeSyncRequestId");p(this,"isSyncProjecting",!1);p(this,"deferredPreloadSlotKeys",new Set);p(this,"deferredPreloadFlushScheduled",!1);this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new Jh(()=>{var i,r;(r=(i=this.callbacks).onPendingPreviewRetry)==null||r.call(i)}),this.transformOverlay=new rd({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,r)=>{var n,s;(s=(n=this.callbacks).onVisualTransformCommit)==null||s.call(n,i,r)}})}emitDiagnostic(e,t,i,r={}){var o,l;const n=this.dependencies.diagnostics;if(!n)return;const s=((l=(o=this.dependencies).getDiagnosticsContext)==null?void 0:l.call(o))??{};n.emit({...s,...r,severity:e,category:t,eventName:i,runtimeState:ca(s.runtimeState,r.runtimeState)})}buildSlotTraceData(e,t={}){var i;return{...t,trackId:e.trackId,clipId:((i=e.entry)==null?void 0:i.clip.id)??null,slotKey:`${e.trackId}:${e.role}`,desiredSourceUrl:e.desiredSource,actualSourceUrl:it(e.element)||null,extra:{role:e.role,kind:e.kind,phase:e.phase,retryCount:e.retryCount,...t.extra??{}}}}hasPreview(){return!!this.container}attach(e){if(this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e;const t=document.createElement("div");t.className=this.dependencies.rootClassName??"timeline-preview-root",t.style.position="relative",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden";const i=document.createElement("div");i.className=this.dependencies.frameClassName??"timeline-preview-frame",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.overflow="hidden",i.style.background=E.black,t.appendChild(i);const r=document.createElement("div");r.className="timeline-preview-text-layer",r.style.position="absolute",r.style.inset="0",r.style.pointerEvents="none",r.style.zIndex="2000",i.appendChild(r);const n=document.createElement("div");t.appendChild(n),this.pendingOverlayRenderer.mount(n),e.appendChild(t),this.rootElement=t,this.frameElement=i,this.textOverlayRoot=r,this.pendingOverlayElement=n,this.transformOverlay.attach(i),this.ensureTextPreviewFontReady(),this.emitDiagnostic("info","session","preview.attach",{message:"Preview attached",extra:{containerWidth:e.clientWidth,containerHeight:e.clientHeight}}),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(e)),this.updateFrameLayout(),this.refreshPendingOverlay(),this.refreshRuntimeState()}detach(){var e,t,i,r,n,s;this.emitDiagnostic("info","session","preview.detach",{message:"Preview detached",extra:{slotCount:this.trackSlots.size}}),(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,this.transformOverlay.detach(),this.finishTextPreviewDrag(!1),this.pendingOverlayRenderer.destroy();for(const o of this.trackSlots.values())this.destroySlot(o.current),this.destroySlot(o.preload);this.trackSlots.clear(),this.clearTextPreviewEntries(),this.resetTextPreviewFontState(),this.aspectRatioProbe&&(He(this.aspectRatioProbe),this.aspectRatioProbe.src="",Fe(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.aspectRatioProbeResolveToken+=1,this.isAspectRatioProbeLoading=!1,this.audioContext&&((n=(i=(t=this.audioContext).close)==null?void 0:(r=i.call(t)).catch)==null||n.call(r,()=>{}),this.audioContext=null,this.masterGainNode=null),(s=this.rootElement)==null||s.remove(),this.rootElement=null,this.frameElement=null,this.textOverlayRoot=null,this.pendingOverlayElement=null,this.container=null,this.primarySelectedClipId=null,this.transientVisualTransform=null,this.pendingState=null,this.activeSyncRequestId=void 0,this.isSyncProjecting=!1,this.loadingCount=0,this.isBuffering=!1,this.clearBufferingVisibleTimeout(),this.lastRuntimeSignature=null,this.lastSettledSyncRequestId=null,this.lastRuntimeState={phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]},this.refreshPendingOverlay(),this.refreshRuntimeState()}setPendingState(e){this.pendingState=e,this.refreshPendingOverlay()}sync(e){var s;if(!this.rootElement||!this.frameElement)return;this.primarySelectedClipId=e.primarySelectedClipId??null,this.activeSyncRequestId=e.syncRequestId,this.emitDiagnostic("info","playback","preview.sync.requested",{message:"Preview sync requested",syncRequestId:e.syncRequestId??null,runtimeState:{currentTimeMs:e.currentTime,playState:e.playState,speed:e.speed,activeClipIds:e.activeClips.map(o=>o.clip.id)},extra:{activeClipCount:e.activeClips.length,nextClipCount:e.nextClips.length,autoAspectRatioClipId:((s=e.autoAspectRatioClip)==null?void 0:s.clip.id)??null}}),this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.textPreviewDragState&&this.textPreviewDragState.clipId!==this.primarySelectedClipId&&this.finishTextPreviewDrag(!1),this.maybeResolveAutoAspectRatio(e.autoAspectRatioClip),this.syncTextPreviewEntries(e.activeClips.filter(o=>o.trackType==="text"));const t=Array.from(this.trackSlots.entries()).map(([o,l],c)=>{var h,d;return{trackId:o,kind:l.current.kind,order:((h=l.current.entry)==null?void 0:h.trackOrder)??((d=l.preload.entry)==null?void 0:d.trackOrder)??1e4+c}}),n=yd(e,t).map(o=>this.applyTrackPlan(o)).filter(o=>tt(o));if(this.isSyncProjecting=n.length>0,this.refreshVisualLayout(),this.refreshRuntimeState(),n.length===0){this.refreshVisualLayout(),this.refreshRuntimeState();return}Promise.all(n).then(()=>{this.activeSyncRequestId===e.syncRequestId&&(this.isSyncProjecting=!1,this.refreshVisualLayout(),this.refreshRuntimeState())}).catch(o=>{this.emitDiagnostic("error","playback","preview.sync.failed",{message:"Preview sync failed",syncRequestId:e.syncRequestId??null,error:o}),G.warn("TimelinePreviewSession","preview sync failed",{error:o,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=Ve(e),this.updateFrameLayout()}getAspectRatio(){return dd(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}createMediaElement(e,t){const i=this.dependencies.createMediaElement,r=i?i(e,t):document.createElement(e==="video"?"video":"audio");return r.preload=t==="preload"?"auto":"metadata",r.crossOrigin="anonymous",r.loop=!1,r.controls=!1,Ui(r)?(r.playsInline=!0,r.disablePictureInPicture=!0,r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.objectFit="fill",r.style.background=E.black,r.style.pointerEvents="none"):r.style.display="none",r}createSlot(e,t,i){var T,v;const r=this.createMediaElement(t,i),n=t==="video"?document.createElement("div"):null;if(n){const w=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";n.className=`${w} timeline-preview-slot--${e} timeline-preview-slot--${i}`,n.style.position="absolute",n.style.overflow="hidden",n.style.background=E.black,n.style.pointerEvents="none",n.style.display="none",n.appendChild(r),(T=this.frameElement)==null||T.appendChild(n)}const s={role:i,trackId:e,kind:t,wrapper:n,element:r,entry:null,desiredSource:null,requestedPlayState:"paused",isActive:!1,isLoading:!1,isBuffering:!1,isSeeking:!1,phase:"idle",errorMessage:null,retryCount:0,recoveryKey:null,sourceNode:null,gainNode:null,audioRoutingFailed:!1,consecutiveStalledCount:0,forceRecover:!1,expectedEmptiedEvents:0,recoverableEventCount:0,loadStartedSinceRecover:!1,resolveToken:0,applyToken:0,cleanup:[]},o=()=>{s.isLoading=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=null,this.resetSlotRecoveryTracking(s),s.consecutiveStalledCount=0,s.entry?s.phase=s.isActive?"active":"primed":s.phase="idle",this.tryResolveAutoAspectRatioFromSlot(s),this.refreshVisualLayout(),this.refreshRuntimeState()},l=()=>{if(!s.entry){s.isLoading=!1,s.phase="idle",this.refreshRuntimeState();return}this.emitDiagnostic("info","playback","media.loadstart",this.buildSlotTraceData(s,{message:"Media load started",mediaState:he(s.element)})),s.isLoading=!0,s.loadStartedSinceRecover=!0,s.phase!=="recovering"&&(s.phase="binding"),this.refreshRuntimeState()},c=w=>{this.emitDiagnostic("info","playback",`media.${w.type}`,this.buildSlotTraceData(s,{message:`Media event: ${w.type}`,mediaState:he(s.element)})),o()},h=()=>{this.emitDiagnostic("warn","playback","media.waiting",this.buildSlotTraceData(s,{message:"Media waiting",mediaState:he(s.element),extra:{active:s.isActive}})),s.isBuffering=s.isActive&&!s.element.paused,this.refreshRuntimeState()},d=()=>{this.emitDiagnostic("warn","playback","media.stalled",this.buildSlotTraceData(s,{message:"Media stalled",mediaState:he(s.element),extra:{active:s.isActive}})),s.isBuffering=s.isActive&&!s.element.paused,s.consecutiveStalledCount+=1,this.refreshRuntimeState(),s.isActive&&s.consecutiveStalledCount>=od&&this.recoverSlot(s,"stalled")},u=()=>{if(!s.entry){s.isSeeking=!1,s.phase="idle",this.refreshRuntimeState();return}this.emitDiagnostic("debug","playback","media.seeking",this.buildSlotTraceData(s,{message:"Media seeking",mediaState:he(s.element),extra:{active:s.isActive}})),s.isSeeking=!0,this.refreshRuntimeState()},g=()=>{this.emitDiagnostic("debug","playback","media.seeked",this.buildSlotTraceData(s,{message:"Media seeked",mediaState:he(s.element)})),s.isSeeking=!1,s.isBuffering=!1,s.entry&&s.phase!=="failed"&&(s.phase=s.isActive?"active":"primed"),this.refreshRuntimeState()},f=w=>{var x;if(!this.shouldIgnoreClearedSlotRecoverableEvent(s)){if(w==="abort"&&this.shouldIgnoreExpectedAbort(s)){this.emitDiagnostic("debug","playback","media.abort.ignored",this.buildSlotTraceData(s,{message:"Ignored expected media abort during source reset",mediaState:he(s.element)}));return}if(w==="emptied"&&this.shouldIgnoreExpectedEmptied(s)){this.emitDiagnostic("debug","playback","media.emptied.ignored",this.buildSlotTraceData(s,{message:"Ignored expected media emptied during source reset",mediaState:he(s.element)}));return}if(this.emitDiagnostic(w==="error"?"error":"warn","playback",`media.${w}`,this.buildSlotTraceData(s,{message:`Media event: ${w}`,mediaState:he(s.element),error:s.element.error})),G.warn("TimelinePreviewSession",`media event: ${w}`,{trackId:s.trackId,role:s.role,clipId:((x=s.entry)==null?void 0:x.clip.id)??null,phase:s.phase,mediaState:he(s.element)}),s.forceRecover=!0,s.expectedEmptiedEvents=0,s.isLoading=!1,s.isSeeking=!1,s.isBuffering=!1,s.recoverableEventCount+=1,this.shouldSkipImmediatePreloadRecovery(s)){s.phase="idle",this.emitDiagnostic("info","recovery","preload.recovery.skipped",this.buildSlotTraceData(s,{message:"Skipped immediate preload recovery after recoverable media event",mediaState:he(s.element),extra:{reason:w,recoverableEventCount:s.recoverableEventCount,loadStartedSinceRecover:s.loadStartedSinceRecover}})),this.refreshRuntimeState();return}if(this.refreshRuntimeState(),this.shouldDeferPreloadRecovery(s)){this.deferPreloadRecovery(s,w);return}this.recoverSlot(s,w)}},y=()=>f("abort"),S=()=>f("emptied"),C=()=>f("error");return r.addEventListener("loadstart",l),r.addEventListener("loadedmetadata",c),r.addEventListener("canplay",c),r.addEventListener("playing",c),r.addEventListener("waiting",h),r.addEventListener("stalled",d),r.addEventListener("seeking",u),r.addEventListener("seeked",g),r.addEventListener("abort",y),r.addEventListener("emptied",S),r.addEventListener("error",C),s.cleanup.push(()=>r.removeEventListener("loadstart",l),()=>r.removeEventListener("loadedmetadata",c),()=>r.removeEventListener("canplay",c),()=>r.removeEventListener("playing",c),()=>r.removeEventListener("waiting",h),()=>r.removeEventListener("stalled",d),()=>r.removeEventListener("seeking",u),()=>r.removeEventListener("seeked",g),()=>r.removeEventListener("abort",y),()=>r.removeEventListener("emptied",S),()=>r.removeEventListener("error",C)),t==="audio"&&((v=this.rootElement)==null||v.appendChild(r)),s}resetSlotRecoveryTracking(e,t=!1){e.forceRecover=t,e.retryCount=0,e.recoveryKey=null,e.expectedEmptiedEvents=0,e.recoverableEventCount=0,e.loadStartedSinceRecover=!1}destroySlot(e){var t,i,r,n,s;this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.resolveToken+=1,e.applyToken+=1,e.cleanup.forEach(o=>o()),He(e.element),e.element.removeAttribute("src"),Fe(e.element),(i=(t=e.gainNode)==null?void 0:t.disconnect)==null||i.call(t),(n=(r=e.sourceNode)==null?void 0:r.disconnect)==null||n.call(r),e.gainNode=null,e.sourceNode=null,(s=e.wrapper)==null||s.remove(),e.element.remove()}getTrackSlots(e,t){const i=this.trackSlots.get(e);if(i&&i.current.kind===t&&i.preload.kind===t)return i;i&&(this.destroySlot(i.current),this.destroySlot(i.preload),this.trackSlots.delete(e));const r={current:this.createSlot(e,t,"current"),preload:this.createSlot(e,t,"preload")};return this.trackSlots.set(e,r),r}swapTrackSlots(e){const t=this.trackSlots.get(e);t&&(t.current.role="preload",t.preload.role="current",this.trackSlots.set(e,{current:t.preload,preload:t.current}))}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);e.current.entry&&md(t.preload,e.current.entry.clip.id)&&(this.swapTrackSlots(e.trackId),t=this.getTrackSlots(e.trackId,e.kind));const i=this.applySlotTarget(t.current,e.current),r=this.applySlotTarget(t.preload,e.preload);if(tt(i)||tt(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=it(e.element)||null;if(e.entry=t.entry,e.requestedPlayState=t.playState,e.isActive=t.role==="current"&&!!t.entry,e.errorMessage=t.entry?e.errorMessage:null,e.isBuffering=t.entry?e.isBuffering:!1,e.isSeeking=t.entry?e.isSeeking:!1,e.consecutiveStalledCount=t.entry?e.consecutiveStalledCount:0,!t.entry){this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),(r||n)&&this.emitDiagnostic("info","playback","slot.cleared",this.buildSlotTraceData(e,{message:"Preview slot cleared",extra:{previousClipId:(r==null?void 0:r.clip.id)??null,previousSource:n}})),He(e.element),e.desiredSource=null,e.errorMessage=null,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,this.resetSlotRecoveryTracking(e),e.element.removeAttribute("src"),Fe(e.element),e.phase="idle",this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}const s=this.resolveDesiredSource(e,t.entry,i);if(tt(s))return s.then(o=>{if(!(!o||!this.isCurrentRequest(e,i,t.entry))){if(e.desiredSource=o,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,o)){if(this.shouldDeferPreloadTarget(e,t,o)){this.deferPreloadTarget(e,t,o,"current-loading");return}return Promise.resolve(this.recoverSlot(e,"reconcile",t,i)).then(()=>{})}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.applyResolvedSlotState(e,t)}});if(!(!s||!this.isCurrentRequest(e,i,t.entry))){if(e.desiredSource=s,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,s)){if(this.shouldDeferPreloadTarget(e,t,s)){this.deferPreloadTarget(e,t,s,"current-loading");return}return this.recoverSlot(e,"reconcile",t,i)}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.applyResolvedSlotState(e,t)}}resolveDesiredSource(e,t,i){const r=this.dependencies.previewSourceResolver,n=this.dependencies.sourceMediaRegistry;if(!r)return this.decorateSlotSourceUrl(e,t.clip.src);try{const s=n?n.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>r(t.clip)):r(t.clip);if(tt(s)){e.resolveToken+=1;const o=e.resolveToken;return e.phase="binding",e.isLoading=!0,this.emitDiagnostic("info","resource","source.resolve.pending",this.buildSlotTraceData(e,{message:"Preview source resolving",sourceUrl:t.clip.src,extra:{requestToken:i,resolveToken:o}})),this.refreshRuntimeState(),s.then(l=>o!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:l?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:l.url,extra:{mimeType:l.mimeType,mediaKind:l.kind}})),this.decorateSlotSourceUrl(e,l.url)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(l=>(this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:l})),G.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:l}),this.failSlot(e,t,"预览源解析失败"),null))}return s?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:s.url,extra:{mimeType:s.mimeType,mediaKind:s.kind}})),this.decorateSlotSourceUrl(e,s.url)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)}catch(s){return this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:s})),G.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:s}),this.failSlot(e,t,"预览源解析失败"),null}}decorateSlotSourceUrl(e,t){return t}slotNeedsRecovery(e,t){const i=it(e.element);return e.forceRecover||!i||i!==t?!0:(typeof e.element.networkState=="number"?e.element.networkState:null)===nd?!(e.isLoading||e.phase==="binding"||e.phase==="recovering"):!1}recoverSlot(e,t,i,r){const n=i??(e.entry?{role:e.role,entry:e.entry,playState:e.requestedPlayState,speed:e.isActive&&e.element.playbackRate||1,visible:e.isActive&&!!e.entry.hasVisual,zIndex:e.entry?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null);if(!e.entry||!n||r!==void 0&&!this.isCurrentRequest(e,r,e.entry))return;const s=e.desiredSource??this.resolveDesiredSource(e,e.entry,e.applyToken);if(tt(s))return s.then(o=>{o&&this.finishSlotRecovery(e,t,n,o,r)});s&&this.finishSlotRecovery(e,t,n,s,r)}finishSlotRecovery(e,t,i,r,n){if(!e.entry)return;const s=fd(e.entry,r,t);if(e.recoveryKey===s){if(e.retryCount>=sd){this.isBackgroundPreloadSlot(e)?this.parkPreloadSlot(e,"媒体恢复失败,请等待下一次重建","retries-exhausted"):this.failSlot(e,e.entry,"媒体恢复失败,请刷新重试");return}e.retryCount+=1}else e.recoveryKey=s,e.retryCount=1;e.phase="recovering",e.errorMessage=null,e.forceRecover=!1,e.isLoading=!0,e.isBuffering=e.isActive&&i.playState==="playing",e.isSeeking=!1,e.consecutiveStalledCount=0,e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.refreshRuntimeState(),this.emitDiagnostic(t==="reconcile"?"info":"warn","recovery","slot.recover",this.buildSlotTraceData(e,{message:"Recovering preview slot",desiredSourceUrl:r,mediaState:he(e.element),extra:{reason:t,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState}})),G.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:r,mediaState:he(e.element)});const l=!!it(e.element)||t!=="reconcile"||e.retryCount>1;He(e.element),e.expectedEmptiedEvents=l?2:1,l&&(e.element.removeAttribute("src"),Fe(e.element)),e.element.setAttribute("src",r),Fe(e.element),this.emitDiagnostic("info","resource","source.assigned",this.buildSlotTraceData(e,{message:"Preview source assigned",desiredSourceUrl:r,actualSourceUrl:r,extra:{reason:t,hardReset:l}})),!(n!==void 0&&!this.isCurrentRequest(e,n,e.entry))&&this.applyResolvedSlotState(e,i)}getSlotKey(e){return`${e.trackId}:${e.role}`}isActiveCurrentSlot(e){return e.role==="current"&&e.isActive&&!!e.entry}hasBlockingActiveCurrentSlot(e){for(const{current:t}of this.trackSlots.values())if(!(e&&this.getSlotKey(t)===e)&&this.isActiveCurrentSlot(t)&&(t.isLoading||t.isSeeking||t.phase==="binding"||t.phase==="recovering"))return!0;return!1}shouldDeferPreloadTarget(e,t,i){return t.role!=="preload"||!t.entry||!this.slotNeedsRecovery(e,i)?!1:this.hasBlockingActiveCurrentSlot()}shouldDeferPreloadRecovery(e){return e.role!=="preload"||e.isActive||!e.entry?!1:this.hasBlockingActiveCurrentSlot()}buildDeferredPreloadTarget(e){return e.role!=="preload"||!e.entry?null:{role:"preload",entry:e.entry,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:this.activeSyncRequestId}}deferPreloadTarget(e,t,i,r){e.desiredSource=i,e.forceRecover=!0,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.errorMessage=null,e.element.getAttribute("src")&&e.element.getAttribute("src")!==i&&(He(e.element),e.element.removeAttribute("src"),Fe(e.element)),it(e.element)||(e.phase="idle"),this.deferredPreloadSlotKeys.add(this.getSlotKey(e)),this.emitDiagnostic("info","recovery","preload.recovery.deferred",this.buildSlotTraceData(e,{message:"Deferred preload recovery until active current media settles",desiredSourceUrl:i,extra:{reason:r,currentLoading:!0,requestedPlayState:t.playState}})),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState()}deferPreloadRecovery(e,t){this.deferredPreloadSlotKeys.add(this.getSlotKey(e)),this.emitDiagnostic("info","recovery","preload.recovery.deferred",this.buildSlotTraceData(e,{message:"Deferred preload recovery until active current media settles",extra:{reason:t,currentLoading:!0,requestedPlayState:e.requestedPlayState}})),this.scheduleDeferredPreloadFlush()}scheduleDeferredPreloadFlush(){this.deferredPreloadFlushScheduled||this.deferredPreloadSlotKeys.size===0||(this.deferredPreloadFlushScheduled=!0,queueMicrotask(()=>{this.deferredPreloadFlushScheduled=!1,this.flushDeferredPreloads()}))}flushDeferredPreloads(){if(this.deferredPreloadSlotKeys.size===0||this.hasBlockingActiveCurrentSlot())return;const e=Array.from(this.deferredPreloadSlotKeys);this.deferredPreloadSlotKeys.clear();for(const t of e){const[i,r]=t.split(":"),n=this.trackSlots.get(i),s=r==="current"?n==null?void 0:n.current:n==null?void 0:n.preload;if(!s||s.role!=="preload"||!s.entry)continue;const o=this.buildDeferredPreloadTarget(s);if(o){if(this.emitDiagnostic("info","recovery","preload.recovery.resumed",this.buildSlotTraceData(s,{message:"Resumed deferred preload recovery",desiredSourceUrl:s.desiredSource,extra:{requestedPlayState:s.requestedPlayState}})),s.desiredSource&&this.slotNeedsRecovery(s,s.desiredSource)){this.recoverSlot(s,"reconcile",o);continue}this.resetSlotRecoveryTracking(s),this.applyResolvedSlotState(s,o)}}}applyResolvedSlotState(e,t){t.entry&&(e.errorMessage=null,e.element.playbackRate=t.role==="current"?t.speed:1,t.role==="current"?this.syncCurrentSlot(e,t.entry,t.speed,t.playState):this.preparePreloadSlot(e,t.entry),!e.isLoading&&!e.isSeeking&&e.phase!=="failed"&&(e.phase=e.isActive?"active":"primed"),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState())}isCurrentRequest(e,t,i){var r;return e.applyToken===t&&((r=e.entry)==null?void 0:r.clip.id)===i.clip.id}shouldIgnoreExpectedEmptied(e){return e.phase==="recovering"&&!e.loadStartedSinceRecover?!0:e.expectedEmptiedEvents<=0?!1:e.phase!=="recovering"&&!e.isLoading?(e.expectedEmptiedEvents=0,!1):(e.expectedEmptiedEvents-=1,!0)}shouldIgnoreExpectedAbort(e){return e.phase==="recovering"&&!e.loadStartedSinceRecover}shouldIgnoreClearedSlotRecoverableEvent(e){return!e.entry&&e.phase==="idle"}shouldSkipImmediatePreloadRecovery(e){return this.isBackgroundPreloadSlot(e)?!e.loadStartedSinceRecover&&e.recoverableEventCount<2:!1}isBackgroundPreloadSlot(e){return e.role==="preload"&&!e.isActive&&!!e.entry}parkPreloadSlot(e,t,i){He(e.element),e.element.removeAttribute("src"),Fe(e.element),e.phase="idle",e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.errorMessage=null,this.resetSlotRecoveryTracking(e,!0),this.emitDiagnostic("warn","recovery","preload.recovery.parked",this.buildSlotTraceData(e,{message:"Background preload parked until next steady sync",mediaState:he(e.element),extra:{reason:i,errorMessage:t}})),this.refreshVisualLayout(),this.refreshRuntimeState()}failSlot(e,t,i){if(this.isBackgroundPreloadSlot(e)){this.parkPreloadSlot(e,i,"failed");return}e.phase="failed",e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.errorMessage=i,e.forceRecover=!1,e.expectedEmptiedEvents=0,this.emitDiagnostic("error","recovery","slot.failed",this.buildSlotTraceData(e,{message:"Preview slot failed",mediaState:he(e.element),extra:{errorMessage:i}})),G.warn("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,mediaState:he(e.element)}),this.refreshRuntimeState()}configureAudioRouting(e,t){const i=Math.max(0,Math.min(1,t.clip.volume??1)),r=t.muted?0:i;if(!t.hasAudio){e.element.muted=!0,e.element.volume=0;return}const n=this.getAudioContext();if(!n||e.audioRoutingFailed){e.element.muted=t.muted,e.element.volume=r;return}if(!e.sourceNode||!e.gainNode)try{e.sourceNode=n.createMediaElementSource(e.element),e.gainNode=n.createGain(),e.sourceNode.connect(e.gainNode),e.gainNode.connect(this.getMasterGainNode(n))}catch{e.audioRoutingFailed=!0,e.element.muted=t.muted,e.element.volume=r;return}e.element.muted=!1,e.element.volume=1,e.gainNode.gain.value=r}syncCurrentSlot(e,t,i,r){e.isActive=!0,e.entry=t,e.element.playbackRate=i;const n=t.mediaTime/1e3,s=Math.max(.1,i*.15);Math.abs(e.element.currentTime-n)>s&&(this.emitDiagnostic("debug","playback","media.current-slot.seek",this.buildSlotTraceData(e,{message:"Current slot seek applied",mediaState:he(e.element),extra:{playState:r,speed:i,fromSeconds:Number(e.element.currentTime.toFixed(3)),toSeconds:Number(n.toFixed(3)),deltaSeconds:Number(Math.abs(e.element.currentTime-n).toFixed(3)),thresholdSeconds:Number(s.toFixed(3))}})),e.isSeeking=!0,is(e.element,n)),r==="playing"?(this.resumeAudioContext(),ud(e.element)):He(e.element),this.setSlotVisible(e,t.hasVisual,1e3-t.trackOrder)}preparePreloadSlot(e,t){e.isActive=!1,e.isBuffering=!1,e.isSeeking=!1,e.entry=t,e.element.playbackRate=1,this.emitDiagnostic("debug","playback","media.preload-slot.seek",this.buildSlotTraceData(e,{message:"Preload slot primed",mediaState:he(e.element),extra:{toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3))}})),is(e.element,t.clip.startTimeAtSource/1e3),He(e.element),this.setSlotVisible(e,!1,0)}setSlotVisible(e,t,i){if(e.kind!=="video"||!e.wrapper){e.element.style.display="none";return}e.wrapper.style.display=t?"block":"none",e.wrapper.style.zIndex=String(i),e.wrapper.style.pointerEvents="none",e.element.style.display=t?"block":"none",e.element.style.zIndex=String(i)}getAudioContext(){if(this.audioContext)return this.audioContext;const e=this.dependencies.createAudioContext;if(e)return this.audioContext=e(),this.audioContext;if(typeof window>"u")return null;const t=window.AudioContext||window.webkitAudioContext;return t?(this.audioContext=new t,this.audioContext):null}getMasterGainNode(e){if(this.masterGainNode)return this.masterGainNode;const t=e.createGain();return t.gain.value=1,t.connect(e.destination),this.masterGainNode=t,t}resumeAudioContext(){var e,t,i,r;!this.audioContext||this.audioContext.state!=="suspended"||(r=(t=(e=this.audioContext).resume)==null?void 0:(i=t.call(e)).catch)==null||r.call(i,()=>{})}updateFrameLayout(){if(!this.container||!this.frameElement)return;const{width:e,height:t}=this.getAspectRatio(),i=this.container.clientWidth,r=this.container.clientHeight;if(i<=0||r<=0||e<=0||t<=0)return;const n=e/t,s=i/r;let o=i,l=r;n>s?l=i/n:o=r*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=`${(r-l)/2}px`,this.refreshVisualLayout()}maybeResolveAutoAspectRatio(e){if(!Ct(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=_i(e,"sys_width"),i=_i(e,"sys_height");if(t&&i){this.handleResolvedAutoAspectRatio(t,i);return}if(this.aspectRatioProbeSrc===e.clip.id)return;const r=++this.aspectRatioProbeResolveToken;(async()=>{const s=await this.resolveAspectRatioProbeSource(e,r);if(!s||r!==this.aspectRatioProbeResolveToken)return;const o=this.getAspectRatioProbe();this.aspectRatioProbeSrc=e.clip.id,this.isAspectRatioProbeLoading=!0,this.emitDiagnostic("info","resource","aspect-ratio.probe.start",{message:"Aspect ratio probe started",clipId:e.clip.id,sourceUrl:s}),this.refreshRuntimeState(),o.crossOrigin="anonymous",o.preload="metadata",o.muted=!0,o.src=s,Fe(o)})().catch(()=>{})}async resolveAspectRatioProbeSource(e,t){const i=this.dependencies.previewSourceResolver,r=this.dependencies.sourceMediaRegistry;if(!i)return e.clip.src;const n=r?r.getPreviewSource(this.buildPreviewSourceCacheKey(e.clip),()=>i(e.clip)):i(e.clip);if(!tt(n))return(n==null?void 0:n.url)??null;this.isAspectRatioProbeLoading=!0,this.refreshRuntimeState();const s=await n;return t!==this.aspectRatioProbeResolveToken?null:(s==null?void 0:s.url)??null}buildPreviewSourceCacheKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src}getAspectRatioProbe(){var r,n;if(this.aspectRatioProbe)return this.aspectRatioProbe;const e=((n=(r=this.dependencies).createAspectRatioProbe)==null?void 0:n.call(r))||document.createElement("video"),t=()=>{this.isAspectRatioProbeLoading=!1,this.emitDiagnostic("info","resource","aspect-ratio.probe.loadedmetadata",{message:"Aspect ratio probe resolved",clipId:this.aspectRatioProbeSrc,extra:{videoWidth:e.videoWidth,videoHeight:e.videoHeight}}),this.refreshRuntimeState(),e.videoWidth>0&&e.videoHeight>0&&this.handleResolvedAutoAspectRatio(e.videoWidth,e.videoHeight)},i=()=>{this.isAspectRatioProbeLoading=!1,this.emitDiagnostic("warn","resource","aspect-ratio.probe.error",{message:"Aspect ratio probe failed",clipId:this.aspectRatioProbeSrc,actualSourceUrl:e.currentSrc||e.src||null}),this.refreshRuntimeState()};return e.addEventListener("loadedmetadata",t),e.addEventListener("error",i),this.aspectRatioProbe=e,e}tryResolveAutoAspectRatioFromSlot(e){if(!Ct(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const t=e.element;t.videoWidth>0&&t.videoHeight>0&&this.handleResolvedAutoAspectRatio(t.videoWidth,t.videoHeight)}handleResolvedAutoAspectRatio(e,t){var i,r;e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),Ct(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var C,T,v,w,x,P,M;const e=[];let t=this.isAspectRatioProbeLoading?1:0,i=0,r=!1,n=null,s=!1,o=!1,l=!1,c=!1,h=!1,d=!1;for(const{current:I,preload:A}of this.trackSlots.values())for(const k of[I,A]){const $=it(k.element)||null;e.push({trackId:k.trackId,role:k.role,kind:k.kind,clipId:((C=k.entry)==null?void 0:C.clip.id)??null,desiredSource:k.desiredSource,actualSource:$,phase:k.phase,retryCount:k.retryCount,errorMessage:k.errorMessage}),k.phase!=="idle"&&(s=!0),k.entry&&k.phase!=="idle"&&k.phase!=="failed"&&(l=!0),(k.isLoading||k.phase==="binding"||k.phase==="recovering")&&(this.isActiveCurrentSlot(k)?t+=1:i+=1),k.isBuffering&&this.isActiveCurrentSlot(k)&&(h=!0),k.phase==="failed"&&(o=!0),k.phase==="failed"&&!n&&(n=k.errorMessage||"资源加载异常,请刷新重试"),k.isActive&&k.entry&&(k.isSeeking||k.phase!=="active"&&k.phase!=="failed")&&(c=!0),k.role==="current"&&k.isActive&&k.entry&&k.phase==="active"&&!k.isLoading&&!k.isSeeking&&!k.isBuffering&&(d=!0)}r=h&&!d;const u=d?0:t;let g="idle";this.activeSyncRequestId!==void 0&&this.isSyncProjecting?g="awaiting-sync":o&&!l?g="failed":u>0||r||c&&!d?g="awaiting-media":s&&(g="ready"),g!=="failed"&&(n=null),this.loadingCount!==u&&(this.loadingCount=u,(v=(T=this.callbacks).onSourceLoadingChange)==null||v.call(T,u)),this.syncVisibleBufferingState(r);const f={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:g,loadingCount:u,isBuffering:r,errorMessage:n,slots:e},y=this.lastRuntimeState,S=JSON.stringify(f);S!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=S,this.lastRuntimeState=f,(y.phase!==f.phase||y.loadingCount!==f.loadingCount||y.isBuffering!==f.isBuffering||y.errorMessage!==f.errorMessage)&&this.emitDiagnostic(f.phase==="failed"?"error":"info","runtime","runtime.state",{message:"Preview runtime state updated",syncRequestId:f.syncRequestId??null,runtimeState:{runtimePhase:f.phase,loadingCount:f.loadingCount,isBuffering:f.isBuffering},extra:{backgroundLoadingCount:i,previousPhase:y.phase,phase:f.phase,errorMessage:f.errorMessage,slots:f.slots.map(I=>({trackId:I.trackId,role:I.role,clipId:I.clipId,phase:I.phase,retryCount:I.retryCount}))}}),(x=(w=this.callbacks).onRuntimeStateChange)==null||x.call(w,f)),(g==="ready"||g==="failed")&&f.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==f.syncRequestId&&(this.lastSettledSyncRequestId=f.syncRequestId,(M=(P=this.callbacks).onSyncProcessed)==null||M.call(P,f.syncRequestId)),!c&&this.deferredPreloadSlotKeys.size>0&&this.scheduleDeferredPreloadFlush(),this.refreshPendingOverlay()}syncVisibleBufferingState(e){var t,i;if(e){if(this.isBuffering||this.bufferingVisibleTimeoutId)return;this.bufferingVisibleTimeoutId=setTimeout(()=>{var r,n;this.bufferingVisibleTimeoutId=null,!this.isBuffering&&(this.isBuffering=!0,(n=(r=this.callbacks).onBufferingStateChange)==null||n.call(r,!0))},ld);return}this.clearBufferingVisibleTimeout(),this.isBuffering&&(this.isBuffering=!1,(i=(t=this.callbacks).onBufferingStateChange)==null||i.call(t,!1))}clearBufferingVisibleTimeout(){this.bufferingVisibleTimeoutId&&(clearTimeout(this.bufferingVisibleTimeoutId),this.bufferingVisibleTimeoutId=null)}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.lastRuntimeState})}handlePreviewTransformChange(e,t){var i;if(!t){((i=this.transientVisualTransform)==null?void 0:i.clipId)===e&&(this.transientVisualTransform=null,this.refreshVisualLayout());return}this.transientVisualTransform={clipId:e,transform:t},this.refreshVisualLayout()}refreshVisualLayout(){for(const{current:e,preload:t}of this.trackSlots.values())this.refreshSlotVisualLayout(e),this.refreshSlotVisualLayout(t);this.refreshTextPreviewLayout(),this.transformOverlay.sync(this.buildSelectedOverlayState())}syncTextPreviewEntries(e){this.ensureTextPreviewFontReady();const t=e.filter(r=>!r.muted&&r.hasVisual).sort((r,n)=>r.trackOrder-n.trackOrder),i=new Set(t.map(r=>r.clip.id));for(const[r]of this.textPreviewEntries)i.has(r)||this.removeTextPreviewEntry(r);t.forEach(r=>{var c;const n=this.textPreviewEntries.get(r.clip.id);if(n){n.entry=r,this.applyTextPreviewEntry(n);return}const s=document.createElement("div");s.className="timeline-preview-text-entry",s.style.position="absolute",s.style.left="0",s.style.top="0",s.style.transformOrigin="center center",s.style.whiteSpace="pre",s.style.wordBreak="normal",s.style.overflowWrap="normal",s.style.pointerEvents="none",s.style.userSelect="none";const o=this.createTextPreviewPointerDownHandler(r.clip.id);s.addEventListener("pointerdown",o),(c=this.textOverlayRoot)==null||c.appendChild(s);const l={entry:r,element:s,handlePointerDown:o};this.textPreviewEntries.set(r.clip.id,l),this.applyTextPreviewEntry(l)}),this.refreshTextPreviewInteractionState()}clearTextPreviewEntries(){for(const e of Array.from(this.textPreviewEntries.keys()))this.removeTextPreviewEntry(e)}removeTextPreviewEntry(e){var i;const t=this.textPreviewEntries.get(e);t&&(((i=this.textPreviewDragState)==null?void 0:i.clipId)===e&&this.finishTextPreviewDrag(!1),t.element.removeEventListener("pointerdown",t.handlePointerDown),t.element.remove(),this.textPreviewEntries.delete(e))}applyTextPreviewEntry(e){const t=Tt(e.entry.clip.textStyle),i=e.entry.clip.textContent||e.entry.clip.name||"";e.element.textContent=i,e.element.style.color=t.color,e.element.style.fontFamily=this.getTextPreviewFontFamily(),e.element.style.fontSize=`${t.fontSize}px`,e.element.style.lineHeight=`${t.lineHeight}px`,e.element.style.textShadow=cd(t.strokeWidth,t.strokeColor),e.element.style.padding=`0 ${t.paddingX}px`,e.element.style.textAlign="left",e.element.style.zIndex=String(2e3-e.entry.trackOrder)}refreshTextPreviewLayout(){const e=this.getFrameSize();if(e.width<=0||e.height<=0)return;const t=this.getTextPreviewBaselineMetrics(e);for(const i of this.textPreviewEntries.values()){const r=this.getEffectiveVisualTransform(i.entry),n=Tt(i.entry.clip.textStyle).rotation;i.element.style.left=`${e.width*r.x}px`,i.element.style.top=`${e.height*r.y}px`,i.element.style.transform=["translate(-50%, -50%)",`scale(${t.scale*r.scale})`,`rotate(${n}deg)`].join(" ")}}refreshTextPreviewEntries(){for(const e of this.textPreviewEntries.values())this.applyTextPreviewEntry(e);this.refreshTextPreviewLayout(),this.refreshTextPreviewInteractionState()}createTextPreviewPointerDownHandler(e){return t=>{var s,o;const i=t;if((i.button??0)!==0||this.primarySelectedClipId!==e)return;this.textPreviewDragState&&this.finishTextPreviewDrag(!1);const r=this.textPreviewEntries.get(e);if(!r)return;(s=i.preventDefault)==null||s.call(i),(o=i.stopPropagation)==null||o.call(i);const n=this.getEffectiveVisualTransform(r.entry);this.textPreviewDragState={clipId:e,pointerStart:this.toFrameLocalPoint(i),startTransform:n,nextTransform:n,changed:!1},this.bindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}}bindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.addEventListener("pointermove",this.boundTextPreviewPointerMove),e.addEventListener("pointerup",this.boundTextPreviewPointerUp),e.addEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.addEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}unbindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.removeEventListener("pointermove",this.boundTextPreviewPointerMove),e.removeEventListener("pointerup",this.boundTextPreviewPointerUp),e.removeEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.removeEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}handleTextPreviewPointerMove(e){var o;const t=this.textPreviewDragState;if(!t)return;if(!this.textPreviewEntries.get(t.clipId)){this.finishTextPreviewDrag(!1);return}const r=e;(o=r.preventDefault)==null||o.call(r);const n=this.toFrameLocalPoint(r),s=_a(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=s,t.changed=!jr(t.startTransform,s),this.handlePreviewTransformChange(t.clipId,s),this.refreshTextPreviewInteractionState()}finishTextPreviewDrag(e){var i,r;const t=this.textPreviewDragState;if(!t){this.unbindTextPreviewDocumentListeners();return}e&&t.changed&&((r=(i=this.callbacks).onVisualTransformCommit)==null||r.call(i,t.clipId,t.nextTransform)),this.handlePreviewTransformChange(t.clipId,null),this.textPreviewDragState=null,this.unbindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}refreshTextPreviewInteractionState(){var e;for(const t of this.textPreviewEntries.values()){const i=t.entry.clip.id===this.primarySelectedClipId,r=t.entry.clip.id===((e=this.textPreviewDragState)==null?void 0:e.clipId);t.element.style.pointerEvents=i?"auto":"none",t.element.style.cursor=i?r?"grabbing":"grab":"default"}}getTextPreviewFontConfig(){const e=this.dependencies.textPreviewFont;return!(e!=null&&e.fontName)||!e.fontSourceUrl?null:e}getTextPreviewFontFamily(){const e=this.getTextPreviewFontConfig();return!e||this.textPreviewFontLoadState==="failed"?ts:`${ur(e.fontName)}, ${ts}`}ensureTextPreviewFontReady(){const e=this.getTextPreviewFontConfig();if(!e||!this.rootElement||typeof document>"u")return;const t=`${e.fontName}::${e.fontSourceUrl}`;if(this.textPreviewFontSignature!==t){this.resetTextPreviewFontState();const n=document.createElement("style");n.textContent=["@font-face {",`font-family: ${ur(e.fontName)};`,`src: url("${Ia(e.fontSourceUrl)}");`,"font-display: swap;","}"].join(""),this.rootElement.appendChild(n),this.textPreviewFontStyleElement=n,this.textPreviewFontSignature=t,this.textPreviewFontLoadState="idle"}const i=document.fonts;if(typeof(i==null?void 0:i.load)!="function"||this.textPreviewFontLoadState==="loading"||this.textPreviewFontLoadState==="loaded")return;const r=++this.textPreviewFontLoadToken;this.textPreviewFontLoadState="loading",Promise.resolve(i.load(`1em ${ur(e.fontName)}`)).then(()=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="loaded",this.refreshTextPreviewEntries())}).catch(n=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="failed",G.warn("TimelinePreviewSession","Failed to load text preview font",{fontName:e.fontName,fontSourceUrl:e.fontSourceUrl,error:n}),this.refreshTextPreviewEntries())})}resetTextPreviewFontState(){var e;this.textPreviewFontLoadToken+=1,this.textPreviewFontLoadState="idle",this.textPreviewFontSignature=null,(e=this.textPreviewFontStyleElement)==null||e.remove(),this.textPreviewFontStyleElement=null}refreshSlotVisualLayout(e){if(e.kind!=="video"||!e.wrapper||!e.entry||!this.frameElement)return;const t=this.getFrameSize();if(t.width<=0||t.height<=0)return;const i=this.getMediaSize(e,e.entry,t),r=this.getEffectiveVisualTransform(e.entry),n=Qn(t,i,r);e.wrapper.style.left=`${n.left}px`,e.wrapper.style.top=`${n.top}px`,e.wrapper.style.width=`${n.width}px`,e.wrapper.style.height=`${n.height}px`}buildSelectedOverlayState(){if(!this.primarySelectedClipId)return null;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return null;for(const{current:t}of this.trackSlots.values()){if(t.kind!=="video"||!t.isActive||!t.entry||t.entry.clip.id!==this.primarySelectedClipId)continue;const i=this.getMediaSize(t,t.entry,e),r=this.getEffectiveVisualTransform(t.entry);return{clipId:t.entry.clip.id,transform:r,frameSize:e,baseRect:Pa(e,i),displayRect:Qn(e,i,r)}}return null}getFrameSize(){var i,r,n,s;const e=((i=this.frameElement)==null?void 0:i.clientWidth)??0,t=((r=this.frameElement)==null?void 0:r.clientHeight)??0;return{width:e>0?e:rs((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:rs((s=this.frameElement)==null?void 0:s.style.height)}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}toFrameLocalPoint(e){var i;const t=(i=this.frameElement)==null?void 0:i.getBoundingClientRect();return{x:(e.clientX??0)-((t==null?void 0:t.left)??0),y:(e.clientY??0)-((t==null?void 0:t.top)??0)}}getTextPreviewBaselineMetrics(e){const t=hd(this.getAspectRatio());return t.width<=0||t.height<=0||e.width<=0||e.height<=0?{width:t.width,height:t.height,scale:1}:{width:t.width,height:t.height,scale:Math.min(e.width/t.width,e.height/t.height)}}getMediaSize(e,t,i){if(Ui(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=_i(t,"sys_width"),n=_i(t,"sys_height");return r&&n?{width:r,height:n}:{width:i.width,height:i.height}}getEffectiveVisualTransform(e){var t;return((t=this.transientVisualTransform)==null?void 0:t.clipId)===e.clip.id?this.transientVisualTransform.transform:ke(e.clip.visualTransform)}}class Cd extends Sd{constructor(e={}){super(e.callbacks,{diagnostics:e.diagnostics,getDiagnosticsContext:e.getDiagnosticsContext,previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont,sourceMediaRegistry:e.sourceMediaRegistry,rootClassName:e.rootClassName,frameClassName:e.frameClassName,slotClassNamePrefix:e.slotClassNamePrefix})}destroy(){this.detach()}}function vd(a){return"dom"}const Td=36e5,bd=3e5;function Mr(a){return a.length===0?0:a.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function ns(a){return Mr(a)}function ss(a){return Math.max(a+bd,Td)}class as{constructor(e={}){p(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(r){G.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function wd(a){return[...a].sort((e,t)=>e.order-t.order)}function kd(a){return[...a].sort((e,t)=>e.startTime-t.startTime)}function pr(a,e,t){const i=a.type==="video"||a.type==="text",r=a.type!=="text";return{trackId:a.id,trackType:a.type,trackOrder:a.order,clip:e,mediaTime:t,muted:(a.isMuted??!1)||(e.isMuted??!1),kind:a.type,hasVisual:i,hasAudio:r}}class xd{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t){const i=wd(e),r=[],n=[];let s=null;for(const o of i){const l=kd(o.clips),c=l.find(d=>t>=d.startTime&&t<d.endTime);if(c){const d=c.startTimeAtSource+(t-c.startTime);r.push(pr(o,c,d))}const h=l.find(d=>d.startTime>t);if(h&&n.push(pr(o,h,h.startTimeAtSource)),!s&&o.type==="video"){const d=l[0];d&&(s=pr(o,d,d.startTimeAtSource))}}return{activeClips:r,nextClips:n,firstVideoClip:s}}}class Pd{constructor(e){p(this,"options");p(this,"_previewSession");p(this,"_previewMountContainer",null);p(this,"_resolvedPreviewBackend","dom");p(this,"_runtimePreviewBackendOverride",null);p(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const _d=8e3,Id=1e3;class Ad{constructor(e){p(this,"callbacks");p(this,"pendingTimeoutMs");p(this,"failedOverlayDelayMs");p(this,"_previewSourceLoadingCount",0);p(this,"_previewBuffering",!1);p(this,"_previewAwaitingMedia",!1);p(this,"_pendingPreviewState",null);p(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.pendingTimeoutMs=e.pendingTimeoutMs??_d,this.failedOverlayDelayMs=e.failedOverlayDelayMs??Id}get previewSourceLoadingCount(){return this._previewSourceLoadingCount}set previewSourceLoadingCount(e){this._previewSourceLoadingCount=Math.max(0,e)}get previewBuffering(){return this._previewBuffering}set previewBuffering(e){this._previewBuffering=e}get pendingPreviewState(){return this._pendingPreviewState}set pendingPreviewState(e){this._pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this._nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this._nextPendingPreviewSyncRequestId=Math.max(0,e)}handleBufferingStateChange(e){this._previewBuffering=e,this.callbacks.emitBufferingStateChange(e),this.updatePendingPreviewState()}handleSourceLoadingChange(e){this._previewSourceLoadingCount=Math.max(0,e),this.callbacks.emitSourceLoadingStateChange(),this.updatePendingPreviewState()}handleRuntimeStateChange(e){const t=Math.max(0,e.loadingCount),i=this._previewBuffering!==e.isBuffering,r=this._previewSourceLoadingCount!==t;this._previewAwaitingMedia=e.phase==="awaiting-media",this._previewBuffering=e.isBuffering,this._previewSourceLoadingCount=t,this._pendingPreviewState&&e.syncRequestId===this._pendingPreviewState.syncRequestId&&((e.phase==="awaiting-media"||e.phase==="ready"||e.phase==="failed")&&(this._pendingPreviewState.awaitingSync=!1),e.phase==="failed"?this.scheduleFailedOverlay(e.errorMessage||"资源加载异常,请刷新重试"):(this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.errorMessage=null)),i&&this.callbacks.emitBufferingStateChange(e.isBuffering),r&&this.callbacks.emitSourceLoadingStateChange(),this.updatePendingPreviewState()}markSyncProcessed(e){this._pendingPreviewState&&e===this._pendingPreviewState.syncRequestId&&(this._pendingPreviewState.awaitingSync=!1),this.updatePendingPreviewState()}beginPendingPreview(e,t,i){this.clearPendingPreviewTimeout(),this._pendingPreviewState={mode:t,targetTime:e,resumePlayOnReady:i,errorMessage:null,timeoutId:null,failedTimeoutId:null,pendingFailedMessage:null,awaitingSync:!0,syncRequestId:++this._nextPendingPreviewSyncRequestId}}buildPreviewPendingState(){return!this._pendingPreviewState||this._pendingPreviewState.mode==="scrub"?null:{mode:this._pendingPreviewState.mode,targetTime:this._pendingPreviewState.targetTime,loadingPending:this._previewSourceLoadingCount,isBuffering:this._previewAwaitingMedia||this._previewBuffering,errorMessage:this._pendingPreviewState.errorMessage}}updatePendingPreviewState(){if(!this._pendingPreviewState){this.callbacks.applyPendingState(null);return}const e=this._previewSourceLoadingCount>0||this._previewAwaitingMedia;if(this._pendingPreviewState.errorMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.pendingFailedMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.awaitingSync){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(e){this.ensurePendingPreviewTimeout(),this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const t=this._pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),t&&this.callbacks.resumePlayback()}retryPendingPreview(){this._pendingPreviewState&&(this._pendingPreviewState.errorMessage=null,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.awaitingSync=!0,this._pendingPreviewState.syncRequestId=++this._nextPendingPreviewSyncRequestId,this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this.callbacks.requestPreviewSync())}clearPendingPreviewState(){this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this._pendingPreviewState=null,this.callbacks.applyPendingState(null)}resetPreviewRuntimeState(){const e=this._previewBuffering,t=this._previewSourceLoadingCount!==0;this._previewBuffering=!1,this._previewAwaitingMedia=!1,this._previewSourceLoadingCount=0,e&&this.callbacks.emitBufferingStateChange(!1),t&&this.callbacks.emitSourceLoadingStateChange()}ensurePendingPreviewTimeout(){if(!this._pendingPreviewState||this._pendingPreviewState.mode==="scrub"||this._pendingPreviewState.timeoutId!==null)return;const e=this._pendingPreviewState.syncRequestId;this._pendingPreviewState.timeoutId=setTimeout(()=>{!this._pendingPreviewState||this._pendingPreviewState.syncRequestId!==e||(this._pendingPreviewState.errorMessage="资源加载异常,请刷新重试",this.clearPendingPreviewTimeout(),this.callbacks.applyPendingState(this.buildPreviewPendingState()))},this.pendingTimeoutMs)}clearPendingPreviewTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.timeoutId&&(clearTimeout(this._pendingPreviewState.timeoutId),this._pendingPreviewState.timeoutId=null)}scheduleFailedOverlay(e){if(!this._pendingPreviewState||this._pendingPreviewState.errorMessage===e||this._pendingPreviewState.pendingFailedMessage===e&&this._pendingPreviewState.failedTimeoutId)return;this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=e;const t=this._pendingPreviewState.syncRequestId;this._pendingPreviewState.failedTimeoutId=setTimeout(()=>{!this._pendingPreviewState||this._pendingPreviewState.syncRequestId!==t||(this._pendingPreviewState.errorMessage=e,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.failedTimeoutId=null,this.callbacks.applyPendingState(this.buildPreviewPendingState()))},this.failedOverlayDelayMs)}clearFailedOverlayTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.failedTimeoutId&&(clearTimeout(this._pendingPreviewState.failedTimeoutId),this._pendingPreviewState.failedTimeoutId=null)}}const Ed=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Ld={togglePlay:["Space"],deleteSelectedClips:["Delete","Backspace"],copySelectedClips:["Mod+C"],cutSelectedClips:["Mod+X"],pasteClipboardClips:["Mod+V"],toggleSelectedClipsAudio:["Mod+Alt+A"],splitCurrentClip:["Mod+B"],undo:["Mod+Z"],redo:["Mod+Shift+Z","Ctrl+Y"]};function Rd(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function Dd(a){const e=a.trim();if(!e)return null;const t=e.toLowerCase();return t==="space"||t==="spacebar"?"Space":t==="delete"?"Delete":t==="backspace"?"Backspace":/^[a-z]$/i.test(e)?`Key${e.toUpperCase()}`:/^key[a-z]$/i.test(e)?`Key${e.slice(-1).toUpperCase()}`:/^[0-9]$/.test(e)?`Digit${e}`:/^digit[0-9]$/i.test(e)?`Digit${e.slice(-1)}`:null}function Md(a,e,t){const i=e.split("+").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return null;let r=null,n=!1,s=!1,o=!1,l=!1;for(const c of i)switch(c.toLowerCase()){case"mod":t?o=!0:s=!0;break;case"alt":case"option":n=!0;break;case"ctrl":case"control":s=!0;break;case"cmd":case"command":case"meta":o=!0;break;case"shift":l=!0;break;default:{const h=Dd(c);if(!h||r)return null;r=h}}return r?{action:a,code:r,altKey:n,ctrlKey:s,metaKey:o,shiftKey:l}:null}function Od(a){if(!(a instanceof HTMLElement))return!1;if(a.isContentEditable)return!0;const e=a.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:!!a.closest('[contenteditable=""], [contenteditable="true"], input, textarea, select')}function Bd(a,e){return a.code===e.code&&a.altKey===e.altKey&&a.ctrlKey===e.ctrlKey&&a.metaKey===e.metaKey&&a.shiftKey===e.shiftKey}function Gd(a,e){return a===!1||(a==null?void 0:a.enabled)===!1?[]:Ed.flatMap(t=>{var n;const i=(n=a==null?void 0:a.bindings)==null?void 0:n[t];return(i===void 0?Ld[t]:Array.isArray(i)?i:[i]).map(s=>Md(t,s,e)).filter(s=>s!==null)})}class Fd{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??Rd();e.root,this.callbacks=e.callbacks,this.bindings=Gd(e.config,t),this.enabled=e.config!==!1&&((i=e.config)==null?void 0:i.enabled)!==!1&&this.bindings.length>0}init(){var e,t;this.enabled&&((t=(e=globalThis.window)==null?void 0:e.addEventListener)==null||t.call(e,"keydown",this.keydownListener))}destroy(){var e,t;(t=(e=globalThis.window)==null?void 0:e.removeEventListener)==null||t.call(e,"keydown",this.keydownListener)}handleKeydown(e){if(Od(e.target))return;const t=this.bindings.find(i=>Bd(e,i));t&&(e.preventDefault(),e.stopPropagation(),this.dispatchAction(t.action))}dispatchAction(e){switch(e){case"togglePlay":this.callbacks.togglePlay();return;case"deleteSelectedClips":this.callbacks.canDeleteSelectedClips()&&this.callbacks.deleteSelectedClips();return;case"copySelectedClips":this.callbacks.canCopySelectedClips()&&this.callbacks.copySelectedClips();return;case"cutSelectedClips":this.callbacks.canCutSelectedClips()&&this.callbacks.cutSelectedClips();return;case"pasteClipboardClips":this.callbacks.canPasteClipboardClips()&&this.callbacks.pasteClipboardClips();return;case"toggleSelectedClipsAudio":this.callbacks.canToggleSelectedClipsAudio()&&this.callbacks.toggleSelectedClipsAudio();return;case"splitCurrentClip":this.callbacks.canSplitSelectedClip()&&this.callbacks.splitCurrentClip();return;case"undo":this.callbacks.undo();return;case"redo":this.callbacks.redo();return}}}function Aa(a){var t;const e=a.getPrimarySelectedClip()||((t=a.findFallbackSelectedClip)==null?void 0:t.call(a))||null;return{clip:e,hasSelectedClip:!!e}}function Hd(a){const e=Aa(a),t=a.getSelectedClipIds(),i=a.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:a.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function Nd(a){var i;const e=a.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===a.lastSelectedClipId?a.lastSelectedClipId:(a.emitSelectedClipChange(e),t)}function Ea(a,e){var t,i,r,n;return((i=(t=a.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((n=(r=a.getLastTrack())==null?void 0:r.getId)==null?void 0:n.call(r))||e}function $d(a){if(a.placement.status==="use_existing_track")return a.trackCollection.addClipToTrack(a.placement.trackId,a.clip);const e=a.createTrack(a.placement.trackType,a.placement.suggestedTrackName,a.placement.insertionPlacement),t=Ea(a.trackCollection,e);return t?a.trackCollection.addClipToTrack(t,a.clip):!1}function os(a,e,t){return e.trackId?a.removeClipFromTrack(e.trackId,t):!1}function zd(a){return a.trackCollection.moveClipToTrack(a.command.clip,a.command.sourceTrackId,a.command.targetTrackId)}function Vd(a){const e=a.createTrack(a.trackType,a.trackName),t=Ea(a.trackCollection,e);return t?a.trackCollection.moveClipToTrack(a.clip,a.currentTrackId,t):!1}function Ne(a){var e,t,i,r,n;(e=a.checkTrackDurationChange)==null||e.call(a),(t=a.updateCanPlayState)==null||t.call(a),(i=a.updateTrackInfoPanel)==null||i.call(a),(r=a.handleClipChange)==null||r.call(a),(n=a.cleanupEmptyTracks)==null||n.call(a)}function Ud(a){var e,t;a.notifySelectionChange(),(e=a.cleanupEmptyTracks)==null||e.call(a),a.updateTrackInfoPanel(),(t=a.batchDraw)==null||t.call(a),a.syncPreviewSession()}class Wd{constructor(){p(this,"panel",null)}init(e){var i,r,n,s;const t=((i=e.theme)==null?void 0:i.background)||be.background;this.panel=new ka({container:e.container,theme:{background:t,border:((r=e.theme)==null?void 0:r.border)||be.border,text:((n=e.theme)==null?void 0:n.clipName)||be.text,buttonBackground:((s=e.theme)==null?void 0:s.clipBackground)||be.buttonBackground,buttonHover:be.buttonHover,buttonDanger:be.buttonDanger},width:200,timeScaleHeight:e.timeScaleHeight||40,includeTimeScaleSpacer:e.includeTimeScaleSpacer},e.onRenameTrack,e.onRemoveTrack,e.onMuteTrack)}hasPanel(){return!!this.panel}update(e){var t;(t=this.panel)==null||t.setTracks(e)}setScrollTop(e){var t;(t=this.panel)==null||t.setScrollTop(e)}destroy(){var e;(e=this.panel)==null||e.destroy(),this.panel=null}}class ls{syncCurrentTime(e,t,i,r){e==null||e.setCurrentTime(r),t==null||t.setCurrentTime(r),i.syncCurrentTime(r)}syncZoom(e,t,i,r){e==null||e.setZoom(r),t==null||t.setZoom(r),i.syncZoom(r)}syncScrollLeft(e,t,i){e==null||e.setScrollLeft(i),t.syncScrollLeft(i)}syncScrollTop(e,t,i){e==null||e.setScrollTop(i),t==null||t.setScrollTop(i)}syncSelection(e,t){e.syncSelection(t,t[0]??null)}findSelectedClip(e){return e.findPrimarySelectedClip()}}function Yd(a){return!!a&&typeof a.then=="function"}class gr{constructor(){p(this,"durationCache",new Map);p(this,"thumbnailCache",new Map);p(this,"previewSourceCache",new Map)}static buildSourceKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src||""}static buildThumbnailKey(e){return[this.buildSourceKey(e),e.type,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}getDuration(e,t,i={}){const r=this.durationCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(typeof(r==null?void 0:r.value)=="number")return Promise.resolve(r.value)}const n=t().then(s=>(this.durationCache.set(e,{value:s,promise:null}),s)).catch(s=>{throw this.durationCache.delete(e),s});return this.durationCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeDuration(e,t){this.durationCache.set(e,{value:t,promise:null})}getThumbnails(e,t,i={}){const r=this.thumbnailCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.value)return Promise.resolve(r.value)}const n=t().then(s=>(this.thumbnailCache.set(e,{value:s,promise:null}),s)).catch(s=>{throw this.thumbnailCache.delete(e),s});return this.thumbnailCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeThumbnails(e,t){this.thumbnailCache.set(e,{value:t,promise:null})}clearThumbnailCache(){this.thumbnailCache.clear()}getPreviewSource(e,t,i={}){const r=this.previewSourceCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.resolved)return r.value}const n=t();if(!Yd(n))return this.previewSourceCache.set(e,{value:n,promise:null,resolved:!0}),n;const s=n.then(o=>(this.previewSourceCache.set(e,{value:o,promise:null,resolved:!0}),o)).catch(o=>{throw this.previewSourceCache.delete(e),o});return this.previewSourceCache.set(e,{value:(r==null?void 0:r.value)??null,promise:s,resolved:!1}),s}primePreviewSource(e,t){this.previewSourceCache.set(e,{value:t,promise:null,resolved:!0})}}class cs{constructor(e,t=zi){this.handlers=e,this.TrackCtor=t}createTrack(e){return new this.TrackCtor(e.layer,e.config,e.trackType,e.zoom,e.trackY,e.trackHeight,e.theme,this.handlers.onClipUpdate,this.handlers.onClipAdd,this.handlers.onClipRemove,this.handlers.onClipSplit,this.handlers.onClipSelect,this.handlers.onTimeJump,this.handlers.onHorizontalDragAutoScroll,this.handlers.onClipOverlap,this.handlers.onClipCrossTrackPreview,this.handlers.onClipCrossTrack,this.handlers.onClearDropPreview,this.handlers.onClearSelection,this.handlers.onSnapGuideChange,this.handlers.onClipToggleSelection,this.handlers.onSetSingleSelection,this.handlers.getMultiDragClipIds,this.handlers.onMultiDragMove,this.handlers.onMultiDragInteractionEnd,e.dragActivationThreshold,e.enableClipSnap,e.clipSnapThreshold)}}class Xd{constructor(e){this.tracks=e}getAll(){return this.tracks}getDefaultTrack(){return this.tracks[0]||null}getPrimaryTrack(){return this.tracks.find(e=>{var t;return((t=e.getRole)==null?void 0:t.call(e))==="primary"})||this.getDefaultTrack()}getLastTrack(){return this.tracks.length>0?this.tracks[this.tracks.length-1]:null}add(e){this.tracks.push(e)}findById(e){return this.tracks.find(t=>this.resolveTrackId(t)===e)||null}removeById(e){const t=this.findIndexById(e);if(t===-1)return null;const[i]=this.tracks.splice(t,1);return i||null}removeEmptyNonPrimaryTracks(){var t;const e=[];for(let i=this.tracks.length-1;i>=0;i-=1){const r=this.tracks[i];if(((t=r.getRole)==null?void 0:t.call(r))==="primary"||(typeof r.getClips=="function"?r.getClips():[]).length>0)continue;const[s]=this.tracks.splice(i,1);s&&e.push(s)}return e.reverse()}findTrackByClipId(e){return this.tracks.find(t=>t.getClips().some(i=>i.id===e))||null}getAllClips(){return this.tracks.flatMap(e=>e.getClips())}syncCurrentTime(e){this.tracks.forEach(t=>{var i;return(i=t.setCurrentTime)==null?void 0:i.call(t,e)})}syncZoom(e){this.tracks.forEach(t=>{var i;return(i=t.setZoom)==null?void 0:i.call(t,e)})}syncScrollLeft(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollLeft)==null?void 0:i.call(t,e)})}syncScrollTop(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollTop)==null?void 0:i.call(t,e)})}updateClip(e,t){this.tracks.forEach(i=>{var r;return(r=i.updateClip)==null?void 0:r.call(i,e,t)})}removeClip(e){this.tracks.forEach(t=>{var i;return(i=t.removeClip)==null?void 0:i.call(t,e)})}addClipToTrack(e,t){const i=this.findById(e);return i!=null&&i.addClip?(i.addClip(t),!0):!1}removeClipFromTrack(e,t){const i=this.findById(e);return i!=null&&i.removeClip?(i.removeClip(t),!0):!1}moveClipToTrack(e,t,i){if(t===i)return!0;const r=this.findById(t),n=this.findById(i);return!(r!=null&&r.removeClip)||!(n!=null&&n.addClip)?!1:(r.removeClip(e.id),n.addClip(e),!0)}removeClipGaps(){this.tracks.forEach(e=>{var t;return(t=e.removeClipGaps)==null?void 0:t.call(e)})}clearSelection(){this.tracks.forEach(e=>{var t;return(t=e.clearSelection)==null?void 0:t.call(e)})}syncSelection(e,t=e[0]??null){this.tracks.forEach(i=>{var r;(r=i.setSelection)==null||r.call(i,e,t)})}findPrimarySelectedClip(){var e;for(const t of this.tracks){const i=(e=t.getPrimarySelectedClip)==null?void 0:e.call(t);if(i)return i}return null}forEach(e){this.tracks.forEach(e)}findIndexById(e){return this.tracks.findIndex(t=>this.resolveTrackId(t)===e)}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}function qd(a){return a==="text"?"文本":a==="video"?"视频":"音频"}function Ii(a){return a==="text"?0:a==="video"?1:2}class La{constructor(e=[]){p(this,"tracks",[]);p(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,r,n){this.trackCounter++;const s=t||`${qd(e)}轨道 ${this.trackCounter}`,o=n??(this.tracks.length===0?"primary":"normal");o==="primary"&&this.tracks.forEach(c=>{c.role==="primary"&&(c.role="normal")});const l={id:`track_${Date.now()}_${this.trackCounter}`,type:e,name:s,order:this.tracks.length,role:o,clips:[]};return this.insertTrack(l,i,r),G.debugLazy("TrackManager",()=>`创建轨道: ${s}`,()=>({trackId:l.id,type:e,order:l.order})),l}removeTrack(e){var i;const t=this.tracks.findIndex(r=>r.id===e);return t===-1?(G.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(G.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),G.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,G.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(G.warn("TrackManager",`轨道不存在: ${e}`),!1)}getTracks(){return[...this.tracks]}getTrack(e){return this.tracks.find(t=>t.id===e)}getTracksByType(e){return this.tracks.filter(t=>t.type===e)}updateTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(Object.assign(i,t),G.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(G.warn("TrackManager",`轨道不存在: ${e}`),!1)}recalculateOrder(){this.tracks.forEach((e,t)=>{e.order=t})}insertTrack(e,t,i){const r=this.tracks.findIndex(s=>s.role==="primary"),n=t??(e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary");if(r===-1||e.role==="primary"){this.tracks.push(e),this.recalculateOrder();return}if((n==="before_track"||n==="after_track")&&i){const s=this.tracks.findIndex(o=>o.id===i);if(s!==-1){this.tracks.splice(s+(n==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(n==="top_of_type_region"){const s=this.tracks.findIndex(l=>l.type===e.type);if(s!==-1){this.tracks.splice(s,0,e),this.recalculateOrder();return}const o=this.tracks.findIndex(l=>Ii(l.type)>Ii(e.type));if(o!==-1){this.tracks.splice(o,0,e),this.recalculateOrder();return}}if(n==="bottom_of_type_region"){const s=this.tracks.reduce((l,c,h)=>c.type===e.type?h:l,-1);if(s!==-1){this.tracks.splice(s+1,0,e),this.recalculateOrder();return}const o=this.tracks.reduce((l,c,h)=>Ii(c.type)<=Ii(e.type)?h:l,-1);if(o!==-1){this.tracks.splice(o+1,0,e),this.recalculateOrder();return}}n==="before_primary"?this.tracks.splice(r,0,e):this.tracks.splice(r+1,0,e),this.recalculateOrder()}muteTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.isMuted=t,G.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(G.warn("TrackManager",`轨道不存在:${e}`),!1)}isTrackMuted(e){const t=this.tracks.find(i=>i.id===e);return(t==null?void 0:t.isMuted)??!1}clearAllTracks(){this.tracks=[],this.trackCounter=0,G.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}function st(a){return a==="text"?Le.TEXT:a==="video"?Le.VIDEO:Le.AUDIO}function Ot(a,e,t){let i=t;for(const r of a){if(r.id===e)break;i+=st(r.type)}return i}function hs(a,e){return a.reduce((t,i)=>t+st(i.type),e)}function jd(a,e){let t=e;return a.map(i=>{const r=st(i.type),n={trackId:i.id,y:t,height:r};return t+=r,n})}class Kd{constructor(){p(this,"container",null)}mount(e,t){return this.container=e,oi(this.renderTemplate(t),e),e.classList.add("timeline-manager-root"),e.style.gridTemplateColumns=`${t.leftPanelWidth}px minmax(0, 1fr)`,e.style.gridTemplateRows=`${t.timeScaleHeight}px minmax(0, 1fr)`,e.style.background=t.theme.background,{headerCorner:this.requireElement(e,'[data-layout-role="header-corner"]'),headerViewport:this.requireElement(e,'[data-layout-role="header-viewport"]'),headerCanvasHost:this.requireElement(e,'[data-layout-role="header-canvas-host"]'),trackInfoViewport:this.requireElement(e,'[data-layout-role="track-info-viewport"]'),bodyViewport:this.requireElement(e,'[data-layout-role="body-viewport"]'),bodyCanvasHost:this.requireElement(e,'[data-layout-role="body-canvas-host"]'),verticalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="vertical-scrollbar-host"]'),horizontalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="horizontal-scrollbar-host"]'),playheadOverlay:this.requireElement(e,'[data-layout-role="playhead-overlay"]')}}destroy(){this.container&&oi(null,this.container),this.container=null}renderTemplate(e){const{theme:t,timeScaleHeight:i,leftPanelWidth:r,scrollbarSize:n}=e,s=["position:relative","min-width:0","min-height:0","max-width:100%","box-sizing:border-box",`background:${t.background}`,`color:${t.clipName}`].join(";");return K`
|
|
493
494
|
<div
|
|
494
495
|
class="timeline-manager-header-corner"
|
|
495
496
|
data-layout-role="header-corner"
|
|
@@ -537,7 +538,7 @@ js: import "konva/skia-backend";
|
|
|
537
538
|
data-layout-role="playhead-overlay"
|
|
538
539
|
style=${["position:absolute",`left:${r}px`,"top:0","right:0","bottom:0","pointer-events:none","z-index:3"].join(";")}
|
|
539
540
|
></div>
|
|
540
|
-
`}requireElement(e,t){const i=e.querySelector(t);if(!i)throw new Error(`Missing timeline manager layout element: ${t}`);return i}}const
|
|
541
|
+
`}requireElement(e,t){const i=e.querySelector(t);if(!i)throw new Error(`Missing timeline manager layout element: ${t}`);return i}}const Ra=200,Da=8,ds="timeline-manager-managed-layout-styles";function Zd(){if(typeof document>"u"||document.getElementById(ds))return;const a=document.createElement("style");a.id=ds,a.textContent=`
|
|
541
542
|
.timeline-manager-root {
|
|
542
543
|
position: relative;
|
|
543
544
|
overflow: hidden;
|
|
@@ -563,4 +564,4 @@ js: import "konva/skia-backend";
|
|
|
563
564
|
height: 0;
|
|
564
565
|
display: none;
|
|
565
566
|
}
|
|
566
|
-
`,document.head.appendChild(a)}function xd(a,e){kd();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??ua,scrollbarSize:e.scrollbarSize??pa};return new wd().mount(a,t)}class Pd{constructor(e){p(this,"currentTime");p(this,"playState");p(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class ga{constructor(){p(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class _d{constructor(e){p(this,"zoom");p(this,"duration");p(this,"scrollLeft");p(this,"scrollTop");p(this,"viewportWidth");p(this,"viewportHeight");p(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class is{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new ga,this.playbackStore=new Pd({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new _d({zoom:e.zoom,duration:e.duration,scrollLeft:e.scrollLeft,scrollTop:e.scrollTop,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,contentHeight:e.contentHeight}),e.selectedClipIds!==void 0?this.selectionStore.setSelection(e.selectedClipIds):e.selectedClipId!==void 0&&this.selectionStore.setPrimarySelection(e.selectedClipId)}getPrimarySelectedClipId(){return this.selectionStore.getPrimarySelectedClipId()}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return this.selectionStore.getSelectedClipIds()}setSelectedClipIds(e){this.selectionStore.setSelection(e)}setPrimarySelectedClipId(e){this.selectionStore.setPrimarySelection(e)}setSelectedClipId(e){this.setPrimarySelectedClipId(e)}clearSelection(){this.selectionStore.clear()}hasSelection(){return this.selectionStore.hasSelection()}getCurrentTime(){return this.playbackStore.getCurrentTime()}setCurrentTime(e){this.playbackStore.setCurrentTime(e)}getPlayState(){return this.playbackStore.getPlayState()}setPlayState(e){this.playbackStore.setPlayState(e)}getSpeed(){return this.playbackStore.getSpeed()}setSpeed(e){this.playbackStore.setSpeed(e)}getZoom(){return this.viewportStore.getZoom()}setZoom(e){this.viewportStore.setZoom(e)}getDuration(){return this.viewportStore.getDuration()}setDuration(e){this.viewportStore.setDuration(e)}getScrollLeft(){return this.viewportStore.getScrollLeft()}setScrollLeft(e){this.viewportStore.setScrollLeft(e)}getScrollTop(){return this.viewportStore.getScrollTop()}setScrollTop(e){this.viewportStore.setScrollTop(e)}getViewportWidth(){return this.viewportStore.getViewportWidth()}setViewportWidth(e){this.viewportStore.setViewportWidth(e)}getViewportHeight(){return this.viewportStore.getViewportHeight()}setViewportHeight(e){this.viewportStore.setViewportHeight(e)}getContentHeight(){return this.viewportStore.getContentHeight()}setContentHeight(e){this.viewportStore.setContentHeight(e)}}class Ad{constructor(e,t,i,r,n){p(this,"stage");p(this,"layer");p(this,"onTimeChange");p(this,"onScrollChange");p(this,"config");p(this,"theme");p(this,"scrollLeft",0);p(this,"timeScaleHeight",40);p(this,"isDragging",!1);p(this,"dragStartX",0);p(this,"isPointerInsideTimeline",!1);p(this,"lastPointerXInTimeline",null);p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=r,this.onScrollChange=n,this.config={duration:i.duration||36e5,zoom:i.zoom||ye.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:jt(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(e){}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setScrollLeft(e){this.scrollLeft=this.clampScrollLeft(e),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(e){const t=F.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=F.timeToPixels(e.startTime,this.config.zoom),r=F.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,n=this.stage.width(),s=r<=n?Math.max(0,t-(n-r)/2):Math.max(0,t);this.setScrollLeft(s)}resize(e){this.stage.width(e),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",e=>{e.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(e.evt.offsetX),"seek")}),this.stage.on("mousedown",e=>{e.target.getLayer()===this.layer&&(this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=ni({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(si({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(e){const t=e.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-t),r=this.scrollLeft;this.dragStartX=e.clientX,this.scrollLeft=i,this.render(),r!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(e){return F.pixelsToTime(e-ue+this.scrollLeft,this.config.zoom)}timeToPixel(e){return F.timeToPixels(e,this.config.zoom)-this.scrollLeft+ue}render(){const e=this.stage.width(),t=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const r=se.createRect(0,0,e,t,this.theme.background,this.theme.border,1);r.name("timeline-header-background"),this.layer.add(r)}this.layer.find(".time-tick-line").forEach(r=>r.remove()),this.layer.find(".time-tick-text").forEach(r=>r.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,r=F.pixelsToTime(t,this.config.zoom),n=F.pixelsToTime(i,this.config.zoom),s=F.msToSeconds(r),o=F.msToSeconds(n),{majorStep:l,minorStep:h}=F.getTickConfig(this.config.zoom),c=F.generateVisibleTicks(s-10,o+10,l,h);for(const d of c){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&se.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,F.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const U=class U{constructor(e,t,i,r,n,s,o){p(this,"container");p(this,"visualElement");p(this,"lineHitAreaElement");p(this,"theme");p(this,"onTimeChange");p(this,"onHorizontalAutoScroll");p(this,"currentTime");p(this,"zoom");p(this,"scrollLeft",0);p(this,"height");p(this,"isDragging",!1);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"lastPointerClientX",null);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});p(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});p(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const r=this.scrollLeft,n=this.onHorizontalAutoScroll(this.scrollLeft+i),s=typeof n=="number"?n:this.scrollLeft;if(this.scrollLeft=Math.max(0,s),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-r)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=e,this.currentTime=t,this.zoom=i,this.height=r,this.theme=n,this.onTimeChange=s,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(U.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${U.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=`${U.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=ni({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(si({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,r=F.pixelsToTime(i-ue+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,r),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(U.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=U.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const n=(i-e)/i;return-Math.max(1,Math.round(n*r))}if(e>t-i){const n=(e-(t-i))/i;return Math.max(1,Math.round(n*r))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const e=F.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+ue,t=e>=0&&e<=this.container.clientWidth,i=Math.max(U.HANDLE_HEIGHT+U.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${U.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=Ei.grip,i=Math.max(U.HANDLE_HEIGHT,e-U.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i,this.theme.playhead))}createHandleShadowPath(){const e=document.createElementNS(U.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill",Ei.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(U.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(U.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(U.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(U.VISUAL_WIDTH-U.LINE_WIDTH)/2}`),t.setAttribute("y",`${U.HANDLE_LINE_START}`),t.setAttribute("width",`${U.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-U.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e,t){const i=document.createElementNS(U.SVG_NS,"g");i.setAttribute("class","timeline-manager-playhead-end-cap"),i.setAttribute("transform",`translate(0 ${e})`);const r=document.createElementNS(U.SVG_NS,"rect");r.setAttribute("x",`${(U.VISUAL_WIDTH-U.LINE_WIDTH)/2}`),r.setAttribute("y","0"),r.setAttribute("width",`${U.LINE_WIDTH}`),r.setAttribute("height","7"),r.setAttribute("rx","1"),r.setAttribute("fill",t);const n=document.createElementNS(U.SVG_NS,"rect");return n.setAttribute("x",`${(U.VISUAL_WIDTH-U.END_CAP_WIDTH)/2}`),n.setAttribute("y","7"),n.setAttribute("width",`${U.END_CAP_WIDTH}`),n.setAttribute("height","3"),n.setAttribute("rx","1.5"),n.setAttribute("fill",t),i.appendChild(r),i.appendChild(n),i}};p(U,"SVG_NS","http://www.w3.org/2000/svg"),p(U,"VISUAL_WIDTH",14),p(U,"HANDLE_HEIGHT",16),p(U,"HANDLE_LINE_START",13),p(U,"LINE_WIDTH",2),p(U,"LINE_HIT_WIDTH",12),p(U,"END_CAP_WIDTH",14),p(U,"END_CAP_HEIGHT",10),p(U,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(U,"AUTO_SCROLL_MAX_SPEED",18);let Ar=U;class rs{constructor(e){p(this,"container");p(this,"orientation");p(this,"theme");p(this,"onScrollChange");p(this,"leadingInset");p(this,"trailingInset");p(this,"stage");p(this,"layer");p(this,"hitAreaRect");p(this,"thumbRect");p(this,"viewportSize",0);p(this,"contentSize",0);p(this,"scrollOffset",0);p(this,"isDragging",!1);p(this,"dragStartClient",0);p(this,"dragStartOffset",0);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleStageMouseDown",e=>{var r;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((r=e.target)==null?void 0:r.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});p(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});p(this,"handleStageMouseEnter",()=>{this.updateCursor()});p(this,"handleStageMouseMove",()=>{this.updateCursor()});p(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new q.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new q.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=se.createRect(0,0,0,0,fe.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=se.createRect(0,0,0,0,this.theme.scrollbarThumb||fe.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border,1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=ni({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(si({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(e){const i=(this.orientation==="horizontal"?e.clientX:e.clientY)-this.dragStartClient,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),s=Math.max(1,r-n),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/s*o;this.emitScrollChange(l)}jumpToPointer(e){const t=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?e-t.left:e-t.top,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),s=Math.max(1,r-n),o=Math.max(0,Math.min(r,i-this.leadingInset)),l=Math.max(0,Math.min(s,o-n/2)),h=this.getMaxScrollOffset(),c=s<=0?0:l/s*h;this.emitScrollChange(c)}emitScrollChange(e){const t=this.clampScrollOffset(e);this.scrollOffset=t,this.render(),this.onScrollChange(t)}render(){const e=Math.max(0,this.container.clientWidth),t=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(e),this.stage.height(t),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(e),this.hitAreaRect.height(t),this.thumbRect.fill(this.theme.scrollbarThumb||fe.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border);const r=this.getAvailableTrackSize();if(r<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const n=this.getThumbSize(r),s=this.leadingInset+this.getThumbPosition(r,n);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(s),this.thumbRect.y(0),this.thumbRect.width(n),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(s),this.thumbRect.width(e),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(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const r=Math.max(1,e-t);return this.scrollOffset/i*r}}class ns{constructor(){p(this,"entries",new Map)}register(e,t){this.entries.set(e,{id:e,destroy:t})}unregister(e){this.entries.delete(e)}destroyAll(){for(const e of this.entries.values())e.destroy();this.entries.clear()}}class Id{constructor(){p(this,"panel",null);p(this,"config",null);p(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new sa({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,e.updateClip(i,r),setTimeout(()=>{this.isInternalUpdate=!1},0)},onGenerateVoice:e.onGenerateVoice})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip();this.panel.setClip(e)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}setPreferredTab(e){var t;(t=this.panel)==null||t.setPreferredTab(e)}setVoiceGenerationBusy(e){var t;(t=this.panel)==null||t.setVoiceGenerationBusy(e)}convertTheme(e){return{backgroundColor:ge.backgroundColor,borderColor:e.border||ge.borderColor,textColor:e.clipName||ge.textColor,labelColor:e.timeText||ge.labelColor,inputBackground:e.trackBackground||ge.inputBackground,inputBorder:e.trackBorder||ge.inputBorder,inputFocusBorder:ge.inputFocusBorder,buttonBackground:e.clipBackground||ge.buttonBackground,buttonBorder:e.clipBorder||ge.buttonBorder,buttonActiveBackground:ge.buttonActiveBackground,buttonActiveBorder:e.clipSelectedBorder||ge.buttonActiveBorder,buttonActiveText:ge.buttonActiveText}}}const Ed="2.0.12",Ld={version:Ed},Rd=1,Md=2,Dd=120;function Od(a){return a==="text"?"文本":a==="video"?"视频":"音频"}class Bd{constructor(e={}){p(this,"timeline",null);p(this,"tracks",[]);p(this,"trackManager");p(this,"trackInfoPanelController");p(this,"playhead",null);p(this,"history");p(this,"config");p(this,"eventDispatcher");p(this,"animationFrameId",null);p(this,"lastUpdateTime",0);p(this,"isInitialized",!1);p(this,"stage",null);p(this,"headerStage",null);p(this,"headerLayer",null);p(this,"backgroundLayer",null);p(this,"trackLayer",null);p(this,"dragOverlayLayer",null);p(this,"snapGuideLayer",null);p(this,"selectionBoxLayer",null);p(this,"selectionBoxRect",null);p(this,"isBoxSelecting",!1);p(this,"boxSelectStartX",0);p(this,"boxSelectStartY",0);p(this,"resizeObserver",null);p(this,"rootContainer",null);p(this,"layout",null);p(this,"bodyBackgroundRect",null);p(this,"snapGuideLine",null);p(this,"trackInsertionPreviewLine",null);p(this,"trackInsertionPreviewY",null);p(this,"snapGuideTime",null);p(this,"horizontalScrollbar",null);p(this,"verticalScrollbar",null);p(this,"isExecutingHistoryAction",!1);p(this,"lastTrackDuration",0);p(this,"lastReportedTrackDuration",0);p(this,"thumbnailProvider",null);p(this,"thumbnailProviderVersion",0);p(this,"clipThumbnailLoadStates",new Map);p(this,"sourceMediaRegistry",new or);p(this,"canPlay",!1);p(this,"sourceLoadingCount",0);p(this,"timelineStore");p(this,"timelineCommands");p(this,"timelineHistoryExecutor");p(this,"timelineHistoryRecorder");p(this,"timelinePresentationAdapter");p(this,"timelineTrackBridge");p(this,"timelinePlaybackResolver");p(this,"previewRuntimeController");p(this,"previewStateController");p(this,"previewPlaybackSuspendedByBuffering",!1);p(this,"previewPlaybackAutoResume",!1);p(this,"previewBufferingSuspendTimeoutId",null);p(this,"lastSelectedClipId",null);p(this,"previewAspectRatio",{...Ee});p(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});p(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});p(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});p(this,"keyboardShortcutsController",null);p(this,"mountManager",new ns);p(this,"pendingDraftData",null);p(this,"selectionStore",new ga);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);p(this,"splitOperationDepth",0);this.config={duration:e.duration||36e5,zoom:e.zoom||ye.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:jt(e.theme),timeScaleHeight:e.timeScaleHeight,logConfig:e.logConfig,speed:e.speed||1,dragActivationThreshold:e.dragActivationThreshold??4,enableClipSnap:e.enableClipSnap??!1,clipSnapThreshold:e.clipSnapThreshold??8,thumbnailProvider:e.thumbnailProvider,previewBackend:e.previewBackend??"dom",previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont??null,keyboardShortcuts:e.keyboardShortcuts},M.setConfig(this.config.logConfig),M.debug("TimelineManager","日志系统初始化完成",{logConfig:this.config.logConfig}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new Sd,this.eventDispatcher=new Kn({can_play_change:()=>({canPlay:this.canPlay}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new Pr(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Nn(this.history),this.timelineHistoryExecutor=new $n({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 da,this.timelineStore=new is({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new Fn(this.timelineStore),this.timelinePresentationAdapter=new Jn,this.timelineTrackBridge=new Qn({onClipUpdate:(t,i,r)=>this.handleClipUpdate(t,i,r),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),e.draftData&&(this.pendingDraftData=e.draftData),this.config.container&&this.init(this.config.container)}getTimelineStore(){var e,t,i,r,n;if(!this.timelineStore){const s=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,h=((r=this.config)==null?void 0:r.zoom)||ye.MEDIUM,c=((n=this.config)==null?void 0:n.duration)||36e5;this.timelineStore=new is({currentTime:s,playState:o,speed:l,zoom:h,duration:c})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new Fn(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new vd(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new Jn),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Qn({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this)})),this.timelineTrackBridge}getTimelinePlaybackResolver(){return this.timelinePlaybackResolver||(this.timelinePlaybackResolver=new Jc),this.timelinePlaybackResolver}get previewSession(){return this.getPreviewRuntimeController().previewSession}set previewSession(e){this.getPreviewRuntimeController().previewSession=e}get previewMountContainer(){return this.getPreviewRuntimeController().previewMountContainer}set previewMountContainer(e){this.getPreviewRuntimeController().previewMountContainer=e}get resolvedPreviewBackend(){return this.getPreviewRuntimeController().resolvedPreviewBackend}set resolvedPreviewBackend(e){this.getPreviewRuntimeController().resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this.getPreviewRuntimeController().runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this.getPreviewRuntimeController().runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this.getPreviewRuntimeController().activePreviewCallbackToken}set activePreviewCallbackToken(e){this.getPreviewRuntimeController().activePreviewCallbackToken=e}get previewSourceLoadingCount(){return this.getPreviewStateController().previewSourceLoadingCount}set previewSourceLoadingCount(e){this.getPreviewStateController().previewSourceLoadingCount=e}get previewBuffering(){return this.getPreviewStateController().previewBuffering}set previewBuffering(e){this.getPreviewStateController().previewBuffering=e}get pendingPreviewState(){return this.getPreviewStateController().pendingPreviewState}set pendingPreviewState(e){this.getPreviewStateController().pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this.getPreviewStateController().nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this.getPreviewStateController().nextPendingPreviewSyncRequestId=e}getPreviewStateController(){return this.previewStateController||(this.previewStateController=new id({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitBufferingStateChange:e=>{this.syncPlaybackClockToPreviewBuffering(e),this.emitEvent("buffering_state_change",{isBuffering:e})},emitSourceLoadingStateChange:()=>{this.emitEvent("source_loading_change",this.getSourceLoadingState())},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new Qc({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Yc({callbacks:t,previewSourceResolver:this.config.previewSourceResolver,textPreviewFont:this.config.textPreviewFont,sourceMediaRegistry:this.sourceMediaRegistry}),resolveConfiguredBackend:e=>e||Xc(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onBufferingStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleBufferingStateChange(t)},onSourceLoadingChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleSourceLoadingChange(t)},onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleRuntimeStateChange(t)},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=$e(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(e)&&this.retryPendingPreview()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Kn({can_play_change:()=>({canPlay:this.canPlay??!1}),selection_change:()=>this.resolveSelectionChangeData(),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 Pr(()=>{},()=>{})),this.timelineHistoryRecorder=new Nn(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new $n({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)})),this.timelineHistoryExecutor}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:36e5,zoom:ye.MEDIUM,currentTime:0,playState:"paused",theme:jt(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,clipSnapThreshold:8,previewBackend:"dom",textPreviewFont:null}),this.config}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(e){this.getTimelineStore().setPlayState(e),this.ensureConfigState().playState=e}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(e){this.getTimelineStore().setDuration(e),this.ensureConfigState().duration=e}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(e){this.getTimelineStore().setScrollLeft(e)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(e){this.getTimelineStore().setScrollTop(e)}setViewportMetrics(e,t,i){const r=this.getTimelineStore();r.setViewportWidth(e),r.setViewportHeight(t),r.setContentHeight(i)}syncCurrentTimeToScene(e){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncZoomToScene(e){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncScrollTopPresentation(e){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,e)}refreshScrollbarMetrics(){var i,r,n,s;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(r=this.verticalScrollbar)==null||r.resize(),(n=this.horizontalScrollbar)==null||n.setViewportMetrics(e,this.getHorizontalContentWidth()),(s=this.verticalScrollbar)==null||s.setViewportMetrics(t,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientWidth)||0}getViewportHeight(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return F.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(e){const t=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(t,e))}clampScrollTop(e){const t=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(t,e))}syncScrollLeft(e){var i,r;const t=this.clampScrollLeft(e);this.setScrollLeftState(t),(i=this.timeline)==null||i.setScrollLeft(t),(r=this.horizontalScrollbar)==null||r.setScrollLeft(t),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),t),this.refreshSnapGuideLine()}syncScrollTop(e){var i;const t=this.clampScrollTop(e);this.setScrollTopState(t),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-t)>.5&&(this.layout.bodyViewport.scrollTop=t),this.syncScrollTopPresentation(t)}getResolvedTracksSnapshot(){const e=this.getTrackCollection();return this.trackManager.getTracks().map(t=>{const i=e.findById(t.id);return{...t,clips:i?i.getClips():[...t.clips]}})}getTracksSortedByOrder(){const e=this.getTrackCollection();return this.trackManager.getTracks().slice().sort((t,i)=>t.order-i.order).map(t=>e.findById(t.id)).filter(t=>t!==null)}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(e=>({id:e.id,type:e.type,order:e.order,isMuted:e.isMuted??!1,clips:e.clips}))}buildPlaybackPlan(e=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),e)}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((s,o)=>s.order-o.order);let i=null,r=null,n=Number.POSITIVE_INFINITY;for(const s of t){if(s.type!=="video")continue;const o=[...s.clips].sort((l,h)=>l.startTime-h.startTime);for(const l of o){const h={trackId:s.id,trackType:s.type,trackOrder:s.order,clip:l,mediaTime:l.startTimeAtSource,muted:(s.isMuted??!1)||(l.isMuted??!1),kind:s.type,hasVisual:!0,hasAudio:!0};i||(i=h);const c=e.get(l.id);c===void 0||c>=n||(r=h,n=c)}}return r||i}registerPreviewAutoAspectRatioClip(e){const t=this,i=this.getPreviewAutoAspectRatioClipOrderMap();e.type!=="video"||i.has(e.id)||(i.set(e.id,this.getNextPreviewAutoAspectRatioOrder()),t.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}syncPreviewSession(){var r,n,s;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;const e=this.buildPlaybackPlan(),t=this.getAutoAspectRatioClip(),i=$e(this.previewAspectRatio);this.previewAspectRatio=i,this.previewSession.applyAspectRatio(i),this.previewSession.sync({...e,autoAspectRatioClip:t,currentTime:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),primarySelectedClipId:this.getPrimarySelectedClipId(),...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),(s=(n=this.previewSession).setPendingState)==null||s.call(n,this.buildPreviewPendingState())}beginPendingPreview(e,t="seek"){var r,n;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;const i=((n=this.pendingPreviewState)==null?void 0:n.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPlayStateState()==="playing"&&this.pause(),this.getPreviewStateController().beginPendingPreview(e,t,i)}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState()}destroyPreviewSession(e=!1){this.getPreviewRuntimeController().destroyPreviewSession(e),this.resetPreviewRuntimeState()}retryPendingPreview(){this.getPreviewStateController().retryPendingPreview()}handlePreviewBackendRuntimeError(){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();const e=this.getPreviewRuntimeController().fallbackToDom($e(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,r,n,s,o,l,h;if(this.isInitialized){M.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=xd(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:ua,scrollbarSize:pa}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(r=(i=this.layout.bodyCanvasHost).addEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(s=(n=this.rootContainer)==null?void 0:n.addEventListener)==null||s.call(n,"wheel",this.rootWheelListener,{passive:!1}),this.initKeyboardShortcuts(),this.headerStage=new q.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new q.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new q.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new q.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new q.Layer({name:"trackLayer"}),this.dragOverlayLayer=new q.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new q.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new q.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const t=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(t&&t.addEventListener("mousedown",this.handleStageMouseDown.bind(this)),this.timeline=new Ad(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new Ar(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 rs({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:ue,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new rs({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:c=>{this.syncScrollTop(c)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(e),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(h=this.stage)==null||h.batchDraw(),this.pendingDraftData){const c=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(c).catch(d=>{M.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,n){var d,u,g;if(!this.trackLayer)return M.error("TimelineManager","Track layer not initialized"),"";const s=this.trackManager.createTrack(e,t,i,r,n),o=s.id,l=tt(e),h=this.calculateTrackY(o),c=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:o,clips:[],role:s.role},trackType:e,zoom:this.getZoomState(),trackY:h,trackHeight:l,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(d=c.setSnapTargetResolver)==null||d.call(c,()=>this.getClips()),(u=c.setDragOverlayLayer)==null||u.call(c,this.dragOverlayLayer),this.getTrackCollection().add(c),this.updateAllTrackPositions(),(g=this.stage)==null||g.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),o}removeTrack(e){var r,n,s,o;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return M.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return M.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((s=(n=t.getTrackGroup)==null?void 0:n.call(t))==null||s.destroy(),this.getTrackCollection().removeById(e),this.updateAllTrackPositions(),(o=this.stage)==null||o.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),i}renameTrack(e,t){const i=this.trackManager.renameTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}getTracks(){return this.getResolvedTracksSnapshot()}initTrackInfoPanel(e){M.warn("TimelineManager","initTrackInfoPanel() is deprecated. TimelineManager now manages the frozen track-info panel inside the root container.")}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){const i=this.trackManager.muteTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return Rt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return es(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=bd(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const r of e){const n=this.getTrackCollection().findById(r.trackId);n&&((t=n.setTrackY)==null||t.call(n,r.y),(i=n.setTrackHeight)==null||i.call(n,r.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}cleanupEmptyTracks(){var t,i,r,n;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return;const e=this.getTrackCollection().removeEmptyNonPrimaryTracks();if(e.length!==0){for(const s of e){const o=(t=s.getId)==null?void 0:t.call(s);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(r=(i=s.getTrackGroup)==null?void 0:i.call(s))==null||r.destroy(),this.getTrackCollection().removeById(o))}this.updateAllTrackPositions(),(n=this.stage)==null||n.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()}}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDropPreview)==null?void 0:t.call(e)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(e,t){this.showClipDropPreviews(new Map([[t,[e]]]))}showClipDropPreviews(e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(t=>{var n,s,o,l;const i=(n=t.getId)==null?void 0:n.call(t),r=i?e.get(i)??[]:[];if(r.length>0){r.length===1?(s=t.showClipDropPreview)==null||s.call(t,r[0]):(o=t.showClipDropPreviews)==null||o.call(t,r);return}(l=t.clearClipDropPreview)==null||l.call(t)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const e=se.createLine([0,0,0,0],this.getSnapGuideAccentColor(),2);e.name("timeline-track-insertion-preview-line"),e.dash([8,4]),e.visible(!1),e.listening(!1),this.snapGuideLayer.add(e),this.trackInsertionPreviewLine=e}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(e=!0){var i,r,n;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),e&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const t=((r=this.stage)==null?void 0:r.width())??0;this.trackInsertionPreviewLine.stroke(this.getSnapGuideAccentColor()),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,t,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(t>0),this.trackInsertionPreviewLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(n=>{var s;return(s=n.clearClipDropPreview)==null?void 0:s.call(n)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const r=this.trackManager.getTracks(),n=r.find(h=>h.role==="primary"),s=r.find(h=>h.type===e),o=[...r].reverse().find(h=>h.type===e);if((t==="before_track"||t==="after_track")&&i){const h=r.find(c=>c.id===i);if(h){const c=Rt(r,h.id,this.getTrackContentTopOffset());return t==="before_track"?c:c+tt(h.type)}}if(t==="top_of_type_region"&&s)return Rt(r,s.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Rt(r,o.id,this.getTrackContentTopOffset())+tt(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():es(r,this.getTrackContentTopOffset());const l=Rt(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+tt(n.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),r=Math.max(i,t),n=this.clampScrollLeft(this.getScrollLeftState()),s=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(e,t,r),this.headerStage.width(e),this.timeline.resize(e),this.stage.width(e),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${r}px`,this.renderBodyBackground(e,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+t),this.refreshScrollbarMetrics(),this.syncScrollLeft(n),this.syncScrollTop(s),this.stage.batchDraw()}renderBodyBackground(e,t,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(e),this.bodyBackgroundRect.height(t),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const r=new q.Rect({x:0,y:0,width:e,height:t,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});r.on("click",n=>{this.handleBodyBackgroundClick(n.evt.offsetX)}),this.bodyBackgroundRect=r,this.backgroundLayer.add(r),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(e){const t=F.pixelsToTime(e-ue+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,t))}handleBodyCanvasHostClick(e){if(!this.layout||e.target!==this.layout.bodyCanvasHost)return;const t=this.layout.bodyCanvasHost.getBoundingClientRect(),i=e.clientX-t.left;this.handleBodyBackgroundClick(i)}getSnapGuideAccentColor(){return this.config.theme.snapGuideLineColor||Q.snapGuideLineColor}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=se.createLine([0,0,0,this.calculateTotalHeight()],this.getSnapGuideAccentColor(),e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var r,n;if(!this.snapGuideLine)return;const t=this.config.theme;if(this.snapGuideLine.stroke(this.getSnapGuideAccentColor()),this.snapGuideLine.strokeWidth(t.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),e&&((r=this.snapGuideLayer)==null||r.batchDraw());return}const i=me(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const n=this.getPrimaryWheelDelta(t,i);if(n===0)return;e.preventDefault(),this.handleWheelZoom(n,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const n=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(n===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+n);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===Rd)return e*16;if(t===Md){const r=i==="x"?this.getViewportWidth():this.getViewportHeight();return e*(r||1)}return e}getPrimaryWheelDelta(e,t){return Math.abs(t)>=Math.abs(e)?t:e}isHorizontalWheelGesture(e,t){const i=Math.abs(e);if(i<.5)return!1;const r=Math.abs(t);return r<.5?!0:i>r*1.2}getHorizontalScrollDelta(e,t,i){return i&&Math.abs(t)>=Math.abs(e)?t:e}handleWheelZoom(e,t){const i=this.getZoomState(),r=Math.exp(-e*.002),n=Math.max(ye.MIN,Math.min(ye.MAX,i*r));Math.abs(n-i)<1e-4||this.setZoomCenteredOnTimelinePointer(n,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var n;const t=(n=this.layout)==null?void 0:n.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const r=e-t.left;return Math.max(0,Math.min(i,r))}play(){if(this.getPlayStateState()!=="playing"){if(this.pendingPreviewState){M.debugLazy("TimelineManager",()=>"Play blocked by pending preview state");return}if(!this.canPlay){M.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}this.setPlayStateState("playing"),this.lastUpdateTime=Date.now(),this.previewBuffering?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession()}}pause(){this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession())}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused")return;if(this.previewBuffering){this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0,this.animationFrameId=null;return}const e=Date.now(),t=e-this.lastUpdateTime;this.lastUpdateTime=e;const i=this.getCurrentTimeState()+t*this.getSpeedState();this.setCurrentTime(i),this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}syncPlaybackClockToPreviewBuffering(e){if(e){if(this.getPlayStateState()!=="playing"||(this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering||this.previewBufferingSuspendTimeoutId))return;this.previewBufferingSuspendTimeoutId=setTimeout(()=>{this.previewBufferingSuspendTimeoutId=null,!(this.getPlayStateState()!=="playing"||!this.previewBuffering||this.previewPlaybackSuspendedByBuffering)&&(this.previewPlaybackSuspendedByBuffering=!0,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null))},Dd);return}if(this.clearPreviewBufferingSuspendTimeout(),!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&this.getPlayStateState()==="playing"&&!this.pendingPreviewState;this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,!(!t||this.animationFrameId)&&(this.lastUpdateTime=Date.now(),this.animate())}clearPreviewBufferingSuspendTimeout(){this.previewBufferingSuspendTimeoutId&&(clearTimeout(this.previewBufferingSuspendTimeoutId),this.previewBufferingSuspendTimeoutId=null)}setCurrentTime(e){const t=this.getTimelineCommands().setCurrentTime(e);if(!t.changed){this.pendingPreviewState&&this.pendingPreviewState.targetTime===t.nextValue&&this.syncPreviewSession();return}const i=t.nextValue;this.ensureConfigState().currentTime=i,this.syncCurrentTimeToScene(i),this.emitEvent("time_change",{time:i}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(e){this.ensureConfigState().enableClipSnap=e,e||this.updateSnapGuideLine(null),this.tracks.forEach(t=>{t.setClipSnapEnabled(e)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setZoom(e){const t=this.getTimelineCommands().setZoom(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(e){const t=this.getZoomState(),i=this.getCurrentTimeState(),r=this.getTimelineCommands().setZoom(e);if(!r.changed)return;const n=r.nextValue;if(this.ensureConfigState().zoom=n,this.syncZoomToScene(n),this.refreshScrollbarMetrics(),this.timeline){const s=this.timeline.getScrollLeft(),o=F.timeToPixels(i,t),h=F.timeToPixels(i,n)-o+s;this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft())}this.emitEvent("zoom_change",{zoom:n})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),r=this.timeline.getScrollLeft(),n=F.pixelsToTime(t-ue+r,i),s=this.getTimelineCommands().setZoom(e);if(!s.changed)return;const o=s.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const h=F.timeToPixels(n,o)-(t-ue);this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft()),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(e){const t=this.getTimelineCommands().setSpeed(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount+this.previewSourceLoadingCount>0}getSourceLoadingState(){const e=this.sourceLoadingCount+this.previewSourceLoadingCount;return{isLoading:e>0,pending:e}}setThumbnailProvider(e){this.thumbnailProvider=e,this.thumbnailProviderVersion+=1,this.config.thumbnailProvider=e,this.clipThumbnailLoadStates.clear(),this.sourceMediaRegistry.clearThumbnailCache(),this.getClips().forEach(i=>{this.primeOrLoadClipThumbnails(i,{allowPrimeExisting:!1,force:!0})})}async loadClipThumbnails(e,t={}){if(!this.thumbnailProvider||e.type!=="video")return!1;const i=this.thumbnailProvider,r=this.buildClipThumbnailLoadSignature(e,this.thumbnailProviderVersion),n=this.clipThumbnailLoadStates.get(e.id);if((n==null?void 0:n.signature)===r){if(n.promise)return n.promise;if(n.completed&&!t.force)return!0}let s=!1;const o=this.sourceMediaRegistry.getThumbnails(this.buildClipThumbnailResourceKey(e),async()=>{const l=await Promise.resolve(i.getThumbnails(e));return Array.isArray(l)?l:[]},{force:t.force}).then(l=>{try{if(!Array.isArray(l))return!1;s=!0;const h=this.findClipById(e.id)??e;return this.isClipThumbnailLoadCurrent(e.id,r)?(this.areThumbnailArraysEqual(h.thumbnails,l)||this.updateClip(e.id,{thumbnails:l}),M.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(h){return M.warn("TimelineManager","Error loading clip thumbnails:",{error:h,clipId:e.id}),!1}}).finally(()=>{const l=this.clipThumbnailLoadStates.get(e.id);(l==null?void 0:l.signature)===r&&(l.promise=null,l.completed=s,s||this.clipThumbnailLoadStates.delete(e.id))});this.clipThumbnailLoadStates.set(e.id,{signature:r,promise:o,completed:!1});try{return await o}catch{return!1}}async refreshClipThumbnails(e){const t=this.getClips().find(i=>i.id===e);return t?this.loadClipThumbnails(t,{force:!0}):!1}async refreshAllClipThumbnails(){const e=this.getClips();return await Promise.all(e.map(i=>this.loadClipThumbnails(i,{force:!0})))}async addClip(e){this.beginSourceLoading();try{return await this.addClipInternal(e)}finally{this.endSourceLoading()}}async addClips(e){if(e.length===0)return[];this.beginSourceLoading();try{const t=[],i=new Map,r=new Map,n=!!this.trackManager;for(const s of e){const o=n?this.resolveBatchClipConfig(s,i,r):s,l=await this.addClipInternal(o);if(t.push(l),!n||s.startTime!==void 0||s.trackId)continue;const h=this.getClips().find(d=>d.id===l),c=this.resolveTrackIdByClipId(l);!h||!c||(i.set(h.type,c),r.set(c,h.endTime))}return t}finally{this.endSourceLoading()}}resolveBatchClipConfig(e,t,i){if(e.startTime!==void 0||e.trackId)return e;const r=e.type||"video",n=t.get(r)||this.resolveBatchAppendTrackId(r);if(!n)return e;const s=i.get(n)??this.getTrackTimelineExtentById(n);return{...e,trackId:n,startTime:s}}resolveBatchAppendTrackId(e){const t=this.getTracksSortedByOrder(),i=t.find(s=>{var o,l;return((o=s.getRole)==null?void 0:o.call(s))==="primary"&&((l=s.getTrackType)==null?void 0:l.call(s))===e});if(i)return i.getId();const r=t.find(s=>{var o;return((o=s.getTrackType)==null?void 0:o.call(s))===e});return r?r.getId():this.createTrack(e)||null}getTrackTimelineExtentById(e){const t=this.getTrackCollection().findById(e);return t?_r(t.getClips()):0}async addClipInternal(e){var C;let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.type||"video",r=i==="text",n=e.src??"",s=e.duration??(r?3e3:0),o=e.name??(r?"文本":`${i}_${Date.now()}`);if(!r&&(!e.name||s<=0))throw new Error(`addClip requires name and duration for ${i} clips`);const l=r?0:e.startTimeAtSource||0,h=r?s:e.endTimeAtSource||l+s;let c=r?s:e.sourceDuration;if(!c)try{c=await F.getVideoDuration(n,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),c<=0&&(c=h)}catch(T){M.error("TimelineManager","Failed to get video duration:",{error:T}),c=h}!r&&c>0&&this.sourceMediaRegistry.primeDuration(this.buildSourceMediaKey(e),c);let d=e.thumbnails;const u=e.id||`clip_${o}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=Rr({id:u,type:i,externalId:e.externalId,src:n,name:o,isMuted:e.isMuted??!1,startTime:t,duration:s,startTimeAtSource:l,endTimeAtSource:h,sourceDuration:c,endTime:t+s,thumbnails:d,style:e.style,visualTransform:r||i==="video"?ke(e.visualTransform):e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1,textContent:e.textContent??(r?"默认文本":void 0),textStyle:r?vt(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});if(M.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:g.id,type:g.type,startTime:g.startTime,duration:g.duration})),e.trackId){const T=this.getTrackCollection().findById(e.trackId);if(T)return this.registerPreviewAutoAspectRatioClip(g),(C=T.addClip)==null||C.call(T,g),Ii({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(g)},applyEffects:()=>Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(g),g.id}const f=this.getTimelineCommands().planTrackPlacement(g,this.getTracksSortedByOrder()),y=this.getTrackCollection(),v=gd({clip:g,placement:f,trackCollection:y,createTrack:this.createTrack.bind(this)});return Ii({applied:v,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(g)},applyEffects:()=>Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(g),g.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),Ii({applied:Zn(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)})}))}removeClipsByExternalId(e){if(!e)return!1;const t=this.resolveClipIdsForExternalIdRemoval(e);if(t.length===0)return!1;const i=new Set(t);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let r=!1;return this.withClipRemovalBatch(()=>{for(const n of t){const s=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);s.exists&&(r=Zn(this.getTrackCollection(),s,n)||r)}}),r?(Ti({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){if(this.getTimelineCommands().findClipById(this.tracks,e)){if(this.getTrackCollection().updateClip(e,t),Object.prototype.hasOwnProperty.call(t,"thumbnails")){const i=this.findClipById(e);i&&this.markClipThumbnailLoadCompleted(i)}Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);if((i==null?void 0:i.clip.type)==="text")return;const r=i==null?void 0:i.track.splitSelectedClip;r&&(this.withSplitOperation(()=>{r.call(i.track,t)}),Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e);if((t==null?void 0:t.clip.type)==="text")return;const i=t==null?void 0:t.track.splitSelectedClip;i&&(this.withSplitOperation(()=>{i.call(t.track,e)}),Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var n,s,o;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(Ct(e.mode)&&t===Ee.width&&i===Ee.height){const l=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,h=(s=l==null?void 0:l.style)==null?void 0:s.sys_width,c=(o=l==null?void 0:l.style)==null?void 0:o.sys_height;typeof h=="number"&&h>0&&typeof c=="number"&&c>0&&(t=h,i=c)}const r=Lr({width:t,height:i});return{width:r.width,height:r.height,aspectRatio:`${r.width}:${r.height}`,mode:e.mode}}getExportCoverUrl(e){var r;let t=null,i=null;for(const n of e)for(const s of n.clips)if(s.type==="video"){if(!t||!i){t=n,i=s;continue}if(s.startTime<i.startTime){t=n,i=s;continue}s.startTime===i.startTime&&n.order<t.order&&(t=n,i=s)}return((r=i==null?void 0:i.thumbnails)==null?void 0:r[0])||""}exportTimeline(){const e=this.getResolvedTracksSnapshot().slice().sort((i,r)=>i.order-r.order).map(i=>{const r=i.clips.map(n=>({id:n.id,type:n.type,externalId:n.externalId,src:n.src,name:n.name,isMuted:n.isMuted??!1,startTime:Math.round(n.startTime),duration:Math.round(n.duration),endTime:Math.round(n.endTime),startTimeAtSource:Math.round(n.startTimeAtSource),endTimeAtSource:Math.round(n.endTimeAtSource),sourceDuration:Math.round(n.sourceDuration),thumbnails:n.thumbnails,visualTransform:n.type==="video"||n.type==="text"?ke(n.visualTransform):void 0,separatedAudioClipId:n.separatedAudioClipId,separatedFromVideoClipId:n.separatedFromVideoClipId,volume:n.volume??1,textContent:n.textContent,textStyle:n.textStyle,ttsSourceTextClipId:n.ttsSourceTextClipId,ttsVoiceId:n.ttsVoiceId,ttsVoiceName:n.ttsVoiceName,ttsFollowTextUpdates:n.ttsFollowTextUpdates})).sort((n,s)=>n.startTime-s.startTime);return{id:i.id,type:i.type,name:i.name||"未命名轨道",order:i.order,role:i.role??"normal",isMuted:i.isMuted??!1,clips:r}}),t=this.getExportCoverUrl(e);return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){M.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const t=new Map,i=[...e.tracks].sort((h,c)=>h.order-c.order),r=this.resolveImportedTrackRoles(i);let n;for(const h of i){const c=this.createTrack(h.type,h.name,n?"after_track":void 0,n,r.get(h.id));c&&(this.muteTrack(c,h.isMuted),t.set(h.id,c),n=c)}const s=new Map,o=[];for(const h of i){const c=t.get(h.id);if(c)for(const d of h.clips)try{let u=d.separatedAudioClipId;u&&s.has(u)&&(u=s.get(u));let g=d.separatedFromVideoClipId;g&&s.has(g)&&(g=s.get(g));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:g,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,ttsSourceTextClipId:d.ttsSourceTextClipId,ttsVoiceId:d.ttsVoiceId,ttsVoiceName:d.ttsVoiceName,ttsFollowTextUpdates:d.ttsFollowTextUpdates,trackId:c},y=await this.addClip(f);s.set(d.id,y)}catch(u){o.push({clipId:d.id,error:u}),M.error("TimelineManager",`Failed to import clip ${d.id}:`,{error:u})}}this.clearHistory();const l={errors:o};this.emitEvent("draft_loaded",l)}resolveImportedTrackRoles(e){const t=new Map;let i=!1;for(const n of e){const s=n.role==="primary"&&!i?"primary":"normal";s==="primary"&&(i=!0),t.set(n.id,s)}if(i)return t;const r=this.inferImportedPrimaryTrackIndex(e);return r>=0&&t.set(e[r].id,"primary"),t}inferImportedPrimaryTrackIndex(e){var t;for(let i=e.length-1;i>=0;i-=1)if(((t=e[i])==null?void 0:t.type)==="video")return i;return e.length>0?0:-1}stopPlaybackForImport(){var i;const e=this.getPlayStateState()==="playing",t=(i=this.previewSession)!=null&&i.hasPreview()?this.previewMountContainer:null;this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),e?this.pause():this.setPlayStateState("paused"),this.destroyPreviewSession(!0),t&&(this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t,this.previewAspectRatio)),this.syncPreviewSession()}getClipsData(){return this.getClips()}getVersion(){return Ld.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(h=>h.startTime)),r=(Math.max(...e.map(h=>h.endTime))-t)/1e3,n=((l=this.stage)==null?void 0:l.width())||0,s=n-ue*2;M.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:s}));const o=Math.min(s/r,ye.MAX);if(this.setZoom(o),this.timeline){const h=e.reduce((c,d)=>d.startTime<c.startTime?d:c);this.scrollToClip(h.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){this.beginPendingPreview(e,t),this.setCurrentTime(e)}handleScrollChange(e){this.syncScrollLeft(e)}handleClipUpdate(e,t,i){this.isExecutingHistoryAction||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i),this.emitEvent("clip_updated",{clip:e});const r=this.selectedClipId===e.id;Sc({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),r&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){this.splitOperationDepth>0||(this.registerPreviewAutoAspectRatioClip(e),this.emitEvent("clip_added",{clip:e}),Ti({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}))}handleClipRemove(e){this.clipThumbnailLoadStates.delete(e),!(this.splitOperationDepth>0)&&(this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Ti({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}))}reloadClipThumbnailsIfNeeded(e,t){Cc(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{M.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){var n;const e=this.getClips(),t=this.getCurrentTime(),i=vc(e,t),r=this.canPlay;this.canPlay=Tc({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:((n=e[e.length-1])==null?void 0:n.endTime)||1,setCanPlay:s=>{this.canPlay=s},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:s=>{this.emitEvent("can_play_change",{canPlay:s})}}),r!==this.canPlay&&M.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:r,newState:this.canPlay}))}findClipById(e){return this.getClips().find(t=>t.id===e)}buildGeneratedAudioClipName(e){return`配音 · ${e}`}normalizeGeneratedAudioDuration(e){return!Number.isFinite(e)||e<=0?1:Math.max(1,Math.round(e))}getVoiceLinkedAudioClips(e){return this.getClips().filter(t=>t.type==="audio"&&t.ttsSourceTextClipId===e)}applyGeneratedAudioClipResult(e,t,i,r,n){const s=this.normalizeGeneratedAudioDuration(r.duration);this.updateClip(e,{src:r.audioSrc,name:this.buildGeneratedAudioClipName(r.voiceName),textContent:i,duration:s,startTimeAtSource:0,endTimeAtSource:s,sourceDuration:s,ttsSourceTextClipId:t,ttsVoiceId:r.voiceId,ttsVoiceName:r.voiceName,ttsFollowTextUpdates:n})}syncTextClipDurationToAudio(e,t){const i=this.normalizeGeneratedAudioDuration(t),r=this.findClipById(e);r&&r.duration===i&&r.endTimeAtSource===i&&r.sourceDuration===i||this.updateClip(e,{duration:i,endTimeAtSource:i,sourceDuration:i})}doesClipOverlapOnTrack(e,t){const i=this.getTrackCollection().findById(e);if(!i)return!1;const r=t.startTime+t.duration;return i.getClips().some(n=>n.id!==t.id&&t.startTime<n.endTime&&r>n.startTime)}findNearestAvailableTrackForClip(e,t){const i=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),r=i.findIndex(o=>o.id===t);if(r===-1)return null;const s=i.map((o,l)=>({track:o,index:l,distance:Math.abs(l-r)})).filter(({track:o})=>o.id!==t&&o.type===e.type).sort((o,l)=>{if(o.distance!==l.distance)return o.distance-l.distance;const h=o.index>r?0:1,c=l.index>r?0:1;return h-c}).find(({track:o})=>!this.doesClipOverlapOnTrack(o.id,e));return(s==null?void 0:s.track.id)??null}relocateGeneratedAudioClipIfNeeded(e){const t=this.findClipById(e);if(!t||t.type!=="audio")return;const i=this.resolveTrackIdByClipId(e);if(!i||!this.doesClipOverlapOnTrack(i,t))return;const r=this.findNearestAvailableTrackForClip(t,i);if(r){this.moveClipToTrack(e,r);return}const n=this.createTrack("audio",void 0,"after_track",i)||this.createTrack("audio",void 0,"bottom_of_type_region");n&&this.moveClipToTrack(e,n)}async regenerateVoiceLinkedAudioClips(e,t,i){const r=this.getVoiceLinkedAudioClips(e).filter(h=>h.ttsFollowTextUpdates===!0&&!!h.ttsVoiceId);if(r.length===0)return;const n=r.map((h,c)=>({requestId:`regen:${h.id}:${Date.now()}:${c}`,sourceTextClipId:e,targetAudioClipId:h.id,text:t,voiceId:h.ttsVoiceId,followTextUpdates:!0,mode:"replace"})),s=await i(n),o=new Map(s.map(h=>[h.requestId,h]));let l=0;n.forEach(h=>{const c=o.get(h.requestId);!c||!h.targetAudioClipId||(this.applyGeneratedAudioClipResult(h.targetAudioClipId,e,t,c,h.followTextUpdates),this.relocateGeneratedAudioClipIfNeeded(h.targetAudioClipId),l=Math.max(l,this.normalizeGeneratedAudioDuration(c.duration)))}),l>0&&this.syncTextClipDurationToAudio(e,l),this.handleClipChange()}async handleVoiceGenerateAction(e,t,i,r,n){if(t.type==="text"){const h=`create:${t.id}:${i.id}:${Date.now()}`,[c]=await n([{requestId:h,sourceTextClipId:t.id,text:t.textContent??t.name??"",voiceId:i.id,followTextUpdates:r,mode:"create"}]);if(!c)throw new Error("生成音频失败:未返回音频结果");const d=this.normalizeGeneratedAudioDuration(c.duration),u=t.textContent??t.name??"";this.syncTextClipDurationToAudio(t.id,d),e.setPreferredTab("voice");const g=await this.addClip({type:"audio",src:c.audioSrc,name:this.buildGeneratedAudioClipName(c.voiceName),textContent:u,startTime:t.startTime,duration:d,startTimeAtSource:0,endTimeAtSource:d,sourceDuration:d,ttsSourceTextClipId:t.id,ttsVoiceId:c.voiceId,ttsVoiceName:c.voiceName,ttsFollowTextUpdates:r});this.scrollToClip(g,{selectClip:!0,setCurrentTime:!0});return}if(t.type!=="audio"||!t.ttsSourceTextClipId)return;const s=this.findClipById(t.ttsSourceTextClipId);if(!s||s.type!=="text")throw new Error("未找到配音关联的文本片段");const o=`replace:${t.id}:${i.id}:${Date.now()}`,[l]=await n([{requestId:o,sourceTextClipId:s.id,targetAudioClipId:t.id,text:s.textContent??s.name??"",voiceId:i.id,followTextUpdates:r,mode:"replace"}]);if(!l)throw new Error("替换音色失败:未返回音频结果");e.setPreferredTab("voice"),this.applyGeneratedAudioClipResult(t.id,s.id,s.textContent??s.name??"",l,r),this.relocateGeneratedAudioClipIfNeeded(t.id),this.syncTextClipDurationToAudio(s.id,l.duration),this.handleClipChange()}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{M.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){M.warn("TimelineManager","Error loading clip thumbnails:",{error:i,clipId:e.id})}}markClipThumbnailLoadCompleted(e){return Array.isArray(e.thumbnails)?(this.sourceMediaRegistry.primeThumbnails(this.buildClipThumbnailResourceKey(e),e.thumbnails),this.clipThumbnailLoadStates.set(e.id,{signature:this.buildClipThumbnailLoadSignature(e),promise:null,completed:!0}),!0):!1}buildClipThumbnailLoadSignature(e,t=this.thumbnailProviderVersion){return[t,e.type,e.src,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}buildSourceMediaKey(e){return or.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return or.buildThumbnailKey({...e,externalId:e.externalId})}isClipThumbnailLoadCurrent(e,t){var i;return((i=this.clipThumbnailLoadStates.get(e))==null?void 0:i.signature)===t}areThumbnailArraysEqual(e,t){return!e||e.length!==t.length?!1:e.every((i,r)=>i===t[r])}handleClipSplit(e,t){kc({clip1:e,clip2:t,isExecutingHistoryAction:this.isExecutingHistoryAction,recordSplitClip:this.getTimelineHistoryRecorder().recordSplitClip.bind(this.getTimelineHistoryRecorder()),emitClipUpdated:i=>{this.emitEvent("clip_updated",{clip:i})},emitClipAdded:i=>{this.emitEvent("clip_added",{clip:i})},applyEffects:()=>Ti({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=bc(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),M.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){M.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeUndo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}handleActionRedo(e){M.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeRedo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}on(e,t){this.getEventDispatcher().on(e,t)}off(e,t){this.getEventDispatcher().off(e,t)}emitEvent(e,t){this.getEventDispatcher().emit(e,t)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=pd({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}handleClipOverlap(e,t){M.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const i=this.getTrackCollection();if(!i.findById(t))return;const r=e.type,n=this.trackManager.getTracksByType(r).length+1,s=`${Od(r)}轨道 ${n}`;md({clip:e,currentTrackId:t,trackType:r,trackName:s,trackCollection:i,createTrack:this.createTrack.bind(this)}),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const r=this.resolveCrossTrackPreviewDestination(e,t,i);return r.status==="existing_track"?(this.showClipDropPreview(e,r.targetTrackId),r.targetTrackId===i?"self":"external"):r.status==="new_track_insertion"?(this.showTrackInsertionPreview(r.trackType,r.insertionPlacement,r.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,r){M.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:r}));const n=this.resolveCrossTrackMoveDestination(e,i,r);return n.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):n.status==="same_track"?(M.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(M.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:n.targetTrackId})),this.showClipDropPreview(e,n.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,n.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}resize(e,t){this.rootContainer&&(this.rootContainer.style.width=`${e}px`,this.rootContainer.style.height=`${t}px`,this.updateViewportLayout())}scrollToTime(e,t=!1){this.timeline&&(this.timeline.scrollToTime(e),this.handleScrollChange(this.timeline.getScrollLeft()),t&&this.setCurrentTime(e))}notifySelectionChange(){const e=this.getSelectedClipIds();this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),e)}syncPrimarySelectionFromSelectionStore(){var t,i,r,n;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((n=(r=this.selectionStore)==null?void 0:r.getSelectedClipId)==null?void 0:n.call(r))??null;this.selectedClipId=e}getOrderedSelectionClipIds(e,t){const i=Array.from(new Set(e));if(i.length<=1)return i;const r=t&&i.includes(t)&&t||this.selectedClipId&&i.includes(this.selectedClipId)&&this.selectedClipId||i[0]||null;return r?[r,...i.filter(n=>n!==r)]:i}setSelection(e,t={}){this.resetMultiDragSession();const i=this.getOrderedSelectionClipIds(e,t.preferredPrimaryClipId);this.selectionStore.setSelection(i),this.syncPrimarySelectionFromSelectionStore(),this.notifySelectionChange(),this.emitSelectionChangeEvent(),t.selectedClipEventClip&&this.emitEvent("clip_selected",{clip:t.selectedClipEventClip}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}selectClip(e,t){var r;const i=t||((r=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:r.clip);this.setSelection([e],{preferredPrimaryClipId:e,selectedClipEventClip:i??null})}clearSelection(){this.setSelection([])}getSelectedClipIds(){var e,t;return((t=(e=this.selectionStore)==null?void 0:e.getSelectedClipIds)==null?void 0:t.call(e))??(this.selectedClipId?[this.selectedClipId]:[])}getPrimarySelectedClipId(){return this.getSelectedClipIds()[0]??null}addToSelection(e){this.setSelection([...this.selectionStore.getSelectedClipIds(),e],{preferredPrimaryClipId:this.selectedClipId??e})}removeFromSelection(e){this.setSelection(this.selectionStore.getSelectedClipIds().filter(t=>t!==e))}toggleSelection(e){const t=this.selectionStore.getSelectedClipIds(),i=t.includes(e);this.setSelection(i?t.filter(r=>r!==e):[...t,e],{preferredPrimaryClipId:i?void 0:e})}isClipSelected(e){return this.selectionStore.isSelected(e)}deleteSelectedClips(){this.resetMultiDragSession();const e=this.selectionStore.getSelectedClipIds();if(e.length===0)return;const t=this.getTimelineHistoryRecorder(),i=e.map(n=>{const s=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);return!s.exists||!s.clip?null:t.createRemoveClipAction({...s.clip},s.trackId,s.trackId?this.cloneTrackSnapshot(s.trackId):null,s.trackId?this.getTrackRestoreAnchor(s.trackId):null)}).filter(n=>n!==null);this.clearSelection();const r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const n of e)this.removeClip(n)}finally{this.isExecutingHistoryAction=r}r||t.recordCompoundAction(i,"delete_selected_clips"),this.emitSelectionChangeEvent()}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.setSelection(this.tracks.flatMap(e=>e.getClips().map(t=>t.id)),{preferredPrimaryClipId:this.selectedClipId})}emitSelectionChangeEvent(){this.emitEvent("selection_change",this.resolveSelectionChangeData())}scrollToClip(e,t={}){const{selectClip:i=!1,setCurrentTime:r=!1}=t,n=this.getClips().find(s=>s.id===e);!n||!this.timeline||(this.timeline.scrollToClip(n),this.handleScrollChange(this.timeline.getScrollLeft()),r&&this.setCurrentTime(n.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}canDeleteSelectedClips(){return this.getSelectedClipIds().length>0}canSplitSelectedClip(){const e=this.resolveSelectedClipAtTime(this.getCurrentTime());return!!e&&e.clip.type!=="text"}getSelectedClipAudioAction(){const e=this.getSelectedClips().filter(r=>r.type==="video");return e.length===0?null:e.some(r=>this.canSeparateClipAudio(r.id))?"separate":e.some(r=>this.canRestoreClipAudio(r.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const e=this.getSelectedClipAudioAction();return e?this.applySelectedClipAudioAction(e):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(e){return this.buildPlaybackPlan(e)}getActiveClipsAtTime(e){return this.buildPlaybackPlan(e).activeClips}attachPreview(e){const t=e instanceof HTMLElement?{container:e}:e;t.aspectRatio&&(this.previewAspectRatio=$e({mode:t.aspectRatio.mode??(t.aspectRatio.width&&t.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:t.aspectRatio.width??this.previewAspectRatio.width,height:t.aspectRatio.height??this.previewAspectRatio.height})),this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t.container,this.previewAspectRatio),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){this.getPreviewRuntimeController().detachPreviewSession()&&(this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),M.debugLazy("TimelineManager",()=>"TimelineManager detached from preview container"))}attachClipConfig(e,t={}){const i=new Id,r=t.generateVoiceBatch,n=r,s=r?async h=>{i.setVoiceGenerationBusy(!0);try{return await r(h)}finally{i.setVoiceGenerationBusy(!1)}}:void 0;i.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),voiceCatalog:t.voiceCatalog??[],updateClip:(h,c)=>{const d=this.findClipById(h);this.updateClip(h,c),this.handleClipChange(),n&&(d==null?void 0:d.type)==="text"&&typeof c.textContent=="string"&&c.textContent!==d.textContent&&this.regenerateVoiceLinkedAudioClips(d.id,c.textContent,n).catch(u=>{M.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:u,clipId:h})})},onGenerateVoice:async(h,c,d)=>{if(!s)throw new Error("未配置音色生成回调");await this.handleVoiceGenerateAction(i,h,c,d,s)}});const o=()=>i.updateFromExternal(),l=(h,c)=>{var u;const d=this.getPrimarySelectedClip();d&&((u=c==null?void 0:c.clip)==null?void 0:u.id)===d.id&&i.updateFromExternal()};return this.on("selected_clip_change",o),this.on("clip_updated",l),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",o),this.off("clip_updated",l),i.destroy()}),i.update(),i}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return $e(this.previewAspectRatio)}setPreviewAspectRatio(e){var t;this.previewAspectRatio=$e({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...Ee},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}resolvePreferredSeparatedAudioTrackId(e,t){var l;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return null;const i=this.resolveTrackIdByClipId(e);if(!i)return null;const r=[...this.getResolvedTracksSnapshot()].sort((h,c)=>h.order-c.order),n=r.findIndex(h=>h.id===i);if(n===-1)return null;const s=t.startTime+t.duration,o=r.map((h,c)=>({track:h,index:c})).filter(({track:h})=>h.type==="audio").filter(({track:h})=>!h.clips.some(c=>t.startTime<c.endTime&&s>c.startTime));return o.length===0?null:(o.sort((h,c)=>{const d=Math.abs(h.index-n)-Math.abs(c.index-n);return d!==0?d:h.index-c.index}),((l=o[0])==null?void 0:l.track.id)??null)}async separateClipAudio(e){if(!this.canSeparateClipAudio(e))return null;const t=this.getClips().find(h=>h.id===e);if(!t||t.type!=="video")return null;const i=this.isExecutingHistoryAction,r=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let n=null;this.isExecutingHistoryAction=!0;try{if(n=await this.addClip({type:"audio",src:t.src,name:t.name,startTime:t.startTime,duration:t.duration,startTimeAtSource:t.startTimeAtSource,endTimeAtSource:t.endTimeAtSource,sourceDuration:t.sourceDuration,separatedFromVideoClipId:t.id,isMuted:!1,volume:t.volume??1,trackId:r??void 0}),!n)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:n})}finally{this.isExecutingHistoryAction=i}if(!n)return null;const s=this.getClips().find(h=>h.id===e),o=this.getClips().find(h=>h.id===n)??null,l=this.resolveTrackIdByClipId(n);return s?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,s,o,l),n):null}restoreClipAudio(e){if(!this.canRestoreClipAudio(e))return!1;const t=this.getClips().find(l=>l.id===e);if(!t||t.type!=="video")return!1;const i=t.separatedAudioClipId??null,r=i?this.getClips().find(l=>l.id===i)??null:null,n=i?this.resolveTrackIdByClipId(i):null,s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=s}const o=this.getClips().find(l=>l.id===e);return o?(s||this.getTimelineHistoryRecorder().recordRestoreClipAudio(t,o,r,n),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(o=>o.type==="video"),i=e==="separate"?t.filter(o=>this.canSeparateClipAudio(o.id)):t.filter(o=>this.canRestoreClipAudio(o.id));if(i.length===0)return!1;if(i.length===1){const[o]=i;return e==="separate"?!!await this.separateClipAudio(o.id):this.restoreClipAudio(o.id)}const r=this.getTimelineHistoryRecorder(),n=[],s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{if(e==="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),g=this.getClips().find(f=>f.id===o.id);!u||!g||n.push(r.createRestoreClipAudioAction({...l},{...g},c?{...c}:null,d))}else for(const o of i){const l=this.getClips().find(g=>g.id===o.id);if(!l||l.type!=="video")continue;const h=await this.separateClipAudio(o.id),c=this.getClips().find(g=>g.id===o.id),d=h?this.getClips().find(g=>g.id===h)??null:null,u=h?this.resolveTrackIdByClipId(h):null;!h||!c||n.push(r.createSeparateClipAudioAction({...l},{...c},d?{...d}:null,u))}}finally{this.isExecutingHistoryAction=s}return s||r.recordCompoundAction(n,`selected_clips_audio_${e}`),n.length>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,r=null){const n=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(n.status==="missing_source_track")return M.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(n.status==="noop")return M.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(n.status==="missing_target_track")return M.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(n.status==="track_type_mismatch")return M.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var f,y,v;return{targetTrackType:(y=(f=this.getTrackCollection().findById(t))==null?void 0:f.getTrackType)==null?void 0:y.call(f),clipType:(v=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:v.clip.type}}),!1;if(n.status!=="ready")return!1;const{sourceTrackId:s,targetTrackId:o}=n,l=i?{...i}:{...n.clip},h=r?{...r}:{...n.clip},c=this.cloneTrackSnapshot(s),d=this.cloneTrackSnapshot(o),u=fd({command:{...n,clip:h},trackCollection:this.getTrackCollection()}),g=this.getClips().find(f=>f.id===e)??null;return wc({applied:u,clipId:e,sourceTrackId:s,targetTrackId:o,clipBefore:l,clipAfter:g??l,sourceTrackSnapshot:c,targetTrackSnapshot:d,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>yd({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 qn(this.getClips())}destroy(){var e,t,i,r,n,s,o,l,h,c,d;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPreviewBufferingSuspendTimeout(),this.clearPendingPreviewState(),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(e=this.layout)==null||e.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(r=(t=this.layout)==null?void 0:(i=t.bodyCanvasHost).removeEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(s=(n=this.rootContainer)==null?void 0:n.removeEventListener)==null||s.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()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new ns),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new dd({root:this.rootContainer,config:this.config.keyboardShortcuts,callbacks:{togglePlay:()=>this.togglePlay(),deleteSelectedClips:()=>{this.removeSelectedClips()},toggleSelectedClipsAudio:()=>this.toggleSelectedClipsAudio(),splitCurrentClip:()=>this.splitCurrentClip(),undo:()=>this.undo(),redo:()=>this.redo(),canDeleteSelectedClips:()=>this.canDeleteSelectedClips(),canSplitSelectedClip:()=>this.canSplitSelectedClip(),canToggleSelectedClipsAudio:()=>this.canToggleSelectedClipsAudio()}}),this.keyboardShortcutsController.init(),this.mountManager.register("keyboardShortcuts",()=>{var t;(t=this.keyboardShortcutsController)==null||t.destroy(),this.keyboardShortcutsController=null}))}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(e){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return e()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}withSplitOperation(e){this.splitOperationDepth=(this.splitOperationDepth??0)+1;try{return e()}finally{this.splitOperationDepth=Math.max(0,(this.splitOperationDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(e){const t=this.getClips(),i=new Map(t.map(s=>[s.id,s])),r=new Set,n=t.filter(s=>s.externalId===e).map(s=>s.id);for(let s=0;s<n.length;s+=1){const o=n[s];if(r.has(o))continue;r.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!r.has(l.separatedAudioClipId)&&n.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!r.has(l.separatedFromVideoClipId)&&n.push(l.separatedFromVideoClipId))}return t.filter(s=>r.has(s.id)).map(s=>s.id)}shouldClearSelectionForClipIds(e){return this.selectedClipId&&e.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(t=>e.has(t))}resolveSelectedClipAtTime(e){var i;const t=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const r of t){const n=this.getTimelineCommands().findClipById(this.tracks,r),s=n==null?void 0:n.clip;if(s&&e>=s.startTime&&e<s.endTime)return n}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{if(e.isFinal){const i=this.finalizeMultiDragCrossTrack(t,e);return i||this.syncMultiDragPeerClips(t,e,!0),i}return this.syncMultiDragOverlayState(t,e.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(t,e,!1),e.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(t,e.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(t,e)}finally{e.isFinal&&(this.syncMultiDragOverlayState(t,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((e,t)=>{var i;(i=e.setTrackStackOrder)==null||i.call(e,t)})}elevateMultiDragTrackGroups(e,t){var o,l,h;const i=this.resolveMultiDragSessionTrackIds(e);if(i.length<=1)return;const r=i.indexOf(t);r>=0&&(i.splice(r,1),i.push(t));const n=new Set(i);let s=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,s++)}for(const c of i){const d=this.getTrackCollection().findById(c);(h=d==null?void 0:d.setTrackStackOrder)==null||h.call(d,s++)}}resolveMultiDragSessionTrackIds(e){var i;const t=new Set;for(const r of this.tracks){const n=(i=r.getId)==null?void 0:i.call(r);if(!n)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===n})&&t.add(n)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const r of e.selectedClipIds){const n=e.clips.get(r);if(!n)continue;const s=i.get(n.trackId);s?s.push(r):i.set(n.trackId,[r])}i.forEach((r,n)=>{var o;const s=this.getTrackCollection().findById(n);(o=s==null?void 0:s.setClipsDragOverlayActive)==null||o.call(s,r,t)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDragOverlay)==null?void 0:t.call(e)})}ensureMultiDragSession(e){var r;const t=this.selectionStore.getSelectedClipIds();if(t.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===e.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,t))return this.multiDragSession;const i=new Map;for(const n of t){const s=this.findTrackByClipId(n),o=((r=s==null?void 0:s.getId)==null?void 0:r.call(s))??this.resolveTrackIdByClipId(n),l=s==null?void 0:s.getClips().find(c=>c.id===n);if(!o||!l)continue;const h=n===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(n,{clipId:n,trackId:o,clip:h})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:e.draggedClipId,selectedClipIds:t.slice(),clips:i},this.multiDragSession)}haveSameClipIds(e,t){if(e.length!==t.length)return!1;const i=new Set(t);return e.every(r=>i.has(r))}restoreDraggedClipSnapshot(e,t){const i=Math.max(0,e.startTime-t);return{...e,startTime:i,endTime:i+e.duration}}syncMultiDragPeerClips(e,t,i){for(const r of e.selectedClipIds){if(r===t.draggedClipId)continue;const n=e.clips.get(r);if(!n||n.trackId===t.currentTrackId)continue;const s=this.getTrackCollection().findById(n.trackId);if(!(s!=null&&s.updateClipPosition))continue;const o=Math.max(0,n.clip.startTime+t.deltaTime);s.updateClipPosition(r,o,i,i?0:t.crossTrackOffsetY)}}previewMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackPreviewDestination(r,t.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 s=this.resolveTrackIndexDelta(i.trackId,n.targetTrackId,i.clip.type);if(s===null)return!1;const o=new Map;this.appendPreviewClip(o,n.targetTrackId,r);for(const l of e.selectedClipIds){if(l===t.draggedClipId)continue;const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(h,s,c);!d||d===h.trackId||this.appendPreviewClip(o,d,c)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackMoveDestination(r,t.targetTrackY,i.trackId);if(n.status==="blocked"||n.status==="same_track")return!1;const s=n.targetTrackId;if(!s)return!1;const o=this.resolveTrackIndexDelta(i.trackId,s,i.clip.type);if(o===null)return!1;for(const l of e.selectedClipIds){const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=c.startTime,u=l===t.draggedClipId?s:this.resolveMultiDragTargetTrackId(h,o,c);if(u){if(u===h.trackId){this.updateClipPositionWithHistory(h.trackId,h.clipId,d);continue}this.updateClipPositionSilently(h.trackId,h.clipId,d),this.moveClipToTrackWithHistorySnapshot(h.clipId,u,h.clip,c)}}return!0}resolveTrackIndexDelta(e,t,i){const r=this.getTrackIdsByType(i),n=r.indexOf(e),s=r.indexOf(t);return n===-1||s===-1?null:s-n}resolveMultiDragTargetTrackId(e,t,i){const r=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return e.trackId;const n=this.calculateTrackY(r)+1,s=this.resolveCrossTrackMoveDestination(i,n,e.trackId);return s.status==="blocked"?r:s.targetTrackId}resolveMultiDragPreviewTargetTrackId(e,t,i){const r=this.findTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return null;const n=this.calculateTrackY(r)+1,s=this.resolveCrossTrackPreviewDestination(i,n,e.trackId);return s.status==="existing_track"?s.targetTrackId:null}buildMovedClipSnapshot(e,t,i=!1){let r=e.startTime+t;if(i){const n=this.getDurationState();r=Math.max(0,Math.min(r,n-e.duration))}else r=Math.max(0,r);return{...e,startTime:r,endTime:r+e.duration}}appendPreviewClip(e,t,i){const r=e.get(t);if(r){r.push(i);return}e.set(t,[i])}resolveCrossTrackMoveDestination(e,t,i){if(!this.trackManager||!this.getTimelineCommands)return{status:"blocked"};const r=this.trackManager.getTracks(),n=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);if(n.status==="missing_target_track_by_position")return M.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return M.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return M.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:e.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};M.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const s=this.createTrack(n.trackType,void 0,n.insertionPlacement,n.referenceTrackId);return s?{status:"move_to_track",targetTrackId:s}:{status:"blocked"}}resolveCrossTrackPreviewDestination(e,t,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const r=this.trackManager.getTracks();if(!Array.isArray(r)||r.length===0)return{status:"clear"};const n=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),r,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(e,t,i){let r=this.getTrackIdsByType(t);const n=r.indexOf(e);if(n===-1)return null;let s=n+i;for(;s<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;r=this.getTrackIdsByType(t),s+=1}for(;s>=r.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;r=this.getTrackIdsByType(t)}return r[s]??null}findTrackIdByRelativeIndex(e,t,i){const r=this.getTrackIdsByType(t),n=r.indexOf(e);if(n===-1)return null;const s=n+i;return s<0||s>=r.length?null:r[s]??null}getTrackIdsByType(e){if(!this.trackManager)return[];const t=this.trackManager.getTracks();return t?t.filter(i=>i.type===e).map(i=>i.id):[]}updateClipPositionWithHistory(e,t,i){var n;const r=this.getTrackCollection().findById(e);(n=r==null?void 0:r.updateClipPosition)==null||n.call(r,t,i,!0)}updateClipPositionSilently(e,t,i){const r=this.getTrackCollection().findById(e);if(!(r!=null&&r.updateClipPosition))return;const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{r.updateClipPosition(t,i,!0)}finally{this.isExecutingHistoryAction=n}}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new q.Rect({fill:zr.fill,stroke:zr.stroke,strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(t=this.selectionBoxLayer)==null||t.add(e),this.selectionBoxRect=e,e}showSelectionBoxRect(e,t,i,r){var s;const n=this.ensureSelectionBoxRect();n.x(e),n.y(t),n.width(Math.max(i,1)),n.height(Math.max(r,1)),n.visible(!0),(s=this.selectionBoxLayer)==null||s.batchDraw()}hideSelectionBoxRect(){var e;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(e=this.selectionBoxLayer)==null||e.batchDraw())}handleStageMouseDown(e){if(e.button!==0)return;const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=e.clientY-r.top;if(this.isPointOnClip(n,s))return;this.isBoxSelecting=!1,this.boxSelectStartX=n,this.boxSelectStartY=s;const l=c=>{this.handleBoxSelectMove(c)},h=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",h)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",h)}handleBoxSelectMove(e){const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=e.clientY-r.top,o=Math.abs(n-this.boxSelectStartX),l=Math.abs(s-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,s),d=Math.abs(n-this.boxSelectStartX),u=Math.abs(s-this.boxSelectStartY);this.showSelectionBoxRect(h,c,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const e=this.selectionBoxRect;if(e){const t={x:e.x(),y:e.y(),width:e.width(),height:e.height()},i=this.getClipsIntersectingBox(t);this.setSelection(i,{preferredPrimaryClipId:this.selectedClipId})}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(e,t){for(const i of this.tracks){const r=i.getTrackGroup(),n=r.y(),s=r.height()||64;if(!(t<n||t>n+s))for(const o of i.getClips()){const l=me(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=F.timeToPixels(o.duration,this.getZoomState());if(e>=l&&e<=l+h&&t>=n+2&&t<=n+s-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const r=i.getTrackGroup(),n=r.y(),s=r.height()||64;for(const o of i.getClips()){const l=me(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=F.timeToPixels(o.duration,this.getZoomState()),c=n+2,d=s-4,u=l+h,g=c+d,f=e.x+e.width,y=e.y+e.height;l<f&&u>e.x&&c<y&&g>e.y&&t.push(o.id)}}return t}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Ge({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(r=>r.id===e);return t?{...t,clips:t.clips.map(r=>({...r}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const r=this.resolveTrackInsertionFromRestoreAnchor(t);if(r){const u=this.createTrack(e.type,e.name,r.insertionPlacement,r.referenceTrackId);return this.muteTrack(u,e.isMuted??!1),u}const n=[...this.getTracks()].sort((u,g)=>u.order-g.order),s=n.find(u=>u.order>=e.order),o=s?n[n.findIndex(u=>u.id===s.id)-1]??null:n[n.length-1]??null;let l,h;s?(l="before_track",h=s.id):o&&(l="after_track",h=o.id);const c=this.createTrack(e.type,e.name,l,h);return this.muteTrack(c,e.isMuted??!1),c}getTrackRestoreAnchor(e){var r,n,s;if(!((r=this.trackManager)!=null&&r.getTracks))return null;const t=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=t.findIndex(o=>o.id===e);return i===-1?null:{previousTrackId:((n=t[i-1])==null?void 0:n.id)??null,nextTrackId:((s=t[i+1])==null?void 0:s.id)??null}}resolveTrackInsertionFromRestoreAnchor(e){return e?e.previousTrackId&&this.getTrackCollection().findById(e.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:e.previousTrackId}:e.nextTrackId&&this.getTrackCollection().findById(e.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:e.nextTrackId}:null:null}resolveTrackIdByClipId(e){var t;return((t=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:t.trackId)??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var s;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=_r(e),n=qn(e);if(r!==t){this.lastTrackDuration=r;const o=jn(r);this.setDurationState(o),(s=this.timeline)==null||s.setDuration(o),this.updateViewportLayout()}n!==i&&(this.lastReportedTrackDuration=n,this.emitEvent("track_duration_change",{duration:n})),!(r===t&&n===i)&&M.debugLazy("TimelineManager",()=>`Track duration changed: total=${n}ms, extent=${r}ms, timeline=${jn(r)}ms`)}resolveSelectedClipSnapshot(){return ha({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}}})}resolveSelectionChangeData(){return ud({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}},getSelectedClipIds:()=>{try{return this.getSelectedClipIds()}catch{return[]}},canSplitSelectedClip:()=>{try{return this.canSplitSelectedClip()}catch{return!1}},getSelectedClipAudioAction:()=>{try{return this.getSelectedClipAudioAction()}catch{return null}}})}commitPreviewVisualTransform(e,t){const i=this.getClips().find(s=>s.id===e);if(!i||i.type!=="video"&&i.type!=="text")return;const r=ke(i.visualTransform),n=ke(t);Nr(r,n)||this.updateClip(e,{visualTransform:n})}clearAllTracksAndClips(){var t,i,r,n;const e=this.getTracks();for(const s of e){const o=this.getTrackCollection().findById(s.id);if(o){const l=[...o.getClips()];for(const h of l)(t=o.removeClip)==null||t.call(o,h.id)}}for(const s of e){const o=s.id,l=this.getTrackCollection().findById(o);(r=(i=l==null?void 0:l.getTrackGroup)==null?void 0:i.call(l))==null||r.destroy(),this.getTrackCollection().removeById(o)}this.trackManager.clearAllTracks(),this.updateAllTrackPositions(),(n=this.stage)==null||n.batchDraw()}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=Ir;exports.CLIP_LAYER=Sa;exports.Clip=Pi;exports.ClipConfigPanel=sa;exports.DEFAULT_CLIP_VIEW_STATE=os;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Ee;exports.DEFAULT_TEXT_CLIP_STYLE=as;exports.HistoryManager=Pr;exports.MIN_CLIP_LINE_WIDTH=Kt;exports.PREVIEW_ASPECT_RATIO_PRESETS=ya;exports.Playhead=Nh;exports.TIMELINE_LEFT_PADDING=ue;exports.TIME_SCALE=Ca;exports.TRACK_HEIGHT=Le;exports.TimeUtils=F;exports.Timeline=Dh;exports.TimelineManager=Bd;exports.Track=Bi;exports.TrackInfoPanel=na;exports.TrackManager=da;exports.ZOOM_ANIMATION=ls;exports.ZOOM_PRESETS=ye;exports.createClipViewState=hs;exports.createClipWithViewState=Rr;exports.defaultDarkTheme=Li;exports.isAutoPreviewAspectRatioMode=Ct;exports.normalizePreviewAspectRatio=$e;exports.normalizePreviewAspectRatioMode=Er;exports.resolveAspectRatioBaselineDimensions=Lr;exports.resolveTextClipStyle=vt;exports.resolveTheme=jt;
|
|
567
|
+
`,document.head.appendChild(a)}function Jd(a,e){Zd();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??Ra,scrollbarSize:e.scrollbarSize??Da};return new Kd().mount(a,t)}class Qd{constructor(e){p(this,"currentTime");p(this,"playState");p(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class Ma{constructor(){p(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class eu{constructor(e){p(this,"zoom");p(this,"duration");p(this,"scrollLeft");p(this,"scrollTop");p(this,"viewportWidth");p(this,"viewportHeight");p(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class us{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new Ma,this.playbackStore=new Qd({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new eu({zoom:e.zoom,duration:e.duration,scrollLeft:e.scrollLeft,scrollTop:e.scrollTop,viewportWidth:e.viewportWidth,viewportHeight:e.viewportHeight,contentHeight:e.contentHeight}),e.selectedClipIds!==void 0?this.selectionStore.setSelection(e.selectedClipIds):e.selectedClipId!==void 0&&this.selectionStore.setPrimarySelection(e.selectedClipId)}getPrimarySelectedClipId(){return this.selectionStore.getPrimarySelectedClipId()}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return this.selectionStore.getSelectedClipIds()}setSelectedClipIds(e){this.selectionStore.setSelection(e)}setPrimarySelectedClipId(e){this.selectionStore.setPrimarySelection(e)}setSelectedClipId(e){this.setPrimarySelectedClipId(e)}clearSelection(){this.selectionStore.clear()}hasSelection(){return this.selectionStore.hasSelection()}getCurrentTime(){return this.playbackStore.getCurrentTime()}setCurrentTime(e){this.playbackStore.setCurrentTime(e)}getPlayState(){return this.playbackStore.getPlayState()}setPlayState(e){this.playbackStore.setPlayState(e)}getSpeed(){return this.playbackStore.getSpeed()}setSpeed(e){this.playbackStore.setSpeed(e)}getZoom(){return this.viewportStore.getZoom()}setZoom(e){this.viewportStore.setZoom(e)}getDuration(){return this.viewportStore.getDuration()}setDuration(e){this.viewportStore.setDuration(e)}getScrollLeft(){return this.viewportStore.getScrollLeft()}setScrollLeft(e){this.viewportStore.setScrollLeft(e)}getScrollTop(){return this.viewportStore.getScrollTop()}setScrollTop(e){this.viewportStore.setScrollTop(e)}getViewportWidth(){return this.viewportStore.getViewportWidth()}setViewportWidth(e){this.viewportStore.setViewportWidth(e)}getViewportHeight(){return this.viewportStore.getViewportHeight()}setViewportHeight(e){this.viewportStore.setViewportHeight(e)}getContentHeight(){return this.viewportStore.getContentHeight()}setContentHeight(e){this.viewportStore.setContentHeight(e)}}class tu{constructor(e,t,i,r,n){p(this,"stage");p(this,"layer");p(this,"onTimeChange");p(this,"onScrollChange");p(this,"config");p(this,"theme");p(this,"scrollLeft",0);p(this,"timeScaleHeight",40);p(this,"isDragging",!1);p(this,"dragStartX",0);p(this,"isPointerInsideTimeline",!1);p(this,"lastPointerXInTimeline",null);p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=r,this.onScrollChange=n,this.config={duration:i.duration||36e5,zoom:i.zoom||ye.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Qt(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(e){}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setScrollLeft(e){this.scrollLeft=this.clampScrollLeft(e),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(e){const t=H.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=H.timeToPixels(e.startTime,this.config.zoom),r=H.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,n=this.stage.width(),s=r<=n?Math.max(0,t-(n-r)/2):Math.max(0,t);this.setScrollLeft(s)}resize(e){this.stage.width(e),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",e=>{e.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(e.evt.offsetX),"seek")}),this.stage.on("mousedown",e=>{e.target.getLayer()===this.layer&&(this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=ci({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(hi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(e){const t=e.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-t),r=this.scrollLeft;this.dragStartX=e.clientX,this.scrollLeft=i,this.render(),r!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(e){return H.pixelsToTime(e-ue+this.scrollLeft,this.config.zoom)}timeToPixel(e){return H.timeToPixels(e,this.config.zoom)-this.scrollLeft+ue}render(){const e=this.stage.width(),t=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const r=se.createRect(0,0,e,t,this.theme.background,this.theme.border,1);r.name("timeline-header-background"),this.layer.add(r)}this.layer.find(".time-tick-line").forEach(r=>r.remove()),this.layer.find(".time-tick-text").forEach(r=>r.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,r=H.pixelsToTime(t,this.config.zoom),n=H.pixelsToTime(i,this.config.zoom),s=H.msToSeconds(r),o=H.msToSeconds(n),{majorStep:l,minorStep:c}=H.getTickConfig(this.config.zoom),h=H.generateVisibleTicks(s-10,o+10,l,c);for(const d of h){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&se.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,H.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const U=class U{constructor(e,t,i,r,n,s,o){p(this,"container");p(this,"visualElement");p(this,"lineHitAreaElement");p(this,"theme");p(this,"onTimeChange");p(this,"onHorizontalAutoScroll");p(this,"currentTime");p(this,"zoom");p(this,"scrollLeft",0);p(this,"height");p(this,"isDragging",!1);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"lastPointerClientX",null);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});p(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});p(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const r=this.scrollLeft,n=this.onHorizontalAutoScroll(this.scrollLeft+i),s=typeof n=="number"?n:this.scrollLeft;if(this.scrollLeft=Math.max(0,s),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-r)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=e,this.currentTime=t,this.zoom=i,this.height=r,this.theme=n,this.onTimeChange=s,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(U.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${U.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=`${U.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=ci({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(hi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,r=H.pixelsToTime(i-ue+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,r),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(U.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=U.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const n=(i-e)/i;return-Math.max(1,Math.round(n*r))}if(e>t-i){const n=(e-(t-i))/i;return Math.max(1,Math.round(n*r))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const e=H.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+ue,t=e>=0&&e<=this.container.clientWidth,i=Math.max(U.HANDLE_HEIGHT+U.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${U.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=Oi.grip,i=Math.max(U.HANDLE_HEIGHT,e-U.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i,this.theme.playhead))}createHandleShadowPath(){const e=document.createElementNS(U.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill",Oi.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(U.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(U.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(U.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(U.VISUAL_WIDTH-U.LINE_WIDTH)/2}`),t.setAttribute("y",`${U.HANDLE_LINE_START}`),t.setAttribute("width",`${U.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-U.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e,t){const i=document.createElementNS(U.SVG_NS,"g");i.setAttribute("class","timeline-manager-playhead-end-cap"),i.setAttribute("transform",`translate(0 ${e})`);const r=document.createElementNS(U.SVG_NS,"rect");r.setAttribute("x",`${(U.VISUAL_WIDTH-U.LINE_WIDTH)/2}`),r.setAttribute("y","0"),r.setAttribute("width",`${U.LINE_WIDTH}`),r.setAttribute("height","7"),r.setAttribute("rx","1"),r.setAttribute("fill",t);const n=document.createElementNS(U.SVG_NS,"rect");return n.setAttribute("x",`${(U.VISUAL_WIDTH-U.END_CAP_WIDTH)/2}`),n.setAttribute("y","7"),n.setAttribute("width",`${U.END_CAP_WIDTH}`),n.setAttribute("height","3"),n.setAttribute("rx","1.5"),n.setAttribute("fill",t),i.appendChild(r),i.appendChild(n),i}};p(U,"SVG_NS","http://www.w3.org/2000/svg"),p(U,"VISUAL_WIDTH",14),p(U,"HANDLE_HEIGHT",16),p(U,"HANDLE_LINE_START",13),p(U,"LINE_WIDTH",2),p(U,"LINE_HIT_WIDTH",12),p(U,"END_CAP_WIDTH",14),p(U,"END_CAP_HEIGHT",10),p(U,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(U,"AUTO_SCROLL_MAX_SPEED",18);let Or=U;class ps{constructor(e){p(this,"container");p(this,"orientation");p(this,"theme");p(this,"onScrollChange");p(this,"leadingInset");p(this,"trailingInset");p(this,"stage");p(this,"layer");p(this,"hitAreaRect");p(this,"thumbRect");p(this,"viewportSize",0);p(this,"contentSize",0);p(this,"scrollOffset",0);p(this,"isDragging",!1);p(this,"dragStartClient",0);p(this,"dragStartOffset",0);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleStageMouseDown",e=>{var r;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((r=e.target)==null?void 0:r.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});p(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});p(this,"handleStageMouseEnter",()=>{this.updateCursor()});p(this,"handleStageMouseMove",()=>{this.updateCursor()});p(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new q.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new q.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=se.createRect(0,0,0,0,fe.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=se.createRect(0,0,0,0,this.theme.scrollbarThumb||fe.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border,1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=ci({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(hi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(e){const i=(this.orientation==="horizontal"?e.clientX:e.clientY)-this.dragStartClient,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),s=Math.max(1,r-n),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/s*o;this.emitScrollChange(l)}jumpToPointer(e){const t=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?e-t.left:e-t.top,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),s=Math.max(1,r-n),o=Math.max(0,Math.min(r,i-this.leadingInset)),l=Math.max(0,Math.min(s,o-n/2)),c=this.getMaxScrollOffset(),h=s<=0?0:l/s*c;this.emitScrollChange(h)}emitScrollChange(e){const t=this.clampScrollOffset(e);this.scrollOffset=t,this.render(),this.onScrollChange(t)}render(){const e=Math.max(0,this.container.clientWidth),t=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(e),this.stage.height(t),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(e),this.hitAreaRect.height(t),this.thumbRect.fill(this.theme.scrollbarThumb||fe.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||fe.border);const r=this.getAvailableTrackSize();if(r<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const n=this.getThumbSize(r),s=this.leadingInset+this.getThumbPosition(r,n);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(s),this.thumbRect.y(0),this.thumbRect.width(n),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(s),this.thumbRect.width(e),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(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const r=Math.max(1,e-t);return this.scrollOffset/i*r}}class gs{constructor(){p(this,"entries",new Map)}register(e,t){this.entries.set(e,{id:e,destroy:t})}unregister(e){this.entries.delete(e)}destroyAll(){for(const e of this.entries.values())e.destroy();this.entries.clear()}}class iu{constructor(){p(this,"panel",null);p(this,"config",null);p(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new xa({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,e.updateClip(i,r),setTimeout(()=>{this.isInternalUpdate=!1},0)},onGenerateVoice:e.onGenerateVoice})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip();this.panel.setClip(e)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}setPreferredTab(e){var t;(t=this.panel)==null||t.setPreferredTab(e)}setVoiceGenerationBusy(e){var t;(t=this.panel)==null||t.setVoiceGenerationBusy(e)}convertTheme(e){return{backgroundColor:ge.backgroundColor,borderColor:e.border||ge.borderColor,textColor:e.clipName||ge.textColor,labelColor:e.timeText||ge.labelColor,inputBackground:e.trackBackground||ge.inputBackground,inputBorder:e.trackBorder||ge.inputBorder,inputFocusBorder:ge.inputFocusBorder,buttonBackground:e.clipBackground||ge.buttonBackground,buttonBorder:e.clipBorder||ge.buttonBorder,buttonActiveBackground:ge.buttonActiveBackground,buttonActiveBorder:e.clipSelectedBorder||ge.buttonActiveBorder,buttonActiveText:ge.buttonActiveText}}}const ru="@linker-design-plus/timeline-track",nu="2.0.13",Bt={name:ru,version:nu},su=1,au=2,ou=120;function fs(a){return a==null?a:JSON.parse(JSON.stringify(a))}function lu(a){return a==="text"?"文本":a==="video"?"视频":"音频"}class cu{constructor(e={}){p(this,"timeline",null);p(this,"tracks",[]);p(this,"trackManager");p(this,"trackInfoPanelController");p(this,"playhead",null);p(this,"history");p(this,"config");p(this,"eventDispatcher");p(this,"animationFrameId",null);p(this,"lastUpdateTime",0);p(this,"isInitialized",!1);p(this,"stage",null);p(this,"headerStage",null);p(this,"headerLayer",null);p(this,"backgroundLayer",null);p(this,"trackLayer",null);p(this,"dragOverlayLayer",null);p(this,"snapGuideLayer",null);p(this,"selectionBoxLayer",null);p(this,"selectionBoxRect",null);p(this,"isBoxSelecting",!1);p(this,"boxSelectStartX",0);p(this,"boxSelectStartY",0);p(this,"resizeObserver",null);p(this,"rootContainer",null);p(this,"layout",null);p(this,"bodyBackgroundRect",null);p(this,"snapGuideLine",null);p(this,"trackInsertionPreviewLine",null);p(this,"trackInsertionPreviewY",null);p(this,"snapGuideTime",null);p(this,"horizontalScrollbar",null);p(this,"verticalScrollbar",null);p(this,"isExecutingHistoryAction",!1);p(this,"lastTrackDuration",0);p(this,"lastReportedTrackDuration",0);p(this,"thumbnailProvider",null);p(this,"thumbnailProviderVersion",0);p(this,"clipThumbnailLoadStates",new Map);p(this,"sourceMediaRegistry",new gr);p(this,"canPlay",!1);p(this,"sourceLoadingCount",0);p(this,"timelineStore");p(this,"timelineCommands");p(this,"timelineHistoryExecutor");p(this,"timelineHistoryRecorder");p(this,"timelinePresentationAdapter");p(this,"timelineTrackBridge");p(this,"timelinePlaybackResolver");p(this,"previewRuntimeController");p(this,"previewStateController");p(this,"previewPlaybackSuspendedByBuffering",!1);p(this,"previewPlaybackAutoResume",!1);p(this,"previewBufferingSuspendTimeoutId",null);p(this,"lastSelectedClipId",null);p(this,"previewAspectRatio",{...Ee});p(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});p(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});p(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});p(this,"keyboardShortcutsController",null);p(this,"clipClipboard",null);p(this,"mountManager",new gs);p(this,"pendingDraftData",null);p(this,"selectionStore",new Ma);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);p(this,"splitOperationDepth",0);p(this,"diagnostics");p(this,"diagnosticsPanel",null);p(this,"previewRuntimeState",{phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]});p(this,"previewActiveClipIds",[]);p(this,"playbackAttemptId",this.createPlaybackAttemptId("initial"));p(this,"lastPreviewSyncedPlayState",null);p(this,"previewSyncInteractionMode",null);this.config={duration:e.duration||36e5,zoom:e.zoom||ye.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:Qt(e.theme),timeScaleHeight:e.timeScaleHeight,diagnostics:e.diagnostics,speed:e.speed||1,dragActivationThreshold:e.dragActivationThreshold??4,enableClipSnap:e.enableClipSnap??!1,clipSnapThreshold:e.clipSnapThreshold??8,thumbnailProvider:e.thumbnailProvider,previewBackend:e.previewBackend??"dom",previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont??null,keyboardShortcuts:e.keyboardShortcuts},this.diagnostics=new la(this.config.diagnostics),this.diagnostics.startSession({packageName:Bt.name,packageVersion:Bt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.config.previewBackend}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new Wd,this.eventDispatcher=new as({can_play_change:()=>({canPlay:this.canPlay}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new Dr(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Jn(this.history),this.timelineHistoryExecutor=new Zn({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 La,this.timelineStore=new us({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new Kn(this.timelineStore),this.timelinePresentationAdapter=new ls,this.timelineTrackBridge=new cs({onClipUpdate:(t,i,r)=>this.handleClipUpdate(t,i,r),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),e.draftData&&(this.pendingDraftData=e.draftData),this.config.container&&this.init(this.config.container)}createPlaybackAttemptId(e){return`playback-${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}refreshPlaybackAttempt(e){this.playbackAttemptId=this.createPlaybackAttemptId(e)}emitDiagnostic(e){var t;(t=this.diagnostics)==null||t.emit(e)}buildDiagnosticsRuntimeState(){var e,t;return{currentTimeMs:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),pendingMode:((e=this.pendingPreviewState)==null?void 0:e.mode)??null,loadingCount:this.getSourceLoadingState().pending,isBuffering:this.previewBuffering,runtimePhase:((t=this.previewRuntimeState)==null?void 0:t.phase)??"idle",selectedClipId:this.getPrimarySelectedClipId(),activeClipIds:Array.isArray(this.previewActiveClipIds)?[...this.previewActiveClipIds]:[],previewAspectRatio:this.getPreviewAspectRatio()}}buildPreviewDiagnosticsContext(){return{playbackAttemptId:this.playbackAttemptId,previewBackend:this.getPreviewBackendType(),runtimeState:this.buildDiagnosticsRuntimeState()}}mountDiagnosticsPanel(){var e;!this.rootContainer||!((e=this.config.diagnostics)!=null&&e.enablePanel)||this.diagnosticsPanel||(this.rootContainer.style.position=this.rootContainer.style.position||"relative",this.diagnosticsPanel=new ha(this.diagnostics),this.diagnosticsPanel.mount(this.rootContainer))}getTimelineStore(){var e,t,i,r,n;if(!this.timelineStore){const s=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,c=((r=this.config)==null?void 0:r.zoom)||ye.MEDIUM,h=((n=this.config)==null?void 0:n.duration)||36e5;this.timelineStore=new us({currentTime:s,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new Kn(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Xd(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new ls),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new cs({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this)})),this.timelineTrackBridge}getTimelinePlaybackResolver(){return this.timelinePlaybackResolver||(this.timelinePlaybackResolver=new xd),this.timelinePlaybackResolver}get previewSession(){return this.getPreviewRuntimeController().previewSession}set previewSession(e){this.getPreviewRuntimeController().previewSession=e}get previewMountContainer(){return this.getPreviewRuntimeController().previewMountContainer}set previewMountContainer(e){this.getPreviewRuntimeController().previewMountContainer=e}get resolvedPreviewBackend(){return this.getPreviewRuntimeController().resolvedPreviewBackend}set resolvedPreviewBackend(e){this.getPreviewRuntimeController().resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this.getPreviewRuntimeController().runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this.getPreviewRuntimeController().runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this.getPreviewRuntimeController().activePreviewCallbackToken}set activePreviewCallbackToken(e){this.getPreviewRuntimeController().activePreviewCallbackToken=e}get previewSourceLoadingCount(){return this.getPreviewStateController().previewSourceLoadingCount}set previewSourceLoadingCount(e){this.getPreviewStateController().previewSourceLoadingCount=e}get previewBuffering(){return this.getPreviewStateController().previewBuffering}set previewBuffering(e){this.getPreviewStateController().previewBuffering=e}get pendingPreviewState(){return this.getPreviewStateController().pendingPreviewState}set pendingPreviewState(e){this.getPreviewStateController().pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this.getPreviewStateController().nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this.getPreviewStateController().nextPendingPreviewSyncRequestId=e}getPreviewStateController(){return this.previewStateController||(this.previewStateController=new Ad({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitBufferingStateChange:e=>{this.syncPlaybackClockToPreviewBuffering(e),this.emitEvent("buffering_state_change",{isBuffering:e})},emitSourceLoadingStateChange:()=>{this.emitEvent("source_loading_change",this.getSourceLoadingState())},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new Pd({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Cd({callbacks:t,diagnostics:this.diagnostics,getDiagnosticsContext:()=>this.buildPreviewDiagnosticsContext(),previewSourceResolver:this.config.previewSourceResolver,textPreviewFont:this.config.textPreviewFont,sourceMediaRegistry:this.sourceMediaRegistry}),resolveConfiguredBackend:e=>e||vd(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onBufferingStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleBufferingStateChange(t)},onSourceLoadingChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleSourceLoadingChange(t)},onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewRuntimeState=t,this.getPreviewStateController().handleRuntimeStateChange(t))},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=Ve(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(e)&&this.retryPendingPreview()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new as({can_play_change:()=>({canPlay:this.canPlay??!1}),selection_change:()=>this.resolveSelectionChangeData(),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 Dr(()=>{},()=>{})),this.timelineHistoryRecorder=new Jn(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new Zn({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)})),this.timelineHistoryExecutor}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:36e5,zoom:ye.MEDIUM,currentTime:0,playState:"paused",theme:Qt(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,clipSnapThreshold:8,previewBackend:"dom",textPreviewFont:null}),this.config}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(e){this.getTimelineStore().setPlayState(e),this.ensureConfigState().playState=e}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(e){this.getTimelineStore().setDuration(e),this.ensureConfigState().duration=e}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(e){this.getTimelineStore().setScrollLeft(e)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(e){this.getTimelineStore().setScrollTop(e)}setViewportMetrics(e,t,i){const r=this.getTimelineStore();r.setViewportWidth(e),r.setViewportHeight(t),r.setContentHeight(i)}syncCurrentTimeToScene(e){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncZoomToScene(e){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncScrollTopPresentation(e){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,e)}refreshScrollbarMetrics(){var i,r,n,s;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(r=this.verticalScrollbar)==null||r.resize(),(n=this.horizontalScrollbar)==null||n.setViewportMetrics(e,this.getHorizontalContentWidth()),(s=this.verticalScrollbar)==null||s.setViewportMetrics(t,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientWidth)||0}getViewportHeight(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return H.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(e){const t=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(t,e))}clampScrollTop(e){const t=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(t,e))}syncScrollLeft(e){var i,r;const t=this.clampScrollLeft(e);this.setScrollLeftState(t),(i=this.timeline)==null||i.setScrollLeft(t),(r=this.horizontalScrollbar)==null||r.setScrollLeft(t),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),t),this.refreshSnapGuideLine()}syncScrollTop(e){var i;const t=this.clampScrollTop(e);this.setScrollTopState(t),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-t)>.5&&(this.layout.bodyViewport.scrollTop=t),this.syncScrollTopPresentation(t)}getResolvedTracksSnapshot(){const e=this.getTrackCollection();return this.trackManager.getTracks().map(t=>{const i=e.findById(t.id);return{...t,clips:i?i.getClips():[...t.clips]}})}getTracksSortedByOrder(){const e=this.getTrackCollection();return this.trackManager.getTracks().slice().sort((t,i)=>t.order-i.order).map(t=>e.findById(t.id)).filter(t=>t!==null)}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(e=>({id:e.id,type:e.type,order:e.order,isMuted:e.isMuted??!1,clips:e.clips}))}buildPlaybackPlan(e=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),e)}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((s,o)=>s.order-o.order);let i=null,r=null,n=Number.POSITIVE_INFINITY;for(const s of t){if(s.type!=="video")continue;const o=[...s.clips].sort((l,c)=>l.startTime-c.startTime);for(const l of o){const c={trackId:s.id,trackType:s.type,trackOrder:s.order,clip:l,mediaTime:l.startTimeAtSource,muted:(s.isMuted??!1)||(l.isMuted??!1),kind:s.type,hasVisual:!0,hasAudio:!0};i||(i=c);const h=e.get(l.id);h===void 0||h>=n||(r=c,n=h)}}return r||i}registerPreviewAutoAspectRatioClip(e){const t=this,i=this.getPreviewAutoAspectRatioClipOrderMap();e.type!=="video"||i.has(e.id)||(i.set(e.id,this.getNextPreviewAutoAspectRatioOrder()),t.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}syncPreviewSession(e){var o,l,c,h;if(!((o=this.previewSession)!=null&&o.hasPreview())){this.previewSyncInteractionMode=null;return}const t=this.buildPlaybackPlan();this.previewActiveClipIds=t.activeClips.map(d=>d.clip.id);const i=this.getAutoAspectRatioClip(),r=Ve(this.previewAspectRatio),n=e??this.getPlayStateState(),s=this.previewSyncInteractionMode??((l=this.pendingPreviewState)==null?void 0:l.mode)??"steady";this.previewAspectRatio=r,this.previewSession.applyAspectRatio(r),this.previewSession.sync({...t,autoAspectRatioClip:i,currentTime:this.getCurrentTimeState(),playState:n,speed:this.getSpeedState(),interactionMode:s,primarySelectedClipId:this.getPrimarySelectedClipId(),...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),this.previewSyncInteractionMode=null,(h=(c=this.previewSession).setPendingState)==null||h.call(c,this.buildPreviewPendingState()),this.lastPreviewSyncedPlayState=n}syncPreviewPlaybackStateIfNeeded(e){this.lastPreviewSyncedPlayState!==e&&this.syncPreviewSession(e)}beginPendingPreview(e,t="seek"){var r,n,s,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;(t!=="scrub"||((n=this.pendingPreviewState)==null?void 0:n.mode)!=="scrub")&&this.refreshPlaybackAttempt(t);const i=((s=this.pendingPreviewState)==null?void 0:s.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPlayStateState()==="playing"&&this.pause(),this.getPreviewStateController().beginPendingPreview(e,t,i),t!=="scrub"&&this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"pending-preview.begin",message:"Pending preview started",playbackAttemptId:this.playbackAttemptId,syncRequestId:((o=this.pendingPreviewState)==null?void 0:o.syncRequestId)??null,runtimeState:{...this.buildDiagnosticsRuntimeState(),pendingMode:t},extra:{targetTime:e,resumePlayOnReady:i}})}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState(),this.previewActiveClipIds=[],this.lastPreviewSyncedPlayState=null,this.previewSyncInteractionMode=null,this.previewRuntimeState={phase:"idle",loadingCount:0,isBuffering:!1,errorMessage:null,slots:[]}}destroyPreviewSession(e=!1){this.getPreviewRuntimeController().destroyPreviewSession(e),this.lastPreviewSyncedPlayState=null,this.resetPreviewRuntimeState()}retryPendingPreview(){var e;this.refreshPlaybackAttempt("retry"),this.getPreviewStateController().retryPendingPreview(),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"pending-preview.retry",message:"Pending preview retried",playbackAttemptId:this.playbackAttemptId,syncRequestId:((e=this.pendingPreviewState)==null?void 0:e.syncRequestId)??null,runtimeState:this.buildDiagnosticsRuntimeState()})}handlePreviewBackendRuntimeError(){this.emitDiagnostic({severity:"error",category:"runtime",eventName:"preview.runtime.error",message:"Preview backend runtime error",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState(),extra:{resolvedBackend:this.getPreviewBackendType()}}),this.clearPendingPreviewState(),this.resetPreviewRuntimeState();const e=this.getPreviewRuntimeController().fallbackToDom(Ve(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,r,n,s,o,l,c;if(this.isInitialized){G.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=Jd(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Ra,scrollbarSize:Da}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(r=(i=this.layout.bodyCanvasHost).addEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(s=(n=this.rootContainer)==null?void 0:n.addEventListener)==null||s.call(n,"wheel",this.rootWheelListener,{passive:!1}),this.initKeyboardShortcuts(),this.headerStage=new q.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new q.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new q.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new q.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new q.Layer({name:"trackLayer"}),this.dragOverlayLayer=new q.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new q.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new q.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const t=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(t&&t.addEventListener("mousedown",this.handleStageMouseDown.bind(this)),this.timeline=new tu(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new Or(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 ps({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:ue,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new ps({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:h=>{this.syncScrollTop(h)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(e),this.mountDiagnosticsPanel(),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(c=this.stage)==null||c.batchDraw(),this.pendingDraftData){const h=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(h).catch(d=>{G.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,n){var d,u,g;if(!this.trackLayer)return G.error("TimelineManager","Track layer not initialized"),"";const s=this.trackManager.createTrack(e,t,i,r,n),o=s.id,l=st(e),c=this.calculateTrackY(o),h=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:o,clips:[],role:s.role},trackType:e,zoom:this.getZoomState(),trackY:c,trackHeight:l,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(d=h.setSnapTargetResolver)==null||d.call(h,()=>this.getClips()),(u=h.setDragOverlayLayer)==null||u.call(h,this.dragOverlayLayer),this.getTrackCollection().add(h),this.updateAllTrackPositions(),(g=this.stage)==null||g.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),o}removeTrack(e){var r,n,s,o;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return G.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return G.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((s=(n=t.getTrackGroup)==null?void 0:n.call(t))==null||s.destroy(),this.getTrackCollection().removeById(e),this.updateAllTrackPositions(),(o=this.stage)==null||o.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),i}renameTrack(e,t){const i=this.trackManager.renameTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}getTracks(){return this.getResolvedTracksSnapshot()}initTrackInfoPanel(e){G.warn("TimelineManager","initTrackInfoPanel() is deprecated. TimelineManager now manages the frozen track-info panel inside the root container.")}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){const i=this.trackManager.muteTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return Ot(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return hs(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=jd(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const r of e){const n=this.getTrackCollection().findById(r.trackId);n&&((t=n.setTrackY)==null||t.call(n,r.y),(i=n.setTrackHeight)==null||i.call(n,r.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}cleanupEmptyTracks(){var t,i,r,n;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return;const e=this.getTrackCollection().removeEmptyNonPrimaryTracks();if(e.length!==0){for(const s of e){const o=(t=s.getId)==null?void 0:t.call(s);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(r=(i=s.getTrackGroup)==null?void 0:i.call(s))==null||r.destroy(),this.getTrackCollection().removeById(o))}this.updateAllTrackPositions(),(n=this.stage)==null||n.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()}}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDropPreview)==null?void 0:t.call(e)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(e,t){this.showClipDropPreviews(new Map([[t,[e]]]))}showClipDropPreviews(e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(t=>{var n,s,o,l;const i=(n=t.getId)==null?void 0:n.call(t),r=i?e.get(i)??[]:[];if(r.length>0){r.length===1?(s=t.showClipDropPreview)==null||s.call(t,r[0]):(o=t.showClipDropPreviews)==null||o.call(t,r);return}(l=t.clearClipDropPreview)==null||l.call(t)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const e=se.createLine([0,0,0,0],this.getSnapGuideAccentColor(),2);e.name("timeline-track-insertion-preview-line"),e.dash([8,4]),e.visible(!1),e.listening(!1),this.snapGuideLayer.add(e),this.trackInsertionPreviewLine=e}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(e=!0){var i,r,n;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),e&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const t=((r=this.stage)==null?void 0:r.width())??0;this.trackInsertionPreviewLine.stroke(this.getSnapGuideAccentColor()),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,t,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(t>0),this.trackInsertionPreviewLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(n=>{var s;return(s=n.clearClipDropPreview)==null?void 0:s.call(n)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const r=this.trackManager.getTracks(),n=r.find(c=>c.role==="primary"),s=r.find(c=>c.type===e),o=[...r].reverse().find(c=>c.type===e);if((t==="before_track"||t==="after_track")&&i){const c=r.find(h=>h.id===i);if(c){const h=Ot(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+st(c.type)}}if(t==="top_of_type_region"&&s)return Ot(r,s.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Ot(r,o.id,this.getTrackContentTopOffset())+st(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():hs(r,this.getTrackContentTopOffset());const l=Ot(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+st(n.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),r=Math.max(i,t),n=this.clampScrollLeft(this.getScrollLeftState()),s=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(e,t,r),this.headerStage.width(e),this.timeline.resize(e),this.stage.width(e),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${r}px`,this.renderBodyBackground(e,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+t),this.refreshScrollbarMetrics(),this.syncScrollLeft(n),this.syncScrollTop(s),this.stage.batchDraw()}renderBodyBackground(e,t,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(e),this.bodyBackgroundRect.height(t),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const r=new q.Rect({x:0,y:0,width:e,height:t,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});r.on("click",n=>{this.handleBodyBackgroundClick(n.evt.offsetX)}),this.bodyBackgroundRect=r,this.backgroundLayer.add(r),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(e){const t=H.pixelsToTime(e-ue+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,t))}handleBodyCanvasHostClick(e){if(!this.layout||e.target!==this.layout.bodyCanvasHost)return;const t=this.layout.bodyCanvasHost.getBoundingClientRect(),i=e.clientX-t.left;this.handleBodyBackgroundClick(i)}getSnapGuideAccentColor(){return this.config.theme.snapGuideLineColor||Q.snapGuideLineColor}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=se.createLine([0,0,0,this.calculateTotalHeight()],this.getSnapGuideAccentColor(),e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var r,n;if(!this.snapGuideLine)return;const t=this.config.theme;if(this.snapGuideLine.stroke(this.getSnapGuideAccentColor()),this.snapGuideLine.strokeWidth(t.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),e&&((r=this.snapGuideLayer)==null||r.batchDraw());return}const i=me(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const n=this.getPrimaryWheelDelta(t,i);if(n===0)return;e.preventDefault(),this.handleWheelZoom(n,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const n=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(n===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+n);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===su)return e*16;if(t===au){const r=i==="x"?this.getViewportWidth():this.getViewportHeight();return e*(r||1)}return e}getPrimaryWheelDelta(e,t){return Math.abs(t)>=Math.abs(e)?t:e}isHorizontalWheelGesture(e,t){const i=Math.abs(e);if(i<.5)return!1;const r=Math.abs(t);return r<.5?!0:i>r*1.2}getHorizontalScrollDelta(e,t,i){return i&&Math.abs(t)>=Math.abs(e)?t:e}handleWheelZoom(e,t){const i=this.getZoomState(),r=Math.exp(-e*.002),n=Math.max(ye.MIN,Math.min(ye.MAX,i*r));Math.abs(n-i)<1e-4||this.setZoomCenteredOnTimelinePointer(n,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var n;const t=(n=this.layout)==null?void 0:n.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const r=e-t.left;return Math.max(0,Math.min(i,r))}play(){if(this.getPlayStateState()!=="playing"){if(this.pendingPreviewState){this.emitDiagnostic({severity:"warn",category:"ui-trigger",eventName:"play.blocked.pending-preview",message:"Play blocked by pending preview state",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()});return}if(!this.canPlay){G.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}this.refreshPlaybackAttempt("play"),this.setPlayStateState("playing"),this.lastUpdateTime=Date.now(),this.previewBuffering?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"play.started",message:"Playback started",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}),this.syncPreviewSession()}}pause(){this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession())}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused")return;if(this.previewPlaybackSuspendedByBuffering){this.animationFrameId=null;return}const e=Date.now(),t=e-this.lastUpdateTime;this.lastUpdateTime=e;const i=this.getCurrentTimeState()+t*this.getSpeedState();this.setCurrentTime(i),this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}syncPlaybackClockToPreviewBuffering(e){if(e){if(this.getPlayStateState()!=="playing"||(this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering||this.previewBufferingSuspendTimeoutId))return;this.previewBufferingSuspendTimeoutId=setTimeout(()=>{this.previewBufferingSuspendTimeoutId=null,!(this.getPlayStateState()!=="playing"||!this.previewBuffering||this.previewPlaybackSuspendedByBuffering)&&(this.previewPlaybackSuspendedByBuffering=!0,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.previewRuntimeState.loadingCount<=0&&this.syncPreviewPlaybackStateIfNeeded("paused"))},ou);return}if(this.clearPreviewBufferingSuspendTimeout(),!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&this.getPlayStateState()==="playing"&&!this.pendingPreviewState;this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,!(!t||this.animationFrameId)&&(this.syncPreviewPlaybackStateIfNeeded("playing"),this.lastUpdateTime=Date.now(),this.animate())}clearPreviewBufferingSuspendTimeout(){this.previewBufferingSuspendTimeoutId&&(clearTimeout(this.previewBufferingSuspendTimeoutId),this.previewBufferingSuspendTimeoutId=null)}setCurrentTime(e){const t=this.getTimelineCommands().setCurrentTime(e);if(!t.changed){this.pendingPreviewState&&this.pendingPreviewState.targetTime===t.nextValue&&this.syncPreviewSession();return}const i=t.nextValue;this.ensureConfigState().currentTime=i,this.syncCurrentTimeToScene(i),this.emitEvent("time_change",{time:i}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(e){this.ensureConfigState().enableClipSnap=e,e||this.updateSnapGuideLine(null),this.tracks.forEach(t=>{t.setClipSnapEnabled(e)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setZoom(e){const t=this.getTimelineCommands().setZoom(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(e){const t=this.getZoomState(),i=this.getCurrentTimeState(),r=this.getTimelineCommands().setZoom(e);if(!r.changed)return;const n=r.nextValue;if(this.ensureConfigState().zoom=n,this.syncZoomToScene(n),this.refreshScrollbarMetrics(),this.timeline){const s=this.timeline.getScrollLeft(),o=H.timeToPixels(i,t),c=H.timeToPixels(i,n)-o+s;this.timeline.setScrollLeft(c),this.handleScrollChange(this.timeline.getScrollLeft())}this.emitEvent("zoom_change",{zoom:n})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),r=this.timeline.getScrollLeft(),n=H.pixelsToTime(t-ue+r,i),s=this.getTimelineCommands().setZoom(e);if(!s.changed)return;const o=s.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const c=H.timeToPixels(n,o)-(t-ue);this.timeline.setScrollLeft(c),this.handleScrollChange(this.timeline.getScrollLeft()),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(e){const t=this.getTimelineCommands().setSpeed(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount+this.previewSourceLoadingCount>0}getSourceLoadingState(){const e=this.sourceLoadingCount+this.previewSourceLoadingCount;return{isLoading:e>0,pending:e}}setThumbnailProvider(e){this.thumbnailProvider=e,this.thumbnailProviderVersion+=1,this.config.thumbnailProvider=e,this.clipThumbnailLoadStates.clear(),this.sourceMediaRegistry.clearThumbnailCache(),this.getClips().forEach(i=>{this.primeOrLoadClipThumbnails(i,{allowPrimeExisting:!1,force:!0})})}async loadClipThumbnails(e,t={}){if(!this.thumbnailProvider||e.type!=="video")return!1;const i=this.thumbnailProvider,r=this.buildClipThumbnailLoadSignature(e,this.thumbnailProviderVersion),n=this.clipThumbnailLoadStates.get(e.id);if((n==null?void 0:n.signature)===r){if(n.promise)return n.promise;if(n.completed&&!t.force)return!0}let s=!1;const o=this.sourceMediaRegistry.getThumbnails(this.buildClipThumbnailResourceKey(e),async()=>{const l=await Promise.resolve(i.getThumbnails(e));return Array.isArray(l)?l:[]},{force:t.force}).then(l=>{try{if(!Array.isArray(l))return!1;s=!0;const c=this.findClipById(e.id)??e;return this.isClipThumbnailLoadCurrent(e.id,r)?(this.areThumbnailArraysEqual(c.thumbnails,l)||this.updateClip(e.id,{thumbnails:l}),G.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return G.warn("TimelineManager","Error loading clip thumbnails:",{error:c,clipId:e.id}),!1}}).finally(()=>{const l=this.clipThumbnailLoadStates.get(e.id);(l==null?void 0:l.signature)===r&&(l.promise=null,l.completed=s,s||this.clipThumbnailLoadStates.delete(e.id))});this.clipThumbnailLoadStates.set(e.id,{signature:r,promise:o,completed:!1});try{return await o}catch{return!1}}async refreshClipThumbnails(e){const t=this.getClips().find(i=>i.id===e);return t?this.loadClipThumbnails(t,{force:!0}):!1}async refreshAllClipThumbnails(){const e=this.getClips();return await Promise.all(e.map(i=>this.loadClipThumbnails(i,{force:!0})))}async addClip(e){this.beginSourceLoading();try{return await this.addClipInternal(e)}finally{this.endSourceLoading()}}async addClips(e){if(e.length===0)return[];this.beginSourceLoading();try{const t=[],i=new Map,r=new Map,n=!!this.trackManager;for(const s of e){const o=n?this.resolveBatchClipConfig(s,i,r):s,l=await this.addClipInternal(o);if(t.push(l),!n||s.startTime!==void 0||s.trackId)continue;const c=this.getClips().find(d=>d.id===l),h=this.resolveTrackIdByClipId(l);!c||!h||(i.set(c.type,h),r.set(h,c.endTime))}return t}finally{this.endSourceLoading()}}resolveBatchClipConfig(e,t,i){if(e.startTime!==void 0||e.trackId)return e;const r=e.type||"video",n=t.get(r)||this.resolveBatchAppendTrackId(r);if(!n)return e;const s=i.get(n)??this.getTrackTimelineExtentById(n);return{...e,trackId:n,startTime:s}}resolveBatchAppendTrackId(e){const t=this.getTracksSortedByOrder(),i=t.find(s=>{var o,l;return((o=s.getRole)==null?void 0:o.call(s))==="primary"&&((l=s.getTrackType)==null?void 0:l.call(s))===e});if(i)return i.getId();const r=t.find(s=>{var o;return((o=s.getTrackType)==null?void 0:o.call(s))===e});return r?r.getId():this.createTrack(e)||null}getTrackTimelineExtentById(e){const t=this.getTrackCollection().findById(e);return t?Mr(t.getClips()):0}async addClipInternal(e){var C;let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.type||"video",r=i==="text",n=e.src??"",s=e.duration??(r?3e3:0),o=e.name??(r?"文本":`${i}_${Date.now()}`);if(!r&&(!e.name||s<=0))throw new Error(`addClip requires name and duration for ${i} clips`);const l=r?0:e.startTimeAtSource||0,c=r?s:e.endTimeAtSource||l+s;let h=r?s:e.sourceDuration;if(!h)try{h=await H.getVideoDuration(n,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(T){G.error("TimelineManager","Failed to get video duration:",{error:T}),h=c}!r&&h>0&&this.sourceMediaRegistry.primeDuration(this.buildSourceMediaKey(e),h);let d=e.thumbnails;const u=e.id||`clip_${o}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=Hr({id:u,type:i,externalId:e.externalId,src:n,name:o,isMuted:e.isMuted??!1,startTime:t,duration:s,startTimeAtSource:l,endTimeAtSource:c,sourceDuration:h,endTime:t+s,thumbnails:d,style:e.style,visualTransform:r||i==="video"?ke(e.visualTransform):e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1,textContent:e.textContent??(r?"默认文本":void 0),textStyle:r?Tt(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});if(G.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:g.id,type:g.type,startTime:g.startTime,duration:g.duration})),e.trackId){const T=this.getTrackCollection().findById(e.trackId);if(T)return this.registerPreviewAutoAspectRatioClip(g),(C=T.addClip)==null||C.call(T,g),Mi({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(g)},applyEffects:()=>Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(g),g.id}const f=this.getTimelineCommands().planTrackPlacement(g,this.getTracksSortedByOrder()),y=this.getTrackCollection(),S=$d({clip:g,placement:f,trackCollection:y,createTrack:this.createTrack.bind(this)});return Mi({applied:S,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(g)},applyEffects:()=>Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(g),g.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),Mi({applied:os(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)})}))}removeClipsByExternalId(e){if(!e)return!1;const t=this.resolveClipIdsForExternalIdRemoval(e);if(t.length===0)return!1;const i=new Set(t);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let r=!1;return this.withClipRemovalBatch(()=>{for(const n of t){const s=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);s.exists&&(r=os(this.getTrackCollection(),s,n)||r)}}),r?(Pi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){if(this.getTimelineCommands().findClipById(this.tracks,e)){if(this.getTrackCollection().updateClip(e,t),Object.prototype.hasOwnProperty.call(t,"thumbnails")){const i=this.findClipById(e);i&&this.markClipThumbnailLoadCompleted(i)}Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);if((i==null?void 0:i.clip.type)==="text")return;const r=i==null?void 0:i.track.splitSelectedClip;r&&(this.withSplitOperation(()=>{r.call(i.track,t)}),Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e);if((t==null?void 0:t.clip.type)==="text")return;const i=t==null?void 0:t.track.splitSelectedClip;i&&(this.withSplitOperation(()=>{i.call(t.track,e)}),Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var n,s,o;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(Ct(e.mode)&&t===Ee.width&&i===Ee.height){const l=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,c=(s=l==null?void 0:l.style)==null?void 0:s.sys_width,h=(o=l==null?void 0:l.style)==null?void 0:o.sys_height;typeof c=="number"&&c>0&&typeof h=="number"&&h>0&&(t=c,i=h)}const r=Fr({width:t,height:i});return{width:r.width,height:r.height,aspectRatio:`${r.width}:${r.height}`,mode:e.mode}}getExportCoverUrl(e){var r;let t=null,i=null;for(const n of e)for(const s of n.clips)if(s.type==="video"){if(!t||!i){t=n,i=s;continue}if(s.startTime<i.startTime){t=n,i=s;continue}s.startTime===i.startTime&&n.order<t.order&&(t=n,i=s)}return((r=i==null?void 0:i.thumbnails)==null?void 0:r[0])||""}exportTimeline(){const e=this.getResolvedTracksSnapshot().slice().sort((i,r)=>i.order-r.order).map(i=>{const r=i.clips.map(n=>({id:n.id,type:n.type,externalId:n.externalId,src:n.src,name:n.name,isMuted:n.isMuted??!1,startTime:Math.round(n.startTime),duration:Math.round(n.duration),endTime:Math.round(n.endTime),startTimeAtSource:Math.round(n.startTimeAtSource),endTimeAtSource:Math.round(n.endTimeAtSource),sourceDuration:Math.round(n.sourceDuration),thumbnails:n.thumbnails,visualTransform:n.type==="video"||n.type==="text"?ke(n.visualTransform):void 0,separatedAudioClipId:n.separatedAudioClipId,separatedFromVideoClipId:n.separatedFromVideoClipId,volume:n.volume??1,textContent:n.textContent,textStyle:n.textStyle,ttsSourceTextClipId:n.ttsSourceTextClipId,ttsVoiceId:n.ttsVoiceId,ttsVoiceName:n.ttsVoiceName,ttsFollowTextUpdates:n.ttsFollowTextUpdates})).sort((n,s)=>n.startTime-s.startTime);return{id:i.id,type:i.type,name:i.name||"未命名轨道",order:i.order,role:i.role??"normal",isMuted:i.isMuted??!1,clips:r}}),t=this.getExportCoverUrl(e);return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){G.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const t=new Map,i=[...e.tracks].sort((c,h)=>c.order-h.order),r=this.resolveImportedTrackRoles(i);let n;for(const c of i){const h=this.createTrack(c.type,c.name,n?"after_track":void 0,n,r.get(c.id));h&&(this.muteTrack(h,c.isMuted),t.set(c.id,h),n=h)}const s=new Map,o=[];for(const c of i){const h=t.get(c.id);if(h)for(const d of c.clips)try{let u=d.separatedAudioClipId;u&&s.has(u)&&(u=s.get(u));let g=d.separatedFromVideoClipId;g&&s.has(g)&&(g=s.get(g));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:g,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,ttsSourceTextClipId:d.ttsSourceTextClipId,ttsVoiceId:d.ttsVoiceId,ttsVoiceName:d.ttsVoiceName,ttsFollowTextUpdates:d.ttsFollowTextUpdates,trackId:h},y=await this.addClip(f);s.set(d.id,y)}catch(u){o.push({clipId:d.id,error:u}),G.error("TimelineManager",`Failed to import clip ${d.id}:`,{error:u})}}this.clearHistory();const l={errors:o};this.emitEvent("draft_loaded",l)}resolveImportedTrackRoles(e){const t=new Map;let i=!1;for(const n of e){const s=n.role==="primary"&&!i?"primary":"normal";s==="primary"&&(i=!0),t.set(n.id,s)}if(i)return t;const r=this.inferImportedPrimaryTrackIndex(e);return r>=0&&t.set(e[r].id,"primary"),t}inferImportedPrimaryTrackIndex(e){var t;for(let i=e.length-1;i>=0;i-=1)if(((t=e[i])==null?void 0:t.type)==="video")return i;return e.length>0?0:-1}stopPlaybackForImport(){var i;const e=this.getPlayStateState()==="playing",t=(i=this.previewSession)!=null&&i.hasPreview()?this.previewMountContainer:null;this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),e?this.pause():this.setPlayStateState("paused"),this.destroyPreviewSession(!0),t&&(this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t,this.previewAspectRatio)),this.syncPreviewSession()}getClipsData(){return this.getClips()}getVersion(){return Bt.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(c=>c.startTime)),r=(Math.max(...e.map(c=>c.endTime))-t)/1e3,n=((l=this.stage)==null?void 0:l.width())||0,s=n-ue*2;G.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:s}));const o=Math.min(s/r,ye.MAX);if(this.setZoom(o),this.timeline){const c=e.reduce((h,d)=>d.startTime<h.startTime?d:h);this.scrollToClip(c.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){var i;this.previewSyncInteractionMode=t,this.beginPendingPreview(e,t),this.setCurrentTime(e),t!=="scrub"&&this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"timeline.seek",message:"Timeline seek requested",playbackAttemptId:this.playbackAttemptId,syncRequestId:((i=this.pendingPreviewState)==null?void 0:i.syncRequestId)??null,runtimeState:this.buildDiagnosticsRuntimeState(),extra:{targetTime:e}})}handleScrollChange(e){this.syncScrollLeft(e)}handleClipUpdate(e,t,i){this.isExecutingHistoryAction||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i),this.emitEvent("clip_updated",{clip:e});const r=this.selectedClipId===e.id;Wh({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),r&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){this.splitOperationDepth>0||(this.registerPreviewAutoAspectRatioClip(e),this.emitEvent("clip_added",{clip:e}),Pi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}))}handleClipRemove(e){this.clipThumbnailLoadStates.delete(e),!(this.splitOperationDepth>0)&&(this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Pi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}))}reloadClipThumbnailsIfNeeded(e,t){Yh(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{G.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){var n;const e=this.getClips(),t=this.getCurrentTime(),i=Xh(e,t),r=this.canPlay;this.canPlay=qh({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:((n=e[e.length-1])==null?void 0:n.endTime)||1,setCanPlay:s=>{this.canPlay=s},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:s=>{this.emitEvent("can_play_change",{canPlay:s})}}),r!==this.canPlay&&G.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:r,newState:this.canPlay}))}findClipById(e){return this.getClips().find(t=>t.id===e)}buildGeneratedAudioClipName(e){return`配音 · ${e}`}normalizeGeneratedAudioDuration(e){return!Number.isFinite(e)||e<=0?1:Math.max(1,Math.round(e))}getVoiceLinkedAudioClips(e){return this.getClips().filter(t=>t.type==="audio"&&t.ttsSourceTextClipId===e)}applyGeneratedAudioClipResult(e,t,i,r,n){const s=this.normalizeGeneratedAudioDuration(r.duration);this.updateClip(e,{src:r.audioSrc,name:this.buildGeneratedAudioClipName(r.voiceName),textContent:i,duration:s,startTimeAtSource:0,endTimeAtSource:s,sourceDuration:s,ttsSourceTextClipId:t,ttsVoiceId:r.voiceId,ttsVoiceName:r.voiceName,ttsFollowTextUpdates:n})}syncTextClipDurationToAudio(e,t){const i=this.normalizeGeneratedAudioDuration(t),r=this.findClipById(e);r&&r.duration===i&&r.endTimeAtSource===i&&r.sourceDuration===i||(this.updateClip(e,{duration:i,endTimeAtSource:i,sourceDuration:i}),this.relocateClipIfNeeded(e))}doesClipOverlapOnTrack(e,t){const i=this.getTrackCollection().findById(e);if(!i)return!1;const r=t.startTime+t.duration;return i.getClips().some(n=>n.id!==t.id&&t.startTime<n.endTime&&r>n.startTime)}doesClipGroupOverlapOnTrack(e,t,i=new Set){const r=this.getTrackCollection().findById(e);if(!r)return!1;const n=r.getClips().filter(s=>!i.has(s.id));return t.some(s=>{const o=s.startTime+s.duration;return n.some(l=>l.id!==s.id&&s.startTime<l.endTime&&o>l.startTime)})}findNearestAvailableTrackForClip(e,t){const i=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),r=i.findIndex(o=>o.id===t);if(r===-1)return null;const s=i.map((o,l)=>({track:o,index:l,distance:Math.abs(l-r)})).filter(({track:o})=>o.id!==t&&o.type===e.type).sort((o,l)=>{if(o.distance!==l.distance)return o.distance-l.distance;const c=o.index>r?0:1,h=l.index>r?0:1;return c-h}).find(({track:o})=>!this.doesClipOverlapOnTrack(o.id,e));return(s==null?void 0:s.track.id)??null}resolveOverlapRelocationTargetTrackId(e,t){const i=this.findNearestAvailableTrackForClip(e,t);if(i)return i;const r=e.type==="audio"?"bottom_of_type_region":"top_of_type_region";return this.createTrack(e.type,void 0,"after_track",t)||this.createTrack(e.type,void 0,r)||null}relocateClipToAvoidOverlap(e){const t=this.findClipById(e);if(!t)return!1;const i=this.resolveTrackIdByClipId(e);if(!i||!this.doesClipOverlapOnTrack(i,t))return!1;const r=this.resolveOverlapRelocationTargetTrackId(t,i);return!r||r===i?!1:this.moveClipToTrack(e,r)}buildClipboardPasteGroups(e,t){const i=new Map,r=new Map;e.trackReferences.slice().sort((o,l)=>{var c,h;return(((c=o.trackSnapshot)==null?void 0:c.order)??Number.MAX_SAFE_INTEGER)-(((h=l.trackSnapshot)==null?void 0:h.order)??Number.MAX_SAFE_INTEGER)}).forEach((o,l)=>{var c;i.set(o.sourceTrackId,l),r.set(o.sourceTrackId,((c=o.trackSnapshot)==null?void 0:c.order)??Number.MAX_SAFE_INTEGER)});let n=i.size;const s=new Map;return e.items.forEach(o=>{const l=o.sourceTrackId??`clipboard-orphan:${o.sourceClipId}`,c=t.get(o.sourceClipId);if(!c)return;let h=s.get(l);if(!h){const d=i.get(l);h={key:l,type:o.clip.type,sourceTrackId:o.sourceTrackId,sourceTrackOrder:r.get(l)??Number.MAX_SAFE_INTEGER,sourceOrder:d??n++,sourceClipIds:[],clipIds:[]},s.set(l,h)}h.sourceClipIds.push(o.sourceClipId),h.clipIds.push(c)}),Array.from(s.values()).sort((o,l)=>o.sourceOrder-l.sourceOrder)}createTracksForTypeBoundary(e,t,i){for(let r=0;r<t;r+=1)i==="before"?this.createTrack(e,void 0,"top_of_type_region"):this.createTrack(e,void 0,"bottom_of_type_region")}buildClipboardPasteGroupPlacementClips(e,t,i,r){const n=new Map(t.items.map(s=>[s.sourceClipId,s]));return e.sourceClipIds.map(s=>{const o=n.get(s),l=i.get(s);return!o||!l?null:{id:l,startTime:r+(o.clip.startTime-t.minStartTime),duration:o.clip.duration}}).filter(s=>s!==null)}ensureClipboardPasteSourceTracks(e,t){const i=e.trackReferences.filter(r=>{var n;return((n=r.trackSnapshot)==null?void 0:n.type)===t}).sort((r,n)=>{var s,o;return(((s=r.trackSnapshot)==null?void 0:s.order)??Number.MAX_SAFE_INTEGER)-(((o=n.trackSnapshot)==null?void 0:o.order)??Number.MAX_SAFE_INTEGER)});for(const r of i)!r.trackSnapshot||r.trackSnapshot.role==="primary"||this.getTrackCollection().findById(r.sourceTrackId)||this.ensureTrackFromHistorySnapshot(r.trackSnapshot,r.trackRestoreAnchor)}resolveClipboardPasteTypeGroupAssignments(e,t,i,r){const n=new Map;if(e.length===0)return n;this.ensureClipboardPasteSourceTracks(t,e[0].type);const s=[...this.getResolvedTracksSnapshot()].filter(v=>{var w;return v.type===((w=e[0])==null?void 0:w.type)}).sort((v,w)=>v.order-w.order);if(s.length===0){const v=this.createTrack(e[0].type);v&&n.set(e[0].key,v);for(let w=1;w<e.length;w+=1){const x=this.createTrack(e[w].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");x&&n.set(e[w].key,x)}return n}const o=new Set(e.flatMap(v=>v.clipIds)),l=e.map(v=>{const w=this.buildClipboardPasteGroupPlacementClips(v,t,i,r);if(w.length===0)return null;const x=this.resolvePreferredTrackIndexForPasteGroup(v,s,Math.min(v.sourceOrder,Math.max(s.length-1,0)));return{...v,preferredTrackIndex:x,clips:w}}).filter(v=>v!==null);if(l.length===0)return n;const c=l.map(v=>v.preferredTrackIndex),h=Math.min(...c),d=s.length,u=-l.length;let g=null,f=Number.POSITIVE_INFINITY;for(let v=u;v<=d;v+=1){let w=!0,x=0,P=0;for(let M=0;M<l.length;M+=1){const I=l[M];if(!I)continue;const A=v+M;if(x+=Math.abs(A-I.preferredTrackIndex),A<0||A>=s.length){P+=1;continue}if(this.doesClipGroupOverlapOnTrack(s[A].id,I.clips,o)){w=!1;break}}w&&(x+=P*.1,x+=Math.abs(v-h)*.001,x<f&&(f=x,g=v))}if(g===null)return n;const y=Math.max(0,-g),S=Math.max(0,g+l.length-s.length);y>0&&this.createTracksForTypeBoundary(l[0].type,y,"before"),S>0&&this.createTracksForTypeBoundary(l[0].type,S,"after");const C=[...this.getResolvedTracksSnapshot()].filter(v=>{var w;return v.type===((w=l[0])==null?void 0:w.type)}).sort((v,w)=>v.order-w.order),T=g+y;return l.forEach((v,w)=>{const x=C[T+w];x&&n.set(v.key,x.id)}),n}resolvePreferredTrackIndexForPasteGroup(e,t,i){if(e.sourceTrackId){const r=t.findIndex(n=>n.id===e.sourceTrackId);if(r!==-1)return r}if(Number.isFinite(e.sourceTrackOrder)){const r=t.findIndex(n=>n.order>=e.sourceTrackOrder);return r!==-1?r:t.length}return i}resolveClipboardPasteTrackAssignments(e,t,i){const r=this.buildClipboardPasteGroups(e,t),n=new Map;r.forEach(o=>{const l=n.get(o.type)??[];l.push(o),n.set(o.type,l)});const s=new Map;return n.forEach(o=>{this.resolveClipboardPasteTypeGroupAssignments(o,e,t,i).forEach((c,h)=>{s.set(h,c)})}),s}relocateClipIfNeeded(e){this.relocateClipToAvoidOverlap(e)}async regenerateVoiceLinkedAudioClips(e,t,i){const r=this.getVoiceLinkedAudioClips(e).filter(c=>c.ttsFollowTextUpdates===!0&&!!c.ttsVoiceId);if(r.length===0)return;const n=r.map((c,h)=>({requestId:`regen:${c.id}:${Date.now()}:${h}`,sourceTextClipId:e,targetAudioClipId:c.id,text:t,voiceId:c.ttsVoiceId,followTextUpdates:!0,mode:"replace"})),s=await i(n),o=new Map(s.map(c=>[c.requestId,c]));let l=0;n.forEach(c=>{const h=o.get(c.requestId);!h||!c.targetAudioClipId||(this.applyGeneratedAudioClipResult(c.targetAudioClipId,e,t,h,c.followTextUpdates),this.relocateClipIfNeeded(c.targetAudioClipId),l=Math.max(l,this.normalizeGeneratedAudioDuration(h.duration)))}),l>0&&this.syncTextClipDurationToAudio(e,l),this.handleClipChange()}getSelectedTextClipsForVoiceGeneration(e){if(e.type!=="text")return[e];const t=this.getSelectedClips().filter(i=>i.type==="text");return t.length===0?[e]:t.some(i=>i.id===e.id)?t:[e]}async handleVoiceGenerateAction(e,t,i,r,n){if(t.type==="text"){const c=this.getSelectedTextClipsForVoiceGeneration(t),h=Date.now(),d=c.map((S,C)=>({requestId:`create:${S.id}:${i.id}:${h}:${C}`,sourceTextClipId:S.id,text:S.textContent??S.name??"",voiceId:i.id,followTextUpdates:r,mode:"create"})),u=await n(d),g=new Map(u.map(S=>[S.requestId,S]));e.setPreferredTab("voice");const f=[];for(const S of d){const C=g.get(S.requestId);if(!C)continue;const T=c.find(P=>P.id===S.sourceTextClipId);if(!T)continue;const v=this.normalizeGeneratedAudioDuration(C.duration),w=T.textContent??T.name??"";this.syncTextClipDurationToAudio(T.id,v);const x=await this.addClip({type:"audio",src:C.audioSrc,name:this.buildGeneratedAudioClipName(C.voiceName),textContent:w,startTime:T.startTime,duration:v,startTimeAtSource:0,endTimeAtSource:v,sourceDuration:v,ttsSourceTextClipId:T.id,ttsVoiceId:C.voiceId,ttsVoiceName:C.voiceName,ttsFollowTextUpdates:r});f.push(x)}if(f.length===0)throw new Error("生成音频失败:未返回音频结果");if(f.length===1){this.scrollToClip(f[0],{selectClip:!0,setCurrentTime:!0});return}const y=f[0]??null;this.scrollToClip(y,{setCurrentTime:!0}),this.setSelection(f,{preferredPrimaryClipId:y});return}if(t.type!=="audio"||!t.ttsSourceTextClipId)return;const s=this.findClipById(t.ttsSourceTextClipId);if(!s||s.type!=="text")throw new Error("未找到配音关联的文本片段");const o=`replace:${t.id}:${i.id}:${Date.now()}`,[l]=await n([{requestId:o,sourceTextClipId:s.id,targetAudioClipId:t.id,text:s.textContent??s.name??"",voiceId:i.id,followTextUpdates:r,mode:"replace"}]);if(!l)throw new Error("替换音色失败:未返回音频结果");e.setPreferredTab("voice"),this.applyGeneratedAudioClipResult(t.id,s.id,s.textContent??s.name??"",l,r),this.relocateClipIfNeeded(t.id),this.syncTextClipDurationToAudio(s.id,l.duration),this.handleClipChange()}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{G.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){G.warn("TimelineManager","Error loading clip thumbnails:",{error:i,clipId:e.id})}}markClipThumbnailLoadCompleted(e){return Array.isArray(e.thumbnails)?(this.sourceMediaRegistry.primeThumbnails(this.buildClipThumbnailResourceKey(e),e.thumbnails),this.clipThumbnailLoadStates.set(e.id,{signature:this.buildClipThumbnailLoadSignature(e),promise:null,completed:!0}),!0):!1}buildClipThumbnailLoadSignature(e,t=this.thumbnailProviderVersion){return[t,e.type,e.src,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}buildSourceMediaKey(e){return gr.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return gr.buildThumbnailKey({...e,externalId:e.externalId})}isClipThumbnailLoadCurrent(e,t){var i;return((i=this.clipThumbnailLoadStates.get(e))==null?void 0:i.signature)===t}areThumbnailArraysEqual(e,t){return!e||e.length!==t.length?!1:e.every((i,r)=>i===t[r])}handleClipSplit(e,t){Zh({clip1:e,clip2:t,isExecutingHistoryAction:this.isExecutingHistoryAction,recordSplitClip:this.getTimelineHistoryRecorder().recordSplitClip.bind(this.getTimelineHistoryRecorder()),emitClipUpdated:i=>{this.emitEvent("clip_updated",{clip:i})},emitClipAdded:i=>{this.emitEvent("clip_added",{clip:i})},applyEffects:()=>Pi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=jh(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),G.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){G.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeUndo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}handleActionRedo(e){G.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeRedo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}on(e,t){this.getEventDispatcher().on(e,t)}off(e,t){this.getEventDispatcher().off(e,t)}emitEvent(e,t){this.getEventDispatcher().emit(e,t)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=Nd({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}handleClipOverlap(e,t){G.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const i=this.getTrackCollection();if(!i.findById(t))return;const r=e.type,n=this.trackManager.getTracksByType(r).length+1,s=`${lu(r)}轨道 ${n}`;Vd({clip:e,currentTrackId:t,trackType:r,trackName:s,trackCollection:i,createTrack:this.createTrack.bind(this)}),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const r=this.resolveCrossTrackPreviewDestination(e,t,i);return r.status==="existing_track"?(this.showClipDropPreview(e,r.targetTrackId),r.targetTrackId===i?"self":"external"):r.status==="new_track_insertion"?(this.showTrackInsertionPreview(r.trackType,r.insertionPlacement,r.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,r){G.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:r}));const n=this.resolveCrossTrackMoveDestination(e,i,r);return n.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):n.status==="same_track"?(G.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(G.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:n.targetTrackId})),this.showClipDropPreview(e,n.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,n.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}resize(e,t){this.rootContainer&&(this.rootContainer.style.width=`${e}px`,this.rootContainer.style.height=`${t}px`,this.updateViewportLayout())}scrollToTime(e,t=!1){this.timeline&&(this.timeline.scrollToTime(e),this.handleScrollChange(this.timeline.getScrollLeft()),t&&this.setCurrentTime(e))}notifySelectionChange(){const e=this.getSelectedClipIds();this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),e)}syncPrimarySelectionFromSelectionStore(){var t,i,r,n;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((n=(r=this.selectionStore)==null?void 0:r.getSelectedClipId)==null?void 0:n.call(r))??null;this.selectedClipId=e}getOrderedSelectionClipIds(e,t){const i=Array.from(new Set(e));if(i.length<=1)return i;const r=t&&i.includes(t)&&t||this.selectedClipId&&i.includes(this.selectedClipId)&&this.selectedClipId||i[0]||null;return r?[r,...i.filter(n=>n!==r)]:i}setSelection(e,t={}){this.resetMultiDragSession();const i=this.getOrderedSelectionClipIds(e,t.preferredPrimaryClipId);this.selectionStore.setSelection(i),this.syncPrimarySelectionFromSelectionStore(),this.notifySelectionChange(),this.emitSelectionChangeEvent(),t.selectedClipEventClip&&this.emitEvent("clip_selected",{clip:t.selectedClipEventClip}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}selectClip(e,t){var r;const i=t||((r=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:r.clip);this.setSelection([e],{preferredPrimaryClipId:e,selectedClipEventClip:i??null})}clearSelection(){this.setSelection([])}getSelectedClipIds(){var e,t;return((t=(e=this.selectionStore)==null?void 0:e.getSelectedClipIds)==null?void 0:t.call(e))??(this.selectedClipId?[this.selectedClipId]:[])}getPrimarySelectedClipId(){return this.getSelectedClipIds()[0]??null}addToSelection(e){this.setSelection([...this.selectionStore.getSelectedClipIds(),e],{preferredPrimaryClipId:this.selectedClipId??e})}removeFromSelection(e){this.setSelection(this.selectionStore.getSelectedClipIds().filter(t=>t!==e))}toggleSelection(e){const t=this.selectionStore.getSelectedClipIds(),i=t.includes(e);this.setSelection(i?t.filter(r=>r!==e):[...t,e],{preferredPrimaryClipId:i?void 0:e})}isClipSelected(e){return this.selectionStore.isSelected(e)}deleteSelectedClips(){this.deleteSelectedClipsWithHistoryLabel("delete_selected_clips")}copySelectedClips(){const e=this.captureSelectedClipsToClipboard();return e?(this.clipClipboard=e,!0):!1}cutSelectedClips(){return this.copySelectedClips()?this.deleteSelectedClipsWithHistoryLabel("cut_selected_clips"):!1}async pasteClipboardClips(){if(!this.clipClipboard||this.clipClipboard.items.length===0)return!1;const e=this.clipClipboard,t=new Map;for(const h of e.items)t.set(h.sourceClipId,this.generateClipId(h.clip.name));const i=this.resolveClipboardPasteTrackAssignments(e,t,this.getCurrentTime()),r=[],n=this.getTimelineHistoryRecorder(),s=this.getCurrentTime(),o=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const h of e.items){const d=this.buildClipboardPasteClipConfig(h,s,t),u=h.sourceTrackId??`clipboard-orphan:${h.sourceClipId}`,g=i.get(u)??this.resolveClipboardPasteTrackId(h,d,i),f=t.get(h.sourceClipId);if(!f)continue;const y=await this.addClipInternal({...d,id:f,...g?{trackId:g}:{}});(this.getClips().find(C=>C.id===y)??null)&&r.push(y)}}finally{this.isExecutingHistoryAction=o}if(r.length===0)return!1;const l=r.map(h=>this.getClips().find(d=>d.id===h)??null).filter(h=>h!==null).map(h=>n.createAddClipAction(this.cloneClipForClipboard(h)));o||n.recordCompoundAction(l,"paste_clipboard_clips");const c=e.primaryClipId?t.get(e.primaryClipId)??r[0]??null:r[0]??null;return this.setSelection(r,{preferredPrimaryClipId:c}),!0}deleteSelectedClipsWithHistoryLabel(e){this.resetMultiDragSession();const t=this.selectionStore.getSelectedClipIds();if(t.length===0)return!1;const i=this.getTimelineHistoryRecorder(),r=t.map(s=>{const o=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);return!o.exists||!o.clip?null:i.createRemoveClipAction({...o.clip},o.trackId,o.trackId?this.cloneTrackSnapshot(o.trackId):null,o.trackId?this.getTrackRestoreAnchor(o.trackId):null)}).filter(s=>s!==null);this.clearSelection();const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const s of t)this.removeClip(s)}finally{this.isExecutingHistoryAction=n}return n||i.recordCompoundAction(r,e),this.emitSelectionChangeEvent(),!0}captureSelectedClipsToClipboard(){const e=this.getSelectedClipIds();if(e.length===0)return null;const t=new Map,i=e.map(r=>{const n=this.getTimelineCommands().prepareRemoveClip(r,this.tracks);return!n.exists||!n.clip?null:(n.trackId&&!t.has(n.trackId)&&t.set(n.trackId,{sourceTrackId:n.trackId,trackSnapshot:this.cloneTrackSnapshot(n.trackId),trackRestoreAnchor:this.getTrackRestoreAnchor(n.trackId)}),{sourceClipId:r,sourceTrackId:n.trackId,clip:this.cloneClipForClipboard(n.clip)})}).filter(r=>r!==null);return i.length===0?null:{items:i,trackReferences:Array.from(t.values()),minStartTime:Math.min(...i.map(r=>r.clip.startTime)),primaryClipId:this.getPrimarySelectedClipId()}}cloneClipForClipboard(e){return{...e,thumbnails:e.thumbnails?[...e.thumbnails]:void 0,style:fs(e.style),visualTransform:e.visualTransform?{...e.visualTransform}:void 0,textStyle:e.textStyle?{...e.textStyle}:void 0}}buildClipboardPasteClipConfig(e,t,i){const r=e.clip,n=r.separatedAudioClipId?i.get(r.separatedAudioClipId)??void 0:void 0,s=r.separatedFromVideoClipId?i.get(r.separatedFromVideoClipId)??void 0:void 0,o=r.ttsSourceTextClipId?i.get(r.ttsSourceTextClipId)??void 0:void 0,l=t+(r.startTime-this.clipClipboard.minStartTime);return{type:r.type,externalId:r.externalId,src:r.src,name:r.name,isMuted:r.isMuted,startTime:l,duration:r.duration,startTimeAtSource:r.startTimeAtSource,endTimeAtSource:r.endTimeAtSource,sourceDuration:r.sourceDuration,thumbnails:r.thumbnails?[...r.thumbnails]:void 0,style:fs(r.style),visualTransform:r.visualTransform?{...r.visualTransform}:void 0,separatedAudioClipId:n,separatedFromVideoClipId:s,volume:r.volume,textContent:r.textContent,textStyle:r.textStyle?{...r.textStyle}:void 0,ttsSourceTextClipId:o,ttsVoiceId:r.ttsVoiceId,ttsVoiceName:r.ttsVoiceName,ttsFollowTextUpdates:r.ttsFollowTextUpdates}}resolveClipboardPasteTrackId(e,t,i){var l,c;const r=e.sourceTrackId??`clipboard-orphan:${e.sourceClipId}`,n=i.get(r);if(n)return n;if(e.sourceTrackId){const h=this.getTrackCollection().findById(e.sourceTrackId);if(h&&((l=h.getTrackType)==null?void 0:l.call(h))===t.type)return i.set(r,e.sourceTrackId),e.sourceTrackId;const d=((c=this.clipClipboard)==null?void 0:c.trackReferences.find(u=>u.sourceTrackId===e.sourceTrackId))??null;if(d!=null&&d.trackSnapshot&&d.trackSnapshot.role!=="primary"){const u=this.ensureTrackFromHistorySnapshot(d.trackSnapshot,d.trackRestoreAnchor);if(u)return i.set(r,u),u}}const s=this.getTimelineCommands().planTrackPlacement({type:t.type||"video",startTime:t.startTime??this.getCurrentTime(),duration:t.duration??0},this.getTracksSortedByOrder()),o=s.status==="use_existing_track"?s.trackId:this.createTrack(s.trackType,void 0,s.insertionPlacement);return o?(i.set(r,o),o):null}generateClipId(e){return`clip_${e}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.setSelection(this.tracks.flatMap(e=>e.getClips().map(t=>t.id)),{preferredPrimaryClipId:this.selectedClipId})}emitSelectionChangeEvent(){this.emitEvent("selection_change",this.resolveSelectionChangeData())}scrollToClip(e,t={}){const{selectClip:i=!1,setCurrentTime:r=!1}=t,n=this.getClips().find(s=>s.id===e);!n||!this.timeline||(this.timeline.scrollToClip(n),this.handleScrollChange(this.timeline.getScrollLeft()),r&&this.setCurrentTime(n.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}canCopySelectedClips(){return this.getSelectedClipIds().length>0}canCutSelectedClips(){return this.canCopySelectedClips()}canPasteClipboardClips(){var e;return(((e=this.clipClipboard)==null?void 0:e.items.length)??0)>0}canDeleteSelectedClips(){return this.getSelectedClipIds().length>0}canSplitSelectedClip(){const e=this.resolveSelectedClipAtTime(this.getCurrentTime());return!!e&&e.clip.type!=="text"}getSelectedClipAudioAction(){const e=this.getSelectedClips().filter(r=>r.type==="video");return e.length===0?null:e.some(r=>this.canSeparateClipAudio(r.id))?"separate":e.some(r=>this.canRestoreClipAudio(r.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const e=this.getSelectedClipAudioAction();return e?this.applySelectedClipAudioAction(e):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(e){return this.buildPlaybackPlan(e)}getActiveClipsAtTime(e){return this.buildPlaybackPlan(e).activeClips}attachPreview(e){const t=e instanceof HTMLElement?{container:e}:e;t.aspectRatio&&(this.previewAspectRatio=Ve({mode:t.aspectRatio.mode??(t.aspectRatio.width&&t.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:t.aspectRatio.width??this.previewAspectRatio.width,height:t.aspectRatio.height??this.previewAspectRatio.height})),this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t.container,this.previewAspectRatio),this.emitDiagnostic({severity:"info",category:"session",eventName:"preview.mount.attached",message:"Preview mount attached",playbackAttemptId:this.playbackAttemptId,previewBackend:this.getPreviewBackendType(),runtimeState:this.buildDiagnosticsRuntimeState(),extra:{hasAspectRatioOverride:!!t.aspectRatio}}),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){this.getPreviewRuntimeController().detachPreviewSession()&&(this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.emitDiagnostic({severity:"info",category:"session",eventName:"preview.mount.detached",message:"Preview mount detached",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}))}attachClipConfig(e,t={}){const i=new iu,r=t.generateVoiceBatch,n=r,s=r?async c=>{i.setVoiceGenerationBusy(!0);try{return await r(c)}finally{i.setVoiceGenerationBusy(!1)}}:void 0;i.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c);this.updateClip(c,h),this.handleClipChange(),n&&(d==null?void 0:d.type)==="text"&&typeof h.textContent=="string"&&h.textContent!==d.textContent&&this.regenerateVoiceLinkedAudioClips(d.id,h.textContent,n).catch(u=>{G.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:u,clipId:c})})},onGenerateVoice:async(c,h,d)=>{if(!s)throw new Error("未配置音色生成回调");await this.handleVoiceGenerateAction(i,c,h,d,s)}});const o=()=>i.updateFromExternal(),l=(c,h)=>{var u;const d=this.getPrimarySelectedClip();d&&((u=h==null?void 0:h.clip)==null?void 0:u.id)===d.id&&i.updateFromExternal()};return this.on("selected_clip_change",o),this.on("clip_updated",l),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",o),this.off("clip_updated",l),i.destroy()}),i.update(),i}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return Ve(this.previewAspectRatio)}getDiagnosticsSnapshot(){return this.diagnostics.getSnapshot()}subscribeDiagnostics(e){return this.diagnostics.subscribe(e)}getDiagnosticsLiveSnapshot(e){return this.diagnostics.getLiveSnapshot(void 0,e)}subscribeDiagnosticsLive(e,t){return this.diagnostics.subscribeLive(e,t)}exportDiagnosticsPackage(){return this.diagnostics.exportPackage()}clearDiagnostics(e=!0){this.diagnostics.clear(e),e&&this.diagnostics.startSession({packageName:Bt.name,packageVersion:Bt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=Ve({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...Ee},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}resolvePreferredSeparatedAudioTrackId(e,t){var l;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return null;const i=this.resolveTrackIdByClipId(e);if(!i)return null;const r=[...this.getResolvedTracksSnapshot()].sort((c,h)=>c.order-h.order),n=r.findIndex(c=>c.id===i);if(n===-1)return null;const s=t.startTime+t.duration,o=r.map((c,h)=>({track:c,index:h})).filter(({track:c})=>c.type==="audio").filter(({track:c})=>!c.clips.some(h=>t.startTime<h.endTime&&s>h.startTime));return o.length===0?null:(o.sort((c,h)=>{const d=Math.abs(c.index-n)-Math.abs(h.index-n);return d!==0?d:c.index-h.index}),((l=o[0])==null?void 0:l.track.id)??null)}async separateClipAudio(e){if(!this.canSeparateClipAudio(e))return null;const t=this.getClips().find(c=>c.id===e);if(!t||t.type!=="video")return null;const i=this.isExecutingHistoryAction,r=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let n=null;this.isExecutingHistoryAction=!0;try{if(n=await this.addClip({type:"audio",src:t.src,name:t.name,startTime:t.startTime,duration:t.duration,startTimeAtSource:t.startTimeAtSource,endTimeAtSource:t.endTimeAtSource,sourceDuration:t.sourceDuration,separatedFromVideoClipId:t.id,isMuted:!1,volume:t.volume??1,trackId:r??void 0}),!n)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:n})}finally{this.isExecutingHistoryAction=i}if(!n)return null;const s=this.getClips().find(c=>c.id===e),o=this.getClips().find(c=>c.id===n)??null,l=this.resolveTrackIdByClipId(n);return s?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,s,o,l),n):null}restoreClipAudio(e){if(!this.canRestoreClipAudio(e))return!1;const t=this.getClips().find(l=>l.id===e);if(!t||t.type!=="video")return!1;const i=t.separatedAudioClipId??null,r=i?this.getClips().find(l=>l.id===i)??null:null,n=i?this.resolveTrackIdByClipId(i):null,s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=s}const o=this.getClips().find(l=>l.id===e);return o?(s||this.getTimelineHistoryRecorder().recordRestoreClipAudio(t,o,r,n),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(o=>o.type==="video"),i=e==="separate"?t.filter(o=>this.canSeparateClipAudio(o.id)):t.filter(o=>this.canRestoreClipAudio(o.id));if(i.length===0)return!1;if(i.length===1){const[o]=i;return e==="separate"?!!await this.separateClipAudio(o.id):this.restoreClipAudio(o.id)}const r=this.getTimelineHistoryRecorder(),n=[],s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{if(e==="restore")for(const o of i){const l=this.getClips().find(f=>f.id===o.id);if(!l||l.type!=="video")continue;const c=l.separatedAudioClipId??null,h=c?this.getClips().find(f=>f.id===c)??null:null,d=c?this.resolveTrackIdByClipId(c):null,u=this.restoreClipAudio(o.id),g=this.getClips().find(f=>f.id===o.id);!u||!g||n.push(r.createRestoreClipAudioAction({...l},{...g},h?{...h}:null,d))}else for(const o of i){const l=this.getClips().find(g=>g.id===o.id);if(!l||l.type!=="video")continue;const c=await this.separateClipAudio(o.id),h=this.getClips().find(g=>g.id===o.id),d=c?this.getClips().find(g=>g.id===c)??null:null,u=c?this.resolveTrackIdByClipId(c):null;!c||!h||n.push(r.createSeparateClipAudioAction({...l},{...h},d?{...d}:null,u))}}finally{this.isExecutingHistoryAction=s}return s||r.recordCompoundAction(n,`selected_clips_audio_${e}`),n.length>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,r=null){const n=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(n.status==="missing_source_track")return G.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(n.status==="noop")return G.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(n.status==="missing_target_track")return G.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(n.status==="track_type_mismatch")return G.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var f,y,S;return{targetTrackType:(y=(f=this.getTrackCollection().findById(t))==null?void 0:f.getTrackType)==null?void 0:y.call(f),clipType:(S=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:S.clip.type}}),!1;if(n.status!=="ready")return!1;const{sourceTrackId:s,targetTrackId:o}=n,l=i?{...i}:{...n.clip},c=r?{...r}:{...n.clip},h=this.cloneTrackSnapshot(s),d=this.cloneTrackSnapshot(o),u=zd({command:{...n,clip:c},trackCollection:this.getTrackCollection()}),g=this.getClips().find(f=>f.id===e)??null;return Kh({applied:u,clipId:e,sourceTrackId:s,targetTrackId:o,clipBefore:l,clipAfter:g??l,sourceTrackSnapshot:h,targetTrackSnapshot:d,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>Ud({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 ns(this.getClips())}destroy(){var e,t,i,r,n,s,o,l,c,h,d,u;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPreviewBufferingSuspendTimeout(),this.clearPendingPreviewState(),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(e=this.diagnosticsPanel)==null||e.destroy(),this.diagnosticsPanel=null,(t=this.layout)==null||t.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(n=(i=this.layout)==null?void 0:(r=i.bodyCanvasHost).removeEventListener)==null||n.call(r,"click",this.bodyCanvasHostClickListener),(o=(s=this.rootContainer)==null?void 0:s.removeEventListener)==null||o.call(s,"wheel",this.rootWheelListener),(l=this.horizontalScrollbar)==null||l.destroy(),(c=this.verticalScrollbar)==null||c.destroy(),(h=this.playhead)==null||h.destroy(),(d=this.timeline)==null||d.destroy(),(u=this.stage)==null||u.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new gs),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new Fd({root:this.rootContainer,config:this.config.keyboardShortcuts,callbacks:{togglePlay:()=>this.togglePlay(),deleteSelectedClips:()=>{this.removeSelectedClips()},copySelectedClips:()=>{this.copySelectedClips()},cutSelectedClips:()=>{this.cutSelectedClips()},pasteClipboardClips:()=>this.pasteClipboardClips(),toggleSelectedClipsAudio:()=>this.toggleSelectedClipsAudio(),splitCurrentClip:()=>this.splitCurrentClip(),undo:()=>this.undo(),redo:()=>this.redo(),canDeleteSelectedClips:()=>this.canDeleteSelectedClips(),canCopySelectedClips:()=>this.canCopySelectedClips(),canCutSelectedClips:()=>this.canCutSelectedClips(),canPasteClipboardClips:()=>this.canPasteClipboardClips(),canSplitSelectedClip:()=>this.canSplitSelectedClip(),canToggleSelectedClipsAudio:()=>this.canToggleSelectedClipsAudio()}}),this.keyboardShortcutsController.init(),this.mountManager.register("keyboardShortcuts",()=>{var t;(t=this.keyboardShortcutsController)==null||t.destroy(),this.keyboardShortcutsController=null}))}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(e){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return e()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}withSplitOperation(e){this.splitOperationDepth=(this.splitOperationDepth??0)+1;try{return e()}finally{this.splitOperationDepth=Math.max(0,(this.splitOperationDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(e){const t=this.getClips(),i=new Map(t.map(s=>[s.id,s])),r=new Set,n=t.filter(s=>s.externalId===e).map(s=>s.id);for(let s=0;s<n.length;s+=1){const o=n[s];if(r.has(o))continue;r.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!r.has(l.separatedAudioClipId)&&n.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!r.has(l.separatedFromVideoClipId)&&n.push(l.separatedFromVideoClipId))}return t.filter(s=>r.has(s.id)).map(s=>s.id)}shouldClearSelectionForClipIds(e){return this.selectedClipId&&e.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(t=>e.has(t))}resolveSelectedClipAtTime(e){var i;const t=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const r of t){const n=this.getTimelineCommands().findClipById(this.tracks,r),s=n==null?void 0:n.clip;if(s&&e>=s.startTime&&e<s.endTime)return n}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{if(e.isFinal){const i=this.finalizeMultiDragCrossTrack(t,e);return i||this.syncMultiDragPeerClips(t,e,!0),i}return this.syncMultiDragOverlayState(t,e.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(t,e,!1),e.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(t,e.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(t,e)}finally{e.isFinal&&(this.syncMultiDragOverlayState(t,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((e,t)=>{var i;(i=e.setTrackStackOrder)==null||i.call(e,t)})}elevateMultiDragTrackGroups(e,t){var o,l,c;const i=this.resolveMultiDragSessionTrackIds(e);if(i.length<=1)return;const r=i.indexOf(t);r>=0&&(i.splice(r,1),i.push(t));const n=new Set(i);let s=0;for(const h of this.tracks){const d=(o=h.getId)==null?void 0:o.call(h);!d||n.has(d)||(l=h.setTrackStackOrder)==null||l.call(h,s++)}for(const h of i){const d=this.getTrackCollection().findById(h);(c=d==null?void 0:d.setTrackStackOrder)==null||c.call(d,s++)}}resolveMultiDragSessionTrackIds(e){var i;const t=new Set;for(const r of this.tracks){const n=(i=r.getId)==null?void 0:i.call(r);if(!n)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===n})&&t.add(n)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const r of e.selectedClipIds){const n=e.clips.get(r);if(!n)continue;const s=i.get(n.trackId);s?s.push(r):i.set(n.trackId,[r])}i.forEach((r,n)=>{var o;const s=this.getTrackCollection().findById(n);(o=s==null?void 0:s.setClipsDragOverlayActive)==null||o.call(s,r,t)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDragOverlay)==null?void 0:t.call(e)})}ensureMultiDragSession(e){var r;const t=this.selectionStore.getSelectedClipIds();if(t.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===e.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,t))return this.multiDragSession;const i=new Map;for(const n of t){const s=this.findTrackByClipId(n),o=((r=s==null?void 0:s.getId)==null?void 0:r.call(s))??this.resolveTrackIdByClipId(n),l=s==null?void 0:s.getClips().find(h=>h.id===n);if(!o||!l)continue;const c=n===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(n,{clipId:n,trackId:o,clip:c})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:e.draggedClipId,selectedClipIds:t.slice(),clips:i},this.multiDragSession)}haveSameClipIds(e,t){if(e.length!==t.length)return!1;const i=new Set(t);return e.every(r=>i.has(r))}restoreDraggedClipSnapshot(e,t){const i=Math.max(0,e.startTime-t);return{...e,startTime:i,endTime:i+e.duration}}syncMultiDragPeerClips(e,t,i){for(const r of e.selectedClipIds){if(r===t.draggedClipId)continue;const n=e.clips.get(r);if(!n||n.trackId===t.currentTrackId)continue;const s=this.getTrackCollection().findById(n.trackId);if(!(s!=null&&s.updateClipPosition))continue;const o=Math.max(0,n.clip.startTime+t.deltaTime);s.updateClipPosition(r,o,i,i?0:t.crossTrackOffsetY)}}previewMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackPreviewDestination(r,t.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 s=this.resolveTrackIndexDelta(i.trackId,n.targetTrackId,i.clip.type);if(s===null)return!1;const o=new Map;this.appendPreviewClip(o,n.targetTrackId,r);for(const l of e.selectedClipIds){if(l===t.draggedClipId)continue;const c=e.clips.get(l);if(!c)continue;const h=this.buildMovedClipSnapshot(c.clip,t.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(c,s,h);!d||d===c.trackId||this.appendPreviewClip(o,d,h)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackMoveDestination(r,t.targetTrackY,i.trackId);if(n.status==="blocked"||n.status==="same_track")return!1;const s=n.targetTrackId;if(!s)return!1;const o=this.resolveTrackIndexDelta(i.trackId,s,i.clip.type);if(o===null)return!1;for(const l of e.selectedClipIds){const c=e.clips.get(l);if(!c)continue;const h=this.buildMovedClipSnapshot(c.clip,t.deltaTime),d=h.startTime,u=l===t.draggedClipId?s:this.resolveMultiDragTargetTrackId(c,o,h);if(u){if(u===c.trackId){this.updateClipPositionWithHistory(c.trackId,c.clipId,d);continue}this.updateClipPositionSilently(c.trackId,c.clipId,d),this.moveClipToTrackWithHistorySnapshot(c.clipId,u,c.clip,h)}}return!0}resolveTrackIndexDelta(e,t,i){const r=this.getTrackIdsByType(i),n=r.indexOf(e),s=r.indexOf(t);return n===-1||s===-1?null:s-n}resolveMultiDragTargetTrackId(e,t,i){const r=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return e.trackId;const n=this.calculateTrackY(r)+1,s=this.resolveCrossTrackMoveDestination(i,n,e.trackId);return s.status==="blocked"?r:s.targetTrackId}resolveMultiDragPreviewTargetTrackId(e,t,i){const r=this.findTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return null;const n=this.calculateTrackY(r)+1,s=this.resolveCrossTrackPreviewDestination(i,n,e.trackId);return s.status==="existing_track"?s.targetTrackId:null}buildMovedClipSnapshot(e,t,i=!1){let r=e.startTime+t;if(i){const n=this.getDurationState();r=Math.max(0,Math.min(r,n-e.duration))}else r=Math.max(0,r);return{...e,startTime:r,endTime:r+e.duration}}appendPreviewClip(e,t,i){const r=e.get(t);if(r){r.push(i);return}e.set(t,[i])}resolveCrossTrackMoveDestination(e,t,i){if(!this.trackManager||!this.getTimelineCommands)return{status:"blocked"};const r=this.trackManager.getTracks(),n=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);if(n.status==="missing_target_track_by_position")return G.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return G.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return G.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:e.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};G.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const s=this.createTrack(n.trackType,void 0,n.insertionPlacement,n.referenceTrackId);return s?{status:"move_to_track",targetTrackId:s}:{status:"blocked"}}resolveCrossTrackPreviewDestination(e,t,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const r=this.trackManager.getTracks();if(!Array.isArray(r)||r.length===0)return{status:"clear"};const n=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),r,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(e,t,i){let r=this.getTrackIdsByType(t);const n=r.indexOf(e);if(n===-1)return null;let s=n+i;for(;s<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;r=this.getTrackIdsByType(t),s+=1}for(;s>=r.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;r=this.getTrackIdsByType(t)}return r[s]??null}findTrackIdByRelativeIndex(e,t,i){const r=this.getTrackIdsByType(t),n=r.indexOf(e);if(n===-1)return null;const s=n+i;return s<0||s>=r.length?null:r[s]??null}getTrackIdsByType(e){if(!this.trackManager)return[];const t=this.trackManager.getTracks();return t?t.filter(i=>i.type===e).map(i=>i.id):[]}updateClipPositionWithHistory(e,t,i){var n;const r=this.getTrackCollection().findById(e);(n=r==null?void 0:r.updateClipPosition)==null||n.call(r,t,i,!0)}updateClipPositionSilently(e,t,i){const r=this.getTrackCollection().findById(e);if(!(r!=null&&r.updateClipPosition))return;const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{r.updateClipPosition(t,i,!0)}finally{this.isExecutingHistoryAction=n}}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new q.Rect({fill:Kr.fill,stroke:Kr.stroke,strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(t=this.selectionBoxLayer)==null||t.add(e),this.selectionBoxRect=e,e}showSelectionBoxRect(e,t,i,r){var s;const n=this.ensureSelectionBoxRect();n.x(e),n.y(t),n.width(Math.max(i,1)),n.height(Math.max(r,1)),n.visible(!0),(s=this.selectionBoxLayer)==null||s.batchDraw()}hideSelectionBoxRect(){var e;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(e=this.selectionBoxLayer)==null||e.batchDraw())}handleStageMouseDown(e){if(e.button!==0)return;const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=e.clientY-r.top;if(this.isPointOnClip(n,s))return;this.isBoxSelecting=!1,this.boxSelectStartX=n,this.boxSelectStartY=s;const l=h=>{this.handleBoxSelectMove(h)},c=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",c)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",c)}handleBoxSelectMove(e){const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,s=e.clientY-r.top,o=Math.abs(n-this.boxSelectStartX),l=Math.abs(s-this.boxSelectStartY);if(!this.isBoxSelecting&&(o>4||l>4)&&(this.isBoxSelecting=!0),!this.isBoxSelecting)return;const c=Math.min(this.boxSelectStartX,n),h=Math.min(this.boxSelectStartY,s),d=Math.abs(n-this.boxSelectStartX),u=Math.abs(s-this.boxSelectStartY);this.showSelectionBoxRect(c,h,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const e=this.selectionBoxRect;if(e){const t={x:e.x(),y:e.y(),width:e.width(),height:e.height()},i=this.getClipsIntersectingBox(t);this.setSelection(i,{preferredPrimaryClipId:this.selectedClipId})}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(e,t){for(const i of this.tracks){const r=i.getTrackGroup(),n=r.y(),s=r.height()||64;if(!(t<n||t>n+s))for(const o of i.getClips()){const l=me(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=H.timeToPixels(o.duration,this.getZoomState());if(e>=l&&e<=l+c&&t>=n+2&&t<=n+s-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const r=i.getTrackGroup(),n=r.y(),s=r.height()||64;for(const o of i.getClips()){const l=me(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=H.timeToPixels(o.duration,this.getZoomState()),h=n+2,d=s-4,u=l+c,g=h+d,f=e.x+e.width,y=e.y+e.height;l<f&&u>e.x&&h<y&&g>e.y&&t.push(o.id)}}return t}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Ne({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(r=>r.id===e);return t?{...t,clips:t.clips.map(r=>({...r}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const r=this.resolveTrackInsertionFromRestoreAnchor(t);if(r){const u=this.createTrack(e.type,e.name,r.insertionPlacement,r.referenceTrackId);return this.muteTrack(u,e.isMuted??!1),u}const n=[...this.getTracks()].sort((u,g)=>u.order-g.order),s=n.find(u=>u.order>=e.order),o=s?n[n.findIndex(u=>u.id===s.id)-1]??null:n[n.length-1]??null;let l,c;s?(l="before_track",c=s.id):o&&(l="after_track",c=o.id);const h=this.createTrack(e.type,e.name,l,c);return this.muteTrack(h,e.isMuted??!1),h}getTrackRestoreAnchor(e){var r,n,s;if(!((r=this.trackManager)!=null&&r.getTracks))return null;const t=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=t.findIndex(o=>o.id===e);return i===-1?null:{previousTrackId:((n=t[i-1])==null?void 0:n.id)??null,nextTrackId:((s=t[i+1])==null?void 0:s.id)??null}}resolveTrackInsertionFromRestoreAnchor(e){return e?e.previousTrackId&&this.getTrackCollection().findById(e.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:e.previousTrackId}:e.nextTrackId&&this.getTrackCollection().findById(e.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:e.nextTrackId}:null:null}resolveTrackIdByClipId(e){var t;return((t=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:t.trackId)??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var s;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=Mr(e),n=ns(e);if(r!==t){this.lastTrackDuration=r;const o=ss(r);this.setDurationState(o),(s=this.timeline)==null||s.setDuration(o),this.updateViewportLayout()}n!==i&&(this.lastReportedTrackDuration=n,this.emitEvent("track_duration_change",{duration:n})),!(r===t&&n===i)&&G.debugLazy("TimelineManager",()=>`Track duration changed: total=${n}ms, extent=${r}ms, timeline=${ss(r)}ms`)}resolveSelectedClipSnapshot(){return Aa({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}}})}resolveSelectionChangeData(){return Hd({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}},getSelectedClipIds:()=>{try{return this.getSelectedClipIds()}catch{return[]}},canSplitSelectedClip:()=>{try{return this.canSplitSelectedClip()}catch{return!1}},getSelectedClipAudioAction:()=>{try{return this.getSelectedClipAudioAction()}catch{return null}}})}commitPreviewVisualTransform(e,t){const i=this.getClips().find(s=>s.id===e);if(!i||i.type!=="video"&&i.type!=="text")return;const r=ke(i.visualTransform),n=ke(t);jr(r,n)||this.updateClip(e,{visualTransform:n})}clearAllTracksAndClips(){var t,i,r,n;const e=this.getTracks();for(const s of e){const o=this.getTrackCollection().findById(s.id);if(o){const l=[...o.getClips()];for(const c of l)(t=o.removeClip)==null||t.call(o,c.id)}}for(const s of e){const o=s.id,l=this.getTrackCollection().findById(o);(r=(i=l==null?void 0:l.getTrackGroup)==null?void 0:i.call(l))==null||r.destroy(),this.getTrackCollection().removeById(o)}this.trackManager.clearAllTracks(),this.updateAllTrackPositions(),(n=this.stage)==null||n.batchDraw()}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=Br;exports.CLIP_LAYER=Fa;exports.Clip=Li;exports.ClipConfigPanel=xa;exports.DEFAULT_CLIP_VIEW_STATE=Ss;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Ee;exports.DEFAULT_TEXT_CLIP_STYLE=ys;exports.DiagnosticsCenter=la;exports.DiagnosticsPanel=ha;exports.HistoryManager=Dr;exports.MIN_CLIP_LINE_WIDTH=ei;exports.PREVIEW_ASPECT_RATIO_PRESETS=Ga;exports.Playhead=gh;exports.TIMELINE_LEFT_PADDING=ue;exports.TIME_SCALE=Ha;exports.TRACK_HEIGHT=Le;exports.TimeUtils=H;exports.Timeline=oh;exports.TimelineManager=cu;exports.Track=zi;exports.TrackInfoPanel=ka;exports.TrackManager=La;exports.ZOOM_ANIMATION=Cs;exports.ZOOM_PRESETS=ye;exports.createClipViewState=vs;exports.createClipWithViewState=Hr;exports.defaultDarkTheme=Bi;exports.devConsole=G;exports.isAutoPreviewAspectRatioMode=Ct;exports.mergeDiagnosticRuntimeState=ca;exports.normalizePreviewAspectRatio=Ve;exports.normalizePreviewAspectRatioMode=Gr;exports.resolveAspectRatioBaselineDimensions=Fr;exports.resolveTextClipStyle=Tt;exports.resolveTheme=Qt;
|