@linker-design-plus/timeline-track 2.0.21 → 2.0.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/panel/ClipConfigPanel.d.ts +15 -1
- package/dist/components/panel/ClipConfigPanelRenderer.d.ts +5 -3
- package/dist/components/track/Track.d.ts +1 -1
- package/dist/core/controllers/timelineClipConfigController.d.ts +4 -0
- package/dist/core/facade/timelineManager.d.ts +21 -1
- package/dist/core/history/timelineHistoryRecorder.d.ts +7 -1
- package/dist/core/layout/timelineManagerDom.d.ts +1 -1
- package/dist/index.cjs.js +185 -187
- package/dist/index.es.js +4654 -4339
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var qa=Object.defineProperty;var ja=(a,e,t)=>e in a?qa(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t;var p=(a,e,t)=>ja(a,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I={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",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)"},ee={background:I.black,border:I.borderStrong,timeTick:I.textSecondary,timeText:I.textSubtle,trackBackground:I.black,trackSelectedBackground:I.selectedTrackSurface,trackBorder:I.borderStrong,clipBackground:I.clipSurface,clipBorder:I.black,clipName:I.textPrimary,clipDuration:I.textMuted,clipHandle:I.textPrimary,clipSelectedBorder:I.clipSelectedBorder,clipCoverBackground:I.borderStrong,audioClipText:I.textAudio,audioClipAccent:I.audioClipAccent,playhead:I.textPrimary,grid:I.borderStrong,snapGuideLineColor:I.accentSelectedBorder,scrollbarBackground:I.borderStrong,scrollbarBorder:I.borderSubtle,scrollbarThumb:I.borderMedium},ge={backgroundColor:"#0f0f0f",borderColor:I.borderStrong,textColor:I.textSecondary,labelColor:I.textHint,inputBackground:I.inputSurface,inputBorder:I.borderMedium,inputFocusBorder:I.accentFocus,buttonBackground:I.inputSurface,buttonBorder:I.borderMedium,buttonActiveBackground:I.accentFocus,buttonActiveBorder:I.accentFocus,buttonActiveText:I.white},be={background:I.panelSurface,border:I.borderStrong,text:I.textPrimary,buttonBackground:I.buttonSurface,buttonHover:"#3a3a3a",buttonDanger:I.accentDanger},It={border:ee.scrollbarBorder,thumb:ee.scrollbarThumb,hitArea:I.overlayHitArea},bt={fill:I.white,stroke:I.black,text:I.black},xe={tabBarBackground:I.buttonSurface,actionBarBackground:I.buttonSurface,activeTabBackground:I.activeTabBackground,activeTabText:I.white,inactiveTabText:I.textInactive,sliderThumbShadow:`0 8px 20px ${I.sliderThumbShadow}`,sliderThumbInnerShadow:`inset 0 1px 1px ${I.sliderThumbInnerShadow}`},hn={grip:I.accentPlayheadGrip,shadow:I.overlayShadow},fi={background:I.overlayPreview,text:I.white,actionBackground:I.accentAction,actionText:I.white},st={border:I.overlayTransformHandle,handleBackground:I.black},dn={fill:I.overlaySelectionBoxFill,stroke:I.accentSelectionBox},gi={videoFill:I.overlayVideoDropPreview,videoStroke:I.accentSelectedBorder,audioFill:I.overlayAudioDropPreview,audioStroke:I.accentAudioPreview},un={line:I.gridLine},Bs={fontSize:32,color:"#fff",rotation:0,strokeColor:"#000000",strokeWidth:1,paddingX:4};function Me(a){return{...Bs,...a??{}}}const Os={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},Gi={background:ee.background,border:ee.border,timeTick:ee.timeTick,timeText:ee.timeText,trackBackground:ee.trackBackground,trackSelectedBackground:ee.trackSelectedBackground,trackBorder:ee.trackBorder,clipBackground:ee.clipBackground,clipBorder:ee.clipBorder,clipName:ee.clipName,clipDuration:ee.clipDuration,clipHandle:ee.clipHandle,clipSelectedBorder:ee.clipSelectedBorder,clipCoverBackground:ee.clipCoverBackground,audioClipText:ee.audioClipText,audioClipAccent:ee.audioClipAccent,playhead:ee.playhead,grid:ee.grid,snapGuideLineColor:ee.snapGuideLineColor,snapGuideLineWidth:1,scrollbarBackground:ee.scrollbarBackground,scrollbarBorder:ee.scrollbarBorder,scrollbarThumb:ee.scrollbarThumb};function Hi(a){return a?{...Gi,...a}:{...Gi}}const qr=720,De={mode:"auto-first-added-video",width:16,height:9},Ka=[{key:"default",label:"默认",aspectRatio:{...De}},{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 jr(a){return a==="manual"?"manual":"auto-first-added-video"}function wt(a){return jr(a)==="auto-first-added-video"}function Xe(a){return{mode:jr(a==null?void 0:a.mode),width:typeof(a==null?void 0:a.width)=="number"&&a.width>0?a.width:De.width,height:typeof(a==null?void 0:a.height)=="number"&&a.height>0?a.height:De.height}}function Kr(a,e=qr){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 Za={DEFAULT:1,ACTIVE:2},Re={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Ja={DURATION:300,EASING:"easeOutCubic"},Qa={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},Te=15,ii=6,Ri={TEXT:25,VIDEO:64,AUDIO:48};function Fs(a={}){const e=Object.fromEntries(Object.entries(a).filter(([,t])=>t!==void 0));return{...Os,...e}}function Zr(a,e={}){return{...a,...Fs(e)}}function kr(a){a.disablePictureInPicture=!0,a.setAttribute("disablepictureinpicture","")}class U{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 f=o;f<=t&&(n.push({time:this.secondsToMs(f),type:this.TICK_TYPE_MAJOR}),l++,!(l>=c));f+=i);let h=0;const d=400;let u=Math.floor(s/r)*r;for(let f=u;f<=t&&!(Math.abs(f-Math.round(f/i)*i)>.001&&(n.push({time:this.secondsToMs(f),type:this.TICK_TYPE_MINOR}),h++,h>=d));f+=r);return n.sort((f,g)=>f.time-g.time)}static getVideoDuration(e,t={}){const i=()=>new Promise(r=>{const n=document.createElement("video");n.preload="metadata",kr(n),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(U,"TICK_TYPE_MAJOR","major"),p(U,"TICK_TYPE_MINOR","minor");const eo=Math.PI/180;function to(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const at=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},D={_global:at,version:"10.2.0",isBrowser:to(),isUnminified:/param/.test((function(a){}).toString()),dblClickWindow:400,getAngle(a){return D.angleDeg?a*eo: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:at.document,_injectGlobal(a){typeof at.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),at.Konva=a}},ae=a=>{D[a.prototype.getClassName()]=a};D._injectGlobal(D);const io=`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,108 @@ or
|
|
|
11
11
|
|
|
12
12
|
bash: npm install skia-canvas
|
|
13
13
|
js: import "konva/skia-backend";
|
|
14
|
-
`,un=()=>{if(typeof document>"u")throw new Error(to)};class ye{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 ye(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,a=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]=a,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,a=this.m[3]+this.m[1]*e;return this.m[0]=i,this.m[1]=r,this.m[2]=n,this.m[3]=a,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],a=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]=a,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,a=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]=a,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],a=this.m[5],o=e*r-t*i,l={x:n,y:a,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 io="[object Array]",ro="[object Number]",no="[object String]",so="[object Boolean]",ao=Math.PI/180,oo=180/Math.PI,Et="#",lo="",co="0",ho="Konva warning: ",pn="Konva error: ",uo="rgb(",ir={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]},po=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let fi=[],Rt=null;const fo=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},b={_isElement(s){return!!(s&&s.nodeType==1)},_isFunction(s){return!!(s&&s.constructor&&s.call&&s.apply)},_isPlainObject(s){return!!s&&s.constructor===Object},_isArray(s){return Object.prototype.toString.call(s)===io},_isNumber(s){return Object.prototype.toString.call(s)===ro&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===no},_isBoolean(s){return Object.prototype.toString.call(s)===so},isObject(s){return s instanceof Object},isValidSelector(s){if(typeof s!="string")return!1;const e=s[0];return e==="#"||e==="."||e===e.toUpperCase()},_sign(s){return s===0||s>0?1:-1},requestAnimFrame(s){fi.push(s),fi.length===1&&fo(function(){const e=fi;fi=[],e.forEach(function(t){t()})})},createCanvasElement(){un();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return un(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,e){const t=b.createImageElement();t.onload=function(){e(t)},t.src=s},_rgbToHex(s,e,t){return((1<<24)+(s<<16)+(e<<8)+t).toString(16).slice(1)},_hexToRgb(s){s=s.replace(Et,lo);const e=parseInt(s,16);return{r:e>>16&255,g:e>>8&255,b:e&255}},getRandomColor(){let s=(Math.random()*16777215<<0).toString(16);for(;s.length<6;)s=co+s;return Et+s},isCanvasFarblingActive(){if(Rt!==null)return Rt;if(typeof document>"u")return Rt=!1,!1;const s=this.createCanvasElement();s.width=10,s.height=10;const e=s.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 Rt=i,this.releaseCanvas(s),Rt},getHitColor(){const s=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(s):s},getHitColorKey(s,e,t){return this.isCanvasFarblingActive()&&(s=Math.round(s/5)*5,e=Math.round(e/5)*5,t=Math.round(t/5)*5),Et+this._rgbToHex(s,e,t)},getSnappedHexColor(s){const e=this._hexToRgb(s);return Et+this._rgbToHex(Math.round(e.r/5)*5,Math.round(e.g/5)*5,Math.round(e.b/5)*5)},getRGB(s){let e;return s in ir?(e=ir[s],{r:e[0],g:e[1],b:e[2]}):s[0]===Et?this._hexToRgb(s.substring(1)):s.substr(0,4)===uo?(e=po.exec(s.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA(s){return s=s||"black",b._namedColorToRBA(s)||b._hex3ColorToRGBA(s)||b._hex4ColorToRGBA(s)||b._hex6ColorToRGBA(s)||b._hex8ColorToRGBA(s)||b._rgbColorToRGBA(s)||b._rgbaColorToRGBA(s)||b._hslColorToRGBA(s)},_namedColorToRBA(s){const e=ir[s.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(s){if(s.indexOf("rgb(")===0){s=s.match(/rgb\(([^)]+)\)/)[1];const e=s.split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(s){if(s.indexOf("rgba(")===0){s=s.match(/rgba\(([^)]+)\)/)[1];const e=s.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(s){if(s[0]==="#"&&s.length===9)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:parseInt(s.slice(7,9),16)/255}},_hex6ColorToRGBA(s){if(s[0]==="#"&&s.length===7)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:1}},_hex4ColorToRGBA(s){if(s[0]==="#"&&s.length===5)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:parseInt(s[4]+s[4],16)/255}},_hex3ColorToRGBA(s){if(s[0]==="#"&&s.length===4)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:1}},_hslColorToRGBA(s){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(s)){const[e,...t]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(s),i=Number(t[0])/360,r=Number(t[1])/100,n=Number(t[2])/100;let a,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?a=n*(1+r):a=n+r-n*r;const c=2*n-a,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+(a-c)*6*o:2*o<1?l=a:3*o<2?l=c+(a-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(s,e){return!(e.x>s.x+s.width||e.x+e.width<s.x||e.y>s.y+s.height||e.y+e.height<s.y)},cloneObject(s){const e={};for(const t in s)this._isPlainObject(s[t])?e[t]=this.cloneObject(s[t]):this._isArray(s[t])?e[t]=this.cloneArray(s[t]):e[t]=s[t];return e},cloneArray(s){return s.slice(0)},degToRad(s){return s*ao},radToDeg(s){return s*oo},_degToRad(s){return b.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),b.degToRad(s)},_radToDeg(s){return b.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),b.radToDeg(s)},_getRotation(s){return D.angleDeg?b.radToDeg(s):s},_capitalize(s){return s.charAt(0).toUpperCase()+s.slice(1)},throw(s){throw new Error(pn+s)},error(s){console.error(pn+s)},warn(s){D.showWarnings&&console.warn(ho+s)},each(s,e){for(const t in s)e(t,s[t])},_inRange(s,e,t){return e<=s&&s<t},_getProjectionToSegment(s,e,t,i,r,n){let a,o,l;const c=(s-t)*(s-t)+(e-i)*(e-i);if(c==0)a=s,o=e,l=(r-t)*(r-t)+(n-i)*(n-i);else{const h=((r-s)*(t-s)+(n-e)*(i-e))/c;h<0?(a=s,o=e,l=(s-r)*(s-r)+(e-n)*(e-n)):h>1?(a=t,o=i,l=(t-r)*(t-r)+(i-n)*(i-n)):(a=s+h*(t-s),o=e+h*(i-e),l=(a-r)*(a-r)+(o-n)*(o-n))}return[a,o,l]},_getProjectionToLine(s,e,t){const i=b.cloneObject(s);let r=Number.MAX_VALUE;return e.forEach(function(n,a){if(!t&&a===e.length-1)return;const o=e[(a+1)%e.length],l=b._getProjectionToSegment(n.x,n.y,o.x,o.y,s.x,s.y),c=l[0],h=l[1],d=l[2];d<r&&(i.x=c,i.y=h,r=d)}),i},_prepareArrayForTween(s,e,t){const i=[],r=[];if(s.length>e.length){const a=e;e=s,s=a}for(let a=0;a<s.length;a+=2)i.push({x:s[a],y:s[a+1]});for(let a=0;a<e.length;a+=2)r.push({x:e[a],y:e[a+1]});const n=[];return r.forEach(function(a){const o=b._getProjectionToLine(a,i,t);n.push(o.x),n.push(o.y)}),n},_prepareToStringify(s){let e;s.visitedByCircularReferenceRemoval=!0;for(const t in s)if(s.hasOwnProperty(t)&&s[t]&&typeof s[t]=="object"){if(e=Object.getOwnPropertyDescriptor(s,t),s[t].visitedByCircularReferenceRemoval||b._isElement(s[t]))if(e.configurable)delete s[t];else return null;else if(b._prepareToStringify(s[t])===null)if(e.configurable)delete s[t];else return null}return delete s.visitedByCircularReferenceRemoval,s},_assign(s,e){for(const t in e)s[t]=e[t];return s},_getFirstPointerId(s){return s.touches?s.changedTouches[0].identifier:s.pointerId||999},releaseCanvas(...s){D.releaseCanvasOnDestroy&&s.forEach(e=>{e.width=0,e.height=0})},drawRoundedRectPath(s,e,t,i){let r=e<0?e:0,n=t<0?t:0;e=Math.abs(e),t=Math.abs(t);let a=0,o=0,l=0,c=0;typeof i=="number"?a=o=l=c=Math.min(i,e/2,t/2):(a=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)),s.moveTo(r+a,n),s.lineTo(r+e-o,n),s.arc(r+e-o,n+o,o,Math.PI*3/2,0,!1),s.lineTo(r+e,n+t-c),s.arc(r+e-c,n+t-c,c,0,Math.PI/2,!1),s.lineTo(r+l,n+t),s.arc(r+l,n+t-l,l,Math.PI/2,Math.PI,!1),s.lineTo(r,n+a),s.arc(r+a,n+a,a,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(s,e,t,i,r){i=Math.abs(i);for(let n=0;n<t;n++){const a=e[(n-1+t)%t],o=e[n],l=e[(n+1)%t],c={x:o.x-a.x,y:o.y-a.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 f;typeof r=="number"?f=r:f=n<r.length?r[n]:0,f=i*Math.cos(Math.PI/t)*Math.min(1,f/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*f,y:o.y-y.y*f},v={x:o.x+S.x*f,y:o.y+S.y*f};n===0?s.moveTo(C.x,C.y):s.lineTo(C.x,C.y),s.arcTo(o.x,o.y,v.x,v.y,f)}}};function go(s){const e=[],t=s.length,i=b;for(let r=0;r<t;r++){let n=s[r];i._isNumber(n)?n=Math.round(n*1e3)/1e3:i._isString(n)||(n=n+""),e.push(n)}return e}const fn=",",mo="(",yo=")",So="([",vo="])",Co=";",bo="()",To="=",gn=["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"],wo=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],ko=100;let gi=null;function mn(){if(gi!==null)return gi;try{const e=b.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(gi=!1,!1)}catch{return gi=!1,!1}}class ji{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="",a,o,l,c;for(a=0;a<r;a++)o=i[a],l=o.method,l?(c=o.args,n+=l,e?n+=bo:b._isArray(c[0])?n+=So+c.join(fn)+vo:(t&&(c=c.map(h=>typeof h=="number"?Math.floor(h):h)),n+=mo+c.join(fn)+yo)):(n+=o.property,e||(n+=To+o.val)),n+=Co;return n}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=ko&&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,a){this._context.arc(e,t,i,r,n,a)}arcTo(e,t,i,r,n){this._context.arcTo(e,t,i,r,n)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,i,r,n,a){this._context.bezierCurveTo(e,t,i,r,n,a)}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,a){return this._context.createRadialGradient(e,t,i,r,n,a)}drawImage(e,t,i,r,n,a,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,a,o,l,c)}ellipse(e,t,i,r,n,a,o,l){this._context.ellipse(e,t,i,r,n,a,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,a){this._context.setTransform(e,t,i,r,n,a)}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,a){this._context.transform(e,t,i,r,n,a)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=gn.length,i=this.setAttr,r,n;const a=function(o){let l=e[o],c;e[o]=function(){return n=go(Array.prototype.slice.call(arguments,0)),c=l.apply(e,arguments),e._trace({method:o,args:n}),c}};for(r=0;r<t;r++)a(gn[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)}}wo.forEach(function(s){Object.defineProperty(ji.prototype,s,{get(){return this._context[s]},set(e){this._context[s]=e}})});class xo extends ji{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 a=e.getFillRadialGradientColorStops();if(a&&i==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):r?this._fillPattern(e):n?this._fillLinearGradient(e):a&&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 a=0;a<r.length;a+=2)n.addColorStop(r[a],r[a+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",a=(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",a*Math.min(Math.abs(h),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*h),this.setAttr("shadowOffsetY",o.y*d)}}class Po extends ji{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 _o(){if(mi)return mi;const s=b.createCanvasElement(),e=s.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(s),mi}class Zr{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||D.pixelRatio||_o();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 qe extends Zr{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new xo(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class Jr extends Zr{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 s=!1;return Z._dragElements.forEach(e=>{e.dragStatus==="dragging"&&(s=!0)}),s},justDragged:!1,get node(){let s;return Z._dragElements.forEach(e=>{s=e.node}),s},_dragElements:new Map,_drag(s){const e=[];Z._dragElements.forEach((t,i)=>{const{node:r}=t,n=r.getStage();n.setPointersPositions(s),t.pointerId===void 0&&(t.pointerId=b._getFirstPointerId(s));const a=n._changedPointerPositions.find(o=>o.id===t.pointerId);if(a){if(t.dragStatus!=="dragging"){const o=r.dragDistance();if(Math.max(Math.abs(a.x-t.startPointerPos.x),Math.abs(a.y-t.startPointerPos.y))<o||(r.startDrag({evt:s}),!r.isDragging()))return}r._setDragPosition(s,t),e.push(r)}}),e.forEach(t=>{t.fire("dragmove",{type:"dragmove",target:t,evt:s},!0)})},_endDragBefore(s){const e=[];Z._dragElements.forEach(t=>{const{node:i}=t,r=i.getStage();if(s&&r.setPointersPositions(s),!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 a=t.node.getLayer()||t.node instanceof D.Stage&&t.node;a&&e.indexOf(a)===-1&&e.push(a)}),e.forEach(t=>{t.draw()})},_endDragAfter(s){Z._dragElements.forEach((e,t)=>{e.dragStatus==="stopped"&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:s},!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 Je(s){return b._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||b._isBoolean(s)?s:Object.prototype.toString.call(s)}function Bs(s){return s>255?255:s<0?0:Math.round(s)}function R(){if(D.isUnminified)return function(s,e){return b._isNumber(s)||b.warn(Je(s)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),s}}function Ki(s){if(D.isUnminified)return function(e,t){let i=b._isNumber(e),r=b._isArray(e)&&e.length==s;return!i&&!r&&b.warn(Je(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+s+")"),e}}function Qr(){if(D.isUnminified)return function(s,e){return b._isNumber(s)||s==="auto"||b.warn(Je(s)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),s}}function dt(){if(D.isUnminified)return function(s,e){return b._isString(s)||b.warn(Je(s)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),s}}function Fs(){if(D.isUnminified)return function(s,e){const t=b._isString(s),i=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return t||i||b.warn(Je(s)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),s}}function Ao(){if(D.isUnminified)return function(s,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&s instanceof t||(b._isArray(s)?s.forEach(function(i){b._isNumber(i)||b.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):b.warn(Je(s)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),s}}function Ae(){if(D.isUnminified)return function(s,e){return s===!0||s===!1||b.warn(Je(s)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),s}}function Io(s){if(D.isUnminified)return function(e,t){return e==null||b.isObject(e)||b.warn(Je(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+s),e}}const Mt="get",Dt="set",m={addGetterSetter(s,e,t,i,r){m.addGetter(s,e,t),m.addSetter(s,e,i,r),m.addOverloadedGetterSetter(s,e)},addGetter(s,e,t){const i=Mt+b._capitalize(e);s.prototype[i]=s.prototype[i]||function(){const r=this.attrs[e];return r===void 0?t:r}},addSetter(s,e,t,i){const r=Dt+b._capitalize(e);s.prototype[r]||m.overWriteSetter(s,e,t,i)},overWriteSetter(s,e,t,i){const r=Dt+b._capitalize(e);s.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(s,e,t,i,r){const n=t.length,a=b._capitalize,o=Mt+a(e),l=Dt+a(e);s.prototype[o]=function(){const h={};for(let d=0;d<n;d++){const u=t[d];h[u]=this.getAttr(e+a(u))}return h};const c=Io(t);s.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+a(u),h[u]);return h||t.forEach(u=>{this._setAttr(e+a(u),void 0)}),this._fireChangeEvent(e,d,h),r&&r.call(this),this},m.addOverloadedGetterSetter(s,e)},addOverloadedGetterSetter(s,e){const t=b._capitalize(e),i=Dt+t,r=Mt+t;s.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[r]()}},addDeprecatedGetterSetter(s,e,t,i){b.error("Adding deprecated "+e);const r=Mt+b._capitalize(e),n=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[r]=function(){b.error(n);const a=this.attrs[e];return a===void 0?t:a},m.addSetter(s,e,i,function(){b.error(n)}),m.addOverloadedGetterSetter(s,e)},backCompat(s,e){b.each(e,function(t,i){const r=s.prototype[i],n=Mt+b._capitalize(t),a=Dt+b._capitalize(t);function o(){r.apply(this,arguments),b.error('"'+t+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}s.prototype[t]=o,s.prototype[n]=o,s.prototype[a]=o})},afterSetFilter(){this._filterUpToDate=!1}};function Eo(s){const e=/(\w+)\(([^)]+)\)/g;let t;for(;(t=e.exec(s))!==null;){const[,i,r]=t;switch(i){case"blur":{const n=parseFloat(r.replace("px",""));return function(a){this.blurRadius(n*.5);const o=D.Filters;o&&o.Blur&&o.Blur.call(this,a)}}case"brightness":{const n=r.includes("%")?parseFloat(r)/100:parseFloat(r);return function(a){this.brightness(n);const o=D.Filters;o&&o.Brightness&&o.Brightness.call(this,a)}}case"contrast":{const n=parseFloat(r);return function(a){const o=100*(Math.sqrt(n)-1);this.contrast(o);const l=D.Filters;l&&l.Contrast&&l.Contrast.call(this,a)}}case"grayscale":return function(n){const a=D.Filters;a&&a.Grayscale&&a.Grayscale.call(this,n)};case"sepia":return function(n){const a=D.Filters;a&&a.Sepia&&a.Sepia.call(this,n)};case"invert":return function(n){const a=D.Filters;a&&a.Invert&&a.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 Ei="absoluteOpacity",yn="allEventListeners",Oe="absoluteTransform",Sn="absoluteScale",it="canvas",Ro="Change",Mo="children",Do="konva",wr="listening",Lo="mouseenter",Oo="mouseleave",Bo="pointerenter",Fo="pointerleave",Go="touchenter",Ho="touchleave",vn="set",Cn="Shape",Ri=" ",bn="stage",We="transform",No="Stage",kr="visible",$o=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Ri);let zo=1;class E{constructor(e){this._id=zo++,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===We||e===Oe)&&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===We||e===Oe)&&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(Ri);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(it)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Oe&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(it)){const{scene:e,filter:t,hit:i}=this._cache.get(it);b.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(it)}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),a=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,f=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=c*2+u,n+=c*2+f,o-=c,l-=c;const g=new qe({pixelRatio:a,width:r,height:n}),y=new qe({pixelRatio:a,width:0,height:0,willReadFrequently:!0}),S=new Jr({pixelRatio:d,width:r,height:n}),C=g.getContext(),v=S.getContext(),T=new qe({width:g.width/g.pixelRatio+Math.abs(o),height:g.height/g.pixelRatio+Math.abs(l),pixelRatio:g.pixelRatio}),w=T.getContext();return S.isCache=!0,g.isCache=!0,this._cache.delete(it),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(g.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),C.save(),v.save(),w.save(),C.translate(-o,-l),v.translate(-o,-l),w.translate(-o,-l),T.x=o,T.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Ei),this._clearSelfAndDescendantCache(Sn),this.drawScene(g,this,T),this.drawHit(S,this),this._isUnderCache=!1,C.restore(),v.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(T._canvas),this._cache.set(it,{scene:g,filter:y,hit:S,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(it)}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,a=-1/0,o=-1/0;const l=this.getAbsoluteTransform(t);return i.forEach(function(c){const h=l.point(c);r===void 0&&(r=a=h.x,n=o=h.y),r=Math.min(r,h.x),n=Math.min(n,h.y),a=Math.max(a,h.x),o=Math.max(o,h.y)}),{x:r,y:n,width:a-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(),a,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"&&mn(),typeof e[u]!="string"||!mn()){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(a=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<a;l++)c=e[l],typeof c=="string"&&(c=Eo(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(yn),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Ri);for(let r=0;r<i.length;r++){const a=i[r].split("."),o=a[0],l=a[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:t})}return this}off(e,t){let i=(e||"").split(Ri),r=i.length,n,a,o,l,c,h;if(this._cache&&this._cache.delete(yn),!e)for(a in this.eventListeners)this._off(a);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(a in this.eventListeners)this._off(a,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 a=n.target.findAncestors(t,!0,r);for(let o=0;o<a.length;o++)n=b.cloneObject(n),n.currentTarget=a[o],i.call(a[o],n)})}remove(){return this.isDragging()&&this.stopDrag(),Z._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Oe),this._clearSelfAndDescendantCache(Ei),this._clearSelfAndDescendantCache(Sn),this._clearSelfAndDescendantCache(bn),this._clearSelfAndDescendantCache(kr),this._clearSelfAndDescendantCache(wr)}_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!==Mo&&(i=vn+b._capitalize(t),b._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(wr,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(kr,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(a=>{a.dragStatus==="dragging"&&(a.node.nodeType==="Stage"||a.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,a,o;function l(h){for(r=[],n=h.length,a=0;a<n;a++)o=h[a],i++,o.nodeType!==Cn&&(r=r.concat(o.getChildren().slice())),o._id===t._id&&(a=n);r.length>0&&r[0].getDepth()<=e&&l(r)}const c=this.getStage();return t.nodeType!==No&&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(We),this._clearSelfAndDescendantCache(Oe)),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 ye,a=this.offset();return n.m=r.slice(),n.translate(a.x,a.y),n.getTranslation()}setAbsolutePosition(e){const{x:t,y:i,...r}=this._clearTransform();this.attrs.x=t,this.attrs.y=i,this._clearCache(We);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(We),this._clearSelfAndDescendantCache(Oe),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,a;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,a=0;a<n;a++)e(i[a])}}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(Ei,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,a;const o={attrs:{},className:this.getClassName()};for(t in e)i=e[t],a=b.isObject(i)&&!b._isPlainObject(i)&&!b._isArray(i),!a&&(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(bn,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(Oe,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new ye,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(Oe)||new ye,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,a=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(r-a,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(We,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get(We)||new ye;i.reset();const r=this.x(),n=this.y(),a=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),a!==0&&i.rotate(a),(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,a,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,a=0;a<n;a++)o=r[a],o.name.indexOf(Do)<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),a=e.pixelRatio||1,o=new qe({width:e.width||Math.ceil(t.width)||(i?i.width():0),height:e.height||Math.ceil(t.height)||(i?i.height():0),pixelRatio:a}),l=o.getContext(),c=new qe({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,a,o;for(n=0;n<r.length;n++)if(a=r[n].name,o=r[n].handler,(a!=="konva"||t==="konva")&&(!t||a===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+Ro,{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[vn+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===Cn&&(t.target=this);const r=[Lo,Oo,Bo,Fo,Go,Ho];if(!(r.indexOf(e)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(e,t);const a=r.indexOf(e)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!a&&(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=E.protoListenerMap.get(r)||{};let a=n==null?void 0:n[e];if(a===void 0){a=[];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:[];a.push(...l),o=Object.getPrototypeOf(o)}n[e]=a,E.protoListenerMap.set(r,n)}return a}_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 a=n.call(this,r,e);a?r=a: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=E.prototype.getClassName.call(e),r=e.children,n,a,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(a=r.length,o=0;o<a;o++)n.add(E._createNode(r[o]));return n}}E.protoListenerMap=new Map;E.prototype.nodeType="Node";E.prototype._attrsAffectingSize=[];E.prototype.eventListeners={};E.prototype.on.call(E.prototype,$o,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(We),this._clearSelfAndDescendantCache(Oe)});E.prototype.on.call(E.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(kr)});E.prototype.on.call(E.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(wr)});E.prototype.on.call(E.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Ei)});const ee=m.addGetterSetter;ee(E,"zIndex");ee(E,"absolutePosition");ee(E,"position");ee(E,"x",0,R());ee(E,"y",0,R());ee(E,"globalCompositeOperation","source-over",dt());ee(E,"opacity",1,R());ee(E,"name","",dt());ee(E,"id","",dt());ee(E,"rotation",0,R());m.addComponentsGetterSetter(E,"scale",["x","y"]);ee(E,"scaleX",1,R());ee(E,"scaleY",1,R());m.addComponentsGetterSetter(E,"skew",["x","y"]);ee(E,"skewX",0,R());ee(E,"skewY",0,R());m.addComponentsGetterSetter(E,"offset",["x","y"]);ee(E,"offsetX",0,R());ee(E,"offsetY",0,R());ee(E,"dragDistance",void 0,R());ee(E,"width",0,R());ee(E,"height",0,R());ee(E,"listening",!0,Ae());ee(E,"preventDefault",!0,Ae());ee(E,"filters",void 0,function(s){return this._filterUpToDate=!1,s});ee(E,"visible",!0,Ae());ee(E,"transformsEnabled","all",dt());ee(E,"size");ee(E,"dragBoundFunc");ee(E,"draggable",!1,Ae());m.backCompat(E,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class Se extends E{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=E.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=E.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(),a=n&&n.getContext(),o=this._getCanvasCache(),l=o&&o.scene,c=n&&n.isCache;if(!this.isVisible()&&!c)return this;if(l){a.save();const h=this.getAbsoluteTransform(t).getMatrix();a.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(a),a.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(),a=this._getCanvasCache();if(a&&a.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 a=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){a.save();const f=this.getAbsoluteTransform(i);let g=f.getMatrix();a.transform(g[0],g[1],g[2],g[3],g[4],g[5]),a.beginPath();let y;if(c)y=c.call(this,a,this);else{const S=this.clipX(),C=this.clipY();a.rect(S||0,C||0,o,l)}a.clip.apply(a,y),g=f.copy().invert().getMatrix(),a.transform(g[0],g[1],g[2],g[3],g[4],g[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";u&&(a.save(),a._applyGlobalCompositeOperation(this)),(n=this.children)===null||n===void 0||n.forEach(function(f){f[e](t,i,r)}),u&&a.restore(),h&&a.restore()}getClientRect(e={}){var t;const i=e.skipTransform,r=e.relativeTo;let n,a,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(f){if(!f.visible())return;const g=f.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});g.width===0&&g.height===0||(n===void 0?(n=g.x,a=g.y,o=g.x+g.width,l=g.y+g.height):(n=Math.min(n,g.x),a=Math.min(a,g.y),o=Math.max(o,g.x+g.width),l=Math.max(l,g.y+g.height)))});const d=this.find("Shape");let u=!1;for(let f=0;f<d.length;f++)if(d[f]._isVisible(this)){u=!0;break}return u&&n!==void 0?c={x:n,y:a,width:o-n,height:l-a}:c={x:0,y:0,width:0,height:0},i?c:this._transformedRect(c,r)}}m.addComponentsGetterSetter(Se,"clip",["x","y","width","height"]);m.addGetterSetter(Se,"clipX",void 0,R());m.addGetterSetter(Se,"clipY",void 0,R());m.addGetterSetter(Se,"clipWidth",void 0,R());m.addGetterSetter(Se,"clipHeight",void 0,R());m.addGetterSetter(Se,"clipFunc");const ii=new Map,Gs=D._global.PointerEvent!==void 0;function rr(s){return ii.get(s)}function en(s){return{evt:s,pointerId:s.pointerId}}function Hs(s,e){return ii.get(s)===e}function Ns(s,e){Xt(s),e.getStage()&&(ii.set(s,e),Gs&&e._fire("gotpointercapture",en(new PointerEvent("gotpointercapture"))))}function Xt(s,e){const t=ii.get(s);if(!t)return;const i=t.getStage();i&&i.content,ii.delete(s),Gs&&t._fire("lostpointercapture",en(new PointerEvent("lostpointercapture")))}const Vo="Stage",Uo="string",Tn="px",Wo="mouseout",$s="mouseleave",zs="mouseover",Vs="mouseenter",Us="mousemove",Ws="mousedown",Ys="mouseup",$t="pointermove",zt="pointerdown",Tt="pointerup",Vt="pointercancel",Yo="lostpointercapture",yi="pointerout",Ut="pointerleave",Si="pointerover",vi="pointerenter",xr="contextmenu",Xs="touchstart",qs="touchend",js="touchmove",Ks="touchcancel",Pr="wheel",Xo=5,qo=[[Vs,"_pointerenter"],[Ws,"_pointerdown"],[Us,"_pointermove"],[Ys,"_pointerup"],[$s,"_pointerleave"],[Xs,"_pointerdown"],[js,"_pointermove"],[qs,"_pointerup"],[Ks,"_pointercancel"],[zs,"_pointerover"],[Pr,"_wheel"],[xr,"_contextmenu"],[zt,"_pointerdown"],[$t,"_pointermove"],[Tt,"_pointerup"],[Vt,"_pointercancel"],[Ut,"_pointerleave"],[Yo,"_lostpointercapture"]],nr={mouse:{[yi]:Wo,[Ut]:$s,[Si]:zs,[vi]:Vs,[$t]:Us,[zt]:Ws,[Tt]:Ys,[Vt]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[yi]:"touchout",[Ut]:"touchleave",[Si]:"touchover",[vi]:"touchenter",[$t]:js,[zt]:Xs,[Tt]:qs,[Vt]:Ks,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[yi]:yi,[Ut]:Ut,[Si]:Si,[vi]:vi,[$t]:$t,[zt]:zt,[Tt]:Tt,[Vt]:Vt,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Wt=s=>s.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",mt=s=>{const e=Wt(s);if(e==="pointer")return D.pointerEventsEnabled&&nr.pointer;if(e==="touch")return nr.touch;if(e==="mouse")return nr.mouse};function wn(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&b.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const jo="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);",qt=[];class Zi extends Se{constructor(e){super(wn(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),qt.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{wn(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===Uo){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"),Se.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&b._isInDocument(e)&&this.container().removeChild(e);const t=qt.indexOf(this);return t>-1&&qt.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(jo),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 qe({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 a=n._toKonvaCanvas(e);i.drawImage(a._canvas,e.x,e.y,a.getWidth()/a.getPixelRatio(),a.getHeight()/a.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 a=t[n].getIntersection(e);if(a)return a}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+Tn,this.content.style.height=t+Tn),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>Xo&&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 Hs(e,this)}setPointerCapture(e){Ns(e,this)}releaseCapture(e){Xt(e)}getLayers(){return this.children}_bindContentEvents(){D.isBrowser&&qo.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=mt(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=mt(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=mt(e.type),i=Wt(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=mt(e.type),i=Wt(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(n=>{const a=this.getIntersection(n);if(Z.justDragged=!1,D["_"+i+"ListenClick"]=!0,!a||!a.isListening()){this[i+"ClickStartShape"]=void 0;return}D.capturePointerEventsEnabled&&a.setPointerCapture(n.id),this[i+"ClickStartShape"]=a,a._fireAndBubble(t.pointerdown,{evt:e,pointerId:n.id}),r=!0;const o=e.type.indexOf("touch")>=0;a.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=mt(e.type),i=Wt(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 a={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(c=>{const h=rr(c.id)||this.getIntersection(c),d=c.id,u={evt:e,pointerId:d},f=l!==h;if(f&&l&&(l._fireAndBubble(t.pointerout,{...u},h),l._fireAndBubble(t.pointerleave,{...u},h)),h){if(a[h._id])return;a[h._id]=!0}h&&h.isListening()?(o=!0,f&&(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=mt(e.type),i=Wt(e.type);if(!t)return;this.setPointersPositions(e);const r=this[i+"ClickStartShape"],n=this[i+"ClickEndShape"],a={};let o=!1;this._changedPointerPositions.forEach(l=>{const c=rr(l.id)||this.getIntersection(l);if(c){if(c.releaseCapture(l.id),a[c._id])return;a[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(xr,{evt:e}):this._fire(xr,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Pr,{evt:e}):this._fire(Pr,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=rr(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(Tt,en(e)),Xt(e.pointerId)}_lostpointercapture(e){Xt(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 qe({width:this.width(),height:this.height()}),this.bufferHitCanvas=new Jr({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}}Zi.prototype.nodeType=Vo;se(Zi);m.addGetterSetter(Zi,"container");D.isBrowser&&document.addEventListener("visibilitychange",()=>{qt.forEach(s=>{s.batchDraw()})});const Zs="hasShadow",Js="shadowRGBA",Qs="patternImage",ea="linearGradient",ta="radialGradient";let Ci;function sr(){return Ci||(Ci=b.createCanvasElement().getContext("2d"),Ci)}const jt={};function Ko(s){const e=this.attrs.fillRule;e?s.fill(e):s.fill()}function Zo(s){s.stroke()}function Jo(s){const e=this.attrs.fillRule;e?s.fill(e):s.fill()}function Qo(s){s.stroke()}function el(){this._clearCache(Zs)}function tl(){this._clearCache(Js)}function il(){this._clearCache(Qs)}function rl(){this._clearCache(ea)}function nl(){this._clearCache(ta)}class A extends E{constructor(e){super(e);let t,i=0;for(;t=b.getHitColor(),!(t&&!(t in jt));)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,jt[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(Zs,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(Qs,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=sr().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new ye;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(ea,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=sr(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),n=t.createLinearGradient(i.x,i.y,r.x,r.y);for(let a=0;a<e.length;a+=2)n.addColorStop(e[a],e[a+1]);return n}}_getRadialGradient(){return this._getCache(ta,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=sr(),i=this.fillRadialGradientStartPoint(),r=this.fillRadialGradientEndPoint(),n=t.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),r.x,r.y,this.fillRadialGradientEndRadius());for(let a=0;a<e.length;a+=2)n.addColorStop(e[a],e[a+1]);return n}}getShadowRGBA(){return this._getCache(Js,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 E.prototype.destroy.call(this),delete jt[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(),a=this.getAbsoluteOpacity()!==1;if(r&&n&&a)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,a=this.getSelfRect(),l=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,c=a.width+l,h=a.height+l,d=!e.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,f=d?this.shadowOffsetY():0,g=c+Math.abs(u),y=h+Math.abs(f),S=d&&this.shadowBlur()||0,C=g+S*2,v=y+S*2,T={width:C,height:v,x:-(l/2+S)+Math.min(u,0)+a.x,y:-(l/2+S)+Math.min(f,0)+a.y};return r?T:this._transformedRect(T,n)}drawScene(e,t,i){const r=this.getLayer(),n=e||r.getCanvas(),a=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){a.save();const u=this.getAbsoluteTransform(t).getMatrix();return a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(a),a.restore(),this}if(!l)return this;if(a.save(),this._useBufferCanvas()){h=this.getStage();const u=i||h.bufferCanvas,f=u.getContext();i?(f.save(),f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,u.width,u.height),f.restore()):f.clear(),f.save(),f._applyLineJoin(this),f._applyMiterLimit(this);const g=this.getAbsoluteTransform(t).getMatrix();f.transform(g[0],g[1],g[2],g[3],g[4],g[5]),l.call(this,f,this),f.restore();const y=u.pixelRatio;c&&a._applyShadow(this),d||(a._applyOpacity(this),a._applyGlobalCompositeOperation(this)),a.drawImage(u._canvas,u.x||0,u.y||0,u.width/y,u.height/y)}else{if(a._applyLineJoin(this),a._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(t).getMatrix();a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),a._applyOpacity(this),a._applyGlobalCompositeOperation(this)}c&&a._applyShadow(this),l.call(this,a,this)}return a.restore(),this}drawHit(e,t,i=!1){if(!this.shouldDrawHit(t,i))return this;const r=this.getLayer(),n=e||r.hitCanvas,a=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){a.save();const d=this.getAbsoluteTransform(t).getMatrix();return a.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(a),a.restore(),this}if(!o)return this;if(a.save(),a._applyLineJoin(this),a._applyMiterLimit(this),!(this===t)){const d=this.getAbsoluteTransform(t).getMatrix();a.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,a,this),a.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),i=this._getCachedSceneCanvas(),r=t.hit,n=r.getContext(),a=r.getWidth(),o=r.getHeight();n.clear(),n.drawImage(i._canvas,0,0,a,o);try{const l=n.getImageData(0,0,a,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 Hs(e,this)}setPointerCapture(e){Ns(e,this)}releaseCapture(e){Xt(e)}}A.prototype._fillFunc=Ko;A.prototype._strokeFunc=Zo;A.prototype._fillFuncHit=Jo;A.prototype._strokeFuncHit=Qo;A.prototype._centroid=!1;A.prototype.nodeType="Shape";se(A);A.prototype.eventListeners={};A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",el);A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",tl);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",il);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",rl);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",nl);m.addGetterSetter(A,"stroke",void 0,Fs());m.addGetterSetter(A,"strokeWidth",2,R());m.addGetterSetter(A,"fillAfterStrokeEnabled",!1);m.addGetterSetter(A,"hitStrokeWidth","auto",Qr());m.addGetterSetter(A,"strokeHitEnabled",!0,Ae());m.addGetterSetter(A,"perfectDrawEnabled",!0,Ae());m.addGetterSetter(A,"shadowForStrokeEnabled",!0,Ae());m.addGetterSetter(A,"lineJoin");m.addGetterSetter(A,"lineCap");m.addGetterSetter(A,"miterLimit");m.addGetterSetter(A,"sceneFunc");m.addGetterSetter(A,"hitFunc");m.addGetterSetter(A,"dash");m.addGetterSetter(A,"dashOffset",0,R());m.addGetterSetter(A,"shadowColor",void 0,dt());m.addGetterSetter(A,"shadowBlur",0,R());m.addGetterSetter(A,"shadowOpacity",1,R());m.addComponentsGetterSetter(A,"shadowOffset",["x","y"]);m.addGetterSetter(A,"shadowOffsetX",0,R());m.addGetterSetter(A,"shadowOffsetY",0,R());m.addGetterSetter(A,"fillPatternImage");m.addGetterSetter(A,"fill",void 0,Fs());m.addGetterSetter(A,"fillPatternX",0,R());m.addGetterSetter(A,"fillPatternY",0,R());m.addGetterSetter(A,"fillLinearGradientColorStops");m.addGetterSetter(A,"strokeLinearGradientColorStops");m.addGetterSetter(A,"fillRadialGradientStartRadius",0);m.addGetterSetter(A,"fillRadialGradientEndRadius",0);m.addGetterSetter(A,"fillRadialGradientColorStops");m.addGetterSetter(A,"fillPatternRepeat","repeat");m.addGetterSetter(A,"fillEnabled",!0);m.addGetterSetter(A,"strokeEnabled",!0);m.addGetterSetter(A,"shadowEnabled",!0);m.addGetterSetter(A,"dashEnabled",!0);m.addGetterSetter(A,"strokeScaleEnabled",!0);m.addGetterSetter(A,"fillPriority","color");m.addComponentsGetterSetter(A,"fillPatternOffset",["x","y"]);m.addGetterSetter(A,"fillPatternOffsetX",0,R());m.addGetterSetter(A,"fillPatternOffsetY",0,R());m.addComponentsGetterSetter(A,"fillPatternScale",["x","y"]);m.addGetterSetter(A,"fillPatternScaleX",1,R());m.addGetterSetter(A,"fillPatternScaleY",1,R());m.addComponentsGetterSetter(A,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(A,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(A,"fillLinearGradientStartPointX",0);m.addGetterSetter(A,"strokeLinearGradientStartPointX",0);m.addGetterSetter(A,"fillLinearGradientStartPointY",0);m.addGetterSetter(A,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(A,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(A,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(A,"fillLinearGradientEndPointX",0);m.addGetterSetter(A,"strokeLinearGradientEndPointX",0);m.addGetterSetter(A,"fillLinearGradientEndPointY",0);m.addGetterSetter(A,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(A,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(A,"fillRadialGradientStartPointX",0);m.addGetterSetter(A,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(A,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(A,"fillRadialGradientEndPointX",0);m.addGetterSetter(A,"fillRadialGradientEndPointY",0);m.addGetterSetter(A,"fillPatternRotation",0);m.addGetterSetter(A,"fillRule",void 0,dt());m.backCompat(A,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const sl="beforeDraw",al="draw",ia=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],ol=ia.length;class ut extends Se{constructor(e){super(e),this.canvas=new qe,this.hitCanvas=new Jr({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(){E.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(!E.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(E.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(E.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 E.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(),E.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<ol;r++){const n=ia[r],a=this._getIntersection({x:e.x+n.x*t,y:e.y+n.y*t}),o=a.shape;if(o)return o;if(i=!!a.antialiased,!a.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]),a=jt[n];return a?{shape:a}:{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(sl,{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),Se.prototype.drawScene.call(this,n,t,i),this._fire(al,{node:this}),this}drawHit(e,t){const i=this.getLayer(),r=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),Se.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()}}ut.prototype.nodeType="Layer";se(ut);m.addGetterSetter(ut,"imageSmoothingEnabled",!0);m.addGetterSetter(ut,"clearBeforeDraw",!0);m.addGetterSetter(ut,"hitGraphEnabled",!0,Ae());class tn extends ut{constructor(e){super(e),this.listening(!1),b.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}tn.prototype.nodeType="FastLayer";se(tn);class xt extends Se{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to groups.")}}xt.prototype.nodeType="Group";se(xt);const ar=function(){return at.performance&&at.performance.now?function(){return at.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:ar(),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=ar(),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,a=r.func;r._updateFrameObject(ar());const o=n.length;let l;if(a?l=a.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 ll={node:1,duration:1,easing:1,onFinish:1,yoyo:1},cl=1,kn=2,xn=3,Pn=["fill","stroke","shadowColor"];let hl=0;class dl{constructor(e,t,i,r,n,a,o){this.prop=e,this.propFunc=t,this.begin=r,this._pos=r,this.duration=a,this._change=0,this.prevPos=0,this.yoyo=o,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=i,this._change=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=kn,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=xn,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===kn?this.setTime(e):this.state===xn&&this.setTime(this.duration-e)}pause(){this.state=cl,this.fire("onPause")}getTimer(){return new Date().getTime()}}class te{constructor(e){const t=this,i=e.node,r=i._id,n=e.easing||Kt.Linear,a=!!e.yoyo;let o,l;typeof e.duration>"u"?o=.3:e.duration===0?o=.001:o=e.duration,this.node=i,this._id=hl++;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 dl(l,function(h){t._tweenFunc(h)},n,0,1,o*1e3,a),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)ll[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,a,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=[],a=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<a;u++)if(u%2===0)n.push(t[u]-d[u]);else{const f=b.colorToRGBA(d[u]);c=b.colorToRGBA(t[u]),d[u]=f,n.push({r:c.r-f.r,g:c.g-f.g,b:c.b-f.b,a:c.a-f.a})}else for(let u=0;u<a;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,a,o,l,c,h,d;for(r in i){if(n=i[r],a=n.start,o=n.diff,d=n.end,b._isArray(a))if(l=[],h=Math.max(a.length,d.length),r.indexOf("fill")===0)for(c=0;c<h;c++)c%2===0?l.push((a[c]||0)+o[c]*e):l.push("rgba("+Math.round(a[c].r+o[c].r*e)+","+Math.round(a[c].g+o[c].g*e)+","+Math.round(a[c].b+o[c].b*e)+","+(a[c].a+o[c].a*e)+")");else for(c=0;c<h;c++)l.push((a[c]||0)+o[c]*e);else Pn.indexOf(r)!==-1?l="rgba("+Math.round(a.r+o.r*e)+","+Math.round(a.g+o.g*e)+","+Math.round(a.b+o.b*e)+","+(a.a+o.a*e)+")":l=a+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={};E.prototype.to=function(s){const e=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),e&&e()},new te(s).play()};const Kt={BackEaseIn(s,e,t,i){return t*(s/=i)*s*((1.70158+1)*s-1.70158)+e},BackEaseOut(s,e,t,i){return t*((s=s/i-1)*s*((1.70158+1)*s+1.70158)+1)+e},BackEaseInOut(s,e,t,i){let r=1.70158;return(s/=i/2)<1?t/2*(s*s*(((r*=1.525)+1)*s-r))+e:t/2*((s-=2)*s*(((r*=1.525)+1)*s+r)+2)+e},ElasticEaseIn(s,e,t,i,r,n){let a=0;return s===0?e:(s/=i)===1?e+t:(n||(n=i*.3),!r||r<Math.abs(t)?(r=t,a=n/4):a=n/(2*Math.PI)*Math.asin(t/r),-(r*Math.pow(2,10*(s-=1))*Math.sin((s*i-a)*(2*Math.PI)/n))+e)},ElasticEaseOut(s,e,t,i,r,n){let a=0;return s===0?e:(s/=i)===1?e+t:(n||(n=i*.3),!r||r<Math.abs(t)?(r=t,a=n/4):a=n/(2*Math.PI)*Math.asin(t/r),r*Math.pow(2,-10*s)*Math.sin((s*i-a)*(2*Math.PI)/n)+t+e)},ElasticEaseInOut(s,e,t,i,r,n){let a=0;return s===0?e:(s/=i/2)===2?e+t:(n||(n=i*(.3*1.5)),!r||r<Math.abs(t)?(r=t,a=n/4):a=n/(2*Math.PI)*Math.asin(t/r),s<1?-.5*(r*Math.pow(2,10*(s-=1))*Math.sin((s*i-a)*(2*Math.PI)/n))+e:r*Math.pow(2,-10*(s-=1))*Math.sin((s*i-a)*(2*Math.PI)/n)*.5+t+e)},BounceEaseOut(s,e,t,i){return(s/=i)<1/2.75?t*(7.5625*s*s)+e:s<2/2.75?t*(7.5625*(s-=1.5/2.75)*s+.75)+e:s<2.5/2.75?t*(7.5625*(s-=2.25/2.75)*s+.9375)+e:t*(7.5625*(s-=2.625/2.75)*s+.984375)+e},BounceEaseIn(s,e,t,i){return t-Kt.BounceEaseOut(i-s,0,t,i)+e},BounceEaseInOut(s,e,t,i){return s<i/2?Kt.BounceEaseIn(s*2,0,t,i)*.5+e:Kt.BounceEaseOut(s*2-i,0,t,i)*.5+t*.5+e},EaseIn(s,e,t,i){return t*(s/=i)*s+e},EaseOut(s,e,t,i){return-t*(s/=i)*(s-2)+e},EaseInOut(s,e,t,i){return(s/=i/2)<1?t/2*s*s+e:-t/2*(--s*(s-2)-1)+e},StrongEaseIn(s,e,t,i){return t*(s/=i)*s*s*s*s+e},StrongEaseOut(s,e,t,i){return t*((s=s/i-1)*s*s*s*s+1)+e},StrongEaseInOut(s,e,t,i){return(s/=i/2)<1?t/2*s*s*s*s*s+e:t/2*((s-=2)*s*s*s*s+2)+e},Linear(s,e,t,i){return t*s/i+e}},_n=b._assign(D,{Util:b,Transform:ye,Node:E,Container:Se,Stage:Zi,stages:qt,Layer:ut,FastLayer:tn,Group:xt,DD:Z,Shape:A,shapes:jt,Animation:we,Tween:te,Easings:Kt,Context:ji,Canvas:Zr});class Fe extends A{_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)),a=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=a*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}}}Fe.prototype._centroid=!0;Fe.prototype.className="Arc";Fe.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];se(Fe);m.addGetterSetter(Fe,"innerRadius",0,R());m.addGetterSetter(Fe,"outerRadius",0,R());m.addGetterSetter(Fe,"angle",0,R());m.addGetterSetter(Fe,"clockwise",!1,Ae());function _r(s,e,t,i,r,n,a){const o=Math.sqrt(Math.pow(t-s,2)+Math.pow(i-e,2)),l=Math.sqrt(Math.pow(r-t,2)+Math.pow(n-i,2)),c=a*o/(o+l),h=a*l/(o+l),d=t-c*(r-s),u=i-c*(n-e),f=t+h*(r-s),g=i+h*(n-e);return[d,u,f,g]}function An(s,e){const t=s.length,i=[];for(let r=2;r<t-2;r+=2){const n=_r(s[r-2],s[r-1],s[r],s[r+1],s[r+2],s[r+3],e);isNaN(n[0])||(i.push(n[0]),i.push(n[1]),i.push(s[r]),i.push(s[r+1]),i.push(n[2]),i.push(n[3]))}return i}function ul(s){const e=[[s[0],s[2],s[4],s[6]],[s[1],s[3],s[5],s[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],a=-3*i[0]+3*i[1],o=n*n-4*r*a;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 Ge extends A{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(),a=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(a)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():An(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=_r(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),n=_r(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),a=An(e,i);return[r[2],r[3]].concat(a).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],...ul(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],a,o;for(let l=0;l<e.length/2;l++)a=e[l*2],o=e[l*2+1],t=Math.min(t,a),i=Math.max(i,a),r=Math.min(r,o),n=Math.max(n,o);return{x:t,y:r,width:i-t,height:n-r}}}Ge.prototype.className="Line";Ge.prototype._attrsAffectingSize=["points","bezier","tension"];se(Ge);m.addGetterSetter(Ge,"closed",!1);m.addGetterSetter(Ge,"bezier",!1);m.addGetterSetter(Ge,"tension",0,R());m.addGetterSetter(Ge,"points",[],Ao());const pl=[[],[],[-.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]],fl=[[],[],[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]],gl=[[1],[1,1],[1,2,1],[1,3,3,1]],In=(s,e,t)=>{let i,r;const a=t/2;i=0;for(let o=0;o<20;o++)r=a*pl[20][o]+a,i+=fl[20][o]*ml(s,e,r);return a*i},En=(s,e,t)=>{t===void 0&&(t=1);const i=s[0]-2*s[1]+s[2],r=e[0]-2*e[1]+e[2],n=2*s[1]-2*s[0],a=2*e[1]-2*e[0],o=4*(i*i+r*r),l=4*(i*n+r*a),c=n*n+a*a;if(o===0)return t*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(e[2]-e[0],2));const h=l/(2*o),d=c/o,u=t+h,f=d-h*h,g=u*u+f>0?Math.sqrt(u*u+f):0,y=h*h+f>0?Math.sqrt(h*h+f):0,S=h+Math.sqrt(h*h+f)!==0?f*Math.log(Math.abs((u+g)/(h+y))):0;return Math.sqrt(o)/2*(u*g-h*y+S)};function ml(s,e,t){const i=Ar(1,t,s),r=Ar(1,t,e),n=i*i+r*r;return Math.sqrt(n)}const Ar=(s,e,t)=>{const i=t.length-1;let r,n;if(i===0)return 0;if(s===0){n=0;for(let a=0;a<=i;a++)n+=gl[i][a]*Math.pow(1-e,i-a)*Math.pow(e,a)*t[a];return n}else{r=new Array(i);for(let a=0;a<i;a++)r[a]=i*(t[a+1]-t[a]);return Ar(s-1,e,r)}},Rn=(s,e,t)=>{let i=1,r=s/e,n=(s-t(r))/e,a=0;for(;i>.001;){const o=t(r+n),l=Math.abs(s-o)/e;if(l<i)i=l,r+=n;else{const c=t(r-n),h=Math.abs(s-c)/e;h<i?(i=h,r-=n):n/=2}if(a++,a>500)break}return r};class ie extends A{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,a=t[r].points;switch(n){case"L":e.lineTo(a[0],a[1]);break;case"M":e.moveTo(a[0],a[1]);break;case"C":e.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5]);break;case"Q":e.quadraticCurveTo(a[0],a[1],a[2],a[3]);break;case"A":const o=a[0],l=a[1],c=a[2],h=a[3],d=a[4],u=a[5],f=a[6],g=a[7],y=c>h?c:h,S=c>h?1:c/h,C=c>h?h/c:1;e.translate(o,l),e.rotate(f),e.scale(S,C),e.arc(0,0,y,d,d+u,1-g),e.scale(1/S,1/C),e.rotate(-f),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const 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 f=c-u;f>d;f-=u){const g=ie.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],f,0);e.push(g.x,g.y)}else for(let f=c+u;f<d;f+=u){const g=ie.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],f,0);e.push(g.x,g.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],a,o;for(let l=0;l<e.length/2;l++)a=e[l*2],o=e[l*2+1],isNaN(a)||(t=Math.min(t,a),i=Math.max(i,a)),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 a=t[r],o=a.points;switch(a.command){case"L":return ie.getPointOnLine(e,a.start.x,a.start.y,o[0],o[1]);case"C":return ie.getPointOnCubicBezier(Rn(e,ie.getPathLength(t),y=>In([a.start.x,o[0],o[2],o[4]],[a.start.y,o[1],o[3],o[5]],y)),a.start.x,a.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return ie.getPointOnQuadraticBezier(Rn(e,ie.getPathLength(t),y=>En([a.start.x,o[0],o[2]],[a.start.y,o[1],o[3]],y)),a.start.x,a.start.y,o[0],o[1],o[2],o[3]);case"A":const l=o[0],c=o[1],h=o[2],d=o[3],u=o[5],f=o[6];let g=o[4];return g+=u*e/a.pathLength,ie.getPointOnEllipticalArc(l,c,h,d,g,f)}return null}static getPointOnLine(e,t,i,r,n,a,o){a=a??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:a,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*(a-t))<1e-10)return{x:a+h,y:o+d};const u=((a-t)*(r-t)+(o-i)*(n-i))/(l*l),f=t+u*(r-t),g=i+u*(n-i),y=this.getLineLength(a,o,f,g),S=Math.sqrt(e*e-y*y),C=Math.sqrt(S*S/(1+c*c))*(r<t?-1:1),v=c*C;return{x:f+C,y:g+v}}static getPointOnCubicBezier(e,t,i,r,n,a,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 f(S){return(1-S)*(1-S)*(1-S)}const g=l*h(e)+a*d(e)+r*u(e)+t*f(e),y=c*h(e)+o*d(e)+n*u(e)+i*f(e);return{x:g,y}}static getPointOnQuadraticBezier(e,t,i,r,n,a,o){function l(f){return f*f}function c(f){return 2*f*(1-f)}function h(f){return(1-f)*(1-f)}const d=a*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,a){const o=Math.cos(a),l=Math.sin(a),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=[],a=[];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],f=u.charAt(0);for(u=u.slice(1),a.length=0;h=c.exec(u);)a.push(h[0]);let g=[],y=f==="A"||f==="a"?0:-1;for(let S=0,C=a.length;S<C;S++){const v=a[S];if(v==="00"){g.push(0,0),y>=0&&(y+=2,y>=7&&(y-=7));continue}if(y>=0){if(y===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(v)){g.push(parseInt(v[0],10)),g.push(parseInt(v[1],10)),g.push(parseFloat(v.slice(2))),y+=3,y>=7&&(y-=7);continue}if(v==="11"||v==="10"||v==="01"){g.push(parseInt(v[0],10)),g.push(parseInt(v[1],10)),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){g.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(v)){g.push(parseInt(v[0],10)),g.push(parseFloat(v.slice(1))),y+=2,y>=7&&(y-=7);continue}if(v==="0"||v==="1"){g.push(parseInt(v,10)),y+=1,y>=7&&(y-=7);continue}}const T=parseFloat(v);isNaN(T)?g.push(0):g.push(T),y+=1,y>=7&&(y-=7)}else{const T=parseFloat(v);isNaN(T)?g.push(0):g.push(T)}}for(;g.length>0&&!isNaN(g[0]);){let S="",C=[];const v=o,T=l;let w,_,x,L,k,M,P,$,G,U;switch(f){case"l":o+=g.shift(),l+=g.shift(),S="L",C.push(o,l);break;case"L":o=g.shift(),l=g.shift(),C.push(o,l);break;case"m":const z=g.shift(),B=g.shift();if(o+=z,l+=B,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]+z,l=n[O].points[1]+B;break}}C.push(o,l),f="l";break;case"M":o=g.shift(),l=g.shift(),S="M",C.push(o,l),f="L";break;case"h":o+=g.shift(),S="L",C.push(o,l);break;case"H":o=g.shift(),S="L",C.push(o,l);break;case"v":l+=g.shift(),S="L",C.push(o,l);break;case"V":l=g.shift(),S="L",C.push(o,l);break;case"C":C.push(g.shift(),g.shift(),g.shift(),g.shift()),o=g.shift(),l=g.shift(),C.push(o,l);break;case"c":C.push(o+g.shift(),l+g.shift(),o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),S="C",C.push(o,l);break;case"S":_=o,x=l,w=n[n.length-1],w.command==="C"&&(_=o+(o-w.points[2]),x=l+(l-w.points[3])),C.push(_,x,g.shift(),g.shift()),o=g.shift(),l=g.shift(),S="C",C.push(o,l);break;case"s":_=o,x=l,w=n[n.length-1],w.command==="C"&&(_=o+(o-w.points[2]),x=l+(l-w.points[3])),C.push(_,x,o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),S="C",C.push(o,l);break;case"Q":C.push(g.shift(),g.shift()),o=g.shift(),l=g.shift(),C.push(o,l);break;case"q":C.push(o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),S="Q",C.push(o,l);break;case"T":_=o,x=l,w=n[n.length-1],w.command==="Q"&&(_=o+(o-w.points[0]),x=l+(l-w.points[1])),o=g.shift(),l=g.shift(),S="Q",C.push(_,x,o,l);break;case"t":_=o,x=l,w=n[n.length-1],w.command==="Q"&&(_=o+(o-w.points[0]),x=l+(l-w.points[1])),o+=g.shift(),l+=g.shift(),S="Q",C.push(_,x,o,l);break;case"A":L=g.shift(),k=g.shift(),M=g.shift(),P=g.shift(),$=g.shift(),G=o,U=l,o=g.shift(),l=g.shift(),S="A",C=this.convertEndpointToCenterParameterization(G,U,o,l,P,$,L,k,M);break;case"a":L=g.shift(),k=g.shift(),M=g.shift(),P=g.shift(),$=g.shift(),G=o,U=l,o+=g.shift(),l+=g.shift(),S="A",C=this.convertEndpointToCenterParameterization(G,U,o,l,P,$,L,k,M);break}n.push({command:S||f,points:C,start:{x:v,y:T},pathLength:this.calcLength(v,T,S||f,C)})}(f==="z"||f==="Z")&&n.push({command:"z",points:[],start:void 0,pathLength:0})}return n}static calcLength(e,t,i,r){let n,a,o,l;const c=ie;switch(i){case"L":return c.getLineLength(e,t,r[0],r[1]);case"C":return In([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return En([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 f=Math.PI/180;if(Math.abs(h-u)<f&&(f=Math.abs(h-u)),a=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),d<0)for(l=h-f;l>u;l-=f)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;else for(l=h+f;l<u;l+=f)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;return o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],u,0),n+=c.getLineLength(a.x,a.y,o.x,o.y),n}return 0}static convertEndpointToCenterParameterization(e,t,i,r,n,a,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,f=d*d/(o*o)+u*u/(l*l);f>1&&(o*=Math.sqrt(f),l*=Math.sqrt(f));let g=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));n===a&&(g*=-1),isNaN(g)&&(g=0);const y=g*o*u/l,S=g*-l*d/o,C=(e+i)/2+Math.cos(h)*y-Math.sin(h)*S,v=(t+r)/2+Math.sin(h)*y+Math.cos(h)*S,T=function(P){return Math.sqrt(P[0]*P[0]+P[1]*P[1])},w=function(P,$){return(P[0]*$[0]+P[1]*$[1])/(T(P)*T($))},_=function(P,$){return(P[0]*$[1]<P[1]*$[0]?-1:1)*Math.acos(w(P,$))},x=_([1,0],[(d-y)/o,(u-S)/l]),L=[(d-y)/o,(u-S)/l],k=[(-1*d-y)/o,(-1*u-S)/l];let M=_(L,k);return w(L,k)<=-1&&(M=Math.PI),w(L,k)>=1&&(M=0),a===0&&M>0&&(M=M-2*Math.PI),a===1&&M<0&&(M=M+2*Math.PI),[C,v,o,l,x,M,h,a]}}ie.prototype.className="Path";ie.prototype._attrsAffectingSize=["data"];se(ie);m.addGetterSetter(ie,"data");class pt extends Ge{_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 a=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]],f=ie.calcLength(r[r.length-4],r[r.length-3],"C",u),g=ie.getPointOnQuadraticBezier(Math.min(1,1-a/f),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-g.x,c=i[o-1]-g.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(-a,d/2),e.lineTo(-a,-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(-a,d/2),e.lineTo(-a,-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}}}pt.prototype.className="Arrow";se(pt);m.addGetterSetter(pt,"pointerLength",10,R());m.addGetterSetter(pt,"pointerWidth",10,R());m.addGetterSetter(pt,"pointerAtBeginning",!1);m.addGetterSetter(pt,"pointerAtEnding",!0);class At extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}At.prototype._centroid=!0;At.prototype.className="Circle";At.prototype._attrsAffectingSize=["radius"];se(At);m.addGetterSetter(At,"radius",0,R());class Qe extends A{_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)}}Qe.prototype.className="Ellipse";Qe.prototype._centroid=!0;Qe.prototype._attrsAffectingSize=["radiusX","radiusY"];se(Qe);m.addComponentsGetterSetter(Qe,"radius",["x","y"]);m.addGetterSetter(Qe,"radiusX",0,R());m.addGetterSetter(Qe,"radiusY",0,R());let Ie=class ra extends A{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 a;if(n){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?a=[n,this.cropX(),this.cropY(),o,l,0,0,t,i]:a=[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,a))}_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 ra({image:r});t(n)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Ie.prototype.className="Image";Ie.prototype._attrsAffectingSize=["image"];se(Ie);m.addGetterSetter(Ie,"cornerRadius",0,Ki(4));m.addGetterSetter(Ie,"image");m.addComponentsGetterSetter(Ie,"crop",["x","y","width","height"]);m.addGetterSetter(Ie,"cropX",0,R());m.addGetterSetter(Ie,"cropY",0,R());m.addGetterSetter(Ie,"cropWidth",0,R());m.addGetterSetter(Ie,"cropHeight",0,R());const na=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],yl="Change.konva",Sl="none",Ir="up",Er="right",Rr="down",Mr="left",vl=na.length;class rn extends xt{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<vl;i++)e.on(na[i]+yl,r)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),i,r,n,a,o,l,c;if(e&&t){switch(i=e.width(),r=e.height(),n=t.pointerDirection(),a=t.pointerWidth(),c=t.pointerHeight(),o=0,l=0,n){case Ir:o=i/2,l=-1*c;break;case Er:o=i+a,l=r/2;break;case Rr:o=i/2,l=r+c;break;case Mr:o=-1*a,l=r/2;break}t.setAttrs({x:-1*o,y:-1*l,width:i,height:r}),e.setAttrs({x:-1*o,y:-1*l})}}}rn.prototype.className="Label";se(rn);class ft extends A{_sceneFunc(e){const t=this.width(),i=this.height(),r=this.pointerDirection(),n=this.pointerWidth(),a=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===Ir&&(e.lineTo((t-n)/2,0),e.lineTo(t/2,-1*a),e.lineTo((t+n)/2,0)),e.lineTo(t-c,0),e.arc(t-c,c,c,Math.PI*3/2,0,!1),r===Er&&(e.lineTo(t,(i-a)/2),e.lineTo(t+n,i/2),e.lineTo(t,(i+a)/2)),e.lineTo(t,i-d),e.arc(t-d,i-d,d,0,Math.PI/2,!1),r===Rr&&(e.lineTo((t+n)/2,i),e.lineTo(t/2,i+a),e.lineTo((t-n)/2,i)),e.lineTo(h,i),e.arc(h,i-h,h,Math.PI/2,Math.PI,!1),r===Mr&&(e.lineTo(0,(i+a)/2),e.lineTo(-1*n,i/2),e.lineTo(0,(i-a)/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(),a=this.width(),o=this.height();return n===Ir?(t-=r,o+=r):n===Rr?o+=r:n===Mr?(e-=i*1.5,a+=i):n===Er&&(a+=i*1.5),{x:e,y:t,width:a,height:o}}}ft.prototype.className="Tag";se(ft);m.addGetterSetter(ft,"pointerDirection",Sl);m.addGetterSetter(ft,"pointerWidth",0,R());m.addGetterSetter(ft,"pointerHeight",0,R());m.addGetterSetter(ft,"cornerRadius",0,Ki(4));class hi extends A{_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)}}hi.prototype.className="Rect";se(hi);m.addGetterSetter(hi,"cornerRadius",0,Ki(4));class et extends A{_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 a=1;a<t.length;a++)e.lineTo(t[a].x,t[a].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(a=>{t=Math.min(t,a.x),i=Math.max(i,a.x),r=Math.min(r,a.y),n=Math.max(n,a.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)}}et.prototype.className="RegularPolygon";et.prototype._centroid=!0;et.prototype._attrsAffectingSize=["radius"];se(et);m.addGetterSetter(et,"radius",0,R());m.addGetterSetter(et,"sides",0,R());m.addGetterSetter(et,"cornerRadius",0,Ki(4));const Mn=Math.PI*2;class gt extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,Mn,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),Mn,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)}}gt.prototype.className="Ring";gt.prototype._centroid=!0;gt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];se(gt);m.addGetterSetter(gt,"innerRadius",0,R());m.addGetterSetter(gt,"outerRadius",0,R());class Le extends A{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],a=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(a){const u=a[t],f=i*2;e.drawImage(d,o,l,c,h,u[f+0],u[f+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],a=this.frameOffsets(),o=n[r+2],l=n[r+3];if(e.beginPath(),a){const c=a[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)}}Le.prototype.className="Sprite";se(Le);m.addGetterSetter(Le,"animation");m.addGetterSetter(Le,"animations");m.addGetterSetter(Le,"frameOffsets");m.addGetterSetter(Le,"image");m.addGetterSetter(Le,"frameIndex",0,R());m.addGetterSetter(Le,"frameRate",17,R());m.backCompat(Le,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class tt extends A{_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 a=n%2===0?i:t,o=a*Math.sin(n*Math.PI/r),l=-1*a*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)}}tt.prototype.className="Star";tt.prototype._centroid=!0;tt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];se(tt);m.addGetterSetter(tt,"numPoints",5,R());m.addGetterSetter(tt,"innerRadius",0,R());m.addGetterSetter(tt,"outerRadius",0,R());function Ye(s){return[...s].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 yt="auto",Cl="center",sa="inherit",Lt="justify",bl="Change.konva",Tl="2d",Dn="-",aa="left",wl="text",kl="Text",xl="top",Pl="bottom",Ln="middle",oa="normal",_l="px ",bi=" ",Al="right",On="rtl",Il="word",El="char",Bn="none",or="…",la=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Rl=la.length;function Ml(s){return s.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 Ti;function lr(){return Ti||(Ti=b.createCanvasElement().getContext(Tl),Ti)}function Dl(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function Ll(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Ol(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}class re extends A{constructor(e){super(Ol(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<Rl;t++)this.on(la[t]+bl,this._setTextData);this._setTextData()}_sceneFunc(e){var t,i;const r=this.textArr,n=r.length;if(!this.text())return;let a=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,c=this.verticalAlign(),h=this.direction(),d=0,u=this.align(),f=this.getWidth(),g=this.letterSpacing(),y=this.charRenderFunc(),S=this.fill(),C=this.textDecoration(),v=this.underlineOffset(),T=C.indexOf("underline")!==-1,w=C.indexOf("line-through")!==-1,_;h=h===sa?e.direction:h;let x=l/2,L=Ln;if(!D.legacyTextRendering){const k=this.measureSize("M");L="alphabetic";const M=(t=k.fontBoundingBoxAscent)!==null&&t!==void 0?t:k.actualBoundingBoxAscent,P=(i=k.fontBoundingBoxDescent)!==null&&i!==void 0?i:k.actualBoundingBoxDescent;x=(M-P)/2+l/2}for(h===On&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",L),e.setAttr("textAlign",aa),c===Ln?d=(this.getHeight()-n*l-a*2)/2:c===Pl&&(d=this.getHeight()-n*l-a*2),e.translate(a,d+a),_=0;_<n;_++){let k=0,M=0;const P=r[_],$=P.text,G=P.width,U=P.lastInParagraph;if(e.save(),u===Al?k+=f-G-a*2:u===Cl&&(k+=(f-G-a*2)/2),T){e.save(),e.beginPath();const B=v??(D.legacyTextRendering?Math.round(o/2):Math.round(o/4)),O=k,J=x+M+B;e.moveTo(O,J);const N=u===Lt&&!U?f-a*2:G;e.lineTo(O+Math.round(N),J),e.lineWidth=o/15;const q=this._getLinearGradient();e.strokeStyle=q||S,e.stroke(),e.restore()}const z=k;if(h!==On&&(g!==0||u===Lt||y)){const B=$.split(" ").length-1,O=Ye($);for(let J=0;J<O.length;J++){const N=O[J];if(N===" "&&!U&&u===Lt&&(k+=(f-a*2-G)/B),this._partialTextX=k,this._partialTextY=x+M,this._partialText=N,y){e.save();const ne=r.slice(0,_).reduce((oe,pe)=>oe+Ye(pe.text).length,0),V=J+ne;y({char:N,index:V,x:k,y:x+M,lineIndex:_,column:J,isLastInLine:U,width:this.measureSize(N).width,context:e})}e.fillStrokeShape(this),y&&e.restore(),k+=this.measureSize(N).width+g}}else g!==0&&e.setAttr("letterSpacing",`${g}px`),this._partialTextX=k,this._partialTextY=x+M,this._partialText=$,e.fillStrokeShape(this);if(w){e.save(),e.beginPath();const B=D.legacyTextRendering?0:-Math.round(o/4),O=z;e.moveTo(O,x+M+B);const J=u===Lt&&!U?f-a*2:G;e.lineTo(O+Math.round(J),x+M+B),e.lineWidth=o/15;const N=this._getLinearGradient();e.strokeStyle=N||S,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=b._isString(e)?e:e==null?"":e+"";return this._setAttr(wl,t),this}getWidth(){return this.attrs.width===yt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===yt||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,a,o,l,c,h,d,u;let f=lr(),g=this.fontSize(),y;f.save(),f.font=this._getContextFont(),y=f.measureText(e),f.restore();const S=g/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:(a=y.alphabeticBaseline)!==null&&a!==void 0?a: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:g}}_getContextFont(){return this.fontStyle()+bi+this.fontVariant()+bi+(this.fontSize()+_l)+Ml(this.fontFamily())}_addTextLine(e){this.align()===Lt&&(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 lr().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,a=this.attrs.height,o=n!==yt&&n!==void 0,l=a!==yt&&a!==void 0,c=this.padding(),h=n-c*2,d=a-c*2,u=0,f=this.wrap(),g=f!==Bn,y=f!==El&&g,S=this.ellipsis();this.textArr=[],lr().font=this._getContextFont();const C=S?this._getTextWidth(or):0;for(let v=0,T=e.length;v<T;++v){let w=e[v],_=this._getTextWidth(w);if(o&&_>h)for(;w.length>0;){let x=0,L=Ye(w).length,k="",M=0;for(;x<L;){const P=x+L>>>1,$=Ye(w),G=$.slice(0,P+1).join(""),U=this._getTextWidth(G);(S&&l&&u+r>d?U+C:U)<=h?(x=P+1,k=G,M=U):L=P}if(k){if(y){const G=Ye(w),U=Ye(k),z=G[U.length],B=z===bi||z===Dn;let O;if(B&&M<=h)O=U.length;else{const J=U.lastIndexOf(bi),N=U.lastIndexOf(Dn);O=Math.max(J,N)+1}O>0&&(x=O,k=G.slice(0,x).join(""),M=this._getTextWidth(k))}if(k=k.trimRight(),this._addTextLine(k),i=Math.max(i,M),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(w=Ye(w).slice(x).join("").trimLeft(),w.length>0&&(_=this._getTextWidth(w),_<=h)){this._addTextLine(w),u+=r,i=Math.max(i,_);break}}else break}else this._addTextLine(w),u+=r,i=Math.max(i,_),this._shouldHandleEllipsis(u)&&v<T-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!==yt&&r!==void 0,a=this.padding(),o=r-a*2;return!(this.wrap()!==Bn)||n&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==yt&&e!==void 0,i=this.padding(),r=e-i*2,n=this.ellipsis(),a=this.textArr[this.textArr.length-1];!a||!n||(t&&(this._getTextWidth(a.text+or)<r||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+or))}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=Dl;re.prototype._strokeFunc=Ll;re.prototype.className=kl;re.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];se(re);m.overWriteSetter(re,"width",Qr());m.overWriteSetter(re,"height",Qr());m.addGetterSetter(re,"direction",sa);m.addGetterSetter(re,"fontFamily","Arial");m.addGetterSetter(re,"fontSize",12,R());m.addGetterSetter(re,"fontStyle",oa);m.addGetterSetter(re,"fontVariant",oa);m.addGetterSetter(re,"padding",0,R());m.addGetterSetter(re,"align",aa);m.addGetterSetter(re,"verticalAlign",xl);m.addGetterSetter(re,"lineHeight",1,R());m.addGetterSetter(re,"wrap",Il);m.addGetterSetter(re,"ellipsis",!1,Ae());m.addGetterSetter(re,"letterSpacing",0,R());m.addGetterSetter(re,"text","",dt());m.addGetterSetter(re,"textDecoration","");m.addGetterSetter(re,"underlineOffset",void 0,R());m.addGetterSetter(re,"charRenderFunc",void 0);const Bl="",ca="normal";function ha(s){s.fillText(this.partialText,0,0)}function da(s){s.strokeText(this.partialText,0,0)}class he extends A{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,a=t.indexOf("underline")!==-1,o=t.indexOf("line-through")!==-1;a&&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),a&&(l===0&&e.moveTo(0,r/2+1),e.lineTo(n[l].width,r/2+1)),e.restore()}if(a&&(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=Ye(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(),a=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*n,0);let c=0;a==="center"&&(c=Math.max(0,this.pathLength/2-l/2)),a==="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 f=t[d].char;let g=t[d].width+n;if(f===" "&&a==="justify"){const w=this.text().split(" ").length-1;g+=(this.pathLength-l)/w}const y=this._getPointAtLength(h+g);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,f)*this.fontSize()}catch{C=0}u.x+=C,y.x+=C,this.textWidth+=C;const v=ie.getPointOnLine(C+S/2,u.x,u.y,y.x,y.y),T=Math.atan2(y.y-u.y,y.x-u.x);this.glyphInfo.push({transposeX:v.x,transposeY:v.y,text:e[d],rotation:T,p0:u,p1:y,width:S}),h+=g}}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,a,o;for(let c=0;c<e.length/2;c++)a=e[c*2],o=e[c*2+1],t=Math.min(t,a),i=Math.max(i,a),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()}}he.prototype._fillFunc=ha;he.prototype._strokeFunc=da;he.prototype._fillFuncHit=ha;he.prototype._strokeFuncHit=da;he.prototype.className="TextPath";he.prototype._attrsAffectingSize=["text","fontSize","data"];se(he);m.addGetterSetter(he,"data");m.addGetterSetter(he,"fontFamily","Arial");m.addGetterSetter(he,"fontSize",12,R());m.addGetterSetter(he,"fontStyle",ca);m.addGetterSetter(he,"align","left");m.addGetterSetter(he,"letterSpacing",0,R());m.addGetterSetter(he,"textBaseline","middle");m.addGetterSetter(he,"fontVariant",ca);m.addGetterSetter(he,"text",Bl);m.addGetterSetter(he,"textDecoration","");m.addGetterSetter(he,"kerningFunc",void 0);const ua="tr-konva",Fl=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(s=>s+`.${ua}`).join(" "),Fn="nodesRect",Gl=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Hl={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Nl="ontouchstart"in D._global;function $l(s,e,t){if(s==="rotater")return t;e+=b.degToRad(Hl[s]||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 zl(s){return{x:s.x+s.width/2*Math.cos(s.rotation)+s.height/2*Math.sin(-s.rotation),y:s.y+s.height/2*Math.cos(s.rotation)+s.width/2*Math.sin(s.rotation)}}function pa(s,e,t){const i=t.x+(s.x-t.x)*Math.cos(e)-(s.y-t.y)*Math.sin(e),r=t.y+(s.x-t.x)*Math.sin(e)+(s.y-t.y)*Math.cos(e);return{...s,rotation:s.rotation+e,x:i,y:r}}function Vl(s,e){const t=zl(s);return pa(s,e,t)}function Ul(s,e,t){let i=e;for(let r=0;r<s.length;r++){const n=D.getAngle(s[r]),a=Math.abs(n-e)%(Math.PI*2);Math.min(a,Math.PI*2-a)<t&&(i=n)}return i}let Dr=0;class W extends xt{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(Fl,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 ua+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 a=r._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");r.on(a,n)}r.on(Gl.map(a=>a+`.${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,a=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+a}),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(Fn),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Fn,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),i){const r=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),n=e.getAbsoluteScale(i),a=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:a.x+o*Math.cos(c)+l*Math.sin(-c),y:a.y+l*Math.cos(c)+o*Math.sin(c),width:r.width*n.x,height:r.height*n.y,rotation:c};return pa(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(f){const g=u.point(f);t.push(g)})});const i=new ye;i.rotate(-D.getAngle(this.rotation()));let r=1/0,n=1/0,a=-1/0,o=-1/0;t.forEach(function(c){const h=i.point(c);r===void 0&&(r=a=h.x,n=o=h.y),r=Math.min(r,h.x),n=Math.min(n,h.y),a=Math.max(a,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:a-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 hi({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Nl?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(),a=$l(e,r,n);t.getStage().content&&(t.getStage().content.style.cursor=a),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new A({name:"back",width:0,height:0,sceneFunc(t,i){const r=i.getParent(),n=r.padding(),a=i.width(),o=i.height();if(t.beginPath(),t.rect(-n,-n,a+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),f=a/2,g=o/2;let y=1/0;u<0?y=Math.min(y,-g/u):u>0&&(y=Math.min(y,(o-g)/u)),d<0?y=Math.min(y,-f/d):d>0&&(y=Math.min(y,(a-f)/d));const S=f+d*y,C=g+u*y,v=b._sign(o),T=S+d*c*v,w=C+u*c*v;t.moveTo(S,C),t.lineTo(T,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 a=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-a.x,y:o.y-a.y},Dr++,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),a=n.getStage();a.setPointersPositions(e);const o=a.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 v=this._getNodeRect();t=n.x()-v.width/2,i=-n.y()+v.height/2;const T=D.getAngle(this.rotateAnchorAngle());let w=Math.atan2(-i,t)+Math.PI/2-T;v.height<0&&(w-=Math.PI);const x=D.getAngle(this.rotation())+w,L=D.getAngle(this.rotationSnapTolerance()),M=Ul(this.rotationSnaps(),x,L)-v.rotation,P=Vl(v,M);this._fitNodesInto(P,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let f=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const v=f?{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(v.x-n.x(),2)+Math.pow(v.y-n.y(),2));const T=this.findOne(".top-left").x()>v.x?-1:1,w=this.findOne(".top-left").y()>v.y?-1:1;t=r*this.cos*T,i=r*this.sin*w,this.findOne(".top-left").x(v.x-t),this.findOne(".top-left").y(v.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(n.y());else if(this._movingAnchorName==="top-right"){if(u){const v=f?{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()-v.x,2)+Math.pow(v.y-n.y(),2));const T=this.findOne(".top-right").x()<v.x?-1:1,w=this.findOne(".top-right").y()>v.y?-1:1;t=r*this.cos*T,i=r*this.sin*w,this.findOne(".top-right").x(v.x+t),this.findOne(".top-right").y(v.y-i)}var g=n.position();this.findOne(".top-left").y(g.y),this.findOne(".bottom-right").x(g.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(n.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(n.x());else if(this._movingAnchorName==="bottom-left"){if(u){const v=f?{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(v.x-n.x(),2)+Math.pow(n.y()-v.y,2));const T=v.x<n.x()?-1:1,w=n.y()<v.y?-1:1;t=r*this.cos*T,i=r*this.sin*w,n.x(v.x-t),n.y(v.y+i)}g=n.position(),this.findOne(".top-left").x(g.x),this.findOne(".bottom-right").y(g.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(n.y());else if(this._movingAnchorName==="bottom-right"){if(u){const v=f?{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()-v.x,2)+Math.pow(n.y()-v.y,2));const T=this.findOne(".bottom-right").x()<v.x?-1:1,w=this.findOne(".bottom-right").y()<v.y?-1:1;t=r*this.cos*T,i=r*this.sin*w,this.findOne(".bottom-right").x(v.x+t),this.findOne(".bottom-right").y(v.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(f=this.centeredScaling()||e.altKey,f){const v=this.findOne(".top-left"),T=this.findOne(".bottom-right"),w=v.x(),_=v.y(),x=this.getWidth()-T.x(),L=this.getHeight()-T.y();T.move({x:-w,y:-_}),v.move({x,y:L})}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();Dr--,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 ye;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 a=1e7,o=new ye;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/a,i.height/a);const l=new ye,c=e.width/a,h=e.height/a;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 f;if(!u.getStage())return;const g=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const S=new ye;S.multiply(g.copy().invert()).multiply(d).multiply(g).multiply(y);const C=S.decompose();u.setAttrs(C),(f=u.getLayer())===null||f===void 0||f.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(),a=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),c=this.find("._anchor");c.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:a&&n.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:a&&n.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:a&&n.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:l/2+o,visible:a&&n.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:l/2-o,visible:a&&n.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:l/2+o,offsetY:l/2-o,visible:a&&n.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:l/2-o,visible:a&&n.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:l/2-o,offsetY:l/2-o,visible:a&&n.indexOf("bottom-right")>=0});const h=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=b.degToRad(h),f=Math.sin(u),g=-Math.cos(u),y=i/2,S=r/2;let C=1/0;g<0?C=Math.min(C,-S/g):g>0&&(C=Math.min(C,(r-S)/g)),f<0?C=Math.min(C,-y/f):f>0&&(C=Math.min(C,(i-y)/f));const v=y+f*C,T=S+g*C,w=b._sign(r);this._batchChangeChild(".rotater",{x:v+f*d*w,y:T+g*d*w-o*g,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 _=this.anchorStyleFunc();_&&c.forEach(x=>{_(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=""),xt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return E.prototype.toObject.call(this)}clone(e){return E.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}W.isTransforming=()=>Dr>0;function Wl(s){return s instanceof Array||b.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(e){Gi.indexOf(e)===-1&&b.warn("Unknown anchor name: "+e+". Available names are: "+Gi.join(", "))}),s||[]}W.prototype.className="Transformer";se(W);m.addGetterSetter(W,"enabledAnchors",Gi,Wl);m.addGetterSetter(W,"flipEnabled",!0,Ae());m.addGetterSetter(W,"resizeEnabled",!0);m.addGetterSetter(W,"anchorSize",10,R());m.addGetterSetter(W,"rotateEnabled",!0);m.addGetterSetter(W,"rotateLineVisible",!0);m.addGetterSetter(W,"rotationSnaps",[]);m.addGetterSetter(W,"rotateAnchorOffset",50,R());m.addGetterSetter(W,"rotateAnchorAngle",0,R());m.addGetterSetter(W,"rotateAnchorCursor","crosshair");m.addGetterSetter(W,"rotationSnapTolerance",5,R());m.addGetterSetter(W,"borderEnabled",!0);m.addGetterSetter(W,"anchorStroke","rgb(0, 161, 255)");m.addGetterSetter(W,"anchorStrokeWidth",1,R());m.addGetterSetter(W,"anchorFill","white");m.addGetterSetter(W,"anchorCornerRadius",0,R());m.addGetterSetter(W,"borderStroke","rgb(0, 161, 255)");m.addGetterSetter(W,"borderStrokeWidth",1,R());m.addGetterSetter(W,"borderDash");m.addGetterSetter(W,"keepRatio",!0);m.addGetterSetter(W,"shiftBehavior","default");m.addGetterSetter(W,"centeredScaling",!1);m.addGetterSetter(W,"ignoreStroke",!1);m.addGetterSetter(W,"padding",0,R());m.addGetterSetter(W,"nodes");m.addGetterSetter(W,"node");m.addGetterSetter(W,"boundBoxFunc");m.addGetterSetter(W,"anchorDragBoundFunc");m.addGetterSetter(W,"anchorStyleFunc");m.addGetterSetter(W,"shouldOverdrawWholeArea",!1);m.addGetterSetter(W,"useSingleNodeRotation",!0);m.backCompat(W,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class He extends A{_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)}}He.prototype.className="Wedge";He.prototype._centroid=!0;He.prototype._attrsAffectingSize=["radius"];se(He);m.addGetterSetter(He,"radius",0,R());m.addGetterSetter(He,"angle",0,R());m.addGetterSetter(He,"clockwise",!1);m.backCompat(He,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Gn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Yl=[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],Xl=[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 ql(s,e){const t=s.data,i=s.width,r=s.height;let n,a,o,l,c,h,d,u,f,g,y,S,C,v,T,w,_,x,L,k;const M=e+e+1,P=i-1,$=r-1,G=e+1,U=G*(G+1)/2,z=new Gn,B=Yl[e],O=Xl[e];let J=null,N=z,q=null,ne=null;for(let V=1;V<M;V++)N=N.next=new Gn,V===G&&(J=N);N.next=z,o=a=0;for(let V=0;V<r;V++){S=C=v=T=l=c=h=d=0,u=G*(w=t[a]),f=G*(_=t[a+1]),g=G*(x=t[a+2]),y=G*(L=t[a+3]),l+=U*w,c+=U*_,h+=U*x,d+=U*L,N=z;for(let oe=0;oe<G;oe++)N.r=w,N.g=_,N.b=x,N.a=L,N=N.next;for(let oe=1;oe<G;oe++)n=a+((P<oe?P:oe)<<2),l+=(N.r=w=t[n])*(k=G-oe),c+=(N.g=_=t[n+1])*k,h+=(N.b=x=t[n+2])*k,d+=(N.a=L=t[n+3])*k,S+=w,C+=_,v+=x,T+=L,N=N.next;q=z,ne=J;for(let oe=0;oe<i;oe++)t[a+3]=L=d*B>>O,L!==0?(L=255/L,t[a]=(l*B>>O)*L,t[a+1]=(c*B>>O)*L,t[a+2]=(h*B>>O)*L):t[a]=t[a+1]=t[a+2]=0,l-=u,c-=f,h-=g,d-=y,u-=q.r,f-=q.g,g-=q.b,y-=q.a,n=o+((n=oe+e+1)<P?n:P)<<2,S+=q.r=t[n],C+=q.g=t[n+1],v+=q.b=t[n+2],T+=q.a=t[n+3],l+=S,c+=C,h+=v,d+=T,q=q.next,u+=w=ne.r,f+=_=ne.g,g+=x=ne.b,y+=L=ne.a,S-=w,C-=_,v-=x,T-=L,ne=ne.next,a+=4;o+=i}for(let V=0;V<i;V++){C=v=T=S=c=h=d=l=0,a=V<<2,u=G*(w=t[a]),f=G*(_=t[a+1]),g=G*(x=t[a+2]),y=G*(L=t[a+3]),l+=U*w,c+=U*_,h+=U*x,d+=U*L,N=z;for(let pe=0;pe<G;pe++)N.r=w,N.g=_,N.b=x,N.a=L,N=N.next;let oe=i;for(let pe=1;pe<=e;pe++)a=oe+V<<2,l+=(N.r=w=t[a])*(k=G-pe),c+=(N.g=_=t[a+1])*k,h+=(N.b=x=t[a+2])*k,d+=(N.a=L=t[a+3])*k,S+=w,C+=_,v+=x,T+=L,N=N.next,pe<$&&(oe+=i);a=V,q=z,ne=J;for(let pe=0;pe<r;pe++)n=a<<2,t[n+3]=L=d*B>>O,L>0?(L=255/L,t[n]=(l*B>>O)*L,t[n+1]=(c*B>>O)*L,t[n+2]=(h*B>>O)*L):t[n]=t[n+1]=t[n+2]=0,l-=u,c-=f,h-=g,d-=y,u-=q.r,f-=q.g,g-=q.b,y-=q.a,n=V+((n=pe+G)<$?n:$)*i<<2,l+=S+=q.r=t[n],c+=C+=q.g=t[n+1],h+=v+=q.b=t[n+2],d+=T+=q.a=t[n+3],q=q.next,u+=w=ne.r,f+=_=ne.g,g+=x=ne.b,y+=L=ne.a,S-=w,C-=_,v-=x,T-=L,ne=ne.next,a+=i}}const jl=function(e){const t=Math.round(this.blurRadius());t>0&&ql(e,t)};m.addGetterSetter(E,"blurRadius",0,R(),m.afterSetFilter);const Kl=function(s){const e=this.brightness()*255,t=s.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(E,"brightness",0,R(),m.afterSetFilter);const Zl=function(s){const e=this.brightness(),t=s.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)},Jl=function(s){const e=Math.pow((this.contrast()+100)/100,2),t=s.data,i=t.length;let r=150,n=150,a=150;for(let o=0;o<i;o+=4)r=t[o],n=t[o+1],a=t[o+2],r/=255,r-=.5,r*=e,r+=.5,r*=255,n/=255,n-=.5,n*=e,n+=.5,n*=255,a/=255,a-=.5,a*=e,a+=.5,a*=255,r=r<0?0:r>255?255:r,n=n<0?0:n>255?255:n,a=a<0?0:a>255?255:a,t[o]=r,t[o+1]=n,t[o+2]=a};m.addGetterSetter(E,"contrast",0,R(),m.afterSetFilter);const Ql=function(s){var e,t,i,r,n,a,o,l,c;const h=s.data,d=s.width,u=s.height,f=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),g=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}[(a=(n=this.embossDirection)===null||n===void 0?void 0:n.call(this))!==null&&a!==void 0?a:"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),v=f*10,T=g*255,w=S*Math.PI/180,_=Math.cos(w),x=Math.sin(w),L=128/1020*v,k=new Uint8ClampedArray(h),M=new Float32Array(d*u);for(let z=0,B=0;B<h.length;B+=4,z++)M[z]=.2126*k[B]+.7152*k[B+1]+.0722*k[B+2];const P=[-1,0,1,-2,0,2,-1,0,1],$=[-1,-2,-1,0,0,0,1,2,1],G=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],U=z=>z<0?0:z>255?255:z;for(let z=1;z<u-1;z++)for(let B=1;B<d-1;B++){const O=z*d+B;let J=0,N=0;J+=M[O+G[0]]*P[0],N+=M[O+G[0]]*$[0],J+=M[O+G[1]]*P[1],N+=M[O+G[1]]*$[1],J+=M[O+G[2]]*P[2],N+=M[O+G[2]]*$[2],J+=M[O+G[3]]*P[3],N+=M[O+G[3]]*$[3],J+=M[O+G[5]]*P[5],N+=M[O+G[5]]*$[5],J+=M[O+G[6]]*P[6],N+=M[O+G[6]]*$[6],J+=M[O+G[7]]*P[7],N+=M[O+G[7]]*$[7],J+=M[O+G[8]]*P[8],N+=M[O+G[8]]*$[8];const q=_*J+x*N,ne=U(T+q*L),V=O*4;if(C){const oe=ne-T;h[V]=U(k[V]+oe),h[V+1]=U(k[V+1]+oe),h[V+2]=U(k[V+2]+oe),h[V+3]=k[V+3]}else h[V]=h[V+1]=h[V+2]=ne,h[V+3]=k[V+3]}for(let z=0;z<d;z++){let B=z*4,O=((u-1)*d+z)*4;h[B]=k[B],h[B+1]=k[B+1],h[B+2]=k[B+2],h[B+3]=k[B+3],h[O]=k[O],h[O+1]=k[O+1],h[O+2]=k[O+2],h[O+3]=k[O+3]}for(let z=1;z<u-1;z++){let B=z*d*4,O=(z*d+(d-1))*4;h[B]=k[B],h[B+1]=k[B+1],h[B+2]=k[B+2],h[B+3]=k[B+3],h[O]=k[O],h[O+1]=k[O+1],h[O+2]=k[O+2],h[O+3]=k[O+3]}return s};m.addGetterSetter(E,"embossStrength",.5,R(),m.afterSetFilter);m.addGetterSetter(E,"embossWhiteLevel",.5,R(),m.afterSetFilter);m.addGetterSetter(E,"embossDirection","top-left",void 0,m.afterSetFilter);m.addGetterSetter(E,"embossBlend",!1,void 0,m.afterSetFilter);function cr(s,e,t,i,r){const n=t-e,a=r-i;if(n===0)return i+a/2;if(a===0)return i;let o=(s-e)/n;return o=a*o+i,o}const ec=function(s){const e=s.data,t=e.length;let i=e[0],r=i,n,a=e[1],o=a,l,c=e[2],h=c,d;const u=this.enhance();if(u===0)return;for(let T=0;T<t;T+=4)n=e[T+0],n<i?i=n:n>r&&(r=n),l=e[T+1],l<a?a=l:l>o&&(o=l),d=e[T+2],d<c?c=d:d>h&&(h=d);r===i&&(r=255,i=0),o===a&&(o=255,a=0),h===c&&(h=255,c=0);let f,g,y,S,C,v;if(u>0)f=r+u*(255-r),g=i-u*(i-0),y=o+u*(255-o),S=a-u*(a-0),C=h+u*(255-h),v=c-u*(c-0);else{const T=(r+i)*.5;f=r+u*(r-T),g=i+u*(i-T);const w=(o+a)*.5;y=o+u*(o-w),S=a+u*(a-w);const _=(h+c)*.5;C=h+u*(h-_),v=c+u*(c-_)}for(let T=0;T<t;T+=4)e[T+0]=cr(e[T+0],i,r,g,f),e[T+1]=cr(e[T+1],a,o,S,y),e[T+2]=cr(e[T+2],c,h,v,C)};m.addGetterSetter(E,"enhance",0,R(),m.afterSetFilter);const tc=function(s){const e=s.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(E,"hue",0,R(),m.afterSetFilter);m.addGetterSetter(E,"saturation",0,R(),m.afterSetFilter);m.addGetterSetter(E,"luminance",0,R(),m.afterSetFilter);const ic=function(s){const e=s.data,t=e.length,i=1,r=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,a=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,f=.587*i+.413*o+.035*l,g=.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 v,T,w,_;for(let x=0;x<t;x+=4)v=e[x+0],T=e[x+1],w=e[x+2],_=e[x+3],e[x+0]=c*v+h*T+d*w+a,e[x+1]=u*v+f*T+g*w+a,e[x+2]=y*v+S*T+C*w+a,e[x+3]=_},rc=function(s){const e=s.data,t=e.length,i=Math.pow(2,this.value()),r=Math.pow(2,this.saturation()),n=Math.abs(this.hue()+360)%360,a=i*r*Math.cos(n*Math.PI/180),o=i*r*Math.sin(n*Math.PI/180),l=.299*i+.701*a+.167*o,c=.587*i-.587*a+.33*o,h=.114*i-.114*a-.497*o,d=.299*i-.299*a-.328*o,u=.587*i+.413*a+.035*o,f=.114*i-.114*a+.293*o,g=.299*i-.3*a+1.25*o,y=.587*i-.586*a-1.05*o,S=.114*i+.886*a-.2*o;for(let C=0;C<t;C+=4){const v=e[C+0],T=e[C+1],w=e[C+2],_=e[C+3];e[C+0]=l*v+c*T+h*w,e[C+1]=d*v+u*T+f*w,e[C+2]=g*v+y*T+S*w,e[C+3]=_}};m.addGetterSetter(E,"hue",0,R(),m.afterSetFilter);m.addGetterSetter(E,"saturation",0,R(),m.afterSetFilter);m.addGetterSetter(E,"value",0,R(),m.afterSetFilter);const nc=function(s){const e=s.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]},sc=function(s,e,t){const i=s.data,r=e.data,n=s.width,a=s.height,o=t.polarCenterX||n/2,l=t.polarCenterY||a/2;let c=Math.sqrt(o*o+l*l),h=n-o,d=a-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const f=a,g=n,y=360/g*Math.PI/180;for(let S=0;S<g;S+=1){const C=Math.sin(S*y),v=Math.cos(S*y);for(let T=0;T<f;T+=1){h=Math.floor(o+c*T/f*v),d=Math.floor(l+c*T/f*C);let w=(d*n+h)*4;const _=i[w+0],x=i[w+1],L=i[w+2],k=i[w+3];w=(S+T*n)*4,r[w+0]=_,r[w+1]=x,r[w+2]=L,r[w+3]=k}}},ac=function(s,e,t){const i=s.data,r=e.data,n=s.width,a=s.height,o=t.polarCenterX||n/2,l=t.polarCenterY||a/2;let c=Math.sqrt(o*o+l*l),h=n-o,d=a-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const f=a,g=n,y=0;let S,C;for(h=0;h<n;h+=1)for(d=0;d<a;d+=1){const v=h-o,T=d-l,w=Math.sqrt(v*v+T*T)*f/c;let _=(Math.atan2(T,v)*180/Math.PI+360+y)%360;_=_*g/360,S=Math.floor(_),C=Math.floor(w);let x=(C*n+S)*4;const L=i[x+0],k=i[x+1],M=i[x+2],P=i[x+3];x=(d*n+h)*4,r[x+0]=L,r[x+1]=k,r[x+2]=M,r[x+3]=P}},oc=function(s){const e=s.width,t=s.height;let i,r,n,a,o,l,c,h,d,u,f=Math.round(this.kaleidoscopePower());const g=Math.round(this.kaleidoscopeAngle()),y=Math.floor(e*(g%360)/360);if(f<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),sc(s,C,{polarCenterX:e/2,polarCenterY:t/2});let v=e/Math.pow(2,f);for(;v<=8;)v=v*2,f-=1;v=Math.ceil(v);let T=v,w=0,_=T,x=1;for(y+v>e&&(w=T,_=0,x=-1),r=0;r<t;r+=1)for(i=w;i!==_;i+=x)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(T=Math.floor(v),a=0;a<f;a+=1){for(i=0;i<T+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+T*2-i-1)*4,C.data[u+0]=o,C.data[u+1]=l,C.data[u+2]=c,C.data[u+3]=h;T*=2}ac(C,s,{})};m.addGetterSetter(E,"kaleidoscopePower",2,R(),m.afterSetFilter);m.addGetterSetter(E,"kaleidoscopeAngle",0,R(),m.afterSetFilter);function wi(s,e,t){let i=(t*s.width+e)*4;const r=[];return r.push(s.data[i++],s.data[i++],s.data[i++],s.data[i++]),r}function Ot(s,e){return Math.sqrt(Math.pow(s[0]-e[0],2)+Math.pow(s[1]-e[1],2)+Math.pow(s[2]-e[2],2))}function lc(s){const e=[0,0,0];for(let t=0;t<s.length;t++)e[0]+=s[t][0],e[1]+=s[t][1],e[2]+=s[t][2];return e[0]/=s.length,e[1]/=s.length,e[2]/=s.length,e}function cc(s,e){const t=wi(s,0,0),i=wi(s,s.width-1,0),r=wi(s,0,s.height-1),n=wi(s,s.width-1,s.height-1),a=e||10;if(Ot(t,i)<a&&Ot(i,n)<a&&Ot(n,r)<a&&Ot(r,t)<a){const o=lc([i,t,n,r]),l=[];for(let c=0;c<s.width*s.height;c++){const h=Ot(o,[s.data[c*4],s.data[c*4+1],s.data[c*4+2]]);l[c]=h<a?0:255}return l}}function hc(s,e){for(let t=0;t<s.width*s.height;t++)s.data[4*t+3]=e[t]}function dc(s,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),a=[];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 f=o+d-n,g=l+u-n;if(f>=0&&f<t&&g>=0&&g<e){const y=f*e+g,S=i[d*r+u];h+=s[y]*S}}a[c]=h===255*8?255:0}return a}function uc(s,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),a=[];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 f=o+d-n,g=l+u-n;if(f>=0&&f<t&&g>=0&&g<e){const y=f*e+g,S=i[d*r+u];h+=s[y]*S}}a[c]=h>=255*4?255:0}return a}function pc(s,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),a=[];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 f=o+d-n,g=l+u-n;if(f>=0&&f<t&&g>=0&&g<e){const y=f*e+g,S=i[d*r+u];h+=s[y]*S}}a[c]=h}return a}const fc=function(s){const e=this.threshold();let t=cc(s,e);return t&&(t=dc(t,s.width,s.height),t=uc(t,s.width,s.height),t=pc(t,s.width,s.height),hc(s,t)),s};m.addGetterSetter(E,"threshold",0,R(),m.afterSetFilter);const gc=function(s){const e=this.noise()*255,t=s.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(E,"noise",.2,R(),m.afterSetFilter);const mc=function(s){let e=Math.ceil(this.pixelSize()),t=s.width,i=s.height,r=Math.ceil(t/e),n=Math.ceil(i/e),a=s.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 f=o*e,g=f+e,y=l*e,S=y+e;let C=0;for(let v=f;v<g;v+=1)if(!(v>=t))for(let T=y;T<S;T+=1){if(T>=i)continue;const w=(t*T+v)*4;c+=a[w+0],h+=a[w+1],d+=a[w+2],u+=a[w+3],C+=1}c=c/C,h=h/C,d=d/C,u=u/C;for(let v=f;v<g;v+=1)if(!(v>=t))for(let T=y;T<S;T+=1){if(T>=i)continue;const w=(t*T+v)*4;a[w+0]=c,a[w+1]=h,a[w+2]=d,a[w+3]=u}}};m.addGetterSetter(E,"pixelSize",8,R(),m.afterSetFilter);const yc=function(s){const e=Math.round(this.levels()*254)+1,t=s.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(E,"levels",.5,R(),m.afterSetFilter);const Sc=function(s){const e=s.data,t=e.length,i=this.red(),r=this.green(),n=this.blue();for(let a=0;a<t;a+=4){const o=(.34*e[a]+.5*e[a+1]+.16*e[a+2])/255;e[a]=o*i,e[a+1]=o*r,e[a+2]=o*n,e[a+3]=e[a+3]}};m.addGetterSetter(E,"red",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});m.addGetterSetter(E,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});m.addGetterSetter(E,"blue",0,Bs,m.afterSetFilter);const vc=function(s){const e=s.data,t=e.length,i=this.red(),r=this.green(),n=this.blue(),a=this.alpha();for(let o=0;o<t;o+=4){const l=1-a;e[o]=i*a+e[o]*l,e[o+1]=r*a+e[o+1]*l,e[o+2]=n*a+e[o+2]*l}};m.addGetterSetter(E,"red",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});m.addGetterSetter(E,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});m.addGetterSetter(E,"blue",0,Bs,m.afterSetFilter);m.addGetterSetter(E,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const Cc=function(s){const e=s.data,t=e.length;for(let i=0;i<t;i+=4){const r=e[i+0],n=e[i+1],a=e[i+2];e[i+0]=Math.min(255,r*.393+n*.769+a*.189),e[i+1]=Math.min(255,r*.349+n*.686+a*.168),e[i+2]=Math.min(255,r*.272+n*.534+a*.131)}},bc=function(s){const t=s.data;for(let i=0;i<t.length;i+=4){const r=t[i],n=t[i+1],a=t[i+2];.2126*r+.7152*n+.0722*a>=128&&(t[i]=255-r,t[i+1]=255-n,t[i+2]=255-a)}return s},Tc=function(s){const e=this.threshold()*255,t=s.data,i=t.length;for(let r=0;r<i;r+=1)t[r]=t[r]<e?0:255};m.addGetterSetter(E,"threshold",.5,R(),m.afterSetFilter);const K=_n.Util._assign(_n,{Arc:Fe,Arrow:pt,Circle:At,Ellipse:Qe,Image:Ie,Label:rn,Tag:ft,Line:Ge,Path:ie,Rect:hi,RegularPolygon:et,Ring:gt,Sprite:Le,Star:tt,Text:re,TextPath:he,Transformer:W,Wedge:He,Filters:{Blur:jl,Brightness:Zl,Brighten:Kl,Contrast:Jl,Emboss:Ql,Enhance:ec,Grayscale:tc,HSL:ic,HSV:rc,Invert:nc,Kaleidoscope:oc,Mask:fc,Noise:gc,Pixelate:mc,Posterize:yc,RGB:Sc,RGBA:vc,Sepia:Cc,Solarize:bc,Threshold:Tc}}),fa="media-editor-track.diagnostics.v1",Lr="media-editor-track.diagnostics.failure-window.v1",ga="media-editor-track-diagnostics",Ke="snapshots",ma="state",ya="latest-failure-window",ri=1,nn=1,Hn=40,wc=48,kc=250,Nn=20,xc=100,Pc=500,Or=new Set(["pending-preview.begin","preview.sync.requested","media.seeking","media.seeked"]),_c=new Set([...Or,"media.current-slot.seek","media.preload-slot.seek","media.play.requested","media.pause.requested","slot.recovery-check","runtime.state"]),$n={debug:10,info:20,warn:30,error:40},Ne={enabled:!0,persist:!0,storageQuotaMb:10,maxSessions:20,maxHotEvents:500,includeFullSourceUrl:!0,consoleSeverityThreshold:"warn",highFrequencyEventThrottleMs:Pc};function zn(s){return`${s}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ac(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function Sa(s){if(!s||typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function kt(s,e,t){if(s==null||typeof s=="string"||typeof s=="number"||typeof s=="boolean")return s??null;if(typeof s=="bigint")return s.toString();if(s instanceof Error)return{name:s.name,message:s.message,stack:s.stack??null,cause:kt(s.cause,e+1,t)};if(e>=4)return"[max-depth]";if(Array.isArray(s))return s.slice(0,40).map(i=>kt(i,e+1,t));if(typeof s=="object"){if(t.has(s))return"[circular]";if(t.add(s),"tagName"in s&&typeof s.tagName=="string")return{tagName:s.tagName};if(!Sa(s))return String(s);const i={};for(const r of Object.keys(s).slice(0,60))i[r]=kt(s[r],e+1,t);return i}return String(s)}function Hi(s){if(!s)return null;const e=kt(s,0,new WeakSet);return Sa(e)?e:{value:e}}function Ic(s){return Hi(s)}function Bt(s){return typeof s=="number"&&Number.isFinite(s)?s:null}function ki(s){return typeof s=="string"&&s.length>0?s:null}function Ec(){var i,r,n,a,o;const s=typeof navigator<"u"?navigator:null,e={platform:ki(s==null?void 0:s.platform),hardwareConcurrency:Bt(s==null?void 0:s.hardwareConcurrency),deviceMemory:Bt(s==null?void 0:s.deviceMemory),maxTouchPoints:Bt(s==null?void 0:s.maxTouchPoints),language:ki(s==null?void 0:s.language),languages:Array.isArray(s==null?void 0:s.languages)?s.languages.filter(l=>typeof l=="string"):null},t={online:typeof(s==null?void 0:s.onLine)=="boolean"?s.onLine:null,effectiveType:ki((i=s==null?void 0:s.connection)==null?void 0:i.effectiveType),downlinkMbps:Bt((r=s==null?void 0:s.connection)==null?void 0:r.downlink),rttMs:Bt((n=s==null?void 0:s.connection)==null?void 0:n.rtt),saveData:typeof((a=s==null?void 0:s.connection)==null?void 0:a.saveData)=="boolean"?s.connection.saveData:null,connectionType:ki((o=s==null?void 0:s.connection)==null?void 0:o.type)};return{hardware:e,network:t}}function Vn(s,e={}){const t=Ec(),i=Hi(s??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 Rc(s){return s?s instanceof Error?{name:s.name,message:s.message,stack:s.stack??null,cause:kt(s.cause,1,new WeakSet)}:{name:null,message:typeof s=="string"?s:String(s),stack:null,cause:kt(s,1,new WeakSet)}:null}function Zt(){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 Mc(s){const e=s??Zt();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 va(s){const e=Zt();return s.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 Un(s){return Mc(s.summary)}function Dc(s){return{sequence:s.sequence,timestamp:s.timestamp,isoTime:s.isoTime,severity:s.severity,category:s.category,eventName:s.eventName,message:s.message,syncRequestId:s.syncRequestId,playbackAttemptId:s.playbackAttemptId,trackId:s.trackId,clipId:s.clipId,extra:s.extra,error:s.error}}function Lc(s,e){s.totalEvents+=1,s.severityCounts[e.severity]+=1,s.categoryCounts[e.category]+=1,e.severity==="error"&&(s.failureCount+=1,s.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 Oc(s){return{enabled:(s==null?void 0:s.enabled)??Ne.enabled,persist:(s==null?void 0:s.persist)??Ne.persist,storageQuotaMb:(s==null?void 0:s.storageQuotaMb)??Ne.storageQuotaMb,maxSessions:Math.max(1,(s==null?void 0:s.maxSessions)??Ne.maxSessions),maxHotEvents:Math.max(20,(s==null?void 0:s.maxHotEvents)??Ne.maxHotEvents),includeFullSourceUrl:(s==null?void 0:s.includeFullSourceUrl)??Ne.includeFullSourceUrl,consoleSeverityThreshold:(s==null?void 0:s.consoleSeverityThreshold)??Ne.consoleSeverityThreshold,highFrequencyEventThrottleMs:Math.max(0,(s==null?void 0:s.highFrequencyEventThrottleMs)??Ne.highFrequencyEventThrottleMs)}}function Bc(){try{if(typeof globalThis.localStorage>"u")return null;const s=globalThis.localStorage.getItem(fa);if(!s)return null;const e=JSON.parse(s);return(e==null?void 0:e.version)!==ri||!Array.isArray(e.sessions)?null:e}catch{return null}}function Fc(){try{if(typeof globalThis.localStorage>"u")return null;const s=globalThis.localStorage.getItem(Lr);if(!s)return null;const e=JSON.parse(s);return(e==null?void 0:e.version)!==nn||typeof e.sessionId!="string"||typeof e.failureEventId!="string"||!Array.isArray(e.events)?null:e}catch{return null}}function Ca(s){const e=Array.isArray(s.events)?s.events:[];return{...s,updatedAt:s.updatedAt||s.startedAt,events:e,summary:va(e)}}function Ft(s,e,t={}){const i=s.slice(-e.maxSessions).map(n=>{const a=n.events.slice(-e.maxHotEvents);return Ca({...n,events:a,updatedAt:n.updatedAt||n.startedAt})});if(!t.enforceStorageQuota)return i;const r=Math.max(2e5,Math.floor(e.storageQuotaMb*1024*1024));for(;i.length>0&&JSON.stringify({version:ri,sessions:i}).length>r;)i.shift();return i}async function Gc(s){return ba(ma,s)}async function Hc(s){return ba(ya,s)}async function ba(s,e){if(typeof indexedDB>"u")return!1;try{const t=await new Promise((i,r)=>{const n=indexedDB.open(ga,1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains(Ke)||a.createObjectStore(Ke)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)});return await new Promise((i,r)=>{const n=t.transaction(Ke,"readwrite");n.objectStore(Ke).put(e,s),n.oncomplete=()=>i(),n.onerror=()=>r(n.error),n.onabort=()=>r(n.error)}),t.close(),!0}catch{return!1}}async function Nc(){const s=await Ta(ma);return s&&typeof s=="object"&&"version"in s&&s.version===ri&&"sessions"in s&&Array.isArray(s.sessions)?s:null}async function $c(){const s=await Ta(ya);return s&&typeof s=="object"&&"version"in s&&s.version===nn&&"sessionId"in s&&typeof s.sessionId=="string"&&"failureEventId"in s&&typeof s.failureEventId=="string"&&"events"in s&&Array.isArray(s.events)?s:null}async function Ta(s){if(typeof indexedDB>"u")return null;try{const e=await new Promise((i,r)=>{const n=indexedDB.open(ga,1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains(Ke)||a.createObjectStore(Ke)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)}),t=await new Promise((i,r)=>{const o=e.transaction(Ke,"readonly").objectStore(Ke).get(s);o.onsuccess=()=>i(o.result??null),o.onerror=()=>r(o.error)});return e.close(),t}catch{return null}}function zc(s,e){return!s&&!e?null:{...s??{},...e??{}}}class wa{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);p(this,"highFrequencyEventTimestamps",new Map);this.config=Oc(e);const t=Bc();this.latestFailureWindow=Fc(),this.state={version:ri,sessions:Ft((t==null?void 0:t.sessions)??[],this.config,{enforceStorageQuota:this.config.persist})},this.restoreIndexedDbState()}startSession(e){const t=new Date().toISOString(),i={sessionId:zn("diag-session"),startedAt:Date.now(),updatedAt:Date.now(),metadata:Vn(e,{capturedAt:t}),sequence:0,events:[],summary:Zt()};return this.currentSessionId=i.sessionId,this.state.sessions=Ft([...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.resolveHighFrequencyDecision(e,i);if(r==="drop")return null;const n=this.findCoalescedEvent(t,e,i);if(n)return r==="skip-update"||(this.updateCoalescedEvent(n,e,i),this.schedulePersist(),this.scheduleNotify()),n;t.sequence+=1;const a=this.createEvent(t,e,i,t.sequence);return t.events.push(a),Lc(t.summary,a),this.trimSessionEvents(t),this.captureFailureWindow(t,a),this.state.sessions=Ft(this.state.sessions,this.config),this.emitToConsole(a),this.schedulePersist(),this.scheduleNotify(),a}subscribe(e){return this.listeners.add(e),e(this.getSnapshot()),()=>{this.listeners.delete(e)}}subscribeLive(e,t=Nn){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:Un(t)}}getLiveSnapshot(e=this.currentSessionId,t=Nn){const i=this.resolveSession(e),r=Math.max(1,t);return{sessionId:i.sessionId,startedAt:i.startedAt,updatedAt:i.updatedAt,metadata:i.metadata,summary:Un(i),recentEvents:i.events.slice(-r).map(n=>Dc(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:a,failureWindowSource:o}=this.resolveExportFailureWindow(t,i,r),l=Vn(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:a,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:Zt()}}createEvent(e,t,i,r,n=zn("diag-event")){return{eventId:n,sessionId:e.sessionId,sequence:r,timestamp:i,isoTime:new Date(i).toISOString(),perfTimeMs:Ac(),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:Hi(t.mediaState),runtimeState:Ic(t.runtimeState),error:Rc(t.error),extra:Hi(t.extra)}}trimSessionEvents(e){const t=e.events.length-this.config.maxHotEvents;t<=0||(e.events=e.events.slice(t),e.summary=va(e.events))}findCoalescedEvent(e,t,i){if(!Or.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 a=e.events[n];if(i-a.timestamp>xc)break;if(this.areEventIdentitiesEqual(r,a))return a}return null}resolveHighFrequencyDecision(e,t){if(e.severity==="warn"||e.severity==="error"||!_c.has(e.eventName))return"record";const i=this.config.highFrequencyEventThrottleMs;if(i<=0)return"record";const r=this.buildHighFrequencyKey(e),n=this.highFrequencyEventTimestamps.get(r);return n!==void 0&&t-n<i?Or.has(e.eventName)?"skip-update":"drop":(this.highFrequencyEventTimestamps.set(r,t),"record")}buildHighFrequencyKey(e){const t=this.buildEventIdentity(e);return[t.eventName,t.playbackAttemptId??"",t.trackId??"",t.clipId??"",t.slotKey??"",t.syncRequestId??""].join("|")}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:Zt()},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($n[e.severity]<$n[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()},wc))}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()},kc)))}persistNow(){if(!this.config.persist)return;const e={version:ri,sessions:Ft(this.state.sessions,this.config,{enforceStorageQuota:!0})};if(this.state=e,typeof indexedDB>"u"){this.persistToLocalStorage(e);return}Promise.all([Gc(e),Hc(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([Nc(),$c()]);if((i=e==null?void 0:e.sessions)!=null&&i.length){const n=new Map;[...this.state.sessions,...e.sessions].forEach(a=>{const o=Ca(a),l=n.get(o.sessionId);(!l||l.updatedAt<o.updatedAt)&&n.set(o.sessionId,o)}),this.state.sessions=Ft(Array.from(n.values()).sort((a,o)=>a.startedAt-o.startedAt),this.config,{enforceStorageQuota:!0})}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:Hn}),!this.activeFailureCapture||this.activeFailureCapture.sessionId!==e.sessionId)return;const i=this.buildFailureWindow(e,this.activeFailureCapture.failureEventId);i.length&&(this.latestFailureWindow={version:nn,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=Hn){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,a=n?e.events.slice(Math.max(0,n.index-t),Math.min(e.events.length,n.index+t+1)):[];return n?{failureWindow:a,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(fa,JSON.stringify(e)),t!==void 0)){if(t){globalThis.localStorage.setItem(Lr,JSON.stringify(t));return}globalThis.localStorage.removeItem(Lr)}}}function ka(s,e){return zc(s,e)}function Wn(s,e,t,i){const r=`[${s.toUpperCase()}] [${e}]`;if(i===void 0){console[s](`${r} ${t}`);return}console[s](`${r} ${t}`,i)}const F={debug(s,e,t){},debugLazy(s,e,t){},warn(s,e,t){Wn("warn",s,e,t)},error(s,e,t){Wn("error",s,e,t)}};class Pe{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={},this.brokenImageUrls.clear()}static renderClipCovers(e,t,i,r,n,a=!1){F.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(),a||this.requestRender(e);return}const l=this.buildSegmentsDataSync(t,i,r,n);if(l){this.renderSegments(e,l,i,r),a||this.requestRender(e);return}a||(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:a,version:o}=e,l=await this.buildSegmentsData(i,r,n,a);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,a=r||e[0]||"",o=await this.getSafeKeyframeDimensions(a,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 f=0;f<h;f++)d.push(Math.round(f*(n-1)/(h-1)));const u=[];for(let f=0;f<h;f++){const g=e[d[f]];u.push({coverUrl:g,singleImageWidth:c,segmentStartX:f*c,segmentWidth:c})}return u}static buildSegmentsDataSync(e,t,i,r){const n=e.length,a=r||e[0]||"",o=this.getCachedKeyframeDimensions(a,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 f=0;f<h;f++)d.push(Math.round(f*(n-1)/(h-1)));const u=[];for(let f=0;f<h;f++){const g=e[d[f]];u.push({coverUrl:g,singleImageWidth:c,segmentStartX:f*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:a,segmentStartX:o,segmentWidth:l}of t){const c=Math.max(a,.01),h=this.getCachedImage(n),d=new K.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 K.Image({image:h,cornerRadius:2,name:"cover-image",visible:this.isImageRenderable(n,h)});u.x(0),u.y(0),u.width(c),u.height(r),this.bindCoverImageLifecycle(n,h,u,e),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 a=this.getCachedImage(t);if(this.isImageRenderable(t,a)){const l={width:a.width,height:a.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)};this.listenToImageEvent(a,"load",()=>{this.brokenImageUrls.delete(t);const l={width:a.width,height:a.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},{once:!0}),this.listenToImageEvent(a,"error",()=>{this.brokenImageUrls.add(t),o(this.DEFAULT_DIMENSIONS)},{once:!0}),a.src||(a.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 a={width:n.width,height:n.height};return this.keyframeDimensionsCache[i]=a,a}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(a=>{const o=this.imageCache[a];return o&&!o.complete}),r=e.filter(a=>!i.includes(a));let n=0;for(const a of i){if(n>=t)break;this.evictCacheKey(a),n++}for(const a of r){if(n>=t)break;this.evictCacheKey(a),n++}}static evictCacheKey(e){delete this.imageCache[e],delete this.keyframeDimensionsCache[e],delete this.keyframeDimensionsPromiseCache[e],this.brokenImageUrls.delete(e)}static bindCoverImageLifecycle(e,t,i,r){this.listenToImageEvent(t,"load",()=>{this.brokenImageUrls.delete(e);try{i.visible(this.isImageRenderable(e,t)),this.requestRender(r)}catch{}}),this.listenToImageEvent(t,"error",()=>{this.brokenImageUrls.add(e);try{i.visible(!1),this.requestRender(r)}catch{}})}static isImageRenderable(e,t){if(this.brokenImageUrls.has(e)||!t.complete)return!1;const i=typeof t.naturalWidth=="number"?t.naturalWidth:t.width,r=typeof t.naturalHeight=="number"?t.naturalHeight:t.height;return i>0&&r>0}static listenToImageEvent(e,t,i,r){typeof e.addEventListener=="function"&&e.addEventListener(t,i,r)}}p(Pe,"MIN_IMAGE_DISPLAY_WIDTH",24),p(Pe,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),p(Pe,"MAX_CACHE_SIZE",1e3),p(Pe,"DEFAULT_DIMENSIONS",{width:160,height:90}),p(Pe,"keyframeDimensionsCache",{}),p(Pe,"keyframeDimensionsPromiseCache",{}),p(Pe,"imageCache",{}),p(Pe,"brokenImageUrls",new Set);const Vc='<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>',Uc='<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>',Wc='<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>',Yc='<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>',Xc='<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>',qc='<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>',jc='<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>',Kc='<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>',Zc='<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>',Jc='<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>',Qc='<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>',eh=new Map([["OmAi-camera",Vc],["OmAi-accept",Uc],["OmAi-display",Wc],["OmAi-hide",Yc],["OmAi-loading",Xc],["OmAi-music",qc],["OmAi-volume",jc],["OmAi-volume-mute",Kc],["OmAi-text",Zc],["clip-audio",Jc],["clip-without-audio",Qc]]),Yn=new Map;function ve(s){return eh.get(s)??""}function th(s){const e=Yn.get(s);if(e)return e;const t=ve(s);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,Yn.set(s,r),r}const ue=3,Xn=10,ih=4,rh=6,qn=8,jn=14,Br=10,nh=12,sh=4,xa=1,Ni=28,Pa=8,Fr=19,Gr=15;function ni(s,e,t,i,r=I.white,n=I.black,a=1){return new K.Rect({x:s,y:e,width:t,height:i,fill:r,stroke:n,strokeWidth:a})}function $i(s,e,t,i=12,r="Arial",n=I.black,a="left",o="top"){return new K.Text({text:s,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:a,verticalAlign:o})}function Pt(s=0,e=0){return new K.Group({x:s,y:e})}function si(s){s.ellipsis(!1),s.wrap("none"),s.width("auto")}function Ji(s,e,t,i){if(i){s.add(new K.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),s.add(new K.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}s.add(new K.Rect({x:0,y:0,width:ue,height:t,name:"clip-resize-left"})),s.add(new K.Rect({x:e-ue,y:0,width:ue,height:t,name:"clip-resize-right"}))}function ah(s,e,t,i){const r=s.findOne(".clip-resize-left"),n=s.findOne(".clip-resize-right");return!r||!n?!1:(r.x(0),r.y(0),r.width(ue),r.height(t),n.x(e-ue),n.y(0),n.width(ue),n.height(t),!0)}function _a(s,e,t){const i=e?s.clipSelectedBorder:I.transparent,r=e?xa:0;return t==="audio"?{background:I.audioClipBackground,label:s.audioClipText||s.clipName,accent:s.audioClipAccent||s.clipHandle,coverBackground:s.clipCoverBackground||Q.clipCoverBackground,border:i,borderWidth:r}:t==="text"?{background:I.textClipBackground,label:s.clipName,accent:s.clipHandle,coverBackground:s.clipCoverBackground||I.accentCoverFallback,border:i,borderWidth:r}:{background:I.videoClipBackground,label:s.clipName,accent:s.clipHandle,coverBackground:s.clipCoverBackground||I.accentCoverFallback,border:i,borderWidth:r}}function oh(s,e,t,i){const r=ni(0,0,e,t,i.background,i.border,i.borderWidth);r.cornerRadius(Math.min(4,Math.floor(e/2))),r.name("clip-background"),s.add(r),Ji(s,e,t,!0)}function lh(s,e,t){const i=ni(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),s.add(i),Ji(s,e.width,e.height,!1);const r=15,n=e.height-r-4,a=e.width-ue*2,o=Pt(ue,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:a,height:n}),s.add(o);const l=ni(0,0,a,n,t.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const c=Pt(0,0);c.name("clip-covers-group"),o.add(c),Pe.renderClipCovers(c,e.thumbnails??[],a,n,e.videoSrc,e.deferCoverRender);const h=a>=120?Ni+Pa:0,d=$i(`${e.clipName} ${Y.formatDuration(e.duration)}`,ue,e.height-r,Br,"Arial",t.label,"left","middle");d.height(r),si(d),d.name("clip-label"),s.add(d),h>0&&Ia(s,e.width,e.height,e.hasSeparatedAudio)}function ch(s,e,t){const i=s.findOne(".clip-background"),r=s.findOne(".clip-cover-container"),n=s.findOne(".clip-cover-background"),a=s.findOne(".clip-covers-group"),o=s.findOne(".clip-label");if(!i||!r||!n||!a||!o||(i.width(e.width),i.height(e.height),i.fill(t.background),i.stroke(t.border),i.strokeWidth(t.borderWidth),i.cornerRadius(4),!ah(s,e.width,e.height)))return!1;const l=15,c=e.height-l-4,h=e.width-ue*2;r.x(ue),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),Pe.renderClipCovers(a,e.thumbnails??[],h,c,e.videoSrc,e.deferCoverRender);const d=h>=120?Ni+Pa:0;o.text(`${e.clipName} ${Y.formatDuration(e.duration)}`),o.x(ue),o.y(e.height-l),o.fill(t.label),o.height(l),si(o);const u=s.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&Ia(s,e.width,e.height,e.hasSeparatedAudio),!0}function hh(s,e){e.complete&&e.naturalWidth>0||e.addEventListener("load",()=>{var t,i;(i=(t=s.getLayer)==null?void 0:t.call(s))==null||i.batchDraw()},{once:!0})}function Aa(s,e,t,i,r){s.name()||s.name(r);const n=th(e);if(!n)return 0;const a=new K.Image({x:0,y:0,width:t,height:i,image:n,listening:!1});return a.name(`${r}-image`),s.add(a),hh(s,n),t}function Ia(s,e,t,i){const r=Pt(Math.max(ue,e-ue-Ni-2),Math.max(0,t-15));r.name("video-audio-status");const n=Pt(Math.max(0,Ni-Fr),0),a=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";n.name(a),Aa(n,o,Fr,Gr,`${a}-icon`),r.add(n),s.add(r)}function dh(s,e,t){const i=ni(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(6),i.name("clip-background"),s.add(i),Ji(s,e.width,e.height,!1);const r=ue+Xn,n=Math.max(0,e.width-ue*2-Xn*2),a=ih,o=Pt(r,a),l=Aa(o,"clip-audio",Fr,Gr,"audio-clip-icon");s.add(o);const c=r+l+qn,h=Math.max(0,n-l-qn);if(e.audioBadgeText&&h>0){const u=$i(e.audioBadgeText,c,a,Br,"Arial",t.label,"left","middle");u.height(Gr),si(u),u.name("audio-clip-badge"),s.add(u)}const d=$i(e.clipName,r,e.height-rh-jn,Br,"Arial",t.label,"left","middle");d.height(jn),si(d),d.name("clip-label"),s.add(d)}function uh(s,e,t){const i=ni(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),s.add(i),Ji(s,e.width,e.height,!1);const r=$i(e.clipName,sh,0,nh,"Arial",t.label,"left","middle");r.height(e.height),r.lineHeight(1),si(r),r.name("clip-label"),s.add(r)}function Ea(s,e){const t=e.width<=ti,i=_a(e.theme,e.isSelected,e.clipType);if(s.destroyChildren(),t){oh(s,e.width,e.height,i);return}if(e.clipType==="audio"){dh(s,e,i);return}if(e.clipType==="text"){uh(s,e,i);return}lh(s,e,i)}function ph(s,e){if(e.width<=ti||e.clipType!=="video")return!1;const i=_a(e.theme,e.isSelected,e.clipType);return ch(s,e,i)}function fh(s,e,t,i,r,n,a,o=!1,l,c,h="video",d=!1,u=!1,f){const g=Pt(s,e);return g.clip({x:0,y:0,width:t,height:i}),Ea(g,{width:t,height:i,clipName:r,audioBadgeText:f,duration:n,theme:a,isSelected:o,thumbnails:l,videoSrc:c,clipType:h,hasSeparatedAudio:d,deferCoverRender:u}),g}function gh(s,e,t,i,r,n,a=!1,o,l,c="video",h=!1,d=!1,u){s.clip({x:0,y:0,width:e,height:t});const f={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:n??Bi,isSelected:a,thumbnails:o,videoSrc:l,clipType:c,hasSeparatedAudio:h,deferCoverRender:d};ph(s,f)||Ea(s,f)}function mh(s,e,t,i){return new K.Rect({x:s,y:e,width:t,height:i,stroke:I.clipSelectedBorder,strokeWidth:xa,fillEnabled:!1})}function Hr(s,e=bt.stroke,t=1){return new K.Line({points:s,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function yh(s,e,t,i=12,r="Arial",n=bt.text,a="left",o="top"){return new K.Text({text:s,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:a,verticalAlign:o})}function Sh(s=0,e=0){return new K.Group({x:s,y:e})}function vh(s,e,t,i,r,n,a,o){const l=o||i,c=a==="major"?l*.6:l*.3,h=Hr([e,t,e,t+c],n.timeTick,a==="major"?1:.5);if(h.name("time-tick-line"),s.add(h),a==="major"){const d=t+c+5,u=yh(Y.formatTime(r),e,d,10,"Arial",n.timeText,"center");u.name("time-tick-text"),s.add(u)}}function Ch(s,e,t,i,r,n){const a=Sh(e,t);for(let o=0;o<=i;o+=n)a.add(Hr([o,0,o,r],dn.line,.5));for(let o=0;o<=r;o+=n)a.add(Hr([0,o,i,o],dn.line,.5));s.add(a)}class de{static createStage(e,t,i){return new K.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new K.Layer;return t.name(e),t}static createRect(e,t,i,r,n=bt.fill,a=bt.stroke,o=1){return new K.Rect({x:e,y:t,width:i,height:r,fill:n,stroke:a,strokeWidth:o})}static createText(e,t,i,r=12,n="Arial",a=bt.text,o="left",l="top"){return new K.Text({text:e,x:t,y:i,fontSize:r,fontFamily:n,fill:a,align:o,verticalAlign:l})}static createLine(e,t=bt.stroke,i=1){return new K.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new K.Group({x:e,y:t})}static drawTimeTick(e,t,i,r,n,a,o,l){vh(e,t,i,r,n,a,o,l)}static drawGrid(e,t,i,r,n,a){Ch(e,t,i,r,n,a)}static clearImageCache(){Pe.clearImageCache()}static createClipGroup(e,t,i,r,n,a,o,l=!1,c,h,d="video",u=!1,f=!1,g){return fh(e,t,i,r,n,a,o,l,c,h,d,u,f,g)}static updateClipGroup(e,t,i,r,n,a,o=!1,l,c,h="video",d=!1,u=!1,f){gh(e,t,i,r,n,a,o,l,c,h,d,u,f)}static createSelectionEffect(e,t,i,r){return mh(e,t,i,r)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}p(de,"RESIZE_AREA_WIDTH",3);const Yt=8;function me(s,e,t){return de.timeToPixels(s,e)-t+Te}function Ce(s,e){const t=Math.max(s,0),i=de.timeToPixels(t,e);return i<=ti?ti:i}function bh(s,e){const t=me(s.startTime,s.zoom,s.scrollLeft),i=Ce(s.duration,s.zoom);return t+i>0&&t<e}function Th(s){for(const e of s.clips){const t=me(e.startTime,s.zoom,s.scrollLeft),i=Ce(e.duration,s.zoom),r=s.y>=s.trackY&&s.y<=s.trackY+s.trackHeight;if(s.x>=t&&s.x<=t+Yt&&r||s.x>=t+i-Yt&&s.x<=t+i&&r)return"ew-resize";if(s.x>t+Yt&&s.x<t+i-Yt&&r)return"pointer"}return"default"}class Mi{constructor(e,t,i){p(this,"clip");p(this,"onUpdate");p(this,"onSplit");this.clip=Kr({...e,endTime:Y.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:Y.calculateEndTime(e.startTime,e.duration)}}setSelected(e){this.clip={...this.clip,isSelected:e},this.onUpdate(this.clip)}isPointInResizeHandle(e,t,i,r,n,a){const o=me(this.clip.startTime,i,a),l=Ce(this.clip.duration,i),c=Yt;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 Qi(s){let e=!1;return typeof window<"u"&&(window.addEventListener("mousemove",s.onPointerMove),window.addEventListener("mouseup",s.onPointerEnd),window.addEventListener("blur",s.onWindowBlur||s.onPointerEnd),e=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",s.onVisibilityChange),e=!0),e}function er(s){typeof window<"u"&&(window.removeEventListener("mousemove",s.onPointerMove),window.removeEventListener("mouseup",s.onPointerEnd),window.removeEventListener("blur",s.onWindowBlur||s.onPointerEnd)),typeof document<"u"&&document.removeEventListener("visibilitychange",s.onVisibilityChange)}function zi(){return{kind:"idle"}}function Kn(s){return!!s&&s.kind!=="idle"}function Vi(s){return(s==null?void 0:s.kind)==="draggingMove"||(s==null?void 0:s.kind)==="draggingResizeLeft"||(s==null?void 0:s.kind)==="draggingResizeRight"}function St(s){return!s||s.kind==="idle"||s.kind==="boxSelecting"?null:s.context}function Ui(s){return!s||s.kind==="idle"||s.kind==="boxSelecting"?null:s.kind==="pressed"?s.operation:s.kind==="draggingResizeLeft"?"resize-left":s.kind==="draggingResizeRight"?"resize-right":"move"}function wh(s){const e=Ui(s);return e?e==="move"?"grabbing":"ew-resize":null}function xi(s,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(s.kind==="idle")return{state:s,effects:{}};if(s.kind==="boxSelecting")return e.type==="BOX_SELECT_MOVE"?{state:{kind:"boxSelecting",context:{...s.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:zi(),effects:{unbindGlobalListeners:!0,commit:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP",cleanup:!0}}:{state:s,effects:{}};if(e.type==="POINTER_MOVE"){const i=xh(s.context,e,Ui(s)||"move");return s.kind==="pressed"?Ph(s.context,e.activationThreshold,e.clientX,e.clientY)?{state:kh(s.operation,i),effects:{updatePreview:!0}}:{state:{...s,context:i},effects:{}}:{state:{...s,context:i},effects:{updatePreview:!0}}}if(e.type==="SCROLL_LEFT_CHANGED")return{state:s,effects:{updatePreview:Vi(s)}};const t=e.type==="POINTER_UP"&&Vi(s);return{state:zi(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function kh(s,e){return s==="resize-left"?{kind:"draggingResizeLeft",context:e}:s==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function xh(s,e,t){const i=t==="move";return{...s,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:i?e.localY:s.pointerStartY,crossTrackDragOffsetY:i?e.localY-s.pointerStartY:0}}function Ph(s,e,t,i){const r=t-s.pointerStartClientX,n=i-s.pointerStartClientY;return Math.hypot(r,n)>=Math.max(0,e)}const ce=class ce{constructor(e,t,i,r,n,a,o,l,c,h,d,u,f,g,y,S,C,v,T,w,_,x,L,k,M,P=ce.DEFAULT_DRAG_ACTIVATION_THRESHOLD,$=!1,G=ce.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",zi());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=>{Kn(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.interactionState;if(!Vi(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=St(e);if(!i||!r){this.stopEdgeAutoScroll();return}const n=i.getBoundingClientRect(),a=r.lastPointerClientX-n.left,o=this.calculateHorizontalAutoScrollVelocity(a,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=a,this.onClipUpdate=l,this.onClipAdd=c,this.onClipRemove=h,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=f,this.onHorizontalDragAutoScroll=g,this.onClipOverlap=y,this.onClipCrossTrackPreview=S,this.onClipCrossTrack=C,this.onClearDropPreview=v,this.onClearSelection=T,this.onSnapGuideChange=w,this.onClipToggleSelection=_,this.onSetSingleSelection=x,this.getMultiDragClipIds=L,this.onMultiDragMove=k,this.onMultiDragInteractionEnd=M,this.dragActivationThreshold=Math.max(0,P),this.enableClipSnap=$,this.clipSnapThreshold=Math.max(0,G),this.trackGroup=de.createGroup(0,n),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}initClips(){this.clips=this.config.clips.map(e=>{const t=new Mi(e,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));return this.createClipGroup(e),t})}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const e=de.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=Ce(e.duration,this.zoom),a=de.createRect(r,2,Math.max(n,1),Math.max(this.trackHeight-4,1),t,i,1);return a.dash([6,4]),a.cornerRadius(4),a.listening(!1),a.visible(r+n>0&&r<this.layer.width()),a}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 a=this.createDropPreviewRect(n);r=r||a.visible(),t.add(a)}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=Qi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(er({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,a=Math.max(0,Y.pixelsToTime(n-Te+this.scrollLeft,this.zoom));this.onTimeJump(a),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=Ce(e.duration,this.zoom),r=2,n=this.trackHeight-4,a=de.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));a.name(`clip-${e.id}`),a.on("click",o=>{this.handleClipClick(e.id,o.evt)}),a.on("mousedown",o=>{this.handleClipMouseDown(e.id,o.evt)}),a.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),a.on("mouseleave",()=>{this.handleClipMouseLeave()}),a.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(a),this.clipGroups.set(e.id,a)}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()})),a=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 f=u.getBoundingClientRect(),g=t.clientX-f.left,y=t.clientY-f.top;if(r){this.multiDragOriginalPositions.clear();for(const C of this.selectedClipIds){const v=this.clips.find(T=>T.getClip().id===C);if(v){const T=v.getClip();this.multiDragOriginalPositions.set(C,{startTime:T.startTime,duration:T.duration})}}}let S;c.isPointInResizeHandle(g,y,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(S=c.getClip().isResizingLeft?"resize-left":"resize-right",c.startResize({x:g,y})):(S="move",c.startDrag({x:g,y}),this.trackGroup.moveToTop()),this.applyInteractionTransition(xi(this.interactionState,{type:"POINTER_DOWN",operation:S,clipId:e,originalClipsState:n,nonDraggedClips:a,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:g,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=zi(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}resolveDraggedClipForInteraction(e=this.interactionState){const t=St(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,e.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const t=wh(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()}handleClipMoveEnd(e,t){var y,S,C;const i=t??this.interactionState,r=St(i)||{clipId:e.id,originalClipsState:[e],nonDraggedClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:0,crossTrackDragOffsetY:0},a=(Ui(i)||(e.isResizingLeft?"resize-left":e.isResizingRight?"resize-right":"move"))==="move",o=a&&this.multiDragOriginalPositions.size>0,l=(y=this.clipGroups)==null?void 0:y.get(e.id);if(l&&l.y(2),o){const v=this.multiDragOriginalPositions.get(e.id),T=v?e.startTime-v.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:e.id,deltaTime:T,targetTrackY:r.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:r.crossTrackDragOffsetY,isFinal:!0})){for(const M of this.selectedClipIds){const P=(S=this.clipGroups)==null?void 0:S.get(M);P==null||P.y(2)}this.multiDragOriginalPositions.clear();return}const w=[],_=[];for(const[k,M]of this.multiDragOriginalPositions){const P=this.clips.find(B=>B.getClip().id===k);if(!P)continue;const $=Math.max(0,M.startTime+T),G={...P.getClip(),startTime:$,endTime:$+M.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(k)};w.push(G);const U=r.originalClipsState.find(B=>B.id===k);U&&_.push(U);const z=(C=this.clipGroups)==null?void 0:C.get(k);z&&z.y(2)}const x=[];for(const k of this.clips){const M=k.getClip(),P=w.find($=>$.id===M.id);P?x.push(P):x.push({...M,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}x.sort((k,M)=>k.startTime-M.startTime),this.isVisualUpdate=!0;for(const k of x)this.clips.find(P=>P.getClip().id===k.id)&&this.handleClipUpdate(k);this.isVisualUpdate=!1;const L=_.map(k=>{const M=w.find(P=>P.id===k.id);return M&&(k.startTime!==M.startTime||k.duration!==M.duration)?{clipId:k.id,previousState:k,newState:M}:null}).filter(k=>k!==null);L.length>0&&this.onClipUpdate(e,_.find(k=>k.id===e.id),L),this.multiDragOriginalPositions.clear();return}if(a&&this.onClipCrossTrack&&this.config.id){const v=r.originalClipsState.find(w=>w.id===e.id)??null;if(this.onClipCrossTrack(e,v,r.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}const c=a?[...r.nonDraggedClips]:[];let h=!1;const d=e.startTime+e.duration;for(const v of c){const T=v.startTime+v.duration;if(e.startTime<T&&d>v.startTime){h=!0;break}}if(a&&h&&this.onClipOverlap&&this.config.id){const v=r.originalClipsState.find(T=>T.id===e.id)??null;this.onClipOverlap(e,this.config.id,v);return}const u=[...r.nonDraggedClips];let f=u.findIndex(v=>v.startTime>=e.startTime);f===-1&&(f=u.length),r.nonDraggedClips.forEach(v=>{v.isSelected=!1});const g={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};u.splice(f,0,g),this.updateAllClips(u),this.buildAndSendUpdates(g,u,r.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 a=t.find(o=>o.id===n.id);return a&&(n.startTime!==a.startTime||n.duration!==a.duration||n.opacity!==a.opacity)?{clipId:n.id,previousState:n,newState:a}: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(),a=e-n.left,o=t-n.top;r.style.cursor=Th({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:a,y:o})}isDragSessionActive(){return Kn(this.interactionState)}handleDragMove(e){const t=this.interactionState,i=this.layer.getStage(),r=i==null?void 0:i.container();if(!r)return;const n=r.getBoundingClientRect(),a=xi(t,{type:"POINTER_MOVE",clientX:e.clientX,clientY:e.clientY,localY:e.clientY-n.top,activationThreshold:this.dragActivationThreshold});this.interactionState=a.state,a.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=Ce(e.duration,this.zoom);this.updateClipViewportState(e);const n=e.isSelected;(e.isDragging||n)&&i.moveToTop(),i.opacity(e.opacity),de.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 Mi(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,a={...e,duration:i,endTime:t,endTimeAtSource:n},o={...e,id:`${e.id}_split_${Date.now()}`,startTime:t,duration:r,endTime:Y.calculateEndTime(t,r),startTimeAtSource:n,endTimeAtSource:e.endTimeAtSource};this.removeClip(e.id),this.addClip(a),this.addClip(o),this.onClipSplit(a,o),this.layer.batchDraw()}addClip(e){if(e.type!==this.trackType){F.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new Mi(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){}setScrollLeft(e){this.scrollLeft=e,this.clips.forEach(n=>{const a=n.getClip();this.updateClipViewportState(a)});const t=this.interactionState,i=St(t),r=xi(t,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=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=bh({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=de.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 a;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??((a=this.selectedClip)==null?void 0:a.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(){F.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 a=t,o=a+r.duration;this.handleClipUpdate({...r,startTime:a,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 a=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(),de.updateClipGroup(o,Ce(a.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(a),a.duration,this.theme,!0,a.thumbnails,a.src,a.type,!!a.separatedAudioClipId,!0,this.getClipAudioBadgeText(a)),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw()}}updateClipPositionFinal(e,t){const i=this.clips.find(a=>a.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.interactionState,i=St(t);if(Vi(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var C,v,T,w,_;const r=this.interactionState,n=St(r),a=Ui(r),o=this.layer.getStage(),l=this.resolveDraggedClipForInteraction(r);if(!o||!l||!n||!a)return;const c=o.container();if(!c)return;const h=c.getBoundingClientRect(),d=e-h.left,u=t-h.top,f=a==="move",g=f&&this.multiDragOriginalPositions.size>0;f&&F.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 x=f&&n.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(y.id,x);const L=n.originalClipsState.find(B=>B.id===y.id);if(!L)return;const k=this.buildPreviewClip(y,L,d,n,a);if(!k){this.hideDropPreview(),(v=this.onClearDropPreview)==null||v.call(this),this.updateSnapGuideLine(null);return}const M=k.clip,P=M.startTime-L.startTime,$=this.applyPreviewClipState(l,M),G=me(M.startTime,this.zoom,this.scrollLeft),U=Ce(M.duration,this.zoom);S.x(G),S.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)),S.visible(G+U>0&&G<this.layer.width()),$&&(this.updateClipGroup(M),S.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)));let z=!1;if(g){this.onMultiDragMove&&this.config.id&&(z=this.onMultiDragMove({draggedClipId:y.id,deltaTime:P,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[B,O]of this.multiDragOriginalPositions){if(B===y.id)continue;const J=this.clips.find(ne=>ne.getClip().id===B);if(!J)continue;const N=Math.max(0,O.startTime+P),q=(T=this.clipGroups)==null?void 0:T.get(B);if(q){const ne=me(N,this.zoom,this.scrollLeft);q.x(ne),q.y(this.resolveClipRenderY(B,n.crossTrackDragOffsetY)),q.visible(ne+Ce(O.duration,this.zoom)>0&&ne<this.layer.width());const V=J.getClip();de.updateClipGroup(q,Ce(V.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(V),V.duration,this.theme,!0,V.thumbnails,V.src,V.type,!!V.separatedAudioClipId,!0,this.getClipAudioBadgeText(V))}}}f&&this.onClipCrossTrackPreview&&this.config.id&&!z?this.onClipCrossTrackPreview(M,n.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():z?this.hideDropPreview():this.showDropPreview(M),this.updateSnapGuideLine(k.guideTime)}else this.hideDropPreview(),(w=this.onClearDropPreview)==null||w.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(d,h.width),this.layer.batchDraw(),(_=this.dragOverlayLayer)==null||_.batchDraw()}buildPreviewClip(e,t,i,r,n){const a=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=Y.pixelsToTime(a,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,a=n-r,o=this.isSourceBoundClip(t)?{startTimeAtSource:t.endTimeAtSource-a,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:a,sourceDuration:a};return{clip:{...e.clip,startTime:r,duration:a,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 a=r-e.clip.startTime,o=this.isSourceBoundClip(t)?{endTimeAtSource:t.startTimeAtSource+a}:{startTimeAtSource:0,endTimeAtSource:a,sourceDuration:a};return{clip:{...e.clip,duration:a,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 f=Y.calculateEndTime(t.startTime,t.duration);let g=Math.max(0,t.startTime+i),y=f-g;return y<ce.MIN_CLIP_DURATION_MS&&(y=ce.MIN_CLIP_DURATION_MS,g=f-y),{...e,startTime:g,duration:y,endTime:g+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=Y.calculateEndTime(t.startTime,t.duration);let h=t.startTime+l,d=t.duration-l,u;return d<ce.MIN_CLIP_DURATION_MS?(d=ce.MIN_CLIP_DURATION_MS,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(ce.MIN_CLIP_DURATION_MS,t.duration+i);return{...e,startTime:t.startTime,duration:o,endTime:t.startTime+o,startTimeAtSource:0,endTimeAtSource:o,sourceDuration:o}}let r=Math.max(ce.MIN_CLIP_DURATION_MS,t.duration+i);const n=t.startTimeAtSource,a=Math.min(t.sourceDuration,n+r);return r=a-n,{...e,startTime:t.startTime,duration:r,endTime:t.startTime+r,startTimeAtSource:n,endTimeAtSource:a}}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=Y.pixelsToTime(this.clipSnapThreshold,this.zoom),a=e.startTime+e.duration,o=[];if(e.isResizingLeft)for(const c of r){const h=a-c,d=t.endTimeAtSource-h,u=Math.abs(c-e.startTime);u>n||h<ce.MIN_CLIP_DURATION_MS||this.isSourceBoundClip(t)&&d<0||o.push({clip:{...e,startTime:c,duration:h,endTime:a,...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-a);u>n||h<ce.MIN_CLIP_DURATION_MS||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-a);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 a=r.getAbsolutePosition();i.set(e,{parent:n,baseY:this.trackY}),r.remove(),this.dragOverlayLayer.add(r),r.position(a),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(ce.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=ce.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(ce,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),p(ce,"DEFAULT_CLIP_SNAP_THRESHOLD",8),p(ce,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(ce,"AUTO_SCROLL_MAX_SPEED",18),p(ce,"MIN_CLIP_DURATION_MS",1);let Wi=ce;/**
|
|
14
|
+
`,pn=()=>{if(typeof document>"u")throw new Error(io)};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=T._getRotation(l.rotation),l}}const ro="[object Array]",no="[object Number]",so="[object String]",ao="[object Boolean]",oo=Math.PI/180,lo=180/Math.PI,Et="#",co="",ho="0",uo="Konva warning: ",fn="Konva error: ",po="rgb(",nr={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]},fo=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let mi=[],Rt=null;const go=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(a){setTimeout(a,16)},T={_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)===ro},_isNumber(a){return Object.prototype.toString.call(a)===no&&!isNaN(a)&&isFinite(a)},_isString(a){return Object.prototype.toString.call(a)===so},_isBoolean(a){return Object.prototype.toString.call(a)===ao},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){mi.push(a),mi.length===1&&go(function(){const e=mi;mi=[],e.forEach(function(t){t()})})},createCanvasElement(){pn();const a=document.createElement("canvas");try{a.style=a.style||{}}catch{}return a},createImageElement(){return pn(),document.createElement("img")},_isInDocument(a){for(;a=a.parentNode;)if(a==document)return!0;return!1},_urlToImage(a,e){const t=T.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(Et,co);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=ho+a;return Et+a},isCanvasFarblingActive(){if(Rt!==null)return Rt;if(typeof document>"u")return Rt=!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 Rt=i,this.releaseCanvas(a),Rt},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),Et+this._rgbToHex(a,e,t)},getSnappedHexColor(a){const e=this._hexToRgb(a);return Et+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 nr?(e=nr[a],{r:e[0],g:e[1],b:e[2]}):a[0]===Et?this._hexToRgb(a.substring(1)):a.substr(0,4)===po?(e=fo.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",T._namedColorToRBA(a)||T._hex3ColorToRGBA(a)||T._hex4ColorToRGBA(a)||T._hex6ColorToRGBA(a)||T._hex8ColorToRGBA(a)||T._rgbColorToRGBA(a)||T._rgbaColorToRGBA(a)||T._hslColorToRGBA(a)},_namedColorToRBA(a){const e=nr[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*oo},radToDeg(a){return a*lo},_degToRad(a){return T.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),T.degToRad(a)},_radToDeg(a){return T.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),T.radToDeg(a)},_getRotation(a){return D.angleDeg?T.radToDeg(a):a},_capitalize(a){return a.charAt(0).toUpperCase()+a.slice(1)},throw(a){throw new Error(fn+a)},error(a){console.error(fn+a)},warn(a){D.showWarnings&&console.warn(uo+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=T.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=T._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=T._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||T._isElement(a[t]))if(e.configurable)delete a[t];else return null;else if(T._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 f;typeof r=="number"?f=r:f=n<r.length?r[n]:0,f=i*Math.cos(Math.PI/t)*Math.min(1,f/i*2);const y={x:c.x/d,y:c.y/d},v={x:h.x/u,y:h.y/u},b={x:o.x-y.x*f,y:o.y-y.y*f},S={x:o.x+v.x*f,y:o.y+v.y*f};n===0?a.moveTo(b.x,b.y):a.lineTo(b.x,b.y),a.arcTo(o.x,o.y,S.x,S.y,f)}}};function mo(a){const e=[],t=a.length,i=T;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 gn=",",yo="(",So=")",vo="([",Co="])",bo=";",To="()",wo="=",mn=["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"],ko=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],xo=100;let yi=null;function yn(){if(yi!==null)return yi;try{const e=T.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(yi=!1,!1)}catch{return yi=!1,!1}}class Zi{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+=To:T._isArray(c[0])?n+=vo+c.join(gn)+Co:(t&&(c=c.map(h=>typeof h=="number"?Math.floor(h):h)),n+=yo+c.join(gn)+So)):(n+=o.property,e||(n+=wo+o.val)),n+=bo;return n}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=xo&&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=mn.length,i=this.setAttr,r,n;const s=function(o){let l=e[o],c;e[o]=function(){return n=mo(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(mn[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)}}ko.forEach(function(a){Object.defineProperty(Zi.prototype,a,{get(){return this._context[a]},set(e){this._context[a]=e}})});class Po extends Zi{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 _o extends Zi{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 Si;function Ao(){if(Si)return Si;const a=T.createCanvasElement(),e=a.getContext("2d");return Si=function(){const t=D._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),T.releaseCanvas(a),Si}class Jr{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||D.pixelRatio||Ao();this.pixelRatio=i,this._canvas=T.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 T.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class qe extends Jr{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new Po(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class Qr extends Jr{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new _o(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=T._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 Je(a){return T._isString(a)?'"'+a+'"':Object.prototype.toString.call(a)==="[object Number]"||T._isBoolean(a)?a:Object.prototype.toString.call(a)}function Gs(a){return a>255?255:a<0?0:Math.round(a)}function R(){if(D.isUnminified)return function(a,e){return T._isNumber(a)||T.warn(Je(a)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),a}}function Ji(a){if(D.isUnminified)return function(e,t){let i=T._isNumber(e),r=T._isArray(e)&&e.length==a;return!i&&!r&&T.warn(Je(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+a+")"),e}}function en(){if(D.isUnminified)return function(a,e){return T._isNumber(a)||a==="auto"||T.warn(Je(a)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),a}}function dt(){if(D.isUnminified)return function(a,e){return T._isString(a)||T.warn(Je(a)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),a}}function Hs(){if(D.isUnminified)return function(a,e){const t=T._isString(a),i=Object.prototype.toString.call(a)==="[object CanvasGradient]"||a&&a.addColorStop;return t||i||T.warn(Je(a)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),a}}function Io(){if(D.isUnminified)return function(a,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&a instanceof t||(T._isArray(a)?a.forEach(function(i){T._isNumber(i)||T.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):T.warn(Je(a)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),a}}function Ae(){if(D.isUnminified)return function(a,e){return a===!0||a===!1||T.warn(Je(a)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),a}}function Eo(a){if(D.isUnminified)return function(e,t){return e==null||T.isObject(e)||T.warn(Je(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+a),e}}const Mt="get",Dt="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=Mt+T._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=Dt+T._capitalize(e);a.prototype[r]||m.overWriteSetter(a,e,t,i)},overWriteSetter(a,e,t,i){const r=Dt+T._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=T._capitalize,o=Mt+s(e),l=Dt+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=Eo(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=T._capitalize(e),i=Dt+t,r=Mt+t;a.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[r]()}},addDeprecatedGetterSetter(a,e,t,i){T.error("Adding deprecated "+e);const r=Mt+T._capitalize(e),n=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";a.prototype[r]=function(){T.error(n);const s=this.attrs[e];return s===void 0?t:s},m.addSetter(a,e,i,function(){T.error(n)}),m.addOverloadedGetterSetter(a,e)},backCompat(a,e){T.each(e,function(t,i){const r=a.prototype[i],n=Mt+T._capitalize(t),s=Dt+T._capitalize(t);function o(){r.apply(this,arguments),T.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 Ro(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:T.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Mi="absoluteOpacity",Sn="allEventListeners",Be="absoluteTransform",vn="absoluteScale",it="canvas",Mo="Change",Do="children",Lo="konva",xr="listening",Bo="mouseenter",Oo="mouseleave",Fo="pointerenter",Go="pointerleave",Ho="touchenter",No="touchleave",Cn="set",bn="Shape",Di=" ",Tn="stage",We="transform",$o="Stage",Pr="visible",zo=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Di);let Vo=1;class E{constructor(e){this._id=Vo++,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===We||e===Be)&&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===We||e===Be)&&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(Di);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(it)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Be&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(it)){const{scene:e,filter:t,hit:i}=this._cache.get(it);T.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(it)}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){T.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const u=Math.abs(Math.round(i.x)-o)>.5?1:0,f=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=c*2+u,n+=c*2+f,o-=c,l-=c;const g=new qe({pixelRatio:s,width:r,height:n}),y=new qe({pixelRatio:s,width:0,height:0,willReadFrequently:!0}),v=new Qr({pixelRatio:d,width:r,height:n}),b=g.getContext(),S=v.getContext(),C=new qe({width:g.width/g.pixelRatio+Math.abs(o),height:g.height/g.pixelRatio+Math.abs(l),pixelRatio:g.pixelRatio}),w=C.getContext();return v.isCache=!0,g.isCache=!0,this._cache.delete(it),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(g.getContext()._context.imageSmoothingEnabled=!1,y.getContext()._context.imageSmoothingEnabled=!1),b.save(),S.save(),w.save(),b.translate(-o,-l),S.translate(-o,-l),w.translate(-o,-l),C.x=o,C.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Mi),this._clearSelfAndDescendantCache(vn),this.drawScene(g,this,C),this.drawHit(v,this),this._isUnderCache=!1,b.restore(),S.restore(),h&&(b.save(),b.beginPath(),b.rect(0,0,r,n),b.closePath(),b.setAttr("strokeStyle","red"),b.setAttr("lineWidth",5),b.stroke(),b.restore()),T.releaseCanvas(C._canvas),this._cache.set(it,{scene:g,filter:y,hit:v,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(it)}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"&&yn(),typeof e[u]!="string"||!yn()){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=Ro(c)),c.call(this,o),n.putImageData(o,0,0)}catch(u){T.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(Sn),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Di);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(Di),r=i.length,n,s,o,l,c,h;if(this._cache&&this._cache.delete(Sn),!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=T.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(Be),this._clearSelfAndDescendantCache(Mi),this._clearSelfAndDescendantCache(vn),this._clearSelfAndDescendantCache(Tn),this._clearSelfAndDescendantCache(Pr),this._clearSelfAndDescendantCache(xr)}_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"+T._capitalize(e);return T._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!==Do&&(i=Cn+T._capitalize(t),T._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(xr,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(Pr,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!==bn&&(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(We),this._clearSelfAndDescendantCache(Be)),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(We);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(We),this._clearSelfAndDescendantCache(Be),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 T.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 T.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 T.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 T.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 T.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&T.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(Mi,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=T.isObject(i)&&!T._isPlainObject(i)&&!T._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 T._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],T.isValidSelector(n)||(T.warn('Selector "'+n+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),T.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),T.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(Tn,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(Be,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(Be)||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(We,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get(We)||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=T.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(Lo)<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 qe({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 qe({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,T._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+Mo,{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[Cn+T._capitalize(e)];return T._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&&!T.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===bn&&(t.target=this);const r=[Bo,Oo,Fo,Go,Ho,No];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=E.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,E.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:T.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 T.haveIntersection(i,this.getClientRect())}static create(e,t){return T._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let i=E.prototype.getClassName.call(e),r=e.children,n,s,o;t&&(e.attrs.container=t),D[i]||(T.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(E._createNode(r[o]));return n}}E.protoListenerMap=new Map;E.prototype.nodeType="Node";E.prototype._attrsAffectingSize=[];E.prototype.eventListeners={};E.prototype.on.call(E.prototype,zo,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(We),this._clearSelfAndDescendantCache(Be)});E.prototype.on.call(E.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(Pr)});E.prototype.on.call(E.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(xr)});E.prototype.on.call(E.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Mi)});const te=m.addGetterSetter;te(E,"zIndex");te(E,"absolutePosition");te(E,"position");te(E,"x",0,R());te(E,"y",0,R());te(E,"globalCompositeOperation","source-over",dt());te(E,"opacity",1,R());te(E,"name","",dt());te(E,"id","",dt());te(E,"rotation",0,R());m.addComponentsGetterSetter(E,"scale",["x","y"]);te(E,"scaleX",1,R());te(E,"scaleY",1,R());m.addComponentsGetterSetter(E,"skew",["x","y"]);te(E,"skewX",0,R());te(E,"skewY",0,R());m.addComponentsGetterSetter(E,"offset",["x","y"]);te(E,"offsetX",0,R());te(E,"offsetY",0,R());te(E,"dragDistance",void 0,R());te(E,"width",0,R());te(E,"height",0,R());te(E,"listening",!0,Ae());te(E,"preventDefault",!0,Ae());te(E,"filters",void 0,function(a){return this._filterUpToDate=!1,a});te(E,"visible",!0,Ae());te(E,"transformsEnabled","all",dt());te(E,"size");te(E,"dragBoundFunc");te(E,"draggable",!1,Ae());m.backCompat(E,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class ve extends E{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=E.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=E.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 f=this.getAbsoluteTransform(i);let g=f.getMatrix();s.transform(g[0],g[1],g[2],g[3],g[4],g[5]),s.beginPath();let y;if(c)y=c.call(this,s,this);else{const v=this.clipX(),b=this.clipY();s.rect(v||0,b||0,o,l)}s.clip.apply(s,y),g=f.copy().invert().getMatrix(),s.transform(g[0],g[1],g[2],g[3],g[4],g[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(f){f[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(f){if(!f.visible())return;const g=f.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});g.width===0&&g.height===0||(n===void 0?(n=g.x,s=g.y,o=g.x+g.width,l=g.y+g.height):(n=Math.min(n,g.x),s=Math.min(s,g.y),o=Math.max(o,g.x+g.width),l=Math.max(l,g.y+g.height)))});const d=this.find("Shape");let u=!1;for(let f=0;f<d.length;f++)if(d[f]._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(ve,"clip",["x","y","width","height"]);m.addGetterSetter(ve,"clipX",void 0,R());m.addGetterSetter(ve,"clipY",void 0,R());m.addGetterSetter(ve,"clipWidth",void 0,R());m.addGetterSetter(ve,"clipHeight",void 0,R());m.addGetterSetter(ve,"clipFunc");const ri=new Map,Ns=D._global.PointerEvent!==void 0;function sr(a){return ri.get(a)}function tn(a){return{evt:a,pointerId:a.pointerId}}function $s(a,e){return ri.get(a)===e}function zs(a,e){qt(a),e.getStage()&&(ri.set(a,e),Ns&&e._fire("gotpointercapture",tn(new PointerEvent("gotpointercapture"))))}function qt(a,e){const t=ri.get(a);if(!t)return;const i=t.getStage();i&&i.content,ri.delete(a),Ns&&t._fire("lostpointercapture",tn(new PointerEvent("lostpointercapture")))}const Uo="Stage",Wo="string",wn="px",Yo="mouseout",Vs="mouseleave",Us="mouseover",Ws="mouseenter",Ys="mousemove",Xs="mousedown",qs="mouseup",$t="pointermove",zt="pointerdown",Tt="pointerup",Vt="pointercancel",Xo="lostpointercapture",vi="pointerout",Ut="pointerleave",Ci="pointerover",bi="pointerenter",_r="contextmenu",js="touchstart",Ks="touchend",Zs="touchmove",Js="touchcancel",Ar="wheel",qo=5,jo=[[Ws,"_pointerenter"],[Xs,"_pointerdown"],[Ys,"_pointermove"],[qs,"_pointerup"],[Vs,"_pointerleave"],[js,"_pointerdown"],[Zs,"_pointermove"],[Ks,"_pointerup"],[Js,"_pointercancel"],[Us,"_pointerover"],[Ar,"_wheel"],[_r,"_contextmenu"],[zt,"_pointerdown"],[$t,"_pointermove"],[Tt,"_pointerup"],[Vt,"_pointercancel"],[Ut,"_pointerleave"],[Xo,"_lostpointercapture"]],ar={mouse:{[vi]:Yo,[Ut]:Vs,[Ci]:Us,[bi]:Ws,[$t]:Ys,[zt]:Xs,[Tt]:qs,[Vt]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[vi]:"touchout",[Ut]:"touchleave",[Ci]:"touchover",[bi]:"touchenter",[$t]:Zs,[zt]:js,[Tt]:Ks,[Vt]:Js,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[vi]:vi,[Ut]:Ut,[Ci]:Ci,[bi]:bi,[$t]:$t,[zt]:zt,[Tt]:Tt,[Vt]:Vt,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Wt=a=>a.indexOf("pointer")>=0?"pointer":a.indexOf("touch")>=0?"touch":"mouse",mt=a=>{const e=Wt(a);if(e==="pointer")return D.pointerEventsEnabled&&ar.pointer;if(e==="touch")return ar.touch;if(e==="mouse")return ar.mouse};function kn(a={}){return(a.clipFunc||a.clipWidth||a.clipHeight)&&T.warn("Stage does not support clipping. Please use clip for Layers or Groups."),a}const Ko="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);",jt=[];class Qi extends ve{constructor(e){super(kn(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),jt.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{kn(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",i=e.getType()==="FastLayer";t||i||T.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===Wo){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"),ve.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&T._isInDocument(e)&&this.container().removeChild(e);const t=jt.indexOf(this);return t>-1&&jt.splice(t,1),T.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}:(T.warn(Ko),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 qe({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+wn,this.content.style.height=t+wn),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>qo&&T.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 $s(e,this)}setPointerCapture(e){zs(e,this)}releaseCapture(e){qt(e)}getLayers(){return this.children}_bindContentEvents(){D.isBrowser&&jo.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=mt(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=mt(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=mt(e.type),i=Wt(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=mt(e.type),i=Wt(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=mt(e.type),i=Wt(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=sr(c.id)||this.getIntersection(c),d=c.id,u={evt:e,pointerId:d},f=l!==h;if(f&&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,f&&(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=mt(e.type),i=Wt(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=sr(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(_r,{evt:e}):this._fire(_r,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Ar,{evt:e}):this._fire(Ar,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=sr(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(Tt,tn(e)),qt(e.pointerId)}_lostpointercapture(e){qt(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:T._getFirstPointerId(e)}],this._changedPointerPositions=[{x:i,y:r,id:T._getFirstPointerId(e)}])}_setPointerPosition(e){T.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 qe({width:this.width(),height:this.height()}),this.bufferHitCanvas=new Qr({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 T.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}}Qi.prototype.nodeType=Uo;ae(Qi);m.addGetterSetter(Qi,"container");D.isBrowser&&document.addEventListener("visibilitychange",()=>{jt.forEach(a=>{a.batchDraw()})});const Qs="hasShadow",ea="shadowRGBA",ta="patternImage",ia="linearGradient",ra="radialGradient";let Ti;function or(){return Ti||(Ti=T.createCanvasElement().getContext("2d"),Ti)}const Kt={};function Zo(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function Jo(a){a.stroke()}function Qo(a){const e=this.attrs.fillRule;e?a.fill(e):a.fill()}function el(a){a.stroke()}function tl(){this._clearCache(Qs)}function il(){this._clearCache(ea)}function rl(){this._clearCache(ta)}function nl(){this._clearCache(ia)}function sl(){this._clearCache(ra)}class A extends E{constructor(e){super(e);let t,i=0;for(;t=T.getHitColor(),!(t&&!(t in Kt));)if(i++,i>=1e4){T.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=T.getRandomColor();break}this.colorKey=t,Kt[t]=this}getContext(){return T.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return T.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(Qs,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(ta,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=or().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(ia,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=or(),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(ra,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=or(),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(ea,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=T.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 E.prototype.destroy.call(this),delete Kt[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){T.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,f=d?this.shadowOffsetY():0,g=c+Math.abs(u),y=h+Math.abs(f),v=d&&this.shadowBlur()||0,b=g+v*2,S=y+v*2,C={width:b,height:S,x:-(l/2+v)+Math.min(u,0)+s.x,y:-(l/2+v)+Math.min(f,0)+s.y};return r?C:this._transformedRect(C,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,f=u.getContext();i?(f.save(),f.setTransform(1,0,0,1,0,0),f.clearRect(0,0,u.width,u.height),f.restore()):f.clear(),f.save(),f._applyLineJoin(this),f._applyMiterLimit(this);const g=this.getAbsoluteTransform(t).getMatrix();f.transform(g[0],g[1],g[2],g[3],g[4],g[5]),l.call(this,f,this),f.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||T.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=T._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){T.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(e){return $s(e,this)}setPointerCapture(e){zs(e,this)}releaseCapture(e){qt(e)}}A.prototype._fillFunc=Zo;A.prototype._strokeFunc=Jo;A.prototype._fillFuncHit=Qo;A.prototype._strokeFuncHit=el;A.prototype._centroid=!1;A.prototype.nodeType="Shape";ae(A);A.prototype.eventListeners={};A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",tl);A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",il);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",rl);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",nl);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",sl);m.addGetterSetter(A,"stroke",void 0,Hs());m.addGetterSetter(A,"strokeWidth",2,R());m.addGetterSetter(A,"fillAfterStrokeEnabled",!1);m.addGetterSetter(A,"hitStrokeWidth","auto",en());m.addGetterSetter(A,"strokeHitEnabled",!0,Ae());m.addGetterSetter(A,"perfectDrawEnabled",!0,Ae());m.addGetterSetter(A,"shadowForStrokeEnabled",!0,Ae());m.addGetterSetter(A,"lineJoin");m.addGetterSetter(A,"lineCap");m.addGetterSetter(A,"miterLimit");m.addGetterSetter(A,"sceneFunc");m.addGetterSetter(A,"hitFunc");m.addGetterSetter(A,"dash");m.addGetterSetter(A,"dashOffset",0,R());m.addGetterSetter(A,"shadowColor",void 0,dt());m.addGetterSetter(A,"shadowBlur",0,R());m.addGetterSetter(A,"shadowOpacity",1,R());m.addComponentsGetterSetter(A,"shadowOffset",["x","y"]);m.addGetterSetter(A,"shadowOffsetX",0,R());m.addGetterSetter(A,"shadowOffsetY",0,R());m.addGetterSetter(A,"fillPatternImage");m.addGetterSetter(A,"fill",void 0,Hs());m.addGetterSetter(A,"fillPatternX",0,R());m.addGetterSetter(A,"fillPatternY",0,R());m.addGetterSetter(A,"fillLinearGradientColorStops");m.addGetterSetter(A,"strokeLinearGradientColorStops");m.addGetterSetter(A,"fillRadialGradientStartRadius",0);m.addGetterSetter(A,"fillRadialGradientEndRadius",0);m.addGetterSetter(A,"fillRadialGradientColorStops");m.addGetterSetter(A,"fillPatternRepeat","repeat");m.addGetterSetter(A,"fillEnabled",!0);m.addGetterSetter(A,"strokeEnabled",!0);m.addGetterSetter(A,"shadowEnabled",!0);m.addGetterSetter(A,"dashEnabled",!0);m.addGetterSetter(A,"strokeScaleEnabled",!0);m.addGetterSetter(A,"fillPriority","color");m.addComponentsGetterSetter(A,"fillPatternOffset",["x","y"]);m.addGetterSetter(A,"fillPatternOffsetX",0,R());m.addGetterSetter(A,"fillPatternOffsetY",0,R());m.addComponentsGetterSetter(A,"fillPatternScale",["x","y"]);m.addGetterSetter(A,"fillPatternScaleX",1,R());m.addGetterSetter(A,"fillPatternScaleY",1,R());m.addComponentsGetterSetter(A,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(A,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(A,"fillLinearGradientStartPointX",0);m.addGetterSetter(A,"strokeLinearGradientStartPointX",0);m.addGetterSetter(A,"fillLinearGradientStartPointY",0);m.addGetterSetter(A,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(A,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(A,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(A,"fillLinearGradientEndPointX",0);m.addGetterSetter(A,"strokeLinearGradientEndPointX",0);m.addGetterSetter(A,"fillLinearGradientEndPointY",0);m.addGetterSetter(A,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(A,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(A,"fillRadialGradientStartPointX",0);m.addGetterSetter(A,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(A,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(A,"fillRadialGradientEndPointX",0);m.addGetterSetter(A,"fillRadialGradientEndPointY",0);m.addGetterSetter(A,"fillPatternRotation",0);m.addGetterSetter(A,"fillRule",void 0,dt());m.backCompat(A,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const al="beforeDraw",ol="draw",na=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],ll=na.length;class ut extends ve{constructor(e){super(e),this.canvas=new qe,this.hitCanvas=new Qr({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(){E.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(!E.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(E.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(E.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 E.prototype.remove.call(this),e&&e.parentNode&&T._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"&&T.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(),E.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(){T.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){T.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,T.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<ll;r++){const n=na[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=T.getHitColorKey(i[0],i[1],i[2]),s=Kt[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(al,{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),ve.prototype.drawScene.call(this,n,t,i),this._fire(ol,{node:this}),this}drawHit(e,t){const i=this.getLayer(),r=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),ve.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){T.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return T.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 T.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}ut.prototype.nodeType="Layer";ae(ut);m.addGetterSetter(ut,"imageSmoothingEnabled",!0);m.addGetterSetter(ut,"clearBeforeDraw",!0);m.addGetterSetter(ut,"hitGraphEnabled",!0,Ae());class rn extends ut{constructor(e){super(e),this.listening(!1),T.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}rn.prototype.nodeType="FastLayer";ae(rn);class xt extends ve{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&T.throw("You may only add groups and shapes to groups.")}}xt.prototype.nodeType="Group";ae(xt);const lr=function(){return at.performance&&at.performance.now?function(){return at.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:lr(),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=lr(),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(lr());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(),T.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,T.requestAnimFrame(this._animationLoop))}}we.animations=[];we.animIdCounter=0;we.animRunning=!1;const cl={node:1,duration:1,easing:1,onFinish:1,yoyo:1},hl=1,xn=2,Pn=3,_n=["fill","stroke","shadowColor"];let dl=0;class ul{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=xn,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Pn,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===xn?this.setTime(e):this.state===Pn&&this.setTime(this.duration-e)}pause(){this.state=hl,this.fire("onPause")}getTimer(){return new Date().getTime()}}class ie{constructor(e){const t=this,i=e.node,r=i._id,n=e.easing||Zt.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=dl++;const c=i.getLayer()||(i instanceof D.Stage?i.getLayers():null);c||T.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 ul(l,function(h){t._tweenFunc(h)},n,0,1,o*1e3,s),this._addListeners(),ie.attrs[r]||(ie.attrs[r]={}),ie.attrs[r][this._id]||(ie.attrs[r][this._id]={}),ie.tweens[r]||(ie.tweens[r]={});for(l in e)cl[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=ie.tweens[r][e];h&&delete ie.attrs[r][h][e];let d=i.getAttr(e);if(T._isArray(t))if(n=[],s=Math.max(t.length,d.length),e==="points"&&t.length!==d.length&&(t.length>d.length?(l=d,d=T._prepareArrayForTween(d,t,i.closed())):(o=t,t=T._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 f=T.colorToRGBA(d[u]);c=T.colorToRGBA(t[u]),d[u]=f,n.push({r:c.r-f.r,g:c.g-f.g,b:c.b-f.b,a:c.a-f.a})}else for(let u=0;u<s;u++)n.push(t[u]-d[u]);else _n.indexOf(e)!==-1?(d=T.colorToRGBA(d),c=T.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;ie.attrs[r][this._id][e]={start:d,diff:n,end:t,trueEnd:o,trueStart:l},ie.tweens[r][e]=this._id}_tweenFunc(e){const t=this.node,i=ie.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,T._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 _n.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=ie.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=ie.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=ie.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const r in i)delete ie.tweens[e][r];delete ie.attrs[e][t],ie.tweens[e]&&(Object.keys(ie.tweens[e]).length===0&&delete ie.tweens[e],Object.keys(ie.attrs[e]).length===0&&delete ie.attrs[e])}}ie.attrs={};ie.tweens={};E.prototype.to=function(a){const e=a.onFinish;a.node=this,a.onFinish=function(){this.destroy(),e&&e()},new ie(a).play()};const Zt={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-Zt.BounceEaseOut(i-a,0,t,i)+e},BounceEaseInOut(a,e,t,i){return a<i/2?Zt.BounceEaseIn(a*2,0,t,i)*.5+e:Zt.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=T._assign(D,{Util:T,Transform:Se,Node:E,Container:ve,Stage:Qi,stages:jt,Layer:ut,FastLayer:rn,Group:xt,DD:Z,Shape:A,shapes:Kt,Animation:we,Tween:ie,Easings:Zt,Context:Zi,Canvas:Jr});class Fe extends A{_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}}}Fe.prototype._centroid=!0;Fe.prototype.className="Arc";Fe.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];ae(Fe);m.addGetterSetter(Fe,"innerRadius",0,R());m.addGetterSetter(Fe,"outerRadius",0,R());m.addGetterSetter(Fe,"angle",0,R());m.addGetterSetter(Fe,"clockwise",!1,Ae());function Ir(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),f=t+h*(r-a),g=i+h*(n-e);return[d,u,f,g]}function In(a,e){const t=a.length,i=[];for(let r=2;r<t-2;r+=2){const n=Ir(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 pl(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 Ge extends A{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():In(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=Ir(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),n=Ir(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),s=In(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],...pl(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}}}Ge.prototype.className="Line";Ge.prototype._attrsAffectingSize=["points","bezier","tension"];ae(Ge);m.addGetterSetter(Ge,"closed",!1);m.addGetterSetter(Ge,"bezier",!1);m.addGetterSetter(Ge,"tension",0,R());m.addGetterSetter(Ge,"points",[],Io());const fl=[[],[],[-.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]],gl=[[],[],[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]],ml=[[1],[1,1],[1,2,1],[1,3,3,1]],En=(a,e,t)=>{let i,r;const s=t/2;i=0;for(let o=0;o<20;o++)r=s*fl[20][o]+s,i+=gl[20][o]*yl(a,e,r);return s*i},Rn=(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,f=d-h*h,g=u*u+f>0?Math.sqrt(u*u+f):0,y=h*h+f>0?Math.sqrt(h*h+f):0,v=h+Math.sqrt(h*h+f)!==0?f*Math.log(Math.abs((u+g)/(h+y))):0;return Math.sqrt(o)/2*(u*g-h*y+v)};function yl(a,e,t){const i=Er(1,t,a),r=Er(1,t,e),n=i*i+r*r;return Math.sqrt(n)}const Er=(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+=ml[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 Er(a-1,e,r)}},Mn=(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 re extends A{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=re.parsePathData(this.data()),this.pathLength=re.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],f=s[6],g=s[7],y=c>h?c:h,v=c>h?1:c/h,b=c>h?h/c:1;e.translate(o,l),e.rotate(f),e.scale(v,b),e.arc(0,0,y,d,d+u,1-g),e.scale(1/v,1/b),e.rotate(-f),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const 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 f=c-u;f>d;f-=u){const g=re.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],f,0);e.push(g.x,g.y)}else for(let f=c+u;f<d;f+=u){const g=re.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],f,0);e.push(g.x,g.y)}}else if(l.command==="C")for(let c=0;c<=1;c+=.01){const h=re.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 re.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 re.getPointOnLine(e,s.start.x,s.start.y,o[0],o[1]);case"C":return re.getPointOnCubicBezier(Mn(e,re.getPathLength(t),y=>En([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 re.getPointOnQuadraticBezier(Mn(e,re.getPathLength(t),y=>Rn([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],f=o[6];let g=o[4];return g+=u*e/s.pathLength,re.getPointOnEllipticalArc(l,c,h,d,g,f)}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),f=t+u*(r-t),g=i+u*(n-i),y=this.getLineLength(s,o,f,g),v=Math.sqrt(e*e-y*y),b=Math.sqrt(v*v/(1+c*c))*(r<t?-1:1),S=c*b;return{x:f+b,y:g+S}}static getPointOnCubicBezier(e,t,i,r,n,s,o,l,c){function h(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 f(v){return(1-v)*(1-v)*(1-v)}const g=l*h(e)+s*d(e)+r*u(e)+t*f(e),y=c*h(e)+o*d(e)+n*u(e)+i*f(e);return{x:g,y}}static getPointOnQuadraticBezier(e,t,i,r,n,s,o){function l(f){return f*f}function c(f){return 2*f*(1-f)}function h(f){return(1-f)*(1-f)}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],f=u.charAt(0);for(u=u.slice(1),s.length=0;h=c.exec(u);)s.push(h[0]);let g=[],y=f==="A"||f==="a"?0:-1;for(let v=0,b=s.length;v<b;v++){const S=s[v];if(S==="00"){g.push(0,0),y>=0&&(y+=2,y>=7&&(y-=7));continue}if(y>=0){if(y===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(S)){g.push(parseInt(S[0],10)),g.push(parseInt(S[1],10)),g.push(parseFloat(S.slice(2))),y+=3,y>=7&&(y-=7);continue}if(S==="11"||S==="10"||S==="01"){g.push(parseInt(S[0],10)),g.push(parseInt(S[1],10)),y+=2,y>=7&&(y-=7);continue}if(S==="0"||S==="1"){g.push(parseInt(S,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(S)){g.push(parseInt(S[0],10)),g.push(parseFloat(S.slice(1))),y+=2,y>=7&&(y-=7);continue}if(S==="0"||S==="1"){g.push(parseInt(S,10)),y+=1,y>=7&&(y-=7);continue}}const C=parseFloat(S);isNaN(C)?g.push(0):g.push(C),y+=1,y>=7&&(y-=7)}else{const C=parseFloat(S);isNaN(C)?g.push(0):g.push(C)}}for(;g.length>0&&!isNaN(g[0]);){let v="",b=[];const S=o,C=l;let w,_,P,B,k,M,x,$,H,V;switch(f){case"l":o+=g.shift(),l+=g.shift(),v="L",b.push(o,l);break;case"L":o=g.shift(),l=g.shift(),b.push(o,l);break;case"m":const z=g.shift(),N=g.shift();if(o+=z,l+=N,v="M",n.length>2&&n[n.length-1].command==="z"){for(let L=n.length-2;L>=0;L--)if(n[L].command==="M"){o=n[L].points[0]+z,l=n[L].points[1]+N;break}}b.push(o,l),f="l";break;case"M":o=g.shift(),l=g.shift(),v="M",b.push(o,l),f="L";break;case"h":o+=g.shift(),v="L",b.push(o,l);break;case"H":o=g.shift(),v="L",b.push(o,l);break;case"v":l+=g.shift(),v="L",b.push(o,l);break;case"V":l=g.shift(),v="L",b.push(o,l);break;case"C":b.push(g.shift(),g.shift(),g.shift(),g.shift()),o=g.shift(),l=g.shift(),b.push(o,l);break;case"c":b.push(o+g.shift(),l+g.shift(),o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),v="C",b.push(o,l);break;case"S":_=o,P=l,w=n[n.length-1],w.command==="C"&&(_=o+(o-w.points[2]),P=l+(l-w.points[3])),b.push(_,P,g.shift(),g.shift()),o=g.shift(),l=g.shift(),v="C",b.push(o,l);break;case"s":_=o,P=l,w=n[n.length-1],w.command==="C"&&(_=o+(o-w.points[2]),P=l+(l-w.points[3])),b.push(_,P,o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),v="C",b.push(o,l);break;case"Q":b.push(g.shift(),g.shift()),o=g.shift(),l=g.shift(),b.push(o,l);break;case"q":b.push(o+g.shift(),l+g.shift()),o+=g.shift(),l+=g.shift(),v="Q",b.push(o,l);break;case"T":_=o,P=l,w=n[n.length-1],w.command==="Q"&&(_=o+(o-w.points[0]),P=l+(l-w.points[1])),o=g.shift(),l=g.shift(),v="Q",b.push(_,P,o,l);break;case"t":_=o,P=l,w=n[n.length-1],w.command==="Q"&&(_=o+(o-w.points[0]),P=l+(l-w.points[1])),o+=g.shift(),l+=g.shift(),v="Q",b.push(_,P,o,l);break;case"A":B=g.shift(),k=g.shift(),M=g.shift(),x=g.shift(),$=g.shift(),H=o,V=l,o=g.shift(),l=g.shift(),v="A",b=this.convertEndpointToCenterParameterization(H,V,o,l,x,$,B,k,M);break;case"a":B=g.shift(),k=g.shift(),M=g.shift(),x=g.shift(),$=g.shift(),H=o,V=l,o+=g.shift(),l+=g.shift(),v="A",b=this.convertEndpointToCenterParameterization(H,V,o,l,x,$,B,k,M);break}n.push({command:v||f,points:b,start:{x:S,y:C},pathLength:this.calcLength(S,C,v||f,b)})}(f==="z"||f==="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=re;switch(i){case"L":return c.getLineLength(e,t,r[0],r[1]);case"C":return En([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return Rn([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 f=Math.PI/180;if(Math.abs(h-u)<f&&(f=Math.abs(h-u)),s=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),d<0)for(l=h-f;l>u;l-=f)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+f;l<u;l+=f)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,f=d*d/(o*o)+u*u/(l*l);f>1&&(o*=Math.sqrt(f),l*=Math.sqrt(f));let g=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));n===s&&(g*=-1),isNaN(g)&&(g=0);const y=g*o*u/l,v=g*-l*d/o,b=(e+i)/2+Math.cos(h)*y-Math.sin(h)*v,S=(t+r)/2+Math.sin(h)*y+Math.cos(h)*v,C=function(x){return Math.sqrt(x[0]*x[0]+x[1]*x[1])},w=function(x,$){return(x[0]*$[0]+x[1]*$[1])/(C(x)*C($))},_=function(x,$){return(x[0]*$[1]<x[1]*$[0]?-1:1)*Math.acos(w(x,$))},P=_([1,0],[(d-y)/o,(u-v)/l]),B=[(d-y)/o,(u-v)/l],k=[(-1*d-y)/o,(-1*u-v)/l];let M=_(B,k);return w(B,k)<=-1&&(M=Math.PI),w(B,k)>=1&&(M=0),s===0&&M>0&&(M=M-2*Math.PI),s===1&&M<0&&(M=M+2*Math.PI),[b,S,o,l,P,M,h,s]}}re.prototype.className="Path";re.prototype._attrsAffectingSize=["data"];ae(re);m.addGetterSetter(re,"data");class pt extends Ge{_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]],f=re.calcLength(r[r.length-4],r[r.length-3],"C",u),g=re.getPointOnQuadraticBezier(Math.min(1,1-s/f),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-g.x,c=i[o-1]-g.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}}}pt.prototype.className="Arrow";ae(pt);m.addGetterSetter(pt,"pointerLength",10,R());m.addGetterSetter(pt,"pointerWidth",10,R());m.addGetterSetter(pt,"pointerAtBeginning",!1);m.addGetterSetter(pt,"pointerAtEnding",!0);class At extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}At.prototype._centroid=!0;At.prototype.className="Circle";At.prototype._attrsAffectingSize=["radius"];ae(At);m.addGetterSetter(At,"radius",0,R());class Qe extends A{_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)}}Qe.prototype.className="Ellipse";Qe.prototype._centroid=!0;Qe.prototype._attrsAffectingSize=["radiusX","radiusY"];ae(Qe);m.addComponentsGetterSetter(Qe,"radius",["x","y"]);m.addGetterSetter(Qe,"radiusX",0,R());m.addGetterSetter(Qe,"radiusY",0,R());let Ie=class sa extends A{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?T.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?T.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=T.createImageElement();r.onload=function(){const n=new sa({image:r});t(n)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Ie.prototype.className="Image";Ie.prototype._attrsAffectingSize=["image"];ae(Ie);m.addGetterSetter(Ie,"cornerRadius",0,Ji(4));m.addGetterSetter(Ie,"image");m.addComponentsGetterSetter(Ie,"crop",["x","y","width","height"]);m.addGetterSetter(Ie,"cropX",0,R());m.addGetterSetter(Ie,"cropY",0,R());m.addGetterSetter(Ie,"cropWidth",0,R());m.addGetterSetter(Ie,"cropHeight",0,R());const aa=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],Sl="Change.konva",vl="none",Rr="up",Mr="right",Dr="down",Lr="left",Cl=aa.length;class nn extends xt{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<Cl;i++)e.on(aa[i]+Sl,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 Rr:o=i/2,l=-1*c;break;case Mr:o=i+s,l=r/2;break;case Dr:o=i/2,l=r+c;break;case Lr: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})}}}nn.prototype.className="Label";ae(nn);class ft extends A{_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===Rr&&(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===Mr&&(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===Dr&&(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===Lr&&(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===Rr?(t-=r,o+=r):n===Dr?o+=r:n===Lr?(e-=i*1.5,s+=i):n===Mr&&(s+=i*1.5),{x:e,y:t,width:s,height:o}}}ft.prototype.className="Tag";ae(ft);m.addGetterSetter(ft,"pointerDirection",vl);m.addGetterSetter(ft,"pointerWidth",0,R());m.addGetterSetter(ft,"pointerHeight",0,R());m.addGetterSetter(ft,"cornerRadius",0,Ji(4));class ui extends A{_sceneFunc(e){const t=this.cornerRadius(),i=this.width(),r=this.height();e.beginPath(),t?T.drawRoundedRectPath(e,i,r,t):e.rect(0,0,i,r),e.closePath(),e.fillStrokeShape(this)}}ui.prototype.className="Rect";ae(ui);m.addGetterSetter(ui,"cornerRadius",0,Ji(4));class et extends A{_sceneFunc(e){const t=this._getPoints(),i=this.radius(),r=this.sides(),n=this.cornerRadius();if(e.beginPath(),n)T.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)}}et.prototype.className="RegularPolygon";et.prototype._centroid=!0;et.prototype._attrsAffectingSize=["radius"];ae(et);m.addGetterSetter(et,"radius",0,R());m.addGetterSetter(et,"sides",0,R());m.addGetterSetter(et,"cornerRadius",0,Ji(4));const Dn=Math.PI*2;class gt extends A{_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)}}gt.prototype.className="Ring";gt.prototype._centroid=!0;gt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(gt);m.addGetterSetter(gt,"innerRadius",0,R());m.addGetterSetter(gt,"outerRadius",0,R());class Le extends A{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],f=i*2;e.drawImage(d,o,l,c,h,u[f+0],u[f+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)}}Le.prototype.className="Sprite";ae(Le);m.addGetterSetter(Le,"animation");m.addGetterSetter(Le,"animations");m.addGetterSetter(Le,"frameOffsets");m.addGetterSetter(Le,"image");m.addGetterSetter(Le,"frameIndex",0,R());m.addGetterSetter(Le,"frameRate",17,R());m.backCompat(Le,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class tt extends A{_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)}}tt.prototype.className="Star";tt.prototype._centroid=!0;tt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(tt);m.addGetterSetter(tt,"numPoints",5,R());m.addGetterSetter(tt,"innerRadius",0,R());m.addGetterSetter(tt,"outerRadius",0,R());function Ye(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 yt="auto",bl="center",oa="inherit",Lt="justify",Tl="Change.konva",wl="2d",Ln="-",la="left",kl="text",xl="Text",Pl="top",_l="bottom",Bn="middle",ca="normal",Al="px ",wi=" ",Il="right",On="rtl",El="word",Rl="char",Fn="none",cr="…",ha=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Ml=ha.length;function Dl(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 ki;function hr(){return ki||(ki=T.createCanvasElement().getContext(wl),ki)}function Ll(a){a.fillText(this._partialText,this._partialTextX,this._partialTextY)}function Bl(a){a.setAttr("miterLimit",2),a.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function Ol(a){return a=a||{},!a.fillLinearGradientColorStops&&!a.fillRadialGradientColorStops&&!a.fillPatternImage&&(a.fill=a.fill||"black"),a}class ne extends A{constructor(e){super(Ol(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<Ml;t++)this.on(ha[t]+Tl,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(),f=this.getWidth(),g=this.letterSpacing(),y=this.charRenderFunc(),v=this.fill(),b=this.textDecoration(),S=this.underlineOffset(),C=b.indexOf("underline")!==-1,w=b.indexOf("line-through")!==-1,_;h=h===oa?e.direction:h;let P=l/2,B=Bn;if(!D.legacyTextRendering){const k=this.measureSize("M");B="alphabetic";const M=(t=k.fontBoundingBoxAscent)!==null&&t!==void 0?t:k.actualBoundingBoxAscent,x=(i=k.fontBoundingBoxDescent)!==null&&i!==void 0?i:k.actualBoundingBoxDescent;P=(M-x)/2+l/2}for(h===On&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",B),e.setAttr("textAlign",la),c===Bn?d=(this.getHeight()-n*l-s*2)/2:c===_l&&(d=this.getHeight()-n*l-s*2),e.translate(s,d+s),_=0;_<n;_++){let k=0,M=0;const x=r[_],$=x.text,H=x.width,V=x.lastInParagraph;if(e.save(),u===Il?k+=f-H-s*2:u===bl&&(k+=(f-H-s*2)/2),C){e.save(),e.beginPath();const N=S??(D.legacyTextRendering?Math.round(o/2):Math.round(o/4)),L=k,X=P+M+N;e.moveTo(L,X);const F=u===Lt&&!V?f-s*2:H;e.lineTo(L+Math.round(F),X),e.lineWidth=o/15;const Q=this._getLinearGradient();e.strokeStyle=Q||v,e.stroke(),e.restore()}const z=k;if(h!==On&&(g!==0||u===Lt||y)){const N=$.split(" ").length-1,L=Ye($);for(let X=0;X<L.length;X++){const F=L[X];if(F===" "&&!V&&u===Lt&&(k+=(f-s*2-H)/N),this._partialTextX=k,this._partialTextY=P+M,this._partialText=F,y){e.save();const se=r.slice(0,_).reduce((J,fe)=>J+Ye(fe.text).length,0),Y=X+se;y({char:F,index:Y,x:k,y:P+M,lineIndex:_,column:X,isLastInLine:V,width:this.measureSize(F).width,context:e})}e.fillStrokeShape(this),y&&e.restore(),k+=this.measureSize(F).width+g}}else g!==0&&e.setAttr("letterSpacing",`${g}px`),this._partialTextX=k,this._partialTextY=P+M,this._partialText=$,e.fillStrokeShape(this);if(w){e.save(),e.beginPath();const N=D.legacyTextRendering?0:-Math.round(o/4),L=z;e.moveTo(L,P+M+N);const X=u===Lt&&!V?f-s*2:H;e.lineTo(L+Math.round(X),P+M+N),e.lineWidth=o/15;const F=this._getLinearGradient();e.strokeStyle=F||v,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=T._isString(e)?e:e==null?"":e+"";return this._setAttr(kl,t),this}getWidth(){return this.attrs.width===yt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===yt||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return T.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 f=hr(),g=this.fontSize(),y;f.save(),f.font=this._getContextFont(),y=f.measureText(e),f.restore();const v=g/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:(c=y.fontBoundingBoxAscent)!==null&&c!==void 0?c:91*v,fontBoundingBoxDescent:(h=y.fontBoundingBoxDescent)!==null&&h!==void 0?h: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:g}}_getContextFont(){return this.fontStyle()+wi+this.fontVariant()+wi+(this.fontSize()+Al)+Dl(this.fontFamily())}_addTextLine(e){this.align()===Lt&&(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 hr().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!==yt&&n!==void 0,l=s!==yt&&s!==void 0,c=this.padding(),h=n-c*2,d=s-c*2,u=0,f=this.wrap(),g=f!==Fn,y=f!==Rl&&g,v=this.ellipsis();this.textArr=[],hr().font=this._getContextFont();const b=v?this._getTextWidth(cr):0;for(let S=0,C=e.length;S<C;++S){let w=e[S],_=this._getTextWidth(w);if(o&&_>h)for(;w.length>0;){let P=0,B=Ye(w).length,k="",M=0;for(;P<B;){const x=P+B>>>1,$=Ye(w),H=$.slice(0,x+1).join(""),V=this._getTextWidth(H);(v&&l&&u+r>d?V+b:V)<=h?(P=x+1,k=H,M=V):B=x}if(k){if(y){const H=Ye(w),V=Ye(k),z=H[V.length],N=z===wi||z===Ln;let L;if(N&&M<=h)L=V.length;else{const X=V.lastIndexOf(wi),F=V.lastIndexOf(Ln);L=Math.max(X,F)+1}L>0&&(P=L,k=H.slice(0,P).join(""),M=this._getTextWidth(k))}if(k=k.trimRight(),this._addTextLine(k),i=Math.max(i,M),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(w=Ye(w).slice(P).join("").trimLeft(),w.length>0&&(_=this._getTextWidth(w),_<=h)){this._addTextLine(w),u+=r,i=Math.max(i,_);break}}else break}else this._addTextLine(w),u+=r,i=Math.max(i,_),this._shouldHandleEllipsis(u)&&S<C-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!==yt&&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!==yt&&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+cr)<r||(s.text=s.text.slice(0,s.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(s.text+cr))}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()}}ne.prototype._fillFunc=Ll;ne.prototype._strokeFunc=Bl;ne.prototype.className=xl;ne.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];ae(ne);m.overWriteSetter(ne,"width",en());m.overWriteSetter(ne,"height",en());m.addGetterSetter(ne,"direction",oa);m.addGetterSetter(ne,"fontFamily","Arial");m.addGetterSetter(ne,"fontSize",12,R());m.addGetterSetter(ne,"fontStyle",ca);m.addGetterSetter(ne,"fontVariant",ca);m.addGetterSetter(ne,"padding",0,R());m.addGetterSetter(ne,"align",la);m.addGetterSetter(ne,"verticalAlign",Pl);m.addGetterSetter(ne,"lineHeight",1,R());m.addGetterSetter(ne,"wrap",El);m.addGetterSetter(ne,"ellipsis",!1,Ae());m.addGetterSetter(ne,"letterSpacing",0,R());m.addGetterSetter(ne,"text","",dt());m.addGetterSetter(ne,"textDecoration","");m.addGetterSetter(ne,"underlineOffset",void 0,R());m.addGetterSetter(ne,"charRenderFunc",void 0);const Fl="",da="normal";function ua(a){a.fillText(this.partialText,0,0)}function pa(a){a.strokeText(this.partialText,0,0)}class he extends A{constructor(e){super(e),this.dummyCanvas=T.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 re.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:re.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=re.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 T.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return ne.prototype.setText.call(this,e)}_getContextFont(){return ne.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=Ye(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 f=t[d].char;let g=t[d].width+n;if(f===" "&&s==="justify"){const w=this.text().split(" ").length-1;g+=(this.pathLength-l)/w}const y=this._getPointAtLength(h+g);if(!y)return;const v=re.getLineLength(u.x,u.y,y.x,y.y);let b=0;if(o)try{b=o(t[d-1].char,f)*this.fontSize()}catch{b=0}u.x+=b,y.x+=b,this.textWidth+=b;const S=re.getPointOnLine(b+v/2,u.x,u.y,y.x,y.y),C=Math.atan2(y.y-u.y,y.x-u.x);this.glyphInfo.push({transposeX:S.x,transposeY:S.y,text:e[d],rotation:C,p0:u,p1:y,width:v}),h+=g}}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 T.releaseCanvas(this.dummyCanvas),super.destroy()}}he.prototype._fillFunc=ua;he.prototype._strokeFunc=pa;he.prototype._fillFuncHit=ua;he.prototype._strokeFuncHit=pa;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,R());m.addGetterSetter(he,"fontStyle",da);m.addGetterSetter(he,"align","left");m.addGetterSetter(he,"letterSpacing",0,R());m.addGetterSetter(he,"textBaseline","middle");m.addGetterSetter(he,"fontVariant",da);m.addGetterSetter(he,"text",Fl);m.addGetterSetter(he,"textDecoration","");m.addGetterSetter(he,"kerningFunc",void 0);const fa="tr-konva",Gl=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(a=>a+`.${fa}`).join(" "),Gn="nodesRect",Hl=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Nl={"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 zl(a,e,t){if(a==="rotater")return t;e+=T.degToRad(Nl[a]||0);const i=(T.radToDeg(e)%360+360)%360;return T._inRange(i,315+22.5,360)||T._inRange(i,0,22.5)?"ns-resize":T._inRange(i,45-22.5,45+22.5)?"nesw-resize":T._inRange(i,90-22.5,90+22.5)?"ew-resize":T._inRange(i,135-22.5,135+22.5)?"nwse-resize":T._inRange(i,180-22.5,180+22.5)?"ns-resize":T._inRange(i,225-22.5,225+22.5)?"nesw-resize":T._inRange(i,270-22.5,270+22.5)?"ew-resize":T._inRange(i,315-22.5,315+22.5)?"nwse-resize":(T.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}const Ni=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function Vl(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 ga(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 Ul(a,e){const t=Vl(a);return ga(a,e,t)}function Wl(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 Br=0;class W extends xt{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(Gl,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return T.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 fa+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(r=>r.isAncestorOf(this)?(T.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(Hl.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(Gn),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Gn,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 ga(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(f){const g=u.point(f);t.push(g)})});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(),Ni.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new ui({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=zl(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 A({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=T.degToRad(l),d=Math.sin(h),u=-Math.cos(h),f=s/2,g=o/2;let y=1/0;u<0?y=Math.min(y,-g/u):u>0&&(y=Math.min(y,(o-g)/u)),d<0?y=Math.min(y,-f/d):d>0&&(y=Math.min(y,(s-f)/d));const v=f+d*y,b=g+u*y,S=T._sign(o),C=v+d*c*S,w=b+u*c*S;t.moveTo(v,b),t.lineTo(C,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},Br++,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 S=this._getNodeRect();t=n.x()-S.width/2,i=-n.y()+S.height/2;const C=D.getAngle(this.rotateAnchorAngle());let w=Math.atan2(-i,t)+Math.PI/2-C;S.height<0&&(w-=Math.PI);const P=D.getAngle(this.rotation())+w,B=D.getAngle(this.rotationSnapTolerance()),M=Wl(this.rotationSnaps(),P,B)-S.rotation,x=Ul(S,M);this._fitNodesInto(x,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let f=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const S=f?{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(S.x-n.x(),2)+Math.pow(S.y-n.y(),2));const C=this.findOne(".top-left").x()>S.x?-1:1,w=this.findOne(".top-left").y()>S.y?-1:1;t=r*this.cos*C,i=r*this.sin*w,this.findOne(".top-left").x(S.x-t),this.findOne(".top-left").y(S.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(n.y());else if(this._movingAnchorName==="top-right"){if(u){const S=f?{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()-S.x,2)+Math.pow(S.y-n.y(),2));const C=this.findOne(".top-right").x()<S.x?-1:1,w=this.findOne(".top-right").y()>S.y?-1:1;t=r*this.cos*C,i=r*this.sin*w,this.findOne(".top-right").x(S.x+t),this.findOne(".top-right").y(S.y-i)}var g=n.position();this.findOne(".top-left").y(g.y),this.findOne(".bottom-right").x(g.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(n.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(n.x());else if(this._movingAnchorName==="bottom-left"){if(u){const S=f?{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(S.x-n.x(),2)+Math.pow(n.y()-S.y,2));const C=S.x<n.x()?-1:1,w=n.y()<S.y?-1:1;t=r*this.cos*C,i=r*this.sin*w,n.x(S.x-t),n.y(S.y+i)}g=n.position(),this.findOne(".top-left").x(g.x),this.findOne(".bottom-right").y(g.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(n.y());else if(this._movingAnchorName==="bottom-right"){if(u){const S=f?{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()-S.x,2)+Math.pow(n.y()-S.y,2));const C=this.findOne(".bottom-right").x()<S.x?-1:1,w=this.findOne(".bottom-right").y()<S.y?-1:1;t=r*this.cos*C,i=r*this.sin*w,this.findOne(".bottom-right").x(S.x+t),this.findOne(".bottom-right").y(S.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(f=this.centeredScaling()||e.altKey,f){const S=this.findOne(".top-left"),C=this.findOne(".bottom-right"),w=S.x(),_=S.y(),P=this.getWidth()-C.x(),B=this.getHeight()-C.y();C.move({x:-w,y:-_}),S.move({x:P,y:B})}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(),b=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:i,width:v,height:b,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();Br--,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(T._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(T._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:T.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 f;if(!u.getStage())return;const g=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const v=new Se;v.multiply(g.copy().invert()).multiply(d).multiply(g).multiply(y);const b=v.decompose();u.setAttrs(b),(f=u.getLayer())===null||f===void 0||f.batchDraw()}),this.rotation(T._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(T._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=T.degToRad(h),f=Math.sin(u),g=-Math.cos(u),y=i/2,v=r/2;let b=1/0;g<0?b=Math.min(b,-v/g):g>0&&(b=Math.min(b,(r-v)/g)),f<0?b=Math.min(b,-y/f):f>0&&(b=Math.min(b,(i-y)/f));const S=y+f*b,C=v+g*b,w=T._sign(r);this._batchChangeChild(".rotater",{x:S+f*d*w,y:C+g*d*w-o*g,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 _=this.anchorStyleFunc();_&&c.forEach(P=>{_(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=""),xt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return E.prototype.toObject.call(this)}clone(e){return E.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}W.isTransforming=()=>Br>0;function Yl(a){return a instanceof Array||T.warn("enabledAnchors value should be an array"),a instanceof Array&&a.forEach(function(e){Ni.indexOf(e)===-1&&T.warn("Unknown anchor name: "+e+". Available names are: "+Ni.join(", "))}),a||[]}W.prototype.className="Transformer";ae(W);m.addGetterSetter(W,"enabledAnchors",Ni,Yl);m.addGetterSetter(W,"flipEnabled",!0,Ae());m.addGetterSetter(W,"resizeEnabled",!0);m.addGetterSetter(W,"anchorSize",10,R());m.addGetterSetter(W,"rotateEnabled",!0);m.addGetterSetter(W,"rotateLineVisible",!0);m.addGetterSetter(W,"rotationSnaps",[]);m.addGetterSetter(W,"rotateAnchorOffset",50,R());m.addGetterSetter(W,"rotateAnchorAngle",0,R());m.addGetterSetter(W,"rotateAnchorCursor","crosshair");m.addGetterSetter(W,"rotationSnapTolerance",5,R());m.addGetterSetter(W,"borderEnabled",!0);m.addGetterSetter(W,"anchorStroke","rgb(0, 161, 255)");m.addGetterSetter(W,"anchorStrokeWidth",1,R());m.addGetterSetter(W,"anchorFill","white");m.addGetterSetter(W,"anchorCornerRadius",0,R());m.addGetterSetter(W,"borderStroke","rgb(0, 161, 255)");m.addGetterSetter(W,"borderStrokeWidth",1,R());m.addGetterSetter(W,"borderDash");m.addGetterSetter(W,"keepRatio",!0);m.addGetterSetter(W,"shiftBehavior","default");m.addGetterSetter(W,"centeredScaling",!1);m.addGetterSetter(W,"ignoreStroke",!1);m.addGetterSetter(W,"padding",0,R());m.addGetterSetter(W,"nodes");m.addGetterSetter(W,"node");m.addGetterSetter(W,"boundBoxFunc");m.addGetterSetter(W,"anchorDragBoundFunc");m.addGetterSetter(W,"anchorStyleFunc");m.addGetterSetter(W,"shouldOverdrawWholeArea",!1);m.addGetterSetter(W,"useSingleNodeRotation",!0);m.backCompat(W,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class He extends A{_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)}}He.prototype.className="Wedge";He.prototype._centroid=!0;He.prototype._attrsAffectingSize=["radius"];ae(He);m.addGetterSetter(He,"radius",0,R());m.addGetterSetter(He,"angle",0,R());m.addGetterSetter(He,"clockwise",!1);m.backCompat(He,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Hn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Xl=[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],ql=[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 jl(a,e){const t=a.data,i=a.width,r=a.height;let n,s,o,l,c,h,d,u,f,g,y,v,b,S,C,w,_,P,B,k;const M=e+e+1,x=i-1,$=r-1,H=e+1,V=H*(H+1)/2,z=new Hn,N=Xl[e],L=ql[e];let X=null,F=z,Q=null,se=null;for(let Y=1;Y<M;Y++)F=F.next=new Hn,Y===H&&(X=F);F.next=z,o=s=0;for(let Y=0;Y<r;Y++){v=b=S=C=l=c=h=d=0,u=H*(w=t[s]),f=H*(_=t[s+1]),g=H*(P=t[s+2]),y=H*(B=t[s+3]),l+=V*w,c+=V*_,h+=V*P,d+=V*B,F=z;for(let J=0;J<H;J++)F.r=w,F.g=_,F.b=P,F.a=B,F=F.next;for(let J=1;J<H;J++)n=s+((x<J?x:J)<<2),l+=(F.r=w=t[n])*(k=H-J),c+=(F.g=_=t[n+1])*k,h+=(F.b=P=t[n+2])*k,d+=(F.a=B=t[n+3])*k,v+=w,b+=_,S+=P,C+=B,F=F.next;Q=z,se=X;for(let J=0;J<i;J++)t[s+3]=B=d*N>>L,B!==0?(B=255/B,t[s]=(l*N>>L)*B,t[s+1]=(c*N>>L)*B,t[s+2]=(h*N>>L)*B):t[s]=t[s+1]=t[s+2]=0,l-=u,c-=f,h-=g,d-=y,u-=Q.r,f-=Q.g,g-=Q.b,y-=Q.a,n=o+((n=J+e+1)<x?n:x)<<2,v+=Q.r=t[n],b+=Q.g=t[n+1],S+=Q.b=t[n+2],C+=Q.a=t[n+3],l+=v,c+=b,h+=S,d+=C,Q=Q.next,u+=w=se.r,f+=_=se.g,g+=P=se.b,y+=B=se.a,v-=w,b-=_,S-=P,C-=B,se=se.next,s+=4;o+=i}for(let Y=0;Y<i;Y++){b=S=C=v=c=h=d=l=0,s=Y<<2,u=H*(w=t[s]),f=H*(_=t[s+1]),g=H*(P=t[s+2]),y=H*(B=t[s+3]),l+=V*w,c+=V*_,h+=V*P,d+=V*B,F=z;for(let fe=0;fe<H;fe++)F.r=w,F.g=_,F.b=P,F.a=B,F=F.next;let J=i;for(let fe=1;fe<=e;fe++)s=J+Y<<2,l+=(F.r=w=t[s])*(k=H-fe),c+=(F.g=_=t[s+1])*k,h+=(F.b=P=t[s+2])*k,d+=(F.a=B=t[s+3])*k,v+=w,b+=_,S+=P,C+=B,F=F.next,fe<$&&(J+=i);s=Y,Q=z,se=X;for(let fe=0;fe<r;fe++)n=s<<2,t[n+3]=B=d*N>>L,B>0?(B=255/B,t[n]=(l*N>>L)*B,t[n+1]=(c*N>>L)*B,t[n+2]=(h*N>>L)*B):t[n]=t[n+1]=t[n+2]=0,l-=u,c-=f,h-=g,d-=y,u-=Q.r,f-=Q.g,g-=Q.b,y-=Q.a,n=Y+((n=fe+H)<$?n:$)*i<<2,l+=v+=Q.r=t[n],c+=b+=Q.g=t[n+1],h+=S+=Q.b=t[n+2],d+=C+=Q.a=t[n+3],Q=Q.next,u+=w=se.r,f+=_=se.g,g+=P=se.b,y+=B=se.a,v-=w,b-=_,S-=P,C-=B,se=se.next,s+=i}}const Kl=function(e){const t=Math.round(this.blurRadius());t>0&&jl(e,t)};m.addGetterSetter(E,"blurRadius",0,R(),m.afterSetFilter);const Zl=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(E,"brightness",0,R(),m.afterSetFilter);const Jl=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)},Ql=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(E,"contrast",0,R(),m.afterSetFilter);const ec=function(a){var e,t,i,r,n,s,o,l,c;const h=a.data,d=a.width,u=a.height,f=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),g=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,b=!!((c=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&c!==void 0&&c),S=f*10,C=g*255,w=v*Math.PI/180,_=Math.cos(w),P=Math.sin(w),B=128/1020*S,k=new Uint8ClampedArray(h),M=new Float32Array(d*u);for(let z=0,N=0;N<h.length;N+=4,z++)M[z]=.2126*k[N]+.7152*k[N+1]+.0722*k[N+2];const x=[-1,0,1,-2,0,2,-1,0,1],$=[-1,-2,-1,0,0,0,1,2,1],H=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],V=z=>z<0?0:z>255?255:z;for(let z=1;z<u-1;z++)for(let N=1;N<d-1;N++){const L=z*d+N;let X=0,F=0;X+=M[L+H[0]]*x[0],F+=M[L+H[0]]*$[0],X+=M[L+H[1]]*x[1],F+=M[L+H[1]]*$[1],X+=M[L+H[2]]*x[2],F+=M[L+H[2]]*$[2],X+=M[L+H[3]]*x[3],F+=M[L+H[3]]*$[3],X+=M[L+H[5]]*x[5],F+=M[L+H[5]]*$[5],X+=M[L+H[6]]*x[6],F+=M[L+H[6]]*$[6],X+=M[L+H[7]]*x[7],F+=M[L+H[7]]*$[7],X+=M[L+H[8]]*x[8],F+=M[L+H[8]]*$[8];const Q=_*X+P*F,se=V(C+Q*B),Y=L*4;if(b){const J=se-C;h[Y]=V(k[Y]+J),h[Y+1]=V(k[Y+1]+J),h[Y+2]=V(k[Y+2]+J),h[Y+3]=k[Y+3]}else h[Y]=h[Y+1]=h[Y+2]=se,h[Y+3]=k[Y+3]}for(let z=0;z<d;z++){let N=z*4,L=((u-1)*d+z)*4;h[N]=k[N],h[N+1]=k[N+1],h[N+2]=k[N+2],h[N+3]=k[N+3],h[L]=k[L],h[L+1]=k[L+1],h[L+2]=k[L+2],h[L+3]=k[L+3]}for(let z=1;z<u-1;z++){let N=z*d*4,L=(z*d+(d-1))*4;h[N]=k[N],h[N+1]=k[N+1],h[N+2]=k[N+2],h[N+3]=k[N+3],h[L]=k[L],h[L+1]=k[L+1],h[L+2]=k[L+2],h[L+3]=k[L+3]}return a};m.addGetterSetter(E,"embossStrength",.5,R(),m.afterSetFilter);m.addGetterSetter(E,"embossWhiteLevel",.5,R(),m.afterSetFilter);m.addGetterSetter(E,"embossDirection","top-left",void 0,m.afterSetFilter);m.addGetterSetter(E,"embossBlend",!1,void 0,m.afterSetFilter);function dr(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 tc=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 C=0;C<t;C+=4)n=e[C+0],n<i?i=n:n>r&&(r=n),l=e[C+1],l<s?s=l:l>o&&(o=l),d=e[C+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 f,g,y,v,b,S;if(u>0)f=r+u*(255-r),g=i-u*(i-0),y=o+u*(255-o),v=s-u*(s-0),b=h+u*(255-h),S=c-u*(c-0);else{const C=(r+i)*.5;f=r+u*(r-C),g=i+u*(i-C);const w=(o+s)*.5;y=o+u*(o-w),v=s+u*(s-w);const _=(h+c)*.5;b=h+u*(h-_),S=c+u*(c-_)}for(let C=0;C<t;C+=4)e[C+0]=dr(e[C+0],i,r,g,f),e[C+1]=dr(e[C+1],s,o,v,y),e[C+2]=dr(e[C+2],c,h,S,b)};m.addGetterSetter(E,"enhance",0,R(),m.afterSetFilter);const ic=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(E,"hue",0,R(),m.afterSetFilter);m.addGetterSetter(E,"saturation",0,R(),m.afterSetFilter);m.addGetterSetter(E,"luminance",0,R(),m.afterSetFilter);const rc=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,f=.587*i+.413*o+.035*l,g=.114*i-.114*o+.293*l,y=.299*i-.3*o+1.25*l,v=.587*i-.586*o-1.05*l,b=.114*i+.886*o-.2*l;let S,C,w,_;for(let P=0;P<t;P+=4)S=e[P+0],C=e[P+1],w=e[P+2],_=e[P+3],e[P+0]=c*S+h*C+d*w+s,e[P+1]=u*S+f*C+g*w+s,e[P+2]=y*S+v*C+b*w+s,e[P+3]=_},nc=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,f=.114*i-.114*s+.293*o,g=.299*i-.3*s+1.25*o,y=.587*i-.586*s-1.05*o,v=.114*i+.886*s-.2*o;for(let b=0;b<t;b+=4){const S=e[b+0],C=e[b+1],w=e[b+2],_=e[b+3];e[b+0]=l*S+c*C+h*w,e[b+1]=d*S+u*C+f*w,e[b+2]=g*S+y*C+v*w,e[b+3]=_}};m.addGetterSetter(E,"hue",0,R(),m.afterSetFilter);m.addGetterSetter(E,"saturation",0,R(),m.afterSetFilter);m.addGetterSetter(E,"value",0,R(),m.afterSetFilter);const sc=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]},ac=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 f=s,g=n,y=360/g*Math.PI/180;for(let v=0;v<g;v+=1){const b=Math.sin(v*y),S=Math.cos(v*y);for(let C=0;C<f;C+=1){h=Math.floor(o+c*C/f*S),d=Math.floor(l+c*C/f*b);let w=(d*n+h)*4;const _=i[w+0],P=i[w+1],B=i[w+2],k=i[w+3];w=(v+C*n)*4,r[w+0]=_,r[w+1]=P,r[w+2]=B,r[w+3]=k}}},oc=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 f=s,g=n,y=0;let v,b;for(h=0;h<n;h+=1)for(d=0;d<s;d+=1){const S=h-o,C=d-l,w=Math.sqrt(S*S+C*C)*f/c;let _=(Math.atan2(C,S)*180/Math.PI+360+y)%360;_=_*g/360,v=Math.floor(_),b=Math.floor(w);let P=(b*n+v)*4;const B=i[P+0],k=i[P+1],M=i[P+2],x=i[P+3];P=(d*n+h)*4,r[P+0]=B,r[P+1]=k,r[P+2]=M,r[P+3]=x}},lc=function(a){const e=a.width,t=a.height;let i,r,n,s,o,l,c,h,d,u,f=Math.round(this.kaleidoscopePower());const g=Math.round(this.kaleidoscopeAngle()),y=Math.floor(e*(g%360)/360);if(f<1)return;const v=T.createCanvasElement();v.width=e,v.height=t;const b=v.getContext("2d").getImageData(0,0,e,t);T.releaseCanvas(v),ac(a,b,{polarCenterX:e/2,polarCenterY:t/2});let S=e/Math.pow(2,f);for(;S<=8;)S=S*2,f-=1;S=Math.ceil(S);let C=S,w=0,_=C,P=1;for(y+S>e&&(w=C,_=0,P=-1),r=0;r<t;r+=1)for(i=w;i!==_;i+=P)n=Math.round(i+y)%e,d=(e*r+n)*4,o=b.data[d+0],l=b.data[d+1],c=b.data[d+2],h=b.data[d+3],u=(e*r+i)*4,b.data[u+0]=o,b.data[u+1]=l,b.data[u+2]=c,b.data[u+3]=h;for(r=0;r<t;r+=1)for(C=Math.floor(S),s=0;s<f;s+=1){for(i=0;i<C+1;i+=1)d=(e*r+i)*4,o=b.data[d+0],l=b.data[d+1],c=b.data[d+2],h=b.data[d+3],u=(e*r+C*2-i-1)*4,b.data[u+0]=o,b.data[u+1]=l,b.data[u+2]=c,b.data[u+3]=h;C*=2}oc(b,a,{})};m.addGetterSetter(E,"kaleidoscopePower",2,R(),m.afterSetFilter);m.addGetterSetter(E,"kaleidoscopeAngle",0,R(),m.afterSetFilter);function xi(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 Bt(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 cc(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 hc(a,e){const t=xi(a,0,0),i=xi(a,a.width-1,0),r=xi(a,0,a.height-1),n=xi(a,a.width-1,a.height-1),s=e||10;if(Bt(t,i)<s&&Bt(i,n)<s&&Bt(n,r)<s&&Bt(r,t)<s){const o=cc([i,t,n,r]),l=[];for(let c=0;c<a.width*a.height;c++){const h=Bt(o,[a.data[c*4],a.data[c*4+1],a.data[c*4+2]]);l[c]=h<s?0:255}return l}}function dc(a,e){for(let t=0;t<a.width*a.height;t++)a.data[4*t+3]=e[t]}function uc(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 f=o+d-n,g=l+u-n;if(f>=0&&f<t&&g>=0&&g<e){const y=f*e+g,v=i[d*r+u];h+=a[y]*v}}s[c]=h===255*8?255:0}return s}function pc(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 f=o+d-n,g=l+u-n;if(f>=0&&f<t&&g>=0&&g<e){const y=f*e+g,v=i[d*r+u];h+=a[y]*v}}s[c]=h>=255*4?255:0}return s}function fc(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 f=o+d-n,g=l+u-n;if(f>=0&&f<t&&g>=0&&g<e){const y=f*e+g,v=i[d*r+u];h+=a[y]*v}}s[c]=h}return s}const gc=function(a){const e=this.threshold();let t=hc(a,e);return t&&(t=uc(t,a.width,a.height),t=pc(t,a.width,a.height),t=fc(t,a.width,a.height),dc(a,t)),a};m.addGetterSetter(E,"threshold",0,R(),m.afterSetFilter);const mc=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(E,"noise",.2,R(),m.afterSetFilter);const yc=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){T.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 f=o*e,g=f+e,y=l*e,v=y+e;let b=0;for(let S=f;S<g;S+=1)if(!(S>=t))for(let C=y;C<v;C+=1){if(C>=i)continue;const w=(t*C+S)*4;c+=s[w+0],h+=s[w+1],d+=s[w+2],u+=s[w+3],b+=1}c=c/b,h=h/b,d=d/b,u=u/b;for(let S=f;S<g;S+=1)if(!(S>=t))for(let C=y;C<v;C+=1){if(C>=i)continue;const w=(t*C+S)*4;s[w+0]=c,s[w+1]=h,s[w+2]=d,s[w+3]=u}}};m.addGetterSetter(E,"pixelSize",8,R(),m.afterSetFilter);const Sc=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(E,"levels",.5,R(),m.afterSetFilter);const vc=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(E,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(E,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(E,"blue",0,Gs,m.afterSetFilter);const Cc=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(E,"red",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(E,"green",0,function(a){return this._filterUpToDate=!1,a>255?255:a<0?0:Math.round(a)});m.addGetterSetter(E,"blue",0,Gs,m.afterSetFilter);m.addGetterSetter(E,"alpha",1,function(a){return this._filterUpToDate=!1,a>1?1:a<0?0:a});const bc=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)}},Tc=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},wc=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(E,"threshold",.5,R(),m.afterSetFilter);const K=An.Util._assign(An,{Arc:Fe,Arrow:pt,Circle:At,Ellipse:Qe,Image:Ie,Label:nn,Tag:ft,Line:Ge,Path:re,Rect:ui,RegularPolygon:et,Ring:gt,Sprite:Le,Star:tt,Text:ne,TextPath:he,Transformer:W,Wedge:He,Filters:{Blur:Kl,Brightness:Jl,Brighten:Zl,Contrast:Ql,Emboss:ec,Enhance:tc,Grayscale:ic,HSL:rc,HSV:nc,Invert:sc,Kaleidoscope:lc,Mask:gc,Noise:mc,Pixelate:yc,Posterize:Sc,RGB:vc,RGBA:Cc,Sepia:bc,Solarize:Tc,Threshold:wc}}),ma="media-editor-track.diagnostics.v1",Or="media-editor-track.diagnostics.failure-window.v1",ya="media-editor-track-diagnostics",Ke="snapshots",Sa="state",va="latest-failure-window",ni=1,sn=1,Nn=40,kc=48,xc=250,$n=20,Pc=100,_c=500,Fr=new Set(["pending-preview.begin","preview.sync.requested","media.seeking","media.seeked"]),Ac=new Set([...Fr,"media.current-slot.seek","media.preload-slot.seek","media.play.requested","media.pause.requested","slot.recovery-check","runtime.state"]),zn={debug:10,info:20,warn:30,error:40},Ne={enabled:!0,persist:!0,storageQuotaMb:10,maxSessions:20,maxHotEvents:500,includeFullSourceUrl:!0,consoleSeverityThreshold:"warn",highFrequencyEventThrottleMs:_c};function Vn(a){return`${a}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Ic(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function Ca(a){if(!a||typeof a!="object")return!1;const e=Object.getPrototypeOf(a);return e===Object.prototype||e===null}function kt(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:kt(a.cause,e+1,t)};if(e>=4)return"[max-depth]";if(Array.isArray(a))return a.slice(0,40).map(i=>kt(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(!Ca(a))return String(a);const i={};for(const r of Object.keys(a).slice(0,60))i[r]=kt(a[r],e+1,t);return i}return String(a)}function $i(a){if(!a)return null;const e=kt(a,0,new WeakSet);return Ca(e)?e:{value:e}}function Ec(a){return $i(a)}function Ot(a){return typeof a=="number"&&Number.isFinite(a)?a:null}function Pi(a){return typeof a=="string"&&a.length>0?a:null}function Rc(){var i,r,n,s,o;const a=typeof navigator<"u"?navigator:null,e={platform:Pi(a==null?void 0:a.platform),hardwareConcurrency:Ot(a==null?void 0:a.hardwareConcurrency),deviceMemory:Ot(a==null?void 0:a.deviceMemory),maxTouchPoints:Ot(a==null?void 0:a.maxTouchPoints),language:Pi(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:Pi((i=a==null?void 0:a.connection)==null?void 0:i.effectiveType),downlinkMbps:Ot((r=a==null?void 0:a.connection)==null?void 0:r.downlink),rttMs:Ot((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:Pi((o=a==null?void 0:a.connection)==null?void 0:o.type)};return{hardware:e,network:t}}function Un(a,e={}){const t=Rc(),i=$i(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 Mc(a){return a?a instanceof Error?{name:a.name,message:a.message,stack:a.stack??null,cause:kt(a.cause,1,new WeakSet)}:{name:null,message:typeof a=="string"?a:String(a),stack:null,cause:kt(a,1,new WeakSet)}:null}function Jt(){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 Dc(a){const e=a??Jt();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 ba(a){const e=Jt();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 Wn(a){return Dc(a.summary)}function Lc(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 Bc(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 Oc(a){return{enabled:(a==null?void 0:a.enabled)??Ne.enabled,persist:(a==null?void 0:a.persist)??Ne.persist,storageQuotaMb:(a==null?void 0:a.storageQuotaMb)??Ne.storageQuotaMb,maxSessions:Math.max(1,(a==null?void 0:a.maxSessions)??Ne.maxSessions),maxHotEvents:Math.max(20,(a==null?void 0:a.maxHotEvents)??Ne.maxHotEvents),includeFullSourceUrl:(a==null?void 0:a.includeFullSourceUrl)??Ne.includeFullSourceUrl,consoleSeverityThreshold:(a==null?void 0:a.consoleSeverityThreshold)??Ne.consoleSeverityThreshold,highFrequencyEventThrottleMs:Math.max(0,(a==null?void 0:a.highFrequencyEventThrottleMs)??Ne.highFrequencyEventThrottleMs)}}function Fc(){try{if(typeof globalThis.localStorage>"u")return null;const a=globalThis.localStorage.getItem(ma);if(!a)return null;const e=JSON.parse(a);return(e==null?void 0:e.version)!==ni||!Array.isArray(e.sessions)?null:e}catch{return null}}function Gc(){try{if(typeof globalThis.localStorage>"u")return null;const a=globalThis.localStorage.getItem(Or);if(!a)return null;const e=JSON.parse(a);return(e==null?void 0:e.version)!==sn||typeof e.sessionId!="string"||typeof e.failureEventId!="string"||!Array.isArray(e.events)?null:e}catch{return null}}function Ta(a){const e=Array.isArray(a.events)?a.events:[];return{...a,updatedAt:a.updatedAt||a.startedAt,events:e,summary:ba(e)}}function Ft(a,e,t={}){const i=a.slice(-e.maxSessions).map(n=>{const s=n.events.slice(-e.maxHotEvents);return Ta({...n,events:s,updatedAt:n.updatedAt||n.startedAt})});if(!t.enforceStorageQuota)return i;const r=Math.max(2e5,Math.floor(e.storageQuotaMb*1024*1024));for(;i.length>0&&JSON.stringify({version:ni,sessions:i}).length>r;)i.shift();return i}async function Hc(a){return wa(Sa,a)}async function Nc(a){return wa(va,a)}async function wa(a,e){if(typeof indexedDB>"u")return!1;try{const t=await new Promise((i,r)=>{const n=indexedDB.open(ya,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(Ke)||s.createObjectStore(Ke)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)});return await new Promise((i,r)=>{const n=t.transaction(Ke,"readwrite");n.objectStore(Ke).put(e,a),n.oncomplete=()=>i(),n.onerror=()=>r(n.error),n.onabort=()=>r(n.error)}),t.close(),!0}catch{return!1}}async function $c(){const a=await ka(Sa);return a&&typeof a=="object"&&"version"in a&&a.version===ni&&"sessions"in a&&Array.isArray(a.sessions)?a:null}async function zc(){const a=await ka(va);return a&&typeof a=="object"&&"version"in a&&a.version===sn&&"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 ka(a){if(typeof indexedDB>"u")return null;try{const e=await new Promise((i,r)=>{const n=indexedDB.open(ya,1);n.onupgradeneeded=()=>{const s=n.result;s.objectStoreNames.contains(Ke)||s.createObjectStore(Ke)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)}),t=await new Promise((i,r)=>{const o=e.transaction(Ke,"readonly").objectStore(Ke).get(a);o.onsuccess=()=>i(o.result??null),o.onerror=()=>r(o.error)});return e.close(),t}catch{return null}}function Vc(a,e){return!a&&!e?null:{...a??{},...e??{}}}class xa{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);p(this,"highFrequencyEventTimestamps",new Map);this.config=Oc(e);const t=Fc();this.latestFailureWindow=Gc(),this.state={version:ni,sessions:Ft((t==null?void 0:t.sessions)??[],this.config,{enforceStorageQuota:this.config.persist})},this.restoreIndexedDbState()}startSession(e){const t=new Date().toISOString(),i={sessionId:Vn("diag-session"),startedAt:Date.now(),updatedAt:Date.now(),metadata:Un(e,{capturedAt:t}),sequence:0,events:[],summary:Jt()};return this.currentSessionId=i.sessionId,this.state.sessions=Ft([...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.resolveHighFrequencyDecision(e,i);if(r==="drop")return null;const n=this.findCoalescedEvent(t,e,i);if(n)return r==="skip-update"||(this.updateCoalescedEvent(n,e,i),this.schedulePersist(),this.scheduleNotify()),n;t.sequence+=1;const s=this.createEvent(t,e,i,t.sequence);return t.events.push(s),Bc(t.summary,s),this.trimSessionEvents(t),this.captureFailureWindow(t,s),this.state.sessions=Ft(this.state.sessions,this.config),this.emitToConsole(s),this.schedulePersist(),this.scheduleNotify(),s}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:Wn(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:Wn(i),recentEvents:i.events.slice(-r).map(n=>Lc(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=Un(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:Jt()}}createEvent(e,t,i,r,n=Vn("diag-event")){return{eventId:n,sessionId:e.sessionId,sequence:r,timestamp:i,isoTime:new Date(i).toISOString(),perfTimeMs:Ic(),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:$i(t.mediaState),runtimeState:Ec(t.runtimeState),error:Mc(t.error),extra:$i(t.extra)}}trimSessionEvents(e){const t=e.events.length-this.config.maxHotEvents;t<=0||(e.events=e.events.slice(t),e.summary=ba(e.events))}findCoalescedEvent(e,t,i){if(!Fr.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>Pc)break;if(this.areEventIdentitiesEqual(r,s))return s}return null}resolveHighFrequencyDecision(e,t){if(e.severity==="warn"||e.severity==="error"||!Ac.has(e.eventName))return"record";const i=this.config.highFrequencyEventThrottleMs;if(i<=0)return"record";const r=this.buildHighFrequencyKey(e),n=this.highFrequencyEventTimestamps.get(r);return n!==void 0&&t-n<i?Fr.has(e.eventName)?"skip-update":"drop":(this.highFrequencyEventTimestamps.set(r,t),"record")}buildHighFrequencyKey(e){const t=this.buildEventIdentity(e);return[t.eventName,t.playbackAttemptId??"",t.trackId??"",t.clipId??"",t.slotKey??"",t.syncRequestId??""].join("|")}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:Jt()},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(zn[e.severity]<zn[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()},kc))}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()},xc)))}persistNow(){if(!this.config.persist)return;const e={version:ni,sessions:Ft(this.state.sessions,this.config,{enforceStorageQuota:!0})};if(this.state=e,typeof indexedDB>"u"){this.persistToLocalStorage(e);return}Promise.all([Hc(e),Nc(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([$c(),zc()]);if((i=e==null?void 0:e.sessions)!=null&&i.length){const n=new Map;[...this.state.sessions,...e.sessions].forEach(s=>{const o=Ta(s),l=n.get(o.sessionId);(!l||l.updatedAt<o.updatedAt)&&n.set(o.sessionId,o)}),this.state.sessions=Ft(Array.from(n.values()).sort((s,o)=>s.startedAt-o.startedAt),this.config,{enforceStorageQuota:!0})}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:Nn}),!this.activeFailureCapture||this.activeFailureCapture.sessionId!==e.sessionId)return;const i=this.buildFailureWindow(e,this.activeFailureCapture.failureEventId);i.length&&(this.latestFailureWindow={version:sn,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=Nn){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(ma,JSON.stringify(e)),t!==void 0)){if(t){globalThis.localStorage.setItem(Or,JSON.stringify(t));return}globalThis.localStorage.removeItem(Or)}}}function Pa(a,e){return Vc(a,e)}function Yn(a,e,t,i){const r=`[${a.toUpperCase()}] [${e}]`;if(i===void 0){console[a](`${r} ${t}`);return}console[a](`${r} ${t}`,i)}const O={debug(a,e,t){},debugLazy(a,e,t){},warn(a,e,t){Yn("warn",a,e,t)},error(a,e,t){Yn("error",a,e,t)}};class Pe{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={},this.brokenImageUrls.clear()}static renderClipCovers(e,t,i,r,n,s=!1){O.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 f=0;f<h;f++)d.push(Math.round(f*(n-1)/(h-1)));const u=[];for(let f=0;f<h;f++){const g=e[d[f]];u.push({coverUrl:g,singleImageWidth:c,segmentStartX:f*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 f=0;f<h;f++)d.push(Math.round(f*(n-1)/(h-1)));const u=[];for(let f=0;f<h;f++){const g=e[d[f]];u.push({coverUrl:g,singleImageWidth:c,segmentStartX:f*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 K.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 K.Image({image:h,cornerRadius:2,name:"cover-image",visible:this.isImageRenderable(n,h)});u.x(0),u.y(0),u.width(c),u.height(r),this.bindCoverImageLifecycle(n,h,u,e),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(this.isImageRenderable(t,s)){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)};this.listenToImageEvent(s,"load",()=>{this.brokenImageUrls.delete(t);const l={width:s.width,height:s.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},{once:!0}),this.listenToImageEvent(s,"error",()=>{this.brokenImageUrls.add(t),o(this.DEFAULT_DIMENSIONS)},{once:!0}),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],this.brokenImageUrls.delete(e)}static bindCoverImageLifecycle(e,t,i,r){this.listenToImageEvent(t,"load",()=>{this.brokenImageUrls.delete(e);try{i.visible(this.isImageRenderable(e,t)),this.requestRender(r)}catch{}}),this.listenToImageEvent(t,"error",()=>{this.brokenImageUrls.add(e);try{i.visible(!1),this.requestRender(r)}catch{}})}static isImageRenderable(e,t){if(this.brokenImageUrls.has(e)||!t.complete)return!1;const i=typeof t.naturalWidth=="number"?t.naturalWidth:t.width,r=typeof t.naturalHeight=="number"?t.naturalHeight:t.height;return i>0&&r>0}static listenToImageEvent(e,t,i,r){typeof e.addEventListener=="function"&&e.addEventListener(t,i,r)}}p(Pe,"MIN_IMAGE_DISPLAY_WIDTH",24),p(Pe,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),p(Pe,"MAX_CACHE_SIZE",1e3),p(Pe,"DEFAULT_DIMENSIONS",{width:160,height:90}),p(Pe,"keyframeDimensionsCache",{}),p(Pe,"keyframeDimensionsPromiseCache",{}),p(Pe,"imageCache",{}),p(Pe,"brokenImageUrls",new Set);const Uc='<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>',Wc='<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>',Yc='<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>',Xc='<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>',qc='<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>',jc='<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>',Kc='<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>',Zc='<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>',Jc='<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>',Qc='<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>',eh='<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>',th=new Map([["OmAi-camera",Uc],["OmAi-accept",Wc],["OmAi-display",Yc],["OmAi-hide",Xc],["OmAi-loading",qc],["OmAi-music",jc],["OmAi-volume",Kc],["OmAi-volume-mute",Zc],["OmAi-text",Jc],["clip-audio",Qc],["clip-without-audio",eh]]),Xn=new Map;function Ce(a){return th.get(a)??""}function ih(a){const e=Xn.get(a);if(e)return e;const t=Ce(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,Xn.set(a,r),r}const ue=3,qn=10,rh=4,nh=6,jn=8,Kn=14,Gr=10,sh=12,ah=4,_a=1,zi=28,Aa=8,Hr=19,Nr=15;function si(a,e,t,i,r=I.white,n=I.black,s=1){return new K.Rect({x:a,y:e,width:t,height:i,fill:r,stroke:n,strokeWidth:s})}function Vi(a,e,t,i=12,r="Arial",n=I.black,s="left",o="top"){return new K.Text({text:a,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:s,verticalAlign:o})}function Pt(a=0,e=0){return new K.Group({x:a,y:e})}function ai(a){a.ellipsis(!1),a.wrap("none"),a.width("auto")}function er(a,e,t,i){if(i){a.add(new K.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),a.add(new K.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}a.add(new K.Rect({x:0,y:0,width:ue,height:t,name:"clip-resize-left"})),a.add(new K.Rect({x:e-ue,y:0,width:ue,height:t,name:"clip-resize-right"}))}function oh(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(ue),r.height(t),n.x(e-ue),n.y(0),n.width(ue),n.height(t),!0)}function Ia(a,e,t){const i=e?a.clipSelectedBorder:I.transparent,r=e?_a:0;return t==="audio"?{background:I.audioClipBackground,label:a.audioClipText||a.clipName,accent:a.audioClipAccent||a.clipHandle,coverBackground:a.clipCoverBackground||ee.clipCoverBackground,border:i,borderWidth:r}:t==="text"?{background:I.textClipBackground,label:a.clipName,accent:a.clipHandle,coverBackground:a.clipCoverBackground||I.accentCoverFallback,border:i,borderWidth:r}:{background:I.videoClipBackground,label:a.clipName,accent:a.clipHandle,coverBackground:a.clipCoverBackground||I.accentCoverFallback,border:i,borderWidth:r}}function lh(a,e,t,i){const r=si(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),er(a,e,t,!0)}function ch(a,e,t){const i=si(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),a.add(i),er(a,e.width,e.height,!1);const r=15,n=e.height-r-4,s=e.width-ue*2,o=Pt(ue,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:s,height:n}),a.add(o);const l=si(0,0,s,n,t.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const c=Pt(0,0);c.name("clip-covers-group"),o.add(c),Pe.renderClipCovers(c,e.thumbnails??[],s,n,e.videoSrc,e.deferCoverRender);const h=s>=120?zi+Aa:0,d=Vi(`${e.clipName} ${U.formatDuration(e.duration)}`,ue,e.height-r,Gr,"Arial",t.label,"left","middle");d.height(r),ai(d),d.name("clip-label"),a.add(d),h>0&&Ra(a,e.width,e.height,e.hasSeparatedAudio)}function hh(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),!oh(a,e.width,e.height)))return!1;const l=15,c=e.height-l-4,h=e.width-ue*2;r.x(ue),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),Pe.renderClipCovers(s,e.thumbnails??[],h,c,e.videoSrc,e.deferCoverRender);const d=h>=120?zi+Aa:0;o.text(`${e.clipName} ${U.formatDuration(e.duration)}`),o.x(ue),o.y(e.height-l),o.fill(t.label),o.height(l),ai(o);const u=a.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&Ra(a,e.width,e.height,e.hasSeparatedAudio),!0}function dh(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 Ea(a,e,t,i,r){a.name()||a.name(r);const n=ih(e);if(!n)return 0;const s=new K.Image({x:0,y:0,width:t,height:i,image:n,listening:!1});return s.name(`${r}-image`),a.add(s),dh(a,n),t}function Ra(a,e,t,i){const r=Pt(Math.max(ue,e-ue-zi-2),Math.max(0,t-15));r.name("video-audio-status");const n=Pt(Math.max(0,zi-Hr),0),s=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";n.name(s),Ea(n,o,Hr,Nr,`${s}-icon`),r.add(n),a.add(r)}function uh(a,e,t){const i=si(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(6),i.name("clip-background"),a.add(i),er(a,e.width,e.height,!1);const r=ue+qn,n=Math.max(0,e.width-ue*2-qn*2),s=rh,o=Pt(r,s),l=Ea(o,"clip-audio",Hr,Nr,"audio-clip-icon");a.add(o);const c=r+l+jn,h=Math.max(0,n-l-jn);if(e.audioBadgeText&&h>0){const u=Vi(e.audioBadgeText,c,s,Gr,"Arial",t.label,"left","middle");u.height(Nr),ai(u),u.name("audio-clip-badge"),a.add(u)}const d=Vi(e.clipName,r,e.height-nh-Kn,Gr,"Arial",t.label,"left","middle");d.height(Kn),ai(d),d.name("clip-label"),a.add(d)}function ph(a,e,t){const i=si(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),a.add(i),er(a,e.width,e.height,!1);const r=Vi(e.clipName,ah,0,sh,"Arial",t.label,"left","middle");r.height(e.height),r.lineHeight(1),ai(r),r.name("clip-label"),a.add(r)}function Ma(a,e){const t=e.width<=ii,i=Ia(e.theme,e.isSelected,e.clipType);if(a.destroyChildren(),t){lh(a,e.width,e.height,i);return}if(e.clipType==="audio"){uh(a,e,i);return}if(e.clipType==="text"){ph(a,e,i);return}ch(a,e,i)}function fh(a,e){if(e.width<=ii||e.clipType!=="video")return!1;const i=Ia(e.theme,e.isSelected,e.clipType);return hh(a,e,i)}function gh(a,e,t,i,r,n,s,o=!1,l,c,h="video",d=!1,u=!1,f){const g=Pt(a,e);return g.clip({x:0,y:0,width:t,height:i}),Ma(g,{width:t,height:i,clipName:r,audioBadgeText:f,duration:n,theme:s,isSelected:o,thumbnails:l,videoSrc:c,clipType:h,hasSeparatedAudio:d,deferCoverRender:u}),g}function mh(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 f={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:n??Gi,isSelected:s,thumbnails:o,videoSrc:l,clipType:c,hasSeparatedAudio:h,deferCoverRender:d};fh(a,f)||Ma(a,f)}function yh(a,e,t,i){return new K.Rect({x:a,y:e,width:t,height:i,stroke:I.clipSelectedBorder,strokeWidth:_a,fillEnabled:!1})}function $r(a,e=bt.stroke,t=1){return new K.Line({points:a,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function Sh(a,e,t,i=12,r="Arial",n=bt.text,s="left",o="top"){return new K.Text({text:a,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:s,verticalAlign:o})}function vh(a=0,e=0){return new K.Group({x:a,y:e})}function Ch(a,e,t,i,r,n,s,o){const l=o||i,c=s==="major"?l*.6:l*.3,h=$r([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=Sh(U.formatTime(r),e,d,10,"Arial",n.timeText,"center");u.name("time-tick-text"),a.add(u)}}function bh(a,e,t,i,r,n){const s=vh(e,t);for(let o=0;o<=i;o+=n)s.add($r([o,0,o,r],un.line,.5));for(let o=0;o<=r;o+=n)s.add($r([0,o,i,o],un.line,.5));a.add(s)}class de{static createStage(e,t,i){return new K.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new K.Layer;return t.name(e),t}static createRect(e,t,i,r,n=bt.fill,s=bt.stroke,o=1){return new K.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=bt.text,o="left",l="top"){return new K.Text({text:e,x:t,y:i,fontSize:r,fontFamily:n,fill:s,align:o,verticalAlign:l})}static createLine(e,t=bt.stroke,i=1){return new K.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new K.Group({x:e,y:t})}static drawTimeTick(e,t,i,r,n,s,o,l){Ch(e,t,i,r,n,s,o,l)}static drawGrid(e,t,i,r,n,s){bh(e,t,i,r,n,s)}static clearImageCache(){Pe.clearImageCache()}static createClipGroup(e,t,i,r,n,s,o,l=!1,c,h,d="video",u=!1,f=!1,g){return gh(e,t,i,r,n,s,o,l,c,h,d,u,f,g)}static updateClipGroup(e,t,i,r,n,s,o=!1,l,c,h="video",d=!1,u=!1,f){mh(e,t,i,r,n,s,o,l,c,h,d,u,f)}static createSelectionEffect(e,t,i,r){return yh(e,t,i,r)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}p(de,"RESIZE_AREA_WIDTH",3);const Yt=8;function pe(a,e,t){return de.timeToPixels(a,e)-t+Te}function ye(a,e){const t=Math.max(a,0),i=de.timeToPixels(t,e);return i<=ii?ii:i}function Th(a,e){const t=pe(a.startTime,a.zoom,a.scrollLeft),i=ye(a.duration,a.zoom);return t+i>0&&t<e}function wh(a){for(const e of a.clips){const t=pe(e.startTime,a.zoom,a.scrollLeft),i=ye(e.duration,a.zoom),r=a.y>=a.trackY&&a.y<=a.trackY+a.trackHeight;if(a.x>=t&&a.x<=t+Yt&&r||a.x>=t+i-Yt&&a.x<=t+i&&r)return"ew-resize";if(a.x>t+Yt&&a.x<t+i-Yt&&r)return"pointer"}return"default"}class Li{constructor(e,t,i){p(this,"clip");p(this,"onUpdate");p(this,"onSplit");this.clip=Zr({...e,endTime:U.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:U.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=pe(this.clip.startTime,i,s),l=ye(this.clip.duration,i),c=Yt;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 tr(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 ir(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)}function Ui(){return{kind:"idle"}}function Zn(a){return!!a&&a.kind!=="idle"}function Wi(a){return(a==null?void 0:a.kind)==="draggingMove"||(a==null?void 0:a.kind)==="draggingResizeLeft"||(a==null?void 0:a.kind)==="draggingResizeRight"}function St(a){return!a||a.kind==="idle"||a.kind==="boxSelecting"?null:a.context}function Yi(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 kh(a){const e=Yi(a);return e?e==="move"?"grabbing":"ew-resize":null}function _i(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:Ui(),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=Ph(a.context,e,Yi(a)||"move");return a.kind==="pressed"?_h(a.context,e.activationThreshold,e.clientX,e.clientY)?{state:xh(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:Wi(a)}};const t=e.type==="POINTER_UP"&&Wi(a);return{state:Ui(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function xh(a,e){return a==="resize-left"?{kind:"draggingResizeLeft",context:e}:a==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function Ph(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 ce=class ce{constructor(e,t,i,r,n,s,o,l,c,h,d,u,f,g,y,v,b,S,C,w,_,P,B,k,M,x=ce.DEFAULT_DRAG_ACTIVATION_THRESHOLD,$=!1,H=ce.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",Ui());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=>{Zn(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.interactionState;if(!Wi(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=St(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=f,this.onHorizontalDragAutoScroll=g,this.onClipOverlap=y,this.onClipCrossTrackPreview=v,this.onClipCrossTrack=b,this.onClearDropPreview=S,this.onClearSelection=C,this.onSnapGuideChange=w,this.onClipToggleSelection=_,this.onSetSingleSelection=P,this.getMultiDragClipIds=B,this.onMultiDragMove=k,this.onMultiDragInteractionEnd=M,this.dragActivationThreshold=Math.max(0,x),this.enableClipSnap=$,this.clipSnapThreshold=Math.max(0,H),this.trackGroup=de.createGroup(0,n),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}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})}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const e=de.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"?gi.videoFill:gi.audioFill,i=this.trackType==="text"?"#C9CBD4":this.trackType==="video"?gi.videoStroke:gi.audioStroke,r=pe(e.startTime,this.zoom,this.scrollLeft),n=ye(e.duration,this.zoom),s=de.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=tr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(ir({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,U.pixelsToTime(n-Te+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=pe(e.startTime,this.zoom,this.scrollLeft),i=ye(e.duration,this.zoom),r=2,n=this.trackHeight-4,s=de.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 f=u.getBoundingClientRect(),g=t.clientX-f.left,y=t.clientY-f.top;if(r){this.multiDragOriginalPositions.clear();for(const b of this.selectedClipIds){const S=this.clips.find(C=>C.getClip().id===b);if(S){const C=S.getClip();this.multiDragOriginalPositions.set(b,{startTime:C.startTime,duration:C.duration})}}}let v;c.isPointInResizeHandle(g,y,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(v=c.getClip().isResizingLeft?"resize-left":"resize-right",c.startResize({x:g,y})):(v="move",c.startDrag({x:g,y}),this.trackGroup.moveToTop()),this.applyInteractionTransition(_i(this.interactionState,{type:"POINTER_DOWN",operation:v,clipId:e,originalClipsState:n,nonDraggedClips:s,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:g,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=_i(t,{type:e});this.interactionState=n.state,n.effects.commit&&this.handleClipMoveEnd(r,t),this.layer.batchDraw()}finally{this.interactionState=Ui(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}resolveDraggedClipForInteraction(e=this.interactionState){const t=St(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,e.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const t=kh(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()}handleClipMoveEnd(e,t){var y,v,b;const i=t??this.interactionState,r=St(i)||{clipId:e.id,originalClipsState:[e],nonDraggedClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:0,crossTrackDragOffsetY:0},n=Yi(i)||(e.isResizingLeft?"resize-left":e.isResizingRight?"resize-right":"move"),s=n==="move",o=s&&this.multiDragOriginalPositions.size>0,l=(y=this.clipGroups)==null?void 0:y.get(e.id);if(l&&l.y(2),o){const S=this.multiDragOriginalPositions.get(e.id),C=S?e.startTime-S.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:e.id,deltaTime:C,targetTrackY:r.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:r.crossTrackDragOffsetY,isFinal:!0})){for(const M of this.selectedClipIds){const x=(v=this.clipGroups)==null?void 0:v.get(M);x==null||x.y(2)}this.multiDragOriginalPositions.clear();return}const w=[],_=[];for(const[k,M]of this.multiDragOriginalPositions){const x=this.clips.find(N=>N.getClip().id===k);if(!x)continue;const $=Math.max(0,M.startTime+C),H={...x.getClip(),startTime:$,endTime:$+M.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(k)};w.push(H);const V=r.originalClipsState.find(N=>N.id===k);V&&_.push(V);const z=(b=this.clipGroups)==null?void 0:b.get(k);z&&z.y(2)}const P=[];for(const k of this.clips){const M=k.getClip(),x=w.find($=>$.id===M.id);x?P.push(x):P.push({...M,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}P.sort((k,M)=>k.startTime-M.startTime),this.isVisualUpdate=!0;for(const k of P)this.clips.find(x=>x.getClip().id===k.id)&&this.handleClipUpdate(k);this.isVisualUpdate=!1;const B=_.map(k=>{const M=w.find(x=>x.id===k.id);return M&&(k.startTime!==M.startTime||k.duration!==M.duration)?{clipId:k.id,previousState:k,newState:M}:null}).filter(k=>k!==null);B.length>0&&this.onClipUpdate(e,_.find(k=>k.id===e.id),B),this.multiDragOriginalPositions.clear();return}if(s&&this.onClipCrossTrack&&this.config.id){const S=r.originalClipsState.find(w=>w.id===e.id)??null;if(this.onClipCrossTrack(e,S,r.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}const c=s?[...r.nonDraggedClips]:[];let h=!1;const d=e.startTime+e.duration;for(const S of c){const C=S.startTime+S.duration;if(e.startTime<C&&d>S.startTime){h=!0;break}}if(s&&h&&this.onClipOverlap&&this.config.id){const S=r.originalClipsState.find(C=>C.id===e.id)??null;this.onClipOverlap(e,this.config.id,S);return}const u=r.nonDraggedClips.map(S=>({...S}));if(n==="resize-right"){const S=r.originalClipsState.find(C=>C.id===e.id);if(S){const C=this.computeResizeRightPushFollowers(S,e,r.nonDraggedClips);for(const w of C){const _=u.findIndex(P=>P.id===w.id);_>=0&&(u[_]={...w,isSelected:!1})}}}let f=u.findIndex(S=>S.startTime>=e.startTime);f===-1&&(f=u.length),r.nonDraggedClips.forEach(S=>{S.isSelected=!1});const g={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};u.splice(f,0,g),this.updateAllClips(u),this.buildAndSendUpdates(g,u,r.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=wh({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 Zn(this.interactionState)}handleDragMove(e){const t=this.interactionState,i=this.layer.getStage(),r=i==null?void 0:i.container();if(!r)return;const n=r.getBoundingClientRect(),s=_i(t,{type:"POINTER_MOVE",clientX:e.clientX,clientY:e.clientY,localY:e.clientY-n.top,activationThreshold:this.dragActivationThreshold});this.interactionState=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=ye(e.duration,this.zoom);this.updateClipViewportState(e);const n=e.isSelected;(e.isDragging||n)&&i.moveToTop(),i.opacity(e.opacity),de.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:U.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){O.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){}setScrollLeft(e){this.scrollLeft=e,this.clips.forEach(n=>{const s=n.getClip();this.updateClipViewportState(s)});const t=this.interactionState,i=St(t),r=_i(t,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=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=Th({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(pe(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=de.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||ee.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(){O.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=pe(t,this.zoom,this.scrollLeft);o.x(c),o.y(this.resolveClipRenderY(e,r)),o.moveToTop(),de.updateClipGroup(o,ye(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.interactionState,i=St(t);if(Wi(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var b,S,C,w,_,P;const r=this.interactionState,n=St(r),s=Yi(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,f=s==="move",g=f&&this.multiDragOriginalPositions.size>0;f&&O.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:u,currentTrackId:this.config.id,offsetY:n.crossTrackDragOffsetY}));const y=l.getClip(),v=(b=this.clipGroups)==null?void 0:b.get(y.id);if(v){const B=f&&n.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(y.id,B);const k=n.originalClipsState.find(L=>L.id===y.id);if(!k)return;const M=this.buildPreviewClip(y,k,d,n,s);if(!M){this.hideDropPreview(),(S=this.onClearDropPreview)==null||S.call(this),this.updateSnapGuideLine(null);return}const x=M.clip,$=x.startTime-k.startTime,H=this.applyPreviewClipState(l,x),V=pe(x.startTime,this.zoom,this.scrollLeft),z=ye(x.duration,this.zoom);v.x(V),v.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)),v.visible(V+z>0&&V<this.layer.width()),H&&(this.updateClipGroup(x),v.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)));let N=!1;if(g){this.onMultiDragMove&&this.config.id&&(N=this.onMultiDragMove({draggedClipId:y.id,deltaTime:$,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[L,X]of this.multiDragOriginalPositions){if(L===y.id)continue;const F=this.clips.find(Y=>Y.getClip().id===L);if(!F)continue;const Q=Math.max(0,X.startTime+$),se=(C=this.clipGroups)==null?void 0:C.get(L);if(se){const Y=pe(Q,this.zoom,this.scrollLeft);se.x(Y),se.y(this.resolveClipRenderY(L,n.crossTrackDragOffsetY)),se.visible(Y+ye(X.duration,this.zoom)>0&&Y<this.layer.width());const J=F.getClip();de.updateClipGroup(se,ye(J.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(J),J.duration,this.theme,!0,J.thumbnails,J.src,J.type,!!J.separatedAudioClipId,!0,this.getClipAudioBadgeText(J))}}}if(!g&&M.resizePushFollowers.length>0)for(const L of M.resizePushFollowers){const X=(w=this.clipGroups)==null?void 0:w.get(L.id);if(!X)continue;const F=pe(L.startTime,this.zoom,this.scrollLeft);X.x(F),X.y(this.resolveClipRenderY(L.id,n.crossTrackDragOffsetY)),X.visible(F+ye(L.duration,this.zoom)>0&&F<this.layer.width())}f&&this.onClipCrossTrackPreview&&this.config.id&&!N?this.onClipCrossTrackPreview(x,n.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():N?this.hideDropPreview():this.showDropPreview(x),this.updateSnapGuideLine(M.guideTime)}else this.hideDropPreview(),(_=this.onClearDropPreview)==null||_.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(d,h.width),this.layer.batchDraw(),(P=this.dragOverlayLayer)==null||P.batchDraw()}buildPreviewClip(e,t,i,r,n){const s=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=U.pixelsToTime(s,this.zoom);let l;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};const c=this.constrainResizePreviewToTrackBounds(this.applyClipSnap(l,t,r.snapCandidateClips),t,r.nonDraggedClips),h=c.clip.isResizingRight?this.computeResizeRightPushFollowers(t,c.clip,r.nonDraggedClips):[];return{...c,resizePushFollowers:h}}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}}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}computeResizeRightPushFollowers(e,t,i){if(!t.isResizingRight)return[];const r=t.startTime+t.duration,n=U.calculateEndTime(e.startTime,e.duration),s=[...i].filter(h=>h.startTime>=n).sort((h,d)=>h.startTime-d.startTime);if(s.length===0)return[];const o=s[0],l=r-o.startTime;if(l<=0)return[];const c=l;return s.map(h=>({...h,startTime:h.startTime+c,endTime:h.startTime+c+h.duration}))}buildResizeLeftPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const f=U.calculateEndTime(t.startTime,t.duration);let g=Math.max(0,t.startTime+i),y=f-g;return y<ce.MIN_CLIP_DURATION_MS&&(y=ce.MIN_CLIP_DURATION_MS,g=f-y),{...e,startTime:g,duration:y,endTime:g+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=U.calculateEndTime(t.startTime,t.duration);let h=t.startTime+l,d=t.duration-l,u;return d<ce.MIN_CLIP_DURATION_MS?(d=ce.MIN_CLIP_DURATION_MS,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(ce.MIN_CLIP_DURATION_MS,t.duration+i);return{...e,startTime:t.startTime,duration:o,endTime:t.startTime+o,startTimeAtSource:0,endTimeAtSource:o,sourceDuration:o}}let r=Math.max(ce.MIN_CLIP_DURATION_MS,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=U.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<ce.MIN_CLIP_DURATION_MS||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<ce.MIN_CLIP_DURATION_MS||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(pe(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(ce.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=ce.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(ce,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),p(ce,"DEFAULT_CLIP_SNAP_THRESHOLD",8),p(ce,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(ce,"AUTO_SCROLL_MAX_SPEED",18),p(ce,"MIN_CLIP_DURATION_MS",1);let Xi=ce;/**
|
|
16
16
|
* @license
|
|
17
17
|
* Copyright 2019 Google LLC
|
|
18
18
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
19
|
-
*/const
|
|
19
|
+
*/const Bi=globalThis,an=Bi.ShadowRoot&&(Bi.ShadyCSS===void 0||Bi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Da=Symbol(),Jn=new WeakMap;let Ah=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==Da)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(an&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=Jn.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&Jn.set(t,e))}return e}toString(){return this.cssText}};const Ih=a=>new Ah(typeof a=="string"?a:a+"",void 0,Da),Eh=(a,e)=>{if(an)a.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),r=Bi.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,a.appendChild(i)}},Qn=an?a=>a:a=>a instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return Ih(t)})(a):a;/**
|
|
20
20
|
* @license
|
|
21
21
|
* Copyright 2017 Google LLC
|
|
22
22
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
23
|
-
*/const{is:
|
|
23
|
+
*/const{is:Rh,defineProperty:Mh,getOwnPropertyDescriptor:Dh,getOwnPropertyNames:Lh,getOwnPropertySymbols:Bh,getPrototypeOf:Oh}=Object,Ze=globalThis,es=Ze.trustedTypes,Fh=es?es.emptyScript:"",ur=Ze.reactiveElementPolyfillSupport,Qt=(a,e)=>a,zr={toAttribute(a,e){switch(e){case Boolean:a=a?Fh: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}},La=(a,e)=>!Rh(a,e),ts={attribute:!0,type:String,converter:zr,reflect:!1,useDefault:!1,hasChanged:La};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Ze.litPropertyMetadata??(Ze.litPropertyMetadata=new WeakMap);let Ct=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=ts){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&&Mh(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){const{get:r,set:n}=Dh(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)??ts}static _$Ei(){if(this.hasOwnProperty(Qt("elementProperties")))return;const e=Oh(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Qt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Qt("properties"))){const t=this.properties,i=[...Lh(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(Qn(r))}else e!==void 0&&t.push(Qn(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 Eh(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:zr).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:zr;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??La)(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){}};Ct.elementStyles=[],Ct.shadowRootOptions={mode:"open"},Ct[Qt("elementProperties")]=new Map,Ct[Qt("finalized")]=new Map,ur==null||ur({ReactiveElement:Ct}),(Ze.reactiveElementVersions??(Ze.reactiveElementVersions=[])).push("2.1.2");/**
|
|
24
24
|
* @license
|
|
25
25
|
* Copyright 2017 Google LLC
|
|
26
26
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
27
|
-
*/const
|
|
28
|
-
\f\r]`,Gt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,
|
|
29
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),
|
|
27
|
+
*/const ei=globalThis,is=a=>a,qi=ei.trustedTypes,rs=qi?qi.createPolicy("lit-html",{createHTML:a=>a}):void 0,Ba="$lit$",je=`lit$${Math.random().toFixed(9).slice(2)}$`,Oa="?"+je,Gh=`<${Oa}>`,ct=document,oi=()=>ct.createComment(""),li=a=>a===null||typeof a!="object"&&typeof a!="function",on=Array.isArray,Hh=a=>on(a)||typeof(a==null?void 0:a[Symbol.iterator])=="function",pr=`[
|
|
28
|
+
\f\r]`,Gt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ns=/-->/g,ss=/>/g,rt=RegExp(`>|${pr}(?:([^\\s"'>=/]+)(${pr}*=${pr}*(?:[^
|
|
29
|
+
\f\r"'\`<>=]|("|')|))|$)`,"g"),as=/'/g,os=/"/g,Fa=/^(?:script|style|textarea|title)$/i,Nh=a=>(e,...t)=>({_$litType$:a,strings:e,values:t}),j=Nh(1),ht=Symbol.for("lit-noChange"),le=Symbol.for("lit-nothing"),ls=new WeakMap,ot=ct.createTreeWalker(ct,129);function Ga(a,e){if(!on(a)||!a.hasOwnProperty("raw"))throw Error("invalid template strings array");return rs!==void 0?rs.createHTML(e):e}const $h=(a,e)=>{const t=a.length-1,i=[];let r,n=e===2?"<svg>":e===3?"<math>":"",s=Gt;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===Gt?h[1]==="!--"?s=ns:h[1]!==void 0?s=ss:h[2]!==void 0?(Fa.test(h[2])&&(r=RegExp("</"+h[2],"g")),s=rt):h[3]!==void 0&&(s=rt):s===rt?h[0]===">"?(s=r??Gt,d=-1):h[1]===void 0?d=-2:(d=s.lastIndex-h[2].length,c=h[1],s=h[3]===void 0?rt:h[3]==='"'?os:as):s===os||s===as?s=rt:s===ns||s===ss?s=Gt:(s=rt,r=void 0);const f=s===rt&&a[o+1].startsWith("/>")?" ":"";n+=s===Gt?l+Gh:d>=0?(i.push(c),l.slice(0,d)+Ba+l.slice(d)+je+f):l+je+(d===-2?o:f)}return[Ga(a,n+(a[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class ci{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]=$h(e,t);if(this.el=ci.createElement(c,i),ot.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=ot.nextNode())!==null&&l.length<o;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(Ba)){const u=h[s++],f=r.getAttribute(d).split(je),g=/([.?@])?(.*)/.exec(u);l.push({type:1,index:n,name:g[2],strings:f,ctor:g[1]==="."?Vh:g[1]==="?"?Uh:g[1]==="@"?Wh:rr}),r.removeAttribute(d)}else d.startsWith(je)&&(l.push({type:6,index:n}),r.removeAttribute(d));if(Fa.test(r.tagName)){const d=r.textContent.split(je),u=d.length-1;if(u>0){r.textContent=qi?qi.emptyScript:"";for(let f=0;f<u;f++)r.append(d[f],oi()),ot.nextNode(),l.push({type:2,index:++n});r.append(d[u],oi())}}}else if(r.nodeType===8)if(r.data===Oa)l.push({type:2,index:n});else{let d=-1;for(;(d=r.data.indexOf(je,d+1))!==-1;)l.push({type:7,index:n}),d+=je.length-1}n++}}static createElement(e,t){const i=ct.createElement("template");return i.innerHTML=e,i}}function _t(a,e,t=a,i){var s,o;if(e===ht)return e;let r=i!==void 0?(s=t._$Co)==null?void 0:s[i]:t._$Cl;const n=li(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=_t(a,r._$AS(a,e.values),r,i)),e}class zh{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)??ct).importNode(t,!0);ot.currentNode=r;let n=ot.nextNode(),s=0,o=0,l=i[0];for(;l!==void 0;){if(s===l.index){let c;l.type===2?c=new pi(n,n.nextSibling,this,e):l.type===1?c=new l.ctor(n,l.name,l.strings,this,e):l.type===6&&(c=new Yh(n,this,e)),this._$AV.push(c),l=i[++o]}s!==(l==null?void 0:l.index)&&(n=ot.nextNode(),s++)}return ot.currentNode=ct,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 pi{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=_t(this,e,t),li(e)?e===le||e==null||e===""?(this._$AH!==le&&this._$AR(),this._$AH=le):e!==this._$AH&&e!==ht&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Hh(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&&li(this._$AH)?this._$AA.nextSibling.data=e:this.T(ct.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=ci.createElement(Ga(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 zh(r,this),o=s.u(this.options);s.p(t),this.T(o),this._$AH=s}}_$AC(e){let t=ls.get(e.strings);return t===void 0&&ls.set(e.strings,t=new ci(e)),t}k(e){on(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 pi(this.O(oi()),this.O(oi()),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=is(e).nextSibling;is(e).remove(),e=r}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class rr{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=_t(this,e,t,0),s=!li(e)||e!==this._$AH&&e!==ht,s&&(this._$AH=e);else{const o=e;let l,c;for(e=n[0],l=0;l<n.length-1;l++)c=_t(this,o[i+l],t,l),c===ht&&(c=this._$AH[l]),s||(s=!li(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 Vh extends rr{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===le?void 0:e}}class Uh extends rr{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==le)}}class Wh extends rr{constructor(e,t,i,r,n){super(e,t,i,r,n),this.type=5}_$AI(e,t=this){if((e=_t(this,e,t,0)??le)===ht)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 Yh{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){_t(this,e)}}const fr=ei.litHtmlPolyfillSupport;fr==null||fr(ci,pi),(ei.litHtmlVersions??(ei.litHtmlVersions=[])).push("3.3.2");const hi=(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 pi(e.insertBefore(oi(),n),n,void 0,t??{})}return r._$AI(a),r};/**
|
|
30
30
|
* @license
|
|
31
31
|
* Copyright 2017 Google LLC
|
|
32
32
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
33
|
-
*/const lt=globalThis;let
|
|
33
|
+
*/const lt=globalThis;let Oi=class extends Ct{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=hi(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 ht}};var Ls;Oi._$litElement$=!0,Oi.finalized=!0,(Ls=lt.litElementHydrateSupport)==null||Ls.call(lt,{LitElement:Oi});const gr=lt.litElementPolyfillSupport;gr==null||gr({LitElement:Oi});(lt.litElementVersions??(lt.litElementVersions=[])).push("4.2.2");class Xh{constructor(){p(this,"container",null)}mount(e,t){return this.container=e,hi(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&&hi(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 j`
|
|
34
|
+
<div
|
|
35
|
+
class="timeline-manager-header-corner"
|
|
36
|
+
data-layout-role="header-corner"
|
|
37
|
+
style=${`${s};grid-column:1;grid-row:1;border-bottom:1px solid ${t.border};`}
|
|
38
|
+
></div>
|
|
39
|
+
<div
|
|
40
|
+
class="timeline-manager-header-viewport"
|
|
41
|
+
data-layout-role="header-viewport"
|
|
42
|
+
style=${`${s};grid-column:2;grid-row:1;border-bottom:1px solid ${t.border};overflow:hidden;`}
|
|
43
|
+
>
|
|
44
|
+
<div
|
|
45
|
+
class="timeline-manager-header-canvas-host"
|
|
46
|
+
data-layout-role="header-canvas-host"
|
|
47
|
+
style="width:100%;height:100%;"
|
|
48
|
+
></div>
|
|
49
|
+
</div>
|
|
50
|
+
<div
|
|
51
|
+
class="timeline-manager-track-info-viewport"
|
|
52
|
+
data-layout-role="track-info-viewport"
|
|
53
|
+
style=${`${s};grid-column:1;grid-row:2;overflow:hidden;border-right:1px solid ${t.border};`}
|
|
54
|
+
></div>
|
|
55
|
+
<div
|
|
56
|
+
class="timeline-manager-scroll-viewport timeline-manager-body-viewport"
|
|
57
|
+
data-layout-role="body-viewport"
|
|
58
|
+
style=${`${s};grid-column:2;grid-row:2;overflow-x:hidden;overflow-y:auto;`}
|
|
59
|
+
>
|
|
60
|
+
<div
|
|
61
|
+
class="timeline-manager-body-canvas-host"
|
|
62
|
+
data-layout-role="body-canvas-host"
|
|
63
|
+
style=${`width:100%;height:100%;position:relative;background:${t.background};`}
|
|
64
|
+
></div>
|
|
65
|
+
</div>
|
|
66
|
+
<div
|
|
67
|
+
class="timeline-manager-v-scrollbar-canvas-host"
|
|
68
|
+
data-layout-role="vertical-scrollbar-host"
|
|
69
|
+
style=${["position:absolute",`top:${i}px`,"right:0","bottom:0",`width:${n}px`,"z-index:5"].join(";")}
|
|
70
|
+
></div>
|
|
71
|
+
<div
|
|
72
|
+
class="timeline-manager-h-scrollbar-canvas-host"
|
|
73
|
+
data-layout-role="horizontal-scrollbar-host"
|
|
74
|
+
style=${["position:absolute",`left:${r}px`,"right:0","bottom:0",`height:${n}px`,"z-index:4"].join(";")}
|
|
75
|
+
></div>
|
|
76
|
+
<div
|
|
77
|
+
class="timeline-manager-playhead-overlay"
|
|
78
|
+
data-layout-role="playhead-overlay"
|
|
79
|
+
style=${["position:absolute",`left:${r}px`,"top:0","right:0","bottom:0","pointer-events:none","z-index:3"].join(";")}
|
|
80
|
+
></div>
|
|
81
|
+
`}requireElement(e,t){const i=e.querySelector(t);if(!i)throw new Error(`Missing timeline manager layout element: ${t}`);return i}}const di=80,Vr=8,cs="timeline-manager-managed-layout-styles";function qh(){if(typeof document>"u"||document.getElementById(cs))return;const a=document.createElement("style");a.id=cs,a.textContent=`
|
|
82
|
+
.timeline-manager-root {
|
|
83
|
+
position: relative;
|
|
84
|
+
overflow: hidden;
|
|
85
|
+
display: grid;
|
|
86
|
+
width: 100%;
|
|
87
|
+
max-width: 100%;
|
|
88
|
+
min-width: 0;
|
|
89
|
+
height: 100%;
|
|
90
|
+
box-sizing: border-box;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
.timeline-manager-scroll-viewport {
|
|
94
|
+
overflow: auto;
|
|
95
|
+
scrollbar-width: none;
|
|
96
|
+
-ms-overflow-style: none;
|
|
97
|
+
min-width: 0;
|
|
98
|
+
max-width: 100%;
|
|
99
|
+
box-sizing: border-box;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
.timeline-manager-scroll-viewport::-webkit-scrollbar {
|
|
103
|
+
width: 0;
|
|
104
|
+
height: 0;
|
|
105
|
+
display: none;
|
|
106
|
+
}
|
|
107
|
+
`,document.head.appendChild(a)}function jh(a,e){qh();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??di,scrollbarSize:e.scrollbarSize??Vr};return new Xh().mount(a,t)}/**
|
|
34
108
|
* @license
|
|
35
109
|
* Copyright 2017 Google LLC
|
|
36
110
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
37
|
-
*/const
|
|
111
|
+
*/const Kh={CHILD:2},Zh=a=>(...e)=>({_$litDirective$:a,values:e});class Jh{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
112
|
* @license
|
|
39
113
|
* Copyright 2017 Google LLC
|
|
40
114
|
* SPDX-License-Identifier: BSD-3-Clause
|
|
41
|
-
*/class
|
|
115
|
+
*/class Ur extends Jh{constructor(e){if(super(e),this.it=le,e.type!==Kh.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===ht)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:[]}}}Ur.directiveName="unsafeHTML",Ur.resultType=1;const ji=Zh(Ur);function _e(a){return a==="text"?Ri.TEXT:a==="video"?Ri.VIDEO:Ri.AUDIO}function Ht(a,e,t){let i=t;for(const r of a){if(r.id===e)break;i+=_e(r.type)}return i}function hs(a,e){return a.reduce((t,i)=>t+_e(i.type),e)}function Qh(a,e){let t=e;return a.map(i=>{const r=_e(i.type),n={trackId:i.id,y:t,height:r};return t+=r,n})}class Ha{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&&hi(le,this.container),this.container=null,this.viewModel=null}get mountedContainer(){return this.container}afterRender(e,t){}renderCurrent(){!this.container||!this.viewModel||(hi(this.renderTemplate(this.viewModel),this.container),this.afterRender(this.container,this.viewModel))}}class ed extends Ha{renderTemplate(e){const{theme:t,tracks:i,scrollTop:r,timeScaleHeight:n,includeTimeScaleSpacer:s,onMuteTrack:o,icons:l}=e;return j`
|
|
42
116
|
<style>
|
|
43
117
|
.track-info-item:hover {
|
|
44
118
|
background: ${t.buttonHover};
|
|
@@ -48,40 +122,36 @@ js: import "konva/skia-backend";
|
|
|
48
122
|
background: ${t.buttonBackground};
|
|
49
123
|
}
|
|
50
124
|
</style>
|
|
51
|
-
${
|
|
125
|
+
${s?j`<div class="track-info-spacer" style=${`height:${n}px;`}></div>`:null}
|
|
52
126
|
<div
|
|
53
127
|
class="track-info-list"
|
|
54
128
|
style=${`will-change:transform;transform:translateY(-${Math.max(0,r)}px);`}
|
|
55
129
|
>
|
|
56
130
|
${i.map((c,h)=>this.renderTrackItem(c,h,t,o,l))}
|
|
57
131
|
</div>
|
|
58
|
-
`}renderTrackItem(e,t,i,r,n){const
|
|
132
|
+
`}renderTrackItem(e,t,i,r,n){const s=_e(e.type),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 j`
|
|
59
133
|
<div
|
|
60
134
|
class="track-info-item"
|
|
61
135
|
data-index=${String(t)}
|
|
62
136
|
data-track-id=${e.id}
|
|
63
|
-
style=${[`height:${
|
|
137
|
+
style=${[`height:${s}px`,"display:flex","align-items:center","justify-content:flex-start","gap:12px","padding:0 12px","box-sizing:border-box",`border-bottom:1px solid ${i.border}`,"transition:background-color 0.15s ease"].join(";")}
|
|
64
138
|
>
|
|
65
|
-
<div style="display:flex;align-items:center;gap:8px;">
|
|
66
139
|
<span
|
|
67
140
|
class="track-icon"
|
|
68
|
-
style="user-select:none;display:flex;align-items:center;justify-content:
|
|
141
|
+
style="user-select:none;display:flex;align-items:center;justify-content:flex-start;flex-shrink:0;"
|
|
69
142
|
>
|
|
70
|
-
${o?
|
|
143
|
+
${o?ji(this.resizeSvg(o,18)):e.type==="text"?"T":e.type==="video"?"🎬":"🎵"}
|
|
71
144
|
</span>
|
|
72
|
-
</div>
|
|
73
|
-
<div style="display:flex;align-items:center;gap:4px;">
|
|
74
145
|
<button
|
|
75
146
|
class="track-mute-btn"
|
|
76
147
|
title=${c}
|
|
77
|
-
style=${["background:transparent","border:none",`color:${i.text}`,"padding:
|
|
148
|
+
style=${["flex-shrink:0","background:transparent","border:none",`color:${i.text}`,"padding:2px","margin:0","border-radius:4px","cursor:pointer","font-size:14px","transition:background-color 0.15s ease","display:flex","align-items:center","justify-content:center"].join(";")}
|
|
78
149
|
@click=${h=>{h.stopPropagation(),r==null||r(e.id,!e.isMuted)}}
|
|
79
150
|
>
|
|
80
|
-
${l?
|
|
151
|
+
${l?ji(this.resizeSvg(l,14)):e.isMuted?"🔇":"🔊"}
|
|
81
152
|
</button>
|
|
82
|
-
</div>
|
|
83
153
|
</div>
|
|
84
|
-
`}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class
|
|
154
|
+
`}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class Na{constructor(e,t,i,r){p(this,"container");p(this,"tracks",[]);p(this,"theme");p(this,"width",di);p(this,"timeScaleHeight",40);p(this,"includeTimeScaleSpacer",!0);p(this,"scrollTop",0);p(this,"renderer",new ed);p(this,"iconCache",new Map);p(this,"onMuteTrack");var n,s,o,l,c,h;this.container=e.container,this.width=e.width??di,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",Ce("OmAi-camera")),this.iconCache.set("OmAi-display",Ce("OmAi-display")),this.iconCache.set("OmAi-hide",Ce("OmAi-hide")),this.iconCache.set("OmAi-music",Ce("OmAi-music")),this.iconCache.set("OmAi-text",Ce("OmAi-text")),this.iconCache.set("OmAi-volume",Ce("OmAi-volume")),this.iconCache.set("OmAi-volume-mute",Ce("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 td={visual:"画面",audio:"音频",text:"文本",voice:"音色"},G={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",voiceCardPreviewing:"clip-config-voice-card--previewing",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",voiceCardAvatarWrap:"clip-config-voice-avatar-wrap",voiceCardAvatarWrapFirstRow:"clip-config-voice-avatar-wrap--first-row",voiceCardAvatarTooltip:"clip-config-voice-avatar-tooltip",voiceCardAvatarMask:"clip-config-voice-avatar-mask",voiceCardAvatarSpeaker:"clip-config-voice-avatar-speaker",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 id extends Ha{renderTemplate(e){const{theme:t}=e;return j`
|
|
85
155
|
<style>
|
|
86
156
|
@keyframes clip-config-voice-loading-spin {
|
|
87
157
|
from { transform: rotate(0deg); }
|
|
@@ -321,67 +391,67 @@ js: import "konva/skia-backend";
|
|
|
321
391
|
transform: none;
|
|
322
392
|
}
|
|
323
393
|
</style>
|
|
324
|
-
<div class=${
|
|
325
|
-
${
|
|
394
|
+
<div class=${G.container} style=${this.getContainerStyle(t)}>
|
|
395
|
+
${e.emptyStateMessage?this.renderEmptyState(t,e.emptyStateMessage):this.renderPanel(e)}
|
|
326
396
|
</div>
|
|
327
397
|
${this.renderVoiceLoadingOverlay(e)}
|
|
328
398
|
`}renderVoiceLoadingOverlay(e){return e.isVoiceLoadingOverlayVisible?j`
|
|
329
399
|
<div
|
|
330
|
-
class=${
|
|
400
|
+
class=${G.voiceLoadingOverlay}
|
|
331
401
|
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(";")}
|
|
332
402
|
>
|
|
333
403
|
<div
|
|
334
|
-
class=${
|
|
404
|
+
class=${G.voiceLoadingCard}
|
|
335
405
|
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(";")}
|
|
336
406
|
>
|
|
337
407
|
<div
|
|
338
|
-
class=${
|
|
408
|
+
class=${G.voiceLoadingIcon}
|
|
339
409
|
style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;animation:clip-config-voice-loading-spin 1s linear infinite;"
|
|
340
410
|
>
|
|
341
|
-
${e.loadingIconSvg?
|
|
411
|
+
${e.loadingIconSvg?ji(this.resizeSvg(e.loadingIconSvg,24)):"⟳"}
|
|
342
412
|
</div>
|
|
343
413
|
<div
|
|
344
|
-
class=${
|
|
414
|
+
class=${G.voiceLoadingText}
|
|
345
415
|
style="font-size:14px;line-height:24px;color:#c9cbd4;"
|
|
346
416
|
>
|
|
347
417
|
配音生成中...
|
|
348
418
|
</div>
|
|
349
419
|
</div>
|
|
350
420
|
</div>
|
|
351
|
-
`:null}renderEmptyState(e){return j`
|
|
421
|
+
`:null}renderEmptyState(e,t){return j`
|
|
352
422
|
<div
|
|
353
|
-
class=${
|
|
423
|
+
class=${G.emptyState}
|
|
354
424
|
style=${`height:100%;display:flex;align-items:center;justify-content:center;padding:40px 20px;color:${e.labelColor};text-align:center;box-sizing:border-box;`}
|
|
355
425
|
>
|
|
356
|
-
<div style="font-size:13px;"
|
|
426
|
+
<div style="font-size:13px;">${t}</div>
|
|
357
427
|
</div>
|
|
358
|
-
`}renderPanel(e){const t=
|
|
428
|
+
`}renderPanel(e){const t=e.availableTabs,i=this.shouldUseVoiceInnerScroll(e);return j`
|
|
359
429
|
${t.length>1?this.renderTabBar(e,t):null}
|
|
360
430
|
<div
|
|
361
|
-
class=${
|
|
431
|
+
class=${G.content}
|
|
362
432
|
style=${i?"padding:12px;flex:1;min-height:0;display:flex;flex-direction:column;overflow:hidden;":"padding:12px;flex:1;overflow-y:auto;min-height:0;"}
|
|
363
433
|
>
|
|
364
434
|
${t.map(r=>this.renderTabPanel(e,r))}
|
|
365
435
|
</div>
|
|
366
436
|
${this.renderActionBar(e)}
|
|
367
|
-
`}shouldUseVoiceInnerScroll(e){return e.activeTab==="voice"&&this.supportsVoicePanel(e.
|
|
437
|
+
`}shouldUseVoiceInnerScroll(e){return e.activeTab==="voice"&&this.supportsVoicePanel(e.selectionState)}renderTabPanel(e,t){return t==="visual"?this.renderVisualPanel(e):t==="audio"?this.renderAudioPanel(e):t==="text"?this.renderTextPanel(e):t==="voice"?this.renderVoicePanel(e):null}renderTabBar(e,t){return j`
|
|
368
438
|
<div
|
|
369
|
-
class=${
|
|
439
|
+
class=${G.tabBar}
|
|
370
440
|
style=${`display:flex;gap:12px;padding:4px;background-color:${xe.tabBarBackground};border-radius:4px 4px 0 0;height:32px;`}
|
|
371
441
|
>
|
|
372
442
|
${t.map(i=>{const r=e.activeTab===i;return j`
|
|
373
443
|
<button
|
|
374
|
-
class=${
|
|
444
|
+
class=${G.tabButton}
|
|
375
445
|
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?xe.activeTabBackground:I.transparent}`,`color:${r?xe.activeTabText:xe.inactiveTabText}`,"border-radius:4px"].join(";")}
|
|
376
446
|
@click=${()=>e.callbacks.onTabChange(i)}
|
|
377
447
|
>
|
|
378
|
-
${
|
|
448
|
+
${td[i]}
|
|
379
449
|
</button>
|
|
380
450
|
`})}
|
|
381
451
|
</div>
|
|
382
|
-
`}renderActionBar(e){const t=e.activeTab==="voice"&&this.supportsVoicePanel(e.
|
|
452
|
+
`}renderActionBar(e){const t=e.activeTab==="voice"&&this.supportsVoicePanel(e.selectionState);return j`
|
|
383
453
|
<div
|
|
384
|
-
class=${
|
|
454
|
+
class=${G.actionBar}
|
|
385
455
|
style=${[`border-top:1px solid ${e.theme.borderColor}`,"border-radius:0 0 4px 4px","min-height:32px",`background-color:${xe.actionBarBackground}`,"padding:8px 10px"].join(";")}
|
|
386
456
|
>
|
|
387
457
|
${t?this.renderVoiceActionBar(e):null}
|
|
@@ -389,18 +459,18 @@ js: import "konva/skia-backend";
|
|
|
389
459
|
`}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 j`
|
|
390
460
|
<div style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
|
|
391
461
|
<label
|
|
392
|
-
class=${
|
|
462
|
+
class=${G.voiceCheckbox}
|
|
393
463
|
style="display:flex;align-items:center;gap:8px;cursor:pointer;"
|
|
394
464
|
>
|
|
395
465
|
<input
|
|
396
466
|
type="checkbox"
|
|
397
467
|
.checked=${e.followTextUpdates}
|
|
398
|
-
@change=${
|
|
468
|
+
@change=${s=>e.callbacks.onVoiceFollowTextUpdatesChange(s.target.checked)}
|
|
399
469
|
/>
|
|
400
470
|
<span style=${`font-size:12px;color:${e.theme.textColor};`}>${r}</span>
|
|
401
471
|
</label>
|
|
402
472
|
<button
|
|
403
|
-
class=${
|
|
473
|
+
class=${G.primaryButton}
|
|
404
474
|
style=${[`--clip-config-primary-bg:${i?e.theme.buttonBackground:xe.activeTabBackground}`,`--clip-config-primary-bg-hover:${i?e.theme.buttonBackground:"#74767C"}`,`--clip-config-primary-bg-active:${i?e.theme.buttonBackground:"#4B4D53"}`,`--clip-config-primary-bg-disabled:${e.theme.buttonBackground}`,`--clip-config-primary-border:${i?"transparent":"#6C6F77"}`,`--clip-config-primary-border-hover:${i?"transparent":"#8C9099"}`,`--clip-config-primary-border-active:${i?"transparent":"#5F626A"}`,"--clip-config-primary-border-disabled:transparent",`--clip-config-primary-color:${i?e.theme.labelColor:e.theme.buttonActiveText}`,`--clip-config-primary-color-disabled:${e.theme.labelColor}`,`--clip-config-primary-shadow:${i?"none":"0 1px 0 rgba(255, 255, 255, 0.06) inset"}`,`--clip-config-primary-shadow-hover:${i?"none":"0 4px 12px rgba(0, 0, 0, 0.18)"}`,"--clip-config-primary-shadow-active:none"].join(";")}
|
|
405
475
|
?disabled=${i}
|
|
406
476
|
@click=${()=>{e.callbacks.onGenerateVoice()}}
|
|
@@ -409,12 +479,12 @@ js: import "konva/skia-backend";
|
|
|
409
479
|
</button>
|
|
410
480
|
</div>
|
|
411
481
|
`}renderVisualPanel(e){const t=e.activeTab==="visual"?"block":"none";return j`
|
|
412
|
-
<div class=${
|
|
482
|
+
<div class=${G.visualPanel} style=${`display:${t};`}>
|
|
413
483
|
${this.renderPositionSection(e)}
|
|
414
484
|
${this.renderScaleSection(e)}
|
|
415
485
|
</div>
|
|
416
486
|
`}renderPositionSection(e){return j`
|
|
417
|
-
<div class=${
|
|
487
|
+
<div class=${G.section} style="margin-bottom:16px;">
|
|
418
488
|
${this.renderSectionTitle("位置",e.theme)}
|
|
419
489
|
${this.renderPositionControl(e,"X","x")}
|
|
420
490
|
${this.renderPositionControl(e,"Y","y")}
|
|
@@ -422,15 +492,15 @@ js: import "konva/skia-backend";
|
|
|
422
492
|
</div>
|
|
423
493
|
`}renderScaleSection(e){const t=this.getTransform(e.clip);return j`
|
|
424
494
|
<div
|
|
425
|
-
class=${
|
|
495
|
+
class=${G.section}
|
|
426
496
|
style=${`border-top:1px solid ${e.theme.borderColor};padding-top:16px;`}
|
|
427
497
|
>
|
|
428
498
|
${this.renderSectionTitle("缩放",e.theme)}
|
|
429
|
-
<div class=${
|
|
499
|
+
<div class=${G.row} style="display:flex;align-items:center;gap:8px;">
|
|
430
500
|
${this.renderRangeInput({min:"0.1",max:"8",step:"0.1",value:String(t.scale),onInput:i=>e.callbacks.onTransformChange("scale",i)})}
|
|
431
501
|
${this.renderNumberInput(e.theme,{min:"0.1",max:"8",step:"0.1",value:String(t.scale),onChange:i=>e.callbacks.onTransformChange("scale",i)})}
|
|
432
502
|
<button
|
|
433
|
-
class=${
|
|
503
|
+
class=${G.resetButton}
|
|
434
504
|
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(";")}
|
|
435
505
|
@click=${()=>e.callbacks.onTransformChange("scale",1)}
|
|
436
506
|
>
|
|
@@ -439,10 +509,10 @@ js: import "konva/skia-backend";
|
|
|
439
509
|
</div>
|
|
440
510
|
</div>
|
|
441
511
|
`}renderAudioPanel(e){var r;const t=e.activeTab==="audio"?"block":"none",i=((r=e.clip)==null?void 0:r.volume)??1;return j`
|
|
442
|
-
<div class=${
|
|
443
|
-
<div class=${
|
|
512
|
+
<div class=${G.audioPanel} style=${`display:${t};`}>
|
|
513
|
+
<div class=${G.section}>
|
|
444
514
|
${this.renderSectionTitle("音量",e.theme)}
|
|
445
|
-
<div class=${
|
|
515
|
+
<div class=${G.row} style="display:flex;align-items:center;gap:8px;">
|
|
446
516
|
${this.renderRangeInput({min:"0",max:"1",step:"0.01",value:String(i),onInput:n=>e.callbacks.onVolumeChange(n)})}
|
|
447
517
|
${this.renderNumberInput(e.theme,{min:"0",max:"100",step:"1",value:String(Math.round(i*100)),onChange:n=>e.callbacks.onVolumeChange(n/100)})}
|
|
448
518
|
<span style=${`font-size:12px;color:${e.theme.labelColor};`}>%</span>
|
|
@@ -450,61 +520,63 @@ js: import "konva/skia-backend";
|
|
|
450
520
|
</div>
|
|
451
521
|
</div>
|
|
452
522
|
`}renderTextPanel(e){const t=e.clip,i=this.getTransform(t),r=Me(t==null?void 0:t.textStyle),n=e.activeTab==="text"?"block":"none";return j`
|
|
453
|
-
<div class=${
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
523
|
+
<div class=${G.textPanel} style=${`display:${n};`}>
|
|
524
|
+
${e.isTextContentEditable?j`
|
|
525
|
+
<div class=${G.section} style="margin-bottom:16px;">
|
|
526
|
+
${this.renderSectionTitle("文本",e.theme)}
|
|
527
|
+
<textarea
|
|
528
|
+
class=${G.textarea}
|
|
529
|
+
rows="5"
|
|
530
|
+
.value=${e.textDraftContent}
|
|
531
|
+
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(";")}
|
|
532
|
+
@input=${s=>e.callbacks.onTextContentInput(s.target.value)}
|
|
533
|
+
@blur=${()=>e.callbacks.onTextContentCommit()}
|
|
534
|
+
></textarea>
|
|
535
|
+
</div>
|
|
536
|
+
`:null}
|
|
537
|
+
<div class=${G.section} style="margin-bottom:16px;">
|
|
466
538
|
${this.renderSectionTitle("字号",e.theme)}
|
|
467
|
-
<div class=${
|
|
468
|
-
${this.renderRangeInput({min:"5",max:"300",step:"1",value:String(r.fontSize),onInput:
|
|
469
|
-
${this.renderNumberInput(e.theme,{min:"5",max:"300",step:"1",value:String(r.fontSize),onChange:
|
|
539
|
+
<div class=${G.row} style="display:flex;align-items:center;gap:8px;">
|
|
540
|
+
${this.renderRangeInput({min:"5",max:"300",step:"1",value:String(r.fontSize),onInput:s=>e.callbacks.onTextStyleChange("fontSize",s)})}
|
|
541
|
+
${this.renderNumberInput(e.theme,{min:"5",max:"300",step:"1",value:String(r.fontSize),onChange:s=>e.callbacks.onTextStyleChange("fontSize",s)})}
|
|
470
542
|
</div>
|
|
471
543
|
</div>
|
|
472
|
-
<div class=${
|
|
544
|
+
<div class=${G.section} style="margin-bottom:16px;">
|
|
473
545
|
${this.renderSectionTitle("颜色",e.theme)}
|
|
474
546
|
<input
|
|
475
547
|
type="color"
|
|
476
|
-
class=${
|
|
548
|
+
class=${G.colorInput}
|
|
477
549
|
.value=${r.color}
|
|
478
550
|
style=${["width:108px","height:48px","padding:4px",`border:1px solid ${e.theme.inputBorder}`,"border-radius:8px",`background-color:${e.theme.inputBackground}`].join(";")}
|
|
479
|
-
@input=${
|
|
551
|
+
@input=${s=>e.callbacks.onTextStyleChange("color",s.target.value)}
|
|
480
552
|
/>
|
|
481
553
|
</div>
|
|
482
|
-
<div class=${
|
|
554
|
+
<div class=${G.section} style="margin-bottom:16px;">
|
|
483
555
|
${this.renderSectionTitle("位置",e.theme)}
|
|
484
|
-
<div class=${
|
|
485
|
-
${this.renderLabeledNumberInput(e,"X",i.x,
|
|
486
|
-
${this.renderLabeledNumberInput(e,"Y",i.y,
|
|
556
|
+
<div class=${G.row} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:12px;">
|
|
557
|
+
${this.renderLabeledNumberInput(e,"X",i.x,s=>e.callbacks.onTextStyleChange("x",s),"0.01","0","1")}
|
|
558
|
+
${this.renderLabeledNumberInput(e,"Y",i.y,s=>e.callbacks.onTextStyleChange("y",s),"0.01","0","1")}
|
|
487
559
|
</div>
|
|
488
560
|
</div>
|
|
489
|
-
<div class=${
|
|
561
|
+
<div class=${G.section}>
|
|
490
562
|
${this.renderSectionTitle("旋转",e.theme)}
|
|
491
|
-
<div class=${
|
|
492
|
-
${this.renderLabeledNumberInput(e,"角度",r.rotation,
|
|
563
|
+
<div class=${G.row} style="max-width:220px;">
|
|
564
|
+
${this.renderLabeledNumberInput(e,"角度",r.rotation,s=>e.callbacks.onTextStyleChange("rotation",s),"1")}
|
|
493
565
|
</div>
|
|
494
566
|
</div>
|
|
495
567
|
</div>
|
|
496
568
|
`}renderVoicePanel(e){const t=e.activeTab==="voice"?"block":"none",i=[{key:"女",label:"女声"},{key:"男",label:"男声"},{key:"普通话",label:"普通话"},{key:"粤语",label:"粤语"}],r=e.voiceCatalog.filter(l=>!e.activeVoiceFilterTag||l.tags.includes(e.activeVoiceFilterTag)),n=this.shouldUseVoiceInnerScroll(e),o=[`display:${t==="block"?n?"flex":"block":"none"}`,n?"flex-direction:column":"",n?"flex:1":"",n?"min-height:0":"",n?"overflow:hidden":""].filter(Boolean).join(";");return j`
|
|
497
|
-
<div class=${
|
|
498
|
-
<div class=${
|
|
499
|
-
<div class=${
|
|
569
|
+
<div class=${G.voicePanel} style=${o}>
|
|
570
|
+
<div class=${G.section} style=${n?"flex-shrink:0;margin-bottom:12px;":"margin-bottom:16px;"}>
|
|
571
|
+
<div class=${G.filterGroup} style="display:flex;gap:8px;flex-wrap:wrap;">
|
|
500
572
|
${i.map(l=>this.renderFilterButton(e,l.key,l.label,e.activeVoiceFilterTag===l.key,()=>e.callbacks.onVoiceFilterChange(l.key)))}
|
|
501
573
|
</div>
|
|
502
574
|
</div>
|
|
503
575
|
<div
|
|
504
|
-
class=${
|
|
576
|
+
class=${G.section}
|
|
505
577
|
style=${n?"flex:1;min-height:0;overflow-y:auto;":""}
|
|
506
578
|
>
|
|
507
|
-
<div class=${
|
|
579
|
+
<div class=${G.voiceCardGrid} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px;">
|
|
508
580
|
${r.map((l,c)=>this.renderVoiceCard(e,l,c))}
|
|
509
581
|
</div>
|
|
510
582
|
${r.length===0?j`
|
|
@@ -514,7 +586,7 @@ js: import "konva/skia-backend";
|
|
|
514
586
|
`:null}
|
|
515
587
|
${e.voiceErrorMessage?j`
|
|
516
588
|
<div
|
|
517
|
-
class=${
|
|
589
|
+
class=${G.errorText}
|
|
518
590
|
style=${`padding-top:12px;font-size:12px;color:${I.accentDanger};`}
|
|
519
591
|
>
|
|
520
592
|
${e.voiceErrorMessage}
|
|
@@ -524,31 +596,31 @@ js: import "konva/skia-backend";
|
|
|
524
596
|
</div>
|
|
525
597
|
`}renderFilterButton(e,t,i,r,n){return j`
|
|
526
598
|
<button
|
|
527
|
-
class=${
|
|
599
|
+
class=${G.filterButton}
|
|
528
600
|
style=${["padding:6px 12px","border:none","border-radius:999px","cursor:pointer","font-size:12px",`background:${r?xe.activeTabBackground:e.theme.buttonBackground}`,`color:${r?e.theme.buttonActiveText:e.theme.textColor}`].join(";")}
|
|
529
601
|
data-key=${t}
|
|
530
602
|
@click=${n}
|
|
531
603
|
>
|
|
532
604
|
${i}
|
|
533
605
|
</button>
|
|
534
|
-
`}renderVoiceCard(e,t,i){const r=e.selectedVoiceId===t.id,n=e.previewingVoiceId===t.id,
|
|
606
|
+
`}renderVoiceCard(e,t,i){const r=e.selectedVoiceId===t.id,n=e.previewingVoiceId===t.id,s=t.avatar,o=i<2;return j`
|
|
535
607
|
<button
|
|
536
|
-
class=${[
|
|
608
|
+
class=${[G.voiceCard,n?G.voiceCardPreviewing:""].filter(Boolean).join(" ")}
|
|
537
609
|
style=${["position:relative","display:flex","align-items:center","gap:12px","width:100%","padding:8px","border-radius:12px","text-align:left","cursor:pointer",`border:${r?`1px solid ${e.theme.buttonActiveBorder}`:""}`,`background:${r?xe.activeTabBackground:e.theme.buttonBackground}`,`color:${e.theme.textColor}`].join(";")}
|
|
538
610
|
@click=${()=>e.callbacks.onVoiceSelect(t.id)}
|
|
539
611
|
>
|
|
540
|
-
${
|
|
612
|
+
${s?j`
|
|
541
613
|
<span
|
|
542
|
-
class=${[
|
|
614
|
+
class=${[G.voiceCardAvatarWrap,o?G.voiceCardAvatarWrapFirstRow:""].filter(Boolean).join(" ")}
|
|
543
615
|
>
|
|
544
616
|
<div
|
|
545
|
-
class=${
|
|
546
|
-
style=${["width:32px","height:32px","border-radius:8px","flex-shrink:0","display:flex","align-items:center","justify-content:center",`background:url(${
|
|
617
|
+
class=${G.voiceCardAvatar}
|
|
618
|
+
style=${["width:32px","height:32px","border-radius:8px","flex-shrink:0","display:flex","align-items:center","justify-content:center",`background:url(${s}) center / cover no-repeat`,`color:${I.white}`,"font-size:18px","font-weight:600"].join(";")}
|
|
547
619
|
>
|
|
548
620
|
</div>
|
|
549
|
-
<span class=${
|
|
621
|
+
<span class=${G.voiceCardAvatarMask} aria-hidden="true"></span>
|
|
550
622
|
<span
|
|
551
|
-
class=${
|
|
623
|
+
class=${G.voiceCardAvatarSpeaker}
|
|
552
624
|
aria-hidden="true"
|
|
553
625
|
>
|
|
554
626
|
<svg
|
|
@@ -562,25 +634,25 @@ js: import "konva/skia-backend";
|
|
|
562
634
|
/>
|
|
563
635
|
</svg>
|
|
564
636
|
</span>
|
|
565
|
-
<span class=${
|
|
637
|
+
<span class=${G.voiceCardAvatarTooltip}>试听</span>
|
|
566
638
|
</span>
|
|
567
639
|
`:j`
|
|
568
640
|
<div
|
|
569
|
-
class=${
|
|
641
|
+
class=${G.voiceCardAvatar}
|
|
570
642
|
style=${["width:32px","height:32px","border-radius:8px","flex-shrink:0","display:flex","align-items:center","justify-content:center","background:linear-gradient(135deg, #6c7080 0%, #424656 100%)",`color:${I.white}`,"font-size:18px","font-weight:600"].join(";")}
|
|
571
643
|
>
|
|
572
644
|
${t.name.slice(0,1)}
|
|
573
645
|
</div>
|
|
574
646
|
`}
|
|
575
|
-
<div class=${
|
|
647
|
+
<div class=${G.voiceCardMeta} style="flex:1;min-width:0;">
|
|
576
648
|
<div
|
|
577
|
-
class=${
|
|
649
|
+
class=${G.voiceCardTitle}
|
|
578
650
|
style=${["display:flex","align-items:center","gap:6px","padding-right:24px","font-size:14px",`color:${I.white}`,"white-space:nowrap","overflow:hidden","text-overflow:ellipsis"].join(";")}
|
|
579
651
|
>
|
|
580
652
|
<span style="overflow:hidden;text-overflow:ellipsis;">${n?"试听中...":t.name}</span>
|
|
581
653
|
</div>
|
|
582
654
|
<div
|
|
583
|
-
class=${
|
|
655
|
+
class=${G.voiceCardSubtitle}
|
|
584
656
|
style=${`padding-top: 2px;font-size:10px;color:${e.theme.labelColor};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`}
|
|
585
657
|
>
|
|
586
658
|
${t.lang} · ${t.emotion}
|
|
@@ -588,35 +660,35 @@ js: import "konva/skia-backend";
|
|
|
588
660
|
</div>
|
|
589
661
|
${r?j`
|
|
590
662
|
<div
|
|
591
|
-
class=${
|
|
663
|
+
class=${G.voiceCardCheck}
|
|
592
664
|
style="position:absolute;top:50%;right:8px;transform:translateY(-42%);"
|
|
593
665
|
>
|
|
594
|
-
${e.selectedIconSvg?
|
|
666
|
+
${e.selectedIconSvg?ji(this.resizeSvg(e.selectedIconSvg,20)):"✓"}
|
|
595
667
|
</div>
|
|
596
668
|
`:null}
|
|
597
669
|
</button>
|
|
598
|
-
`}renderPositionControl(e,t,i){const r=this.getTransform(e.clip),n=r.scale/2,
|
|
670
|
+
`}renderPositionControl(e,t,i){const r=this.getTransform(e.clip),n=r.scale/2,s=-n,o=1+n;return j`
|
|
599
671
|
<div
|
|
600
|
-
class=${
|
|
672
|
+
class=${G.row}
|
|
601
673
|
style="display:flex;align-items:center;gap:8px;margin-bottom:8px;"
|
|
602
674
|
>
|
|
603
675
|
<label
|
|
604
|
-
class=${
|
|
676
|
+
class=${G.label}
|
|
605
677
|
style=${`width:16px;font-size:13px;color:${e.theme.labelColor};`}
|
|
606
678
|
>
|
|
607
679
|
${t}
|
|
608
680
|
</label>
|
|
609
|
-
${this.renderRangeInput({min:String(
|
|
610
|
-
${this.renderNumberInput(e.theme,{min:String(
|
|
681
|
+
${this.renderRangeInput({min:String(s),max:String(o),step:"0.01",value:String(r[i]),onInput:l=>e.callbacks.onTransformChange(i,l)})}
|
|
682
|
+
${this.renderNumberInput(e.theme,{min:String(s),max:String(o),step:"0.01",value:String(r[i]),onChange:l=>e.callbacks.onTransformChange(i,l)})}
|
|
611
683
|
</div>
|
|
612
684
|
`}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 j`
|
|
613
685
|
<div
|
|
614
|
-
class=${
|
|
686
|
+
class=${G.presetGrid}
|
|
615
687
|
style="display:grid;grid-template-columns:repeat(3, 1fr);gap:4px;"
|
|
616
688
|
>
|
|
617
689
|
${t.map(i=>j`
|
|
618
690
|
<button
|
|
619
|
-
class=${
|
|
691
|
+
class=${G.presetButton}
|
|
620
692
|
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(";")}
|
|
621
693
|
@click=${()=>{const{x:r,y:n}=this.calculatePresetPosition(e.clip,i.x,i.y);e.callbacks.onPresetSelect(r,n)}}
|
|
622
694
|
>
|
|
@@ -626,7 +698,7 @@ js: import "konva/skia-backend";
|
|
|
626
698
|
</div>
|
|
627
699
|
`}renderSectionTitle(e,t){return j`
|
|
628
700
|
<div
|
|
629
|
-
class=${
|
|
701
|
+
class=${G.sectionTitle}
|
|
630
702
|
style=${`font-size:12px;color:${t.labelColor};margin-bottom:8px;text-transform:uppercase;`}
|
|
631
703
|
>
|
|
632
704
|
${e}
|
|
@@ -634,7 +706,7 @@ js: import "konva/skia-backend";
|
|
|
634
706
|
`}renderRangeInput(e){return j`
|
|
635
707
|
<input
|
|
636
708
|
type="range"
|
|
637
|
-
class=${
|
|
709
|
+
class=${G.slider}
|
|
638
710
|
min=${e.min}
|
|
639
711
|
max=${e.max}
|
|
640
712
|
step=${e.step}
|
|
@@ -645,7 +717,7 @@ js: import "konva/skia-backend";
|
|
|
645
717
|
`}renderNumberInput(e,t){return j`
|
|
646
718
|
<input
|
|
647
719
|
type="number"
|
|
648
|
-
class=${
|
|
720
|
+
class=${G.input}
|
|
649
721
|
min=${t.min}
|
|
650
722
|
max=${t.max}
|
|
651
723
|
step=${t.step}
|
|
@@ -653,83 +725,9 @@ js: import "konva/skia-backend";
|
|
|
653
725
|
style=${["width:60px","padding:4px 6px",`border:1px solid ${e.inputBorder}`,"border-radius:4px","font-size:12px",`background-color:${e.inputBackground}`,`color:${e.textColor}`].join(";")}
|
|
654
726
|
@change=${i=>t.onChange(Number.parseFloat(i.target.value))}
|
|
655
727
|
/>
|
|
656
|
-
`}renderLabeledNumberInput(e,t,i,r,n="0.01",
|
|
728
|
+
`}renderLabeledNumberInput(e,t,i,r,n="0.01",s="-9999",o="9999"){return j`
|
|
657
729
|
<label style="display:flex;align-items:center;gap:8px;">
|
|
658
730
|
<span style=${`min-width:18px;font-size:13px;color:${e.theme.labelColor};`}>${t}</span>
|
|
659
|
-
${this.renderNumberInput(e.theme,{min:
|
|
731
|
+
${this.renderNumberInput(e.theme,{min:s,max:o,step:n,value:String(i),onChange:r})}
|
|
660
732
|
</label>
|
|
661
|
-
`}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:${I.sliderFillStart}`,`--clip-slider-fill-end:${I.sliderFillEnd}`,`--clip-slider-road:${I.sliderRoad}`,`--clip-slider-thumb-border:${I.sliderThumbBorder}`,`--clip-slider-thumb-shadow:${xe.sliderThumbShadow}`].join(";")}getSliderStyle(e,t,i){const r=Number(e||0),n=Number(t||100),a=Number(i||0),o=n-r,l=o<=0?0:(a-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?["voice","audio"]:["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,a={left:n,center:.5,right:1-n},o={top:n,center:.5,bottom:1-n};return{x:a[t],y:o[i]}}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}const Qh={...fe};class Ha{constructor(e){p(this,"container");p(this,"theme");p(this,"renderer",new Jh);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","男");p(this,"textDraftContent","");p(this,"followTextUpdates",!0);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??Qh,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",ve("OmAi-camera")),this.iconCache.set("OmAi-accept",ve("OmAi-accept")),this.iconCache.set("OmAi-loading",ve("OmAi-loading")),this.iconCache.set("OmAi-text",ve("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,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?["voice","audio"]:["audio"]:["visual","audio"]:[]}resetVoiceState(){this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=!1,this.stopVoicePreview(!1)}syncVoiceStateForClip(e){if(!e||!this.supportsVoicePanel(e)){this.resetVoiceState();return}this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=e.type==="audio"?e.ttsFollowTextUpdates??!1:!0,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)}ensureVoiceFilters(){if(this.voiceCatalog.length===0){this.selectedVoiceId=null,this.stopVoicePreview(!1);return}this.selectedVoiceId&&!this.voiceCatalog.some(e=>e.id===this.selectedVoiceId)&&(this.selectedVoiceId=null,this.stopVoicePreview(!1))}handleVoiceFilterChange(e){const t=e==="男"||e==="女"||e==="普通话"||e==="粤语"?e:null;this.activeVoiceFilterTag=this.activeVoiceFilterTag===t?null:t,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={...Me(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 ed(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class cs{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:a,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:a,sourceTrackId:o,targetTrack:l,targetTrackId:t}}planTrackPlacement(e,t){var n;const i=e.startTime+e.duration;for(const a of t){if(((n=a.getTrackType)==null?void 0:n.call(a))!==e.type)continue;if(!a.getClips().some(l=>e.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(a);if(l)return{status:"use_existing_track",trackId:l}}}const r=t.filter(a=>{var o;return((o=a.getTrackType)==null?void 0:o.call(a))===e.type}).length+1;return{status:"create_track",trackType:e.type,suggestedTrackName:`${ed(e.type)}轨道 ${r}`,insertionPlacement:e.type==="text"||e.type==="video"?"top_of_type_region":"bottom_of_type_region"}}planCrossTrackMove(e,t,i,r,n,a){var g;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=a.find(y=>this.resolveTrackId(y)===l);if(!c)return{status:"missing_target_track_view",targetTrackId:l};const h=this.resolveTrackType(c)??((g=n.find(y=>y.id===l))==null?void 0:g.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),f=u.indexOf(l);for(let y=1;y<=u.length;y+=1){const S=f-y;if(S>=0){const v=u[S],T=a.find(w=>this.resolveTrackId(w)===v);if(T&&!this.hasOverlapOnTrack(e,T))return{status:"move_to_track",targetTrackId:v}}const C=f+y;if(C<u.length){const v=u[C],T=a.find(w=>this.resolveTrackId(w)===v);if(T&&!this.hasOverlapOnTrack(e,T))return{status:"move_to_track",targetTrackId:v}}}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,a){const o=this.planCrossTrackMove(e,t,i,r,n,a);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(e){const t=Math.max(0,e);return this.updateCurrentTime(t)}setZoom(e){const t=Math.max(Re.MIN,Math.min(Re.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,a=null,o=null;for(const l of i){const c=_e(l.type),h=n+c;if(l.type===r&&(a===null&&(a=n),o=h),e>=n&&e<h)return{status:"existing_track",targetTrackId:l.id};n=h}return r==="text"&&a!==null&&e<a?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="video"&&a!==null&&e<a?{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 a=r;const o=n.map(d=>{const u=a,f=_e(d.type),g=u+f;return a=g,{id:d.id,type:d.type,role:d.role,startY:u,endY:g,height:f}}).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 zr{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,a,o){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:r,clipAfter:n,sourceTrackSnapshot:a,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 hs{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 a=!1;const o=this.resolveTrackIdForHistorySnapshot(n.sourceTrackSnapshot,n.sourceTrackId,t,n.sourceTrackRestoreAnchor);if(o&&(a=this.target.addClipToTrack(o,n.clip)),!a){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":{const n=this.target.findTrackByClipId(e.data.clip1.id)||this.target.getDefaultTrack();this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id),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 a=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();a==null||a.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:F.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,a=this.target.findTrackByClipId(n.id)||this.target.getDefaultTrack();a==null||a.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:F.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 a=this.target.ensureTrackFromHistorySnapshot(e,this.resolveRestoreAnchor(r,i))??t;return n&&a&&i.set(n,a),a}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 td=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],id=new Set(["thumbnails"]);function rd(s,e){return Object.is(s,e)?!0:s===void 0||e===void 0?!1:typeof s=="object"&&typeof e=="object"?JSON.stringify(s)===JSON.stringify(e):!1}class ds{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,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,a,o){const l=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,a,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 a={},o={};return td.forEach(c=>{rd(e[c],t[c])||(a[c]=e[c],o[c]=t[c])}),Object.keys(a).length===0||Object.keys(a).every(c=>id.has(c))?null:this.history.createUpdateClipAction(e.id,a,o)}}function Pi(s){var e;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function nd(s){var e,t,i;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),(t=s.reloadClipThumbnailsIfNeeded)==null||t.call(s),(i=s.checkTrackDurationChange)==null||i.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function sd(s,e,t=!1){if(!e||!t||s.type==="audio")return!1;const i=e.duration!==s.duration,r=e.startTimeAtSource!==s.startTimeAtSource||e.endTimeAtSource!==s.endTimeAtSource;return i||r}function Vr(s){return s.length===0?0:Math.max(...s.map(e=>e.endTime))}function ad(s,e){return e<Vr(s)}function od(s){return s.currentCanPlay===s.nextCanPlay?s.currentCanPlay:(s.setCanPlay(s.nextCanPlay),s.currentCanPlay&&!s.nextCanPlay&&s.playState==="playing"&&(s.pauseTimeline(),s.setCurrentTime(s.clipEndTime||1)),s.emitCanPlayChange(s.nextCanPlay),s.nextCanPlay)}function ld(s){const e=!s.id&&s.startTime>0;return{shouldJumpToTime:e,jumpTime:e?s.startTime:null,shouldSelectClip:!!s.id}}function Oi(s){var e;return s.applied?(s.isExecutingHistoryAction||(e=s.recordHistory)==null||e.call(s),s.applyEffects(),!0):!1}function cd(s){return Oi({applied:s.applied,isExecutingHistoryAction:s.isExecutingHistoryAction,recordHistory:()=>{var e;(e=s.recordMoveClipBetweenTracks)==null||e.call(s,s.clipId,s.sourceTrackId,s.targetTrackId,s.clipBefore,s.clipAfter,s.sourceTrackSnapshot,s.targetTrackSnapshot)},applyEffects:s.applyEffects})}function hd(s){var e;s.isExecutingHistoryAction||(e=s.recordSplitClip)==null||e.call(s,s.clip1,s.clip2),s.emitClipUpdated(s.clip1),s.emitClipAdded(s.clip2),s.applyEffects()}const dd={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function ud(s){var e,t;try{const i=typeof location<"u"?location.href:"http://localhost/";return((e=new URL(s,i).pathname.split(".").pop())==null?void 0:e.toLowerCase())??""}catch{return((t=(s.split(/[?#]/,1)[0]??"").split(".").pop())==null?void 0:t.toLowerCase())??""}}function pd(s){const e=ud(s.src);if(e==="mp4")return{url:s.src,mimeType:"video/mp4",kind:"mp4"};if(e==="m3u8")return{url:s.src,mimeType:"application/vnd.apple.mpegurl",kind:"hls-fmp4"};const t=dd[e];return t?{url:s.src,mimeType:t,kind:"audio"}:null}class fd{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.top="12px",this.container.style.left="12px",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="flex-start",this.container.style.flexDirection="row",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.lineHeight="1",this.container.style.padding="8px 10px",this.container.style.borderRadius="6px",this.container.style.zIndex="2000",this.container.style.pointerEvents="auto";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,isBuffering:r}=e,n=i.isBuffering||r;if(!t&&!n){this.container.style.display="none",this.actionElement.style.display="none",this.detailElement.style.display="none";return}if(this.container.style.display="inline-flex",this.detailElement.style.display="none",this.detailElement.textContent="",t!=null&&t.errorMessage||i.phase==="failed"){this.statusElement.textContent="资源加载异常",this.actionElement.style.display="inline-flex";return}if(!t){this.statusElement.textContent="视频缓冲中...",this.actionElement.style.display="none";return}const a=t.loadingPending>0||i.loadingCount>0;this.statusElement.textContent=a?"资源加载中...":"正在缓冲预览...",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 fr={x:.5,y:.5,scale:1},gd=.1,md=8;function gr(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function yd(s){return Math.min(md,Math.max(gd,s))}function ke(s){return{x:gr(s==null?void 0:s.x,fr.x),y:gr(s==null?void 0:s.y,fr.y),scale:yd(gr(s==null?void 0:s.scale,fr.scale))}}function on(s,e,t=1e-4){const i=ke(s),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 Na(s,e){if(s.width<=0||s.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const t=e.width>0?e.width:s.width,i=e.height>0?e.height:s.height,r=t/i,n=s.width/s.height;let a=s.width,o=s.height;r>n?o=a/r:a=o*r;const l=(s.width-a)/2,c=(s.height-o)/2;return{left:l,top:c,width:a,height:o,centerX:l+a/2,centerY:c+o/2}}function us(s,e,t){const i=Na(s,e),r=ke(t),n=i.width*r.scale,a=i.height*r.scale,o=s.width*r.x,l=s.height*r.y;return{left:o-n/2,top:l-a/2,width:n,height:a,centerX:o,centerY:l}}function $a(s,e,t,i){const r=ke(s),n=i.width>0?i.width:1,a=i.height>0?i.height:1;return ke({x:r.x+e/n,y:r.y+t/a,scale:r.scale})}function Sd(s,e,t,i,r,n){const a=ke(n),o=Math.max(r.width/2,1),l=Math.max(r.height/2,1),c=Math.abs(t-s)/o,h=Math.abs(i-e)/l;return ke({x:a.x,y:a.y,scale:Math.max(c,h)})}function ps(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}class vd{constructor(e={}){p(this,"frameElement",null);p(this,"overlayElement",null);p(this,"boxElement",null);p(this,"rotateHandleElement",null);p(this,"rotateHandlePointerDownHandler",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",clipType:this.state.clipType??"video",startFontSize:void 0,nextFontSize:void 0,centerX:void 0,centerY:void 0,startCenterDistance:void 0,startRotation:void 0,nextRotation:void 0,startAngle:void 0},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 ${st.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"),this.createRotateHandle(),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(),this.rotateHandleElement&&this.rotateHandlePointerDownHandler&&this.rotateHandleElement.removeEventListener("pointerdown",this.rotateHandlePointerDownHandler),this.rotateHandleElement=null,this.rotateHandlePointerDownHandler=null,(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()}createRotateHandle(){if(!this.overlayElement)return;const e=document.createElement("div");e.className="timeline-preview-transform-rotate-handle",e.style.position="absolute",e.style.display="none",e.style.width="20px",e.style.height="20px",e.style.borderRadius="999px",e.style.border=`1px solid ${st.border}`,e.style.background=st.handleBackground,e.style.pointerEvents="auto",e.style.cursor="grab",e.style.boxSizing="border-box",e.style.transform="translate(-50%, -50%)",e.style.display="none",e.style.alignItems="center",e.style.justifyContent="center",e.style.fontSize="12px",e.style.color=st.border,e.style.userSelect="none",e.textContent="↺";const t=this.getRotateHandlePointerDown();e.addEventListener("pointerdown",t),this.rotateHandleElement=e,this.rotateHandlePointerDownHandler=t,this.overlayElement.appendChild(e)}getRotateHandlePointerDown(){return e=>{var o,l;const t=e;if((t.button??0)!==0||!this.state)return;(o=t.preventDefault)==null||o.call(t),(l=t.stopPropagation)==null||l.call(t);const i=this.state.displayRect.left+this.state.displayRect.width/2,r=this.state.displayRect.top+this.state.displayRect.height/2,n=this.toLocalPoint(t),a=Math.atan2(n.y-r,n.x-i)*(180/Math.PI);this.interaction={clipId:this.state.clipId,mode:"rotate",pointerStart:n,startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing",clipType:"text",startFontSize:void 0,nextFontSize:void 0,centerX:i,centerY:r,startCenterDistance:void 0,startRotation:this.state.currentRotation??0,nextRotation:this.state.currentRotation??0,startAngle:a},this.setGlobalCursor("grabbing"),this.bindDocumentListeners()}}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 ${st.border}`,i.style.background=st.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 c,h;const i=t;if((i.button??0)!==0||!this.state)return;(c=i.preventDefault)==null||c.call(i),(h=i.stopPropagation)==null||h.call(i);const r=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize",n=this.state.clipType==="text",a=n?this.state.displayRect.left+this.state.displayRect.width/2:void 0,o=n?this.state.displayRect.top+this.state.displayRect.height/2:void 0,l=n?Math.sqrt(Math.pow(this.state.displayRect.width/2,2)+Math.pow(this.state.displayRect.height/2,2)):void 0;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,clipType:this.state.clipType??"video",startFontSize:n?this.state.currentFontSize:void 0,nextFontSize:n?this.state.currentFontSize:void 0,centerX:a,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor(r),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,r,n,a;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),(a=(n=globalThis.window)==null?void 0:n.addEventListener)==null||a.call(n,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,r,n,a;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),(a=(n=globalThis.window)==null?void 0:n.removeEventListener)==null||a.call(n,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var n,a,o,l,c,h,d;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);if(this.interaction.mode==="rotate"&&this.interaction.startRotation!==void 0){const u=i.x-this.interaction.centerX,f=i.y-this.interaction.centerY,y=Math.atan2(f,u)*(180/Math.PI)-this.interaction.startAngle,S=Math.round(this.interaction.startRotation+y);this.interaction.nextRotation=S,this.interaction.changed=S!==this.interaction.startRotation,(o=(a=this.callbacks).onRotationChange)==null||o.call(a,this.interaction.clipId,S);return}if(this.interaction.clipType==="text"&&this.interaction.startFontSize!==void 0){const u=i.x-this.interaction.centerX,f=i.y-this.interaction.centerY,g=Math.sqrt(u*u+f*f),y=(this.interaction.startCenterDistance??0)>0?g/this.interaction.startCenterDistance:1,S=Math.max(5,Math.min(300,Math.round(this.interaction.startFontSize*y)));this.interaction.nextFontSize=S,this.interaction.changed=S!==this.interaction.startFontSize,(c=(l=this.callbacks).onFontSizeChange)==null||c.call(l,this.interaction.clipId,S);return}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 u=this.interaction.startTransform.x*this.interaction.frameSize.width,f=this.interaction.startTransform.y*this.interaction.frameSize.height;r=Sd(u,f,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!on(this.interaction.startTransform,r),(d=(h=this.callbacks).onPreviewTransformChange)==null||d.call(h,this.interaction.clipId,r)}finishInteraction(e){var i,r,n,a,o,l,c,h,d,u,f,g;const t=this.interaction;if(!t){this.setGlobalCursor(null),this.unbindDocumentListeners();return}t.mode==="rotate"?(e&&t.changed&&t.nextRotation!==void 0&&((r=(i=this.callbacks).onRotationCommit)==null||r.call(i,t.clipId,t.nextRotation)),(a=(n=this.callbacks).onRotationChange)==null||a.call(n,t.clipId,null)):t.clipType==="text"?(e&&t.changed&&t.nextFontSize!==void 0&&((l=(o=this.callbacks).onFontSizeCommit)==null||l.call(o,t.clipId,t.nextFontSize)),(h=(c=this.callbacks).onFontSizeChange)==null||h.call(c,t.clipId,null)):(e&&t.changed&&((u=(d=this.callbacks).onPreviewTransformCommit)==null||u.call(d,t.clipId,t.nextTransform)),(g=(f=this.callbacks).onPreviewTransformChange)==null||g.call(f,t.clipId,null)),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners(),this.render()}render(){var r;if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none"),this.rotateHandleElement&&(this.rotateHandleElement.style.display="none");return}const e=this.state.clipType==="text";this.boxElement.style.pointerEvents=e?"none":"auto",this.boxElement.style.cursor=e?"default":"grab";const{displayRect:t}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${t.left}px`,this.boxElement.style.top=`${t.top}px`,this.boxElement.style.width=`${t.width}px`,this.boxElement.style.height=`${t.height}px`;const i=e?this.state.currentRotation??0:0;if(this.boxElement.style.transformOrigin="center",this.boxElement.style.transform=i!==0?`rotate(${i}deg)`:"",this.positionHandle("top-left",0,0),this.positionHandle("top-right",t.width,0),this.positionHandle("bottom-right",t.width,t.height),this.positionHandle("bottom-left",0,t.height),this.rotateHandleElement)if(e){if(!(((r=this.interaction)==null?void 0:r.mode)==="rotate")){const a=t.left+t.width/2,o=t.top+t.height/2,l=t.height/2+20,c=i*(Math.PI/180),h=a-l*Math.sin(c),d=o+l*Math.cos(c);this.rotateHandleElement.style.left=`${h}px`,this.rotateHandleElement.style.top=`${d}px`}this.rotateHandleElement.style.display="flex"}else this.rotateHandleElement.style.display="none"}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:ps(this.frameElement.style.left),top:ps(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 Cd=0,bd=2,Td=250,wd=2,kd=120,fs="Arial, sans-serif";function xd(s,e){const t=Math.max(0,Math.round(s));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 za(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function mr(s){return`"${za(s)}"`}function Pd(s){return jr(s,Xr)}function _d(s,e){return!wt(s.mode)||!e?s:{mode:De.mode,width:e.width,height:e.height}}function Be(s){return s.getAttribute("src")||s.currentSrc||s.src||""}function ln(s){return s.getAttribute("src")||""}function nt(s,e){const t=ln(s),i=s.currentSrc||"",r=s.src||"",n=Be(s);return{desiredSource:e||null,srcAttribute:t||null,currentSrc:i||null,elementSrc:r||null,assignedSrc:n||null,hasSrcAttribute:!!t,matchesDesiredByAttribute:!!e&&t===e,matchesDesiredByAssigned:!!e&&n===e}}function qi(s){return typeof HTMLVideoElement<"u"?s instanceof HTMLVideoElement:s.tagName==="VIDEO"}function $e(s){try{s.load()}catch{}}function ze(s){try{s.pause()}catch{}}function Ad(s){var e;try{const t=s.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function gs(s,e){try{s.currentTime=Math.max(0,e)}catch{}}function _i(s,e){var i;const t=(i=s==null?void 0:s.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function ms(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}function Id(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function Ed(s){const e=s.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 ae(s){return{tsMs:Id(),currentTime:Number.isFinite(s.currentTime)?Number(s.currentTime.toFixed(3)):null,duration:Number.isFinite(s.duration)?Number(s.duration.toFixed(3)):null,currentSrc:Be(s)||null,srcAttribute:ln(s)||null,elementSrc:s.src||null,rawCurrentSrc:s.currentSrc||null,readyState:typeof s.readyState=="number"?s.readyState:null,networkState:typeof s.networkState=="number"?s.networkState:null,paused:typeof s.paused=="boolean"?s.paused:null,ended:typeof s.ended=="boolean"?s.ended:null,playbackRate:typeof s.playbackRate=="number"?Number(s.playbackRate.toFixed(3)):null,bufferedEnd:Ed(s),videoWidth:qi(s)?s.videoWidth:null,videoHeight:qi(s)?s.videoHeight:null,error:s.error?{code:typeof s.error.code=="number"?s.error.code:null,message:s.error.message??null}:null}}function Rd(s,e,t){const i=e||s.clip.src||"";switch(t){case"abort":case"emptied":return`${s.clip.id}:${i}:${t}`;case"error":case"reconcile":case"stalled":return`${s.clip.id}:${i}:${Math.floor(s.mediaTime/Td)}`;default:return`${s.clip.id}:${i}`}}function Ve(s){return typeof(s==null?void 0:s.then)=="function"}function Md(s,e){var t;return((t=s.entry)==null?void 0:t.clip.id)===e}function Dd(s,e){var u;const t=s.activeClips.filter(f=>f.trackType!=="text"),i=s.nextClips.filter(f=>f.trackType!=="text"),r=s.interactionMode??"steady",n=new Map(t.map(f=>[f.trackId,f])),a=new Map(i.map(f=>[f.trackId,f])),o=new Map,l=t.filter(f=>f.trackType==="video"&&f.hasVisual).sort((f,g)=>f.trackOrder-g.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(f,g)=>!a.has(f)||r!=="steady"&&c?!1:c?s.playState==="playing"&&g==="video"&&f===h:s.playState!=="playing"||t.length<=1;return e.forEach(f=>{o.set(f.trackId,{kind:f.kind,order:f.order})}),t.forEach(f=>{o.set(f.trackId,{kind:f.trackType,order:f.trackOrder})}),i.forEach(f=>{o.set(f.trackId,{kind:f.trackType,order:f.trackOrder})}),Array.from(o.entries()).map(([f,g])=>{const y=n.get(f)||null,S=d(f,g.kind)&&a.get(f)||null;return{trackId:f,kind:g.kind,order:g.order,current:{role:"current",entry:y,playState:s.playState,speed:s.speed,visible:!!(y!=null&&y.hasVisual),zIndex:y?1e3-y.trackOrder:0,syncRequestId:s.syncRequestId},preload:{role:"preload",entry:S,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:s.syncRequestId}}}).sort((f,g)=>f.order-g.order)}class Ld{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,"transientFontSize",null);p(this,"transientRotation",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",{...De});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 fd(()=>{var i,r;(r=(i=this.callbacks).onPendingPreviewRetry)==null||r.call(i)}),this.transformOverlay=new vd({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onVisualTransformCommit)==null||a.call(n,i,r)},onFontSizeChange:(i,r)=>{var a;if(r===null){if(((a=this.transientFontSize)==null?void 0:a.clipId)===i){this.transientFontSize=null;const o=this.textPreviewEntries.get(i);o&&(o.element.style.fontSize=`${Me(o.entry.clip.textStyle).fontSize}px`),this.refreshVisualLayout()}return}this.transientFontSize={clipId:i,fontSize:r};const n=this.textPreviewEntries.get(i);n&&(n.element.style.fontSize=`${r}px`),this.refreshVisualLayout()},onFontSizeCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onTextFontSizeCommit)==null||a.call(n,i,r)},onRotationChange:(i,r)=>{var n;if(r===null){((n=this.transientRotation)==null?void 0:n.clipId)===i&&(this.transientRotation=null,this.refreshVisualLayout());return}this.transientRotation={clipId:i,rotation:r},this.refreshVisualLayout()},onRotationCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onTextRotationCommit)==null||a.call(n,i,r)}})}emitDiagnostic(e,t,i,r={}){var o,l;const n=this.dependencies.diagnostics;if(!n)return;const a=((l=(o=this.dependencies).getDiagnosticsContext)==null?void 0:l.call(o))??{};n.emit({...a,...r,severity:e,category:t,eventName:i,runtimeState:ka(a.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:Be(e.element)||null,extra:{role:e.role,kind:e.kind,phase:e.phase,retryCount:e.retryCount,sourceState:nt(e.element,e.desiredSource),...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=I.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,a;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&&(ze(this.aspectRatioProbe),this.aspectRatioProbe.src="",$e(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),(a=this.rootElement)==null||a.remove(),this.rootElement=null,this.frameElement=null,this.textOverlayRoot=null,this.pendingOverlayElement=null,this.container=null,this.primarySelectedClipId=null,this.transientVisualTransform=null,this.transientFontSize=null,this.transientRotation=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 a;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:((a=e.autoAspectRatioClip)==null?void 0:a.clip.id)??null}}),this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.transientFontSize&&this.transientFontSize.clipId!==this.primarySelectedClipId&&(this.transientFontSize=null),this.transientRotation&&this.transientRotation.clipId!==this.primarySelectedClipId&&(this.transientRotation=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=Dd(e,t).map(o=>this.applyTrackPlan(o)).filter(o=>Ve(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}),F.warn("TimelinePreviewSession","preview sync failed",{error:o,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=Xe(e),this.updateFrameLayout()}getAspectRatio(){return _d(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,qi(r)?(Tr(r),r.playsInline=!0,r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.objectFit="fill",r.style.background=I.black,r.style.pointerEvents="none"):r.style.display="none",r}createSlot(e,t,i){var v,T;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=I.black,n.style.pointerEvents="none",n.style.display="none",n.appendChild(r),(v=this.frameElement)==null||v.appendChild(n)}const a={role:i,trackId:e,kind:t,wrapper:n,element:r,entry:null,stableSourceUrl:null,desiredSource:null,objectUrl:null,pendingRuntimeSourceUrl:null,pendingRuntimeSourcePromise: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=()=>{a.isLoading=!1,a.isSeeking=!1,a.isBuffering=!1,a.errorMessage=null,this.resetSlotRecoveryTracking(a),a.consecutiveStalledCount=0,a.entry?a.phase=a.isActive?"active":"primed":a.phase="idle",this.tryResolveAutoAspectRatioFromSlot(a),this.refreshVisualLayout(),this.refreshRuntimeState()},l=()=>{if(!a.entry){a.isLoading=!1,a.phase="idle",this.refreshRuntimeState();return}this.emitDiagnostic("info","playback","media.loadstart",this.buildSlotTraceData(a,{message:"Media load started",mediaState:ae(a.element)})),a.isLoading=!0,a.loadStartedSinceRecover=!0,a.phase!=="recovering"&&(a.phase="binding"),this.refreshRuntimeState()},c=w=>{this.emitDiagnostic("info","playback",`media.${w.type}`,this.buildSlotTraceData(a,{message:`Media event: ${w.type}`,mediaState:ae(a.element)})),o()},h=()=>{this.emitDiagnostic("warn","playback","media.waiting",this.buildSlotTraceData(a,{message:"Media waiting",mediaState:ae(a.element),extra:{active:a.isActive}})),a.isBuffering=a.isActive&&!a.element.paused,this.refreshRuntimeState()},d=()=>{this.emitDiagnostic("warn","playback","media.stalled",this.buildSlotTraceData(a,{message:"Media stalled",mediaState:ae(a.element),extra:{active:a.isActive}})),a.isBuffering=a.isActive&&!a.element.paused,a.consecutiveStalledCount+=1,this.refreshRuntimeState(),a.isActive&&a.consecutiveStalledCount>=wd&&this.recoverSlot(a,"stalled")},u=()=>{if(!a.entry){a.isSeeking=!1,a.phase="idle",this.refreshRuntimeState();return}this.emitDiagnostic("debug","playback","media.seeking",this.buildSlotTraceData(a,{message:"Media seeking",mediaState:ae(a.element),extra:{active:a.isActive}})),a.isSeeking=!0,this.refreshRuntimeState()},f=()=>{this.emitDiagnostic("debug","playback","media.seeked",this.buildSlotTraceData(a,{message:"Media seeked",mediaState:ae(a.element)})),a.isSeeking=!1,a.isBuffering=!1,a.entry&&a.phase!=="failed"&&(a.phase=a.isActive?"active":"primed"),this.refreshRuntimeState()},g=w=>{var _;if(!this.shouldIgnoreClearedSlotRecoverableEvent(a)){if(w==="abort"&&this.shouldIgnoreExpectedAbort(a)){this.emitDiagnostic("debug","playback","media.abort.ignored",this.buildSlotTraceData(a,{message:"Ignored expected media abort during source reset",mediaState:ae(a.element)}));return}if(w==="emptied"&&this.shouldIgnoreExpectedEmptied(a)){this.emitDiagnostic("debug","playback","media.emptied.ignored",this.buildSlotTraceData(a,{message:"Ignored expected media emptied during source reset",mediaState:ae(a.element)}));return}if(this.emitDiagnostic(w==="error"?"error":"warn","playback",`media.${w}`,this.buildSlotTraceData(a,{message:`Media event: ${w}`,mediaState:ae(a.element),error:a.element.error})),F.warn("TimelinePreviewSession",`media event: ${w}`,{trackId:a.trackId,role:a.role,clipId:((_=a.entry)==null?void 0:_.clip.id)??null,phase:a.phase,mediaState:ae(a.element)}),a.forceRecover=!0,a.expectedEmptiedEvents=0,a.isLoading=!1,a.isSeeking=!1,a.isBuffering=!1,a.recoverableEventCount+=1,this.shouldSkipImmediatePreloadRecovery(a)){a.phase="idle",this.emitDiagnostic("info","recovery","preload.recovery.skipped",this.buildSlotTraceData(a,{message:"Skipped immediate preload recovery after recoverable media event",mediaState:ae(a.element),extra:{reason:w,recoverableEventCount:a.recoverableEventCount,loadStartedSinceRecover:a.loadStartedSinceRecover}})),this.refreshRuntimeState();return}if(this.refreshRuntimeState(),this.shouldDeferPreloadRecovery(a)){this.deferPreloadRecovery(a,w);return}this.recoverSlot(a,w)}},y=()=>g("abort"),S=()=>g("emptied"),C=()=>g("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",f),r.addEventListener("abort",y),r.addEventListener("emptied",S),r.addEventListener("error",C),a.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",f),()=>r.removeEventListener("abort",y),()=>r.removeEventListener("emptied",S),()=>r.removeEventListener("error",C)),t==="audio"&&((T=this.rootElement)==null||T.appendChild(r)),a}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,a;this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.resolveToken+=1,e.applyToken+=1,e.cleanup.forEach(o=>o()),ze(e.element),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.stableSourceUrl=null,e.element.removeAttribute("src"),$e(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,(a=e.wrapper)==null||a.remove(),e.element.remove()}releaseSlotObjectUrl(e){var t;e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl),e.objectUrl=null)}clearPendingRuntimeSource(e){e.pendingRuntimeSourceUrl=null,e.pendingRuntimeSourcePromise=null}rememberSlotObjectUrl(e,t){e.objectUrl&&e.objectUrl!==t&&this.releaseSlotObjectUrl(e),e.objectUrl=t??null}revokeResolvedObjectUrl(e){var t;e!=null&&e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl))}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(Ve(i)||Ve(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=Be(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}})),ze(e.element),e.stableSourceUrl=null,e.desiredSource=null,e.errorMessage=null,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,this.resetSlotRecoveryTracking(e),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.element.removeAttribute("src"),$e(e.element),e.phase="idle",this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}const a=this.resolveDesiredSource(e,t.entry,i);if(Ve(a))return a.then(o=>{if(!o||!this.isCurrentSourceTarget(e,t.entry,o.stableSourceUrl)){this.revokeResolvedObjectUrl(o);return}const l=this.buildCurrentTargetForSlot(e)??t;if(!l.entry){this.revokeResolvedObjectUrl(o);return}if(e.stableSourceUrl=o.stableSourceUrl,e.desiredSource=o.url,this.configureAudioRouting(e,l.entry),this.slotNeedsRecovery(e,o.url)){if(this.shouldDeferPreloadTarget(e,l,o.url)){this.deferPreloadTarget(e,l,o,"current-loading");return}return Promise.resolve(this.recoverSlot(e,"reconcile",l,void 0,o)).then(()=>{})}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,o.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,l)});if(!a||!this.isCurrentRequest(e,i,t.entry)){this.revokeResolvedObjectUrl(a);return}if(e.stableSourceUrl=a.stableSourceUrl,e.desiredSource=a.url,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,a.url)){if(this.shouldDeferPreloadTarget(e,t,a.url)){this.deferPreloadTarget(e,t,a,"current-loading");return}return this.recoverSlot(e,"reconcile",t,i,a)}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,a.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,t)}settleResolvedSourceWithoutRecovery(e){e.phase==="binding"&&(e.phase=e.isActive?"active":"primed"),e.isLoading=!1,e.isBuffering=!1,e.errorMessage=null}resolveDesiredSource(e,t,i){const r=this.dependencies.previewSourceResolver??pd,n=this.dependencies.sourceMediaRegistry;let a=null;const o=()=>(a!==null||(e.resolveToken+=1,a=e.resolveToken,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:a}})),this.refreshRuntimeState()),a);if(!r){const l={url:t.clip.src};return this.dependencies.resourceCacheManager&&o(),this.resolvePlayableSlotSource(e,t,l)}try{const l=n?n.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>r(t.clip)):r(t.clip);if(Ve(l)){const c=o();return l.then(h=>c!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:h?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:h.url,extra:{mimeType:h.mimeType,mediaKind:h.kind}})),this.resolvePlayableSlotSource(e,t,h)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(h=>(this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:h})),F.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:h}),this.failSlot(e,t,"预览源解析失败"),null))}return 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.dependencies.resourceCacheManager&&o(),this.resolvePlayableSlotSource(e,t,l)):(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){return this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:l})),F.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:l}),this.failSlot(e,t,"预览源解析失败"),null}}decorateSlotSourceUrl(e,t){return t}resolvePlayableSlotSource(e,t,i){const r=this.dependencies.resourceCacheManager,n=this.getReusableResolvedSlotSource(e,i);if(n)return this.emitRuntimeSourceDiagnostic(e,i.url,n,"source.runtime.reused","Reused existing runtime preview source"),n;if(e.pendingRuntimeSourceUrl===i.url&&e.pendingRuntimeSourcePromise)return this.emitRuntimeSourceDiagnostic(e,i.url,null,"source.runtime.pending-reused","Reused pending runtime preview source resolution"),e.pendingRuntimeSourcePromise;if(!r)return{stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null};const a=()=>!this.isCurrentSourceTarget(e,t,i.url),o={url:i.url,mimeType:i.mimeType,kind:i.kind,sourceKey:this.buildPreviewSourceCacheKey(t.clip)},l=()=>({stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null});try{const c=r.resolvePlayableUrl(o),h=d=>{if(!(d!=null&&d.url))return a()?null:l();const u={stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,d.url),objectUrl:d.objectUrl??null};return a()?(this.revokeResolvedObjectUrl(u),null):(this.emitRuntimeSourceDiagnostic(e,i.url,u,"source.runtime.resolved","Resolved runtime playable source",{cacheStatus:d.cacheStatus}),u)};if(Ve(c)){const d=c.then(h).catch(()=>a()?null:l());return d.finally(()=>{e.pendingRuntimeSourcePromise===d&&this.clearPendingRuntimeSource(e)}).catch(()=>{}),e.pendingRuntimeSourceUrl=i.url,e.pendingRuntimeSourcePromise=d,d}return h(c)}catch{return a()?null:l()}}emitRuntimeSourceDiagnostic(e,t,i,r,n,a={}){const o=(i==null?void 0:i.url)??t;this.emitDiagnostic("debug","resource",r,this.buildSlotTraceData(e,{message:n,desiredSourceUrl:o,actualSourceUrl:Be(e.element)||null,mediaState:ae(e.element),extra:{stableSourceUrl:t,runtimeSourceUrl:(i==null?void 0:i.url)??null,objectUrl:(i==null?void 0:i.objectUrl)??null,sourceState:nt(e.element,o),...a}}))}getReusableResolvedSlotSource(e,t){if(!e.desiredSource||e.stableSourceUrl!==t.url)return null;const i=e.objectUrl??(e.desiredSource.startsWith("blob:")?e.desiredSource:null);return{stableSourceUrl:t.url,url:e.desiredSource,objectUrl:i}}slotNeedsRecovery(e,t){const i=ln(e.element),r=i||Be(e.element);let n=!1,a=null;e.forceRecover?(n=!0,a="force-recover"):i?r!==t?(n=!0,a="source-mismatch"):(typeof e.element.networkState=="number"?e.element.networkState:null)===Cd&&(n=!(e.isLoading||e.phase==="binding"||e.phase==="recovering"),a=n?"network-empty":"network-empty-binding-in-flight"):(n=!0,a="missing-src-attribute");const o=n&&(a==="source-mismatch"||e.isActive&&e.phase!=="idle"&&e.phase!=="binding");return this.emitDiagnostic(o?"warn":"debug","recovery","slot.recovery-check",this.buildSlotTraceData(e,{message:n?"Preview slot needs recovery":"Preview slot source is reusable",desiredSourceUrl:t,actualSourceUrl:r||null,mediaState:ae(e.element),extra:{needsRecovery:n,recoveryReason:a,configuredSource:i||null,actualSource:r||null,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,sourceState:nt(e.element,t)}})),n}recoverSlot(e,t,i,r,n){const a=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||!a||r!==void 0&&!this.isCurrentRequest(e,r,e.entry))return;const o=n??(e.desiredSource?{stableSourceUrl:e.stableSourceUrl??e.desiredSource,url:e.desiredSource,objectUrl:e.objectUrl}:this.resolveDesiredSource(e,e.entry,e.applyToken));if(Ve(o))return o.then(l=>{l&&this.finishSlotRecovery(e,t,a,l,r)});o&&this.finishSlotRecovery(e,t,a,o,r)}finishSlotRecovery(e,t,i,r,n){if(!e.entry)return;const a=typeof r=="string"?{stableSourceUrl:e.stableSourceUrl??r,url:r,objectUrl:e.objectUrl}:r,o=a.url,l=Rd(e.entry,o,t);if(e.recoveryKey===l){if(e.retryCount>=bd){this.isBackgroundPreloadSlot(e)?this.parkPreloadSlot(e,"媒体恢复失败,请等待下一次重建","retries-exhausted"):this.failSlot(e,e.entry,"媒体恢复失败,请刷新重试");return}e.retryCount+=1}else e.recoveryKey=l,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:o,mediaState:ae(e.element),extra:{reason:t,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState}})),(t!=="reconcile"||e.retryCount>1)&&F.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:o,mediaState:ae(e.element)});const c=Be(e.element),h=nt(e.element,o),d=!!c||t!=="reconcile"||e.retryCount>1;ze(e.element),e.expectedEmptiedEvents=d?2:1,e.stableSourceUrl=a.stableSourceUrl,this.rememberSlotObjectUrl(e,a.objectUrl),d&&(e.element.removeAttribute("src"),$e(e.element)),e.element.setAttribute("src",o),$e(e.element),this.emitDiagnostic("info","resource","source.assigned",this.buildSlotTraceData(e,{message:"Preview source assigned",desiredSourceUrl:o,actualSourceUrl:o,extra:{reason:t,hardReset:d,previousSourceState:h,nextSourceState:nt(e.element,o),objectUrl:a.objectUrl,stableSourceUrl:a.stableSourceUrl}})),!(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){const n=i.url;e.desiredSource=n,this.rememberSlotObjectUrl(e,i.objectUrl),e.forceRecover=!0,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.errorMessage=null,e.element.getAttribute("src")&&e.element.getAttribute("src")!==n&&(ze(e.element),e.element.removeAttribute("src"),$e(e.element)),Be(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:n,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),a=r==="current"?n==null?void 0:n.current:n==null?void 0:n.preload;if(!a||a.role!=="preload"||!a.entry)continue;const o=this.buildDeferredPreloadTarget(a);if(o){if(this.emitDiagnostic("info","recovery","preload.recovery.resumed",this.buildSlotTraceData(a,{message:"Resumed deferred preload recovery",desiredSourceUrl:a.desiredSource,extra:{requestedPlayState:a.requestedPlayState}})),a.desiredSource&&this.slotNeedsRecovery(a,a.desiredSource)){this.recoverSlot(a,"reconcile",o);continue}this.resetSlotRecoveryTracking(a),this.applyResolvedSlotState(a,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())}buildCurrentTargetForSlot(e){return 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.isActive?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null}isCurrentRequest(e,t,i){var r;return e.applyToken===t&&((r=e.entry)==null?void 0:r.clip.id)===i.clip.id}isCurrentSourceTarget(e,t,i){return!e.entry||e.entry.clip.id!==t.clip.id?!1:this.buildPreviewSourceCacheKey(e.entry.clip)===this.buildPreviewSourceCacheKey(t.clip)||e.stableSourceUrl===i||e.desiredSource===i}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){ze(e.element),this.releaseSlotObjectUrl(e),e.element.removeAttribute("src"),$e(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:ae(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:ae(e.element),extra:{errorMessage:i}})),F.warn("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,mediaState:ae(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,a=Math.max(.1,i*.15);if(Math.abs(e.element.currentTime-n)>a&&(this.emitDiagnostic("debug","playback","media.current-slot.seek",this.buildSlotTraceData(e,{message:"Current slot seek applied",mediaState:ae(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(a.toFixed(3))}})),e.isSeeking=!0,gs(e.element,n)),r==="playing"){this.resumeAudioContext();const l=nt(e.element,e.desiredSource);this.emitDiagnostic(l.hasSrcAttribute?"debug":"warn","playback","media.play.requested",this.buildSlotTraceData(e,{message:l.hasSrcAttribute?"Media play requested":"Media play requested without configured src attribute",mediaState:ae(e.element),extra:{playState:r,speed:i,sourceState:l}})),Ad(e.element)}else this.emitDiagnostic("debug","playback","media.pause.requested",this.buildSlotTraceData(e,{message:"Media pause requested",mediaState:ae(e.element),extra:{playState:r,speed:i,sourceState:nt(e.element,e.desiredSource)}})),ze(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:ae(e.element),extra:{toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3))}})),gs(e.element,t.clip.startTimeAtSource/1e3),ze(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,a=i/r;let o=i,l=r;n>a?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(!wt(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 a=await this.resolveAspectRatioProbeSource(e,r);if(!a||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:a}),this.refreshRuntimeState(),o.crossOrigin="anonymous",o.preload="metadata",o.muted=!0,o.src=a,$e(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(!Ve(n))return(n==null?void 0:n.url)??null;this.isAspectRatioProbeLoading=!0,this.refreshRuntimeState();const a=await n;return t!==this.aspectRatioProbeResolveToken?null:(a==null?void 0:a.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");Tr(e);const 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(!wt(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(),wt(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var C,v,T,w,_,x,L;const e=[];let t=this.isAspectRatioProbeLoading?1:0,i=0,r=!1,n=null,a=!1,o=!1,l=!1,c=!1,h=!1,d=!1;for(const{current:k,preload:M}of this.trackSlots.values())for(const P of[k,M]){const $=Be(P.element)||null;e.push({trackId:P.trackId,role:P.role,kind:P.kind,clipId:((C=P.entry)==null?void 0:C.clip.id)??null,desiredSource:P.desiredSource,actualSource:$,phase:P.phase,retryCount:P.retryCount,errorMessage:P.errorMessage}),P.phase!=="idle"&&(a=!0),P.entry&&P.phase!=="idle"&&P.phase!=="failed"&&(l=!0),(P.isLoading||P.phase==="binding"||P.phase==="recovering")&&(this.isActiveCurrentSlot(P)?t+=1:i+=1),P.isBuffering&&this.isActiveCurrentSlot(P)&&(h=!0),P.phase==="failed"&&(o=!0),P.phase==="failed"&&!n&&(n=P.errorMessage||"资源加载异常,请刷新重试"),P.isActive&&P.entry&&(P.isSeeking||P.phase!=="active"&&P.phase!=="failed")&&(c=!0),P.role==="current"&&P.isActive&&P.entry&&P.phase==="active"&&!P.isLoading&&!P.isSeeking&&!P.isBuffering&&(d=!0)}r=h&&!d;const u=d?0:t;let f="idle";this.activeSyncRequestId!==void 0&&this.isSyncProjecting?f="awaiting-sync":o&&!l?f="failed":u>0||r||c&&!d?f="awaiting-media":a&&(f="ready"),f!=="failed"&&(n=null),this.loadingCount!==u&&(this.loadingCount=u,(T=(v=this.callbacks).onSourceLoadingChange)==null||T.call(v,u)),this.syncVisibleBufferingState(r);const g={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:f,loadingCount:u,isBuffering:r,errorMessage:n,slots:e},y=this.lastRuntimeState,S=JSON.stringify(g);S!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=S,this.lastRuntimeState=g,(y.phase!==g.phase||y.loadingCount!==g.loadingCount||y.isBuffering!==g.isBuffering||y.errorMessage!==g.errorMessage)&&this.emitDiagnostic(g.phase==="failed"?"error":"info","runtime","runtime.state",{message:"Preview runtime state updated",syncRequestId:g.syncRequestId??null,runtimeState:{runtimePhase:g.phase,loadingCount:g.loadingCount,isBuffering:g.isBuffering},extra:{backgroundLoadingCount:i,previousPhase:y.phase,phase:g.phase,errorMessage:g.errorMessage,slots:g.slots.map(k=>({trackId:k.trackId,role:k.role,clipId:k.clipId,phase:k.phase,retryCount:k.retryCount,desiredSource:k.desiredSource,actualSource:k.actualSource}))}}),(_=(w=this.callbacks).onRuntimeStateChange)==null||_.call(w,g)),(f==="ready"||f==="failed")&&g.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==g.syncRequestId&&(this.lastSettledSyncRequestId=g.syncRequestId,(L=(x=this.callbacks).onSyncProcessed)==null||L.call(x,g.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,this.refreshPendingOverlay(),(n=(r=this.callbacks).onBufferingStateChange)==null||n.call(r,!0))},kd);return}this.clearBufferingVisibleTimeout(),this.isBuffering&&(this.isBuffering=!1,this.refreshPendingOverlay(),(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,isBuffering:this.isBuffering})}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 a=document.createElement("div");a.className="timeline-preview-text-entry",a.style.position="absolute",a.style.left="0",a.style.top="0",a.style.transformOrigin="center center",a.style.whiteSpace="pre",a.style.wordBreak="normal",a.style.overflowWrap="normal",a.style.pointerEvents="none",a.style.userSelect="none",a.style.boxSizing="border-box",a.style.border="1px solid transparent";const o=this.createTextPreviewPointerDownHandler(r.clip.id);a.addEventListener("pointerdown",o),(c=this.textOverlayRoot)==null||c.appendChild(a);const l={entry:r,element:a,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=Me(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.textShadow=xd(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(){var i;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return;const t=this.getTextPreviewBaselineMetrics(e);for(const r of this.textPreviewEntries.values()){const n=this.getEffectiveVisualTransform(r.entry),a=r.entry.clip.id,o=Me(r.entry.clip.textStyle).rotation,l=((i=this.transientRotation)==null?void 0:i.clipId)===a?this.transientRotation.rotation:o;r.element.style.left=`${e.width*n.x}px`,r.element.style.top=`${e.height*n.y}px`,r.element.style.transform=["translate(-50%, -50%)",`scale(${t.scale*n.scale})`,`rotate(${l}deg)`].join(" ")}}refreshTextPreviewEntries(){for(const e of this.textPreviewEntries.values())this.applyTextPreviewEntry(e);this.refreshTextPreviewLayout(),this.refreshTextPreviewInteractionState()}createTextPreviewPointerDownHandler(e){return t=>{var a,o,l,c;const i=t;if((i.button??0)!==0)return;if((a=i.preventDefault)==null||a.call(i),(o=i.stopPropagation)==null||o.call(i),this.primarySelectedClipId!==e){(c=(l=this.callbacks).onPreviewClipSelect)==null||c.call(l,e);return}this.textPreviewDragState&&this.finishTextPreviewDrag(!1);const r=this.textPreviewEntries.get(e);if(!r)return;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),a=$a(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=a,t.changed=!on(t.startTransform,a),this.handlePreviewTransformChange(t.clipId,a),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="auto",t.element.style.cursor=i?r?"grabbing":"grab":"pointer",t.element.style.border=i?`1px solid ${st.border}`:"1px solid transparent"}}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"?fs:`${mr(e.fontName)}, ${fs}`}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: ${mr(e.fontName)};`,`src: url("${za(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 ${mr(e.fontName)}`)).then(()=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="loaded",this.refreshTextPreviewEntries())}).catch(n=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="failed",F.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=us(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(){var t,i;if(!this.primarySelectedClipId)return null;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return null;for(const{current:r}of this.trackSlots.values()){if(r.kind!=="video"||!r.isActive||!r.entry||r.entry.clip.id!==this.primarySelectedClipId)continue;const n=this.getMediaSize(r,r.entry,e),a=this.getEffectiveVisualTransform(r.entry);return{clipId:r.entry.clip.id,transform:a,frameSize:e,baseRect:Na(e,n),displayRect:us(e,n,a),clipType:"video"}}if(this.frameElement)for(const[r,n]of this.textPreviewEntries){if(r!==this.primarySelectedClipId)continue;const a=this.getEffectiveVisualTransform(n.entry),o=Me(n.entry.clip.textStyle),l=((t=this.transientFontSize)==null?void 0:t.clipId)===r?this.transientFontSize.fontSize:o.fontSize,c=((i=this.transientRotation)==null?void 0:i.clipId)===r?this.transientRotation.rotation:o.rotation,d=this.getTextPreviewBaselineMetrics(e).scale*a.scale,u=(n.element.offsetWidth||0)*d,f=(n.element.offsetHeight||0)*d,g=e.width*a.x,y=e.height*a.y;return{clipId:r,transform:a,frameSize:e,baseRect:{left:0,top:0,width:e.width,height:e.height,centerX:e.width/2,centerY:e.height/2},displayRect:{left:g-u/2,top:y-f/2,width:u,height:f,centerX:g,centerY:y},clipType:"text",currentFontSize:l,currentRotation:c}}return null}getFrameSize(){var i,r,n,a;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:ms((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:ms((a=this.frameElement)==null?void 0:a.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=Pd(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(qi(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 Od extends Ld{constructor(e={}){super(e.callbacks,{diagnostics:e.diagnostics,getDiagnosticsContext:e.getDiagnosticsContext,previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont,sourceMediaRegistry:e.sourceMediaRegistry,resourceCacheManager:e.resourceCacheManager,rootClassName:e.rootClassName,frameClassName:e.frameClassName,slotClassNamePrefix:e.slotClassNamePrefix})}destroy(){this.detach()}}function Bd(s){return"dom"}const Fd=36e5,Gd=3e5;function Ur(s){return s.length===0?0:s.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function ys(s){return Ur(s)}function Ss(s){return Math.max(s+Gd,Fd)}class vs{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){F.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function Hd(s){return[...s].sort((e,t)=>e.order-t.order)}function Nd(s){return[...s].sort((e,t)=>e.startTime-t.startTime)}function yr(s,e,t){const i=s.type==="video"||s.type==="text",r=s.type!=="text";return{trackId:s.id,trackType:s.type,trackOrder:s.order,clip:e,mediaTime:t,muted:(s.isMuted??!1)||(e.isMuted??!1),kind:s.type,hasVisual:i,hasAudio:r}}class $d{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t){const i=Hd(e),r=[],n=[];let a=null;for(const o of i){const l=Nd(o.clips),c=l.find(d=>t>=d.startTime&&t<d.endTime);if(c){const d=c.startTimeAtSource+(t-c.startTime);r.push(yr(o,c,d))}const h=l.find(d=>d.startTime>t);if(h&&n.push(yr(o,h,h.startTimeAtSource)),!a&&o.type==="video"){const d=l[0];d&&(a=yr(o,d,d.startTimeAtSource))}}return{activeClips:r,nextClips:n,firstVideoClip:a}}}class zd{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 Vd=8e3,Ud=1e3;class Wd{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??Vd,this.failedOverlayDelayMs=e.failedOverlayDelayMs??Ud}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 Yd=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Xd={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 qd(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function jd(s){const e=s.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 Kd(s,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,a=!1,o=!1,l=!1;for(const c of i)switch(c.toLowerCase()){case"mod":t?o=!0:a=!0;break;case"alt":case"option":n=!0;break;case"ctrl":case"control":a=!0;break;case"cmd":case"command":case"meta":o=!0;break;case"shift":l=!0;break;default:{const h=jd(c);if(!h||r)return null;r=h}}return r?{action:s,code:r,altKey:n,ctrlKey:a,metaKey:o,shiftKey:l}:null}function Zd(s){if(!(s instanceof HTMLElement))return!1;if(s.isContentEditable)return!0;const e=s.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:!!s.closest('[contenteditable=""], [contenteditable="true"], input, textarea, select')}function Jd(s,e){return s.code===e.code&&s.altKey===e.altKey&&s.ctrlKey===e.ctrlKey&&s.metaKey===e.metaKey&&s.shiftKey===e.shiftKey}function Qd(s,e){return s===!1||(s==null?void 0:s.enabled)===!1?[]:Yd.flatMap(t=>{var n;const i=(n=s==null?void 0:s.bindings)==null?void 0:n[t];return(i===void 0?Xd[t]:Array.isArray(i)?i:[i]).map(a=>Kd(t,a,e)).filter(a=>a!==null)})}class eu{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??qd();e.root,this.callbacks=e.callbacks,this.bindings=Qd(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(Zd(e.target))return;const t=this.bindings.find(i=>Jd(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 Va(s){var t;const e=s.getPrimarySelectedClip()||((t=s.findFallbackSelectedClip)==null?void 0:t.call(s))||null;return{clip:e,hasSelectedClip:!!e}}function tu(s){const e=Va(s),t=s.getSelectedClipIds(),i=s.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:s.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function iu(s){var i;const e=s.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===s.lastSelectedClipId?s.lastSelectedClipId:(s.emitSelectedClipChange(e),t)}function ru(s,e){var t,i,r,n;return((i=(t=s.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((n=(r=s.getLastTrack())==null?void 0:r.getId)==null?void 0:n.call(r))||e}function nu(s){if(s.placement.status==="use_existing_track")return s.trackCollection.addClipToTrack(s.placement.trackId,s.clip);const e=s.createTrack(s.placement.trackType,s.placement.suggestedTrackName,s.placement.insertionPlacement),t=ru(s.trackCollection,e);return t?s.trackCollection.addClipToTrack(t,s.clip):!1}function Cs(s,e,t){return e.trackId?s.removeClipFromTrack(e.trackId,t):!1}function su(s){return s.trackCollection.moveClipToTrack(s.command.clip,s.command.sourceTrackId,s.command.targetTrackId)}function Ue(s){var e,t,i,r,n;(e=s.checkTrackDurationChange)==null||e.call(s),(t=s.updateCanPlayState)==null||t.call(s),(i=s.updateTrackInfoPanel)==null||i.call(s),(r=s.handleClipChange)==null||r.call(s),(n=s.cleanupEmptyTracks)==null||n.call(s)}function au(s){var e,t;s.notifySelectionChange(),(e=s.cleanupEmptyTracks)==null||e.call(s),s.updateTrackInfoPanel(),(t=s.batchDraw)==null||t.call(s),s.syncPreviewSession()}class ou{constructor(){p(this,"panel",null)}init(e){var i,r,n,a;const t=((i=e.theme)==null?void 0:i.background)||be.background;this.panel=new Ga({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:((a=e.theme)==null?void 0:a.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 bs{syncCurrentTime(e,t,i,r){e==null||e.setCurrentTime(r),t==null||t.setCurrentTime(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()}}const lu=100*1024*1024,cu=10*1024*1024*1024,hu=30*24*60*60*1e3,du=["video/mp4","audio/aac","audio/mpeg","audio/mp4","audio/mp3","audio/ogg","audio/wav","audio/x-wav"],ei={enabled:!1,maxEntryBytes:lu,maxTotalBytes:cu,ttlMs:hu,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:du},uu="timeline-preview-resource-cache",pu=1,ge="metadata";function fu(){return new Promise((s,e)=>{const t=indexedDB.open(uu,pu);t.onupgradeneeded=()=>{const i=t.result,r=i.objectStoreNames.contains(ge)?t.transaction.objectStore(ge):i.createObjectStore(ge,{keyPath:"cacheKey"});r.indexNames.contains("sourceUrl")||r.createIndex("sourceUrl","sourceUrl"),r.indexNames.contains("expiresAt")||r.createIndex("expiresAt","expiresAt"),r.indexNames.contains("lastAccessedAt")||r.createIndex("lastAccessedAt","lastAccessedAt"),r.indexNames.contains("storageKind")||r.createIndex("storageKind","storageKind")},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function Sr(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class gu{constructor(){p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=fu().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async get(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(ge,"readonly").objectStore(ge).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async put(e){const i=(await this.getDb()).transaction(ge,"readwrite");i.objectStore(ge).put(e),await Sr(i)}async delete(e){const i=(await this.getDb()).transaction(ge,"readwrite");i.objectStore(ge).delete(e),await Sr(i)}async clear(){const t=(await this.getDb()).transaction(ge,"readwrite");t.objectStore(ge).clear(),await Sr(t)}async list(){const e=await this.getDb();return new Promise((t,i)=>{const r=e.transaction(ge,"readonly").objectStore(ge).getAll();r.onerror=()=>i(r.error),r.onsuccess=()=>t(r.result)})}}const mu="timeline-preview-resource-cache",yu="timeline-preview-resource-cache-blobs",Su=1,Ee="blobs";function vu(){return new Promise((s,e)=>{const t=indexedDB.open(yu,Su);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function vr(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class Cu{constructor(){p(this,"kind","indexeddb");p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=vu().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async read(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(Ee,"readonly").objectStore(Ee).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Ee,"readwrite");r.objectStore(Ee).put(t,e),await vr(r)}async delete(e){const i=(await this.getDb()).transaction(Ee,"readwrite");i.objectStore(Ee).delete(e),await vr(i)}async clear(){const t=(await this.getDb()).transaction(Ee,"readwrite");t.objectStore(Ee).clear(),await vr(t)}}class bu{constructor(){p(this,"kind","opfs");p(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(mu,{create:!0})).catch(e=>{throw this.directoryPromise=null,e})),this.directoryPromise}async ensureReady(){try{return await this.getDirectory(),!0}catch{return!1}}async read(e){try{return await(await(await this.getDirectory()).getFileHandle(e)).getFile()}catch{return null}}async write(e,t){const n=await(await(await this.getDirectory()).getFileHandle(e,{create:!0})).createWritable();try{await n.write(t),await n.close()}catch(a){try{typeof n.abort=="function"&&await n.abort()}catch{}throw a}}async delete(e){const t=await this.getDirectory();try{await t.removeEntry(e)}catch{}}async clear(){const e=await this.getDirectory();for await(const[t]of e)await e.removeEntry(t)}}async function Tu(s){var e;if(s.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new bu;if(await t.ensureReady())return t}return new Cu}function wu(s){return Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function Ts(s){return s.split(";",1)[0].trim().toLowerCase()}async function ku(s){const e=globalThis.crypto;if(!(e!=null&&e.subtle))throw new Error("Resource cache key generation requires Web Crypto SHA-256 support.");const t=await e.subtle.digest("SHA-256",new TextEncoder().encode(s));return wu(new Uint8Array(t))}function Cr(s){return s?[...s]:[...ei.allowedMimeTypes]}function xu(s){return s?s===!0?{...ei,enabled:!0,allowedMimeTypes:Cr(void 0)}:{...ei,...s,enabled:s.enabled??!0,allowedMimeTypes:Cr(s.allowedMimeTypes)}:{...ei,allowedMimeTypes:Cr(void 0)}}function Pu(s){try{const e=new URL(s);return e.hash="",e.toString()}catch{return s.trim()}}async function _u(s){var t;const e=((t=s.sourceKey)==null?void 0:t.trim())||Pu(s.url);return ku(e)}function ws(s,e=ei.allowedMimeTypes){if(!s.url)return!0;let t;try{t=new URL(s.url)}catch{return!0}if(t.protocol!=="http:"&&t.protocol!=="https:"||s.kind==="hls-fmp4"||/\.m3u8(?:$|\?|#)/i.test(t.pathname))return!0;if(!s.mimeType)return!1;const i=Ts(s.mimeType);return!e.some(r=>Ts(r)===i)}function Au(s){return s&&s.split(";",1)[0].trim().toLowerCase()||null}function ks(s){if(!s)return null;const e=Number(s);return Number.isSafeInteger(e)&&e>=0?e:null}function Iu(s){if(!s)return null;const e=s.match(/^bytes\s+(?:\d+-\d+|\*)\/(\d+|\*)$/i);if(!e||e[1]==="*")return null;const t=Number(e[1]);return Number.isSafeInteger(t)&&t>=0?t:null}function xs(s,e,t){return{url:e,ok:s.ok,status:s.status,mimeType:Au(s.headers.get("content-type")),sizeBytes:t,etag:s.headers.get("etag"),lastModified:s.headers.get("last-modified"),acceptRanges:s.headers.get("accept-ranges")}}class Eu{async probe(e){var r;try{const n=await fetch(e,{method:"HEAD"}),a=ks(n.headers.get("content-length"));if(n.ok&&a!==null)return xs(n,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=Iu(t.headers.get("content-range"))??ks(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return xs(t,e,i)}async download(e){const t=await fetch(e);if(!t.ok)throw new Error(`Resource cache download failed with HTTP ${t.status}.`);return t.blob()}}const Ru={createObjectURL(s){return URL.createObjectURL(s)},revokeObjectURL(s){URL.revokeObjectURL(s)}};function vt(s,e){return{url:s.url,cacheStatus:e,sourceUrl:s.url}}function Mu(s,e){return s.etag||e.etag?s.etag===e.etag&&s.sizeBytes===e.contentLength:s.sizeBytes===e.contentLength&&s.lastModified===e.lastModified}class Du{constructor(e={}){p(this,"options");p(this,"metadataStore");p(this,"storagePromise");p(this,"http");p(this,"objectUrl");p(this,"now");p(this,"cacheKeyBuilder");p(this,"onEvent");p(this,"objectUrls",new Set);p(this,"inflightDownloads",new Map);this.options=xu(e.options),this.metadataStore=e.metadataStore??new gu,this.storagePromise=e.storage?Promise.resolve(e.storage):Tu({preferStorage:this.options.preferStorage}),this.http=e.http??new Eu,this.objectUrl=e.objectUrl??Ru,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??_u,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||ws(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),vt(e,"bypass");try{const t=await this.cacheKeyBuilder(e),i=await this.storagePromise,r=await this.metadataStore.get(t);if(r){const l=await i.read(t);if(l){if(r.expiresAt>this.now()){const c={...r,lastAccessedAt:this.now()};return await this.metadataStore.put(c),this.emitEvent("resource-cache.hit",{sourceUrl:e.url,sizeBytes:c.sizeBytes}),this.blobResult(e.url,l,c,"hit")}return await this.resolveExpired(e,t,r,l,i)}await this.metadataStore.delete(t)}if(this.options.resolveMode==="prefer-fast-start")return this.probeAndDownload(t,e,i).catch(()=>{}),this.emitEvent("resource-cache.miss",{sourceUrl:e.url}),vt(e,"miss");const n=await this.probeCacheable(e);if(n.cacheStatus!=="miss")return n.result;const{blob:a,metadata:o}=await this.getOrCreateDownload(t,e,n.probe,i);return this.emitEvent("resource-cache.miss",{sourceUrl:e.url,sizeBytes:o.sizeBytes}),this.blobResult(e.url,a,o,"miss")}catch{return this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),vt(e,"fallback")}}revokeObjectUrl(e){this.objectUrls.delete(e)&&this.objectUrl.revokeObjectURL(e)}async cleanupExpired(){const e=await this.storagePromise,t=this.now(),i=await this.metadataStore.list();await Promise.all(i.filter(r=>r.expiresAt<=t).map(r=>this.deleteEntry(r.cacheKey,e)))}async clear(){const e=await this.storagePromise;await Promise.all([e.clear(),this.metadataStore.clear()]);for(const t of[...this.objectUrls])this.revokeObjectUrl(t)}async getStats(){const e=await this.metadataStore.list();return{entryCount:e.length,totalBytes:e.reduce((t,i)=>t+i.sizeBytes,0),maxTotalBytes:this.options.maxTotalBytes}}async resolveExpired(e,t,i,r,n){const a=await this.probeCacheable(e);if(a.cacheStatus!=="miss")return a.result;if(Mu(a.probe,i)){const c=this.now(),h={...i,updatedAt:c,lastAccessedAt:c,expiresAt:c+this.options.ttlMs};return await this.metadataStore.put(h),this.emitEvent("resource-cache.revalidate.success",{sourceUrl:e.url,sizeBytes:h.sizeBytes}),this.blobResult(e.url,r,h,"stale-revalidated")}this.emitEvent("resource-cache.revalidate.stale",{sourceUrl:e.url}),await this.deleteEntry(t,n);const{blob:o,metadata:l}=await this.getOrCreateDownload(t,e,a.probe,n);return this.blobResult(e.url,o,l,"miss")}async probeCacheable(e){const t=await this.http.probe(e.url);return t.ok?t.sizeBytes===null?(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:vt(e,"fallback")}):ws({...e,mimeType:e.mimeType??t.mimeType},this.options.allowedMimeTypes)||t.sizeBytes>this.options.maxEntryBytes||t.sizeBytes>this.options.maxTotalBytes?(this.emitEvent("resource-cache.bypass",{sourceUrl:e.url,sizeBytes:t.sizeBytes,mimeType:t.mimeType}),{cacheStatus:"bypass",result:vt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:vt(e,"fallback")})}async probeAndDownload(e,t,i){const r=await this.probeCacheable(t);r.cacheStatus==="miss"&&await this.getOrCreateDownload(e,t,r.probe,i)}getOrCreateDownload(e,t,i,r){const n=this.inflightDownloads.get(e);if(n)return n;const a=this.downloadAndStore(e,t,i,r).finally(()=>{this.inflightDownloads.delete(e)});return this.inflightDownloads.set(e,a),a}async downloadAndStore(e,t,i,r){this.emitEvent("resource-cache.download.start",{sourceUrl:t.url});try{const n=await this.http.download(t.url),a=n.size;if(a>this.options.maxEntryBytes||a>this.options.maxTotalBytes)throw new Error("Resource exceeds cache capacity.");await this.evictForWrite(e,a,r),await r.write(e,n);const o=this.now(),l={cacheKey:e,sourceUrl:t.url,mimeType:i.mimeType??t.mimeType??null,sizeBytes:a,etag:i.etag,lastModified:i.lastModified,contentLength:a,storageKind:r.kind,createdAt:o,updatedAt:o,lastAccessedAt:o,expiresAt:o+this.options.ttlMs};return await this.metadataStore.put(l),this.emitEvent("resource-cache.download.success",{sourceUrl:t.url,sizeBytes:a}),{blob:n,metadata:l}}catch(n){throw this.emitEvent("resource-cache.download.failed",{sourceUrl:t.url,error:n instanceof Error?n.message:String(n)}),n}}async evictForWrite(e,t,i){const r=(await this.metadataStore.list()).filter(a=>a.cacheKey!==e);let n=r.reduce((a,o)=>a+o.sizeBytes,0);for(const a of r.sort((o,l)=>o.lastAccessedAt-l.lastAccessedAt)){if(n+t<=this.options.maxTotalBytes)return;await this.deleteEntry(a.cacheKey,i),n-=a.sizeBytes}}async deleteEntry(e,t){await Promise.all([t.delete(e),this.metadataStore.delete(e)]),this.emitEvent("resource-cache.cleanup.deleted",{cacheKey:e})}blobResult(e,t,i,r){const n=this.objectUrl.createObjectURL(t);return this.objectUrls.add(n),{url:n,cacheStatus:r,sourceUrl:e,sizeBytes:i.sizeBytes,objectUrl:n}}emitEvent(e,t){var i;(i=this.onEvent)==null||i.call(this,e,t)}}function Lu(s){return!!s&&typeof s.then=="function"}class br{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(a=>(this.durationCache.set(e,{value:a,promise:null}),a)).catch(a=>{throw this.durationCache.delete(e),a});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(a=>(this.thumbnailCache.set(e,{value:a,promise:null}),a)).catch(a=>{throw this.thumbnailCache.delete(e),a});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(!Lu(n))return this.previewSourceCache.set(e,{value:n,promise:null,resolved:!0}),n;const a=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:a,resolved:!1}),a}primePreviewSource(e,t){this.previewSourceCache.set(e,{value:t,promise:null,resolved:!0})}}class Ps{constructor(e,t=Wi){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 Ou{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[a]=this.tracks.splice(i,1);a&&e.push(a)}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 Bu(s){return s==="text"?"文本":s==="video"?"视频":"音频"}function Ai(s){return s==="text"?0:s==="video"?1:2}class Ua{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 a=t||`${Bu(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:a,order:this.tracks.length,role:o,clips:[]};return this.insertTrack(l,i,r),F.debugLazy("TrackManager",()=>`创建轨道: ${a}`,()=>({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?(F.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(F.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),F.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,F.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(F.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),F.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(F.warn("TrackManager",`轨道不存在: ${e}`),!1)}recalculateOrder(){this.tracks.forEach((e,t)=>{e.order=t})}insertTrack(e,t,i){const r=this.tracks.findIndex(a=>a.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 a=this.tracks.findIndex(o=>o.id===i);if(a!==-1){this.tracks.splice(a+(n==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(n==="top_of_type_region"){const a=this.tracks.findIndex(l=>l.type===e.type);if(a!==-1){this.tracks.splice(a,0,e),this.recalculateOrder();return}const o=this.tracks.findIndex(l=>Ai(l.type)>Ai(e.type));if(o!==-1){this.tracks.splice(o,0,e),this.recalculateOrder();return}}if(n==="bottom_of_type_region"){const a=this.tracks.reduce((l,c,h)=>c.type===e.type?h:l,-1);if(a!==-1){this.tracks.splice(a+1,0,e),this.recalculateOrder();return}const o=this.tracks.reduce((l,c,h)=>Ai(c.type)<=Ai(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,F.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(F.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,F.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}class Fu{constructor(){p(this,"container",null)}mount(e,t){return this.container=e,ci(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&&ci(null,this.container),this.container=null}renderTemplate(e){const{theme:t,timeScaleHeight:i,leftPanelWidth:r,scrollbarSize:n}=e,a=["position:relative","min-width:0","min-height:0","max-width:100%","box-sizing:border-box",`background:${t.background}`,`color:${t.clipName}`].join(";");return j`
|
|
662
|
-
<div
|
|
663
|
-
class="timeline-manager-header-corner"
|
|
664
|
-
data-layout-role="header-corner"
|
|
665
|
-
style=${`${a};grid-column:1;grid-row:1;border-bottom:1px solid ${t.border};`}
|
|
666
|
-
></div>
|
|
667
|
-
<div
|
|
668
|
-
class="timeline-manager-header-viewport"
|
|
669
|
-
data-layout-role="header-viewport"
|
|
670
|
-
style=${`${a};grid-column:2;grid-row:1;border-bottom:1px solid ${t.border};overflow:hidden;`}
|
|
671
|
-
>
|
|
672
|
-
<div
|
|
673
|
-
class="timeline-manager-header-canvas-host"
|
|
674
|
-
data-layout-role="header-canvas-host"
|
|
675
|
-
style="width:100%;height:100%;"
|
|
676
|
-
></div>
|
|
677
|
-
</div>
|
|
678
|
-
<div
|
|
679
|
-
class="timeline-manager-track-info-viewport"
|
|
680
|
-
data-layout-role="track-info-viewport"
|
|
681
|
-
style=${`${a};grid-column:1;grid-row:2;overflow:hidden;border-right:1px solid ${t.border};`}
|
|
682
|
-
></div>
|
|
683
|
-
<div
|
|
684
|
-
class="timeline-manager-scroll-viewport timeline-manager-body-viewport"
|
|
685
|
-
data-layout-role="body-viewport"
|
|
686
|
-
style=${`${a};grid-column:2;grid-row:2;overflow-x:hidden;overflow-y:auto;`}
|
|
687
|
-
>
|
|
688
|
-
<div
|
|
689
|
-
class="timeline-manager-body-canvas-host"
|
|
690
|
-
data-layout-role="body-canvas-host"
|
|
691
|
-
style=${`width:100%;height:100%;position:relative;background:${t.background};`}
|
|
692
|
-
></div>
|
|
693
|
-
</div>
|
|
694
|
-
<div
|
|
695
|
-
class="timeline-manager-v-scrollbar-canvas-host"
|
|
696
|
-
data-layout-role="vertical-scrollbar-host"
|
|
697
|
-
style=${["position:absolute",`top:${i}px`,"right:0","bottom:0",`width:${n}px`,"z-index:5"].join(";")}
|
|
698
|
-
></div>
|
|
699
|
-
<div
|
|
700
|
-
class="timeline-manager-h-scrollbar-canvas-host"
|
|
701
|
-
data-layout-role="horizontal-scrollbar-host"
|
|
702
|
-
style=${["position:absolute",`left:${r}px`,"right:0","bottom:0",`height:${n}px`,"z-index:4"].join(";")}
|
|
703
|
-
></div>
|
|
704
|
-
<div
|
|
705
|
-
class="timeline-manager-playhead-overlay"
|
|
706
|
-
data-layout-role="playhead-overlay"
|
|
707
|
-
style=${["position:absolute",`left:${r}px`,"top:0","right:0","bottom:0","pointer-events:none","z-index:3"].join(";")}
|
|
708
|
-
></div>
|
|
709
|
-
`}requireElement(e,t){const i=e.querySelector(t);if(!i)throw new Error(`Missing timeline manager layout element: ${t}`);return i}}const Wa=200,Wr=8,_s="timeline-manager-managed-layout-styles";function Gu(){if(typeof document>"u"||document.getElementById(_s))return;const s=document.createElement("style");s.id=_s,s.textContent=`
|
|
710
|
-
.timeline-manager-root {
|
|
711
|
-
position: relative;
|
|
712
|
-
overflow: hidden;
|
|
713
|
-
display: grid;
|
|
714
|
-
width: 100%;
|
|
715
|
-
max-width: 100%;
|
|
716
|
-
min-width: 0;
|
|
717
|
-
height: 100%;
|
|
718
|
-
box-sizing: border-box;
|
|
719
|
-
}
|
|
720
|
-
|
|
721
|
-
.timeline-manager-scroll-viewport {
|
|
722
|
-
overflow: auto;
|
|
723
|
-
scrollbar-width: none;
|
|
724
|
-
-ms-overflow-style: none;
|
|
725
|
-
min-width: 0;
|
|
726
|
-
max-width: 100%;
|
|
727
|
-
box-sizing: border-box;
|
|
728
|
-
}
|
|
729
|
-
|
|
730
|
-
.timeline-manager-scroll-viewport::-webkit-scrollbar {
|
|
731
|
-
width: 0;
|
|
732
|
-
height: 0;
|
|
733
|
-
display: none;
|
|
734
|
-
}
|
|
735
|
-
`,document.head.appendChild(s)}function Hu(s,e){Gu();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??Wa,scrollbarSize:e.scrollbarSize??Wr};return new Fu().mount(s,t)}class Nu{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 Ya{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 $u{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 As{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new Ya,this.playbackStore=new Nu({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new $u({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 zu{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||Re.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Fi(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=Y.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=Y.timeToPixels(e.startTime,this.config.zoom),r=Y.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,n=this.stage.width(),a=r<=n?Math.max(0,t-(n-r)/2):Math.max(0,t);this.setScrollLeft(a)}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=Qi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(er({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 Y.pixelsToTime(e-Te+this.scrollLeft,this.config.zoom)}timeToPixel(e){return Y.timeToPixels(e,this.config.zoom)-this.scrollLeft+Te}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=de.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=Y.pixelsToTime(t,this.config.zoom),n=Y.pixelsToTime(i,this.config.zoom),a=Y.msToSeconds(r),o=Y.msToSeconds(n),{majorStep:l,minorStep:c}=Y.getTickConfig(this.config.zoom),h=Y.generateVisibleTicks(a-10,o+10,l,c);for(const d of h){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&de.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,Y.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const X=class X{constructor(e,t,i,r,n,a,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),a=typeof n=="number"?n:this.scrollLeft;if(this.scrollLeft=Math.max(0,a),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=a,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(X.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${X.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=`${X.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=Qi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(er({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,r=Y.pixelsToTime(i-Te+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(X.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=X.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=Y.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+Te,t=e>=0&&e<=this.container.clientWidth,i=Math.max(X.HANDLE_HEIGHT+X.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 ${X.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=cn.grip,i=Math.max(X.HANDLE_HEIGHT,e-X.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i))}createHandleShadowPath(){const e=document.createElementNS(X.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",cn.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(X.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(X.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(X.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(X.VISUAL_WIDTH-X.LINE_WIDTH)/2}`),t.setAttribute("y",`${X.HANDLE_LINE_START}`),t.setAttribute("width",`${X.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-X.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e){const t=document.createElementNS(X.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-end-cap"),t.setAttribute("x","3"),t.setAttribute("y",`${e}`),t.setAttribute("width",`${X.END_CAP_WIDTH}`),t.setAttribute("height",`${X.END_CAP_HEIGHT}`),t.setAttribute("rx","1.5"),t.setAttribute("fill","#ffffff"),t}};p(X,"SVG_NS","http://www.w3.org/2000/svg"),p(X,"VISUAL_WIDTH",14),p(X,"HANDLE_HEIGHT",16),p(X,"HANDLE_LINE_START",13),p(X,"LINE_WIDTH",1),p(X,"LINE_HIT_WIDTH",12),p(X,"END_CAP_WIDTH",8),p(X,"END_CAP_HEIGHT",1),p(X,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(X,"AUTO_SCROLL_MAX_SPEED",18);let Yr=X;class Is{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 K.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new K.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=de.createRect(0,0,0,0,It.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||It.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||It.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=Qi({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(er({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),a=Math.max(1,r-n),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/a*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),a=Math.max(1,r-n),o=Math.max(0,Math.min(r,i-this.leadingInset)),l=Math.max(0,Math.min(a,o-n/2)),c=this.getMaxScrollOffset(),h=a<=0?0:l/a*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||It.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||It.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),a=this.leadingInset+this.getThumbPosition(r,n);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(a),this.thumbRect.y(0),this.thumbRect.width(n),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(a),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 Es{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 Vu{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 Ha({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:fe.backgroundColor,borderColor:e.border||fe.borderColor,textColor:e.clipName||fe.textColor,labelColor:e.timeText||fe.labelColor,inputBackground:e.trackBackground||fe.inputBackground,inputBorder:e.trackBorder||fe.inputBorder,inputFocusBorder:fe.inputFocusBorder,buttonBackground:e.clipBackground||fe.buttonBackground,buttonBorder:e.clipBorder||fe.buttonBorder,buttonActiveBackground:fe.buttonActiveBackground,buttonActiveBorder:e.clipSelectedBorder||fe.buttonActiveBorder,buttonActiveText:fe.buttonActiveText}}}const Uu="@linker-design-plus/timeline-track",Wu="2.0.20",Nt={name:Uu,version:Wu},Yu=1,Xu=2,qu=120,ju=250;function Rs(s){return s==null?s:JSON.parse(JSON.stringify(s))}function Ku(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class Zu{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 br);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",{...De});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 Es);p(this,"pendingDraftData",null);p(this,"selectionStore",new Ya);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);p(this,"splitOperationDepth",0);p(this,"diagnostics");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,"lastPreviewSyncSignature",null);p(this,"lastSteadyPlaybackPreviewSyncAt",0);p(this,"previewSyncInteractionMode",null);p(this,"resourceCacheManager");this.config={duration:e.duration||36e5,zoom:e.zoom||Re.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:Fi(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,resourceCache:e.resourceCache,textPreviewFont:e.textPreviewFont??null,keyboardShortcuts:e.keyboardShortcuts},this.diagnostics=new wa(this.config.diagnostics),this.resourceCacheManager=this.config.resourceCache?new Du({options:this.config.resourceCache,onEvent:(t,i)=>{this.emitDiagnostic({...this.buildPreviewDiagnosticsContext(),severity:t.endsWith(".failed")||t.endsWith(".fallback")?"warn":"info",category:"resource",eventName:t,message:t,extra:i})}}):null,this.diagnostics.startSession({packageName:Nt.name,packageVersion:Nt.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 ou,this.eventDispatcher=new vs({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 zr(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new ds(this.history),this.timelineHistoryExecutor=new hs({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 Ua,this.timelineStore=new As({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new cs(this.timelineStore),this.timelinePresentationAdapter=new bs,this.timelineTrackBridge=new Ps({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()}}getTimelineStore(){var e,t,i,r,n;if(!this.timelineStore){const a=((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)||Re.MEDIUM,h=((n=this.config)==null?void 0:n.duration)||36e5;this.timelineStore=new As({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new cs(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Ou(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new bs),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Ps({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 $d),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 Wd({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,this.buildPreviewIndicatorState(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 zd({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Od({callbacks:t,diagnostics:this.diagnostics,getDiagnosticsContext:()=>this.buildPreviewDiagnosticsContext(),previewSourceResolver:this.config.previewSourceResolver,resourceCacheManager:this.resourceCacheManager,textPreviewFont:this.config.textPreviewFont,sourceMediaRegistry:this.sourceMediaRegistry}),resolveConfiguredBackend:e=>e||Bd(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=Xe(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onPreviewClipSelect:t=>{this.isActivePreviewCallbackToken(e)&&this.selectClip(t)},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onTextFontSizeCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextFontSize(t,i)},onTextRotationCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextRotation(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 vs({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 zr(()=>{},()=>{})),this.timelineHistoryRecorder=new ds(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new hs({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:Re.MEDIUM,currentTime:0,playState:"paused",theme:Fi(),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,a;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()),(a=this.verticalScrollbar)==null||a.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 Y.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)}hasTimelineVideoClip(e=this.getCurrentTimeState()){return this.buildPlaybackPlan(e).firstVideoClip!==null}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((a,o)=>a.order-o.order);let i=null,r=null,n=Number.POSITIVE_INFINITY;for(const a of t){if(a.type!=="video")continue;const o=[...a.clips].sort((l,c)=>l.startTime-c.startTime);for(const l of o){const c={trackId:a.id,trackType:a.type,trackOrder:a.order,clip:l,mediaTime:l.startTimeAtSource,muted:(a.isMuted??!1)||(l.isMuted??!1),kind:a.type,hasVisual:!0,hasAudio:!0};i||(i=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)}buildPreviewSyncSignature(e){var i,r;const t=n=>[n.trackId,n.clip.id,n.trackType,n.trackOrder,n.clip.startTime,n.clip.endTime,n.clip.startTimeAtSource,n.muted?1:0,n.clip.volume??""].join(":");return JSON.stringify({active:e.playbackPlan.activeClips.map(t),next:e.playbackPlan.nextClips.map(t),firstVideoClipId:((i=e.playbackPlan.firstVideoClip)==null?void 0:i.clip.id)??null,autoAspectRatioClipId:((r=e.autoAspectRatioClip)==null?void 0:r.clip.id)??null,previewAspectRatio:e.previewAspectRatio,playState:e.targetPlayState,speed:e.speed,interactionMode:e.interactionMode,primarySelectedClipId:e.primarySelectedClipId})}shouldSkipSteadyPlaybackPreviewSync(e,t,i){return t!=="playing"||i!=="steady"||this.pendingPreviewState||this.previewBuffering||this.lastPreviewSyncedPlayState!=="playing"||this.lastPreviewSyncSignature!==e?!1:Date.now()-this.lastSteadyPlaybackPreviewSyncAt<ju}syncPreviewSession(e){var h,d,u,f;if(!((h=this.previewSession)!=null&&h.hasPreview())){this.previewSyncInteractionMode=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0;return}const t=this.buildPlaybackPlan();this.previewActiveClipIds=t.activeClips.map(g=>g.clip.id);const i=this.getAutoAspectRatioClip(),r=Xe(this.previewAspectRatio),n=e??this.getPlayStateState(),a=this.getSpeedState(),o=this.previewSyncInteractionMode??((d=this.pendingPreviewState)==null?void 0:d.mode)??"steady",l=this.getPrimarySelectedClipId(),c=this.buildPreviewSyncSignature({playbackPlan:t,autoAspectRatioClip:i,previewAspectRatio:r,targetPlayState:n,speed:a,interactionMode:o,primarySelectedClipId:l});if(this.shouldSkipSteadyPlaybackPreviewSync(c,n,o)){this.previewSyncInteractionMode=null;return}this.previewAspectRatio=r,this.previewSession.applyAspectRatio(r),this.previewSession.sync({...t,autoAspectRatioClip:i,currentTime:this.getCurrentTimeState(),playState:n,speed:a,interactionMode:o,primarySelectedClipId:l,...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),this.previewSyncInteractionMode=null,(f=(u=this.previewSession).setPendingState)==null||f.call(u,this.buildPreviewPendingState()),this.lastPreviewSyncedPlayState=n,this.lastPreviewSyncSignature=c,this.lastSteadyPlaybackPreviewSyncAt=n==="playing"&&o==="steady"?Date.now():0}syncPreviewPlaybackStateIfNeeded(e){this.lastPreviewSyncedPlayState!==e&&this.syncPreviewSession(e)}beginPendingPreview(e,t="seek"){var r,n,a,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;if(!this.hasTimelineVideoClip(e)){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();return}(t!=="scrub"||((n=this.pendingPreviewState)==null?void 0:n.mode)!=="scrub")&&this.refreshPlaybackAttempt(t);const i=((a=this.pendingPreviewState)==null?void 0:a.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.buildPreviewIndicatorState(this.getPreviewStateController().buildPreviewPendingState())}buildPreviewIndicatorState(e){const t=Number.isFinite(this.sourceLoadingCount)?Math.max(0,this.sourceLoadingCount):0;return t<=0?e:e?{...e,loadingPending:e.loadingPending+t}:{mode:"seek",targetTime:this.getCurrentTimeState(),loadingPending:t,isBuffering:!1,errorMessage:null}}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState(),this.previewActiveClipIds=[],this.lastPreviewSyncedPlayState=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0,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(Xe(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,a,o,l,c;if(this.isInitialized){F.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=Hu(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Wa,scrollbarSize:Wr}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(r=(i=this.layout.bodyCanvasHost).addEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(a=(n=this.rootContainer)==null?void 0:n.addEventListener)==null||a.call(n,"wheel",this.rootWheelListener,{passive:!1}),this.initKeyboardShortcuts(),this.headerStage=new K.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new K.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new K.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new K.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new K.Layer({name:"trackLayer"}),this.dragOverlayLayer=new K.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new K.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new K.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 zu(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new Yr(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 Is({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:Te,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Is({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.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=>{F.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,n){var d,u,f;if(!this.trackLayer)return F.error("TimelineManager","Track layer not initialized"),"";const a=this.trackManager.createTrack(e,t,i,r,n),o=a.id,l=_e(e),c=this.calculateTrackY(o),h=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:o,clips:[],role:a.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(),(f=this.stage)==null||f.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),o}removeTrack(e){var r,n,a,o;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return F.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return F.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((a=(n=t.getTrackGroup)==null?void 0:n.call(t))==null||a.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()}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 Ht(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return ls(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=jh(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 a of e){const o=(t=a.getId)==null?void 0:t.call(a);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(r=(i=a.getTrackGroup)==null?void 0:i.call(a))==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,a,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?(a=t.showClipDropPreview)==null||a.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=de.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 a;return(a=n.clearClipDropPreview)==null?void 0:a.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"),a=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=Ht(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+_e(c.type)}}if(t==="top_of_type_region"&&a)return Ht(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Ht(r,o.id,this.getTrackContentTopOffset())+_e(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():ls(r,this.getTrackContentTopOffset());const l=Ht(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+_e(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()),a=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(a),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 K.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=Y.pixelsToTime(e-Te+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=de.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===Yu)return e*16;if(t===Xu){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(Re.MIN,Math.min(Re.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){const e=this.getClips();if(e.length>0&&this.getCurrentTime()>=Vr(e)){if(this.setCurrentTime(0),!this.canPlay)return}else{F.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"))},qu);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 a=this.timeline.getScrollLeft(),o=Y.timeToPixels(i,t),c=Y.timeToPixels(i,n)-o+a;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=Y.pixelsToTime(t-Te+r,i),a=this.getTimelineCommands().setZoom(e);if(!a.changed)return;const o=a.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const c=Y.timeToPixels(n,o)-(t-Te);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 a=!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;a=!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}),F.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return F.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=a,a||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 a of e){const o=n?this.resolveBatchClipConfig(a,i,r):a,l=await this.addClipInternal(o);if(t.push(l),!n||a.startTime!==void 0||a.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 a=i.get(n)??this.getTrackTimelineExtentById(n);return{...e,trackId:n,startTime:a}}resolveBatchAppendTrackId(e){const t=this.getTracksSortedByOrder(),i=t.find(a=>{var o,l;return((o=a.getRole)==null?void 0:o.call(a))==="primary"&&((l=a.getTrackType)==null?void 0:l.call(a))===e});if(i)return i.getId();const r=t.find(a=>{var o;return((o=a.getTrackType)==null?void 0:o.call(a))===e});return r?r.getId():this.createTrack(e)||null}getTrackTimelineExtentById(e){const t=this.getTrackCollection().findById(e);return t?Ur(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??"",a=e.duration??(r?3e3:0),o=e.name??(r?"文本":`${i}_${Date.now()}`);if(!r&&(!e.name||a<=0))throw new Error(`addClip requires name and duration for ${i} clips`);const l=r?0:e.startTimeAtSource||0,c=r?a:e.endTimeAtSource||l+a;let h=r?a:e.sourceDuration;if(!h)try{h=await Y.getVideoDuration(n,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(v){F.error("TimelineManager","Failed to get video duration:",{error:v}),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)}`,f=Kr({id:u,type:i,externalId:e.externalId,src:n,name:o,isMuted:e.isMuted??!1,startTime:t,duration:a,startTimeAtSource:l,endTimeAtSource:c,sourceDuration:h,endTime:t+a,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?Me(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});if(F.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:f.id,type:f.type,startTime:f.startTime,duration:f.duration})),e.trackId){const v=this.getTrackCollection().findById(e.trackId);if(v)return this.registerPreviewAutoAspectRatioClip(f),(C=v.addClip)==null||C.call(v,f),Oi({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(f)},applyEffects:()=>Ue({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(f),f.id}const g=this.getTimelineCommands().planTrackPlacement(f,this.getTracksSortedByOrder()),y=this.getTrackCollection(),S=nu({clip:f,placement:g,trackCollection:y,createTrack:this.createTrack.bind(this)});return Oi({applied:S,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(f)},applyEffects:()=>Ue({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(f),f.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),Oi({applied:Cs(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:()=>Ue({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 a=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);a.exists&&(r=Cs(this.getTrackCollection(),a,n)||r)}}),r?(Pi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Ue({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)}Ue({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)}),Ue({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)}),Ue({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var n,a,o;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(wt(e.mode)&&t===De.width&&i===De.height){const l=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,c=(a=l==null?void 0:l.style)==null?void 0:a.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=jr({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 a of n.clips)if(a.type==="video"){if(!t||!i){t=n,i=a;continue}if(a.startTime<i.startTime){t=n,i=a;continue}a.startTime===i.startTime&&n.order<t.order&&(t=n,i=a)}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,a)=>n.startTime-a.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){F.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 a=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&&a.has(u)&&(u=a.get(u));let f=d.separatedFromVideoClipId;f&&a.has(f)&&(f=a.get(f));const g={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:f,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(g);a.set(d.id,y)}catch(u){o.push({clipId:d.id,error:u}),F.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 a=n.role==="primary"&&!i?"primary":"normal";a==="primary"&&(i=!0),t.set(n.id,a)}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 Nt.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,a=n-Te*2;F.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:a}));const o=Math.min(a/r,Re.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;nd({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){sd(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{F.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){const e=this.getClips(),t=this.getCurrentTime(),i=ad(e,t),r=this.canPlay;this.canPlay=od({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:Vr(e)||1,setCanPlay:n=>{this.canPlay=n},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:n=>{this.emitEvent("can_play_change",{canPlay:n})}}),r!==this.canPlay&&F.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 a=this.normalizeGeneratedAudioDuration(r.duration);this.updateClip(e,{src:r.audioSrc,name:this.buildGeneratedAudioClipName(r.voiceName),textContent:i,duration:a,startTimeAtSource:0,endTimeAtSource:a,sourceDuration:a,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(a=>!i.has(a.id));return t.some(a=>{const o=a.startTime+a.duration;return n.some(l=>l.id!==a.id&&a.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 a=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(a==null?void 0:a.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 a=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=a.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:[]},a.set(l,h)}h.sourceClipIds.push(o.sourceClipId),h.clipIds.push(c)}),Array.from(a.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(a=>[a.sourceClipId,a]));return e.sourceClipIds.map(a=>{const o=n.get(a),l=i.get(a);return!o||!l?null:{id:l,startTime:r+(o.clip.startTime-t.minStartTime),duration:o.clip.duration}}).filter(a=>a!==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 a,o;return(((a=r.trackSnapshot)==null?void 0:a.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 a=[...this.getResolvedTracksSnapshot()].filter(T=>{var w;return T.type===((w=e[0])==null?void 0:w.type)}).sort((T,w)=>T.order-w.order);if(a.length===0){const T=this.createTrack(e[0].type);T&&n.set(e[0].key,T);for(let w=1;w<e.length;w+=1){const _=this.createTrack(e[w].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");_&&n.set(e[w].key,_)}return n}const o=new Set(e.flatMap(T=>T.clipIds)),l=e.map(T=>{const w=this.buildClipboardPasteGroupPlacementClips(T,t,i,r);if(w.length===0)return null;const _=this.resolvePreferredTrackIndexForPasteGroup(T,a,Math.min(T.sourceOrder,Math.max(a.length-1,0)));return{...T,preferredTrackIndex:_,clips:w}}).filter(T=>T!==null);if(l.length===0)return n;const c=l.map(T=>T.preferredTrackIndex),h=Math.min(...c),d=a.length,u=-l.length;let f=null,g=Number.POSITIVE_INFINITY;for(let T=u;T<=d;T+=1){let w=!0,_=0,x=0;for(let L=0;L<l.length;L+=1){const k=l[L];if(!k)continue;const M=T+L;if(_+=Math.abs(M-k.preferredTrackIndex),M<0||M>=a.length){x+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[M].id,k.clips,o)){w=!1;break}}w&&(_+=x*.1,_+=Math.abs(T-h)*.001,_<g&&(g=_,f=T))}if(f===null)return n;const y=Math.max(0,-f),S=Math.max(0,f+l.length-a.length);y>0&&this.createTracksForTypeBoundary(l[0].type,y,"before"),S>0&&this.createTracksForTypeBoundary(l[0].type,S,"after");const C=[...this.getResolvedTracksSnapshot()].filter(T=>{var w;return T.type===((w=l[0])==null?void 0:w.type)}).sort((T,w)=>T.order-w.order),v=f+y;return l.forEach((T,w)=>{const _=C[v+w];_&&n.set(T.key,_.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 a=new Map;return n.forEach(o=>{this.resolveClipboardPasteTypeGroupAssignments(o,e,t,i).forEach((c,h)=>{a.set(h,c)})}),a}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"})),a=await i(n),o=new Map(a.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),f=new Map(u.map(S=>[S.requestId,S]));e.setPreferredTab("voice");const g=[];for(const S of d){const C=f.get(S.requestId);if(!C)continue;const v=c.find(x=>x.id===S.sourceTextClipId);if(!v)continue;const T=this.normalizeGeneratedAudioDuration(C.duration),w=v.textContent??v.name??"";this.syncTextClipDurationToAudio(v.id,T);const _=await this.addClip({type:"audio",src:C.audioSrc,name:this.buildGeneratedAudioClipName(C.voiceName),textContent:w,startTime:v.startTime,duration:T,startTimeAtSource:0,endTimeAtSource:T,sourceDuration:T,ttsSourceTextClipId:v.id,ttsVoiceId:C.voiceId,ttsVoiceName:C.voiceName,ttsFollowTextUpdates:r});g.push(_)}if(g.length===0)throw new Error("生成音频失败:未返回音频结果");if(g.length===1){this.scrollToClip(g[0],{selectClip:!0,setCurrentTime:!0});return}const y=g[0]??null;this.scrollToClip(y,{setCurrentTime:!0}),this.setSelection(g,{preferredPrimaryClipId:y});return}if(t.type!=="audio"||!t.ttsSourceTextClipId)return;const a=this.findClipById(t.ttsSourceTextClipId);if(!a||a.type!=="text")throw new Error("未找到配音关联的文本片段");const o=`replace:${t.id}:${i.id}:${Date.now()}`,[l]=await n([{requestId:o,sourceTextClipId:a.id,targetAudioClipId:t.id,text:a.textContent??a.name??"",voiceId:i.id,followTextUpdates:r,mode:"replace"}]);if(!l)throw new Error("替换音色失败:未返回音频结果");e.setPreferredTab("voice"),this.applyGeneratedAudioClipResult(t.id,a.id,a.textContent??a.name??"",l,r),this.relocateClipIfNeeded(t.id),this.syncTextClipDurationToAudio(a.id,l.duration),this.handleClipChange()}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{F.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){F.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 br.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return br.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){hd({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=ld(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),F.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){F.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){F.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=iu({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){var e,t;this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount}),(t=(e=this.previewSession)==null?void 0:e.setPendingState)==null||t.call(e,this.buildPreviewPendingState())}endSourceLoading(){var e,t;this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount}),(t=(e=this.previewSession)==null?void 0:e.setPendingState)==null||t.call(e,this.buildPreviewPendingState())}handleClipOverlap(e,t,i){var h,d,u,f;F.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const r=this.getTrackCollection();if(!r.findById(t))return;const n=e.type,a=this.trackManager.getTracksByType(n).length+1,o=`${Ku(n)}轨道 ${a}`,l=this.createTrack(n,o);if(!l)return;const c=((d=(h=r.findById(l))==null?void 0:h.getId)==null?void 0:d.call(h))||((f=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:f.call(u))||l;this.moveClipToTrackWithHistorySnapshot(e.id,c,i??null,e),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){F.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"?(F.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(F.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()}getRenderedHeight(){return this.getTimeScaleHeight()+this.calculateTotalHeight()+Wr}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(),a=this.getCurrentTime(),o=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const h of e.items){const d=this.buildClipboardPasteClipConfig(h,a,t),u=h.sourceTrackId??`clipboard-orphan:${h.sourceClipId}`,f=i.get(u)??this.resolveClipboardPasteTrackId(h,d,i),g=t.get(h.sourceClipId);if(!g)continue;const y=await this.addClipInternal({...d,id:g,...f?{trackId:f}:{}});(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(a=>{const o=this.getTimelineCommands().prepareRemoveClip(a,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(a=>a!==null);this.clearSelection();const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const a of t)this.removeClip(a)}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:Rs(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,a=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:Rs(r.style),visualTransform:r.visualTransform?{...r.visualTransform}:void 0,separatedAudioClipId:n,separatedFromVideoClipId:a,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 a=this.getTimelineCommands().planTrackPlacement({type:t.type||"video",startTime:t.startTime??this.getCurrentTime(),duration:t.duration??0},this.getTracksSortedByOrder()),o=a.status==="use_existing_track"?a.trackId:this.createTrack(a.trackType,void 0,a.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(a=>a.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=Xe({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 Vu,r=t.generateVoiceBatch,n=r,a=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=>{F.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:u,clipId:c})})},onGenerateVoice:async(c,h,d)=>{if(!a)throw new Error("未配置音色生成回调");await this.handleVoiceGenerateAction(i,c,h,d,a)}});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 Xe(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:Nt.name,packageVersion:Nt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=Xe({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={...De},(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}pausePlaybackForAudioSeparation(){var t,i,r;(((i=(t=this.timelineStore)==null?void 0:t.getPlayState)==null?void 0:i.call(t))??((r=this.config)==null?void 0:r.playState))==="playing"&&this.pause()}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 a=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&&a>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;this.pausePlaybackForAudioSeparation();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 a=this.getClips().find(c=>c.id===e),o=this.getClips().find(c=>c.id===n)??null,l=this.resolveTrackIdByClipId(n);return a?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,a,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,a=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=a}const o=this.getClips().find(l=>l.id===e);return o?(a||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=[],a=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{if(e==="restore")for(const o of i){const l=this.getClips().find(g=>g.id===o.id);if(!l||l.type!=="video")continue;const c=l.separatedAudioClipId??null,h=c?this.getClips().find(g=>g.id===c)??null:null,d=c?this.resolveTrackIdByClipId(c):null,u=this.restoreClipAudio(o.id),f=this.getClips().find(g=>g.id===o.id);!u||!f||n.push(r.createRestoreClipAudioAction({...l},{...f},h?{...h}:null,d))}else for(const o of i){const l=this.getClips().find(f=>f.id===o.id);if(!l||l.type!=="video")continue;const c=await this.separateClipAudio(o.id),h=this.getClips().find(f=>f.id===o.id),d=c?this.getClips().find(f=>f.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=a}return a||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 F.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(n.status==="noop")return F.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(n.status==="missing_target_track")return F.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(n.status==="track_type_mismatch")return F.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var g,y,S;return{targetTrackType:(y=(g=this.getTrackCollection().findById(t))==null?void 0:g.getTrackType)==null?void 0:y.call(g),clipType:(S=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:S.clip.type}}),!1;if(n.status!=="ready")return!1;const{sourceTrackId:a,targetTrackId:o}=n,l=i?{...i}:{...n.clip},c=r?{...r}:{...n.clip},h=this.cloneTrackSnapshot(a),d=this.cloneTrackSnapshot(o),u=su({command:{...n,clip:c},trackCollection:this.getTrackCollection()}),f=this.getClips().find(g=>g.id===e)??null;return cd({applied:u,clipId:e,sourceTrackId:a,targetTrackId:o,clipBefore:l,clipAfter:f??l,sourceTrackSnapshot:h,targetTrackSnapshot:d,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>au({notifySelectionChange:this.notifySelectionChange.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),batchDraw:()=>{var g;(g=this.stage)==null||g.batchDraw()},syncPreviewSession:this.syncPreviewSession.bind(this)})})?(this.clearAllTrackDropPreviews(),!0):!1}getTrackTotalDuration(){return ys(this.getClips())}async getResourceCacheStats(){return this.resourceCacheManager?{enabled:!0,...await this.resourceCacheManager.getStats()}:{enabled:!1,entryCount:0,totalBytes:0,maxTotalBytes:0}}async cleanupResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.cleanupExpired())}async clearResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.clear())}destroy(){var e,t,i,r,n,a,o,l,c,h,d,u;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPreviewBufferingSuspendTimeout(),this.clearPendingPreviewState(),(e=this.resourceCacheManager)==null||e.cleanupExpired().catch(()=>{}),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(t=this.layout)==null||t.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(n=(i=this.layout)==null?void 0:(r=i.bodyCanvasHost).removeEventListener)==null||n.call(r,"click",this.bodyCanvasHostClickListener),(o=(a=this.rootContainer)==null?void 0:a.removeEventListener)==null||o.call(a,"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 Es),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new eu({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(a=>[a.id,a])),r=new Set,n=t.filter(a=>a.externalId===e).map(a=>a.id);for(let a=0;a<n.length;a+=1){const o=n[a];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(a=>r.has(a.id)).map(a=>a.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),a=n==null?void 0:n.clip;if(a&&e>=a.startTime&&e<a.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 a=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,a++)}for(const h of i){const d=this.getTrackCollection().findById(h);(c=d==null?void 0:d.setTrackStackOrder)==null||c.call(d,a++)}}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 a=i.get(n.trackId);a?a.push(r):i.set(n.trackId,[r])}i.forEach((r,n)=>{var o;const a=this.getTrackCollection().findById(n);(o=a==null?void 0:a.setClipsDragOverlayActive)==null||o.call(a,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 a=this.findTrackByClipId(n),o=((r=a==null?void 0:a.getId)==null?void 0:r.call(a))??this.resolveTrackIdByClipId(n),l=a==null?void 0:a.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 a=this.getTrackCollection().findById(n.trackId);if(!(a!=null&&a.updateClipPosition))continue;const o=Math.max(0,n.clip.startTime+t.deltaTime);a.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 a=this.resolveTrackIndexDelta(i.trackId,n.targetTrackId,i.clip.type);if(a===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,a,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 a=n.targetTrackId;if(!a)return!1;const o=this.resolveTrackIndexDelta(i.trackId,a,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?a: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),a=r.indexOf(t);return n===-1||a===-1?null:a-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,a=this.resolveCrossTrackMoveDestination(i,n,e.trackId);return a.status==="blocked"?r:a.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,a=this.resolveCrossTrackPreviewDestination(i,n,e.trackId);return a.status==="existing_track"?a.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 F.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return F.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return F.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:e.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};F.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const a=this.createTrack(n.trackType,void 0,n.insertionPlacement,n.referenceTrackId);return a?{status:"move_to_track",targetTrackId:a}:{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 a=n+i;for(;a<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;r=this.getTrackIdsByType(t),a+=1}for(;a>=r.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;r=this.getTrackIdsByType(t)}return r[a]??null}findTrackIdByRelativeIndex(e,t,i){const r=this.getTrackIdsByType(t),n=r.indexOf(e);if(n===-1)return null;const a=n+i;return a<0||a>=r.length?null:r[a]??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 K.Rect({fill:hn.fill,stroke:hn.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 a;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),(a=this.selectionBoxLayer)==null||a.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,a=e.clientY-r.top;if(this.isPointOnClip(n,a))return;this.isBoxSelecting=!1,this.boxSelectStartX=n,this.boxSelectStartY=a;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,a=e.clientY-r.top,o=Math.abs(n-this.boxSelectStartX),l=Math.abs(a-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,a),d=Math.abs(n-this.boxSelectStartX),u=Math.abs(a-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 n=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);if(!(t<n||t>n+a))for(const o of i.getClips()){const l=me(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Ce(o.duration,this.getZoomState());if(e>=l&&e<=l+c&&t>=n+2&&t<=n+a-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const n=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);for(const o of i.getClips()){const l=me(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Ce(o.duration,this.getZoomState()),h=n+2,d=a-4,u=l+c,f=h+d,g=e.x+e.width,y=e.y+e.height;l<g&&u>e.x&&h<y&&f>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return _e(e.getTrackType())}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Ue({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,f)=>u.order-f.order),a=n.find(u=>u.order>=e.order),o=a?n[n.findIndex(u=>u.id===a.id)-1]??null:n[n.length-1]??null;let l,c;a?(l="before_track",c=a.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,a;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:((a=t[i+1])==null?void 0:a.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 a;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=Ur(e),n=ys(e);if(r!==t){this.lastTrackDuration=r;const o=Ss(r);this.setDurationState(o),(a=this.timeline)==null||a.setDuration(o),this.updateViewportLayout()}n!==i&&(this.lastReportedTrackDuration=n,this.emitEvent("track_duration_change",{duration:n})),e.length===0&&this.getCurrentTimeState()!==0&&this.setCurrentTime(0),!(r===t&&n===i)&&F.debugLazy("TimelineManager",()=>`Track duration changed: total=${n}ms, extent=${r}ms, timeline=${Ss(r)}ms`)}resolveSelectedClipSnapshot(){return Va({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 tu({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(a=>a.id===e);if(!i||i.type!=="video"&&i.type!=="text")return;const r=ke(i.visualTransform),n=ke(t);on(r,n)||this.updateClip(e,{visualTransform:n})}commitPreviewTextFontSize(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=Me(i.textStyle),n=Math.max(5,Math.min(300,Math.round(t)));r.fontSize!==n&&this.updateClip(e,{textStyle:{...r,fontSize:n}})}commitPreviewTextRotation(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=Me(i.textStyle),n=Math.round(t);r.rotation!==n&&this.updateClip(e,{textStyle:{...r,rotation:n}})}clearAllTracksAndClips(){var t,i,r,n;const e=this.getTracks();for(const a of e){const o=this.getTrackCollection().findById(a.id);if(o){const l=[...o.getClips()];for(const c of l)(t=o.removeClip)==null||t.call(o,c.id)}}for(const a of e){const o=a.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=Xr;exports.CLIP_LAYER=Ka;exports.Clip=Mi;exports.ClipConfigPanel=Ha;exports.DEFAULT_CLIP_VIEW_STATE=Ls;exports.DEFAULT_PREVIEW_ASPECT_RATIO=De;exports.DEFAULT_TEXT_CLIP_STYLE=Ds;exports.DiagnosticsCenter=wa;exports.HistoryManager=zr;exports.MIN_CLIP_LINE_WIDTH=ti;exports.PREVIEW_ASPECT_RATIO_PRESETS=ja;exports.TIMELINE_LEFT_PADDING=Te;exports.TIME_SCALE=Ja;exports.TRACK_HEIGHT=Ii;exports.TimeUtils=Y;exports.TimelineManager=Zu;exports.Track=Wi;exports.TrackInfoPanel=Ga;exports.TrackManager=Ua;exports.ZOOM_ANIMATION=Za;exports.ZOOM_PRESETS=Re;exports.createClipViewState=Os;exports.createClipWithViewState=Kr;exports.defaultDarkTheme=Bi;exports.devConsole=F;exports.isAutoPreviewAspectRatioMode=wt;exports.mergeDiagnosticRuntimeState=ka;exports.normalizePreviewAspectRatio=Xe;exports.normalizePreviewAspectRatioMode=qr;exports.resolveAspectRatioBaselineDimensions=jr;exports.resolveTextClipStyle=Me;exports.resolveTheme=Fi;
|
|
733
|
+
`}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:${I.sliderFillStart}`,`--clip-slider-fill-end:${I.sliderFillEnd}`,`--clip-slider-road:${I.sliderRoad}`,`--clip-slider-thumb-border:${I.sliderThumbBorder}`,`--clip-slider-thumb-shadow:${xe.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(";")}supportsVoicePanel(e){return e.groupKind==="text"||e.groupKind==="audio"&&e.supportsVoiceBatch}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 rd={...ge};function ds(a){return a?{primaryClip:a,selectedClips:[a],selectionCount:1,groupKind:a.type,supportsVoiceBatch:a.type==="text"||a.type==="audio"&&!!a.ttsSourceTextClipId,supportsTextContentBatch:a.type==="text",supportsVisualBatch:a.type==="video",supportsVolumeBatch:a.type==="video"||a.type==="audio"}:{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1}}function nd(a,e){return a.groupKind!==e.groupKind||a.selectionCount!==e.selectionCount||a.supportsVoiceBatch!==e.supportsVoiceBatch||a.supportsTextContentBatch!==e.supportsTextContentBatch||a.supportsVisualBatch!==e.supportsVisualBatch||a.supportsVolumeBatch!==e.supportsVolumeBatch||a.selectedClips.length!==e.selectedClips.length?!1:a.selectedClips.every((t,i)=>{var r;return t.id===((r=e.selectedClips[i])==null?void 0:r.id)})}class $a{constructor(e){p(this,"container");p(this,"theme");p(this,"renderer",new id);p(this,"onClipUpdate");p(this,"onGenerateVoice");p(this,"voiceCatalog");p(this,"currentClip",null);p(this,"selectionState",ds(null));p(this,"activeTab","visual");p(this,"iconCache",new Map);p(this,"pendingPreferredTab",null);p(this,"selectedVoiceId",null);p(this,"activeVoiceFilterTag","男");p(this,"textDraftContent","");p(this,"followTextUpdates",!0);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??rd,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",Ce("OmAi-camera")),this.iconCache.set("OmAi-accept",Ce("OmAi-accept")),this.iconCache.set("OmAi-loading",Ce("OmAi-loading")),this.iconCache.set("OmAi-text",Ce("OmAi-text")),this.renderer.mount(this.container),this.render()}setClip(e){this.setSelectionState(ds(e))}setSelectionState(e){var l,c,h,d,u,f;const t=e,i=this.selectionState,r=((l=this.currentClip)==null?void 0:l.id)??null,n=((c=t.primaryClip)==null?void 0:c.id)??null,s=r!==n,o=!nd(i,t);s&&this.stopVoicePreview(!1),this.selectionState=t,this.currentClip=t.primaryClip,s||o?(this.voiceErrorMessage=null,this.textDraftContent=((h=this.currentClip)==null?void 0:h.textContent)??((d=this.currentClip)==null?void 0:d.name)??"",this.syncVoiceStateForSelection(t)):((u=this.currentClip)==null?void 0:u.type)==="text"?this.textDraftContent=this.currentClip.textContent??this.currentClip.name??"":((f=this.currentClip)==null?void 0:f.type)==="audio"&&t.supportsVoiceBatch?(this.followTextUpdates=this.currentClip.ttsFollowTextUpdates??!1,this.ensureVoiceFilters()):this.currentClip||this.resetVoiceState(),this.syncActiveTab(t),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(){const e=this.getAvailableTabs(this.selectionState);this.renderer.update({clip:this.currentClip,selectionState:this.selectionState,activeTab:this.activeTab,availableTabs:e,theme:this.theme,emptyStateMessage:this.getEmptyStateMessage(this.selectionState),isTextContentEditable:this.selectionState.supportsTextContentBatch,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:t=>{this.activeTab=t,this.render()},onTransformChange:(t,i)=>{this.handleTransformChange(t,i)},onPresetSelect:(t,i)=>{this.handleTransformChanges({x:t,y:i})},onVolumeChange:t=>{this.handleVolumeChange(t)},onTextContentInput:t=>{this.handleTextContentInput(t)},onTextContentCommit:()=>{this.handleTextContentCommit()},onTextStyleChange:(t,i)=>{this.handleTextStyleChange(t,i)},onVoiceFilterChange:t=>{this.handleVoiceFilterChange(t)},onVoiceSelect:t=>{this.handleVoiceSelect(t)},onVoiceFollowTextUpdatesChange:t=>{this.handleVoiceFollowTextUpdatesChange(t)},onGenerateVoice:async()=>{await this.handleGenerateVoice()}}})}getAvailableTabs(e=this.selectionState){return e.groupKind==="text"?["text","voice"]:e.groupKind==="audio"?e.supportsVoiceBatch?["voice","audio"]:["audio"]:e.groupKind==="video"?["visual","audio"]:[]}getEmptyStateMessage(e=this.selectionState){return e.groupKind==="empty"?"请选择一个片段":e.groupKind==="mixed"?"暂不支持跨类型批量配置":null}resetVoiceState(){this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=!1,this.stopVoicePreview(!1)}syncVoiceStateForSelection(e){if(!this.supportsVoicePanel(e)||!e.primaryClip){this.resetVoiceState();return}this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=e.primaryClip.type==="audio"?e.primaryClip.ttsFollowTextUpdates??!1:!0,this.ensureVoiceFilters()}syncActiveTab(e){const t=this.getAvailableTabs(e);if(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=this.selectionState){return e.groupKind==="text"||e.groupKind==="audio"&&e.supportsVoiceBatch}ensureVoiceFilters(){if(this.voiceCatalog.length===0){this.selectedVoiceId=null,this.stopVoicePreview(!1);return}this.selectedVoiceId&&!this.voiceCatalog.some(e=>e.id===this.selectedVoiceId)&&(this.selectedVoiceId=null,this.stopVoicePreview(!1))}handleVoiceFilterChange(e){const t=e==="男"||e==="女"||e==="普通话"||e==="粤语"?e:null;this.activeVoiceFilterTag=this.activeVoiceFilterTag===t?null:t,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.selectionState.supportsVoiceBatch&&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){if(this.selectionState.supportsTextContentBatch){if(this.textDraftContent=e,!this.currentClip||!this.onClipUpdate){this.render();return}this.currentClip={...this.currentClip,textContent:e},this.onClipUpdate(this.currentClip.id,{textContent:e})}}handleTextContentCommit(){if(!this.currentClip||!this.onClipUpdate||!this.selectionState.supportsTextContentBatch)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={...Me(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 sd(a){return a==="text"?"文本":a==="video"?"视频":"音频"}class us{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:`${sd(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 g;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)??((g=n.find(y=>y.id===l))==null?void 0:g.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),f=u.indexOf(l);for(let y=1;y<=u.length;y+=1){const v=f-y;if(v>=0){const S=u[v],C=s.find(w=>this.resolveTrackId(w)===S);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:S}}const b=f+y;if(b<u.length){const S=u[b],C=s.find(w=>this.resolveTrackId(w)===S);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:S}}}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(Re.MIN,Math.min(Re.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=_e(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,f=_e(d.type),g=u+f;return s=g,{id:d.id,type:d.type,role:d.role,startY:u,endY:g,height:f}}).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 Wr{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 ps{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":{const n=this.target.findTrackByClipId(e.data.clip1.id)||this.target.getDefaultTrack();this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id),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:O.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:O.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 ad=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],od=new Set(["thumbnails"]);function ld(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 fs{constructor(e){p(this,"transactionStack",[]);this.history=e}createAddClipAction(e){return this.history.createAddClipAction(e)}recordAddClip(e){const t=this.history.createAddClipAction(e);return this.recordAction(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.recordAction(n),n}recordClipUpdate(e,t,i){const r=this.createClipUpdateAction(e,t,i);return r?(this.recordAction(r),r):null}recordSplitClip(e,t){const i={...e,duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},r=this.history.createSplitClipAction(i,e,t);return this.recordAction(r),r}recordRemoveGaps(e){if(e.length===0)return null;const t=this.history.createRemoveGapsAction(e);return this.recordAction(t),t}recordMoveClipBetweenTracks(e,t,i,r,n,s,o){const l=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,s,o);return this.recordAction(l),l}recordSeparateClipAudio(e,t,i,r){const n=this.history.createSeparateClipAudioAction(e,t,i,r);return this.recordAction(n),n}recordRestoreClipAudio(e,t,i,r){const n=this.history.createRestoreClipAudioAction(e,t,i,r);return this.recordAction(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.recordAction(i),i}createClipUpdateAction(e,t,i){if(i&&i.length>0)return this.history.createMultiClipUpdateAction(i);if(!t)return null;const r={},n={};if(ad.forEach(d=>{ld(e[d],t[d])||(r[d]=e[d],n[d]=t[d])}),Object.keys(r).length===0)return null;const s=Object.keys(r);if(s.every(d=>od.has(d)))return null;const o=new Set(["startTime","endTime"]);if(s.includes("startTime")&&s.every(d=>o.has(d)))return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);const c=new Set(["duration","startTime","endTime"]);return s.includes("duration")&&s.every(d=>c.has(d))?this.history.createResizeClipAction(e.id,e.duration,e.startTime,t.duration,t.startTime):this.history.createUpdateClipAction(e.id,r,n)}withTransaction(e,t){this.transactionStack.push({label:e,actions:[]});try{const i=t();return i instanceof Promise?i.then(r=>(this.finalizeTransaction(),r),r=>{throw this.finalizeTransaction(),r}):(this.finalizeTransaction(),i)}catch(i){throw this.finalizeTransaction(),i}}recordAction(e){const t=this.transactionStack[this.transactionStack.length-1];return t?(t.actions.push(e),e):(this.history.addAction(e),e)}finalizeTransaction(){const e=this.transactionStack.pop();if(!e)return;const t=this.normalizeTransactionActions(e.actions,e.label);if(!t)return;const i=this.transactionStack[this.transactionStack.length-1];if(i){i.actions.push(t);return}this.history.addAction(t)}normalizeTransactionActions(e,t){return e.length===0?null:e.length===1?e[0]??null:this.history.createCompoundAction(e,t)}}function Ai(a){var e;a.notifySelectionChange(),(e=a.emitSelectionChangeEvent)==null||e.call(a),a.emitSelectedClipChangeIfNeeded(),a.handleClipChange()}function cd(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 hd(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 Xt(a){return a.length===0?0:Math.max(...a.map(e=>e.endTime))}function dd(a,e){return e<Xt(a)}function ud(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 pd(a){const e=!a.id&&a.startTime>0;return{shouldJumpToTime:e,jumpTime:e?a.startTime:null,shouldSelectClip:!!a.id}}function Fi(a){var e;return a.applied?(a.isExecutingHistoryAction||(e=a.recordHistory)==null||e.call(a),a.applyEffects(),!0):!1}function fd(a){return Fi({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 gd(a){var e;a.isExecutingHistoryAction||(e=a.recordSplitClip)==null||e.call(a,a.clip1,a.clip2),a.emitClipUpdated(a.clip1),a.emitClipAdded(a.clip2),a.applyEffects()}const md={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function yd(a){var e,t;try{const i=typeof location<"u"?location.href:"http://localhost/";return((e=new URL(a,i).pathname.split(".").pop())==null?void 0:e.toLowerCase())??""}catch{return((t=(a.split(/[?#]/,1)[0]??"").split(".").pop())==null?void 0:t.toLowerCase())??""}}function Sd(a){const e=yd(a.src);if(e==="mp4")return{url:a.src,mimeType:"video/mp4",kind:"mp4"};if(e==="m3u8")return{url:a.src,mimeType:"application/vnd.apple.mpegurl",kind:"hls-fmp4"};const t=md[e];return t?{url:a.src,mimeType:t,kind:"audio"}:null}class vd{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.top="12px",this.container.style.left="12px",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="flex-start",this.container.style.flexDirection="row",this.container.style.gap="8px",this.container.style.background=fi.background,this.container.style.color=fi.text,this.container.style.fontSize="13px",this.container.style.lineHeight="1",this.container.style.padding="8px 10px",this.container.style.borderRadius="6px",this.container.style.zIndex="2000",this.container.style.pointerEvents="auto";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=fi.actionBackground,r.style.color=fi.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,isBuffering:r}=e,n=i.isBuffering||r;if(!t&&!n){this.container.style.display="none",this.actionElement.style.display="none",this.detailElement.style.display="none";return}if(this.container.style.display="inline-flex",this.detailElement.style.display="none",this.detailElement.textContent="",t!=null&&t.errorMessage||i.phase==="failed"){this.statusElement.textContent="资源加载异常",this.actionElement.style.display="inline-flex";return}if(!t){this.statusElement.textContent="视频缓冲中...",this.actionElement.style.display="none";return}const s=t.loadingPending>0||i.loadingCount>0;this.statusElement.textContent=s?"资源加载中...":"正在缓冲预览...",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 mr={x:.5,y:.5,scale:1},Cd=.1,bd=8;function yr(a,e){return typeof a=="number"&&Number.isFinite(a)?a:e}function Td(a){return Math.min(bd,Math.max(Cd,a))}function ke(a){return{x:yr(a==null?void 0:a.x,mr.x),y:yr(a==null?void 0:a.y,mr.y),scale:Td(yr(a==null?void 0:a.scale,mr.scale))}}function ln(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 za(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 gs(a,e,t){const i=za(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 Va(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 wd(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 ms(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}class kd{constructor(e={}){p(this,"frameElement",null);p(this,"overlayElement",null);p(this,"boxElement",null);p(this,"rotateHandleElement",null);p(this,"rotateHandlePointerDownHandler",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",clipType:this.state.clipType??"video",startFontSize:void 0,nextFontSize:void 0,centerX:void 0,centerY:void 0,startCenterDistance:void 0,startRotation:void 0,nextRotation:void 0,startAngle:void 0},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 ${st.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"),this.createRotateHandle(),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(),this.rotateHandleElement&&this.rotateHandlePointerDownHandler&&this.rotateHandleElement.removeEventListener("pointerdown",this.rotateHandlePointerDownHandler),this.rotateHandleElement=null,this.rotateHandlePointerDownHandler=null,(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()}createRotateHandle(){if(!this.overlayElement)return;const e=document.createElement("div");e.className="timeline-preview-transform-rotate-handle",e.style.position="absolute",e.style.display="none",e.style.width="20px",e.style.height="20px",e.style.borderRadius="999px",e.style.border=`1px solid ${st.border}`,e.style.background=st.handleBackground,e.style.pointerEvents="auto",e.style.cursor="grab",e.style.boxSizing="border-box",e.style.transform="translate(-50%, -50%)",e.style.display="none",e.style.alignItems="center",e.style.justifyContent="center",e.style.fontSize="12px",e.style.color=st.border,e.style.userSelect="none",e.textContent="↺";const t=this.getRotateHandlePointerDown();e.addEventListener("pointerdown",t),this.rotateHandleElement=e,this.rotateHandlePointerDownHandler=t,this.overlayElement.appendChild(e)}getRotateHandlePointerDown(){return e=>{var o,l;const t=e;if((t.button??0)!==0||!this.state)return;(o=t.preventDefault)==null||o.call(t),(l=t.stopPropagation)==null||l.call(t);const i=this.state.displayRect.left+this.state.displayRect.width/2,r=this.state.displayRect.top+this.state.displayRect.height/2,n=this.toLocalPoint(t),s=Math.atan2(n.y-r,n.x-i)*(180/Math.PI);this.interaction={clipId:this.state.clipId,mode:"rotate",pointerStart:n,startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing",clipType:"text",startFontSize:void 0,nextFontSize:void 0,centerX:i,centerY:r,startCenterDistance:void 0,startRotation:this.state.currentRotation??0,nextRotation:this.state.currentRotation??0,startAngle:s},this.setGlobalCursor("grabbing"),this.bindDocumentListeners()}}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 ${st.border}`,i.style.background=st.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 c,h;const i=t;if((i.button??0)!==0||!this.state)return;(c=i.preventDefault)==null||c.call(i),(h=i.stopPropagation)==null||h.call(i);const r=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize",n=this.state.clipType==="text",s=n?this.state.displayRect.left+this.state.displayRect.width/2:void 0,o=n?this.state.displayRect.top+this.state.displayRect.height/2:void 0,l=n?Math.sqrt(Math.pow(this.state.displayRect.width/2,2)+Math.pow(this.state.displayRect.height/2,2)):void 0;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,clipType:this.state.clipType??"video",startFontSize:n?this.state.currentFontSize:void 0,nextFontSize:n?this.state.currentFontSize:void 0,centerX:s,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},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,l,c,h,d;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);if(this.interaction.mode==="rotate"&&this.interaction.startRotation!==void 0){const u=i.x-this.interaction.centerX,f=i.y-this.interaction.centerY,y=Math.atan2(f,u)*(180/Math.PI)-this.interaction.startAngle,v=Math.round(this.interaction.startRotation+y);this.interaction.nextRotation=v,this.interaction.changed=v!==this.interaction.startRotation,(o=(s=this.callbacks).onRotationChange)==null||o.call(s,this.interaction.clipId,v);return}if(this.interaction.clipType==="text"&&this.interaction.startFontSize!==void 0){const u=i.x-this.interaction.centerX,f=i.y-this.interaction.centerY,g=Math.sqrt(u*u+f*f),y=(this.interaction.startCenterDistance??0)>0?g/this.interaction.startCenterDistance:1,v=Math.max(5,Math.min(300,Math.round(this.interaction.startFontSize*y)));this.interaction.nextFontSize=v,this.interaction.changed=v!==this.interaction.startFontSize,(c=(l=this.callbacks).onFontSizeChange)==null||c.call(l,this.interaction.clipId,v);return}let r=this.interaction.startTransform;if(this.interaction.mode==="move")r=Va(this.interaction.startTransform,i.x-this.interaction.pointerStart.x,i.y-this.interaction.pointerStart.y,this.interaction.frameSize);else{const u=this.interaction.startTransform.x*this.interaction.frameSize.width,f=this.interaction.startTransform.y*this.interaction.frameSize.height;r=wd(u,f,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!ln(this.interaction.startTransform,r),(d=(h=this.callbacks).onPreviewTransformChange)==null||d.call(h,this.interaction.clipId,r)}finishInteraction(e){var i,r,n,s,o,l,c,h,d,u,f,g;const t=this.interaction;if(!t){this.setGlobalCursor(null),this.unbindDocumentListeners();return}t.mode==="rotate"?(e&&t.changed&&t.nextRotation!==void 0&&((r=(i=this.callbacks).onRotationCommit)==null||r.call(i,t.clipId,t.nextRotation)),(s=(n=this.callbacks).onRotationChange)==null||s.call(n,t.clipId,null)):t.clipType==="text"?(e&&t.changed&&t.nextFontSize!==void 0&&((l=(o=this.callbacks).onFontSizeCommit)==null||l.call(o,t.clipId,t.nextFontSize)),(h=(c=this.callbacks).onFontSizeChange)==null||h.call(c,t.clipId,null)):(e&&t.changed&&((u=(d=this.callbacks).onPreviewTransformCommit)==null||u.call(d,t.clipId,t.nextTransform)),(g=(f=this.callbacks).onPreviewTransformChange)==null||g.call(f,t.clipId,null)),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners(),this.render()}render(){var r;if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none"),this.rotateHandleElement&&(this.rotateHandleElement.style.display="none");return}const e=this.state.clipType==="text";this.boxElement.style.pointerEvents=e?"none":"auto",this.boxElement.style.cursor=e?"default":"grab";const{displayRect:t}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${t.left}px`,this.boxElement.style.top=`${t.top}px`,this.boxElement.style.width=`${t.width}px`,this.boxElement.style.height=`${t.height}px`;const i=e?this.state.currentRotation??0:0;if(this.boxElement.style.transformOrigin="center",this.boxElement.style.transform=i!==0?`rotate(${i}deg)`:"",this.positionHandle("top-left",0,0),this.positionHandle("top-right",t.width,0),this.positionHandle("bottom-right",t.width,t.height),this.positionHandle("bottom-left",0,t.height),this.rotateHandleElement)if(e){if(!(((r=this.interaction)==null?void 0:r.mode)==="rotate")){const s=t.left+t.width/2,o=t.top+t.height/2,l=t.height/2+20,c=i*(Math.PI/180),h=s-l*Math.sin(c),d=o+l*Math.cos(c);this.rotateHandleElement.style.left=`${h}px`,this.rotateHandleElement.style.top=`${d}px`}this.rotateHandleElement.style.display="flex"}else this.rotateHandleElement.style.display="none"}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:ms(this.frameElement.style.left),top:ms(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 xd=0,Pd=2,_d=250,Ad=2,Id=120,ys="Arial, sans-serif";function Ed(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 Ua(a){return a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Sr(a){return`"${Ua(a)}"`}function Rd(a){return Kr(a,qr)}function Md(a,e){return!wt(a.mode)||!e?a:{mode:De.mode,width:e.width,height:e.height}}function Oe(a){return a.getAttribute("src")||a.currentSrc||a.src||""}function cn(a){return a.getAttribute("src")||""}function nt(a,e){const t=cn(a),i=a.currentSrc||"",r=a.src||"",n=Oe(a);return{desiredSource:e||null,srcAttribute:t||null,currentSrc:i||null,elementSrc:r||null,assignedSrc:n||null,hasSrcAttribute:!!t,matchesDesiredByAttribute:!!e&&t===e,matchesDesiredByAssigned:!!e&&n===e}}function Ki(a){return typeof HTMLVideoElement<"u"?a instanceof HTMLVideoElement:a.tagName==="VIDEO"}function $e(a){try{a.load()}catch{}}function ze(a){try{a.pause()}catch{}}function Dd(a){var e;try{const t=a.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function Ss(a,e){try{a.currentTime=Math.max(0,e)}catch{}}function Ii(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 vs(a){if(!a)return 0;const e=Number.parseFloat(a);return Number.isFinite(e)?e:0}function Ld(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function Bd(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 oe(a){return{tsMs:Ld(),currentTime:Number.isFinite(a.currentTime)?Number(a.currentTime.toFixed(3)):null,duration:Number.isFinite(a.duration)?Number(a.duration.toFixed(3)):null,currentSrc:Oe(a)||null,srcAttribute:cn(a)||null,elementSrc:a.src||null,rawCurrentSrc:a.currentSrc||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:Bd(a),videoWidth:Ki(a)?a.videoWidth:null,videoHeight:Ki(a)?a.videoHeight:null,error:a.error?{code:typeof a.error.code=="number"?a.error.code:null,message:a.error.message??null}:null}}function Od(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/_d)}`;default:return`${a.clip.id}:${i}`}}function Ve(a){return typeof(a==null?void 0:a.then)=="function"}function Fd(a,e){var t;return((t=a.entry)==null?void 0:t.clip.id)===e}function Gd(a,e){var u;const t=a.activeClips.filter(f=>f.trackType!=="text"),i=a.nextClips.filter(f=>f.trackType!=="text"),r=a.interactionMode??"steady",n=new Map(t.map(f=>[f.trackId,f])),s=new Map(i.map(f=>[f.trackId,f])),o=new Map,l=t.filter(f=>f.trackType==="video"&&f.hasVisual).sort((f,g)=>f.trackOrder-g.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(f,g)=>!s.has(f)||r!=="steady"&&c?!1:c?a.playState==="playing"&&g==="video"&&f===h:a.playState!=="playing"||t.length<=1;return e.forEach(f=>{o.set(f.trackId,{kind:f.kind,order:f.order})}),t.forEach(f=>{o.set(f.trackId,{kind:f.trackType,order:f.trackOrder})}),i.forEach(f=>{o.set(f.trackId,{kind:f.trackType,order:f.trackOrder})}),Array.from(o.entries()).map(([f,g])=>{const y=n.get(f)||null,v=d(f,g.kind)&&s.get(f)||null;return{trackId:f,kind:g.kind,order:g.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:v,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:a.syncRequestId}}}).sort((f,g)=>f.order-g.order)}class Hd{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,"transientFontSize",null);p(this,"transientRotation",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",{...De});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 vd(()=>{var i,r;(r=(i=this.callbacks).onPendingPreviewRetry)==null||r.call(i)}),this.transformOverlay=new kd({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,r)=>{var n,s;(s=(n=this.callbacks).onVisualTransformCommit)==null||s.call(n,i,r)},onFontSizeChange:(i,r)=>{var s;if(r===null){if(((s=this.transientFontSize)==null?void 0:s.clipId)===i){this.transientFontSize=null;const o=this.textPreviewEntries.get(i);o&&(o.element.style.fontSize=`${Me(o.entry.clip.textStyle).fontSize}px`),this.refreshVisualLayout()}return}this.transientFontSize={clipId:i,fontSize:r};const n=this.textPreviewEntries.get(i);n&&(n.element.style.fontSize=`${r}px`),this.refreshVisualLayout()},onFontSizeCommit:(i,r)=>{var n,s;(s=(n=this.callbacks).onTextFontSizeCommit)==null||s.call(n,i,r)},onRotationChange:(i,r)=>{var n;if(r===null){((n=this.transientRotation)==null?void 0:n.clipId)===i&&(this.transientRotation=null,this.refreshVisualLayout());return}this.transientRotation={clipId:i,rotation:r},this.refreshVisualLayout()},onRotationCommit:(i,r)=>{var n,s;(s=(n=this.callbacks).onTextRotationCommit)==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:Pa(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:Oe(e.element)||null,extra:{role:e.role,kind:e.kind,phase:e.phase,retryCount:e.retryCount,sourceState:nt(e.element,e.desiredSource),...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=I.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&&(ze(this.aspectRatioProbe),this.aspectRatioProbe.src="",$e(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.transientFontSize=null,this.transientRotation=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.transientFontSize&&this.transientFontSize.clipId!==this.primarySelectedClipId&&(this.transientFontSize=null),this.transientRotation&&this.transientRotation.clipId!==this.primarySelectedClipId&&(this.transientRotation=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=Gd(e,t).map(o=>this.applyTrackPlan(o)).filter(o=>Ve(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}),O.warn("TimelinePreviewSession","preview sync failed",{error:o,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=Xe(e),this.updateFrameLayout()}getAspectRatio(){return Md(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,Ki(r)?(kr(r),r.playsInline=!0,r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.objectFit="fill",r.style.background=I.black,r.style.pointerEvents="none"):r.style.display="none",r}createSlot(e,t,i){var S,C;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=I.black,n.style.pointerEvents="none",n.style.display="none",n.appendChild(r),(S=this.frameElement)==null||S.appendChild(n)}const s={role:i,trackId:e,kind:t,wrapper:n,element:r,entry:null,stableSourceUrl:null,desiredSource:null,objectUrl:null,pendingRuntimeSourceUrl:null,pendingRuntimeSourcePromise: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:oe(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:oe(s.element)})),o()},h=()=>{this.emitDiagnostic("warn","playback","media.waiting",this.buildSlotTraceData(s,{message:"Media waiting",mediaState:oe(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:oe(s.element),extra:{active:s.isActive}})),s.isBuffering=s.isActive&&!s.element.paused,s.consecutiveStalledCount+=1,this.refreshRuntimeState(),s.isActive&&s.consecutiveStalledCount>=Ad&&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:oe(s.element),extra:{active:s.isActive}})),s.isSeeking=!0,this.refreshRuntimeState()},f=()=>{this.emitDiagnostic("debug","playback","media.seeked",this.buildSlotTraceData(s,{message:"Media seeked",mediaState:oe(s.element)})),s.isSeeking=!1,s.isBuffering=!1,s.entry&&s.phase!=="failed"&&(s.phase=s.isActive?"active":"primed"),this.refreshRuntimeState()},g=w=>{var _;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:oe(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:oe(s.element)}));return}if(this.emitDiagnostic(w==="error"?"error":"warn","playback",`media.${w}`,this.buildSlotTraceData(s,{message:`Media event: ${w}`,mediaState:oe(s.element),error:s.element.error})),O.warn("TimelinePreviewSession",`media event: ${w}`,{trackId:s.trackId,role:s.role,clipId:((_=s.entry)==null?void 0:_.clip.id)??null,phase:s.phase,mediaState:oe(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:oe(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=()=>g("abort"),v=()=>g("emptied"),b=()=>g("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",f),r.addEventListener("abort",y),r.addEventListener("emptied",v),r.addEventListener("error",b),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",f),()=>r.removeEventListener("abort",y),()=>r.removeEventListener("emptied",v),()=>r.removeEventListener("error",b)),t==="audio"&&((C=this.rootElement)==null||C.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()),ze(e.element),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.stableSourceUrl=null,e.element.removeAttribute("src"),$e(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()}releaseSlotObjectUrl(e){var t;e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl),e.objectUrl=null)}clearPendingRuntimeSource(e){e.pendingRuntimeSourceUrl=null,e.pendingRuntimeSourcePromise=null}rememberSlotObjectUrl(e,t){e.objectUrl&&e.objectUrl!==t&&this.releaseSlotObjectUrl(e),e.objectUrl=t??null}revokeResolvedObjectUrl(e){var t;e!=null&&e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl))}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&&Fd(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(Ve(i)||Ve(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=Oe(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}})),ze(e.element),e.stableSourceUrl=null,e.desiredSource=null,e.errorMessage=null,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,this.resetSlotRecoveryTracking(e),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.element.removeAttribute("src"),$e(e.element),e.phase="idle",this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}const s=this.resolveDesiredSource(e,t.entry,i);if(Ve(s))return s.then(o=>{if(!o||!this.isCurrentSourceTarget(e,t.entry,o.stableSourceUrl)){this.revokeResolvedObjectUrl(o);return}const l=this.buildCurrentTargetForSlot(e)??t;if(!l.entry){this.revokeResolvedObjectUrl(o);return}if(e.stableSourceUrl=o.stableSourceUrl,e.desiredSource=o.url,this.configureAudioRouting(e,l.entry),this.slotNeedsRecovery(e,o.url)){if(this.shouldDeferPreloadTarget(e,l,o.url)){this.deferPreloadTarget(e,l,o,"current-loading");return}return Promise.resolve(this.recoverSlot(e,"reconcile",l,void 0,o)).then(()=>{})}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,o.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,l)});if(!s||!this.isCurrentRequest(e,i,t.entry)){this.revokeResolvedObjectUrl(s);return}if(e.stableSourceUrl=s.stableSourceUrl,e.desiredSource=s.url,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,s.url)){if(this.shouldDeferPreloadTarget(e,t,s.url)){this.deferPreloadTarget(e,t,s,"current-loading");return}return this.recoverSlot(e,"reconcile",t,i,s)}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,s.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,t)}settleResolvedSourceWithoutRecovery(e){e.phase==="binding"&&(e.phase=e.isActive?"active":"primed"),e.isLoading=!1,e.isBuffering=!1,e.errorMessage=null}resolveDesiredSource(e,t,i){const r=this.dependencies.previewSourceResolver??Sd,n=this.dependencies.sourceMediaRegistry;let s=null;const o=()=>(s!==null||(e.resolveToken+=1,s=e.resolveToken,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:s}})),this.refreshRuntimeState()),s);if(!r){const l={url:t.clip.src};return this.dependencies.resourceCacheManager&&o(),this.resolvePlayableSlotSource(e,t,l)}try{const l=n?n.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>r(t.clip)):r(t.clip);if(Ve(l)){const c=o();return l.then(h=>c!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:h?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:h.url,extra:{mimeType:h.mimeType,mediaKind:h.kind}})),this.resolvePlayableSlotSource(e,t,h)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(h=>(this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:h})),O.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:h}),this.failSlot(e,t,"预览源解析失败"),null))}return 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.dependencies.resourceCacheManager&&o(),this.resolvePlayableSlotSource(e,t,l)):(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){return this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:l})),O.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:l}),this.failSlot(e,t,"预览源解析失败"),null}}decorateSlotSourceUrl(e,t){return t}resolvePlayableSlotSource(e,t,i){const r=this.dependencies.resourceCacheManager,n=this.getReusableResolvedSlotSource(e,i);if(n)return this.emitRuntimeSourceDiagnostic(e,i.url,n,"source.runtime.reused","Reused existing runtime preview source"),n;if(e.pendingRuntimeSourceUrl===i.url&&e.pendingRuntimeSourcePromise)return this.emitRuntimeSourceDiagnostic(e,i.url,null,"source.runtime.pending-reused","Reused pending runtime preview source resolution"),e.pendingRuntimeSourcePromise;if(!r)return{stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null};const s=()=>!this.isCurrentSourceTarget(e,t,i.url),o={url:i.url,mimeType:i.mimeType,kind:i.kind,sourceKey:this.buildPreviewSourceCacheKey(t.clip)},l=()=>({stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null});try{const c=r.resolvePlayableUrl(o),h=d=>{if(!(d!=null&&d.url))return s()?null:l();const u={stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,d.url),objectUrl:d.objectUrl??null};return s()?(this.revokeResolvedObjectUrl(u),null):(this.emitRuntimeSourceDiagnostic(e,i.url,u,"source.runtime.resolved","Resolved runtime playable source",{cacheStatus:d.cacheStatus}),u)};if(Ve(c)){const d=c.then(h).catch(()=>s()?null:l());return d.finally(()=>{e.pendingRuntimeSourcePromise===d&&this.clearPendingRuntimeSource(e)}).catch(()=>{}),e.pendingRuntimeSourceUrl=i.url,e.pendingRuntimeSourcePromise=d,d}return h(c)}catch{return s()?null:l()}}emitRuntimeSourceDiagnostic(e,t,i,r,n,s={}){const o=(i==null?void 0:i.url)??t;this.emitDiagnostic("debug","resource",r,this.buildSlotTraceData(e,{message:n,desiredSourceUrl:o,actualSourceUrl:Oe(e.element)||null,mediaState:oe(e.element),extra:{stableSourceUrl:t,runtimeSourceUrl:(i==null?void 0:i.url)??null,objectUrl:(i==null?void 0:i.objectUrl)??null,sourceState:nt(e.element,o),...s}}))}getReusableResolvedSlotSource(e,t){if(!e.desiredSource||e.stableSourceUrl!==t.url)return null;const i=e.objectUrl??(e.desiredSource.startsWith("blob:")?e.desiredSource:null);return{stableSourceUrl:t.url,url:e.desiredSource,objectUrl:i}}slotNeedsRecovery(e,t){const i=cn(e.element),r=i||Oe(e.element);let n=!1,s=null;e.forceRecover?(n=!0,s="force-recover"):i?r!==t?(n=!0,s="source-mismatch"):(typeof e.element.networkState=="number"?e.element.networkState:null)===xd&&(n=!(e.isLoading||e.phase==="binding"||e.phase==="recovering"),s=n?"network-empty":"network-empty-binding-in-flight"):(n=!0,s="missing-src-attribute");const o=n&&(s==="source-mismatch"||e.isActive&&e.phase!=="idle"&&e.phase!=="binding");return this.emitDiagnostic(o?"warn":"debug","recovery","slot.recovery-check",this.buildSlotTraceData(e,{message:n?"Preview slot needs recovery":"Preview slot source is reusable",desiredSourceUrl:t,actualSourceUrl:r||null,mediaState:oe(e.element),extra:{needsRecovery:n,recoveryReason:s,configuredSource:i||null,actualSource:r||null,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,sourceState:nt(e.element,t)}})),n}recoverSlot(e,t,i,r,n){const s=i??(e.entry?{role:e.role,entry:e.entry,playState:e.requestedPlayState,speed:e.isActive&&e.element.playbackRate||1,visible:e.isActive&&!!e.entry.hasVisual,zIndex:e.entry?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null);if(!e.entry||!s||r!==void 0&&!this.isCurrentRequest(e,r,e.entry))return;const o=n??(e.desiredSource?{stableSourceUrl:e.stableSourceUrl??e.desiredSource,url:e.desiredSource,objectUrl:e.objectUrl}:this.resolveDesiredSource(e,e.entry,e.applyToken));if(Ve(o))return o.then(l=>{l&&this.finishSlotRecovery(e,t,s,l,r)});o&&this.finishSlotRecovery(e,t,s,o,r)}finishSlotRecovery(e,t,i,r,n){if(!e.entry)return;const s=typeof r=="string"?{stableSourceUrl:e.stableSourceUrl??r,url:r,objectUrl:e.objectUrl}:r,o=s.url,l=Od(e.entry,o,t);if(e.recoveryKey===l){if(e.retryCount>=Pd){this.isBackgroundPreloadSlot(e)?this.parkPreloadSlot(e,"媒体恢复失败,请等待下一次重建","retries-exhausted"):this.failSlot(e,e.entry,"媒体恢复失败,请刷新重试");return}e.retryCount+=1}else e.recoveryKey=l,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:o,mediaState:oe(e.element),extra:{reason:t,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState}})),(t!=="reconcile"||e.retryCount>1)&&O.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:o,mediaState:oe(e.element)});const c=Oe(e.element),h=nt(e.element,o),d=!!c||t!=="reconcile"||e.retryCount>1;ze(e.element),e.expectedEmptiedEvents=d?2:1,e.stableSourceUrl=s.stableSourceUrl,this.rememberSlotObjectUrl(e,s.objectUrl),d&&(e.element.removeAttribute("src"),$e(e.element)),e.element.setAttribute("src",o),$e(e.element),this.emitDiagnostic("info","resource","source.assigned",this.buildSlotTraceData(e,{message:"Preview source assigned",desiredSourceUrl:o,actualSourceUrl:o,extra:{reason:t,hardReset:d,previousSourceState:h,nextSourceState:nt(e.element,o),objectUrl:s.objectUrl,stableSourceUrl:s.stableSourceUrl}})),!(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){const n=i.url;e.desiredSource=n,this.rememberSlotObjectUrl(e,i.objectUrl),e.forceRecover=!0,e.isLoading=!1,e.isSeeking=!1,e.isBuffering=!1,e.errorMessage=null,e.element.getAttribute("src")&&e.element.getAttribute("src")!==n&&(ze(e.element),e.element.removeAttribute("src"),$e(e.element)),Oe(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:n,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())}buildCurrentTargetForSlot(e){return 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.isActive?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null}isCurrentRequest(e,t,i){var r;return e.applyToken===t&&((r=e.entry)==null?void 0:r.clip.id)===i.clip.id}isCurrentSourceTarget(e,t,i){return!e.entry||e.entry.clip.id!==t.clip.id?!1:this.buildPreviewSourceCacheKey(e.entry.clip)===this.buildPreviewSourceCacheKey(t.clip)||e.stableSourceUrl===i||e.desiredSource===i}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){ze(e.element),this.releaseSlotObjectUrl(e),e.element.removeAttribute("src"),$e(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:oe(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:oe(e.element),extra:{errorMessage:i}})),O.warn("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,mediaState:oe(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);if(Math.abs(e.element.currentTime-n)>s&&(this.emitDiagnostic("debug","playback","media.current-slot.seek",this.buildSlotTraceData(e,{message:"Current slot seek applied",mediaState:oe(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,Ss(e.element,n)),r==="playing"){this.resumeAudioContext();const l=nt(e.element,e.desiredSource);this.emitDiagnostic(l.hasSrcAttribute?"debug":"warn","playback","media.play.requested",this.buildSlotTraceData(e,{message:l.hasSrcAttribute?"Media play requested":"Media play requested without configured src attribute",mediaState:oe(e.element),extra:{playState:r,speed:i,sourceState:l}})),Dd(e.element)}else this.emitDiagnostic("debug","playback","media.pause.requested",this.buildSlotTraceData(e,{message:"Media pause requested",mediaState:oe(e.element),extra:{playState:r,speed:i,sourceState:nt(e.element,e.desiredSource)}})),ze(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:oe(e.element),extra:{toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3))}})),Ss(e.element,t.clip.startTimeAtSource/1e3),ze(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(!wt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=Ii(e,"sys_width"),i=Ii(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,$e(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(!Ve(n))return(n==null?void 0:n.url)??null;this.isAspectRatioProbeLoading=!0,this.refreshRuntimeState();const s=await n;return t!==this.aspectRatioProbeResolveToken?null:(s==null?void 0:s.url)??null}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");kr(e);const 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(!wt(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(),wt(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var b,S,C,w,_,P,B;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:k,preload:M}of this.trackSlots.values())for(const x of[k,M]){const $=Oe(x.element)||null;e.push({trackId:x.trackId,role:x.role,kind:x.kind,clipId:((b=x.entry)==null?void 0:b.clip.id)??null,desiredSource:x.desiredSource,actualSource:$,phase:x.phase,retryCount:x.retryCount,errorMessage:x.errorMessage}),x.phase!=="idle"&&(s=!0),x.entry&&x.phase!=="idle"&&x.phase!=="failed"&&(l=!0),(x.isLoading||x.phase==="binding"||x.phase==="recovering")&&(this.isActiveCurrentSlot(x)?t+=1:i+=1),x.isBuffering&&this.isActiveCurrentSlot(x)&&(h=!0),x.phase==="failed"&&(o=!0),x.phase==="failed"&&!n&&(n=x.errorMessage||"资源加载异常,请刷新重试"),x.isActive&&x.entry&&(x.isSeeking||x.phase!=="active"&&x.phase!=="failed")&&(c=!0),x.role==="current"&&x.isActive&&x.entry&&x.phase==="active"&&!x.isLoading&&!x.isSeeking&&!x.isBuffering&&(d=!0)}r=h&&!d;const u=d?0:t;let f="idle";this.activeSyncRequestId!==void 0&&this.isSyncProjecting?f="awaiting-sync":o&&!l?f="failed":u>0||r||c&&!d?f="awaiting-media":s&&(f="ready"),f!=="failed"&&(n=null),this.loadingCount!==u&&(this.loadingCount=u,(C=(S=this.callbacks).onSourceLoadingChange)==null||C.call(S,u)),this.syncVisibleBufferingState(r);const g={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:f,loadingCount:u,isBuffering:r,errorMessage:n,slots:e},y=this.lastRuntimeState,v=JSON.stringify(g);v!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=v,this.lastRuntimeState=g,(y.phase!==g.phase||y.loadingCount!==g.loadingCount||y.isBuffering!==g.isBuffering||y.errorMessage!==g.errorMessage)&&this.emitDiagnostic(g.phase==="failed"?"error":"info","runtime","runtime.state",{message:"Preview runtime state updated",syncRequestId:g.syncRequestId??null,runtimeState:{runtimePhase:g.phase,loadingCount:g.loadingCount,isBuffering:g.isBuffering},extra:{backgroundLoadingCount:i,previousPhase:y.phase,phase:g.phase,errorMessage:g.errorMessage,slots:g.slots.map(k=>({trackId:k.trackId,role:k.role,clipId:k.clipId,phase:k.phase,retryCount:k.retryCount,desiredSource:k.desiredSource,actualSource:k.actualSource}))}}),(_=(w=this.callbacks).onRuntimeStateChange)==null||_.call(w,g)),(f==="ready"||f==="failed")&&g.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==g.syncRequestId&&(this.lastSettledSyncRequestId=g.syncRequestId,(B=(P=this.callbacks).onSyncProcessed)==null||B.call(P,g.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,this.refreshPendingOverlay(),(n=(r=this.callbacks).onBufferingStateChange)==null||n.call(r,!0))},Id);return}this.clearBufferingVisibleTimeout(),this.isBuffering&&(this.isBuffering=!1,this.refreshPendingOverlay(),(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,isBuffering:this.isBuffering})}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",s.style.boxSizing="border-box",s.style.border="1px solid transparent";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=Me(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.textShadow=Ed(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(){var i;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return;const t=this.getTextPreviewBaselineMetrics(e);for(const r of this.textPreviewEntries.values()){const n=this.getEffectiveVisualTransform(r.entry),s=r.entry.clip.id,o=Me(r.entry.clip.textStyle).rotation,l=((i=this.transientRotation)==null?void 0:i.clipId)===s?this.transientRotation.rotation:o;r.element.style.left=`${e.width*n.x}px`,r.element.style.top=`${e.height*n.y}px`,r.element.style.transform=["translate(-50%, -50%)",`scale(${t.scale*n.scale})`,`rotate(${l}deg)`].join(" ")}}refreshTextPreviewEntries(){for(const e of this.textPreviewEntries.values())this.applyTextPreviewEntry(e);this.refreshTextPreviewLayout(),this.refreshTextPreviewInteractionState()}createTextPreviewPointerDownHandler(e){return t=>{var s,o,l,c;const i=t;if((i.button??0)!==0)return;if((s=i.preventDefault)==null||s.call(i),(o=i.stopPropagation)==null||o.call(i),this.primarySelectedClipId!==e){(c=(l=this.callbacks).onPreviewClipSelect)==null||c.call(l,e);return}this.textPreviewDragState&&this.finishTextPreviewDrag(!1);const r=this.textPreviewEntries.get(e);if(!r)return;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=Va(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=s,t.changed=!ln(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="auto",t.element.style.cursor=i?r?"grabbing":"grab":"pointer",t.element.style.border=i?`1px solid ${st.border}`:"1px solid transparent"}}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"?ys:`${Sr(e.fontName)}, ${ys}`}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("${Ua(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",O.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=gs(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(){var t,i;if(!this.primarySelectedClipId)return null;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return null;for(const{current:r}of this.trackSlots.values()){if(r.kind!=="video"||!r.isActive||!r.entry||r.entry.clip.id!==this.primarySelectedClipId)continue;const n=this.getMediaSize(r,r.entry,e),s=this.getEffectiveVisualTransform(r.entry);return{clipId:r.entry.clip.id,transform:s,frameSize:e,baseRect:za(e,n),displayRect:gs(e,n,s),clipType:"video"}}if(this.frameElement)for(const[r,n]of this.textPreviewEntries){if(r!==this.primarySelectedClipId)continue;const s=this.getEffectiveVisualTransform(n.entry),o=Me(n.entry.clip.textStyle),l=((t=this.transientFontSize)==null?void 0:t.clipId)===r?this.transientFontSize.fontSize:o.fontSize,c=((i=this.transientRotation)==null?void 0:i.clipId)===r?this.transientRotation.rotation:o.rotation,d=this.getTextPreviewBaselineMetrics(e).scale*s.scale,u=(n.element.offsetWidth||0)*d,f=(n.element.offsetHeight||0)*d,g=e.width*s.x,y=e.height*s.y;return{clipId:r,transform:s,frameSize:e,baseRect:{left:0,top:0,width:e.width,height:e.height,centerX:e.width/2,centerY:e.height/2},displayRect:{left:g-u/2,top:y-f/2,width:u,height:f,centerX:g,centerY:y},clipType:"text",currentFontSize:l,currentRotation:c}}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:vs((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:vs((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=Rd(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(Ki(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=Ii(t,"sys_width"),n=Ii(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 Nd extends Hd{constructor(e={}){super(e.callbacks,{diagnostics:e.diagnostics,getDiagnosticsContext:e.getDiagnosticsContext,previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont,sourceMediaRegistry:e.sourceMediaRegistry,resourceCacheManager:e.resourceCacheManager,rootClassName:e.rootClassName,frameClassName:e.frameClassName,slotClassNamePrefix:e.slotClassNamePrefix})}destroy(){this.detach()}}function $d(a){return"dom"}const zd=36e5,Vd=3e5;function Yr(a){return a.length===0?0:a.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function Cs(a){return Yr(a)}function bs(a){return Math.max(a+Vd,zd)}class Ts{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){O.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function Ud(a){return[...a].sort((e,t)=>e.order-t.order)}function Wd(a){return[...a].sort((e,t)=>e.startTime-t.startTime)}function vr(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 Yd{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t){const i=Ud(e),r=[],n=[];let s=null;for(const o of i){const l=Wd(o.clips),c=l.find(d=>t>=d.startTime&&t<d.endTime);if(c){const d=c.startTimeAtSource+(t-c.startTime);r.push(vr(o,c,d))}const h=l.find(d=>d.startTime>t);if(h&&n.push(vr(o,h,h.startTimeAtSource)),!s&&o.type==="video"){const d=l[0];d&&(s=vr(o,d,d.startTimeAtSource))}}return{activeClips:r,nextClips:n,firstVideoClip:s}}}class Xd{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 qd=8e3,jd=1e3;class Kd{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??qd,this.failedOverlayDelayMs=e.failedOverlayDelayMs??jd}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 Zd=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Jd={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 Qd(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function eu(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 tu(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=eu(c);if(!h||r)return null;r=h}}return r?{action:a,code:r,altKey:n,ctrlKey:s,metaKey:o,shiftKey:l}:null}function iu(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 ru(a,e){return a.code===e.code&&a.altKey===e.altKey&&a.ctrlKey===e.ctrlKey&&a.metaKey===e.metaKey&&a.shiftKey===e.shiftKey}function nu(a,e){return a===!1||(a==null?void 0:a.enabled)===!1?[]:Zd.flatMap(t=>{var n;const i=(n=a==null?void 0:a.bindings)==null?void 0:n[t];return(i===void 0?Jd[t]:Array.isArray(i)?i:[i]).map(s=>tu(t,s,e)).filter(s=>s!==null)})}class su{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??Qd();e.root,this.callbacks=e.callbacks,this.bindings=nu(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(iu(e.target))return;const t=this.bindings.find(i=>ru(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 Wa(a){var t;const e=a.getPrimarySelectedClip()||((t=a.findFallbackSelectedClip)==null?void 0:t.call(a))||null;return{clip:e,hasSelectedClip:!!e}}function au(a){const e=Wa(a),t=a.getSelectedClipIds(),i=a.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:a.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function ou(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 lu(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 cu(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=lu(a.trackCollection,e);return t?a.trackCollection.addClipToTrack(t,a.clip):!1}function ws(a,e,t){return e.trackId?a.removeClipFromTrack(e.trackId,t):!1}function hu(a){return a.trackCollection.moveClipToTrack(a.command.clip,a.command.sourceTrackId,a.command.targetTrackId)}function Ue(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 du(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 uu{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:di,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 ks{syncCurrentTime(e,t,i,r){e==null||e.setCurrentTime(r),t==null||t.setCurrentTime(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()}}const pu=100*1024*1024,fu=10*1024*1024*1024,gu=30*24*60*60*1e3,mu=["video/mp4","audio/aac","audio/mpeg","audio/mp4","audio/mp3","audio/ogg","audio/wav","audio/x-wav"],ti={enabled:!1,maxEntryBytes:pu,maxTotalBytes:fu,ttlMs:gu,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:mu},yu="timeline-preview-resource-cache",Su=1,me="metadata";function vu(){return new Promise((a,e)=>{const t=indexedDB.open(yu,Su);t.onupgradeneeded=()=>{const i=t.result,r=i.objectStoreNames.contains(me)?t.transaction.objectStore(me):i.createObjectStore(me,{keyPath:"cacheKey"});r.indexNames.contains("sourceUrl")||r.createIndex("sourceUrl","sourceUrl"),r.indexNames.contains("expiresAt")||r.createIndex("expiresAt","expiresAt"),r.indexNames.contains("lastAccessedAt")||r.createIndex("lastAccessedAt","lastAccessedAt"),r.indexNames.contains("storageKind")||r.createIndex("storageKind","storageKind")},t.onerror=()=>e(t.error),t.onsuccess=()=>a(t.result)})}function Cr(a){return new Promise((e,t)=>{a.oncomplete=()=>e(),a.onerror=()=>t(a.error),a.onabort=()=>t(a.error)})}class Cu{constructor(){p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=vu().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async get(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(me,"readonly").objectStore(me).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async put(e){const i=(await this.getDb()).transaction(me,"readwrite");i.objectStore(me).put(e),await Cr(i)}async delete(e){const i=(await this.getDb()).transaction(me,"readwrite");i.objectStore(me).delete(e),await Cr(i)}async clear(){const t=(await this.getDb()).transaction(me,"readwrite");t.objectStore(me).clear(),await Cr(t)}async list(){const e=await this.getDb();return new Promise((t,i)=>{const r=e.transaction(me,"readonly").objectStore(me).getAll();r.onerror=()=>i(r.error),r.onsuccess=()=>t(r.result)})}}const bu="timeline-preview-resource-cache",Tu="timeline-preview-resource-cache-blobs",wu=1,Ee="blobs";function ku(){return new Promise((a,e)=>{const t=indexedDB.open(Tu,wu);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},t.onerror=()=>e(t.error),t.onsuccess=()=>a(t.result)})}function br(a){return new Promise((e,t)=>{a.oncomplete=()=>e(),a.onerror=()=>t(a.error),a.onabort=()=>t(a.error)})}class xu{constructor(){p(this,"kind","indexeddb");p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=ku().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async read(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(Ee,"readonly").objectStore(Ee).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Ee,"readwrite");r.objectStore(Ee).put(t,e),await br(r)}async delete(e){const i=(await this.getDb()).transaction(Ee,"readwrite");i.objectStore(Ee).delete(e),await br(i)}async clear(){const t=(await this.getDb()).transaction(Ee,"readwrite");t.objectStore(Ee).clear(),await br(t)}}class Pu{constructor(){p(this,"kind","opfs");p(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(bu,{create:!0})).catch(e=>{throw this.directoryPromise=null,e})),this.directoryPromise}async ensureReady(){try{return await this.getDirectory(),!0}catch{return!1}}async read(e){try{return await(await(await this.getDirectory()).getFileHandle(e)).getFile()}catch{return null}}async write(e,t){const n=await(await(await this.getDirectory()).getFileHandle(e,{create:!0})).createWritable();try{await n.write(t),await n.close()}catch(s){try{typeof n.abort=="function"&&await n.abort()}catch{}throw s}}async delete(e){const t=await this.getDirectory();try{await t.removeEntry(e)}catch{}}async clear(){const e=await this.getDirectory();for await(const[t]of e)await e.removeEntry(t)}}async function _u(a){var e;if(a.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new Pu;if(await t.ensureReady())return t}return new xu}function Au(a){return Array.from(a).map(e=>e.toString(16).padStart(2,"0")).join("")}function xs(a){return a.split(";",1)[0].trim().toLowerCase()}async function Iu(a){const e=globalThis.crypto;if(!(e!=null&&e.subtle))throw new Error("Resource cache key generation requires Web Crypto SHA-256 support.");const t=await e.subtle.digest("SHA-256",new TextEncoder().encode(a));return Au(new Uint8Array(t))}function Tr(a){return a?[...a]:[...ti.allowedMimeTypes]}function Eu(a){return a?a===!0?{...ti,enabled:!0,allowedMimeTypes:Tr(void 0)}:{...ti,...a,enabled:a.enabled??!0,allowedMimeTypes:Tr(a.allowedMimeTypes)}:{...ti,allowedMimeTypes:Tr(void 0)}}function Ru(a){try{const e=new URL(a);return e.hash="",e.toString()}catch{return a.trim()}}async function Mu(a){var t;const e=((t=a.sourceKey)==null?void 0:t.trim())||Ru(a.url);return Iu(e)}function Ps(a,e=ti.allowedMimeTypes){if(!a.url)return!0;let t;try{t=new URL(a.url)}catch{return!0}if(t.protocol!=="http:"&&t.protocol!=="https:"||a.kind==="hls-fmp4"||/\.m3u8(?:$|\?|#)/i.test(t.pathname))return!0;if(!a.mimeType)return!1;const i=xs(a.mimeType);return!e.some(r=>xs(r)===i)}function Du(a){return a&&a.split(";",1)[0].trim().toLowerCase()||null}function _s(a){if(!a)return null;const e=Number(a);return Number.isSafeInteger(e)&&e>=0?e:null}function Lu(a){if(!a)return null;const e=a.match(/^bytes\s+(?:\d+-\d+|\*)\/(\d+|\*)$/i);if(!e||e[1]==="*")return null;const t=Number(e[1]);return Number.isSafeInteger(t)&&t>=0?t:null}function As(a,e,t){return{url:e,ok:a.ok,status:a.status,mimeType:Du(a.headers.get("content-type")),sizeBytes:t,etag:a.headers.get("etag"),lastModified:a.headers.get("last-modified"),acceptRanges:a.headers.get("accept-ranges")}}class Bu{async probe(e){var r;try{const n=await fetch(e,{method:"HEAD"}),s=_s(n.headers.get("content-length"));if(n.ok&&s!==null)return As(n,e,s)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=Lu(t.headers.get("content-range"))??_s(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return As(t,e,i)}async download(e){const t=await fetch(e);if(!t.ok)throw new Error(`Resource cache download failed with HTTP ${t.status}.`);return t.blob()}}const Ou={createObjectURL(a){return URL.createObjectURL(a)},revokeObjectURL(a){URL.revokeObjectURL(a)}};function vt(a,e){return{url:a.url,cacheStatus:e,sourceUrl:a.url}}function Fu(a,e){return a.etag||e.etag?a.etag===e.etag&&a.sizeBytes===e.contentLength:a.sizeBytes===e.contentLength&&a.lastModified===e.lastModified}class Gu{constructor(e={}){p(this,"options");p(this,"metadataStore");p(this,"storagePromise");p(this,"http");p(this,"objectUrl");p(this,"now");p(this,"cacheKeyBuilder");p(this,"onEvent");p(this,"objectUrls",new Set);p(this,"inflightDownloads",new Map);this.options=Eu(e.options),this.metadataStore=e.metadataStore??new Cu,this.storagePromise=e.storage?Promise.resolve(e.storage):_u({preferStorage:this.options.preferStorage}),this.http=e.http??new Bu,this.objectUrl=e.objectUrl??Ou,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??Mu,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Ps(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),vt(e,"bypass");try{const t=await this.cacheKeyBuilder(e),i=await this.storagePromise,r=await this.metadataStore.get(t);if(r){const l=await i.read(t);if(l){if(r.expiresAt>this.now()){const c={...r,lastAccessedAt:this.now()};return await this.metadataStore.put(c),this.emitEvent("resource-cache.hit",{sourceUrl:e.url,sizeBytes:c.sizeBytes}),this.blobResult(e.url,l,c,"hit")}return await this.resolveExpired(e,t,r,l,i)}await this.metadataStore.delete(t)}if(this.options.resolveMode==="prefer-fast-start")return this.probeAndDownload(t,e,i).catch(()=>{}),this.emitEvent("resource-cache.miss",{sourceUrl:e.url}),vt(e,"miss");const n=await this.probeCacheable(e);if(n.cacheStatus!=="miss")return n.result;const{blob:s,metadata:o}=await this.getOrCreateDownload(t,e,n.probe,i);return this.emitEvent("resource-cache.miss",{sourceUrl:e.url,sizeBytes:o.sizeBytes}),this.blobResult(e.url,s,o,"miss")}catch{return this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),vt(e,"fallback")}}revokeObjectUrl(e){this.objectUrls.delete(e)&&this.objectUrl.revokeObjectURL(e)}async cleanupExpired(){const e=await this.storagePromise,t=this.now(),i=await this.metadataStore.list();await Promise.all(i.filter(r=>r.expiresAt<=t).map(r=>this.deleteEntry(r.cacheKey,e)))}async clear(){const e=await this.storagePromise;await Promise.all([e.clear(),this.metadataStore.clear()]);for(const t of[...this.objectUrls])this.revokeObjectUrl(t)}async getStats(){const e=await this.metadataStore.list();return{entryCount:e.length,totalBytes:e.reduce((t,i)=>t+i.sizeBytes,0),maxTotalBytes:this.options.maxTotalBytes}}async resolveExpired(e,t,i,r,n){const s=await this.probeCacheable(e);if(s.cacheStatus!=="miss")return s.result;if(Fu(s.probe,i)){const c=this.now(),h={...i,updatedAt:c,lastAccessedAt:c,expiresAt:c+this.options.ttlMs};return await this.metadataStore.put(h),this.emitEvent("resource-cache.revalidate.success",{sourceUrl:e.url,sizeBytes:h.sizeBytes}),this.blobResult(e.url,r,h,"stale-revalidated")}this.emitEvent("resource-cache.revalidate.stale",{sourceUrl:e.url}),await this.deleteEntry(t,n);const{blob:o,metadata:l}=await this.getOrCreateDownload(t,e,s.probe,n);return this.blobResult(e.url,o,l,"miss")}async probeCacheable(e){const t=await this.http.probe(e.url);return t.ok?t.sizeBytes===null?(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:vt(e,"fallback")}):Ps({...e,mimeType:e.mimeType??t.mimeType},this.options.allowedMimeTypes)||t.sizeBytes>this.options.maxEntryBytes||t.sizeBytes>this.options.maxTotalBytes?(this.emitEvent("resource-cache.bypass",{sourceUrl:e.url,sizeBytes:t.sizeBytes,mimeType:t.mimeType}),{cacheStatus:"bypass",result:vt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:vt(e,"fallback")})}async probeAndDownload(e,t,i){const r=await this.probeCacheable(t);r.cacheStatus==="miss"&&await this.getOrCreateDownload(e,t,r.probe,i)}getOrCreateDownload(e,t,i,r){const n=this.inflightDownloads.get(e);if(n)return n;const s=this.downloadAndStore(e,t,i,r).finally(()=>{this.inflightDownloads.delete(e)});return this.inflightDownloads.set(e,s),s}async downloadAndStore(e,t,i,r){this.emitEvent("resource-cache.download.start",{sourceUrl:t.url});try{const n=await this.http.download(t.url),s=n.size;if(s>this.options.maxEntryBytes||s>this.options.maxTotalBytes)throw new Error("Resource exceeds cache capacity.");await this.evictForWrite(e,s,r),await r.write(e,n);const o=this.now(),l={cacheKey:e,sourceUrl:t.url,mimeType:i.mimeType??t.mimeType??null,sizeBytes:s,etag:i.etag,lastModified:i.lastModified,contentLength:s,storageKind:r.kind,createdAt:o,updatedAt:o,lastAccessedAt:o,expiresAt:o+this.options.ttlMs};return await this.metadataStore.put(l),this.emitEvent("resource-cache.download.success",{sourceUrl:t.url,sizeBytes:s}),{blob:n,metadata:l}}catch(n){throw this.emitEvent("resource-cache.download.failed",{sourceUrl:t.url,error:n instanceof Error?n.message:String(n)}),n}}async evictForWrite(e,t,i){const r=(await this.metadataStore.list()).filter(s=>s.cacheKey!==e);let n=r.reduce((s,o)=>s+o.sizeBytes,0);for(const s of r.sort((o,l)=>o.lastAccessedAt-l.lastAccessedAt)){if(n+t<=this.options.maxTotalBytes)return;await this.deleteEntry(s.cacheKey,i),n-=s.sizeBytes}}async deleteEntry(e,t){await Promise.all([t.delete(e),this.metadataStore.delete(e)]),this.emitEvent("resource-cache.cleanup.deleted",{cacheKey:e})}blobResult(e,t,i,r){const n=this.objectUrl.createObjectURL(t);return this.objectUrls.add(n),{url:n,cacheStatus:r,sourceUrl:e,sizeBytes:i.sizeBytes,objectUrl:n}}emitEvent(e,t){var i;(i=this.onEvent)==null||i.call(this,e,t)}}function Hu(a){return!!a&&typeof a.then=="function"}class wr{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(!Hu(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 Is{constructor(e,t=Xi){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 Nu{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 $u(a){return a==="text"?"文本":a==="video"?"视频":"音频"}function Ei(a){return a==="text"?0:a==="video"?1:2}class Ya{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||`${$u(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),O.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?(O.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(O.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),O.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,O.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(O.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),O.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(O.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=>Ei(l.type)>Ei(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)=>Ei(c.type)<=Ei(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,O.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(O.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,O.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}class zu{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 Xa{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 Vu{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 Es{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new Xa,this.playbackStore=new zu({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new Vu({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 Uu{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||Re.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Hi(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=U.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=U.timeToPixels(e.startTime,this.config.zoom),r=U.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=tr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(ir({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 U.pixelsToTime(e-Te+this.scrollLeft,this.config.zoom)}timeToPixel(e){return U.timeToPixels(e,this.config.zoom)-this.scrollLeft+Te}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=de.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=U.pixelsToTime(t,this.config.zoom),n=U.pixelsToTime(i,this.config.zoom),s=U.msToSeconds(r),o=U.msToSeconds(n),{majorStep:l,minorStep:c}=U.getTickConfig(this.config.zoom),h=U.generateVisibleTicks(s-10,o+10,l,c);for(const d of h){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&de.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,U.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const q=class q{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(q.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${q.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=`${q.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=tr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(ir({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,r=U.pixelsToTime(i-Te+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(q.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=q.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=U.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+Te,t=e>=0&&e<=this.container.clientWidth,i=Math.max(q.HANDLE_HEIGHT+q.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 ${q.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=hn.grip,i=Math.max(q.HANDLE_HEIGHT,e-q.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i))}createHandleShadowPath(){const e=document.createElementNS(q.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",hn.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(q.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(q.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(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(q.VISUAL_WIDTH-q.LINE_WIDTH)/2}`),t.setAttribute("y",`${q.HANDLE_LINE_START}`),t.setAttribute("width",`${q.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-q.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e){const t=document.createElementNS(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-end-cap"),t.setAttribute("x","3"),t.setAttribute("y",`${e}`),t.setAttribute("width",`${q.END_CAP_WIDTH}`),t.setAttribute("height",`${q.END_CAP_HEIGHT}`),t.setAttribute("rx","1.5"),t.setAttribute("fill","#ffffff"),t}};p(q,"SVG_NS","http://www.w3.org/2000/svg"),p(q,"VISUAL_WIDTH",14),p(q,"HANDLE_HEIGHT",16),p(q,"HANDLE_LINE_START",13),p(q,"LINE_WIDTH",1),p(q,"LINE_HIT_WIDTH",12),p(q,"END_CAP_WIDTH",8),p(q,"END_CAP_HEIGHT",1),p(q,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(q,"AUTO_SCROLL_MAX_SPEED",18);let Xr=q;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 K.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new K.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=de.createRect(0,0,0,0,It.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||It.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||It.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=tr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(ir({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||It.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||It.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 Ms{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 Wu{constructor(){p(this,"panel",null);p(this,"config",null);p(this,"currentSelectionState",this.buildSelectionState(null,[]));p(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new $a({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,this.resolveUpdateTargets(i,r).forEach(s=>{e.updateClip(s.id,r)}),setTimeout(()=>{this.isInternalUpdate=!1},0)},onGenerateVoice:e.onGenerateVoice})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip(),t=this.config.getSelectedClips();this.currentSelectionState=this.buildSelectionState(e,t),this.panel.setSelectionState(this.currentSelectionState)}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)}buildSelectionState(e,t){const i=t.length>0?t:e?[e]:[],r=e??i[0]??null;if(!r||i.length===0)return{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1};const s=new Set(i.map(c=>c.type)).size>1?"mixed":r.type,o=i.length>1,l=s==="audio"&&i.every(c=>c.type==="audio"&&!!c.ttsSourceTextClipId);return{primaryClip:r,selectedClips:i,selectionCount:i.length,groupKind:s,supportsVoiceBatch:s==="text"||l,supportsTextContentBatch:s==="text"&&!o,supportsVisualBatch:s==="video",supportsVolumeBatch:s==="video"||s==="audio"}}resolveUpdateTargets(e,t){const{primaryClip:i,selectedClips:r,groupKind:n,supportsVoiceBatch:s}=this.currentSelectionState,o=r.find(l=>l.id===e)??i;return o?Object.prototype.hasOwnProperty.call(t,"textContent")?[o]:Object.prototype.hasOwnProperty.call(t,"ttsFollowTextUpdates")?s&&n==="audio"?r.filter(l=>l.type==="audio"&&!!l.ttsSourceTextClipId):[o]:Object.prototype.hasOwnProperty.call(t,"textStyle")?n==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"visualTransform")?n==="video"||n==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"volume")?n==="video"||n==="audio"?r:[o]:[o]:[]}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 Yu="@linker-design-plus/timeline-track",Xu="2.0.23",Nt={name:Yu,version:Xu},qu=1,ju=2,Ku=120,Zu=250;function Ds(a){return a==null?a:JSON.parse(JSON.stringify(a))}function Ju(a){return a==="text"?"文本":a==="video"?"视频":"音频"}class Qu{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 wr);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",{...De});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 Ms);p(this,"pendingDraftData",null);p(this,"selectionStore",new Xa);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);p(this,"splitOperationDepth",0);p(this,"diagnostics");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,"lastPreviewSyncSignature",null);p(this,"lastSteadyPlaybackPreviewSyncAt",0);p(this,"previewSyncInteractionMode",null);p(this,"resourceCacheManager");p(this,"voiceLinkedTextRegenerationTimer",null);p(this,"pendingVoiceLinkedTextRegeneration",null);p(this,"historyRecordingSuppressionDepth",0);this.config={duration:e.duration||36e5,zoom:e.zoom||Re.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:Hi(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,resourceCache:e.resourceCache,textPreviewFont:e.textPreviewFont??null,keyboardShortcuts:e.keyboardShortcuts},this.diagnostics=new xa(this.config.diagnostics),this.resourceCacheManager=this.config.resourceCache?new Gu({options:this.config.resourceCache,onEvent:(t,i)=>{this.emitDiagnostic({...this.buildPreviewDiagnosticsContext(),severity:t.endsWith(".failed")||t.endsWith(".fallback")?"warn":"info",category:"resource",eventName:t,message:t,extra:i})}}):null,this.diagnostics.startSession({packageName:Nt.name,packageVersion:Nt.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 uu,this.eventDispatcher=new Ts({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 Wr(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new fs(this.history),this.timelineHistoryExecutor=new ps({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 Ya,this.timelineStore=new Es({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new us(this.timelineStore),this.timelinePresentationAdapter=new ks,this.timelineTrackBridge=new Is({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()}}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)||Re.MEDIUM,h=((n=this.config)==null?void 0:n.duration)||36e5;this.timelineStore=new Es({currentTime:s,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new us(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Nu(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new ks),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Is({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 Yd),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 Kd({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,this.buildPreviewIndicatorState(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 Xd({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Nd({callbacks:t,diagnostics:this.diagnostics,getDiagnosticsContext:()=>this.buildPreviewDiagnosticsContext(),previewSourceResolver:this.config.previewSourceResolver,resourceCacheManager:this.resourceCacheManager,textPreviewFont:this.config.textPreviewFont,sourceMediaRegistry:this.sourceMediaRegistry}),resolveConfiguredBackend:e=>e||$d(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=Xe(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onPreviewClipSelect:t=>{this.isActivePreviewCallbackToken(e)&&this.selectClip(t)},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onTextFontSizeCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextFontSize(t,i)},onTextRotationCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextRotation(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 Ts({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 Wr(()=>{},()=>{})),this.timelineHistoryRecorder=new fs(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new ps({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}withHistoryBoundary(e,t,i){if(e==="transaction"){const s=t,o=i;if(!o)throw new Error("transaction history boundary requires a callback");return this.getTimelineHistoryRecorder().withTransaction(s,o)}const r=typeof t=="function"?t:i;if(!r)throw new Error(`history boundary "${e}" requires a callback`);if(e==="record")return r();if(e==="suppressed"||e==="reset"){this.historyRecordingSuppressionDepth=(this.historyRecordingSuppressionDepth??0)+1;try{const s=r();return s instanceof Promise?s.then(o=>(this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),o),o=>{throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),o}):(this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),s)}catch(s){throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),s}}const n=this.isExecutingHistoryAction??!1;this.isExecutingHistoryAction=!0;try{const s=r();return s instanceof Promise?s.then(o=>(this.isExecutingHistoryAction=n,o),o=>{throw this.isExecutingHistoryAction=n,o}):(this.isExecutingHistoryAction=n,s)}catch(s){throw this.isExecutingHistoryAction=n,s}}shouldSkipHistoryRecording(){return this.isExecutingHistoryAction||this.historyRecordingSuppressionDepth>0}withHistoryTransaction(e,t){return this.withHistoryBoundary("transaction",e,t)}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:Re.MEDIUM,currentTime:0,playState:"paused",theme:Hi(),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 U.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)}hasTimelineVideoClip(e=this.getCurrentTimeState()){return this.buildPlaybackPlan(e).firstVideoClip!==null}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)}buildPreviewSyncSignature(e){var i,r;const t=n=>[n.trackId,n.clip.id,n.trackType,n.trackOrder,n.clip.startTime,n.clip.endTime,n.clip.startTimeAtSource,n.muted?1:0,n.clip.volume??""].join(":");return JSON.stringify({active:e.playbackPlan.activeClips.map(t),next:e.playbackPlan.nextClips.map(t),firstVideoClipId:((i=e.playbackPlan.firstVideoClip)==null?void 0:i.clip.id)??null,autoAspectRatioClipId:((r=e.autoAspectRatioClip)==null?void 0:r.clip.id)??null,previewAspectRatio:e.previewAspectRatio,playState:e.targetPlayState,speed:e.speed,interactionMode:e.interactionMode,primarySelectedClipId:e.primarySelectedClipId})}shouldSkipSteadyPlaybackPreviewSync(e,t,i){return t!=="playing"||i!=="steady"||this.pendingPreviewState||this.previewBuffering||this.lastPreviewSyncedPlayState!=="playing"||this.lastPreviewSyncSignature!==e?!1:Date.now()-this.lastSteadyPlaybackPreviewSyncAt<Zu}syncPreviewSession(e){var h,d,u,f;if(!((h=this.previewSession)!=null&&h.hasPreview())){this.previewSyncInteractionMode=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0;return}const t=this.buildPlaybackPlan();this.previewActiveClipIds=t.activeClips.map(g=>g.clip.id);const i=this.getAutoAspectRatioClip(),r=Xe(this.previewAspectRatio),n=e??this.getPlayStateState(),s=this.getSpeedState(),o=this.previewSyncInteractionMode??((d=this.pendingPreviewState)==null?void 0:d.mode)??"steady",l=this.getPrimarySelectedClipId(),c=this.buildPreviewSyncSignature({playbackPlan:t,autoAspectRatioClip:i,previewAspectRatio:r,targetPlayState:n,speed:s,interactionMode:o,primarySelectedClipId:l});if(this.shouldSkipSteadyPlaybackPreviewSync(c,n,o)){this.previewSyncInteractionMode=null;return}this.previewAspectRatio=r,this.previewSession.applyAspectRatio(r),this.previewSession.sync({...t,autoAspectRatioClip:i,currentTime:this.getCurrentTimeState(),playState:n,speed:s,interactionMode:o,primarySelectedClipId:l,...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),this.previewSyncInteractionMode=null,(f=(u=this.previewSession).setPendingState)==null||f.call(u,this.buildPreviewPendingState()),this.lastPreviewSyncedPlayState=n,this.lastPreviewSyncSignature=c,this.lastSteadyPlaybackPreviewSyncAt=n==="playing"&&o==="steady"?Date.now():0}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;if(!this.hasTimelineVideoClip(e)){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();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.buildPreviewIndicatorState(this.getPreviewStateController().buildPreviewPendingState())}buildPreviewIndicatorState(e){const t=Number.isFinite(this.sourceLoadingCount)?Math.max(0,this.sourceLoadingCount):0;return t<=0?e:e?{...e,loadingPending:e.loadingPending+t}:{mode:"seek",targetTime:this.getCurrentTimeState(),loadingPending:t,isBuffering:!1,errorMessage:null}}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState(),this.previewActiveClipIds=[],this.lastPreviewSyncedPlayState=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0,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(Xe(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){O.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=jh(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:di,scrollbarSize:Vr}),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 K.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new K.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new K.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new K.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new K.Layer({name:"trackLayer"}),this.dragOverlayLayer=new K.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new K.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new K.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 Uu(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new Xr(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:Te,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Rs({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.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=>{O.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,n){var d,u,f;if(!this.trackLayer)return O.error("TimelineManager","Track layer not initialized"),"";const s=this.trackManager.createTrack(e,t,i,r,n),o=s.id,l=_e(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(),(f=this.stage)==null||f.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 O.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return O.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()}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 Ht(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return hs(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=Qh(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=de.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=Ht(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+_e(c.type)}}if(t==="top_of_type_region"&&s)return Ht(r,s.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Ht(r,o.id,this.getTrackContentTopOffset())+_e(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():hs(r,this.getTrackContentTopOffset());const l=Ht(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+_e(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 K.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=U.pixelsToTime(e-Te+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||ee.snapGuideLineColor}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=de.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=pe(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===qu)return e*16;if(t===ju){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(Re.MIN,Math.min(Re.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){const e=this.getClips();if(e.length>0&&this.getCurrentTime()>=Xt(e)){if(this.setCurrentTime(0),!this.canPlay)return}else{O.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"))},Ku);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)}clampPlaybackSeekTime(e){const t=Math.max(0,e);let i;try{const n=this.getClips();i=Array.isArray(n)?n:[]}catch{return t}if(i.length===0)return t;const r=Xt(i);return!Number.isFinite(r)||r<=0?t:Math.min(t,r)}setCurrentTime(e){const t=this.clampPlaybackSeekTime(e),i=this.getTimelineCommands().setCurrentTime(t);if(!i.changed){this.pendingPreviewState&&this.pendingPreviewState.targetTime===i.nextValue&&this.syncPreviewSession();return}const r=i.nextValue;this.ensureConfigState().currentTime=r,this.syncCurrentTimeToScene(r),this.emitEvent("time_change",{time:r}),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=U.timeToPixels(i,t),c=U.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=U.pixelsToTime(t-Te+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=U.timeToPixels(n,o)-(t-Te);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}),O.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return O.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{return await this.withHistoryTransaction("add_clips",async()=>{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?Yr(t.getClips()):0}async addClipInternal(e){var b;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 U.getVideoDuration(n,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(S){O.error("TimelineManager","Failed to get video duration:",{error:S}),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)}`,f=Zr({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?Me(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});if(O.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:f.id,type:f.type,startTime:f.startTime,duration:f.duration})),e.trackId){const S=this.getTrackCollection().findById(e.trackId);if(S)return this.registerPreviewAutoAspectRatioClip(f),(b=S.addClip)==null||b.call(S,f),Fi({applied:!0,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(f)},applyEffects:()=>Ue({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(f),f.id}const g=this.getTimelineCommands().planTrackPlacement(f,this.getTracksSortedByOrder()),y=this.getTrackCollection(),v=cu({clip:f,placement:g,trackCollection:y,createTrack:this.createTrack.bind(this)});return Fi({applied:v,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(f)},applyEffects:()=>Ue({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(f),f.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),Fi({applied:ws(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>Ue({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.withHistoryBoundary("suppressed",()=>{this.withClipRemovalBatch(()=>{for(const n of t){const s=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);s.exists&&(r=ws(this.getTrackCollection(),s,n)||r)}})}),r?(Ai({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Ue({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)}Ue({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)}),Ue({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)}),Ue({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(wt(e.mode)&&t===De.width&&i===De.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=Kr({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){O.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}const t=[];await this.withHistoryBoundary("reset",async()=>{this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const r=new Map,n=[...e.tracks].sort((c,h)=>c.order-h.order),s=this.resolveImportedTrackRoles(n);let o;for(const c of n){const h=this.createTrack(c.type,c.name,o?"after_track":void 0,o,s.get(c.id));h&&(this.muteTrack(h,c.isMuted),r.set(c.id,h),o=h)}const l=new Map;for(const c of n){const h=r.get(c.id);if(h)for(const d of c.clips)try{let u=d.separatedAudioClipId;u&&l.has(u)&&(u=l.get(u));let f=d.separatedFromVideoClipId;f&&l.has(f)&&(f=l.get(f));const g={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:f,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(g);l.set(d.id,y)}catch(u){t.push({clipId:d.id,error:u}),O.error("TimelineManager",`Failed to import clip ${d.id}:`,{error:u})}}}),this.clearHistory();const i={errors:t};this.emitEvent("draft_loaded",i)}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 Nt.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-Te*2;O.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:s}));const o=Math.min(s/r,Re.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.shouldSkipHistoryRecording()||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i),this.emitEvent("clip_updated",{clip:e});const r=this.selectedClipId===e.id;cd({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}),Ai({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)&&Ai({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}))}reloadClipThumbnailsIfNeeded(e,t){hd(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{O.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){const e=this.getClips(),t=this.getCurrentTime(),i=dd(e,t),r=this.canPlay;this.canPlay=ud({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:Xt(e)||1,setCanPlay:n=>{this.canPlay=n},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:n=>{this.emitEvent("can_play_change",{canPlay:n})}}),r!==this.canPlay&&O.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)}hasVoiceLinkedAudioClipsToRegenerate(e){return this.getVoiceLinkedAudioClips(e).some(t=>t.ttsFollowTextUpdates===!0&&!!t.ttsVoiceId)}scheduleVoiceLinkedTextRegeneration(e,t,i,r){var n;this.pendingVoiceLinkedTextRegeneration&&this.pendingVoiceLinkedTextRegeneration.clipId!==e&&(this.voiceLinkedTextRegenerationTimer!==null&&(clearTimeout(this.voiceLinkedTextRegenerationTimer),this.voiceLinkedTextRegenerationTimer=null),this.flushPendingVoiceLinkedTextRegeneration().catch(s=>{O.error("TimelineManager","Failed to flush pending linked voice regeneration",{error:s,clipId:e})})),this.voiceLinkedTextRegenerationTimer!==null&&clearTimeout(this.voiceLinkedTextRegenerationTimer),this.pendingVoiceLinkedTextRegeneration={clipId:e,originalClip:((n=this.pendingVoiceLinkedTextRegeneration)==null?void 0:n.clipId)===e?this.pendingVoiceLinkedTextRegeneration.originalClip:{...t},nextText:i,generateVoiceBatch:r},this.voiceLinkedTextRegenerationTimer=setTimeout(()=>{this.voiceLinkedTextRegenerationTimer=null,this.flushPendingVoiceLinkedTextRegeneration().catch(s=>{O.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:s,clipId:e})})},450)}async flushPendingVoiceLinkedTextRegeneration(){const e=this.pendingVoiceLinkedTextRegeneration;if(this.pendingVoiceLinkedTextRegeneration=null,!e)return;const t=this.findClipById(e.clipId),i=(t==null?void 0:t.type)==="text"?{...t,textContent:e.nextText}:null,r=e.nextText,n=i?this.getTimelineHistoryRecorder().createClipUpdateAction(i,e.originalClip):null;await this.withHistoryTransaction("update_text_with_voice_regeneration",async()=>{n&&this.getTimelineHistoryRecorder().recordAction(n),await this.regenerateVoiceLinkedAudioClips(e.clipId,r,e.generateVoiceBatch)})}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")}selectBestClipboardPasteStartIndex(e,t){var r;if(t.length===0)return null;const i=t.filter(n=>n.newTrackCount===0).sort((n,s)=>n.score-s.score)[0];if(i)return i.startIndex;if(e==="text"){const n=t.filter(s=>s.startIndex<0).sort((s,o)=>s.newTrackCount!==o.newTrackCount?s.newTrackCount-o.newTrackCount:s.score-o.score)[0];if(n)return n.startIndex}return((r=t.slice().sort((n,s)=>n.score-s.score)[0])==null?void 0:r.startIndex)??null}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(C=>{var w;return C.type===((w=e[0])==null?void 0:w.type)}).sort((C,w)=>C.order-w.order);if(s.length===0){const C=this.createTrack(e[0].type);C&&n.set(e[0].key,C);for(let w=1;w<e.length;w+=1){const _=this.createTrack(e[w].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");_&&n.set(e[w].key,_)}return n}const o=new Set(e.flatMap(C=>C.clipIds)),l=e.map(C=>{const w=this.buildClipboardPasteGroupPlacementClips(C,t,i,r);if(w.length===0)return null;const _=this.resolvePreferredTrackIndexForPasteGroup(C,s,Math.min(C.sourceOrder,Math.max(s.length-1,0)));return{...C,preferredTrackIndex:_,clips:w}}).filter(C=>C!==null);if(l.length===0)return n;const c=l.map(C=>C.preferredTrackIndex),h=Math.min(...c),d=s.length,u=-l.length,f=[];for(let C=u;C<=d;C+=1){let w=!0,_=0,P=0;for(let B=0;B<l.length;B+=1){const k=l[B];if(!k)continue;const M=C+B;if(_+=Math.abs(M-k.preferredTrackIndex),M<0||M>=s.length){P+=1;continue}if(this.doesClipGroupOverlapOnTrack(s[M].id,k.clips,o)){w=!1;break}}w&&(_+=P*.1,_+=Math.abs(C-h)*.001,f.push({startIndex:C,score:_,newTrackCount:P}))}const g=this.selectBestClipboardPasteStartIndex(l[0].type,f);if(g===null)return n;const y=Math.max(0,-g),v=Math.max(0,g+l.length-s.length);y>0&&this.createTracksForTypeBoundary(l[0].type,y,"before"),v>0&&this.createTracksForTypeBoundary(l[0].type,v,"after");const b=[...this.getResolvedTracksSnapshot()].filter(C=>{var w;return C.type===((w=l[0])==null?void 0:w.type)}).sort((C,w)=>C.order-w.order),S=g+y;return l.forEach((C,w)=>{const _=b[S+w];_&&n.set(C.key,_.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]}getSelectedTtsAudioClipsForVoiceGeneration(e){if(e.type!=="audio"||!e.ttsSourceTextClipId)return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(n=>n.type==="audio"&&!!n.ttsSourceTextClipId)))return[e];const r=t.filter(n=>n.type==="audio"&&!!n.ttsSourceTextClipId);return r.some(n=>n.id===e.id)?r:[e]}async handleVoiceGenerateAction(e,t,i,r,n){if(t.type==="text"){const c=this.getSelectedTextClipsForVoiceGeneration(t),h=Date.now(),d=c.map((g,y)=>({requestId:`create:${g.id}:${i.id}:${h}:${y}`,sourceTextClipId:g.id,text:g.textContent??g.name??"",voiceId:i.id,followTextUpdates:r,mode:"create"}));e.setPreferredTab("voice");const u=[];if(await this.withHistoryTransaction("generate_voice_from_text_clips",async()=>{const g=await n(d),y=new Map(g.map(v=>[v.requestId,v]));for(const v of d){const b=y.get(v.requestId);if(!b)continue;const S=c.find(P=>P.id===v.sourceTextClipId);if(!S)continue;const C=this.normalizeGeneratedAudioDuration(b.duration),w=S.textContent??S.name??"";this.syncTextClipDurationToAudio(S.id,C);const _=await this.addClip({type:"audio",src:b.audioSrc,name:this.buildGeneratedAudioClipName(b.voiceName),textContent:w,startTime:S.startTime,duration:C,startTimeAtSource:0,endTimeAtSource:C,sourceDuration:C,ttsSourceTextClipId:S.id,ttsVoiceId:b.voiceId,ttsVoiceName:b.voiceName,ttsFollowTextUpdates:r});u.push(_)}if(u.length===0)throw new Error("生成音频失败:未返回音频结果")}),u.length===1){this.scrollToClip(u[0],{selectClip:!0,setCurrentTime:!0});return}const f=u[0]??null;this.scrollToClip(f,{setCurrentTime:!0}),this.setSelection(u,{preferredPrimaryClipId:f});return}if(t.type!=="audio"||!t.ttsSourceTextClipId)return;const s=this.getSelectedTtsAudioClipsForVoiceGeneration(t),o=Date.now(),l=s.map((c,h)=>{const d=this.findClipById(c.ttsSourceTextClipId);if(!d||d.type!=="text")throw new Error("未找到配音关联的文本片段");return{requestId:`replace:${c.id}:${i.id}:${o}:${h}`,sourceTextClipId:d.id,targetAudioClipId:c.id,text:d.textContent??d.name??"",voiceId:i.id,followTextUpdates:r,mode:"replace"}});e.setPreferredTab("voice"),await this.withHistoryTransaction("replace_voice_for_tts_audio_clips",async()=>{const c=await n(l),h=new Map(c.map(u=>[u.requestId,u])),d=new Map;if(l.some(u=>!h.has(u.requestId)))throw new Error("替换音色失败:未返回音频结果");for(const u of l){const f=h.get(u.requestId);if(!f||!u.targetAudioClipId)continue;this.applyGeneratedAudioClipResult(u.targetAudioClipId,u.sourceTextClipId,u.text,f,r),this.relocateClipIfNeeded(u.targetAudioClipId);const g=d.get(u.sourceTextClipId)??0;d.set(u.sourceTextClipId,Math.max(g,f.duration))}d.forEach((u,f)=>{this.syncTextClipDurationToAudio(f,u)}),this.handleClipChange()})}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{O.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){O.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 wr.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return wr.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){gd({clip1:e,clip2:t,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordSplitClip:this.getTimelineHistoryRecorder().recordSplitClip.bind(this.getTimelineHistoryRecorder()),emitClipUpdated:i=>{this.emitEvent("clip_updated",{clip:i})},emitClipAdded:i=>{this.emitEvent("clip_added",{clip:i})},applyEffects:()=>Ai({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=pd(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),O.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){O.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.getTimelineHistoryExecutor().executeUndo(e)}),this.checkTrackDurationChange()}handleActionRedo(e){O.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.getTimelineHistoryExecutor().executeRedo(e)}),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=ou({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){var e,t;this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount}),(t=(e=this.previewSession)==null?void 0:e.setPendingState)==null||t.call(e,this.buildPreviewPendingState())}endSourceLoading(){var e,t;this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount}),(t=(e=this.previewSession)==null?void 0:e.setPendingState)==null||t.call(e,this.buildPreviewPendingState())}handleClipOverlap(e,t,i){var h,d,u,f;O.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const r=this.getTrackCollection();if(!r.findById(t))return;const n=e.type,s=this.trackManager.getTracksByType(n).length+1,o=`${Ju(n)}轨道 ${s}`,l=this.createTrack(n,o);if(!l)return;const c=((d=(h=r.findById(l))==null?void 0:h.getId)==null?void 0:d.call(h))||((f=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:f.call(u))||l;this.moveClipToTrackWithHistorySnapshot(e.id,c,i??null,e),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){O.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"?(O.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(O.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()}getRenderedHeight(){return this.getTimeScaleHeight()+this.calculateTotalHeight()+Vr}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 o of e.items)t.set(o.sourceClipId,this.generateClipId(o.clip.name));const i=this.resolveClipboardPasteTrackAssignments(e,t,this.getCurrentTime()),r=[],n=this.getCurrentTime();if(await this.withHistoryTransaction("paste_clipboard_clips",async()=>{for(const o of e.items){const l=this.buildClipboardPasteClipConfig(o,n,t),c=o.sourceTrackId??`clipboard-orphan:${o.sourceClipId}`,h=i.get(c)??this.resolveClipboardPasteTrackId(o,l,i),d=t.get(o.sourceClipId);if(!d)continue;const u=await this.addClipInternal({...l,id:d,...h?{trackId:h}:{}});(this.getClips().find(g=>g.id===u)??null)&&r.push(u)}}),r.length===0)return!1;const s=e.primaryClipId?t.get(e.primaryClipId)??r[0]??null:r[0]??null;return this.setSelection(r,{preferredPrimaryClipId:s}),!0}deleteSelectedClipsWithHistoryLabel(e){this.resetMultiDragSession();const t=this.selectionStore.getSelectedClipIds();return t.length===0?!1:(this.clearSelection(),this.withHistoryTransaction(e,()=>{for(const i of t)this.removeClip(i)}),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:Ds(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:Ds(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=Xe({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 Wu,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(),getSelectedClips:()=>this.getSelectedClips(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c),u=d?{...d}:null,f=typeof h.textContent=="string"?h.textContent:null;if(n&&(u==null?void 0:u.type)==="text"&&f!==null&&f!==u.textContent&&this.hasVoiceLinkedAudioClipsToRegenerate(c)&&(u==null?void 0:u.type)==="text"){this.withHistoryBoundary("suppressed",()=>{this.updateClip(c,h)}),this.handleClipChange(),this.scheduleVoiceLinkedTextRegeneration(c,u,f,n);return}this.updateClip(c,h),this.handleClipChange()},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 f;const d=new Set(this.getSelectedClipIds()),u=this.getPrimarySelectedClip();d.size===0&&(u!=null&&u.id)&&d.add(u.id),(f=h==null?void 0:h.clip)!=null&&f.id&&d.has(h.clip.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 Xe(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:Nt.name,packageVersion:Nt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=Xe({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={...De},(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}pausePlaybackForAudioSeparation(){var t,i,r;(((i=(t=this.timelineStore)==null?void 0:t.getPlayState)==null?void 0:i.call(t))??((r=this.config)==null?void 0:r.playState))==="playing"&&this.pause()}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;this.pausePlaybackForAudioSeparation();const t=this.getClips().find(c=>c.id===e);if(!t||t.type!=="video")return null;const i=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let r=null;const n=!this.shouldSkipHistoryRecording();if(await this.withHistoryBoundary("suppressed",async()=>{if(r=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:i??void 0}),!r)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:r})}),!r)return null;const s=this.getClips().find(c=>c.id===e),o=this.getClips().find(c=>c.id===r)??null,l=this.resolveTrackIdByClipId(r);return s?(n&&this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,s,o,l),r):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.shouldSkipHistoryRecording();this.withHistoryBoundary("suppressed",()=>{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})});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(n=>n.type==="video"),i=e==="separate"?t.filter(n=>this.canSeparateClipAudio(n.id)):t.filter(n=>this.canRestoreClipAudio(n.id));if(i.length===0)return!1;if(i.length===1){const[n]=i;return e==="separate"?!!await this.separateClipAudio(n.id):this.restoreClipAudio(n.id)}let r=0;return await this.withHistoryTransaction(`selected_clips_audio_${e}`,async()=>{if(e==="restore"){for(const n of i)this.restoreClipAudio(n.id)&&(r+=1);return}for(const n of i)await this.separateClipAudio(n.id)&&(r+=1)}),r>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 O.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(n.status==="noop")return O.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(n.status==="missing_target_track")return O.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var g,y,v;return{targetTrackType:(y=(g=this.getTrackCollection().findById(t))==null?void 0:g.getTrackType)==null?void 0:y.call(g),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},c=r?{...r}:{...n.clip},h=this.cloneTrackSnapshot(s),d=this.cloneTrackSnapshot(o),u=hu({command:{...n,clip:c},trackCollection:this.getTrackCollection()}),f=this.getClips().find(g=>g.id===e)??null;return fd({applied:u,clipId:e,sourceTrackId:s,targetTrackId:o,clipBefore:l,clipAfter:f??l,sourceTrackSnapshot:h,targetTrackSnapshot:d,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>du({notifySelectionChange:this.notifySelectionChange.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),batchDraw:()=>{var g;(g=this.stage)==null||g.batchDraw()},syncPreviewSession:this.syncPreviewSession.bind(this)})})?(this.clearAllTrackDropPreviews(),!0):!1}getTrackTotalDuration(){return Cs(this.getClips())}async getResourceCacheStats(){return this.resourceCacheManager?{enabled:!0,...await this.resourceCacheManager.getStats()}:{enabled:!1,entryCount:0,totalBytes:0,maxTotalBytes:0}}async cleanupResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.cleanupExpired())}async clearResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.clear())}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(),(e=this.resourceCacheManager)==null||e.cleanupExpired().catch(()=>{}),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(t=this.layout)==null||t.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(n=(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 Ms),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new su({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{return e.isFinal?this.withHistoryTransaction("move_selected_clips",()=>this.finalizeMultiDragCrossTrack(t,e)?!0:this.finalizeMultiDragSameTrack(t,e)):(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)}}createMultiDragPlacementContext(e){const t=new Map,i=new Map,r=[...this.getResolvedTracksSnapshot()].sort((n,s)=>(n.order??0)-(s.order??0));for(const n of r){const s=i.get(n.type)??[];s.push(n.id),i.set(n.type,s),t.set(n.id,n.clips.filter(o=>!e.has(o.id)).map(o=>({id:o.id,startTime:o.startTime,duration:o.duration})))}return{occupancyByTrackId:t,orderedTrackIdsByType:i}}doesMultiDragPlacementOverlap(e,t,i){const r=e.occupancyByTrackId.get(t)??[],n=i.startTime+i.duration;return r.some(s=>s.id!==i.id&&i.startTime<s.startTime+s.duration&&n>s.startTime)}reserveMultiDragPlacement(e,t,i){const r=e.occupancyByTrackId.get(t)??[];r.push({id:i.id,startTime:i.startTime,duration:i.duration}),e.occupancyByTrackId.set(t,r)}registerMultiDragPlacementTrack(e,t,i,r,n){const s=e.orderedTrackIdsByType.get(i)??[];if(!s.includes(t)){if(r==="before_track"&&n){const o=s.indexOf(n);o>=0?s.splice(o,0,t):s.unshift(t)}else if(r==="after_track"&&n){const o=s.indexOf(n);o>=0?s.splice(o+1,0,t):s.push(t)}else r==="top_of_type_region"?s.unshift(t):s.push(t);e.orderedTrackIdsByType.set(i,s)}e.occupancyByTrackId.has(t)||e.occupancyByTrackId.set(t,[])}findNearestAvailableTrackForMultiDragPlacement(e,t,i){const r=e.orderedTrackIdsByType.get(t.type)??[],n=r.indexOf(i);if(n===-1)return null;const o=r.map((l,c)=>({trackId:l,index:c,distance:Math.abs(c-n)})).filter(({trackId:l})=>l!==i).sort((l,c)=>{if(l.distance!==c.distance)return l.distance-c.distance;const h=l.index>n?0:1,d=c.index>n?0:1;return h-d}).find(({trackId:l})=>!this.doesMultiDragPlacementOverlap(e,l,t));return(o==null?void 0:o.trackId)??null}resolveMultiDragOverlapTargetTrackId(e,t,i){const r=this.findNearestAvailableTrackForMultiDragPlacement(e,t,i);if(r)return r;const n=this.createTrack(t.type,void 0,"after_track",i);if(n)return this.registerMultiDragPlacementTrack(e,n,t.type,"after_track",i),n;const s=t.type==="audio"?"bottom_of_type_region":"top_of_type_region",o=this.createTrack(t.type,void 0,s);return o?(this.registerMultiDragPlacementTrack(e,o,t.type,s),o):null}commitMultiDragPlacements(e,t,i){const r=[],n=this.createMultiDragPlacementContext(new Set(e.selectedClipIds));for(const s of e.selectedClipIds){const o=e.clips.get(s);if(!o)continue;const l=this.buildMovedClipSnapshot(o.clip,t.deltaTime),c=i(o,l);if(!c)continue;let h=c;if(!(this.doesMultiDragPlacementOverlap(n,c,l)&&(h=this.resolveMultiDragOverlapTargetTrackId(n,l,c),!h))){if(this.reserveMultiDragPlacement(n,h,l),h===o.trackId){if(l.startTime===o.clip.startTime&&l.endTime===o.clip.endTime)continue;this.updateClipPositionSilently(o.trackId,o.clipId,l.startTime),r.push({clipId:o.clipId,previousState:o.clip,newState:l});continue}this.updateClipPositionSilently(o.trackId,o.clipId,l.startTime),this.moveClipToTrackWithHistorySnapshot(o.clipId,h,o.clip,l)}}return r.length>0&&this.getTimelineHistoryRecorder().recordClipUpdate(r[0].newState,void 0,r),!0}finalizeMultiDragSameTrack(e,t){return this.commitMultiDragPlacements(e,t,i=>i.trackId)}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);return o===null?!1:this.commitMultiDragPlacements(e,t,(l,c)=>l.clipId===t.draggedClipId?s:this.resolveMultiDragTargetTrackId(l,o,c))}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 O.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return O.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:e.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};O.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):[]}updateClipPositionSilently(e,t,i){const r=this.getTrackCollection().findById(e),n=r==null?void 0:r.updateClipPosition;n&&this.withHistoryBoundary("suppressed",()=>{n.call(r,t,i,!0)})}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new K.Rect({fill:dn.fill,stroke:dn.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 n=i.getTrackGroup().y(),s=this.resolveTrackRenderHeight(i);if(!(t<n||t>n+s))for(const o of i.getClips()){const l=pe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ye(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 n=i.getTrackGroup().y(),s=this.resolveTrackRenderHeight(i);for(const o of i.getClips()){const l=pe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ye(o.duration,this.getZoomState()),h=n+2,d=s-4,u=l+c,f=h+d,g=e.x+e.width,y=e.y+e.height;l<g&&u>e.x&&h<y&&f>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return _e(e.getTrackType())}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Ue({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,f)=>u.order-f.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=Yr(e),n=Cs(e);if(r!==t){this.lastTrackDuration=r;const o=bs(r);this.setDurationState(o),(s=this.timeline)==null||s.setDuration(o),this.updateViewportLayout()}if(n!==i&&(this.lastReportedTrackDuration=n,this.emitEvent("track_duration_change",{duration:n})),e.length===0&&this.getCurrentTimeState()!==0&&this.setCurrentTime(0),e.length>0){const o=Xt(e);o>0&&this.getCurrentTimeState()>o&&this.setCurrentTime(o)}r===t&&n===i||O.debugLazy("TimelineManager",()=>`Track duration changed: total=${n}ms, extent=${r}ms, timeline=${bs(r)}ms`)}resolveSelectedClipSnapshot(){return Wa({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 au({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);ln(r,n)||this.updateClip(e,{visualTransform:n})}commitPreviewTextFontSize(e,t){const i=this.getClips().find(s=>s.id===e);if(!i||i.type!=="text")return;const r=Me(i.textStyle),n=Math.max(5,Math.min(300,Math.round(t)));r.fontSize!==n&&this.updateClip(e,{textStyle:{...r,fontSize:n}})}commitPreviewTextRotation(e,t){const i=this.getClips().find(s=>s.id===e);if(!i||i.type!=="text")return;const r=Me(i.textStyle),n=Math.round(t);r.rotation!==n&&this.updateClip(e,{textStyle:{...r,rotation:n}})}clearAllTracksAndClips(){this.withHistoryBoundary("reset",()=>{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(),this.clearHistory()})}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=qr;exports.CLIP_LAYER=Za;exports.Clip=Li;exports.ClipConfigPanel=$a;exports.DEFAULT_CLIP_VIEW_STATE=Os;exports.DEFAULT_PREVIEW_ASPECT_RATIO=De;exports.DEFAULT_TEXT_CLIP_STYLE=Bs;exports.DiagnosticsCenter=xa;exports.HistoryManager=Wr;exports.MIN_CLIP_LINE_WIDTH=ii;exports.PREVIEW_ASPECT_RATIO_PRESETS=Ka;exports.TIMELINE_LEFT_PADDING=Te;exports.TIME_SCALE=Qa;exports.TRACK_HEIGHT=Ri;exports.TimeUtils=U;exports.TimelineManager=Qu;exports.Track=Xi;exports.TrackInfoPanel=Na;exports.TrackManager=Ya;exports.ZOOM_ANIMATION=Ja;exports.ZOOM_PRESETS=Re;exports.createClipViewState=Fs;exports.createClipWithViewState=Zr;exports.defaultDarkTheme=Gi;exports.devConsole=O;exports.isAutoPreviewAspectRatioMode=wt;exports.mergeDiagnosticRuntimeState=Pa;exports.normalizePreviewAspectRatio=Xe;exports.normalizePreviewAspectRatioMode=jr;exports.resolveAspectRatioBaselineDimensions=Kr;exports.resolveTextClipStyle=Me;exports.resolveTheme=Hi;
|