@linker-design-plus/timeline-track 2.1.1 → 2.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var go=Object.defineProperty;var fo=(s,e,t)=>e in s?go(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var p=(s,e,t)=>fo(s,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)"},te={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},fe={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},Mt={border:te.scrollbarBorder,thumb:te.scrollbarThumb,hitArea:I.overlayHitArea},wt={fill:I.white,stroke:I.black,text:I.black},Pe={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}`},bn={grip:I.accentPlayheadGrip,shadow:I.overlayShadow},vi={background:I.overlayPreview,text:I.white,actionBackground:I.accentAction,actionText:I.white},ot={border:I.overlayTransformHandle,handleBackground:I.black},Tn={fill:I.overlaySelectionBoxFill,stroke:I.accentSelectionBox},Ci={videoFill:I.overlayVideoDropPreview,videoStroke:I.accentSelectedBorder,audioFill:I.overlayAudioDropPreview,audioStroke:I.accentAudioPreview},wn={line:I.gridLine},qs={fontSize:32,color:"#fff",rotation:0,strokeColor:"#000000",strokeWidth:1,paddingX:4};function De(s){return{...qs,...s??{}}}function js(s){return s.type==="audio"&&typeof s.textContent=="string"&&s.textContent.trim().length>0&&typeof s.ttsVoiceId=="string"&&s.ttsVoiceId.trim().length>0}function Le(s){return s.type==="audio"&&(typeof s.ttsSourceTextClipId=="string"&&s.ttsSourceTextClipId.trim().length>0||js(s))}const Ks={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},Vi={background:te.background,border:te.border,timeTick:te.timeTick,timeText:te.timeText,trackBackground:te.trackBackground,trackSelectedBackground:te.trackSelectedBackground,trackBorder:te.trackBorder,clipBackground:te.clipBackground,clipBorder:te.clipBorder,clipName:te.clipName,clipDuration:te.clipDuration,clipHandle:te.clipHandle,clipSelectedBorder:te.clipSelectedBorder,clipCoverBackground:te.clipCoverBackground,audioClipText:te.audioClipText,audioClipAccent:te.audioClipAccent,playhead:te.playhead,grid:te.grid,snapGuideLineColor:te.snapGuideLineColor,snapGuideLineWidth:1,scrollbarBackground:te.scrollbarBackground,scrollbarBorder:te.scrollbarBorder,scrollbarThumb:te.scrollbarThumb};function Ui(s){return s?{...Vi,...s}:{...Vi}}const an=720,Oe={mode:"auto-first-added-video",width:16,height:9},mo=[{key:"default",label:"默认",aspectRatio:{...Oe}},{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 on(s){return s==="manual"?"manual":"auto-first-added-video"}function xt(s){return on(s)==="auto-first-added-video"}function je(s){return{mode:on(s==null?void 0:s.mode),width:typeof(s==null?void 0:s.width)=="number"&&s.width>0?s.width:Oe.width,height:typeof(s==null?void 0:s.height)=="number"&&s.height>0?s.height:Oe.height}}function ln(s,e=an){const t=Math.max(0,s.width),i=Math.max(0,s.height),r=Math.max(0,e);if(t<=0||i<=0||r<=0)return{width:0,height:0};const n=Math.min(t,i),a=r/n;return{width:Math.round(t*a),height:Math.round(i*a)}}const yo={DEFAULT:1,ACTIVE:2},Me={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Zt=36e5,Rr={SENSITIVITY_FACTOR:.002,CONVERGENCE_THRESHOLD:1e-4},Zs=3e3,Js=450,Qs={ANCHOR_INDEX_WEIGHT:.001},ai={MIN:5,MAX:300},So={DURATION:300,EASING:"easeOutCubic"},vo={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},Te=15,oi=6,Bi={TEXT:25,VIDEO:64,AUDIO:48};function ea(s={}){const e=Object.fromEntries(Object.entries(s).filter(([,t])=>t!==void 0));return{...Ks,...e}}function cn(s,e={}){return{...s,...ea(e)}}function Mr(s){s.disablePictureInPicture=!0,s.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=[],a=Math.max(0,e);let o=Math.floor(a/i)*i,l=0;const c=100;for(let g=o;g<=t&&(n.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MAJOR}),l++,!(l>=c));g+=i);let h=0;const d=400;let u=Math.floor(a/r)*r;for(let g=u;g<=t&&!(Math.abs(g-Math.round(g/i)*i)>.001&&(n.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MINOR}),h++,h>=d));g+=r);return n.sort((g,f)=>g.time-f.time)}static getVideoDuration(e,t={}){const i=()=>new Promise(r=>{const n=document.createElement("video");n.preload="metadata",Mr(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 Co=Math.PI/180;function bo(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const lt=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},M={_global:lt,version:"10.2.0",isBrowser:bo(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return M.angleDeg?s*Co:s},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 M.DD.isDragging},isTransforming(){var s,e;return(e=(s=M.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&e!==void 0?e:!1},isDragReady(){return!!M.DD.node},releaseCanvasOnDestroy:!0,document:lt.document,_injectGlobal(s){typeof lt.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),lt.Konva=s}},oe=s=>{M[s.prototype.getClassName()]=s};M._injectGlobal(M);const To=`Konva.js unsupported environment.
1
+ "use strict";var vo=Object.defineProperty;var Co=(s,e,t)=>e in s?vo(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t;var g=(s,e,t)=>Co(s,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const _={transparent:"transparent",white:"#ffffff",black:"#000000",panelSurface:"#0f0f0f",buttonSurface:"#2a2a2a",inputSurface:"#2d2d2d",clipSurface:"#2e2e2e",videoClipBackground:"#1e5679",textClipBackground:"#604c32",audioClipBackground:"#254428",mediaClipFailedBackground:"#670014",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)"},te={background:_.black,border:_.borderStrong,timeTick:_.textSecondary,timeText:_.textSubtle,trackBackground:_.black,trackSelectedBackground:_.selectedTrackSurface,trackBorder:_.borderStrong,clipBackground:_.clipSurface,clipBorder:_.black,clipName:_.textPrimary,clipDuration:_.textMuted,clipHandle:_.textPrimary,clipSelectedBorder:_.clipSelectedBorder,clipCoverBackground:_.borderStrong,audioClipText:_.textAudio,audioClipAccent:_.audioClipAccent,playhead:_.textPrimary,grid:_.borderStrong,snapGuideLineColor:_.accentSelectedBorder,scrollbarBackground:_.borderStrong,scrollbarBorder:_.borderSubtle,scrollbarThumb:_.borderMedium},me={backgroundColor:"#0f0f0f",borderColor:_.borderStrong,textColor:_.textSecondary,labelColor:_.textHint,inputBackground:_.inputSurface,inputBorder:_.borderMedium,inputFocusBorder:_.accentFocus,buttonBackground:_.inputSurface,buttonBorder:_.borderMedium,buttonActiveBackground:_.accentFocus,buttonActiveBorder:_.accentFocus,buttonActiveText:_.white},be={background:_.panelSurface,border:_.borderStrong,text:_.textPrimary,buttonBackground:_.buttonSurface,buttonHover:"#3a3a3a",buttonDanger:_.accentDanger},Lt={border:te.scrollbarBorder,thumb:te.scrollbarThumb,hitArea:_.overlayHitArea},wt={fill:_.white,stroke:_.black,text:_.black},xe={tabBarBackground:_.buttonSurface,actionBarBackground:_.buttonSurface,activeTabBackground:_.activeTabBackground,activeTabText:_.white,inactiveTabText:_.textInactive,sliderThumbShadow:`0 8px 20px ${_.sliderThumbShadow}`,sliderThumbInnerShadow:`inset 0 1px 1px ${_.sliderThumbInnerShadow}`},wn={grip:_.accentPlayheadGrip,shadow:_.overlayShadow},Ue={background:_.overlayPreview,text:_.white,failedBackground:_.mediaClipFailedBackground,failedText:_.white,actionBackground:_.accentAction,actionText:_.white},ot={border:_.overlayTransformHandle,handleBackground:_.black},Pn={fill:_.overlaySelectionBoxFill,stroke:_.accentSelectionBox},Ti={videoFill:_.overlayVideoDropPreview,videoStroke:_.accentSelectedBorder,audioFill:_.overlayAudioDropPreview,audioStroke:_.accentAudioPreview},xn={line:_.gridLine},Js={fontSize:32,color:"#fff",rotation:0,strokeColor:"#000000",strokeWidth:1,paddingX:4};function De(s){return{...Js,...s??{}}}function Qs(s){return s.type==="audio"&&typeof s.textContent=="string"&&s.textContent.trim().length>0&&typeof s.ttsVoiceId=="string"&&s.ttsVoiceId.trim().length>0}function Le(s){return s.type==="audio"&&(typeof s.ttsSourceTextClipId=="string"&&s.ttsSourceTextClipId.trim().length>0||Qs(s))}const ea={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},Wi={background:te.background,border:te.border,timeTick:te.timeTick,timeText:te.timeText,trackBackground:te.trackBackground,trackSelectedBackground:te.trackSelectedBackground,trackBorder:te.trackBorder,clipBackground:te.clipBackground,clipBorder:te.clipBorder,clipName:te.clipName,clipDuration:te.clipDuration,clipHandle:te.clipHandle,clipSelectedBorder:te.clipSelectedBorder,clipCoverBackground:te.clipCoverBackground,audioClipText:te.audioClipText,audioClipAccent:te.audioClipAccent,playhead:te.playhead,grid:te.grid,snapGuideLineColor:te.snapGuideLineColor,snapGuideLineWidth:1,scrollbarBackground:te.scrollbarBackground,scrollbarBorder:te.scrollbarBorder,scrollbarThumb:te.scrollbarThumb};function Yi(s){return s?{...Wi,...s}:{...Wi}}const ln=720,Be={mode:"auto-first-added-video",width:16,height:9},To=[{key:"default",label:"默认",aspectRatio:{...Be}},{key:"9:16",label:"9:16",aspectRatio:{mode:"manual",width:9,height:16}},{key:"16:9",label:"16:9",aspectRatio:{mode:"manual",width:16,height:9}},{key:"3:4",label:"3:4",aspectRatio:{mode:"manual",width:3,height:4}},{key:"4:3",label:"4:3",aspectRatio:{mode:"manual",width:4,height:3}}];function cn(s){return s==="manual"?"manual":"auto-first-added-video"}function _t(s){return cn(s)==="auto-first-added-video"}function je(s){return{mode:cn(s==null?void 0:s.mode),width:typeof(s==null?void 0:s.width)=="number"&&s.width>0?s.width:Be.width,height:typeof(s==null?void 0:s.height)=="number"&&s.height>0?s.height:Be.height}}function hn(s,e=ln){const t=Math.max(0,s.width),i=Math.max(0,s.height),r=Math.max(0,e);if(t<=0||i<=0||r<=0)return{width:0,height:0};const n=Math.min(t,i),a=r/n;return{width:Math.round(t*a),height:Math.round(i*a)}}const bo={DEFAULT:1,ACTIVE:2},Me={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Jt=36e5,Lr={SENSITIVITY_FACTOR:.002,CONVERGENCE_THRESHOLD:1e-4},ta=3e3,ia=450,ra={ANCHOR_INDEX_WEIGHT:.001},li={MIN:5,MAX:300},ko={DURATION:300,EASING:"easeOutCubic"},wo={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},ke=15,ci=6,Ni={TEXT:25,VIDEO:64,AUDIO:48};function na(s={}){const e=Object.fromEntries(Object.entries(s).filter(([,t])=>t!==void 0));return{...ea,...e}}function dn(s,e={}){return{...s,...na(e)}}function Br(s){s.disablePictureInPicture=!0,s.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=[],a=Math.max(0,e);let o=Math.floor(a/i)*i,l=0;const c=100;for(let p=o;p<=t&&(n.push({time:this.secondsToMs(p),type:this.TICK_TYPE_MAJOR}),l++,!(l>=c));p+=i);let h=0;const d=400;let u=Math.floor(a/r)*r;for(let p=u;p<=t&&!(Math.abs(p-Math.round(p/i)*i)>.001&&(n.push({time:this.secondsToMs(p),type:this.TICK_TYPE_MINOR}),h++,h>=d));p+=r);return n.sort((p,f)=>p.time-f.time)}static getVideoDuration(e,t={}){const i=()=>new Promise(r=>{const n=document.createElement("video");n.preload="metadata",Br(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()}}g(U,"TICK_TYPE_MAJOR","major"),g(U,"TICK_TYPE_MINOR","minor");const Po=Math.PI/180;function xo(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const lt=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},M={_global:lt,version:"10.2.0",isBrowser:xo(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return M.angleDeg?s*Po:s},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 M.DD.isDragging},isTransforming(){var s,e;return(e=(s=M.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&e!==void 0?e:!1},isDragReady(){return!!M.DD.node},releaseCanvasOnDestroy:!0,document:lt.document,_injectGlobal(s){typeof lt.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),lt.Konva=s}},oe=s=>{M[s.prototype.getClassName()]=s};M._injectGlobal(M);const _o=`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,26 +11,26 @@ or
11
11
 
12
12
  bash: npm install skia-canvas
13
13
  js: import "konva/skia-backend";
14
- `,kn=()=>{if(typeof document>"u")throw new Error(To)};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,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=T._getRotation(l.rotation),l}}const wo="[object Array]",ko="[object Number]",Po="[object String]",xo="[object Boolean]",_o=Math.PI/180,Ao=180/Math.PI,Dt="#",Io="",Eo="0",Ro="Konva warning: ",Pn="Konva error: ",Mo="rgb(",hr={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]},Do=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let bi=[],Lt=null;const Lo=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},T={_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)===wo},_isNumber(s){return Object.prototype.toString.call(s)===ko&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===Po},_isBoolean(s){return Object.prototype.toString.call(s)===xo},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){bi.push(s),bi.length===1&&Lo(function(){const e=bi;bi=[],e.forEach(function(t){t()})})},createCanvasElement(){kn();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return kn(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,e){const t=T.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(Dt,Io);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=Eo+s;return Dt+s},isCanvasFarblingActive(){if(Lt!==null)return Lt;if(typeof document>"u")return Lt=!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 Lt=i,this.releaseCanvas(s),Lt},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),Dt+this._rgbToHex(s,e,t)},getSnappedHexColor(s){const e=this._hexToRgb(s);return Dt+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 hr?(e=hr[s],{r:e[0],g:e[1],b:e[2]}):s[0]===Dt?this._hexToRgb(s.substring(1)):s.substr(0,4)===Mo?(e=Do.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",T._namedColorToRBA(s)||T._hex3ColorToRGBA(s)||T._hex4ColorToRGBA(s)||T._hex6ColorToRGBA(s)||T._hex8ColorToRGBA(s)||T._rgbColorToRGBA(s)||T._rgbaColorToRGBA(s)||T._hslColorToRGBA(s)},_namedColorToRBA(s){const e=hr[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*_o},radToDeg(s){return s*Ao},_degToRad(s){return T.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),T.degToRad(s)},_radToDeg(s){return T.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),T.radToDeg(s)},_getRotation(s){return M.angleDeg?T.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){M.showWarnings&&console.warn(Ro+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=T.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=T._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=T._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||T._isElement(s[t]))if(e.configurable)delete s[t];else return null;else if(T._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){M.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 g;typeof r=="number"?g=r:g=n<r.length?r[n]:0,g=i*Math.cos(Math.PI/t)*Math.min(1,g/i*2);const y={x:c.x/d,y:c.y/d},v={x:h.x/u,y:h.y/u},b={x:o.x-y.x*g,y:o.y-y.y*g},S={x:o.x+v.x*g,y:o.y+v.y*g};n===0?s.moveTo(b.x,b.y):s.lineTo(b.x,b.y),s.arcTo(o.x,o.y,S.x,S.y,g)}}};function Oo(s){const e=[],t=s.length,i=T;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 xn=",",Bo="(",Fo=")",Go="([",No="])",Ho=";",$o="()",zo="=",_n=["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"],Vo=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],Uo=100;let Ti=null;function An(){if(Ti!==null)return Ti;try{const e=T.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(Ti=!1,!1)}catch{return Ti=!1,!1}}class rr{constructor(e){this.canvas=e,M.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+=$o:T._isArray(c[0])?n+=Go+c.join(xn)+No:(t&&(c=c.map(h=>typeof h=="number"?Math.floor(h):h)),n+=Bo+c.join(xn)+Fo)):(n+=o.property,e||(n+=zo+o.val)),n+=Ho;return n}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=Uo&&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=_n.length,i=this.setAttr,r,n;const a=function(o){let l=e[o],c;e[o]=function(){return n=Oo(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(_n[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)}}Vo.forEach(function(s){Object.defineProperty(rr.prototype,s,{get(){return this._context[s]},set(e){this._context[s]=e}})});class Wo extends rr{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 Yo extends rr{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 wi;function Xo(){if(wi)return wi;const s=T.createCanvasElement(),e=s.getContext("2d");return wi=function(){const t=M._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),T.releaseCanvas(s),wi}class hn{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||M.pixelRatio||Xo();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 Ke extends hn{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new Wo(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class dn extends hn{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new Yo(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=T._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,M._mouseListenClick=!1,M._touchListenClick=!1,M._pointerListenClick=!1,t.dragStatus="stopped");const a=t.node.getLayer()||t.node instanceof M.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)})}};M.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 et(s){return T._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||T._isBoolean(s)?s:Object.prototype.toString.call(s)}function ta(s){return s>255?255:s<0?0:Math.round(s)}function R(){if(M.isUnminified)return function(s,e){return T._isNumber(s)||T.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),s}}function nr(s){if(M.isUnminified)return function(e,t){let i=T._isNumber(e),r=T._isArray(e)&&e.length==s;return!i&&!r&&T.warn(et(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+s+")"),e}}function un(){if(M.isUnminified)return function(s,e){return T._isNumber(s)||s==="auto"||T.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),s}}function pt(){if(M.isUnminified)return function(s,e){return T._isString(s)||T.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),s}}function ia(){if(M.isUnminified)return function(s,e){const t=T._isString(s),i=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return t||i||T.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),s}}function qo(){if(M.isUnminified)return function(s,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&s instanceof t||(T._isArray(s)?s.forEach(function(i){T._isNumber(i)||T.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):T.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),s}}function Ie(){if(M.isUnminified)return function(s,e){return s===!0||s===!1||T.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),s}}function jo(s){if(M.isUnminified)return function(e,t){return e==null||T.isObject(e)||T.warn(et(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+s),e}}const Ot="get",Bt="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=Ot+T._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=Bt+T._capitalize(e);s.prototype[r]||m.overWriteSetter(s,e,t,i)},overWriteSetter(s,e,t,i){const r=Bt+T._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=T._capitalize,o=Ot+a(e),l=Bt+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=jo(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=T._capitalize(e),i=Bt+t,r=Ot+t;s.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[r]()}},addDeprecatedGetterSetter(s,e,t,i){T.error("Adding deprecated "+e);const r=Ot+T._capitalize(e),n=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[r]=function(){T.error(n);const a=this.attrs[e];return a===void 0?t:a},m.addSetter(s,e,i,function(){T.error(n)}),m.addOverloadedGetterSetter(s,e)},backCompat(s,e){T.each(e,function(t,i){const r=s.prototype[i],n=Ot+T._capitalize(t),a=Bt+T._capitalize(t);function o(){r.apply(this,arguments),T.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 Ko(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=M.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=M.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=M.Filters;l&&l.Contrast&&l.Contrast.call(this,a)}}case"grayscale":return function(n){const a=M.Filters;a&&a.Grayscale&&a.Grayscale.call(this,n)};case"sepia":return function(n){const a=M.Filters;a&&a.Sepia&&a.Sepia.call(this,n)};case"invert":return function(n){const a=M.Filters;a&&a.Invert&&a.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 Fi="absoluteOpacity",In="allEventListeners",He="absoluteTransform",En="absoluteScale",nt="canvas",Zo="Change",Jo="children",Qo="konva",Dr="listening",el="mouseenter",tl="mouseleave",il="pointerenter",rl="pointerleave",nl="touchenter",sl="touchleave",Rn="set",Mn="Shape",Gi=" ",Dn="stage",Xe="transform",al="Stage",Lr="visible",ol=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Gi);let ll=1;class E{constructor(e){this._id=ll++,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===Xe||e===He)&&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===Xe||e===He)&&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(Gi);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(nt)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===He&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(nt)){const{scene:e,filter:t,hit:i}=this._cache.get(nt);T.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(nt)}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){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,g=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=c*2+u,n+=c*2+g,o-=c,l-=c;const f=new Ke({pixelRatio:a,width:r,height:n}),y=new Ke({pixelRatio:a,width:0,height:0,willReadFrequently:!0}),v=new dn({pixelRatio:d,width:r,height:n}),b=f.getContext(),S=v.getContext(),C=new Ke({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(l),pixelRatio:f.pixelRatio}),w=C.getContext();return v.isCache=!0,f.isCache=!0,this._cache.delete(nt),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(f.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(Fi),this._clearSelfAndDescendantCache(En),this.drawScene(f,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(nt,{scene:f,filter:y,hit:v,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(nt)}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"&&An(),typeof e[u]!="string"||!An()){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=Ko(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(In),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Gi);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(Gi),r=i.length,n,a,o,l,c,h;if(this._cache&&this._cache.delete(In),!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=T.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(He),this._clearSelfAndDescendantCache(Fi),this._clearSelfAndDescendantCache(En),this._clearSelfAndDescendantCache(Dn),this._clearSelfAndDescendantCache(Lr),this._clearSelfAndDescendantCache(Dr)}_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!==Jo&&(i=Rn+T._capitalize(t),T._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(Dr,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(Lr,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&&!M.hitOnDragEnabled&&(r||M.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!==Mn&&(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!==al&&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(Xe),this._clearSelfAndDescendantCache(He)),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,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(Xe);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(Xe),this._clearSelfAndDescendantCache(He),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 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(Fi,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=T.isObject(i)&&!T._isPlainObject(i)&&!T._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 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(Dn,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(He,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(He)||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,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(Xe,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get(Xe)||new Se;i.reset();const r=this.x(),n=this.y(),a=M.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=T.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(Qo)<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 Ke({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 Ke({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():M.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+Zo,{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[Rn+T._capitalize(e)];return T._isFunction(i)?i.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(M.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===Mn&&(t.target=this);const r=[el,tl,il,rl,nl,sl];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: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)||M.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,a,o;t&&(e.attrs.container=t),M[i]||(T.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=M[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,ol,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(Xe),this._clearSelfAndDescendantCache(He)});E.prototype.on.call(E.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(Lr)});E.prototype.on.call(E.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(Dr)});E.prototype.on.call(E.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Fi)});const ie=m.addGetterSetter;ie(E,"zIndex");ie(E,"absolutePosition");ie(E,"position");ie(E,"x",0,R());ie(E,"y",0,R());ie(E,"globalCompositeOperation","source-over",pt());ie(E,"opacity",1,R());ie(E,"name","",pt());ie(E,"id","",pt());ie(E,"rotation",0,R());m.addComponentsGetterSetter(E,"scale",["x","y"]);ie(E,"scaleX",1,R());ie(E,"scaleY",1,R());m.addComponentsGetterSetter(E,"skew",["x","y"]);ie(E,"skewX",0,R());ie(E,"skewY",0,R());m.addComponentsGetterSetter(E,"offset",["x","y"]);ie(E,"offsetX",0,R());ie(E,"offsetY",0,R());ie(E,"dragDistance",void 0,R());ie(E,"width",0,R());ie(E,"height",0,R());ie(E,"listening",!0,Ie());ie(E,"preventDefault",!0,Ie());ie(E,"filters",void 0,function(s){return this._filterUpToDate=!1,s});ie(E,"visible",!0,Ie());ie(E,"transformsEnabled","all",pt());ie(E,"size");ie(E,"dragBoundFunc");ie(E,"draggable",!1,Ie());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(),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 g=this.getAbsoluteTransform(i);let f=g.getMatrix();a.transform(f[0],f[1],f[2],f[3],f[4],f[5]),a.beginPath();let y;if(c)y=c.call(this,a,this);else{const v=this.clipX(),b=this.clipY();a.rect(v||0,b||0,o,l)}a.clip.apply(a,y),f=g.copy().invert().getMatrix(),a.transform(f[0],f[1],f[2],f[3],f[4],f[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(g){g[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(g){if(!g.visible())return;const f=g.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});f.width===0&&f.height===0||(n===void 0?(n=f.x,a=f.y,o=f.x+f.width,l=f.y+f.height):(n=Math.min(n,f.x),a=Math.min(a,f.y),o=Math.max(o,f.x+f.width),l=Math.max(l,f.y+f.height)))});const d=this.find("Shape");let u=!1;for(let g=0;g<d.length;g++)if(d[g]._isVisible(this)){u=!0;break}return u&&n!==void 0?c={x:n,y:a,width:o-n,height:l-a}: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 li=new Map,ra=M._global.PointerEvent!==void 0;function dr(s){return li.get(s)}function pn(s){return{evt:s,pointerId:s.pointerId}}function na(s,e){return li.get(s)===e}function sa(s,e){Jt(s),e.getStage()&&(li.set(s,e),ra&&e._fire("gotpointercapture",pn(new PointerEvent("gotpointercapture"))))}function Jt(s,e){const t=li.get(s);if(!t)return;const i=t.getStage();i&&i.content,li.delete(s),ra&&t._fire("lostpointercapture",pn(new PointerEvent("lostpointercapture")))}const cl="Stage",hl="string",Ln="px",dl="mouseout",aa="mouseleave",oa="mouseover",la="mouseenter",ca="mousemove",ha="mousedown",da="mouseup",Ut="pointermove",Wt="pointerdown",kt="pointerup",Yt="pointercancel",ul="lostpointercapture",ki="pointerout",Xt="pointerleave",Pi="pointerover",xi="pointerenter",Or="contextmenu",ua="touchstart",pa="touchend",ga="touchmove",fa="touchcancel",Br="wheel",pl=5,gl=[[la,"_pointerenter"],[ha,"_pointerdown"],[ca,"_pointermove"],[da,"_pointerup"],[aa,"_pointerleave"],[ua,"_pointerdown"],[ga,"_pointermove"],[pa,"_pointerup"],[fa,"_pointercancel"],[oa,"_pointerover"],[Br,"_wheel"],[Or,"_contextmenu"],[Wt,"_pointerdown"],[Ut,"_pointermove"],[kt,"_pointerup"],[Yt,"_pointercancel"],[Xt,"_pointerleave"],[ul,"_lostpointercapture"]],ur={mouse:{[ki]:dl,[Xt]:aa,[Pi]:oa,[xi]:la,[Ut]:ca,[Wt]:ha,[kt]:da,[Yt]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[ki]:"touchout",[Xt]:"touchleave",[Pi]:"touchover",[xi]:"touchenter",[Ut]:ga,[Wt]:ua,[kt]:pa,[Yt]:fa,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[ki]:ki,[Xt]:Xt,[Pi]:Pi,[xi]:xi,[Ut]:Ut,[Wt]:Wt,[kt]:kt,[Yt]:Yt,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},qt=s=>s.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",St=s=>{const e=qt(s);if(e==="pointer")return M.pointerEventsEnabled&&ur.pointer;if(e==="touch")return ur.touch;if(e==="mouse")return ur.mouse};function On(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&T.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const fl="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 sr extends ve{constructor(e){super(On(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",()=>{On(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===hl){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=Qt.indexOf(this);return t>-1&&Qt.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(fl),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 Ke({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+Ln,this.content.style.height=t+Ln),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>pl&&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(),M.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return na(e,this)}setPointerCapture(e){sa(e,this)}releaseCapture(e){Jt(e)}getLayers(){return this.children}_bindContentEvents(){M.isBrowser&&gl.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=St(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=St(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=St(e.type),i=qt(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(i),n=!(M.isDragging()||M.isTransforming())||M.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=St(e.type),i=qt(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(n=>{const a=this.getIntersection(n);if(Z.justDragged=!1,M["_"+i+"ListenClick"]=!0,!a||!a.isListening()){this[i+"ClickStartShape"]=void 0;return}M.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=St(e.type),i=qt(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(M.isDragging()&&Z.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(M.isDragging()||M.isTransforming())||M.hitOnDragEnabled))return;const a={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(c=>{const h=dr(c.id)||this.getIntersection(c),d=c.id,u={evt:e,pointerId:d},g=l!==h;if(g&&l&&(l._fireAndBubble(t.pointerout,{...u},h),l._fireAndBubble(t.pointerleave,{...u},h)),h){if(a[h._id])return;a[h._id]=!0}h&&h.isListening()?(o=!0,g&&(h._fireAndBubble(t.pointerover,{...u},l),h._fireAndBubble(t.pointerenter,{...u},l),this[i+"targetShape"]=h),h._fireAndBubble(t.pointermove,{...u})):l&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:d}),this[i+"targetShape"]=null)}),o||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=St(e.type),i=qt(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=dr(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;M["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):Z.justDragged||(M["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){M["_"+i+"InDblClickWindow"]=!1},M.dblClickWindow),c&&c.isListening()?(o=!0,this[i+"ClickEndShape"]=c,c._fireAndBubble(t.pointerup,{...d}),M["_"+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),M["_"+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}),M["_"+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(Or,{evt:e}):this._fire(Or,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Br,{evt:e}):this._fire(Br,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=dr(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(kt,pn(e)),Jt(e.pointerId)}_lostpointercapture(e){Jt(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 Ke({width:this.width(),height:this.height()}),this.bufferHitCanvas=new dn({pixelRatio:1,width:this.width(),height:this.height()}),!M.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}}sr.prototype.nodeType=cl;oe(sr);m.addGetterSetter(sr,"container");M.isBrowser&&document.addEventListener("visibilitychange",()=>{Qt.forEach(s=>{s.batchDraw()})});const ma="hasShadow",ya="shadowRGBA",Sa="patternImage",va="linearGradient",Ca="radialGradient";let _i;function pr(){return _i||(_i=T.createCanvasElement().getContext("2d"),_i)}const ei={};function ml(s){const e=this.attrs.fillRule;e?s.fill(e):s.fill()}function yl(s){s.stroke()}function Sl(s){const e=this.attrs.fillRule;e?s.fill(e):s.fill()}function vl(s){s.stroke()}function Cl(){this._clearCache(ma)}function bl(){this._clearCache(ya)}function Tl(){this._clearCache(Sa)}function wl(){this._clearCache(va)}function kl(){this._clearCache(Ca)}class _ extends E{constructor(e){super(e);let t,i=0;for(;t=T.getHitColor(),!(t&&!(t in ei));)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,ei[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(ma,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(Sa,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=pr().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new Se;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(M.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(va,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=pr(),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(Ca,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=pr(),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(ya,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 ei[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){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,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,g=d?this.shadowOffsetY():0,f=c+Math.abs(u),y=h+Math.abs(g),v=d&&this.shadowBlur()||0,b=f+v*2,S=y+v*2,C={width:b,height:S,x:-(l/2+v)+Math.min(u,0)+a.x,y:-(l/2+v)+Math.min(g,0)+a.y};return r?C:this._transformedRect(C,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,g=u.getContext();i?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,u.width,u.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const f=this.getAbsoluteTransform(t).getMatrix();g.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.call(this,g,this),g.restore();const y=u.pixelRatio;c&&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||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){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=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 na(e,this)}setPointerCapture(e){sa(e,this)}releaseCapture(e){Jt(e)}}_.prototype._fillFunc=ml;_.prototype._strokeFunc=yl;_.prototype._fillFuncHit=Sl;_.prototype._strokeFuncHit=vl;_.prototype._centroid=!1;_.prototype.nodeType="Shape";oe(_);_.prototype.eventListeners={};_.prototype.on.call(_.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Cl);_.prototype.on.call(_.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",bl);_.prototype.on.call(_.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Tl);_.prototype.on.call(_.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",wl);_.prototype.on.call(_.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",kl);m.addGetterSetter(_,"stroke",void 0,ia());m.addGetterSetter(_,"strokeWidth",2,R());m.addGetterSetter(_,"fillAfterStrokeEnabled",!1);m.addGetterSetter(_,"hitStrokeWidth","auto",un());m.addGetterSetter(_,"strokeHitEnabled",!0,Ie());m.addGetterSetter(_,"perfectDrawEnabled",!0,Ie());m.addGetterSetter(_,"shadowForStrokeEnabled",!0,Ie());m.addGetterSetter(_,"lineJoin");m.addGetterSetter(_,"lineCap");m.addGetterSetter(_,"miterLimit");m.addGetterSetter(_,"sceneFunc");m.addGetterSetter(_,"hitFunc");m.addGetterSetter(_,"dash");m.addGetterSetter(_,"dashOffset",0,R());m.addGetterSetter(_,"shadowColor",void 0,pt());m.addGetterSetter(_,"shadowBlur",0,R());m.addGetterSetter(_,"shadowOpacity",1,R());m.addComponentsGetterSetter(_,"shadowOffset",["x","y"]);m.addGetterSetter(_,"shadowOffsetX",0,R());m.addGetterSetter(_,"shadowOffsetY",0,R());m.addGetterSetter(_,"fillPatternImage");m.addGetterSetter(_,"fill",void 0,ia());m.addGetterSetter(_,"fillPatternX",0,R());m.addGetterSetter(_,"fillPatternY",0,R());m.addGetterSetter(_,"fillLinearGradientColorStops");m.addGetterSetter(_,"strokeLinearGradientColorStops");m.addGetterSetter(_,"fillRadialGradientStartRadius",0);m.addGetterSetter(_,"fillRadialGradientEndRadius",0);m.addGetterSetter(_,"fillRadialGradientColorStops");m.addGetterSetter(_,"fillPatternRepeat","repeat");m.addGetterSetter(_,"fillEnabled",!0);m.addGetterSetter(_,"strokeEnabled",!0);m.addGetterSetter(_,"shadowEnabled",!0);m.addGetterSetter(_,"dashEnabled",!0);m.addGetterSetter(_,"strokeScaleEnabled",!0);m.addGetterSetter(_,"fillPriority","color");m.addComponentsGetterSetter(_,"fillPatternOffset",["x","y"]);m.addGetterSetter(_,"fillPatternOffsetX",0,R());m.addGetterSetter(_,"fillPatternOffsetY",0,R());m.addComponentsGetterSetter(_,"fillPatternScale",["x","y"]);m.addGetterSetter(_,"fillPatternScaleX",1,R());m.addGetterSetter(_,"fillPatternScaleY",1,R());m.addComponentsGetterSetter(_,"fillLinearGradientStartPoint",["x","y"]);m.addComponentsGetterSetter(_,"strokeLinearGradientStartPoint",["x","y"]);m.addGetterSetter(_,"fillLinearGradientStartPointX",0);m.addGetterSetter(_,"strokeLinearGradientStartPointX",0);m.addGetterSetter(_,"fillLinearGradientStartPointY",0);m.addGetterSetter(_,"strokeLinearGradientStartPointY",0);m.addComponentsGetterSetter(_,"fillLinearGradientEndPoint",["x","y"]);m.addComponentsGetterSetter(_,"strokeLinearGradientEndPoint",["x","y"]);m.addGetterSetter(_,"fillLinearGradientEndPointX",0);m.addGetterSetter(_,"strokeLinearGradientEndPointX",0);m.addGetterSetter(_,"fillLinearGradientEndPointY",0);m.addGetterSetter(_,"strokeLinearGradientEndPointY",0);m.addComponentsGetterSetter(_,"fillRadialGradientStartPoint",["x","y"]);m.addGetterSetter(_,"fillRadialGradientStartPointX",0);m.addGetterSetter(_,"fillRadialGradientStartPointY",0);m.addComponentsGetterSetter(_,"fillRadialGradientEndPoint",["x","y"]);m.addGetterSetter(_,"fillRadialGradientEndPointX",0);m.addGetterSetter(_,"fillRadialGradientEndPointY",0);m.addGetterSetter(_,"fillPatternRotation",0);m.addGetterSetter(_,"fillRule",void 0,pt());m.backCompat(_,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Pl="beforeDraw",xl="draw",ba=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],_l=ba.length;class gt extends ve{constructor(e){super(e),this.canvas=new Ke,this.hitCanvas=new dn({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<_l;r++){const n=ba[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=T.getHitColorKey(i[0],i[1],i[2]),a=ei[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(Pl,{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),ve.prototype.drawScene.call(this,n,t,i),this._fire(xl,{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()}}gt.prototype.nodeType="Layer";oe(gt);m.addGetterSetter(gt,"imageSmoothingEnabled",!0);m.addGetterSetter(gt,"clearBeforeDraw",!0);m.addGetterSetter(gt,"hitGraphEnabled",!0,Ie());class gn extends gt{constructor(e){super(e),this.listening(!1),T.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}gn.prototype.nodeType="FastLayer";oe(gn);class At extends ve{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&T.throw("You may only add groups and shapes to groups.")}}At.prototype.nodeType="Group";oe(At);const gr=function(){return lt.performance&&lt.performance.now?function(){return lt.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:gr(),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=gr(),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(gr());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(),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 Al={node:1,duration:1,easing:1,onFinish:1,yoyo:1},Il=1,Bn=2,Fn=3,Gn=["fill","stroke","shadowColor"];let El=0;class Rl{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=Bn,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Fn,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===Bn?this.setTime(e):this.state===Fn&&this.setTime(this.duration-e)}pause(){this.state=Il,this.fire("onPause")}getTimer(){return new Date().getTime()}}class re{constructor(e){const t=this,i=e.node,r=i._id,n=e.easing||ti.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=El++;const c=i.getLayer()||(i instanceof M.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 Rl(l,function(h){t._tweenFunc(h)},n,0,1,o*1e3,a),this._addListeners(),re.attrs[r]||(re.attrs[r]={}),re.attrs[r][this._id]||(re.attrs[r][this._id]={}),re.tweens[r]||(re.tweens[r]={});for(l in e)Al[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=re.tweens[r][e];h&&delete re.attrs[r][h][e];let d=i.getAttr(e);if(T._isArray(t))if(n=[],a=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<a;u++)if(u%2===0)n.push(t[u]-d[u]);else{const g=T.colorToRGBA(d[u]);c=T.colorToRGBA(t[u]),d[u]=g,n.push({r:c.r-g.r,g:c.g-g.g,b:c.b-g.b,a:c.a-g.a})}else for(let u=0;u<a;u++)n.push(t[u]-d[u]);else Gn.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;re.attrs[r][this._id][e]={start:d,diff:n,end:t,trueEnd:o,trueStart:l},re.tweens[r][e]=this._id}_tweenFunc(e){const t=this.node,i=re.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,T._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 Gn.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=re.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=re.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=re.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const r in i)delete re.tweens[e][r];delete re.attrs[e][t],re.tweens[e]&&(Object.keys(re.tweens[e]).length===0&&delete re.tweens[e],Object.keys(re.attrs[e]).length===0&&delete re.attrs[e])}}re.attrs={};re.tweens={};E.prototype.to=function(s){const e=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),e&&e()},new re(s).play()};const ti={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-ti.BounceEaseOut(i-s,0,t,i)+e},BounceEaseInOut(s,e,t,i){return s<i/2?ti.BounceEaseIn(s*2,0,t,i)*.5+e:ti.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}},Nn=T._assign(M,{Util:T,Transform:Se,Node:E,Container:ve,Stage:sr,stages:Qt,Layer:gt,FastLayer:gn,Group:At,DD:Z,Shape:_,shapes:ei,Animation:we,Tween:re,Easings:ti,Context:rr,Canvas:hn});class $e extends _{_sceneFunc(e){const t=M.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=M.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}}}$e.prototype._centroid=!0;$e.prototype.className="Arc";$e.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];oe($e);m.addGetterSetter($e,"innerRadius",0,R());m.addGetterSetter($e,"outerRadius",0,R());m.addGetterSetter($e,"angle",0,R());m.addGetterSetter($e,"clockwise",!1,Ie());function Fr(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),g=t+h*(r-s),f=i+h*(n-e);return[d,u,g,f]}function Hn(s,e){const t=s.length,i=[];for(let r=2;r<t-2;r+=2){const n=Fr(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 Ml(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 ze extends _{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),i=t.length,r=this.tension(),n=this.closed(),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():Hn(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=Fr(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),n=Fr(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),a=Hn(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],...Ml(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}}}ze.prototype.className="Line";ze.prototype._attrsAffectingSize=["points","bezier","tension"];oe(ze);m.addGetterSetter(ze,"closed",!1);m.addGetterSetter(ze,"bezier",!1);m.addGetterSetter(ze,"tension",0,R());m.addGetterSetter(ze,"points",[],qo());const Dl=[[],[],[-.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]],Ll=[[],[],[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]],Ol=[[1],[1,1],[1,2,1],[1,3,3,1]],$n=(s,e,t)=>{let i,r;const a=t/2;i=0;for(let o=0;o<20;o++)r=a*Dl[20][o]+a,i+=Ll[20][o]*Bl(s,e,r);return a*i},zn=(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,g=d-h*h,f=u*u+g>0?Math.sqrt(u*u+g):0,y=h*h+g>0?Math.sqrt(h*h+g):0,v=h+Math.sqrt(h*h+g)!==0?g*Math.log(Math.abs((u+f)/(h+y))):0;return Math.sqrt(o)/2*(u*f-h*y+v)};function Bl(s,e,t){const i=Gr(1,t,s),r=Gr(1,t,e),n=i*i+r*r;return Math.sqrt(n)}const Gr=(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+=Ol[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 Gr(s-1,e,r)}},Vn=(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 ne extends _{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=ne.parsePathData(this.data()),this.pathLength=ne.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],g=a[6],f=a[7],y=c>h?c:h,v=c>h?1:c/h,b=c>h?h/c:1;e.translate(o,l),e.rotate(g),e.scale(v,b),e.arc(0,0,y,d,d+u,1-f),e.scale(1/v,1/b),e.rotate(-g),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const c=l.points[4],h=l.points[5],d=l.points[4]+h;let u=Math.PI/180;if(Math.abs(c-d)<u&&(u=Math.abs(c-d)),h<0)for(let g=c-u;g>d;g-=u){const f=ne.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}else for(let g=c+u;g<d;g+=u){const f=ne.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}}else if(l.command==="C")for(let c=0;c<=1;c+=.01){const h=ne.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 ne.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 ne.getPointOnLine(e,a.start.x,a.start.y,o[0],o[1]);case"C":return ne.getPointOnCubicBezier(Vn(e,ne.getPathLength(t),y=>$n([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 ne.getPointOnQuadraticBezier(Vn(e,ne.getPathLength(t),y=>zn([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],g=o[6];let f=o[4];return f+=u*e/a.pathLength,ne.getPointOnEllipticalArc(l,c,h,d,f,g)}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),g=t+u*(r-t),f=i+u*(n-i),y=this.getLineLength(a,o,g,f),v=Math.sqrt(e*e-y*y),b=Math.sqrt(v*v/(1+c*c))*(r<t?-1:1),S=c*b;return{x:g+b,y:f+S}}static getPointOnCubicBezier(e,t,i,r,n,a,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 g(v){return(1-v)*(1-v)*(1-v)}const f=l*h(e)+a*d(e)+r*u(e)+t*g(e),y=c*h(e)+o*d(e)+n*u(e)+i*g(e);return{x:f,y}}static getPointOnQuadraticBezier(e,t,i,r,n,a,o){function l(g){return g*g}function c(g){return 2*g*(1-g)}function h(g){return(1-g)*(1-g)}const d=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],g=u.charAt(0);for(u=u.slice(1),a.length=0;h=c.exec(u);)a.push(h[0]);let f=[],y=g==="A"||g==="a"?0:-1;for(let v=0,b=a.length;v<b;v++){const S=a[v];if(S==="00"){f.push(0,0),y>=0&&(y+=2,y>=7&&(y-=7));continue}if(y>=0){if(y===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),f.push(parseFloat(S.slice(2))),y+=3,y>=7&&(y-=7);continue}if(S==="11"||S==="10"||S==="01"){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),y+=2,y>=7&&(y-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),y+=1,y>=7&&(y-=7);continue}}else if(y===4){if(/^[01]\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseFloat(S.slice(1))),y+=2,y>=7&&(y-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),y+=1,y>=7&&(y-=7);continue}}const C=parseFloat(S);isNaN(C)?f.push(0):f.push(C),y+=1,y>=7&&(y-=7)}else{const C=parseFloat(S);isNaN(C)?f.push(0):f.push(C)}}for(;f.length>0&&!isNaN(f[0]);){let v="",b=[];const S=o,C=l;let w,x,k,D,P,A,O,$,F,V;switch(g){case"l":o+=f.shift(),l+=f.shift(),v="L",b.push(o,l);break;case"L":o=f.shift(),l=f.shift(),b.push(o,l);break;case"m":const z=f.shift(),H=f.shift();if(o+=z,l+=H,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]+H;break}}b.push(o,l),g="l";break;case"M":o=f.shift(),l=f.shift(),v="M",b.push(o,l),g="L";break;case"h":o+=f.shift(),v="L",b.push(o,l);break;case"H":o=f.shift(),v="L",b.push(o,l);break;case"v":l+=f.shift(),v="L",b.push(o,l);break;case"V":l=f.shift(),v="L",b.push(o,l);break;case"C":b.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),l=f.shift(),b.push(o,l);break;case"c":b.push(o+f.shift(),l+f.shift(),o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="C",b.push(o,l);break;case"S":x=o,k=l,w=n[n.length-1],w.command==="C"&&(x=o+(o-w.points[2]),k=l+(l-w.points[3])),b.push(x,k,f.shift(),f.shift()),o=f.shift(),l=f.shift(),v="C",b.push(o,l);break;case"s":x=o,k=l,w=n[n.length-1],w.command==="C"&&(x=o+(o-w.points[2]),k=l+(l-w.points[3])),b.push(x,k,o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="C",b.push(o,l);break;case"Q":b.push(f.shift(),f.shift()),o=f.shift(),l=f.shift(),b.push(o,l);break;case"q":b.push(o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="Q",b.push(o,l);break;case"T":x=o,k=l,w=n[n.length-1],w.command==="Q"&&(x=o+(o-w.points[0]),k=l+(l-w.points[1])),o=f.shift(),l=f.shift(),v="Q",b.push(x,k,o,l);break;case"t":x=o,k=l,w=n[n.length-1],w.command==="Q"&&(x=o+(o-w.points[0]),k=l+(l-w.points[1])),o+=f.shift(),l+=f.shift(),v="Q",b.push(x,k,o,l);break;case"A":D=f.shift(),P=f.shift(),A=f.shift(),O=f.shift(),$=f.shift(),F=o,V=l,o=f.shift(),l=f.shift(),v="A",b=this.convertEndpointToCenterParameterization(F,V,o,l,O,$,D,P,A);break;case"a":D=f.shift(),P=f.shift(),A=f.shift(),O=f.shift(),$=f.shift(),F=o,V=l,o+=f.shift(),l+=f.shift(),v="A",b=this.convertEndpointToCenterParameterization(F,V,o,l,O,$,D,P,A);break}n.push({command:v||g,points:b,start:{x:S,y:C},pathLength:this.calcLength(S,C,v||g,b)})}(g==="z"||g==="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=ne;switch(i){case"L":return c.getLineLength(e,t,r[0],r[1]);case"C":return $n([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return zn([e,r[0],r[2]],[t,r[1],r[3]],1);case"A":n=0;const h=r[4],d=r[5],u=r[4]+d;let g=Math.PI/180;if(Math.abs(h-u)<g&&(g=Math.abs(h-u)),a=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),d<0)for(l=h-g;l>u;l-=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;else for(l=h+g;l<u;l+=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),n+=c.getLineLength(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,g=d*d/(o*o)+u*u/(l*l);g>1&&(o*=Math.sqrt(g),l*=Math.sqrt(g));let f=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));n===a&&(f*=-1),isNaN(f)&&(f=0);const y=f*o*u/l,v=f*-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(O){return Math.sqrt(O[0]*O[0]+O[1]*O[1])},w=function(O,$){return(O[0]*$[0]+O[1]*$[1])/(C(O)*C($))},x=function(O,$){return(O[0]*$[1]<O[1]*$[0]?-1:1)*Math.acos(w(O,$))},k=x([1,0],[(d-y)/o,(u-v)/l]),D=[(d-y)/o,(u-v)/l],P=[(-1*d-y)/o,(-1*u-v)/l];let A=x(D,P);return w(D,P)<=-1&&(A=Math.PI),w(D,P)>=1&&(A=0),a===0&&A>0&&(A=A-2*Math.PI),a===1&&A<0&&(A=A+2*Math.PI),[b,S,o,l,k,A,h,a]}}ne.prototype.className="Path";ne.prototype._attrsAffectingSize=["data"];oe(ne);m.addGetterSetter(ne,"data");class ft extends ze{_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]],g=ne.calcLength(r[r.length-4],r[r.length-3],"C",u),f=ne.getPointOnQuadraticBezier(Math.min(1,1-a/g),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-f.x,c=i[o-1]-f.y}else l=i[o-2]-i[o-4],c=i[o-1]-i[o-3];const h=(Math.atan2(c,l)+t)%t,d=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(i[o-2],i[o-1]),e.rotate(h),e.moveTo(0,0),e.lineTo(-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}}}ft.prototype.className="Arrow";oe(ft);m.addGetterSetter(ft,"pointerLength",10,R());m.addGetterSetter(ft,"pointerWidth",10,R());m.addGetterSetter(ft,"pointerAtBeginning",!1);m.addGetterSetter(ft,"pointerAtEnding",!0);class Rt extends _{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}Rt.prototype._centroid=!0;Rt.prototype.className="Circle";Rt.prototype._attrsAffectingSize=["radius"];oe(Rt);m.addGetterSetter(Rt,"radius",0,R());class tt extends _{_sceneFunc(e){const t=this.radiusX(),i=this.radiusY();e.beginPath(),e.save(),t!==i&&e.scale(1,i/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}tt.prototype.className="Ellipse";tt.prototype._centroid=!0;tt.prototype._attrsAffectingSize=["radiusX","radiusY"];oe(tt);m.addComponentsGetterSetter(tt,"radius",["x","y"]);m.addGetterSetter(tt,"radiusX",0,R());m.addGetterSetter(tt,"radiusY",0,R());let Ee=class Ta extends _{constructor(e){super(e),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",t=>{this._removeImageLoad(t.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const e=this.image();e&&e.complete||e&&e.readyState===4||e&&e.addEventListener&&e.addEventListener("load",this._loadListener)}_removeImageLoad(e){e&&e.removeEventListener&&e.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const e=!!this.cornerRadius(),t=this.hasShadow();return e&&t?!0:super._useBufferCanvas(!0)}_sceneFunc(e){const t=this.getWidth(),i=this.getHeight(),r=this.cornerRadius(),n=this.attrs.image;let 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?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,a))}_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 Ta({image:r});t(n)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Ee.prototype.className="Image";Ee.prototype._attrsAffectingSize=["image"];oe(Ee);m.addGetterSetter(Ee,"cornerRadius",0,nr(4));m.addGetterSetter(Ee,"image");m.addComponentsGetterSetter(Ee,"crop",["x","y","width","height"]);m.addGetterSetter(Ee,"cropX",0,R());m.addGetterSetter(Ee,"cropY",0,R());m.addGetterSetter(Ee,"cropWidth",0,R());m.addGetterSetter(Ee,"cropHeight",0,R());const wa=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],Fl="Change.konva",Gl="none",Nr="up",Hr="right",$r="down",zr="left",Nl=wa.length;class fn extends At{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<Nl;i++)e.on(wa[i]+Fl,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 Nr:o=i/2,l=-1*c;break;case Hr:o=i+a,l=r/2;break;case $r:o=i/2,l=r+c;break;case zr: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})}}}fn.prototype.className="Label";oe(fn);class mt extends _{_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===Nr&&(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===Hr&&(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===$r&&(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===zr&&(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===Nr?(t-=r,o+=r):n===$r?o+=r:n===zr?(e-=i*1.5,a+=i):n===Hr&&(a+=i*1.5),{x:e,y:t,width:a,height:o}}}mt.prototype.className="Tag";oe(mt);m.addGetterSetter(mt,"pointerDirection",Gl);m.addGetterSetter(mt,"pointerWidth",0,R());m.addGetterSetter(mt,"pointerHeight",0,R());m.addGetterSetter(mt,"cornerRadius",0,nr(4));class yi extends _{_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)}}yi.prototype.className="Rect";oe(yi);m.addGetterSetter(yi,"cornerRadius",0,nr(4));class it extends _{_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 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)}}it.prototype.className="RegularPolygon";it.prototype._centroid=!0;it.prototype._attrsAffectingSize=["radius"];oe(it);m.addGetterSetter(it,"radius",0,R());m.addGetterSetter(it,"sides",0,R());m.addGetterSetter(it,"cornerRadius",0,nr(4));const Un=Math.PI*2;class yt extends _{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,Un,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),Un,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)}}yt.prototype.className="Ring";yt.prototype._centroid=!0;yt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];oe(yt);m.addGetterSetter(yt,"innerRadius",0,R());m.addGetterSetter(yt,"outerRadius",0,R());class Be extends _{constructor(e){super(e),this._updated=!0,this.anim=new we(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,n=this.animations()[t],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],g=i*2;e.drawImage(d,o,l,c,h,u[g+0],u[g+1],c,h)}else e.drawImage(d,o,l,c,h,0,0,c,h)}_hitFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,n=this.animations()[t],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)}}Be.prototype.className="Sprite";oe(Be);m.addGetterSetter(Be,"animation");m.addGetterSetter(Be,"animations");m.addGetterSetter(Be,"frameOffsets");m.addGetterSetter(Be,"image");m.addGetterSetter(Be,"frameIndex",0,R());m.addGetterSetter(Be,"frameRate",17,R());m.backCompat(Be,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class rt extends _{_sceneFunc(e){const t=this.innerRadius(),i=this.outerRadius(),r=this.numPoints();e.beginPath(),e.moveTo(0,0-i);for(let n=1;n<r*2;n++){const 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)}}rt.prototype.className="Star";rt.prototype._centroid=!0;rt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];oe(rt);m.addGetterSetter(rt,"numPoints",5,R());m.addGetterSetter(rt,"innerRadius",0,R());m.addGetterSetter(rt,"outerRadius",0,R());function qe(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 vt="auto",Hl="center",ka="inherit",Ft="justify",$l="Change.konva",zl="2d",Wn="-",Pa="left",Vl="text",Ul="Text",Wl="top",Yl="bottom",Yn="middle",xa="normal",Xl="px ",Ai=" ",ql="right",Xn="rtl",jl="word",Kl="char",qn="none",fr="…",_a=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],Zl=_a.length;function Jl(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 Ii;function mr(){return Ii||(Ii=T.createCanvasElement().getContext(zl),Ii)}function Ql(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function ec(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function tc(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}class se extends _{constructor(e){super(tc(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<Zl;t++)this.on(_a[t]+$l,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(),g=this.getWidth(),f=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,x;h=h===ka?e.direction:h;let k=l/2,D=Yn;if(!M.legacyTextRendering){const P=this.measureSize("M");D="alphabetic";const A=(t=P.fontBoundingBoxAscent)!==null&&t!==void 0?t:P.actualBoundingBoxAscent,O=(i=P.fontBoundingBoxDescent)!==null&&i!==void 0?i:P.actualBoundingBoxDescent;k=(A-O)/2+l/2}for(h===Xn&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",D),e.setAttr("textAlign",Pa),c===Yn?d=(this.getHeight()-n*l-a*2)/2:c===Yl&&(d=this.getHeight()-n*l-a*2),e.translate(a,d+a),x=0;x<n;x++){let P=0,A=0;const O=r[x],$=O.text,F=O.width,V=O.lastInParagraph;if(e.save(),u===ql?P+=g-F-a*2:u===Hl&&(P+=(g-F-a*2)/2),C){e.save(),e.beginPath();const H=S??(M.legacyTextRendering?Math.round(o/2):Math.round(o/4)),L=P,X=k+A+H;e.moveTo(L,X);const G=u===Ft&&!V?g-a*2:F;e.lineTo(L+Math.round(G),X),e.lineWidth=o/15;const Q=this._getLinearGradient();e.strokeStyle=Q||v,e.stroke(),e.restore()}const z=P;if(h!==Xn&&(f!==0||u===Ft||y)){const H=$.split(" ").length-1,L=qe($);for(let X=0;X<L.length;X++){const G=L[X];if(G===" "&&!V&&u===Ft&&(P+=(g-a*2-F)/H),this._partialTextX=P,this._partialTextY=k+A,this._partialText=G,y){e.save();const ae=r.slice(0,x).reduce((J,ge)=>J+qe(ge.text).length,0),Y=X+ae;y({char:G,index:Y,x:P,y:k+A,lineIndex:x,column:X,isLastInLine:V,width:this.measureSize(G).width,context:e})}e.fillStrokeShape(this),y&&e.restore(),P+=this.measureSize(G).width+f}}else f!==0&&e.setAttr("letterSpacing",`${f}px`),this._partialTextX=P,this._partialTextY=k+A,this._partialText=$,e.fillStrokeShape(this);if(w){e.save(),e.beginPath();const H=M.legacyTextRendering?0:-Math.round(o/4),L=z;e.moveTo(L,k+A+H);const X=u===Ft&&!V?g-a*2:F;e.lineTo(L+Math.round(X),k+A+H),e.lineWidth=o/15;const G=this._getLinearGradient();e.strokeStyle=G||v,e.stroke(),e.restore()}e.restore(),n>1&&(k+=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(Vl,t),this}getWidth(){return this.attrs.width===vt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===vt||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,a,o,l,c,h,d,u;let g=mr(),f=this.fontSize(),y;g.save(),g.font=this._getContextFont(),y=g.measureText(e),g.restore();const v=f/100;return{actualBoundingBoxAscent:(t=y.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*v,actualBoundingBoxDescent:(i=y.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(r=y.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*v,actualBoundingBoxRight:(n=y.actualBoundingBoxRight)!==null&&n!==void 0?n:75.732421875*v,alphabeticBaseline:(a=y.alphabeticBaseline)!==null&&a!==void 0?a: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:f}}_getContextFont(){return this.fontStyle()+Ai+this.fontVariant()+Ai+(this.fontSize()+Xl)+Jl(this.fontFamily())}_addTextLine(e){this.align()===Ft&&(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 mr().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!==vt&&n!==void 0,l=a!==vt&&a!==void 0,c=this.padding(),h=n-c*2,d=a-c*2,u=0,g=this.wrap(),f=g!==qn,y=g!==Kl&&f,v=this.ellipsis();this.textArr=[],mr().font=this._getContextFont();const b=v?this._getTextWidth(fr):0;for(let S=0,C=e.length;S<C;++S){let w=e[S],x=this._getTextWidth(w);if(o&&x>h)for(;w.length>0;){let k=0,D=qe(w).length,P="",A=0;for(;k<D;){const O=k+D>>>1,$=qe(w),F=$.slice(0,O+1).join(""),V=this._getTextWidth(F);(v&&l&&u+r>d?V+b:V)<=h?(k=O+1,P=F,A=V):D=O}if(P){if(y){const F=qe(w),V=qe(P),z=F[V.length],H=z===Ai||z===Wn;let L;if(H&&A<=h)L=V.length;else{const X=V.lastIndexOf(Ai),G=V.lastIndexOf(Wn);L=Math.max(X,G)+1}L>0&&(k=L,P=F.slice(0,k).join(""),A=this._getTextWidth(P))}if(P=P.trimRight(),this._addTextLine(P),i=Math.max(i,A),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(w=qe(w).slice(k).join("").trimLeft(),w.length>0&&(x=this._getTextWidth(w),x<=h)){this._addTextLine(w),u+=r,i=Math.max(i,x);break}}else break}else this._addTextLine(w),u+=r,i=Math.max(i,x),this._shouldHandleEllipsis(u)&&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!==vt&&r!==void 0,a=this.padding(),o=r-a*2;return!(this.wrap()!==qn)||n&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==vt&&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+fr)<r||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+fr))}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()}}se.prototype._fillFunc=Ql;se.prototype._strokeFunc=ec;se.prototype.className=Ul;se.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];oe(se);m.overWriteSetter(se,"width",un());m.overWriteSetter(se,"height",un());m.addGetterSetter(se,"direction",ka);m.addGetterSetter(se,"fontFamily","Arial");m.addGetterSetter(se,"fontSize",12,R());m.addGetterSetter(se,"fontStyle",xa);m.addGetterSetter(se,"fontVariant",xa);m.addGetterSetter(se,"padding",0,R());m.addGetterSetter(se,"align",Pa);m.addGetterSetter(se,"verticalAlign",Wl);m.addGetterSetter(se,"lineHeight",1,R());m.addGetterSetter(se,"wrap",jl);m.addGetterSetter(se,"ellipsis",!1,Ie());m.addGetterSetter(se,"letterSpacing",0,R());m.addGetterSetter(se,"text","",pt());m.addGetterSetter(se,"textDecoration","");m.addGetterSetter(se,"underlineOffset",void 0,R());m.addGetterSetter(se,"charRenderFunc",void 0);const ic="",Aa="normal";function Ia(s){s.fillText(this.partialText,0,0)}function Ea(s){s.strokeText(this.partialText,0,0)}class he extends _{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 ne.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:ne.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=ne.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 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 se.prototype.setText.call(this,e)}_getContextFont(){return se.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=qe(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 g=t[d].char;let f=t[d].width+n;if(g===" "&&a==="justify"){const w=this.text().split(" ").length-1;f+=(this.pathLength-l)/w}const y=this._getPointAtLength(h+f);if(!y)return;const v=ne.getLineLength(u.x,u.y,y.x,y.y);let b=0;if(o)try{b=o(t[d-1].char,g)*this.fontSize()}catch{b=0}u.x+=b,y.x+=b,this.textWidth+=b;const S=ne.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+=f}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,i=e[0]||0,r=e[1]||0,n=e[1]||0,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 T.releaseCanvas(this.dummyCanvas),super.destroy()}}he.prototype._fillFunc=Ia;he.prototype._strokeFunc=Ea;he.prototype._fillFuncHit=Ia;he.prototype._strokeFuncHit=Ea;he.prototype.className="TextPath";he.prototype._attrsAffectingSize=["text","fontSize","data"];oe(he);m.addGetterSetter(he,"data");m.addGetterSetter(he,"fontFamily","Arial");m.addGetterSetter(he,"fontSize",12,R());m.addGetterSetter(he,"fontStyle",Aa);m.addGetterSetter(he,"align","left");m.addGetterSetter(he,"letterSpacing",0,R());m.addGetterSetter(he,"textBaseline","middle");m.addGetterSetter(he,"fontVariant",Aa);m.addGetterSetter(he,"text",ic);m.addGetterSetter(he,"textDecoration","");m.addGetterSetter(he,"kerningFunc",void 0);const Ra="tr-konva",rc=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(s=>s+`.${Ra}`).join(" "),jn="nodesRect",nc=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],sc={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},ac="ontouchstart"in M._global;function oc(s,e,t){if(s==="rotater")return t;e+=T.degToRad(sc[s]||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 Wi=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function lc(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 Ma(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 cc(s,e){const t=lc(s);return Ma(s,e,t)}function hc(s,e,t){let i=e;for(let r=0;r<s.length;r++){const n=M.getAngle(s[r]),a=Math.abs(n-e)%(Math.PI*2);Math.min(a,Math.PI*2-a)<t&&(i=n)}return i}let Vr=0;class W extends At{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(rc,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 Ra+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 a=r._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");r.on(a,n)}r.on(nc.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(jn),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(jn,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=(M.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 Ma(h,-M.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(c=>{const h=c.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:h.x,y:h.y},{x:h.x+h.width,y:h.y},{x:h.x+h.width,y:h.y+h.height},{x:h.x,y:h.y+h.height}],u=c.getAbsoluteTransform();d.forEach(function(g){const f=u.point(g);t.push(f)})});const i=new Se;i.rotate(-M.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:M.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(),Wi.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new yi({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:ac?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=M.getAngle(this.rotation()),n=this.rotateAnchorCursor(),a=oc(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 _({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=T.degToRad(l),d=Math.sin(h),u=-Math.cos(h),g=a/2,f=o/2;let y=1/0;u<0?y=Math.min(y,-f/u):u>0&&(y=Math.min(y,(o-f)/u)),d<0?y=Math.min(y,-g/d):d>0&&(y=Math.min(y,(a-g)/d));const v=g+d*y,b=f+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 a=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-a.x,y:o.y-a.y},Vr++,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 S=this._getNodeRect();t=n.x()-S.width/2,i=-n.y()+S.height/2;const C=M.getAngle(this.rotateAnchorAngle());let w=Math.atan2(-i,t)+Math.PI/2-C;S.height<0&&(w-=Math.PI);const k=M.getAngle(this.rotation())+w,D=M.getAngle(this.rotationSnapTolerance()),A=hc(this.rotationSnaps(),k,D)-S.rotation,O=cc(S,A);this._fitNodesInto(O,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let g=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(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=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(n.x()-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 f=n.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(n.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(n.x());else if(this._movingAnchorName==="bottom-left"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(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)}f=n.position(),this.findOne(".top-left").x(f.x),this.findOne(".bottom-right").y(f.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(n.y());else if(this._movingAnchorName==="bottom-right"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};r=Math.sqrt(Math.pow(n.x()-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(g=this.centeredScaling()||e.altKey,g){const S=this.findOne(".top-left"),C=this.findOne(".bottom-right"),w=S.x(),x=S.y(),k=this.getWidth()-C.x(),D=this.getHeight()-C.y();C.move({x:-w,y:-x}),S.move({x:k,y:D})}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:M.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();Vr--,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(M.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 a=1e7,o=new Se;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/a,i.height/a);const l=new Se,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 g;if(!u.getStage())return;const f=u.getParent().getAbsoluteTransform(),y=u.getTransform().copy();y.translate(u.offsetX(),u.offsetY());const v=new Se;v.multiply(f.copy().invert()).multiply(d).multiply(f).multiply(y);const b=v.decompose();u.setAttrs(b),(g=u.getLayer())===null||g===void 0||g.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(),a=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),c=this.find("._anchor");c.forEach(k=>{k.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=T.degToRad(h),g=Math.sin(u),f=-Math.cos(u),y=i/2,v=r/2;let b=1/0;f<0?b=Math.min(b,-v/f):f>0&&(b=Math.min(b,(r-v)/f)),g<0?b=Math.min(b,-y/g):g>0&&(b=Math.min(b,(i-y)/g));const S=y+g*b,C=v+f*b,w=T._sign(r);this._batchChangeChild(".rotater",{x:S+g*d*w,y:C+f*d*w-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(k=>k.draggable()),x:0,y:0});const x=this.anchorStyleFunc();x&&c.forEach(k=>{x(k)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),At.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=()=>Vr>0;function dc(s){return s instanceof Array||T.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(e){Wi.indexOf(e)===-1&&T.warn("Unknown anchor name: "+e+". Available names are: "+Wi.join(", "))}),s||[]}W.prototype.className="Transformer";oe(W);m.addGetterSetter(W,"enabledAnchors",Wi,dc);m.addGetterSetter(W,"flipEnabled",!0,Ie());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 Ve extends _{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,M.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)}}Ve.prototype.className="Wedge";Ve.prototype._centroid=!0;Ve.prototype._attrsAffectingSize=["radius"];oe(Ve);m.addGetterSetter(Ve,"radius",0,R());m.addGetterSetter(Ve,"angle",0,R());m.addGetterSetter(Ve,"clockwise",!1);m.backCompat(Ve,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Kn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const uc=[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],pc=[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 gc(s,e){const t=s.data,i=s.width,r=s.height;let n,a,o,l,c,h,d,u,g,f,y,v,b,S,C,w,x,k,D,P;const A=e+e+1,O=i-1,$=r-1,F=e+1,V=F*(F+1)/2,z=new Kn,H=uc[e],L=pc[e];let X=null,G=z,Q=null,ae=null;for(let Y=1;Y<A;Y++)G=G.next=new Kn,Y===F&&(X=G);G.next=z,o=a=0;for(let Y=0;Y<r;Y++){v=b=S=C=l=c=h=d=0,u=F*(w=t[a]),g=F*(x=t[a+1]),f=F*(k=t[a+2]),y=F*(D=t[a+3]),l+=V*w,c+=V*x,h+=V*k,d+=V*D,G=z;for(let J=0;J<F;J++)G.r=w,G.g=x,G.b=k,G.a=D,G=G.next;for(let J=1;J<F;J++)n=a+((O<J?O:J)<<2),l+=(G.r=w=t[n])*(P=F-J),c+=(G.g=x=t[n+1])*P,h+=(G.b=k=t[n+2])*P,d+=(G.a=D=t[n+3])*P,v+=w,b+=x,S+=k,C+=D,G=G.next;Q=z,ae=X;for(let J=0;J<i;J++)t[a+3]=D=d*H>>L,D!==0?(D=255/D,t[a]=(l*H>>L)*D,t[a+1]=(c*H>>L)*D,t[a+2]=(h*H>>L)*D):t[a]=t[a+1]=t[a+2]=0,l-=u,c-=g,h-=f,d-=y,u-=Q.r,g-=Q.g,f-=Q.b,y-=Q.a,n=o+((n=J+e+1)<O?n:O)<<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=ae.r,g+=x=ae.g,f+=k=ae.b,y+=D=ae.a,v-=w,b-=x,S-=k,C-=D,ae=ae.next,a+=4;o+=i}for(let Y=0;Y<i;Y++){b=S=C=v=c=h=d=l=0,a=Y<<2,u=F*(w=t[a]),g=F*(x=t[a+1]),f=F*(k=t[a+2]),y=F*(D=t[a+3]),l+=V*w,c+=V*x,h+=V*k,d+=V*D,G=z;for(let ge=0;ge<F;ge++)G.r=w,G.g=x,G.b=k,G.a=D,G=G.next;let J=i;for(let ge=1;ge<=e;ge++)a=J+Y<<2,l+=(G.r=w=t[a])*(P=F-ge),c+=(G.g=x=t[a+1])*P,h+=(G.b=k=t[a+2])*P,d+=(G.a=D=t[a+3])*P,v+=w,b+=x,S+=k,C+=D,G=G.next,ge<$&&(J+=i);a=Y,Q=z,ae=X;for(let ge=0;ge<r;ge++)n=a<<2,t[n+3]=D=d*H>>L,D>0?(D=255/D,t[n]=(l*H>>L)*D,t[n+1]=(c*H>>L)*D,t[n+2]=(h*H>>L)*D):t[n]=t[n+1]=t[n+2]=0,l-=u,c-=g,h-=f,d-=y,u-=Q.r,g-=Q.g,f-=Q.b,y-=Q.a,n=Y+((n=ge+F)<$?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=ae.r,g+=x=ae.g,f+=k=ae.b,y+=D=ae.a,v-=w,b-=x,S-=k,C-=D,ae=ae.next,a+=i}}const fc=function(e){const t=Math.round(this.blurRadius());t>0&&gc(e,t)};m.addGetterSetter(E,"blurRadius",0,R(),m.afterSetFilter);const mc=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 yc=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)},Sc=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 vc=function(s){var e,t,i,r,n,a,o,l,c;const h=s.data,d=s.width,u=s.height,g=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),f=Math.min(1,Math.max(0,(r=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&r!==void 0?r:.5)),v=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(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,b=!!((c=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&c!==void 0&&c),S=g*10,C=f*255,w=v*Math.PI/180,x=Math.cos(w),k=Math.sin(w),D=128/1020*S,P=new Uint8ClampedArray(h),A=new Float32Array(d*u);for(let z=0,H=0;H<h.length;H+=4,z++)A[z]=.2126*P[H]+.7152*P[H+1]+.0722*P[H+2];const O=[-1,0,1,-2,0,2,-1,0,1],$=[-1,-2,-1,0,0,0,1,2,1],F=[-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 H=1;H<d-1;H++){const L=z*d+H;let X=0,G=0;X+=A[L+F[0]]*O[0],G+=A[L+F[0]]*$[0],X+=A[L+F[1]]*O[1],G+=A[L+F[1]]*$[1],X+=A[L+F[2]]*O[2],G+=A[L+F[2]]*$[2],X+=A[L+F[3]]*O[3],G+=A[L+F[3]]*$[3],X+=A[L+F[5]]*O[5],G+=A[L+F[5]]*$[5],X+=A[L+F[6]]*O[6],G+=A[L+F[6]]*$[6],X+=A[L+F[7]]*O[7],G+=A[L+F[7]]*$[7],X+=A[L+F[8]]*O[8],G+=A[L+F[8]]*$[8];const Q=x*X+k*G,ae=V(C+Q*D),Y=L*4;if(b){const J=ae-C;h[Y]=V(P[Y]+J),h[Y+1]=V(P[Y+1]+J),h[Y+2]=V(P[Y+2]+J),h[Y+3]=P[Y+3]}else h[Y]=h[Y+1]=h[Y+2]=ae,h[Y+3]=P[Y+3]}for(let z=0;z<d;z++){let H=z*4,L=((u-1)*d+z)*4;h[H]=P[H],h[H+1]=P[H+1],h[H+2]=P[H+2],h[H+3]=P[H+3],h[L]=P[L],h[L+1]=P[L+1],h[L+2]=P[L+2],h[L+3]=P[L+3]}for(let z=1;z<u-1;z++){let H=z*d*4,L=(z*d+(d-1))*4;h[H]=P[H],h[H+1]=P[H+1],h[H+2]=P[H+2],h[H+3]=P[H+3],h[L]=P[L],h[L+1]=P[L+1],h[L+2]=P[L+2],h[L+3]=P[L+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 yr(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 Cc=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 C=0;C<t;C+=4)n=e[C+0],n<i?i=n:n>r&&(r=n),l=e[C+1],l<a?a=l:l>o&&(o=l),d=e[C+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 g,f,y,v,b,S;if(u>0)g=r+u*(255-r),f=i-u*(i-0),y=o+u*(255-o),v=a-u*(a-0),b=h+u*(255-h),S=c-u*(c-0);else{const C=(r+i)*.5;g=r+u*(r-C),f=i+u*(i-C);const w=(o+a)*.5;y=o+u*(o-w),v=a+u*(a-w);const x=(h+c)*.5;b=h+u*(h-x),S=c+u*(c-x)}for(let C=0;C<t;C+=4)e[C+0]=yr(e[C+0],i,r,f,g),e[C+1]=yr(e[C+1],a,o,v,y),e[C+2]=yr(e[C+2],c,h,S,b)};m.addGetterSetter(E,"enhance",0,R(),m.afterSetFilter);const bc=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 Tc=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,g=.587*i+.413*o+.035*l,f=.114*i-.114*o+.293*l,y=.299*i-.3*o+1.25*l,v=.587*i-.586*o-1.05*l,b=.114*i+.886*o-.2*l;let S,C,w,x;for(let k=0;k<t;k+=4)S=e[k+0],C=e[k+1],w=e[k+2],x=e[k+3],e[k+0]=c*S+h*C+d*w+a,e[k+1]=u*S+g*C+f*w+a,e[k+2]=y*S+v*C+b*w+a,e[k+3]=x},wc=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,g=.114*i-.114*a+.293*o,f=.299*i-.3*a+1.25*o,y=.587*i-.586*a-1.05*o,v=.114*i+.886*a-.2*o;for(let b=0;b<t;b+=4){const S=e[b+0],C=e[b+1],w=e[b+2],x=e[b+3];e[b+0]=l*S+c*C+h*w,e[b+1]=d*S+u*C+g*w,e[b+2]=f*S+y*C+v*w,e[b+3]=x}};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 kc=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]},Pc=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 g=a,f=n,y=360/f*Math.PI/180;for(let v=0;v<f;v+=1){const b=Math.sin(v*y),S=Math.cos(v*y);for(let C=0;C<g;C+=1){h=Math.floor(o+c*C/g*S),d=Math.floor(l+c*C/g*b);let w=(d*n+h)*4;const x=i[w+0],k=i[w+1],D=i[w+2],P=i[w+3];w=(v+C*n)*4,r[w+0]=x,r[w+1]=k,r[w+2]=D,r[w+3]=P}}},xc=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 g=a,f=n,y=0;let v,b;for(h=0;h<n;h+=1)for(d=0;d<a;d+=1){const S=h-o,C=d-l,w=Math.sqrt(S*S+C*C)*g/c;let x=(Math.atan2(C,S)*180/Math.PI+360+y)%360;x=x*f/360,v=Math.floor(x),b=Math.floor(w);let k=(b*n+v)*4;const D=i[k+0],P=i[k+1],A=i[k+2],O=i[k+3];k=(d*n+h)*4,r[k+0]=D,r[k+1]=P,r[k+2]=A,r[k+3]=O}},_c=function(s){const e=s.width,t=s.height;let i,r,n,a,o,l,c,h,d,u,g=Math.round(this.kaleidoscopePower());const f=Math.round(this.kaleidoscopeAngle()),y=Math.floor(e*(f%360)/360);if(g<1)return;const v=T.createCanvasElement();v.width=e,v.height=t;const b=v.getContext("2d").getImageData(0,0,e,t);T.releaseCanvas(v),Pc(s,b,{polarCenterX:e/2,polarCenterY:t/2});let S=e/Math.pow(2,g);for(;S<=8;)S=S*2,g-=1;S=Math.ceil(S);let C=S,w=0,x=C,k=1;for(y+S>e&&(w=C,x=0,k=-1),r=0;r<t;r+=1)for(i=w;i!==x;i+=k)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),a=0;a<g;a+=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}xc(b,s,{})};m.addGetterSetter(E,"kaleidoscopePower",2,R(),m.afterSetFilter);m.addGetterSetter(E,"kaleidoscopeAngle",0,R(),m.afterSetFilter);function Ei(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 Gt(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 Ac(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 Ic(s,e){const t=Ei(s,0,0),i=Ei(s,s.width-1,0),r=Ei(s,0,s.height-1),n=Ei(s,s.width-1,s.height-1),a=e||10;if(Gt(t,i)<a&&Gt(i,n)<a&&Gt(n,r)<a&&Gt(r,t)<a){const o=Ac([i,t,n,r]),l=[];for(let c=0;c<s.width*s.height;c++){const h=Gt(o,[s.data[c*4],s.data[c*4+1],s.data[c*4+2]]);l[c]=h<a?0:255}return l}}function Ec(s,e){for(let t=0;t<s.width*s.height;t++)s.data[4*t+3]=e[t]}function Rc(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 g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,v=i[d*r+u];h+=s[y]*v}}a[c]=h===255*8?255:0}return a}function Mc(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 g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,v=i[d*r+u];h+=s[y]*v}}a[c]=h>=255*4?255:0}return a}function Dc(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 g=o+d-n,f=l+u-n;if(g>=0&&g<t&&f>=0&&f<e){const y=g*e+f,v=i[d*r+u];h+=s[y]*v}}a[c]=h}return a}const Lc=function(s){const e=this.threshold();let t=Ic(s,e);return t&&(t=Rc(t,s.width,s.height),t=Mc(t,s.width,s.height),t=Dc(t,s.width,s.height),Ec(s,t)),s};m.addGetterSetter(E,"threshold",0,R(),m.afterSetFilter);const Oc=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 Bc=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){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 g=o*e,f=g+e,y=l*e,v=y+e;let b=0;for(let S=g;S<f;S+=1)if(!(S>=t))for(let C=y;C<v;C+=1){if(C>=i)continue;const w=(t*C+S)*4;c+=a[w+0],h+=a[w+1],d+=a[w+2],u+=a[w+3],b+=1}c=c/b,h=h/b,d=d/b,u=u/b;for(let S=g;S<f;S+=1)if(!(S>=t))for(let C=y;C<v;C+=1){if(C>=i)continue;const w=(t*C+S)*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 Fc=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 Gc=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,ta,m.afterSetFilter);const Nc=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,ta,m.afterSetFilter);m.addGetterSetter(E,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const Hc=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)}},$c=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},zc=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=Nn.Util._assign(Nn,{Arc:$e,Arrow:ft,Circle:Rt,Ellipse:tt,Image:Ee,Label:fn,Tag:mt,Line:ze,Path:ne,Rect:yi,RegularPolygon:it,Ring:yt,Sprite:Be,Star:rt,Text:se,TextPath:he,Transformer:W,Wedge:Ve,Filters:{Blur:fc,Brightness:yc,Brighten:mc,Contrast:Sc,Emboss:vc,Enhance:Cc,Grayscale:bc,HSL:Tc,HSV:wc,Invert:kc,Kaleidoscope:_c,Mask:Lc,Noise:Oc,Pixelate:Bc,Posterize:Fc,RGB:Gc,RGBA:Nc,Sepia:Hc,Solarize:$c,Threshold:zc}}),Da="media-editor-track.diagnostics.v1",Ur="media-editor-track.diagnostics.failure-window.v1",La="media-editor-track-diagnostics",Je="snapshots",Oa="state",Ba="latest-failure-window",ci=1,mn=1,Zn=40,Vc=48,Uc=250,Jn=20,Wc=100,Yc=500,Wr=new Set(["pending-preview.begin","preview.sync.requested","media.seeking","media.seeked"]),Xc=new Set([...Wr,"media.current-slot.seek","media.preload-slot.seek","media.play.requested","media.pause.requested","slot.recovery-check","runtime.state"]),Qn={debug:10,info:20,warn:30,error:40},Ue={enabled:!0,persist:!0,storageQuotaMb:10,maxSessions:20,maxHotEvents:500,includeFullSourceUrl:!0,consoleSeverityThreshold:"error",highFrequencyEventThrottleMs:Yc};function es(s){return`${s}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function qc(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function Fa(s){if(!s||typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function _t(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:_t(s.cause,e+1,t)};if(e>=4)return"[max-depth]";if(Array.isArray(s))return s.slice(0,40).map(i=>_t(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(!Fa(s))return String(s);const i={};for(const r of Object.keys(s).slice(0,60))i[r]=_t(s[r],e+1,t);return i}return String(s)}function Yi(s){if(!s)return null;const e=_t(s,0,new WeakSet);return Fa(e)?e:{value:e}}function jc(s){return Yi(s)}function Nt(s){return typeof s=="number"&&Number.isFinite(s)?s:null}function Ri(s){return typeof s=="string"&&s.length>0?s:null}function Kc(){var i,r,n,a,o;const s=typeof navigator<"u"?navigator:null,e={platform:Ri(s==null?void 0:s.platform),hardwareConcurrency:Nt(s==null?void 0:s.hardwareConcurrency),deviceMemory:Nt(s==null?void 0:s.deviceMemory),maxTouchPoints:Nt(s==null?void 0:s.maxTouchPoints),language:Ri(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:Ri((i=s==null?void 0:s.connection)==null?void 0:i.effectiveType),downlinkMbps:Nt((r=s==null?void 0:s.connection)==null?void 0:r.downlink),rttMs:Nt((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:Ri((o=s==null?void 0:s.connection)==null?void 0:o.type)};return{hardware:e,network:t}}function ts(s,e={}){const t=Kc(),i=Yi(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 Zc(s){return s?s instanceof Error?{name:s.name,message:s.message,stack:s.stack??null,cause:_t(s.cause,1,new WeakSet)}:{name:null,message:typeof s=="string"?s:String(s),stack:null,cause:_t(s,1,new WeakSet)}:null}function ii(){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 Jc(s){const e=s??ii();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 Ga(s){const e=ii();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 is(s){return Jc(s.summary)}function Qc(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 eh(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 th(s){return{enabled:(s==null?void 0:s.enabled)??Ue.enabled,persist:(s==null?void 0:s.persist)??Ue.persist,storageQuotaMb:(s==null?void 0:s.storageQuotaMb)??Ue.storageQuotaMb,maxSessions:Math.max(1,(s==null?void 0:s.maxSessions)??Ue.maxSessions),maxHotEvents:Math.max(20,(s==null?void 0:s.maxHotEvents)??Ue.maxHotEvents),includeFullSourceUrl:(s==null?void 0:s.includeFullSourceUrl)??Ue.includeFullSourceUrl,consoleSeverityThreshold:(s==null?void 0:s.consoleSeverityThreshold)??Ue.consoleSeverityThreshold,highFrequencyEventThrottleMs:Math.max(0,(s==null?void 0:s.highFrequencyEventThrottleMs)??Ue.highFrequencyEventThrottleMs)}}function ih(){try{if(typeof globalThis.localStorage>"u")return null;const s=globalThis.localStorage.getItem(Da);if(!s)return null;const e=JSON.parse(s);return(e==null?void 0:e.version)!==ci||!Array.isArray(e.sessions)?null:e}catch{return null}}function rh(){try{if(typeof globalThis.localStorage>"u")return null;const s=globalThis.localStorage.getItem(Ur);if(!s)return null;const e=JSON.parse(s);return(e==null?void 0:e.version)!==mn||typeof e.sessionId!="string"||typeof e.failureEventId!="string"||!Array.isArray(e.events)?null:e}catch{return null}}function Na(s){const e=Array.isArray(s.events)?s.events:[];return{...s,updatedAt:s.updatedAt||s.startedAt,events:e,summary:Ga(e)}}function Ht(s,e,t={}){const i=s.slice(-e.maxSessions).map(n=>{const a=n.events.slice(-e.maxHotEvents);return Na({...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:ci,sessions:i}).length>r;)i.shift();return i}async function nh(s){return Ha(Oa,s)}async function sh(s){return Ha(Ba,s)}async function Ha(s,e){if(typeof indexedDB>"u")return!1;try{const t=await new Promise((i,r)=>{const n=indexedDB.open(La,1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains(Je)||a.createObjectStore(Je)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)});return await new Promise((i,r)=>{const n=t.transaction(Je,"readwrite");n.objectStore(Je).put(e,s),n.oncomplete=()=>i(),n.onerror=()=>r(n.error),n.onabort=()=>r(n.error)}),t.close(),!0}catch{return!1}}async function ah(){const s=await $a(Oa);return s&&typeof s=="object"&&"version"in s&&s.version===ci&&"sessions"in s&&Array.isArray(s.sessions)?s:null}async function oh(){const s=await $a(Ba);return s&&typeof s=="object"&&"version"in s&&s.version===mn&&"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 $a(s){if(typeof indexedDB>"u")return null;try{const e=await new Promise((i,r)=>{const n=indexedDB.open(La,1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains(Je)||a.createObjectStore(Je)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)}),t=await new Promise((i,r)=>{const o=e.transaction(Je,"readonly").objectStore(Je).get(s);o.onsuccess=()=>i(o.result??null),o.onerror=()=>r(o.error)});return e.close(),t}catch{return null}}function lh(s,e){return!s&&!e?null:{...s??{},...e??{}}}class za{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=th(e);const t=ih();this.latestFailureWindow=rh(),this.state={version:ci,sessions:Ht((t==null?void 0:t.sessions)??[],this.config,{enforceStorageQuota:this.config.persist})},this.restoreIndexedDbState()}startSession(e){const t=new Date().toISOString(),i={sessionId:es("diag-session"),startedAt:Date.now(),updatedAt:Date.now(),metadata:ts(e,{capturedAt:t}),sequence:0,events:[],summary:ii()};return this.currentSessionId=i.sessionId,this.state.sessions=Ht([...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),eh(t.summary,a),this.trimSessionEvents(t),this.captureFailureWindow(t,a),this.state.sessions=Ht(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=Jn){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:is(t)}}getLiveSnapshot(e=this.currentSessionId,t=Jn){const i=this.resolveSession(e),r=Math.max(1,t);return{sessionId:i.sessionId,startedAt:i.startedAt,updatedAt:i.updatedAt,metadata:i.metadata,summary:is(i),recentEvents:i.events.slice(-r).map(n=>Qc(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=ts(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:ii()}}createEvent(e,t,i,r,n=es("diag-event")){return{eventId:n,sessionId:e.sessionId,sequence:r,timestamp:i,isoTime:new Date(i).toISOString(),perfTimeMs:qc(),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:Yi(t.mediaState),runtimeState:jc(t.runtimeState),error:Zc(t.error),extra:Yi(t.extra)}}trimSessionEvents(e){const t=e.events.length-this.config.maxHotEvents;t<=0||(e.events=e.events.slice(t),e.summary=Ga(e.events))}findCoalescedEvent(e,t,i){if(!Wr.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>Wc)break;if(this.areEventIdentitiesEqual(r,a))return a}return null}resolveHighFrequencyDecision(e,t){if(e.severity==="warn"||e.severity==="error"||!Xc.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?Wr.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:ii()},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(Qn[e.severity]<Qn[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()},Vc))}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()},Uc)))}persistNow(){if(!this.config.persist)return;const e={version:ci,sessions:Ht(this.state.sessions,this.config,{enforceStorageQuota:!0})};if(this.state=e,typeof indexedDB>"u"){this.persistToLocalStorage(e);return}Promise.all([nh(e),sh(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([ah(),oh()]);if((i=e==null?void 0:e.sessions)!=null&&i.length){const n=new Map;[...this.state.sessions,...e.sessions].forEach(a=>{const o=Na(a),l=n.get(o.sessionId);(!l||l.updatedAt<o.updatedAt)&&n.set(o.sessionId,o)}),this.state.sessions=Ht(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:Zn}),!this.activeFailureCapture||this.activeFailureCapture.sessionId!==e.sessionId)return;const i=this.buildFailureWindow(e,this.activeFailureCapture.failureEventId);i.length&&(this.latestFailureWindow={version:mn,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=Zn){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(Da,JSON.stringify(e)),t!==void 0)){if(t){globalThis.localStorage.setItem(Ur,JSON.stringify(t));return}globalThis.localStorage.removeItem(Ur)}}}function Va(s,e){return lh(s,e)}function rs(s,e,t,i){const r=`[${s.toUpperCase()}] [${e}]`;if(i===void 0){console[s](`${r} ${t}`);return}console[s](`${r} ${t}`,i)}const B={debug(s,e,t){},debugLazy(s,e,t){},warn(s,e,t){rs("warn",s,e,t)},error(s,e,t){rs("error",s,e,t)}};class _e{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={},this.brokenImageUrls.clear()}static renderClipCovers(e,t,i,r,n,a=!1){B.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 g=0;g<h;g++)d.push(Math.round(g*(n-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static buildSegmentsDataSync(e,t,i,r){const n=e.length,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 g=0;g<h;g++)d.push(Math.round(g*(n-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static requestRender(e){var i,r;const t=(i=e.getLayer)==null?void 0:i.call(e);if((r=t==null?void 0:t.getStage)!=null&&r.call(t))try{e.draw(),t.batchDraw()}catch{}}static isRenderJobCurrent(e,t){return e.getAttr(this.COVER_RENDER_VERSION_KEY)===t}static renderSegments(e,t,i,r){e.destroyChildren(),e.clip({x:0,y:0,width:i,height:r});for(const{coverUrl:n,singleImageWidth: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(_e,"MIN_IMAGE_DISPLAY_WIDTH",24),p(_e,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),p(_e,"MAX_CACHE_SIZE",1e3),p(_e,"DEFAULT_DIMENSIONS",{width:160,height:90}),p(_e,"keyframeDimensionsCache",{}),p(_e,"keyframeDimensionsPromiseCache",{}),p(_e,"imageCache",{}),p(_e,"brokenImageUrls",new Set);const ch='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="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>',hh='<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>',dh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="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>',uh='<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>',ph='<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>',gh='<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>',fh='<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>',mh='<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>',yh='<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>',Sh='<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>',vh='<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>',Ch=new Map([["OmAi-camera",ch],["OmAi-accept",hh],["OmAi-display",dh],["OmAi-hide",uh],["OmAi-loading",ph],["OmAi-music",gh],["OmAi-volume",fh],["OmAi-volume-mute",mh],["OmAi-text",yh],["clip-audio",Sh],["clip-without-audio",vh]]),ns=new Map;function Ce(s){return Ch.get(s)??""}function bh(s){const e=ns.get(s);if(e)return e;const t=Ce(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,ns.set(s,r),r}const ue=3,ss=10,Th=4,wh=6,as=8,os=14,Yr=10,kh=12,Ph=4,Ua=1,Xi=28,Wa=8,Xr=19,qr=15;function hi(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 qi(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 It(s=0,e=0){return new K.Group({x:s,y:e})}function di(s){s.ellipsis(!1),s.wrap("none"),s.width("auto")}function ar(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 xh(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 Ya(s,e,t){const i=e?s.clipSelectedBorder:I.transparent,r=e?Ua:0;return t==="audio"?{background:I.audioClipBackground,label:s.audioClipText||s.clipName,accent:s.audioClipAccent||s.clipHandle,coverBackground:s.clipCoverBackground||te.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 _h(s,e,t,i){const r=hi(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),ar(s,e,t,!0)}function Ah(s,e,t){const i=hi(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),s.add(i),ar(s,e.width,e.height,!1);const r=15,n=e.height-r-4,a=e.width-ue*2,o=It(ue,2);o.name("clip-cover-container"),o.clip({x:0,y:0,width:a,height:n}),s.add(o);const l=hi(0,0,a,n,t.coverBackground,"transparent",0);l.cornerRadius(2),l.name("clip-cover-background"),o.add(l);const c=It(0,0);c.name("clip-covers-group"),o.add(c),_e.renderClipCovers(c,e.thumbnails??[],a,n,e.videoSrc,e.deferCoverRender);const h=a>=120?Xi+Wa:0,d=qi(`${e.clipName} ${U.formatDuration(e.duration)}`,ue,e.height-r,Yr,"Arial",t.label,"left","middle");d.height(r),di(d),d.name("clip-label"),s.add(d),h>0&&qa(s,e.width,e.height,e.hasSeparatedAudio)}function Ih(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),!xh(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),_e.renderClipCovers(a,e.thumbnails??[],h,c,e.videoSrc,e.deferCoverRender);const d=h>=120?Xi+Wa:0;o.text(`${e.clipName} ${U.formatDuration(e.duration)}`),o.x(ue),o.y(e.height-l),o.fill(t.label),o.height(l),di(o);const u=s.findOne(".video-audio-status");return u==null||u.destroy(),d>0&&qa(s,e.width,e.height,e.hasSeparatedAudio),!0}function Eh(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 Xa(s,e,t,i,r){s.name()||s.name(r);const n=bh(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),Eh(s,n),t}function qa(s,e,t,i){const r=It(Math.max(ue,e-ue-Xi-2),Math.max(0,t-15));r.name("video-audio-status");const n=It(Math.max(0,Xi-Xr),0),a=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";n.name(a),Xa(n,o,Xr,qr,`${a}-icon`),r.add(n),s.add(r)}function Rh(s,e,t){const i=hi(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(6),i.name("clip-background"),s.add(i),ar(s,e.width,e.height,!1);const r=ue+ss,n=Math.max(0,e.width-ue*2-ss*2),a=Th,o=It(r,a),l=Xa(o,"clip-audio",Xr,qr,"audio-clip-icon");s.add(o);const c=r+l+as,h=Math.max(0,n-l-as);if(e.audioBadgeText&&h>0){const u=qi(e.audioBadgeText,c,a,Yr,"Arial",t.label,"left","middle");u.height(qr),di(u),u.name("audio-clip-badge"),s.add(u)}const d=qi(e.clipName,r,e.height-wh-os,Yr,"Arial",t.label,"left","middle");d.height(os),di(d),d.name("clip-label"),s.add(d)}function Mh(s,e,t){const i=hi(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),s.add(i),ar(s,e.width,e.height,!1);const r=qi(e.clipName,Ph,0,kh,"Arial",t.label,"left","middle");r.height(e.height),r.lineHeight(1),di(r),r.name("clip-label"),s.add(r)}function ja(s,e){const t=e.width<=oi,i=Ya(e.theme,e.isSelected,e.clipType);if(s.destroyChildren(),t){_h(s,e.width,e.height,i);return}if(e.clipType==="audio"){Rh(s,e,i);return}if(e.clipType==="text"){Mh(s,e,i);return}Ah(s,e,i)}function Dh(s,e){if(e.width<=oi||e.clipType!=="video")return!1;const i=Ya(e.theme,e.isSelected,e.clipType);return Ih(s,e,i)}function Lh(s,e,t,i,r,n,a,o=!1,l,c,h="video",d=!1,u=!1,g){const f=It(s,e);return f.clip({x:0,y:0,width:t,height:i}),ja(f,{width:t,height:i,clipName:r,audioBadgeText:g,duration:n,theme:a,isSelected:o,thumbnails:l,videoSrc:c,clipType:h,hasSeparatedAudio:d,deferCoverRender:u}),f}function Oh(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 g={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:n??Vi,isSelected:a,thumbnails:o,videoSrc:l,clipType:c,hasSeparatedAudio:h,deferCoverRender:d};Dh(s,g)||ja(s,g)}function Bh(s,e,t,i){return new K.Rect({x:s,y:e,width:t,height:i,stroke:I.clipSelectedBorder,strokeWidth:Ua,fillEnabled:!1})}function jr(s,e=wt.stroke,t=1){return new K.Line({points:s,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function Fh(s,e,t,i=12,r="Arial",n=wt.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 Gh(s=0,e=0){return new K.Group({x:s,y:e})}function Nh(s,e,t,i,r,n,a,o){const l=o||i,c=a==="major"?l*.6:l*.3,h=jr([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=Fh(U.formatTime(r),e,d,10,"Arial",n.timeText,"center");u.name("time-tick-text"),s.add(u)}}function Hh(s,e,t,i,r,n){const a=Gh(e,t);for(let o=0;o<=i;o+=n)a.add(jr([o,0,o,r],wn.line,.5));for(let o=0;o<=r;o+=n)a.add(jr([0,o,i,o],wn.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=wt.fill,a=wt.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=wt.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=wt.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){Nh(e,t,i,r,n,a,o,l)}static drawGrid(e,t,i,r,n,a){Hh(e,t,i,r,n,a)}static clearImageCache(){_e.clearImageCache()}static createClipGroup(e,t,i,r,n,a,o,l=!1,c,h,d="video",u=!1,g=!1,f){return Lh(e,t,i,r,n,a,o,l,c,h,d,u,g,f)}static updateClipGroup(e,t,i,r,n,a,o=!1,l,c,h="video",d=!1,u=!1,g){Oh(e,t,i,r,n,a,o,l,c,h,d,u,g)}static createSelectionEffect(e,t,i,r){return Bh(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 jt=8;function pe(s,e,t){return de.timeToPixels(s,e)-t+Te}function ye(s,e){const t=Math.max(s,0),i=de.timeToPixels(t,e);return i<=oi?oi:i}function $h(s,e){const t=pe(s.startTime,s.zoom,s.scrollLeft),i=ye(s.duration,s.zoom);return t+i>0&&t<e}function zh(s){for(const e of s.clips){const t=pe(e.startTime,s.zoom,s.scrollLeft),i=ye(e.duration,s.zoom),r=s.y>=s.trackY&&s.y<=s.trackY+s.trackHeight;if(s.x>=t&&s.x<=t+jt&&r||s.x>=t+i-jt&&s.x<=t+i&&r)return"ew-resize";if(s.x>t+jt&&s.x<t+i-jt&&r)return"pointer"}return"default"}class Ni{constructor(e,t,i){p(this,"clip");p(this,"onUpdate");p(this,"onSplit");this.clip=cn({...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,a){const o=pe(this.clip.startTime,i,a),l=ye(this.clip.duration,i),c=jt;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 or(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 lr(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 ji(){return{kind:"idle"}}function ls(s){return!!s&&s.kind!=="idle"}function Ki(s){return(s==null?void 0:s.kind)==="draggingMove"||(s==null?void 0:s.kind)==="draggingResizeLeft"||(s==null?void 0:s.kind)==="draggingResizeRight"}function Ct(s){return!s||s.kind==="idle"||s.kind==="boxSelecting"?null:s.context}function Zi(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 Vh(s){const e=Zi(s);return e?e==="move"?"grabbing":"ew-resize":null}function Mi(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:ji(),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=Wh(s.context,e,Zi(s)||"move");return s.kind==="pressed"?Yh(s.context,e.activationThreshold,e.clientX,e.clientY)?{state:Uh(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:Ki(s)}};const t=e.type==="POINTER_UP"&&Ki(s);return{state:ji(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function Uh(s,e){return s==="resize-left"?{kind:"draggingResizeLeft",context:e}:s==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function Wh(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 Yh(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,g,f,y,v,b,S,C,w,x,k,D,P,A,O=ce.DEFAULT_DRAG_ACTIVATION_THRESHOLD,$=!1,F=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",ji());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=>{ls(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(!Ki(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=Ct(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=g,this.onHorizontalDragAutoScroll=f,this.onClipOverlap=y,this.onClipCrossTrackPreview=v,this.onClipCrossTrack=b,this.onClearDropPreview=S,this.onClearSelection=C,this.onSnapGuideChange=w,this.onClipToggleSelection=x,this.onSetSingleSelection=k,this.getMultiDragClipIds=D,this.onMultiDragMove=P,this.onMultiDragInteractionEnd=A,this.dragActivationThreshold=Math.max(0,O),this.enableClipSnap=$,this.clipSnapThreshold=Math.max(0,F),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 Ni(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"?Ci.videoFill:Ci.audioFill,i=this.trackType==="text"?"#C9CBD4":this.trackType==="video"?Ci.videoStroke:Ci.audioStroke,r=pe(e.startTime,this.zoom,this.scrollLeft),n=ye(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=or({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(lr({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,U.pixelsToTime(n-Te+this.scrollLeft,this.zoom));this.onTimeJump(a),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(e){}getClipDisplayLabel(e){return(e.type==="text"||Le(e))&&e.textContent||e.name}getClipAudioBadgeText(e){if(Le(e))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,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 g=u.getBoundingClientRect(),f=t.clientX-g.left,y=t.clientY-g.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(f,y,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(v=c.getClip().isResizingLeft?"resize-left":"resize-right",c.startResize({x:f,y})):(v="move",c.startDrag({x:f,y}),this.trackGroup.moveToTop()),this.applyInteractionTransition(Mi(this.interactionState,{type:"POINTER_DOWN",operation:v,clipId:e,originalClipsState:n,nonDraggedClips:a,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:f,localY:y,scrollLeft:this.scrollLeft})),this.render()}}handleClipMouseMove(e){this.updateHoverCursor(e.clientX,e.clientY)}handleTrackBackgroundMouseMove(){if(this.isDragSessionActive())return;const e=this.layer.getStage(),t=e==null?void 0:e.container();t&&(t.style.cursor="default")}handleClipMouseUp(){this.finishPointerInteraction("POINTER_UP")}finishPointerInteraction(e){const t=this.interactionState,i=this.resolveDraggedClipForInteraction(t);try{if(!i)return;const r=i.getClip();if(!r.isDragging)return;i.endDrag();const n=Mi(t,{type:e});this.interactionState=n.state,n.effects.commit&&this.handleClipMoveEnd(r,t),this.layer.batchDraw()}finally{this.interactionState=ji(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}resolveDraggedClipForInteraction(e=this.interactionState){const t=Ct(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=Vh(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=Ct(i)||{clipId:e.id,originalClipsState:[e],nonDraggedClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:0,crossTrackDragOffsetY:0},n=Zi(i)||(e.isResizingLeft?"resize-left":e.isResizingRight?"resize-right":"move"),a=n==="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 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 A of this.selectedClipIds){const O=(v=this.clipGroups)==null?void 0:v.get(A);O==null||O.y(2)}this.multiDragOriginalPositions.clear();return}const w=[],x=[];for(const[P,A]of this.multiDragOriginalPositions){const O=this.clips.find(H=>H.getClip().id===P);if(!O)continue;const $=Math.max(0,A.startTime+C),F={...O.getClip(),startTime:$,endTime:$+A.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(P)};w.push(F);const V=r.originalClipsState.find(H=>H.id===P);V&&x.push(V);const z=(b=this.clipGroups)==null?void 0:b.get(P);z&&z.y(2)}const k=[];for(const P of this.clips){const A=P.getClip(),O=w.find($=>$.id===A.id);O?k.push(O):k.push({...A,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}k.sort((P,A)=>P.startTime-A.startTime),this.isVisualUpdate=!0;for(const P of k)this.clips.find(O=>O.getClip().id===P.id)&&this.handleClipUpdate(P);this.isVisualUpdate=!1;const D=x.map(P=>{const A=w.find(O=>O.id===P.id);return A&&(P.startTime!==A.startTime||P.duration!==A.duration)?{clipId:P.id,previousState:P,newState:A}:null}).filter(P=>P!==null);D.length>0&&this.onClipUpdate(e,x.find(P=>P.id===e.id),D),this.multiDragOriginalPositions.clear();return}if(a&&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=a?[...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(a&&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 x=u.findIndex(k=>k.id===w.id);x>=0&&(u[x]={...w,isSelected:!1})}}}let g=u.findIndex(S=>S.startTime>=e.startTime);g===-1&&(g=u.length),r.nonDraggedClips.forEach(S=>{S.isSelected=!1});const f={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};u.splice(g,0,f),this.updateAllClips(u),this.buildAndSendUpdates(f,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=zh({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 ls(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=Mi(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=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 Ni(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:U.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){B.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new Ni(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=Ct(t),r=Mi(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=$h({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||te.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(){B.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=pe(t,this.zoom,this.scrollLeft);o.x(c),o.y(this.resolveClipRenderY(e,r)),o.moveToTop(),de.updateClipGroup(o,ye(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=Ct(t);if(Ki(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,x,k;const r=this.interactionState,n=Ct(r),a=Zi(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,g=a==="move",f=g&&this.multiDragOriginalPositions.size>0;g&&B.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 D=g&&n.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(y.id,D);const P=n.originalClipsState.find(L=>L.id===y.id);if(!P)return;const A=this.buildPreviewClip(y,P,d,n,a);if(!A){this.hideDropPreview(),(S=this.onClearDropPreview)==null||S.call(this),this.updateSnapGuideLine(null);return}const O=A.clip,$=O.startTime-P.startTime,F=this.applyPreviewClipState(l,O),V=pe(O.startTime,this.zoom,this.scrollLeft),z=ye(O.duration,this.zoom);v.x(V),v.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)),v.visible(V+z>0&&V<this.layer.width()),F&&(this.updateClipGroup(O),v.y(this.resolveClipRenderY(y.id,n.crossTrackDragOffsetY)));let H=!1;if(f){this.onMultiDragMove&&this.config.id&&(H=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 G=this.clips.find(Y=>Y.getClip().id===L);if(!G)continue;const Q=Math.max(0,X.startTime+$),ae=(C=this.clipGroups)==null?void 0:C.get(L);if(ae){const Y=pe(Q,this.zoom,this.scrollLeft);ae.x(Y),ae.y(this.resolveClipRenderY(L,n.crossTrackDragOffsetY)),ae.visible(Y+ye(X.duration,this.zoom)>0&&Y<this.layer.width());const J=G.getClip();de.updateClipGroup(ae,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(!f&&A.resizePushFollowers.length>0)for(const L of A.resizePushFollowers){const X=(w=this.clipGroups)==null?void 0:w.get(L.id);if(!X)continue;const G=pe(L.startTime,this.zoom,this.scrollLeft);X.x(G),X.y(this.resolveClipRenderY(L.id,n.crossTrackDragOffsetY)),X.visible(G+ye(L.duration,this.zoom)>0&&G<this.layer.width())}g&&this.onClipCrossTrackPreview&&this.config.id&&!H?this.onClipCrossTrackPreview(O,n.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():H?this.hideDropPreview():this.showDropPreview(O),this.updateSnapGuideLine(A.guideTime)}else this.hideDropPreview(),(x=this.onClearDropPreview)==null||x.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(d,h.width),this.layer.batchDraw(),(k=this.dragOverlayLayer)==null||k.batchDraw()}buildPreviewClip(e,t,i,r,n){const a=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=U.pixelsToTime(a,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,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}}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),a=[...i].filter(h=>h.startTime>=n).sort((h,d)=>h.startTime-d.startTime);if(a.length===0)return[];const o=a[0],l=r-o.startTime;if(l<=0)return[];const c=l;return a.map(h=>({...h,startTime:h.startTime+c,endTime:h.startTime+c+h.duration}))}buildResizeLeftPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const g=U.calculateEndTime(t.startTime,t.duration);let f=Math.max(0,t.startTime+i),y=g-f;return y<ce.MIN_CLIP_DURATION_MS&&(y=ce.MIN_CLIP_DURATION_MS,f=g-y),{...e,startTime:f,duration:y,endTime:f+y,startTimeAtSource:0,endTimeAtSource:y,sourceDuration:y}}const n=Math.max(0,t.startTime+i)-t.startTime,o=Math.max(0,t.startTimeAtSource+i)-t.startTimeAtSource,l=Math.abs(n)<Math.abs(o)?n:o,c=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,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=U.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(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 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 Ji=ce;/**
14
+ `,_n=()=>{if(typeof document>"u")throw new Error(_o)};class ve{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 ve(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 Ao="[object Array]",Io="[object Number]",Eo="[object String]",Ro="[object Boolean]",Mo=Math.PI/180,Do=180/Math.PI,Bt="#",Lo="",Bo="0",Oo="Konva warning: ",An="Konva error: ",Fo="rgb(",ur={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]},No=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let bi=[],Ot=null;const Go=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)===Ao},_isNumber(s){return Object.prototype.toString.call(s)===Io&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===Eo},_isBoolean(s){return Object.prototype.toString.call(s)===Ro},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){bi.push(s),bi.length===1&&Go(function(){const e=bi;bi=[],e.forEach(function(t){t()})})},createCanvasElement(){_n();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return _n(),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(Bt,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=Bo+s;return Bt+s},isCanvasFarblingActive(){if(Ot!==null)return Ot;if(typeof document>"u")return Ot=!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 Ot=i,this.releaseCanvas(s),Ot},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),Bt+this._rgbToHex(s,e,t)},getSnappedHexColor(s){const e=this._hexToRgb(s);return Bt+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 ur?(e=ur[s],{r:e[0],g:e[1],b:e[2]}):s[0]===Bt?this._hexToRgb(s.substring(1)):s.substr(0,4)===Fo?(e=No.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=ur[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*Mo},radToDeg(s){return s*Do},_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 M.angleDeg?b.radToDeg(s):s},_capitalize(s){return s.charAt(0).toUpperCase()+s.slice(1)},throw(s){throw new Error(An+s)},error(s){console.error(An+s)},warn(s){M.showWarnings&&console.warn(Oo+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){M.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 p;typeof r=="number"?p=r:p=n<r.length?r[n]:0,p=i*Math.cos(Math.PI/t)*Math.min(1,p/i*2);const m={x:c.x/d,y:c.y/d},v={x:h.x/u,y:h.y/u},T={x:o.x-m.x*p,y:o.y-m.y*p},S={x:o.x+v.x*p,y:o.y+v.y*p};n===0?s.moveTo(T.x,T.y):s.lineTo(T.x,T.y),s.arcTo(o.x,o.y,S.x,S.y,p)}}};function Ho(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 In=",",$o="(",zo=")",Vo="([",Uo="])",Wo=";",Yo="()",Xo="=",En=["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"],qo=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],jo=100;let ki=null;function Rn(){if(ki!==null)return ki;try{const e=b.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(ki=!1,!1)}catch{return ki=!1,!1}}class sr{constructor(e){this.canvas=e,M.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+=Yo:b._isArray(c[0])?n+=Vo+c.join(In)+Uo:(t&&(c=c.map(h=>typeof h=="number"?Math.floor(h):h)),n+=$o+c.join(In)+zo)):(n+=o.property,e||(n+=Xo+o.val)),n+=Wo;return n}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=jo&&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=En.length,i=this.setAttr,r,n;const a=function(o){let l=e[o],c;e[o]=function(){return n=Ho(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(En[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)}}qo.forEach(function(s){Object.defineProperty(sr.prototype,s,{get(){return this._context[s]},set(e){this._context[s]=e}})});class Ko extends sr{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 Zo extends sr{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 wi;function Jo(){if(wi)return wi;const s=b.createCanvasElement(),e=s.getContext("2d");return wi=function(){const t=M._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),b.releaseCanvas(s),wi}class un{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||M.pixelRatio||Jo();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 Ke extends un{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new Ko(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class pn extends un{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new Zo(this),this.setSize(e.width,e.height)}}const J={get isDragging(){let s=!1;return J._dragElements.forEach(e=>{e.dragStatus==="dragging"&&(s=!0)}),s},justDragged:!1,get node(){let s;return J._dragElements.forEach(e=>{s=e.node}),s},_dragElements:new Map,_drag(s){const e=[];J._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=[];J._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")&&(J.justDragged=!0,M._mouseListenClick=!1,M._touchListenClick=!1,M._pointerListenClick=!1,t.dragStatus="stopped");const a=t.node.getLayer()||t.node instanceof M.Stage&&t.node;a&&e.indexOf(a)===-1&&e.push(a)}),e.forEach(t=>{t.draw()})},_endDragAfter(s){J._dragElements.forEach((e,t)=>{e.dragStatus==="stopped"&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:s},!0),e.dragStatus!=="dragging"&&J._dragElements.delete(t)})}};M.isBrowser&&(window.addEventListener("mouseup",J._endDragBefore,!0),window.addEventListener("touchend",J._endDragBefore,!0),window.addEventListener("touchcancel",J._endDragBefore,!0),window.addEventListener("mousemove",J._drag),window.addEventListener("touchmove",J._drag),window.addEventListener("mouseup",J._endDragAfter,!1),window.addEventListener("touchend",J._endDragAfter,!1),window.addEventListener("touchcancel",J._endDragAfter,!1));function et(s){return b._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||b._isBoolean(s)?s:Object.prototype.toString.call(s)}function sa(s){return s>255?255:s<0?0:Math.round(s)}function R(){if(M.isUnminified)return function(s,e){return b._isNumber(s)||b.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),s}}function ar(s){if(M.isUnminified)return function(e,t){let i=b._isNumber(e),r=b._isArray(e)&&e.length==s;return!i&&!r&&b.warn(et(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+s+")"),e}}function gn(){if(M.isUnminified)return function(s,e){return b._isNumber(s)||s==="auto"||b.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),s}}function pt(){if(M.isUnminified)return function(s,e){return b._isString(s)||b.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),s}}function aa(){if(M.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(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),s}}function Qo(){if(M.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(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),s}}function Ie(){if(M.isUnminified)return function(s,e){return s===!0||s===!1||b.warn(et(s)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),s}}function el(s){if(M.isUnminified)return function(e,t){return e==null||b.isObject(e)||b.warn(et(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+s),e}}const Ft="get",Nt="set",y={addGetterSetter(s,e,t,i,r){y.addGetter(s,e,t),y.addSetter(s,e,i,r),y.addOverloadedGetterSetter(s,e)},addGetter(s,e,t){const i=Ft+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=Nt+b._capitalize(e);s.prototype[r]||y.overWriteSetter(s,e,t,i)},overWriteSetter(s,e,t,i){const r=Nt+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=Ft+a(e),l=Nt+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=el(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},y.addOverloadedGetterSetter(s,e)},addOverloadedGetterSetter(s,e){const t=b._capitalize(e),i=Nt+t,r=Ft+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=Ft+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},y.addSetter(s,e,i,function(){b.error(n)}),y.addOverloadedGetterSetter(s,e)},backCompat(s,e){b.each(e,function(t,i){const r=s.prototype[i],n=Ft+b._capitalize(t),a=Nt+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 tl(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=M.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=M.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=M.Filters;l&&l.Contrast&&l.Contrast.call(this,a)}}case"grayscale":return function(n){const a=M.Filters;a&&a.Grayscale&&a.Grayscale.call(this,n)};case"sepia":return function(n){const a=M.Filters;a&&a.Sepia&&a.Sepia.call(this,n)};case"invert":return function(n){const a=M.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 Gi="absoluteOpacity",Mn="allEventListeners",He="absoluteTransform",Dn="absoluteScale",nt="canvas",il="Change",rl="children",nl="konva",Or="listening",sl="mouseenter",al="mouseleave",ol="pointerenter",ll="pointerleave",cl="touchenter",hl="touchleave",Ln="set",Bn="Shape",Hi=" ",On="stage",Xe="transform",dl="Stage",Fr="visible",ul=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Hi);let pl=1;class E{constructor(e){this._id=pl++,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===Xe||e===He)&&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===Xe||e===He)&&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(Hi);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(nt)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===He&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(nt)){const{scene:e,filter:t,hit:i}=this._cache.get(nt);b.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(nt)}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,p=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=c*2+u,n+=c*2+p,o-=c,l-=c;const f=new Ke({pixelRatio:a,width:r,height:n}),m=new Ke({pixelRatio:a,width:0,height:0,willReadFrequently:!0}),v=new pn({pixelRatio:d,width:r,height:n}),T=f.getContext(),S=v.getContext(),C=new Ke({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(l),pixelRatio:f.pixelRatio}),k=C.getContext();return v.isCache=!0,f.isCache=!0,this._cache.delete(nt),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,m.getContext()._context.imageSmoothingEnabled=!1),T.save(),S.save(),k.save(),T.translate(-o,-l),S.translate(-o,-l),k.translate(-o,-l),C.x=o,C.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Gi),this._clearSelfAndDescendantCache(Dn),this.drawScene(f,this,C),this.drawHit(v,this),this._isUnderCache=!1,T.restore(),S.restore(),h&&(T.save(),T.beginPath(),T.rect(0,0,r,n),T.closePath(),T.setAttr("strokeStyle","red"),T.setAttr("lineWidth",5),T.stroke(),T.restore()),b.releaseCanvas(C._canvas),this._cache.set(nt,{scene:f,filter:m,hit:v,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(nt)}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"&&Rn(),typeof e[u]!="string"||!Rn()){h=!1;break}const d=i.pixelRatio;if(r.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),h){const u=e.join(" ");return n.save(),n.setAttr("filter",u),n.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),n.restore(),this._filterUpToDate=!0,r}try{for(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=tl(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(Mn),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Hi);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(Hi),r=i.length,n,a,o,l,c,h;if(this._cache&&this._cache.delete(Mn),!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(),J._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(He),this._clearSelfAndDescendantCache(Gi),this._clearSelfAndDescendantCache(Dn),this._clearSelfAndDescendantCache(On),this._clearSelfAndDescendantCache(Fr),this._clearSelfAndDescendantCache(Or)}_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!==rl&&(i=Ln+b._capitalize(t),b._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(Or,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(Fr,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;J._dragElements.forEach(a=>{a.dragStatus==="dragging"&&(a.node.nodeType==="Stage"||a.node.getLayer()===i)&&(r=!0)});const n=!t&&!M.hitOnDragEnabled&&(r||M.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!==Bn&&(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!==dl&&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(Xe),this._clearSelfAndDescendantCache(He)),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 ve,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(Xe);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(Xe),this._clearSelfAndDescendantCache(He),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(Gi,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(On,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(He,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new ve,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(He)||new ve,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(Xe,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get(Xe)||new ve;i.reset();const r=this.x(),n=this.y(),a=M.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(nl)<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 Ke({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 Ke({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():M.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+il,{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[Ln+b._capitalize(e)];return b._isFunction(i)?i.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(M.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===Bn&&(t.target=this);const r=[sl,al,ol,ll,cl,hl];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;J._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){J._dragElements.has(this._id)||this._createDragElement(e);const i=J._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=J._dragElements.get(this._id);t&&(t.dragStatus="stopped"),J._endDragBefore(e),J._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=J._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)||M.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let r=!1;J._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=J._dragElements.get(this._id),i=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";i?this.stopDrag():r&&J._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),M[i]||(b.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=M[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,ul,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache(Xe),this._clearSelfAndDescendantCache(He)});E.prototype.on.call(E.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(Fr)});E.prototype.on.call(E.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(Or)});E.prototype.on.call(E.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Gi)});const ie=y.addGetterSetter;ie(E,"zIndex");ie(E,"absolutePosition");ie(E,"position");ie(E,"x",0,R());ie(E,"y",0,R());ie(E,"globalCompositeOperation","source-over",pt());ie(E,"opacity",1,R());ie(E,"name","",pt());ie(E,"id","",pt());ie(E,"rotation",0,R());y.addComponentsGetterSetter(E,"scale",["x","y"]);ie(E,"scaleX",1,R());ie(E,"scaleY",1,R());y.addComponentsGetterSetter(E,"skew",["x","y"]);ie(E,"skewX",0,R());ie(E,"skewY",0,R());y.addComponentsGetterSetter(E,"offset",["x","y"]);ie(E,"offsetX",0,R());ie(E,"offsetY",0,R());ie(E,"dragDistance",void 0,R());ie(E,"width",0,R());ie(E,"height",0,R());ie(E,"listening",!0,Ie());ie(E,"preventDefault",!0,Ie());ie(E,"filters",void 0,function(s){return this._filterUpToDate=!1,s});ie(E,"visible",!0,Ie());ie(E,"transformsEnabled","all",pt());ie(E,"size");ie(E,"dragBoundFunc");ie(E,"draggable",!1,Ie());y.backCompat(E,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class Ce 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 p=this.getAbsoluteTransform(i);let f=p.getMatrix();a.transform(f[0],f[1],f[2],f[3],f[4],f[5]),a.beginPath();let m;if(c)m=c.call(this,a,this);else{const v=this.clipX(),T=this.clipY();a.rect(v||0,T||0,o,l)}a.clip.apply(a,m),f=p.copy().invert().getMatrix(),a.transform(f[0],f[1],f[2],f[3],f[4],f[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(p){p[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(p){if(!p.visible())return;const f=p.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});f.width===0&&f.height===0||(n===void 0?(n=f.x,a=f.y,o=f.x+f.width,l=f.y+f.height):(n=Math.min(n,f.x),a=Math.min(a,f.y),o=Math.max(o,f.x+f.width),l=Math.max(l,f.y+f.height)))});const d=this.find("Shape");let u=!1;for(let p=0;p<d.length;p++)if(d[p]._isVisible(this)){u=!0;break}return u&&n!==void 0?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)}}y.addComponentsGetterSetter(Ce,"clip",["x","y","width","height"]);y.addGetterSetter(Ce,"clipX",void 0,R());y.addGetterSetter(Ce,"clipY",void 0,R());y.addGetterSetter(Ce,"clipWidth",void 0,R());y.addGetterSetter(Ce,"clipHeight",void 0,R());y.addGetterSetter(Ce,"clipFunc");const hi=new Map,oa=M._global.PointerEvent!==void 0;function pr(s){return hi.get(s)}function fn(s){return{evt:s,pointerId:s.pointerId}}function la(s,e){return hi.get(s)===e}function ca(s,e){Qt(s),e.getStage()&&(hi.set(s,e),oa&&e._fire("gotpointercapture",fn(new PointerEvent("gotpointercapture"))))}function Qt(s,e){const t=hi.get(s);if(!t)return;const i=t.getStage();i&&i.content,hi.delete(s),oa&&t._fire("lostpointercapture",fn(new PointerEvent("lostpointercapture")))}const gl="Stage",fl="string",Fn="px",ml="mouseout",ha="mouseleave",da="mouseover",ua="mouseenter",pa="mousemove",ga="mousedown",fa="mouseup",Yt="pointermove",Xt="pointerdown",Pt="pointerup",qt="pointercancel",yl="lostpointercapture",Pi="pointerout",jt="pointerleave",xi="pointerover",_i="pointerenter",Nr="contextmenu",ma="touchstart",ya="touchend",Sa="touchmove",va="touchcancel",Gr="wheel",Sl=5,vl=[[ua,"_pointerenter"],[ga,"_pointerdown"],[pa,"_pointermove"],[fa,"_pointerup"],[ha,"_pointerleave"],[ma,"_pointerdown"],[Sa,"_pointermove"],[ya,"_pointerup"],[va,"_pointercancel"],[da,"_pointerover"],[Gr,"_wheel"],[Nr,"_contextmenu"],[Xt,"_pointerdown"],[Yt,"_pointermove"],[Pt,"_pointerup"],[qt,"_pointercancel"],[jt,"_pointerleave"],[yl,"_lostpointercapture"]],gr={mouse:{[Pi]:ml,[jt]:ha,[xi]:da,[_i]:ua,[Yt]:pa,[Xt]:ga,[Pt]:fa,[qt]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Pi]:"touchout",[jt]:"touchleave",[xi]:"touchover",[_i]:"touchenter",[Yt]:Sa,[Xt]:ma,[Pt]:ya,[qt]:va,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Pi]:Pi,[jt]:jt,[xi]:xi,[_i]:_i,[Yt]:Yt,[Xt]:Xt,[Pt]:Pt,[qt]:qt,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Kt=s=>s.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",St=s=>{const e=Kt(s);if(e==="pointer")return M.pointerEventsEnabled&&gr.pointer;if(e==="touch")return gr.touch;if(e==="mouse")return gr.mouse};function Nn(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&b.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const Cl="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);",ei=[];class or extends Ce{constructor(e){super(Nn(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),ei.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{Nn(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===fl){let t;if(e.charAt(0)==="."){const i=e.slice(1);e=document.getElementsByClassName(i)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),Ce.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&b._isInDocument(e)&&this.container().removeChild(e);const t=ei.indexOf(this);return t>-1&&ei.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(Cl),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 Ke({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+Fn,this.content.style.height=t+Fn),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>Sl&&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(),M.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return la(e,this)}setPointerCapture(e){ca(e,this)}releaseCapture(e){Qt(e)}getLayers(){return this.children}_bindContentEvents(){M.isBrowser&&vl.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=St(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=St(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=St(e.type),i=Kt(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(i),n=!(M.isDragging()||M.isTransforming())||M.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=St(e.type),i=Kt(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(n=>{const a=this.getIntersection(n);if(J.justDragged=!1,M["_"+i+"ListenClick"]=!0,!a||!a.isListening()){this[i+"ClickStartShape"]=void 0;return}M.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=St(e.type),i=Kt(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(M.isDragging()&&J.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(M.isDragging()||M.isTransforming())||M.hitOnDragEnabled))return;const a={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(c=>{const h=pr(c.id)||this.getIntersection(c),d=c.id,u={evt:e,pointerId:d},p=l!==h;if(p&&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,p&&(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=St(e.type),i=Kt(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=pr(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;M["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):J.justDragged||(M["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){M["_"+i+"InDblClickWindow"]=!1},M.dblClickWindow),c&&c.isListening()?(o=!0,this[i+"ClickEndShape"]=c,c._fireAndBubble(t.pointerup,{...d}),M["_"+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),M["_"+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}),M["_"+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(Nr,{evt:e}):this._fire(Nr,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Gr,{evt:e}):this._fire(Gr,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=pr(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(Pt,fn(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: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 Ke({width:this.width(),height:this.height()}),this.bufferHitCanvas=new pn({pixelRatio:1,width:this.width(),height:this.height()}),!M.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}}or.prototype.nodeType=gl;oe(or);y.addGetterSetter(or,"container");M.isBrowser&&document.addEventListener("visibilitychange",()=>{ei.forEach(s=>{s.batchDraw()})});const Ca="hasShadow",Ta="shadowRGBA",ba="patternImage",ka="linearGradient",wa="radialGradient";let Ai;function fr(){return Ai||(Ai=b.createCanvasElement().getContext("2d"),Ai)}const ti={};function Tl(s){const e=this.attrs.fillRule;e?s.fill(e):s.fill()}function bl(s){s.stroke()}function kl(s){const e=this.attrs.fillRule;e?s.fill(e):s.fill()}function wl(s){s.stroke()}function Pl(){this._clearCache(Ca)}function xl(){this._clearCache(Ta)}function _l(){this._clearCache(ba)}function Al(){this._clearCache(ka)}function Il(){this._clearCache(wa)}class I extends E{constructor(e){super(e);let t,i=0;for(;t=b.getHitColor(),!(t&&!(t in ti));)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,ti[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(Ca,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(ba,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=fr().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new ve;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(M.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(ka,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=fr(),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(wa,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=fr(),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(Ta,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 ti[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,p=d?this.shadowOffsetY():0,f=c+Math.abs(u),m=h+Math.abs(p),v=d&&this.shadowBlur()||0,T=f+v*2,S=m+v*2,C={width:T,height:S,x:-(l/2+v)+Math.min(u,0)+a.x,y:-(l/2+v)+Math.min(p,0)+a.y};return r?C:this._transformedRect(C,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,p=u.getContext();i?(p.save(),p.setTransform(1,0,0,1,0,0),p.clearRect(0,0,u.width,u.height),p.restore()):p.clear(),p.save(),p._applyLineJoin(this),p._applyMiterLimit(this);const f=this.getAbsoluteTransform(t).getMatrix();p.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.call(this,p,this),p.restore();const m=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/m,u.height/m)}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 la(e,this)}setPointerCapture(e){ca(e,this)}releaseCapture(e){Qt(e)}}I.prototype._fillFunc=Tl;I.prototype._strokeFunc=bl;I.prototype._fillFuncHit=kl;I.prototype._strokeFuncHit=wl;I.prototype._centroid=!1;I.prototype.nodeType="Shape";oe(I);I.prototype.eventListeners={};I.prototype.on.call(I.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Pl);I.prototype.on.call(I.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",xl);I.prototype.on.call(I.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",_l);I.prototype.on.call(I.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Al);I.prototype.on.call(I.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Il);y.addGetterSetter(I,"stroke",void 0,aa());y.addGetterSetter(I,"strokeWidth",2,R());y.addGetterSetter(I,"fillAfterStrokeEnabled",!1);y.addGetterSetter(I,"hitStrokeWidth","auto",gn());y.addGetterSetter(I,"strokeHitEnabled",!0,Ie());y.addGetterSetter(I,"perfectDrawEnabled",!0,Ie());y.addGetterSetter(I,"shadowForStrokeEnabled",!0,Ie());y.addGetterSetter(I,"lineJoin");y.addGetterSetter(I,"lineCap");y.addGetterSetter(I,"miterLimit");y.addGetterSetter(I,"sceneFunc");y.addGetterSetter(I,"hitFunc");y.addGetterSetter(I,"dash");y.addGetterSetter(I,"dashOffset",0,R());y.addGetterSetter(I,"shadowColor",void 0,pt());y.addGetterSetter(I,"shadowBlur",0,R());y.addGetterSetter(I,"shadowOpacity",1,R());y.addComponentsGetterSetter(I,"shadowOffset",["x","y"]);y.addGetterSetter(I,"shadowOffsetX",0,R());y.addGetterSetter(I,"shadowOffsetY",0,R());y.addGetterSetter(I,"fillPatternImage");y.addGetterSetter(I,"fill",void 0,aa());y.addGetterSetter(I,"fillPatternX",0,R());y.addGetterSetter(I,"fillPatternY",0,R());y.addGetterSetter(I,"fillLinearGradientColorStops");y.addGetterSetter(I,"strokeLinearGradientColorStops");y.addGetterSetter(I,"fillRadialGradientStartRadius",0);y.addGetterSetter(I,"fillRadialGradientEndRadius",0);y.addGetterSetter(I,"fillRadialGradientColorStops");y.addGetterSetter(I,"fillPatternRepeat","repeat");y.addGetterSetter(I,"fillEnabled",!0);y.addGetterSetter(I,"strokeEnabled",!0);y.addGetterSetter(I,"shadowEnabled",!0);y.addGetterSetter(I,"dashEnabled",!0);y.addGetterSetter(I,"strokeScaleEnabled",!0);y.addGetterSetter(I,"fillPriority","color");y.addComponentsGetterSetter(I,"fillPatternOffset",["x","y"]);y.addGetterSetter(I,"fillPatternOffsetX",0,R());y.addGetterSetter(I,"fillPatternOffsetY",0,R());y.addComponentsGetterSetter(I,"fillPatternScale",["x","y"]);y.addGetterSetter(I,"fillPatternScaleX",1,R());y.addGetterSetter(I,"fillPatternScaleY",1,R());y.addComponentsGetterSetter(I,"fillLinearGradientStartPoint",["x","y"]);y.addComponentsGetterSetter(I,"strokeLinearGradientStartPoint",["x","y"]);y.addGetterSetter(I,"fillLinearGradientStartPointX",0);y.addGetterSetter(I,"strokeLinearGradientStartPointX",0);y.addGetterSetter(I,"fillLinearGradientStartPointY",0);y.addGetterSetter(I,"strokeLinearGradientStartPointY",0);y.addComponentsGetterSetter(I,"fillLinearGradientEndPoint",["x","y"]);y.addComponentsGetterSetter(I,"strokeLinearGradientEndPoint",["x","y"]);y.addGetterSetter(I,"fillLinearGradientEndPointX",0);y.addGetterSetter(I,"strokeLinearGradientEndPointX",0);y.addGetterSetter(I,"fillLinearGradientEndPointY",0);y.addGetterSetter(I,"strokeLinearGradientEndPointY",0);y.addComponentsGetterSetter(I,"fillRadialGradientStartPoint",["x","y"]);y.addGetterSetter(I,"fillRadialGradientStartPointX",0);y.addGetterSetter(I,"fillRadialGradientStartPointY",0);y.addComponentsGetterSetter(I,"fillRadialGradientEndPoint",["x","y"]);y.addGetterSetter(I,"fillRadialGradientEndPointX",0);y.addGetterSetter(I,"fillRadialGradientEndPointY",0);y.addGetterSetter(I,"fillPatternRotation",0);y.addGetterSetter(I,"fillRule",void 0,pt());y.backCompat(I,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const El="beforeDraw",Rl="draw",Pa=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Ml=Pa.length;class gt extends Ce{constructor(e){super(e),this.canvas=new Ke,this.hitCanvas=new pn({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<Ml;r++){const n=Pa[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=ti[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(El,{node:this}),this.clearBeforeDraw()&&n.getContext().clear(),Ce.prototype.drawScene.call(this,n,t,i),this._fire(Rl,{node:this}),this}drawHit(e,t){const i=this.getLayer(),r=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),Ce.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;!!this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return b.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}gt.prototype.nodeType="Layer";oe(gt);y.addGetterSetter(gt,"imageSmoothingEnabled",!0);y.addGetterSetter(gt,"clearBeforeDraw",!0);y.addGetterSetter(gt,"hitGraphEnabled",!0,Ie());class mn extends gt{constructor(e){super(e),this.listening(!1),b.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}mn.prototype.nodeType="FastLayer";oe(mn);class It extends Ce{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to groups.")}}It.prototype.nodeType="Group";oe(It);const mr=function(){return lt.performance&&lt.performance.now?function(){return lt.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:mr(),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=mr(),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(mr());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 Dl={node:1,duration:1,easing:1,onFinish:1,yoyo:1},Ll=1,Gn=2,Hn=3,$n=["fill","stroke","shadowColor"];let Bl=0;class Ol{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=Gn,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Hn,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===Gn?this.setTime(e):this.state===Hn&&this.setTime(this.duration-e)}pause(){this.state=Ll,this.fire("onPause")}getTimer(){return new Date().getTime()}}class re{constructor(e){const t=this,i=e.node,r=i._id,n=e.easing||ii.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=Bl++;const c=i.getLayer()||(i instanceof M.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 Ol(l,function(h){t._tweenFunc(h)},n,0,1,o*1e3,a),this._addListeners(),re.attrs[r]||(re.attrs[r]={}),re.attrs[r][this._id]||(re.attrs[r][this._id]={}),re.tweens[r]||(re.tweens[r]={});for(l in e)Dl[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=re.tweens[r][e];h&&delete re.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 p=b.colorToRGBA(d[u]);c=b.colorToRGBA(t[u]),d[u]=p,n.push({r:c.r-p.r,g:c.g-p.g,b:c.b-p.b,a:c.a-p.a})}else for(let u=0;u<a;u++)n.push(t[u]-d[u]);else $n.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;re.attrs[r][this._id][e]={start:d,diff:n,end:t,trueEnd:o,trueStart:l},re.tweens[r][e]=this._id}_tweenFunc(e){const t=this.node,i=re.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 $n.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=re.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=re.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=re.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const r in i)delete re.tweens[e][r];delete re.attrs[e][t],re.tweens[e]&&(Object.keys(re.tweens[e]).length===0&&delete re.tweens[e],Object.keys(re.attrs[e]).length===0&&delete re.attrs[e])}}re.attrs={};re.tweens={};E.prototype.to=function(s){const e=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),e&&e()},new re(s).play()};const ii={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-ii.BounceEaseOut(i-s,0,t,i)+e},BounceEaseInOut(s,e,t,i){return s<i/2?ii.BounceEaseIn(s*2,0,t,i)*.5+e:ii.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}},zn=b._assign(M,{Util:b,Transform:ve,Node:E,Container:Ce,Stage:or,stages:ei,Layer:gt,FastLayer:mn,Group:It,DD:J,Shape:I,shapes:ti,Animation:we,Tween:re,Easings:ii,Context:sr,Canvas:un});class $e extends I{_sceneFunc(e){const t=M.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=M.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}}}$e.prototype._centroid=!0;$e.prototype.className="Arc";$e.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];oe($e);y.addGetterSetter($e,"innerRadius",0,R());y.addGetterSetter($e,"outerRadius",0,R());y.addGetterSetter($e,"angle",0,R());y.addGetterSetter($e,"clockwise",!1,Ie());function Hr(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),p=t+h*(r-s),f=i+h*(n-e);return[d,u,p,f]}function Vn(s,e){const t=s.length,i=[];for(let r=2;r<t-2;r+=2){const n=Hr(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 Fl(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 ze extends I{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():Vn(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=Hr(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),n=Hr(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),a=Vn(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],...Fl(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}}}ze.prototype.className="Line";ze.prototype._attrsAffectingSize=["points","bezier","tension"];oe(ze);y.addGetterSetter(ze,"closed",!1);y.addGetterSetter(ze,"bezier",!1);y.addGetterSetter(ze,"tension",0,R());y.addGetterSetter(ze,"points",[],Qo());const Nl=[[],[],[-.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]],Hl=[[1],[1,1],[1,2,1],[1,3,3,1]],Un=(s,e,t)=>{let i,r;const a=t/2;i=0;for(let o=0;o<20;o++)r=a*Nl[20][o]+a,i+=Gl[20][o]*$l(s,e,r);return a*i},Wn=(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,p=d-h*h,f=u*u+p>0?Math.sqrt(u*u+p):0,m=h*h+p>0?Math.sqrt(h*h+p):0,v=h+Math.sqrt(h*h+p)!==0?p*Math.log(Math.abs((u+f)/(h+m))):0;return Math.sqrt(o)/2*(u*f-h*m+v)};function $l(s,e,t){const i=$r(1,t,s),r=$r(1,t,e),n=i*i+r*r;return Math.sqrt(n)}const $r=(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+=Hl[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 $r(s-1,e,r)}},Yn=(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 ne extends I{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=ne.parsePathData(this.data()),this.pathLength=ne.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],p=a[6],f=a[7],m=c>h?c:h,v=c>h?1:c/h,T=c>h?h/c:1;e.translate(o,l),e.rotate(p),e.scale(v,T),e.arc(0,0,m,d,d+u,1-f),e.scale(1/v,1/T),e.rotate(-p),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 p=c-u;p>d;p-=u){const f=ne.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);e.push(f.x,f.y)}else for(let p=c+u;p<d;p+=u){const f=ne.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],p,0);e.push(f.x,f.y)}}else if(l.command==="C")for(let c=0;c<=1;c+=.01){const h=ne.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 ne.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 ne.getPointOnLine(e,a.start.x,a.start.y,o[0],o[1]);case"C":return ne.getPointOnCubicBezier(Yn(e,ne.getPathLength(t),m=>Un([a.start.x,o[0],o[2],o[4]],[a.start.y,o[1],o[3],o[5]],m)),a.start.x,a.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return ne.getPointOnQuadraticBezier(Yn(e,ne.getPathLength(t),m=>Wn([a.start.x,o[0],o[2]],[a.start.y,o[1],o[3]],m)),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],p=o[6];let f=o[4];return f+=u*e/a.pathLength,ne.getPointOnEllipticalArc(l,c,h,d,f,p)}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),p=t+u*(r-t),f=i+u*(n-i),m=this.getLineLength(a,o,p,f),v=Math.sqrt(e*e-m*m),T=Math.sqrt(v*v/(1+c*c))*(r<t?-1:1),S=c*T;return{x:p+T,y:f+S}}static getPointOnCubicBezier(e,t,i,r,n,a,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 p(v){return(1-v)*(1-v)*(1-v)}const f=l*h(e)+a*d(e)+r*u(e)+t*p(e),m=c*h(e)+o*d(e)+n*u(e)+i*p(e);return{x:f,y:m}}static getPointOnQuadraticBezier(e,t,i,r,n,a,o){function l(p){return p*p}function c(p){return 2*p*(1-p)}function h(p){return(1-p)*(1-p)}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],p=u.charAt(0);for(u=u.slice(1),a.length=0;h=c.exec(u);)a.push(h[0]);let f=[],m=p==="A"||p==="a"?0:-1;for(let v=0,T=a.length;v<T;v++){const S=a[v];if(S==="00"){f.push(0,0),m>=0&&(m+=2,m>=7&&(m-=7));continue}if(m>=0){if(m===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),f.push(parseFloat(S.slice(2))),m+=3,m>=7&&(m-=7);continue}if(S==="11"||S==="10"||S==="01"){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),m+=2,m>=7&&(m-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),m+=1,m>=7&&(m-=7);continue}}else if(m===4){if(/^[01]\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseFloat(S.slice(1))),m+=2,m>=7&&(m-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),m+=1,m>=7&&(m-=7);continue}}const C=parseFloat(S);isNaN(C)?f.push(0):f.push(C),m+=1,m>=7&&(m-=7)}else{const C=parseFloat(S);isNaN(C)?f.push(0):f.push(C)}}for(;f.length>0&&!isNaN(f[0]);){let v="",T=[];const S=o,C=l;let k,x,P,D,w,A,B,$,F,V;switch(p){case"l":o+=f.shift(),l+=f.shift(),v="L",T.push(o,l);break;case"L":o=f.shift(),l=f.shift(),T.push(o,l);break;case"m":const z=f.shift(),H=f.shift();if(o+=z,l+=H,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]+H;break}}T.push(o,l),p="l";break;case"M":o=f.shift(),l=f.shift(),v="M",T.push(o,l),p="L";break;case"h":o+=f.shift(),v="L",T.push(o,l);break;case"H":o=f.shift(),v="L",T.push(o,l);break;case"v":l+=f.shift(),v="L",T.push(o,l);break;case"V":l=f.shift(),v="L",T.push(o,l);break;case"C":T.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),l=f.shift(),T.push(o,l);break;case"c":T.push(o+f.shift(),l+f.shift(),o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="C",T.push(o,l);break;case"S":x=o,P=l,k=n[n.length-1],k.command==="C"&&(x=o+(o-k.points[2]),P=l+(l-k.points[3])),T.push(x,P,f.shift(),f.shift()),o=f.shift(),l=f.shift(),v="C",T.push(o,l);break;case"s":x=o,P=l,k=n[n.length-1],k.command==="C"&&(x=o+(o-k.points[2]),P=l+(l-k.points[3])),T.push(x,P,o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="C",T.push(o,l);break;case"Q":T.push(f.shift(),f.shift()),o=f.shift(),l=f.shift(),T.push(o,l);break;case"q":T.push(o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),v="Q",T.push(o,l);break;case"T":x=o,P=l,k=n[n.length-1],k.command==="Q"&&(x=o+(o-k.points[0]),P=l+(l-k.points[1])),o=f.shift(),l=f.shift(),v="Q",T.push(x,P,o,l);break;case"t":x=o,P=l,k=n[n.length-1],k.command==="Q"&&(x=o+(o-k.points[0]),P=l+(l-k.points[1])),o+=f.shift(),l+=f.shift(),v="Q",T.push(x,P,o,l);break;case"A":D=f.shift(),w=f.shift(),A=f.shift(),B=f.shift(),$=f.shift(),F=o,V=l,o=f.shift(),l=f.shift(),v="A",T=this.convertEndpointToCenterParameterization(F,V,o,l,B,$,D,w,A);break;case"a":D=f.shift(),w=f.shift(),A=f.shift(),B=f.shift(),$=f.shift(),F=o,V=l,o+=f.shift(),l+=f.shift(),v="A",T=this.convertEndpointToCenterParameterization(F,V,o,l,B,$,D,w,A);break}n.push({command:v||p,points:T,start:{x:S,y:C},pathLength:this.calcLength(S,C,v||p,T)})}(p==="z"||p==="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=ne;switch(i){case"L":return c.getLineLength(e,t,r[0],r[1]);case"C":return Un([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return Wn([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 p=Math.PI/180;if(Math.abs(h-u)<p&&(p=Math.abs(h-u)),a=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),d<0)for(l=h-p;l>u;l-=p)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+p;l<u;l+=p)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,p=d*d/(o*o)+u*u/(l*l);p>1&&(o*=Math.sqrt(p),l*=Math.sqrt(p));let f=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));n===a&&(f*=-1),isNaN(f)&&(f=0);const m=f*o*u/l,v=f*-l*d/o,T=(e+i)/2+Math.cos(h)*m-Math.sin(h)*v,S=(t+r)/2+Math.sin(h)*m+Math.cos(h)*v,C=function(B){return Math.sqrt(B[0]*B[0]+B[1]*B[1])},k=function(B,$){return(B[0]*$[0]+B[1]*$[1])/(C(B)*C($))},x=function(B,$){return(B[0]*$[1]<B[1]*$[0]?-1:1)*Math.acos(k(B,$))},P=x([1,0],[(d-m)/o,(u-v)/l]),D=[(d-m)/o,(u-v)/l],w=[(-1*d-m)/o,(-1*u-v)/l];let A=x(D,w);return k(D,w)<=-1&&(A=Math.PI),k(D,w)>=1&&(A=0),a===0&&A>0&&(A=A-2*Math.PI),a===1&&A<0&&(A=A+2*Math.PI),[T,S,o,l,P,A,h,a]}}ne.prototype.className="Path";ne.prototype._attrsAffectingSize=["data"];oe(ne);y.addGetterSetter(ne,"data");class ft extends ze{_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]],p=ne.calcLength(r[r.length-4],r[r.length-3],"C",u),f=ne.getPointOnQuadraticBezier(Math.min(1,1-a/p),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-f.x,c=i[o-1]-f.y}else l=i[o-2]-i[o-4],c=i[o-1]-i[o-3];const h=(Math.atan2(c,l)+t)%t,d=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(i[o-2],i[o-1]),e.rotate(h),e.moveTo(0,0),e.lineTo(-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}}}ft.prototype.className="Arrow";oe(ft);y.addGetterSetter(ft,"pointerLength",10,R());y.addGetterSetter(ft,"pointerWidth",10,R());y.addGetterSetter(ft,"pointerAtBeginning",!1);y.addGetterSetter(ft,"pointerAtEnding",!0);class Dt extends I{_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)}}Dt.prototype._centroid=!0;Dt.prototype.className="Circle";Dt.prototype._attrsAffectingSize=["radius"];oe(Dt);y.addGetterSetter(Dt,"radius",0,R());class tt extends I{_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)}}tt.prototype.className="Ellipse";tt.prototype._centroid=!0;tt.prototype._attrsAffectingSize=["radiusX","radiusY"];oe(tt);y.addComponentsGetterSetter(tt,"radius",["x","y"]);y.addGetterSetter(tt,"radiusX",0,R());y.addGetterSetter(tt,"radiusY",0,R());let Ee=class xa extends I{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 xa({image:r});t(n)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Ee.prototype.className="Image";Ee.prototype._attrsAffectingSize=["image"];oe(Ee);y.addGetterSetter(Ee,"cornerRadius",0,ar(4));y.addGetterSetter(Ee,"image");y.addComponentsGetterSetter(Ee,"crop",["x","y","width","height"]);y.addGetterSetter(Ee,"cropX",0,R());y.addGetterSetter(Ee,"cropY",0,R());y.addGetterSetter(Ee,"cropWidth",0,R());y.addGetterSetter(Ee,"cropHeight",0,R());const _a=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],zl="Change.konva",Vl="none",zr="up",Vr="right",Ur="down",Wr="left",Ul=_a.length;class yn extends It{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<Ul;i++)e.on(_a[i]+zl,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 zr:o=i/2,l=-1*c;break;case Vr:o=i+a,l=r/2;break;case Ur:o=i/2,l=r+c;break;case Wr: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})}}}yn.prototype.className="Label";oe(yn);class mt extends I{_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===zr&&(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===Vr&&(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===Ur&&(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===Wr&&(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===zr?(t-=r,o+=r):n===Ur?o+=r:n===Wr?(e-=i*1.5,a+=i):n===Vr&&(a+=i*1.5),{x:e,y:t,width:a,height:o}}}mt.prototype.className="Tag";oe(mt);y.addGetterSetter(mt,"pointerDirection",Vl);y.addGetterSetter(mt,"pointerWidth",0,R());y.addGetterSetter(mt,"pointerHeight",0,R());y.addGetterSetter(mt,"cornerRadius",0,ar(4));class vi extends I{_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)}}vi.prototype.className="Rect";oe(vi);y.addGetterSetter(vi,"cornerRadius",0,ar(4));class it extends I{_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)}}it.prototype.className="RegularPolygon";it.prototype._centroid=!0;it.prototype._attrsAffectingSize=["radius"];oe(it);y.addGetterSetter(it,"radius",0,R());y.addGetterSetter(it,"sides",0,R());y.addGetterSetter(it,"cornerRadius",0,ar(4));const Xn=Math.PI*2;class yt extends I{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,Xn,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),Xn,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)}}yt.prototype.className="Ring";yt.prototype._centroid=!0;yt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];oe(yt);y.addGetterSetter(yt,"innerRadius",0,R());y.addGetterSetter(yt,"outerRadius",0,R());class Oe extends I{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],p=i*2;e.drawImage(d,o,l,c,h,u[p+0],u[p+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)}}Oe.prototype.className="Sprite";oe(Oe);y.addGetterSetter(Oe,"animation");y.addGetterSetter(Oe,"animations");y.addGetterSetter(Oe,"frameOffsets");y.addGetterSetter(Oe,"image");y.addGetterSetter(Oe,"frameIndex",0,R());y.addGetterSetter(Oe,"frameRate",17,R());y.backCompat(Oe,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class rt extends I{_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)}}rt.prototype.className="Star";rt.prototype._centroid=!0;rt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];oe(rt);y.addGetterSetter(rt,"numPoints",5,R());y.addGetterSetter(rt,"innerRadius",0,R());y.addGetterSetter(rt,"outerRadius",0,R());function qe(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 vt="auto",Wl="center",Aa="inherit",Gt="justify",Yl="Change.konva",Xl="2d",qn="-",Ia="left",ql="text",jl="Text",Kl="top",Zl="bottom",jn="middle",Ea="normal",Jl="px ",Ii=" ",Ql="right",Kn="rtl",ec="word",tc="char",Zn="none",yr="…",Ra=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],ic=Ra.length;function rc(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 Ei;function Sr(){return Ei||(Ei=b.createCanvasElement().getContext(Xl),Ei)}function nc(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function sc(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function ac(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}class se extends I{constructor(e){super(ac(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<ic;t++)this.on(Ra[t]+Yl,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(),p=this.getWidth(),f=this.letterSpacing(),m=this.charRenderFunc(),v=this.fill(),T=this.textDecoration(),S=this.underlineOffset(),C=T.indexOf("underline")!==-1,k=T.indexOf("line-through")!==-1,x;h=h===Aa?e.direction:h;let P=l/2,D=jn;if(!M.legacyTextRendering){const w=this.measureSize("M");D="alphabetic";const A=(t=w.fontBoundingBoxAscent)!==null&&t!==void 0?t:w.actualBoundingBoxAscent,B=(i=w.fontBoundingBoxDescent)!==null&&i!==void 0?i:w.actualBoundingBoxDescent;P=(A-B)/2+l/2}for(h===Kn&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",D),e.setAttr("textAlign",Ia),c===jn?d=(this.getHeight()-n*l-a*2)/2:c===Zl&&(d=this.getHeight()-n*l-a*2),e.translate(a,d+a),x=0;x<n;x++){let w=0,A=0;const B=r[x],$=B.text,F=B.width,V=B.lastInParagraph;if(e.save(),u===Ql?w+=p-F-a*2:u===Wl&&(w+=(p-F-a*2)/2),C){e.save(),e.beginPath();const H=S??(M.legacyTextRendering?Math.round(o/2):Math.round(o/4)),L=w,X=P+A+H;e.moveTo(L,X);const N=u===Gt&&!V?p-a*2:F;e.lineTo(L+Math.round(N),X),e.lineWidth=o/15;const Q=this._getLinearGradient();e.strokeStyle=Q||v,e.stroke(),e.restore()}const z=w;if(h!==Kn&&(f!==0||u===Gt||m)){const H=$.split(" ").length-1,L=qe($);for(let X=0;X<L.length;X++){const N=L[X];if(N===" "&&!V&&u===Gt&&(w+=(p-a*2-F)/H),this._partialTextX=w,this._partialTextY=P+A,this._partialText=N,m){e.save();const ae=r.slice(0,x).reduce((K,fe)=>K+qe(fe.text).length,0),Y=X+ae;m({char:N,index:Y,x:w,y:P+A,lineIndex:x,column:X,isLastInLine:V,width:this.measureSize(N).width,context:e})}e.fillStrokeShape(this),m&&e.restore(),w+=this.measureSize(N).width+f}}else f!==0&&e.setAttr("letterSpacing",`${f}px`),this._partialTextX=w,this._partialTextY=P+A,this._partialText=$,e.fillStrokeShape(this);if(k){e.save(),e.beginPath();const H=M.legacyTextRendering?0:-Math.round(o/4),L=z;e.moveTo(L,P+A+H);const X=u===Gt&&!V?p-a*2:F;e.lineTo(L+Math.round(X),P+A+H),e.lineWidth=o/15;const N=this._getLinearGradient();e.strokeStyle=N||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=b._isString(e)?e:e==null?"":e+"";return this._setAttr(ql,t),this}getWidth(){return this.attrs.width===vt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===vt||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 p=Sr(),f=this.fontSize(),m;p.save(),p.font=this._getContextFont(),m=p.measureText(e),p.restore();const v=f/100;return{actualBoundingBoxAscent:(t=m.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*v,actualBoundingBoxDescent:(i=m.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(r=m.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*v,actualBoundingBoxRight:(n=m.actualBoundingBoxRight)!==null&&n!==void 0?n:75.732421875*v,alphabeticBaseline:(a=m.alphabeticBaseline)!==null&&a!==void 0?a:0,emHeightAscent:(o=m.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(l=m.emHeightDescent)!==null&&l!==void 0?l:-20*v,fontBoundingBoxAscent:(c=m.fontBoundingBoxAscent)!==null&&c!==void 0?c:91*v,fontBoundingBoxDescent:(h=m.fontBoundingBoxDescent)!==null&&h!==void 0?h:21*v,hangingBaseline:(d=m.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*v,ideographicBaseline:(u=m.ideographicBaseline)!==null&&u!==void 0?u:-21*v,width:m.width,height:f}}_getContextFont(){return this.fontStyle()+Ii+this.fontVariant()+Ii+(this.fontSize()+Jl)+rc(this.fontFamily())}_addTextLine(e){this.align()===Gt&&(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 Sr().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!==vt&&n!==void 0,l=a!==vt&&a!==void 0,c=this.padding(),h=n-c*2,d=a-c*2,u=0,p=this.wrap(),f=p!==Zn,m=p!==tc&&f,v=this.ellipsis();this.textArr=[],Sr().font=this._getContextFont();const T=v?this._getTextWidth(yr):0;for(let S=0,C=e.length;S<C;++S){let k=e[S],x=this._getTextWidth(k);if(o&&x>h)for(;k.length>0;){let P=0,D=qe(k).length,w="",A=0;for(;P<D;){const B=P+D>>>1,$=qe(k),F=$.slice(0,B+1).join(""),V=this._getTextWidth(F);(v&&l&&u+r>d?V+T:V)<=h?(P=B+1,w=F,A=V):D=B}if(w){if(m){const F=qe(k),V=qe(w),z=F[V.length],H=z===Ii||z===qn;let L;if(H&&A<=h)L=V.length;else{const X=V.lastIndexOf(Ii),N=V.lastIndexOf(qn);L=Math.max(X,N)+1}L>0&&(P=L,w=F.slice(0,P).join(""),A=this._getTextWidth(w))}if(w=w.trimRight(),this._addTextLine(w),i=Math.max(i,A),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(k=qe(k).slice(P).join("").trimLeft(),k.length>0&&(x=this._getTextWidth(k),x<=h)){this._addTextLine(k),u+=r,i=Math.max(i,x);break}}else break}else this._addTextLine(k),u+=r,i=Math.max(i,x),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!==vt&&r!==void 0,a=this.padding(),o=r-a*2;return!(this.wrap()!==Zn)||n&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==vt&&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+yr)<r||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+yr))}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()}}se.prototype._fillFunc=nc;se.prototype._strokeFunc=sc;se.prototype.className=jl;se.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];oe(se);y.overWriteSetter(se,"width",gn());y.overWriteSetter(se,"height",gn());y.addGetterSetter(se,"direction",Aa);y.addGetterSetter(se,"fontFamily","Arial");y.addGetterSetter(se,"fontSize",12,R());y.addGetterSetter(se,"fontStyle",Ea);y.addGetterSetter(se,"fontVariant",Ea);y.addGetterSetter(se,"padding",0,R());y.addGetterSetter(se,"align",Ia);y.addGetterSetter(se,"verticalAlign",Kl);y.addGetterSetter(se,"lineHeight",1,R());y.addGetterSetter(se,"wrap",ec);y.addGetterSetter(se,"ellipsis",!1,Ie());y.addGetterSetter(se,"letterSpacing",0,R());y.addGetterSetter(se,"text","",pt());y.addGetterSetter(se,"textDecoration","");y.addGetterSetter(se,"underlineOffset",void 0,R());y.addGetterSetter(se,"charRenderFunc",void 0);const oc="",Ma="normal";function Da(s){s.fillText(this.partialText,0,0)}function La(s){s.strokeText(this.partialText,0,0)}class he extends I{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 ne.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:ne.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=ne.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 se.prototype.setText.call(this,e)}_getContextFont(){return se.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=qe(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 p=t[d].char;let f=t[d].width+n;if(p===" "&&a==="justify"){const k=this.text().split(" ").length-1;f+=(this.pathLength-l)/k}const m=this._getPointAtLength(h+f);if(!m)return;const v=ne.getLineLength(u.x,u.y,m.x,m.y);let T=0;if(o)try{T=o(t[d-1].char,p)*this.fontSize()}catch{T=0}u.x+=T,m.x+=T,this.textWidth+=T;const S=ne.getPointOnLine(T+v/2,u.x,u.y,m.x,m.y),C=Math.atan2(m.y-u.y,m.x-u.x);this.glyphInfo.push({transposeX:S.x,transposeY:S.y,text:e[d],rotation:C,p0:u,p1:m,width:v}),h+=f}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,i=e[0]||0,r=e[1]||0,n=e[1]||0,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=Da;he.prototype._strokeFunc=La;he.prototype._fillFuncHit=Da;he.prototype._strokeFuncHit=La;he.prototype.className="TextPath";he.prototype._attrsAffectingSize=["text","fontSize","data"];oe(he);y.addGetterSetter(he,"data");y.addGetterSetter(he,"fontFamily","Arial");y.addGetterSetter(he,"fontSize",12,R());y.addGetterSetter(he,"fontStyle",Ma);y.addGetterSetter(he,"align","left");y.addGetterSetter(he,"letterSpacing",0,R());y.addGetterSetter(he,"textBaseline","middle");y.addGetterSetter(he,"fontVariant",Ma);y.addGetterSetter(he,"text",oc);y.addGetterSetter(he,"textDecoration","");y.addGetterSetter(he,"kerningFunc",void 0);const Ba="tr-konva",lc=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(s=>s+`.${Ba}`).join(" "),Jn="nodesRect",cc=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],hc={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},dc="ontouchstart"in M._global;function uc(s,e,t){if(s==="rotater")return t;e+=b.degToRad(hc[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 Xi=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function pc(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 Oa(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 gc(s,e){const t=pc(s);return Oa(s,e,t)}function fc(s,e,t){let i=e;for(let r=0;r<s.length;r++){const n=M.getAngle(s[r]),a=Math.abs(n-e)%(Math.PI*2);Math.min(a,Math.PI*2-a)<t&&(i=n)}return i}let Yr=0;class W extends It{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(lc,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 Ba+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(cc.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(Jn),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Jn,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=(M.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 Oa(h,-M.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(p){const f=u.point(p);t.push(f)})});const i=new ve;i.rotate(-M.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:M.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(),Xi.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new vi({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:dc?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=M.getAngle(this.rotation()),n=this.rotateAnchorCursor(),a=uc(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 I({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),p=a/2,f=o/2;let m=1/0;u<0?m=Math.min(m,-f/u):u>0&&(m=Math.min(m,(o-f)/u)),d<0?m=Math.min(m,-p/d):d>0&&(m=Math.min(m,(a-p)/d));const v=p+d*m,T=f+u*m,S=b._sign(o),C=v+d*c*S,k=T+u*c*S;t.moveTo(v,T),t.lineTo(C,k)}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},Yr++,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 S=this._getNodeRect();t=n.x()-S.width/2,i=-n.y()+S.height/2;const C=M.getAngle(this.rotateAnchorAngle());let k=Math.atan2(-i,t)+Math.PI/2-C;S.height<0&&(k-=Math.PI);const P=M.getAngle(this.rotation())+k,D=M.getAngle(this.rotationSnapTolerance()),A=fc(this.rotationSnaps(),P,D)-S.rotation,B=gc(S,A);this._fitNodesInto(B,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let p=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const S=p?{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,k=this.findOne(".top-left").y()>S.y?-1:1;t=r*this.cos*C,i=r*this.sin*k,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=p?{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,k=this.findOne(".top-right").y()>S.y?-1:1;t=r*this.cos*C,i=r*this.sin*k,this.findOne(".top-right").x(S.x+t),this.findOne(".top-right").y(S.y-i)}var f=n.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(n.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(n.x());else if(this._movingAnchorName==="bottom-left"){if(u){const S=p?{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,k=n.y()<S.y?-1:1;t=r*this.cos*C,i=r*this.sin*k,n.x(S.x-t),n.y(S.y+i)}f=n.position(),this.findOne(".top-left").x(f.x),this.findOne(".bottom-right").y(f.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(n.y());else if(this._movingAnchorName==="bottom-right"){if(u){const S=p?{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,k=this.findOne(".bottom-right").y()<S.y?-1:1;t=r*this.cos*C,i=r*this.sin*k,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(p=this.centeredScaling()||e.altKey,p){const S=this.findOne(".top-left"),C=this.findOne(".bottom-right"),k=S.x(),x=S.y(),P=this.getWidth()-C.x(),D=this.getHeight()-C.y();C.move({x:-k,y:-x}),S.move({x:P,y:D})}const m=this.findOne(".top-left").getAbsolutePosition();t=m.x,i=m.y;const v=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),T=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:i,width:v,height:T,rotation:M.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();Yr--,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 ve;if(n.rotate(M.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 ve;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/a,i.height/a);const l=new ve,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 p;if(!u.getStage())return;const f=u.getParent().getAbsoluteTransform(),m=u.getTransform().copy();m.translate(u.offsetX(),u.offsetY());const v=new ve;v.multiply(f.copy().invert()).multiply(d).multiply(f).multiply(m);const T=v.decompose();u.setAttrs(T),(p=u.getLayer())===null||p===void 0||p.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(P=>{P.setAttrs({width:l,height:l,offsetX:l/2,offsetY:l/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:l/2+o,offsetY:l/2+o,visible:a&&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),p=Math.sin(u),f=-Math.cos(u),m=i/2,v=r/2;let T=1/0;f<0?T=Math.min(T,-v/f):f>0&&(T=Math.min(T,(r-v)/f)),p<0?T=Math.min(T,-m/p):p>0&&(T=Math.min(T,(i-m)/p));const S=m+p*T,C=v+f*T,k=b._sign(r);this._batchChangeChild(".rotater",{x:S+p*d*k,y:C+f*d*k-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(P=>P.draggable()),x:0,y:0});const x=this.anchorStyleFunc();x&&c.forEach(P=>{x(P)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),It.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=()=>Yr>0;function mc(s){return s instanceof Array||b.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(e){Xi.indexOf(e)===-1&&b.warn("Unknown anchor name: "+e+". Available names are: "+Xi.join(", "))}),s||[]}W.prototype.className="Transformer";oe(W);y.addGetterSetter(W,"enabledAnchors",Xi,mc);y.addGetterSetter(W,"flipEnabled",!0,Ie());y.addGetterSetter(W,"resizeEnabled",!0);y.addGetterSetter(W,"anchorSize",10,R());y.addGetterSetter(W,"rotateEnabled",!0);y.addGetterSetter(W,"rotateLineVisible",!0);y.addGetterSetter(W,"rotationSnaps",[]);y.addGetterSetter(W,"rotateAnchorOffset",50,R());y.addGetterSetter(W,"rotateAnchorAngle",0,R());y.addGetterSetter(W,"rotateAnchorCursor","crosshair");y.addGetterSetter(W,"rotationSnapTolerance",5,R());y.addGetterSetter(W,"borderEnabled",!0);y.addGetterSetter(W,"anchorStroke","rgb(0, 161, 255)");y.addGetterSetter(W,"anchorStrokeWidth",1,R());y.addGetterSetter(W,"anchorFill","white");y.addGetterSetter(W,"anchorCornerRadius",0,R());y.addGetterSetter(W,"borderStroke","rgb(0, 161, 255)");y.addGetterSetter(W,"borderStrokeWidth",1,R());y.addGetterSetter(W,"borderDash");y.addGetterSetter(W,"keepRatio",!0);y.addGetterSetter(W,"shiftBehavior","default");y.addGetterSetter(W,"centeredScaling",!1);y.addGetterSetter(W,"ignoreStroke",!1);y.addGetterSetter(W,"padding",0,R());y.addGetterSetter(W,"nodes");y.addGetterSetter(W,"node");y.addGetterSetter(W,"boundBoxFunc");y.addGetterSetter(W,"anchorDragBoundFunc");y.addGetterSetter(W,"anchorStyleFunc");y.addGetterSetter(W,"shouldOverdrawWholeArea",!1);y.addGetterSetter(W,"useSingleNodeRotation",!0);y.backCompat(W,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Ve extends I{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,M.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)}}Ve.prototype.className="Wedge";Ve.prototype._centroid=!0;Ve.prototype._attrsAffectingSize=["radius"];oe(Ve);y.addGetterSetter(Ve,"radius",0,R());y.addGetterSetter(Ve,"angle",0,R());y.addGetterSetter(Ve,"clockwise",!1);y.backCompat(Ve,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Qn(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const yc=[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],Sc=[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 vc(s,e){const t=s.data,i=s.width,r=s.height;let n,a,o,l,c,h,d,u,p,f,m,v,T,S,C,k,x,P,D,w;const A=e+e+1,B=i-1,$=r-1,F=e+1,V=F*(F+1)/2,z=new Qn,H=yc[e],L=Sc[e];let X=null,N=z,Q=null,ae=null;for(let Y=1;Y<A;Y++)N=N.next=new Qn,Y===F&&(X=N);N.next=z,o=a=0;for(let Y=0;Y<r;Y++){v=T=S=C=l=c=h=d=0,u=F*(k=t[a]),p=F*(x=t[a+1]),f=F*(P=t[a+2]),m=F*(D=t[a+3]),l+=V*k,c+=V*x,h+=V*P,d+=V*D,N=z;for(let K=0;K<F;K++)N.r=k,N.g=x,N.b=P,N.a=D,N=N.next;for(let K=1;K<F;K++)n=a+((B<K?B:K)<<2),l+=(N.r=k=t[n])*(w=F-K),c+=(N.g=x=t[n+1])*w,h+=(N.b=P=t[n+2])*w,d+=(N.a=D=t[n+3])*w,v+=k,T+=x,S+=P,C+=D,N=N.next;Q=z,ae=X;for(let K=0;K<i;K++)t[a+3]=D=d*H>>L,D!==0?(D=255/D,t[a]=(l*H>>L)*D,t[a+1]=(c*H>>L)*D,t[a+2]=(h*H>>L)*D):t[a]=t[a+1]=t[a+2]=0,l-=u,c-=p,h-=f,d-=m,u-=Q.r,p-=Q.g,f-=Q.b,m-=Q.a,n=o+((n=K+e+1)<B?n:B)<<2,v+=Q.r=t[n],T+=Q.g=t[n+1],S+=Q.b=t[n+2],C+=Q.a=t[n+3],l+=v,c+=T,h+=S,d+=C,Q=Q.next,u+=k=ae.r,p+=x=ae.g,f+=P=ae.b,m+=D=ae.a,v-=k,T-=x,S-=P,C-=D,ae=ae.next,a+=4;o+=i}for(let Y=0;Y<i;Y++){T=S=C=v=c=h=d=l=0,a=Y<<2,u=F*(k=t[a]),p=F*(x=t[a+1]),f=F*(P=t[a+2]),m=F*(D=t[a+3]),l+=V*k,c+=V*x,h+=V*P,d+=V*D,N=z;for(let fe=0;fe<F;fe++)N.r=k,N.g=x,N.b=P,N.a=D,N=N.next;let K=i;for(let fe=1;fe<=e;fe++)a=K+Y<<2,l+=(N.r=k=t[a])*(w=F-fe),c+=(N.g=x=t[a+1])*w,h+=(N.b=P=t[a+2])*w,d+=(N.a=D=t[a+3])*w,v+=k,T+=x,S+=P,C+=D,N=N.next,fe<$&&(K+=i);a=Y,Q=z,ae=X;for(let fe=0;fe<r;fe++)n=a<<2,t[n+3]=D=d*H>>L,D>0?(D=255/D,t[n]=(l*H>>L)*D,t[n+1]=(c*H>>L)*D,t[n+2]=(h*H>>L)*D):t[n]=t[n+1]=t[n+2]=0,l-=u,c-=p,h-=f,d-=m,u-=Q.r,p-=Q.g,f-=Q.b,m-=Q.a,n=Y+((n=fe+F)<$?n:$)*i<<2,l+=v+=Q.r=t[n],c+=T+=Q.g=t[n+1],h+=S+=Q.b=t[n+2],d+=C+=Q.a=t[n+3],Q=Q.next,u+=k=ae.r,p+=x=ae.g,f+=P=ae.b,m+=D=ae.a,v-=k,T-=x,S-=P,C-=D,ae=ae.next,a+=i}}const Cc=function(e){const t=Math.round(this.blurRadius());t>0&&vc(e,t)};y.addGetterSetter(E,"blurRadius",0,R(),y.afterSetFilter);const Tc=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};y.addGetterSetter(E,"brightness",0,R(),y.afterSetFilter);const bc=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)},kc=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};y.addGetterSetter(E,"contrast",0,R(),y.afterSetFilter);const wc=function(s){var e,t,i,r,n,a,o,l,c;const h=s.data,d=s.width,u=s.height,p=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),f=Math.min(1,Math.max(0,(r=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&r!==void 0?r:.5)),v=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(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,T=!!((c=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&c!==void 0&&c),S=p*10,C=f*255,k=v*Math.PI/180,x=Math.cos(k),P=Math.sin(k),D=128/1020*S,w=new Uint8ClampedArray(h),A=new Float32Array(d*u);for(let z=0,H=0;H<h.length;H+=4,z++)A[z]=.2126*w[H]+.7152*w[H+1]+.0722*w[H+2];const B=[-1,0,1,-2,0,2,-1,0,1],$=[-1,-2,-1,0,0,0,1,2,1],F=[-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 H=1;H<d-1;H++){const L=z*d+H;let X=0,N=0;X+=A[L+F[0]]*B[0],N+=A[L+F[0]]*$[0],X+=A[L+F[1]]*B[1],N+=A[L+F[1]]*$[1],X+=A[L+F[2]]*B[2],N+=A[L+F[2]]*$[2],X+=A[L+F[3]]*B[3],N+=A[L+F[3]]*$[3],X+=A[L+F[5]]*B[5],N+=A[L+F[5]]*$[5],X+=A[L+F[6]]*B[6],N+=A[L+F[6]]*$[6],X+=A[L+F[7]]*B[7],N+=A[L+F[7]]*$[7],X+=A[L+F[8]]*B[8],N+=A[L+F[8]]*$[8];const Q=x*X+P*N,ae=V(C+Q*D),Y=L*4;if(T){const K=ae-C;h[Y]=V(w[Y]+K),h[Y+1]=V(w[Y+1]+K),h[Y+2]=V(w[Y+2]+K),h[Y+3]=w[Y+3]}else h[Y]=h[Y+1]=h[Y+2]=ae,h[Y+3]=w[Y+3]}for(let z=0;z<d;z++){let H=z*4,L=((u-1)*d+z)*4;h[H]=w[H],h[H+1]=w[H+1],h[H+2]=w[H+2],h[H+3]=w[H+3],h[L]=w[L],h[L+1]=w[L+1],h[L+2]=w[L+2],h[L+3]=w[L+3]}for(let z=1;z<u-1;z++){let H=z*d*4,L=(z*d+(d-1))*4;h[H]=w[H],h[H+1]=w[H+1],h[H+2]=w[H+2],h[H+3]=w[H+3],h[L]=w[L],h[L+1]=w[L+1],h[L+2]=w[L+2],h[L+3]=w[L+3]}return s};y.addGetterSetter(E,"embossStrength",.5,R(),y.afterSetFilter);y.addGetterSetter(E,"embossWhiteLevel",.5,R(),y.afterSetFilter);y.addGetterSetter(E,"embossDirection","top-left",void 0,y.afterSetFilter);y.addGetterSetter(E,"embossBlend",!1,void 0,y.afterSetFilter);function vr(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 Pc=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 C=0;C<t;C+=4)n=e[C+0],n<i?i=n:n>r&&(r=n),l=e[C+1],l<a?a=l:l>o&&(o=l),d=e[C+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 p,f,m,v,T,S;if(u>0)p=r+u*(255-r),f=i-u*(i-0),m=o+u*(255-o),v=a-u*(a-0),T=h+u*(255-h),S=c-u*(c-0);else{const C=(r+i)*.5;p=r+u*(r-C),f=i+u*(i-C);const k=(o+a)*.5;m=o+u*(o-k),v=a+u*(a-k);const x=(h+c)*.5;T=h+u*(h-x),S=c+u*(c-x)}for(let C=0;C<t;C+=4)e[C+0]=vr(e[C+0],i,r,f,p),e[C+1]=vr(e[C+1],a,o,v,m),e[C+2]=vr(e[C+2],c,h,S,T)};y.addGetterSetter(E,"enhance",0,R(),y.afterSetFilter);const xc=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}};y.addGetterSetter(E,"hue",0,R(),y.afterSetFilter);y.addGetterSetter(E,"saturation",0,R(),y.afterSetFilter);y.addGetterSetter(E,"luminance",0,R(),y.afterSetFilter);const _c=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,p=.587*i+.413*o+.035*l,f=.114*i-.114*o+.293*l,m=.299*i-.3*o+1.25*l,v=.587*i-.586*o-1.05*l,T=.114*i+.886*o-.2*l;let S,C,k,x;for(let P=0;P<t;P+=4)S=e[P+0],C=e[P+1],k=e[P+2],x=e[P+3],e[P+0]=c*S+h*C+d*k+a,e[P+1]=u*S+p*C+f*k+a,e[P+2]=m*S+v*C+T*k+a,e[P+3]=x},Ac=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,p=.114*i-.114*a+.293*o,f=.299*i-.3*a+1.25*o,m=.587*i-.586*a-1.05*o,v=.114*i+.886*a-.2*o;for(let T=0;T<t;T+=4){const S=e[T+0],C=e[T+1],k=e[T+2],x=e[T+3];e[T+0]=l*S+c*C+h*k,e[T+1]=d*S+u*C+p*k,e[T+2]=f*S+m*C+v*k,e[T+3]=x}};y.addGetterSetter(E,"hue",0,R(),y.afterSetFilter);y.addGetterSetter(E,"saturation",0,R(),y.afterSetFilter);y.addGetterSetter(E,"value",0,R(),y.afterSetFilter);const Ic=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]},Ec=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 p=a,f=n,m=360/f*Math.PI/180;for(let v=0;v<f;v+=1){const T=Math.sin(v*m),S=Math.cos(v*m);for(let C=0;C<p;C+=1){h=Math.floor(o+c*C/p*S),d=Math.floor(l+c*C/p*T);let k=(d*n+h)*4;const x=i[k+0],P=i[k+1],D=i[k+2],w=i[k+3];k=(v+C*n)*4,r[k+0]=x,r[k+1]=P,r[k+2]=D,r[k+3]=w}}},Rc=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 p=a,f=n,m=0;let v,T;for(h=0;h<n;h+=1)for(d=0;d<a;d+=1){const S=h-o,C=d-l,k=Math.sqrt(S*S+C*C)*p/c;let x=(Math.atan2(C,S)*180/Math.PI+360+m)%360;x=x*f/360,v=Math.floor(x),T=Math.floor(k);let P=(T*n+v)*4;const D=i[P+0],w=i[P+1],A=i[P+2],B=i[P+3];P=(d*n+h)*4,r[P+0]=D,r[P+1]=w,r[P+2]=A,r[P+3]=B}},Mc=function(s){const e=s.width,t=s.height;let i,r,n,a,o,l,c,h,d,u,p=Math.round(this.kaleidoscopePower());const f=Math.round(this.kaleidoscopeAngle()),m=Math.floor(e*(f%360)/360);if(p<1)return;const v=b.createCanvasElement();v.width=e,v.height=t;const T=v.getContext("2d").getImageData(0,0,e,t);b.releaseCanvas(v),Ec(s,T,{polarCenterX:e/2,polarCenterY:t/2});let S=e/Math.pow(2,p);for(;S<=8;)S=S*2,p-=1;S=Math.ceil(S);let C=S,k=0,x=C,P=1;for(m+S>e&&(k=C,x=0,P=-1),r=0;r<t;r+=1)for(i=k;i!==x;i+=P)n=Math.round(i+m)%e,d=(e*r+n)*4,o=T.data[d+0],l=T.data[d+1],c=T.data[d+2],h=T.data[d+3],u=(e*r+i)*4,T.data[u+0]=o,T.data[u+1]=l,T.data[u+2]=c,T.data[u+3]=h;for(r=0;r<t;r+=1)for(C=Math.floor(S),a=0;a<p;a+=1){for(i=0;i<C+1;i+=1)d=(e*r+i)*4,o=T.data[d+0],l=T.data[d+1],c=T.data[d+2],h=T.data[d+3],u=(e*r+C*2-i-1)*4,T.data[u+0]=o,T.data[u+1]=l,T.data[u+2]=c,T.data[u+3]=h;C*=2}Rc(T,s,{})};y.addGetterSetter(E,"kaleidoscopePower",2,R(),y.afterSetFilter);y.addGetterSetter(E,"kaleidoscopeAngle",0,R(),y.afterSetFilter);function Ri(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 Ht(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 Dc(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 Lc(s,e){const t=Ri(s,0,0),i=Ri(s,s.width-1,0),r=Ri(s,0,s.height-1),n=Ri(s,s.width-1,s.height-1),a=e||10;if(Ht(t,i)<a&&Ht(i,n)<a&&Ht(n,r)<a&&Ht(r,t)<a){const o=Dc([i,t,n,r]),l=[];for(let c=0;c<s.width*s.height;c++){const h=Ht(o,[s.data[c*4],s.data[c*4+1],s.data[c*4+2]]);l[c]=h<a?0:255}return l}}function Bc(s,e){for(let t=0;t<s.width*s.height;t++)s.data[4*t+3]=e[t]}function Oc(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 p=o+d-n,f=l+u-n;if(p>=0&&p<t&&f>=0&&f<e){const m=p*e+f,v=i[d*r+u];h+=s[m]*v}}a[c]=h===255*8?255:0}return a}function Fc(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 p=o+d-n,f=l+u-n;if(p>=0&&p<t&&f>=0&&f<e){const m=p*e+f,v=i[d*r+u];h+=s[m]*v}}a[c]=h>=255*4?255:0}return a}function Nc(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 p=o+d-n,f=l+u-n;if(p>=0&&p<t&&f>=0&&f<e){const m=p*e+f,v=i[d*r+u];h+=s[m]*v}}a[c]=h}return a}const Gc=function(s){const e=this.threshold();let t=Lc(s,e);return t&&(t=Oc(t,s.width,s.height),t=Fc(t,s.width,s.height),t=Nc(t,s.width,s.height),Bc(s,t)),s};y.addGetterSetter(E,"threshold",0,R(),y.afterSetFilter);const Hc=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()};y.addGetterSetter(E,"noise",.2,R(),y.afterSetFilter);const $c=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 p=o*e,f=p+e,m=l*e,v=m+e;let T=0;for(let S=p;S<f;S+=1)if(!(S>=t))for(let C=m;C<v;C+=1){if(C>=i)continue;const k=(t*C+S)*4;c+=a[k+0],h+=a[k+1],d+=a[k+2],u+=a[k+3],T+=1}c=c/T,h=h/T,d=d/T,u=u/T;for(let S=p;S<f;S+=1)if(!(S>=t))for(let C=m;C<v;C+=1){if(C>=i)continue;const k=(t*C+S)*4;a[k+0]=c,a[k+1]=h,a[k+2]=d,a[k+3]=u}}};y.addGetterSetter(E,"pixelSize",8,R(),y.afterSetFilter);const zc=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};y.addGetterSetter(E,"levels",.5,R(),y.afterSetFilter);const Vc=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]}};y.addGetterSetter(E,"red",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});y.addGetterSetter(E,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});y.addGetterSetter(E,"blue",0,sa,y.afterSetFilter);const Uc=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}};y.addGetterSetter(E,"red",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});y.addGetterSetter(E,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});y.addGetterSetter(E,"blue",0,sa,y.afterSetFilter);y.addGetterSetter(E,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const Wc=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)}},Yc=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},Xc=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};y.addGetterSetter(E,"threshold",.5,R(),y.afterSetFilter);const Z=zn.Util._assign(zn,{Arc:$e,Arrow:ft,Circle:Dt,Ellipse:tt,Image:Ee,Label:yn,Tag:mt,Line:ze,Path:ne,Rect:vi,RegularPolygon:it,Ring:yt,Sprite:Oe,Star:rt,Text:se,TextPath:he,Transformer:W,Wedge:Ve,Filters:{Blur:Cc,Brightness:bc,Brighten:Tc,Contrast:kc,Emboss:wc,Enhance:Pc,Grayscale:xc,HSL:_c,HSV:Ac,Invert:Ic,Kaleidoscope:Mc,Mask:Gc,Noise:Hc,Pixelate:$c,Posterize:zc,RGB:Vc,RGBA:Uc,Sepia:Wc,Solarize:Yc,Threshold:Xc}}),Fa="media-editor-track.diagnostics.v1",Xr="media-editor-track.diagnostics.failure-window.v1",Na="media-editor-track-diagnostics",Je="snapshots",Ga="state",Ha="latest-failure-window",di=1,Sn=1,es=40,qc=48,jc=250,ts=20,Kc=100,Zc=500,qr=new Set(["pending-preview.begin","preview.sync.requested","media.seeking","media.seeked"]),Jc=new Set([...qr,"media.current-slot.seek","media.preload-slot.seek","media.play.requested","media.pause.requested","slot.recovery-check","runtime.state"]),is={debug:10,info:20,warn:30,error:40},We={enabled:!0,persist:!0,storageQuotaMb:10,maxSessions:20,maxHotEvents:500,includeFullSourceUrl:!0,consoleSeverityThreshold:"error",highFrequencyEventThrottleMs:Zc};function rs(s){return`${s}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function Qc(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function $a(s){if(!s||typeof s!="object")return!1;const e=Object.getPrototypeOf(s);return e===Object.prototype||e===null}function At(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:At(s.cause,e+1,t)};if(e>=4)return"[max-depth]";if(Array.isArray(s))return s.slice(0,40).map(i=>At(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(!$a(s))return String(s);const i={};for(const r of Object.keys(s).slice(0,60))i[r]=At(s[r],e+1,t);return i}return String(s)}function qi(s){if(!s)return null;const e=At(s,0,new WeakSet);return $a(e)?e:{value:e}}function eh(s){return qi(s)}function $t(s){return typeof s=="number"&&Number.isFinite(s)?s:null}function Mi(s){return typeof s=="string"&&s.length>0?s:null}function th(){var i,r,n,a,o;const s=typeof navigator<"u"?navigator:null,e={platform:Mi(s==null?void 0:s.platform),hardwareConcurrency:$t(s==null?void 0:s.hardwareConcurrency),deviceMemory:$t(s==null?void 0:s.deviceMemory),maxTouchPoints:$t(s==null?void 0:s.maxTouchPoints),language:Mi(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:Mi((i=s==null?void 0:s.connection)==null?void 0:i.effectiveType),downlinkMbps:$t((r=s==null?void 0:s.connection)==null?void 0:r.downlink),rttMs:$t((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:Mi((o=s==null?void 0:s.connection)==null?void 0:o.type)};return{hardware:e,network:t}}function ns(s,e={}){const t=th(),i=qi(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 ih(s){return s?s instanceof Error?{name:s.name,message:s.message,stack:s.stack??null,cause:At(s.cause,1,new WeakSet)}:{name:null,message:typeof s=="string"?s:String(s),stack:null,cause:At(s,1,new WeakSet)}:null}function ri(){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 rh(s){const e=s??ri();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 za(s){const e=ri();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 ss(s){return rh(s.summary)}function nh(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 sh(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 ah(s){return{enabled:(s==null?void 0:s.enabled)??We.enabled,persist:(s==null?void 0:s.persist)??We.persist,storageQuotaMb:(s==null?void 0:s.storageQuotaMb)??We.storageQuotaMb,maxSessions:Math.max(1,(s==null?void 0:s.maxSessions)??We.maxSessions),maxHotEvents:Math.max(20,(s==null?void 0:s.maxHotEvents)??We.maxHotEvents),includeFullSourceUrl:(s==null?void 0:s.includeFullSourceUrl)??We.includeFullSourceUrl,consoleSeverityThreshold:(s==null?void 0:s.consoleSeverityThreshold)??We.consoleSeverityThreshold,highFrequencyEventThrottleMs:Math.max(0,(s==null?void 0:s.highFrequencyEventThrottleMs)??We.highFrequencyEventThrottleMs)}}function oh(){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)!==di||!Array.isArray(e.sessions)?null:e}catch{return null}}function lh(){try{if(typeof globalThis.localStorage>"u")return null;const s=globalThis.localStorage.getItem(Xr);if(!s)return null;const e=JSON.parse(s);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 Va(s){const e=Array.isArray(s.events)?s.events:[];return{...s,updatedAt:s.updatedAt||s.startedAt,events:e,summary:za(e)}}function zt(s,e,t={}){const i=s.slice(-e.maxSessions).map(n=>{const a=n.events.slice(-e.maxHotEvents);return Va({...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:di,sessions:i}).length>r;)i.shift();return i}async function ch(s){return Ua(Ga,s)}async function hh(s){return Ua(Ha,s)}async function Ua(s,e){if(typeof indexedDB>"u")return!1;try{const t=await new Promise((i,r)=>{const n=indexedDB.open(Na,1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains(Je)||a.createObjectStore(Je)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)});return await new Promise((i,r)=>{const n=t.transaction(Je,"readwrite");n.objectStore(Je).put(e,s),n.oncomplete=()=>i(),n.onerror=()=>r(n.error),n.onabort=()=>r(n.error)}),t.close(),!0}catch{return!1}}async function dh(){const s=await Wa(Ga);return s&&typeof s=="object"&&"version"in s&&s.version===di&&"sessions"in s&&Array.isArray(s.sessions)?s:null}async function uh(){const s=await Wa(Ha);return s&&typeof s=="object"&&"version"in s&&s.version===Sn&&"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 Wa(s){if(typeof indexedDB>"u")return null;try{const e=await new Promise((i,r)=>{const n=indexedDB.open(Na,1);n.onupgradeneeded=()=>{const a=n.result;a.objectStoreNames.contains(Je)||a.createObjectStore(Je)},n.onsuccess=()=>i(n.result),n.onerror=()=>r(n.error)}),t=await new Promise((i,r)=>{const o=e.transaction(Je,"readonly").objectStore(Je).get(s);o.onsuccess=()=>i(o.result??null),o.onerror=()=>r(o.error)});return e.close(),t}catch{return null}}function ph(s,e){return!s&&!e?null:{...s??{},...e??{}}}class Ya{constructor(e){g(this,"config");g(this,"listeners",new Set);g(this,"liveListeners",new Map);g(this,"state");g(this,"currentSessionId",null);g(this,"latestFailureWindow");g(this,"activeFailureCapture",null);g(this,"notifyTimeoutId",null);g(this,"persistTimeoutId",null);g(this,"highFrequencyEventTimestamps",new Map);this.config=ah(e);const t=oh();this.latestFailureWindow=lh(),this.state={version:di,sessions:zt((t==null?void 0:t.sessions)??[],this.config,{enforceStorageQuota:this.config.persist})},this.restoreIndexedDbState()}startSession(e){const t=new Date().toISOString(),i={sessionId:rs("diag-session"),startedAt:Date.now(),updatedAt:Date.now(),metadata:ns(e,{capturedAt:t}),sequence:0,events:[],summary:ri()};return this.currentSessionId=i.sessionId,this.state.sessions=zt([...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),sh(t.summary,a),this.trimSessionEvents(t),this.captureFailureWindow(t,a),this.state.sessions=zt(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=ts){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:ss(t)}}getLiveSnapshot(e=this.currentSessionId,t=ts){const i=this.resolveSession(e),r=Math.max(1,t);return{sessionId:i.sessionId,startedAt:i.startedAt,updatedAt:i.updatedAt,metadata:i.metadata,summary:ss(i),recentEvents:i.events.slice(-r).map(n=>nh(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=ns(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:ri()}}createEvent(e,t,i,r,n=rs("diag-event")){return{eventId:n,sessionId:e.sessionId,sequence:r,timestamp:i,isoTime:new Date(i).toISOString(),perfTimeMs:Qc(),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:qi(t.mediaState),runtimeState:eh(t.runtimeState),error:ih(t.error),extra:qi(t.extra)}}trimSessionEvents(e){const t=e.events.length-this.config.maxHotEvents;t<=0||(e.events=e.events.slice(t),e.summary=za(e.events))}findCoalescedEvent(e,t,i){if(!qr.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>Kc)break;if(this.areEventIdentitiesEqual(r,a))return a}return null}resolveHighFrequencyDecision(e,t){if(e.severity==="warn"||e.severity==="error"||!Jc.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?qr.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:ri()},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(is[e.severity]<is[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()},qc))}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()},jc)))}persistNow(){if(!this.config.persist)return;const e={version:di,sessions:zt(this.state.sessions,this.config,{enforceStorageQuota:!0})};if(this.state=e,typeof indexedDB>"u"){this.persistToLocalStorage(e);return}Promise.all([ch(e),hh(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([dh(),uh()]);if((i=e==null?void 0:e.sessions)!=null&&i.length){const n=new Map;[...this.state.sessions,...e.sessions].forEach(a=>{const o=Va(a),l=n.get(o.sessionId);(!l||l.updatedAt<o.updatedAt)&&n.set(o.sessionId,o)}),this.state.sessions=zt(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:es}),!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=es){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(Xr,JSON.stringify(t));return}globalThis.localStorage.removeItem(Xr)}}}function Xa(s,e){return ph(s,e)}function as(s,e,t,i){const r=`[${s.toUpperCase()}] [${e}]`;if(i===void 0){console[s](`${r} ${t}`);return}console[s](`${r} ${t}`,i)}const O={debug(s,e,t){},debugLazy(s,e,t){},warn(s,e,t){as("warn",s,e,t)},error(s,e,t){as("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){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),e.setAttr(this.COVER_SOURCE_KEY,[...t??[]]),!t||t.length===0){e.destroyChildren(),this.syncCoverBackgroundState(e),a||this.requestRender(e);return}const l=this.buildSegmentsDataSync(t,i,r,n);if(l){this.renderSegments(e,l,i,r),this.syncCoverBackgroundState(e),a||this.requestRender(e);return}a||(e.destroyChildren(),this.syncCoverBackgroundState(e),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.syncCoverBackgroundState(t),!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 p=0;p<h;p++)d.push(Math.round(p*(n-1)/(h-1)));const u=[];for(let p=0;p<h;p++){const f=e[d[p]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:p*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 p=0;p<h;p++)d.push(Math.round(p*(n-1)/(h-1)));const u=[];for(let p=0;p<h;p++){const f=e[d[p]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:p*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 Z.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 Z.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.syncCoverBackgroundState(r),this.requestRender(r)}catch{}}),this.listenToImageEvent(t,"error",()=>{this.brokenImageUrls.add(e);try{i.visible(!1),this.syncCoverBackgroundState(r),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)}static syncCoverBackgroundState(e){var c,h;const t=(c=e.getParent)==null?void 0:c.call(e),i=(h=t==null?void 0:t.findOne)==null?void 0:h.call(t,".clip-cover-background");if(!i)return;const r=e.getAttr("coverFallbackFill"),n=e.getAttr("coverUnavailableFill"),a=e.getAttr(this.COVER_SOURCE_KEY)??[],l=a.length>0&&a.every(d=>this.brokenImageUrls.has(d));i.fill(l?n:r)}}g(pe,"MIN_IMAGE_DISPLAY_WIDTH",24),g(pe,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),g(pe,"COVER_SOURCE_KEY","_coverSource"),g(pe,"MAX_CACHE_SIZE",1e3),g(pe,"DEFAULT_DIMENSIONS",{width:160,height:90}),g(pe,"keyframeDimensionsCache",{}),g(pe,"keyframeDimensionsPromiseCache",{}),g(pe,"imageCache",{}),g(pe,"brokenImageUrls",new Set);const gh='<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>',fh='<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>',mh='<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>',yh='<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>',Sh='<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>',vh='<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>',Ch='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="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>',Th='<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>',bh='<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>',kh='<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>',wh='<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>',Ph=new Map([["OmAi-camera",gh],["OmAi-accept",fh],["OmAi-display",mh],["OmAi-hide",yh],["OmAi-loading",Sh],["OmAi-music",vh],["OmAi-volume",Ch],["OmAi-volume-mute",Th],["OmAi-text",bh],["clip-audio",kh],["clip-without-audio",wh]]),os=new Map;function Te(s){return Ph.get(s)??""}function xh(s){const e=os.get(s);if(e)return e;const t=Te(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,os.set(s,r),r}const ue=3,ls=10,_h=4,Ah=6,cs=8,hs=14,jr=10,Ih=12,Eh=4,qa=1,ji=28,ja=8,ni=12,Kr=19,Ki=15,Rh=12;function ui(s,e,t,i,r=_.white,n=_.black,a=1){return new Z.Rect({x:s,y:e,width:t,height:i,fill:r,stroke:n,strokeWidth:a})}function Et(s,e,t,i=12,r="Arial",n=_.black,a="left",o="top"){return new Z.Text({text:s,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:a,verticalAlign:o})}function Rt(s=0,e=0){return new Z.Group({x:s,y:e})}function pi(s){s.ellipsis(!1),s.wrap("none"),s.width("auto")}function vn(s){return typeof s=="string"&&s.trim().length>0?s.trim():"媒体丢失"}function lr(s,e,t,i){if(i){s.add(new Z.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),s.add(new Z.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}s.add(new Z.Rect({x:0,y:0,width:ue,height:t,name:"clip-resize-left"})),s.add(new Z.Rect({x:e-ue,y:0,width:ue,height:t,name:"clip-resize-right"}))}function Mh(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 Ka(s,e,t){const i=e?s.clipSelectedBorder:_.transparent,r=e?qa:0;return t==="audio"?{background:_.audioClipBackground,label:s.audioClipText||s.clipName,accent:s.audioClipAccent||s.clipHandle,coverBackground:s.clipCoverBackground||te.clipCoverBackground,failedBackground:_.mediaClipFailedBackground,failedLabel:s.audioClipText||s.clipName,border:i,borderWidth:r}:t==="text"?{background:_.textClipBackground,label:s.clipName,accent:s.clipHandle,coverBackground:s.clipCoverBackground||_.accentCoverFallback,failedBackground:_.mediaClipFailedBackground,failedLabel:s.clipName,border:i,borderWidth:r}:{background:_.videoClipBackground,label:s.clipName,accent:s.clipHandle,coverBackground:s.clipCoverBackground||_.accentCoverFallback,failedBackground:_.mediaClipFailedBackground,failedLabel:s.clipName,border:i,borderWidth:r}}function Za(s,e,t,i,r){const n=Et(i,0,Math.max(0,Math.floor((t-ni)/2)-2),ni,"Arial",r,"center","middle");n.width(e),n.height(ni+6),n.name("clip-media-status"),s.add(n)}function Dh(s,e,t,i,r,n){const a=Et(r,e,t,Rh,"Arial",n,"center","middle");a.width(i),a.height(Ki),a.name("clip-media-status"),s.add(a)}function Lh(s,e,t,i){const r=ui(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),lr(s,e,t,!0)}function Bh(s,e,t){const i=e.mediaStatus==="failed",r=vn(e.mediaStatusMessage),n=ui(0,0,e.width,e.height,t.background,t.border,t.borderWidth);n.cornerRadius(4),n.name("clip-background"),s.add(n),lr(s,e.width,e.height,!1);const a=15,o=e.height-a-4,l=e.width-ue*2,c=Rt(ue,2);c.name("clip-cover-container"),c.clip({x:0,y:0,width:l,height:o}),s.add(c);const h=ui(0,0,l,o,i?t.failedBackground:t.coverBackground,"transparent",0);h.cornerRadius(2),h.name("clip-cover-background"),c.add(h);const d=Rt(0,0);d.name("clip-covers-group"),d.setAttr("coverFallbackFill",i?t.failedBackground:t.coverBackground),d.setAttr("coverUnavailableFill",i?t.failedBackground:_.mediaClipFailedBackground),c.add(d),i?(pe.renderClipCovers(d,[],l,o,e.videoSrc,e.deferCoverRender),Za(c,l,o,r,t.failedLabel)):pe.renderClipCovers(d,e.thumbnails??[],l,o,e.videoSrc,e.deferCoverRender);const u=l>=120?ji+ja:0,p=Et(`${e.clipName} ${U.formatDuration(e.duration)}`,ue,e.height-a,jr,"Arial",t.label,"left","middle");p.height(a),pi(p),p.name("clip-label"),s.add(p),u>0&&Qa(s,e.width,e.height,e.hasSeparatedAudio)}function Oh(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"),l=s.findOne(".clip-media-status");if(!i||!r||!n||!a||!o)return!1;const c=e.mediaStatus==="failed",h=vn(e.mediaStatusMessage);if(i.width(e.width),i.height(e.height),i.fill(t.background),i.stroke(t.border),i.strokeWidth(t.borderWidth),i.cornerRadius(4),!Mh(s,e.width,e.height))return!1;const d=15,u=e.height-d-4,p=e.width-ue*2;r.x(ue),r.y(2),r.clip({x:0,y:0,width:p,height:u}),n.width(p),n.height(u),n.fill(c?t.failedBackground:t.coverBackground),n.cornerRadius(2),a.setAttr("coverFallbackFill",c?t.failedBackground:t.coverBackground),a.setAttr("coverUnavailableFill",c?t.failedBackground:_.mediaClipFailedBackground),c?(pe.renderClipCovers(a,[],p,u,e.videoSrc,e.deferCoverRender),l?(l.text(h),l.x(0),l.y(Math.max(0,Math.floor((u-ni)/2)-2)),l.width(p),l.height(ni+6),l.fill(t.failedLabel)):Za(r,p,u,h,t.failedLabel)):(l==null||l.destroy(),pe.renderClipCovers(a,e.thumbnails??[],p,u,e.videoSrc,e.deferCoverRender));const f=p>=120?ji+ja:0;o.text(`${e.clipName} ${U.formatDuration(e.duration)}`),o.x(ue),o.y(e.height-d),o.fill(t.label),o.height(d),pi(o);const m=s.findOne(".video-audio-status");return m==null||m.destroy(),f>0&&Qa(s,e.width,e.height,e.hasSeparatedAudio),!0}function Fh(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 Ja(s,e,t,i,r){s.name()||s.name(r);const n=xh(e);if(!n)return 0;const a=new Z.Image({x:0,y:0,width:t,height:i,image:n,listening:!1});return a.name(`${r}-image`),s.add(a),Fh(s,n),t}function Qa(s,e,t,i){const r=Rt(Math.max(ue,e-ue-ji-2),Math.max(0,t-15));r.name("video-audio-status");const n=Rt(Math.max(0,ji-Kr),0),a=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";n.name(a),Ja(n,o,Kr,Ki,`${a}-icon`),r.add(n),s.add(r)}function Nh(s,e,t){const i=e.mediaStatus==="failed",r=vn(e.mediaStatusMessage),n=ui(0,0,e.width,e.height,i?t.failedBackground:t.background,t.border,t.borderWidth);n.cornerRadius(6),n.name("clip-background"),s.add(n),lr(s,e.width,e.height,!1);const a=ue+ls,o=Math.max(0,e.width-ue*2-ls*2),l=_h,c=Rt(a,l),h=Ja(c,"clip-audio",Kr,Ki,"audio-clip-icon");s.add(c);const d=a+h+cs,u=Math.max(0,o-h-cs);if(i&&u>0)Dh(s,d,l,u,r,t.failedLabel);else if(e.audioBadgeText&&u>0){const f=Et(e.audioBadgeText,d,l,jr,"Arial",t.label,"left","middle");f.height(Ki),pi(f),f.name("audio-clip-badge"),s.add(f)}const p=Et(e.clipName,a,e.height-Ah-hs,jr,"Arial",t.label,"left","middle");p.height(hs),pi(p),p.name("clip-label"),s.add(p)}function Gh(s,e,t){const i=ui(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),s.add(i),lr(s,e.width,e.height,!1);const r=Et(e.clipName,Eh,0,Ih,"Arial",t.label,"left","middle");r.height(e.height),r.lineHeight(1),pi(r),r.name("clip-label"),s.add(r)}function eo(s,e){const t=e.width<=ci,i=Ka(e.theme,e.isSelected,e.clipType);if(s.destroyChildren(),t){Lh(s,e.width,e.height,i);return}if(e.clipType==="audio"){Nh(s,e,i);return}if(e.clipType==="text"){Gh(s,e,i);return}Bh(s,e,i)}function Hh(s,e){if(e.width<=ci||e.clipType!=="video")return!1;const i=Ka(e.theme,e.isSelected,e.clipType);return Oh(s,e,i)}function $h(s,e,t,i,r,n,a,o=!1,l,c,h="video",d=!1,u=!1,p,f,m){const v=Rt(s,e);return v.clip({x:0,y:0,width:t,height:i}),eo(v,{width:t,height:i,clipName:r,audioBadgeText:p,duration:n,theme:a,isSelected:o,thumbnails:l,videoSrc:c,clipType:h,hasSeparatedAudio:d,deferCoverRender:u,mediaStatus:f,mediaStatusMessage:m}),v}function zh(s,e,t,i,r,n,a=!1,o,l,c="video",h=!1,d=!1,u,p,f){s.clip({x:0,y:0,width:e,height:t});const m={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:n??Wi,isSelected:a,thumbnails:o,videoSrc:l,clipType:c,hasSeparatedAudio:h,deferCoverRender:d,mediaStatus:p,mediaStatusMessage:f};Hh(s,m)||eo(s,m)}function Vh(s,e,t,i){return new Z.Rect({x:s,y:e,width:t,height:i,stroke:_.clipSelectedBorder,strokeWidth:qa,fillEnabled:!1})}function Zr(s,e=wt.stroke,t=1){return new Z.Line({points:s,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function Uh(s,e,t,i=12,r="Arial",n=wt.text,a="left",o="top"){return new Z.Text({text:s,x:e,y:t,fontSize:i,fontFamily:r,fill:n,align:a,verticalAlign:o})}function Wh(s=0,e=0){return new Z.Group({x:s,y:e})}function Yh(s,e,t,i,r,n,a,o){const l=o||i,c=a==="major"?l*.6:l*.3,h=Zr([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=Uh(U.formatTime(r),e,d,10,"Arial",n.timeText,"center");u.name("time-tick-text"),s.add(u)}}function Xh(s,e,t,i,r,n){const a=Wh(e,t);for(let o=0;o<=i;o+=n)a.add(Zr([o,0,o,r],xn.line,.5));for(let o=0;o<=r;o+=n)a.add(Zr([0,o,i,o],xn.line,.5));s.add(a)}class de{static createStage(e,t,i){return new Z.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new Z.Layer;return t.name(e),t}static createRect(e,t,i,r,n=wt.fill,a=wt.stroke,o=1){return new Z.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=wt.text,o="left",l="top"){return new Z.Text({text:e,x:t,y:i,fontSize:r,fontFamily:n,fill:a,align:o,verticalAlign:l})}static createLine(e,t=wt.stroke,i=1){return new Z.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new Z.Group({x:e,y:t})}static drawTimeTick(e,t,i,r,n,a,o,l){Yh(e,t,i,r,n,a,o,l)}static drawGrid(e,t,i,r,n,a){Xh(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,p=!1,f,m,v){return $h(e,t,i,r,n,a,o,l,c,h,d,u,p,f,m,v)}static updateClipGroup(e,t,i,r,n,a,o=!1,l,c,h="video",d=!1,u=!1,p,f,m){zh(e,t,i,r,n,a,o,l,c,h,d,u,p,f,m)}static createSelectionEffect(e,t,i,r){return Vh(e,t,i,r)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}g(de,"RESIZE_AREA_WIDTH",3);const Zt=8;function ge(s,e,t){return de.timeToPixels(s,e)-t+ke}function Se(s,e){const t=Math.max(s,0),i=de.timeToPixels(t,e);return i<=ci?ci:i}function qh(s,e){const t=ge(s.startTime,s.zoom,s.scrollLeft),i=Se(s.duration,s.zoom);return t+i>0&&t<e}function jh(s){for(const e of s.clips){const t=ge(e.startTime,s.zoom,s.scrollLeft),i=Se(e.duration,s.zoom),r=s.y>=s.trackY&&s.y<=s.trackY+s.trackHeight;if(s.x>=t&&s.x<=t+Zt&&r||s.x>=t+i-Zt&&s.x<=t+i&&r)return"ew-resize";if(s.x>t+Zt&&s.x<t+i-Zt&&r)return"pointer"}return"default"}class $i{constructor(e,t,i){g(this,"clip");g(this,"onUpdate");g(this,"onSplit");this.clip=dn({...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,a){const o=ge(this.clip.startTime,i,a),l=Se(this.clip.duration,i),c=Zt;return t<r||t>r+n?(this.setResizeHandleState(!1,!1),!1):e>=o&&e<=o+c?(this.setResizeHandleState(!0,!1),!0):e>=o+l-c&&e<=o+l?(this.setResizeHandleState(!1,!0),!0):(this.setResizeHandleState(!1,!1),!1)}startDrag(e){this.clip={...this.clip,isDragging:!0,isResizing:!1,isResizingLeft:!1,isResizingRight:!1},this.onUpdate(this.clip)}startResize(e){this.clip={...this.clip,isDragging:!0,isResizing:!0},this.onUpdate(this.clip)}endDrag(){this.clip={...this.clip,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1}}split(e){e>this.clip.startTime+1&&e<this.clip.endTime-1&&this.onSplit(this.clip,e)}setResizeHandleState(e,t){this.clip={...this.clip,isResizingLeft:e,isResizingRight:t}}}function cr(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 hr(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 ds(s){return!!s&&s.kind!=="idle"}function Ji(s){return(s==null?void 0:s.kind)==="draggingMove"||(s==null?void 0:s.kind)==="draggingResizeLeft"||(s==null?void 0:s.kind)==="draggingResizeRight"}function Ct(s){return!s||s.kind==="idle"||s.kind==="boxSelecting"?null:s.context}function Qi(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 Kh(s){const e=Qi(s);return e?e==="move"?"grabbing":"ew-resize":null}function Di(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=Jh(s.context,e,Qi(s)||"move");return s.kind==="pressed"?Qh(s.context,e.activationThreshold,e.clientX,e.clientY)?{state:Zh(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:Ji(s)}};const t=e.type==="POINTER_UP"&&Ji(s);return{state:Zi(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function Zh(s,e){return s==="resize-left"?{kind:"draggingResizeLeft",context:e}:s==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function Jh(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 Qh(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,p,f,m,v,T,S,C,k,x,P,D,w,A,B=ce.DEFAULT_DRAG_ACTIVATION_THRESHOLD,$=!1,F=ce.DEFAULT_CLIP_SNAP_THRESHOLD){g(this,"layer");g(this,"trackGroup");g(this,"dragOverlayLayer",null);g(this,"dropPreviewGroup",null);g(this,"dropPreviewClips",[]);g(this,"config");g(this,"theme");g(this,"trackType");g(this,"clips",[]);g(this,"clipGroups",new Map);g(this,"zoom",100);g(this,"scrollLeft",0);g(this,"trackY",0);g(this,"trackHeight",64);g(this,"selectedClip",null);g(this,"hasSelectedClip",!1);g(this,"selectedClipIds",new Set);g(this,"multiDragOriginalPositions",new Map);g(this,"promotedClipParents",new Map);g(this,"interactionState",Zi());g(this,"isVisualUpdate",!1);g(this,"onClipUpdate");g(this,"onClipAdd");g(this,"onClipRemove");g(this,"onClipSplit");g(this,"onClipSelect");g(this,"onTimeJump");g(this,"onClipOverlap");g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"hasLockedGlobalCursor",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"onHorizontalDragAutoScroll");g(this,"onClipCrossTrackPreview");g(this,"onClipCrossTrack");g(this,"onClearDropPreview");g(this,"onClearSelection");g(this,"onSnapGuideChange");g(this,"onClipToggleSelection");g(this,"onSetSingleSelection");g(this,"getMultiDragClipIds");g(this,"onMultiDragMove");g(this,"onMultiDragInteractionEnd");g(this,"resolveSnapTargetClips");g(this,"dragActivationThreshold");g(this,"enableClipSnap");g(this,"clipSnapThreshold");g(this,"handleGlobalPointerMove",e=>{ds(this.interactionState)&&this.handleDragMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});g(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});g(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const e=this.interactionState;if(!Ji(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=Ct(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=p,this.onHorizontalDragAutoScroll=f,this.onClipOverlap=m,this.onClipCrossTrackPreview=v,this.onClipCrossTrack=T,this.onClearDropPreview=S,this.onClearSelection=C,this.onSnapGuideChange=k,this.onClipToggleSelection=x,this.onSetSingleSelection=P,this.getMultiDragClipIds=D,this.onMultiDragMove=w,this.onMultiDragInteractionEnd=A,this.dragActivationThreshold=Math.max(0,B),this.enableClipSnap=$,this.clipSnapThreshold=Math.max(0,F),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 $i(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"?Ti.videoFill:Ti.audioFill,i=this.trackType==="text"?"#C9CBD4":this.trackType==="video"?Ti.videoStroke:Ti.audioStroke,r=ge(e.startTime,this.zoom,this.scrollLeft),n=Se(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=cr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(hr({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,U.pixelsToTime(n-ke+this.scrollLeft,this.zoom));this.onTimeJump(a),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(e){}getClipDisplayLabel(e){return(e.type==="text"||Le(e))&&e.textContent||e.name}getClipAudioBadgeText(e){if(Le(e))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=ge(e.startTime,this.zoom,this.scrollLeft),i=Se(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),e.mediaStatus,e.mediaStatusMessage);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 p=u.getBoundingClientRect(),f=t.clientX-p.left,m=t.clientY-p.top;if(r){this.multiDragOriginalPositions.clear();for(const T of this.selectedClipIds){const S=this.clips.find(C=>C.getClip().id===T);if(S){const C=S.getClip();this.multiDragOriginalPositions.set(T,{startTime:C.startTime,duration:C.duration})}}}let v;c.isPointInResizeHandle(f,m,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(v=c.getClip().isResizingLeft?"resize-left":"resize-right",c.startResize({x:f,y:m})):(v="move",c.startDrag({x:f,y:m}),this.trackGroup.moveToTop()),this.applyInteractionTransition(Di(this.interactionState,{type:"POINTER_DOWN",operation:v,clipId:e,originalClipsState:n,nonDraggedClips:a,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:f,localY:m,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=Di(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=Ct(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 m,v,T;const i=t??this.interactionState,r=Ct(i)||{clipId:e.id,originalClipsState:[e],nonDraggedClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:0,crossTrackDragOffsetY:0},n=Qi(i)||(e.isResizingLeft?"resize-left":e.isResizingRight?"resize-right":"move"),a=n==="move",o=a&&this.multiDragOriginalPositions.size>0,l=(m=this.clipGroups)==null?void 0:m.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 A of this.selectedClipIds){const B=(v=this.clipGroups)==null?void 0:v.get(A);B==null||B.y(2)}this.multiDragOriginalPositions.clear();return}const k=[],x=[];for(const[w,A]of this.multiDragOriginalPositions){const B=this.clips.find(H=>H.getClip().id===w);if(!B)continue;const $=Math.max(0,A.startTime+C),F={...B.getClip(),startTime:$,endTime:$+A.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(w)};k.push(F);const V=r.originalClipsState.find(H=>H.id===w);V&&x.push(V);const z=(T=this.clipGroups)==null?void 0:T.get(w);z&&z.y(2)}const P=[];for(const w of this.clips){const A=w.getClip(),B=k.find($=>$.id===A.id);B?P.push(B):P.push({...A,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}P.sort((w,A)=>w.startTime-A.startTime),this.isVisualUpdate=!0;for(const w of P)this.clips.find(B=>B.getClip().id===w.id)&&this.handleClipUpdate(w);this.isVisualUpdate=!1;const D=x.map(w=>{const A=k.find(B=>B.id===w.id);return A&&(w.startTime!==A.startTime||w.duration!==A.duration)?{clipId:w.id,previousState:w,newState:A}:null}).filter(w=>w!==null);D.length>0&&this.onClipUpdate(e,x.find(w=>w.id===e.id),D),this.multiDragOriginalPositions.clear();return}if(a&&this.onClipCrossTrack&&this.config.id){const S=r.originalClipsState.find(k=>k.id===e.id)??null;if(this.onClipCrossTrack(e,S,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 S of c){const C=S.startTime+S.duration;if(e.startTime<C&&d>S.startTime){h=!0;break}}if(a&&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 k of C){const x=u.findIndex(P=>P.id===k.id);x>=0&&(u[x]={...k,isSelected:!1})}}}let p=u.findIndex(S=>S.startTime>=e.startTime);p===-1&&(p=u.length),r.nonDraggedClips.forEach(S=>{S.isSelected=!1});const f={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};u.splice(p,0,f),this.updateAllClips(u),this.buildAndSendUpdates(f,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=jh({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 ds(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=Di(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=Se(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),e.mediaStatus,e.mediaStatusMessage)}}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 $i(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:U.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){O.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new $i(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=Ct(t),r=Di(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=qh({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(ge(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||te.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(){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 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=ge(t,this.zoom,this.scrollLeft);o.x(c),o.y(this.resolveClipRenderY(e,r)),o.moveToTop(),de.updateClipGroup(o,Se(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),a.mediaStatus,a.mediaStatusMessage),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=Ct(t);if(Ji(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var T,S,C,k,x,P;const r=this.interactionState,n=Ct(r),a=Qi(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,p=a==="move",f=p&&this.multiDragOriginalPositions.size>0;p&&O.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:u,currentTrackId:this.config.id,offsetY:n.crossTrackDragOffsetY}));const m=l.getClip(),v=(T=this.clipGroups)==null?void 0:T.get(m.id);if(v){const D=p&&n.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(m.id,D);const w=n.originalClipsState.find(L=>L.id===m.id);if(!w)return;const A=this.buildPreviewClip(m,w,d,n,a);if(!A){this.hideDropPreview(),(S=this.onClearDropPreview)==null||S.call(this),this.updateSnapGuideLine(null);return}const B=A.clip,$=B.startTime-w.startTime,F=this.applyPreviewClipState(l,B),V=ge(B.startTime,this.zoom,this.scrollLeft),z=Se(B.duration,this.zoom);v.x(V),v.y(this.resolveClipRenderY(m.id,n.crossTrackDragOffsetY)),v.visible(V+z>0&&V<this.layer.width()),F&&(this.updateClipGroup(B),v.y(this.resolveClipRenderY(m.id,n.crossTrackDragOffsetY)));let H=!1;if(f){this.onMultiDragMove&&this.config.id&&(H=this.onMultiDragMove({draggedClipId:m.id,deltaTime:$,targetTrackY:n.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:n.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[L,X]of this.multiDragOriginalPositions){if(L===m.id)continue;const N=this.clips.find(Y=>Y.getClip().id===L);if(!N)continue;const Q=Math.max(0,X.startTime+$),ae=(C=this.clipGroups)==null?void 0:C.get(L);if(ae){const Y=ge(Q,this.zoom,this.scrollLeft);ae.x(Y),ae.y(this.resolveClipRenderY(L,n.crossTrackDragOffsetY)),ae.visible(Y+Se(X.duration,this.zoom)>0&&Y<this.layer.width());const K=N.getClip();de.updateClipGroup(ae,Se(K.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(K),K.duration,this.theme,!0,K.thumbnails,K.src,K.type,!!K.separatedAudioClipId,!0,this.getClipAudioBadgeText(K),K.mediaStatus,K.mediaStatusMessage)}}}if(!f&&A.resizePushFollowers.length>0)for(const L of A.resizePushFollowers){const X=(k=this.clipGroups)==null?void 0:k.get(L.id);if(!X)continue;const N=ge(L.startTime,this.zoom,this.scrollLeft);X.x(N),X.y(this.resolveClipRenderY(L.id,n.crossTrackDragOffsetY)),X.visible(N+Se(L.duration,this.zoom)>0&&N<this.layer.width())}p&&this.onClipCrossTrackPreview&&this.config.id&&!H?this.onClipCrossTrackPreview(B,n.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():H?this.hideDropPreview():this.showDropPreview(B),this.updateSnapGuideLine(A.guideTime)}else this.hideDropPreview(),(x=this.onClearDropPreview)==null||x.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 a=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=U.pixelsToTime(a,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,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}}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),a=[...i].filter(h=>h.startTime>=n).sort((h,d)=>h.startTime-d.startTime);if(a.length===0)return[];const o=a[0],l=r-o.startTime;if(l<=0)return[];const c=l;return a.map(h=>({...h,startTime:h.startTime+c,endTime:h.startTime+c+h.duration}))}buildResizeLeftPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const p=U.calculateEndTime(t.startTime,t.duration);let f=Math.max(0,t.startTime+i),m=p-f;return m<ce.MIN_CLIP_DURATION_MS&&(m=ce.MIN_CLIP_DURATION_MS,f=p-m),{...e,startTime:f,duration:m,endTime:f+m,startTimeAtSource:0,endTimeAtSource:m,sourceDuration:m}}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,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=U.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(ge(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)}};g(ce,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),g(ce,"DEFAULT_CLIP_SNAP_THRESHOLD",8),g(ce,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(ce,"AUTO_SCROLL_MAX_SPEED",18),g(ce,"MIN_CLIP_DURATION_MS",1);let er=ce;/**
16
16
  * @license
17
17
  * Copyright 2019 Google LLC
18
18
  * SPDX-License-Identifier: BSD-3-Clause
19
- */const Hi=globalThis,yn=Hi.ShadowRoot&&(Hi.ShadyCSS===void 0||Hi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Ka=Symbol(),cs=new WeakMap;let Xh=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==Ka)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(yn&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=cs.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&cs.set(t,e))}return e}toString(){return this.cssText}};const qh=s=>new Xh(typeof s=="string"?s:s+"",void 0,Ka),jh=(s,e)=>{if(yn)s.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),r=Hi.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,s.appendChild(i)}},hs=yn?s=>s:s=>s instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return qh(t)})(s):s;/**
19
+ */const zi=globalThis,Cn=zi.ShadowRoot&&(zi.ShadyCSS===void 0||zi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,to=Symbol(),us=new WeakMap;let ed=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==to)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(Cn&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=us.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&us.set(t,e))}return e}toString(){return this.cssText}};const td=s=>new ed(typeof s=="string"?s:s+"",void 0,to),id=(s,e)=>{if(Cn)s.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),r=zi.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,s.appendChild(i)}},ps=Cn?s=>s:s=>s instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return td(t)})(s):s;/**
20
20
  * @license
21
21
  * Copyright 2017 Google LLC
22
22
  * SPDX-License-Identifier: BSD-3-Clause
23
- */const{is:Kh,defineProperty:Zh,getOwnPropertyDescriptor:Jh,getOwnPropertyNames:Qh,getOwnPropertySymbols:ed,getPrototypeOf:td}=Object,Qe=globalThis,ds=Qe.trustedTypes,id=ds?ds.emptyScript:"",Sr=Qe.reactiveElementPolyfillSupport,ri=(s,e)=>s,Kr={toAttribute(s,e){switch(e){case Boolean:s=s?id:null;break;case Object:case Array:s=s==null?s:JSON.stringify(s)}return s},fromAttribute(s,e){let t=s;switch(e){case Boolean:t=s!==null;break;case Number:t=s===null?null:Number(s);break;case Object:case Array:try{t=JSON.parse(s)}catch{t=null}}return t}},Za=(s,e)=>!Kh(s,e),us={attribute:!0,type:String,converter:Kr,reflect:!1,useDefault:!1,hasChanged:Za};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Qe.litPropertyMetadata??(Qe.litPropertyMetadata=new WeakMap);let Tt=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=us){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&&Zh(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){const{get:r,set:n}=Jh(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){const o=r==null?void 0:r.call(this);n==null||n.call(this,a),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??us}static _$Ei(){if(this.hasOwnProperty(ri("elementProperties")))return;const e=td(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(ri("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ri("properties"))){const t=this.properties,i=[...Qh(t),...ed(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(hs(r))}else e!==void 0&&t.push(hs(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 jh(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 a=(((n=i.converter)==null?void 0:n.toAttribute)!==void 0?i.converter:Kr).toAttribute(t,i.type);this._$Em=e,a==null?this.removeAttribute(r):this.setAttribute(r,a),this._$Em=null}}_$AK(e,t){var n,a;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:Kr;this._$Em=r;const c=l.fromAttribute(t,o.type);this[r]=c??((a=this._$Ej)==null?void 0:a.get(r))??c,this._$Em=null}}requestUpdate(e,t,i,r=!1,n){var a;if(e!==void 0){const o=this.constructor;if(r===!1&&(n=this[e]),i??(i=o.getPropertyOptions(e)),!((i.hasChanged??Za)(n,t)||i.useDefault&&i.reflect&&n===((a=this._$Ej)==null?void 0:a.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},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),n!==!0||a!==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,a]of this._$Ep)this[n]=a;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[n,a]of r){const{wrapped:o}=a,l=this[n];o!==!0||this._$AL.has(n)||l===void 0||this.C(n,void 0,a,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){}};Tt.elementStyles=[],Tt.shadowRootOptions={mode:"open"},Tt[ri("elementProperties")]=new Map,Tt[ri("finalized")]=new Map,Sr==null||Sr({ReactiveElement:Tt}),(Qe.reactiveElementVersions??(Qe.reactiveElementVersions=[])).push("2.1.2");/**
23
+ */const{is:rd,defineProperty:nd,getOwnPropertyDescriptor:sd,getOwnPropertyNames:ad,getOwnPropertySymbols:od,getPrototypeOf:ld}=Object,Qe=globalThis,gs=Qe.trustedTypes,cd=gs?gs.emptyScript:"",Cr=Qe.reactiveElementPolyfillSupport,si=(s,e)=>s,Jr={toAttribute(s,e){switch(e){case Boolean:s=s?cd:null;break;case Object:case Array:s=s==null?s:JSON.stringify(s)}return s},fromAttribute(s,e){let t=s;switch(e){case Boolean:t=s!==null;break;case Number:t=s===null?null:Number(s);break;case Object:case Array:try{t=JSON.parse(s)}catch{t=null}}return t}},io=(s,e)=>!rd(s,e),fs={attribute:!0,type:String,converter:Jr,reflect:!1,useDefault:!1,hasChanged:io};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),Qe.litPropertyMetadata??(Qe.litPropertyMetadata=new WeakMap);let bt=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=fs){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&&nd(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){const{get:r,set:n}=sd(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){const o=r==null?void 0:r.call(this);n==null||n.call(this,a),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??fs}static _$Ei(){if(this.hasOwnProperty(si("elementProperties")))return;const e=ld(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(si("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(si("properties"))){const t=this.properties,i=[...ad(t),...od(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(ps(r))}else e!==void 0&&t.push(ps(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 id(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 a=(((n=i.converter)==null?void 0:n.toAttribute)!==void 0?i.converter:Jr).toAttribute(t,i.type);this._$Em=e,a==null?this.removeAttribute(r):this.setAttribute(r,a),this._$Em=null}}_$AK(e,t){var n,a;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:Jr;this._$Em=r;const c=l.fromAttribute(t,o.type);this[r]=c??((a=this._$Ej)==null?void 0:a.get(r))??c,this._$Em=null}}requestUpdate(e,t,i,r=!1,n){var a;if(e!==void 0){const o=this.constructor;if(r===!1&&(n=this[e]),i??(i=o.getPropertyOptions(e)),!((i.hasChanged??io)(n,t)||i.useDefault&&i.reflect&&n===((a=this._$Ej)==null?void 0:a.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},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),n!==!0||a!==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,a]of this._$Ep)this[n]=a;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[n,a]of r){const{wrapped:o}=a,l=this[n];o!==!0||this._$AL.has(n)||l===void 0||this.C(n,void 0,a,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){}};bt.elementStyles=[],bt.shadowRootOptions={mode:"open"},bt[si("elementProperties")]=new Map,bt[si("finalized")]=new Map,Cr==null||Cr({ReactiveElement:bt}),(Qe.reactiveElementVersions??(Qe.reactiveElementVersions=[])).push("2.1.2");/**
24
24
  * @license
25
25
  * Copyright 2017 Google LLC
26
26
  * SPDX-License-Identifier: BSD-3-Clause
27
- */const ni=globalThis,ps=s=>s,Qi=ni.trustedTypes,gs=Qi?Qi.createPolicy("lit-html",{createHTML:s=>s}):void 0,Ja="$lit$",Ze=`lit$${Math.random().toFixed(9).slice(2)}$`,Qa="?"+Ze,rd=`<${Qa}>`,dt=document,ui=()=>dt.createComment(""),pi=s=>s===null||typeof s!="object"&&typeof s!="function",Sn=Array.isArray,nd=s=>Sn(s)||typeof(s==null?void 0:s[Symbol.iterator])=="function",vr=`[
28
- \f\r]`,$t=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,fs=/-->/g,ms=/>/g,st=RegExp(`>|${vr}(?:([^\\s"'>=/]+)(${vr}*=${vr}*(?:[^
29
- \f\r"'\`<>=]|("|')|))|$)`,"g"),ys=/'/g,Ss=/"/g,eo=/^(?:script|style|textarea|title)$/i,sd=s=>(e,...t)=>({_$litType$:s,strings:e,values:t}),j=sd(1),ut=Symbol.for("lit-noChange"),le=Symbol.for("lit-nothing"),vs=new WeakMap,ct=dt.createTreeWalker(dt,129);function to(s,e){if(!Sn(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return gs!==void 0?gs.createHTML(e):e}const ad=(s,e)=>{const t=s.length-1,i=[];let r,n=e===2?"<svg>":e===3?"<math>":"",a=$t;for(let o=0;o<t;o++){const l=s[o];let c,h,d=-1,u=0;for(;u<l.length&&(a.lastIndex=u,h=a.exec(l),h!==null);)u=a.lastIndex,a===$t?h[1]==="!--"?a=fs:h[1]!==void 0?a=ms:h[2]!==void 0?(eo.test(h[2])&&(r=RegExp("</"+h[2],"g")),a=st):h[3]!==void 0&&(a=st):a===st?h[0]===">"?(a=r??$t,d=-1):h[1]===void 0?d=-2:(d=a.lastIndex-h[2].length,c=h[1],a=h[3]===void 0?st:h[3]==='"'?Ss:ys):a===Ss||a===ys?a=st:a===fs||a===ms?a=$t:(a=st,r=void 0);const g=a===st&&s[o+1].startsWith("/>")?" ":"";n+=a===$t?l+rd:d>=0?(i.push(c),l.slice(0,d)+Ja+l.slice(d)+Ze+g):l+Ze+(d===-2?o:g)}return[to(s,n+(s[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class gi{constructor({strings:e,_$litType$:t},i){let r;this.parts=[];let n=0,a=0;const o=e.length-1,l=this.parts,[c,h]=ad(e,t);if(this.el=gi.createElement(c,i),ct.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=ct.nextNode())!==null&&l.length<o;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(Ja)){const u=h[a++],g=r.getAttribute(d).split(Ze),f=/([.?@])?(.*)/.exec(u);l.push({type:1,index:n,name:f[2],strings:g,ctor:f[1]==="."?ld:f[1]==="?"?cd:f[1]==="@"?hd:cr}),r.removeAttribute(d)}else d.startsWith(Ze)&&(l.push({type:6,index:n}),r.removeAttribute(d));if(eo.test(r.tagName)){const d=r.textContent.split(Ze),u=d.length-1;if(u>0){r.textContent=Qi?Qi.emptyScript:"";for(let g=0;g<u;g++)r.append(d[g],ui()),ct.nextNode(),l.push({type:2,index:++n});r.append(d[u],ui())}}}else if(r.nodeType===8)if(r.data===Qa)l.push({type:2,index:n});else{let d=-1;for(;(d=r.data.indexOf(Ze,d+1))!==-1;)l.push({type:7,index:n}),d+=Ze.length-1}n++}}static createElement(e,t){const i=dt.createElement("template");return i.innerHTML=e,i}}function Et(s,e,t=s,i){var a,o;if(e===ut)return e;let r=i!==void 0?(a=t._$Co)==null?void 0:a[i]:t._$Cl;const n=pi(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(s),r._$AT(s,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=r:t._$Cl=r),r!==void 0&&(e=Et(s,r._$AS(s,e.values),r,i)),e}class od{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)??dt).importNode(t,!0);ct.currentNode=r;let n=ct.nextNode(),a=0,o=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new Si(n,n.nextSibling,this,e):l.type===1?c=new l.ctor(n,l.name,l.strings,this,e):l.type===6&&(c=new dd(n,this,e)),this._$AV.push(c),l=i[++o]}a!==(l==null?void 0:l.index)&&(n=ct.nextNode(),a++)}return ct.currentNode=dt,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 Si{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=Et(this,e,t),pi(e)?e===le||e==null||e===""?(this._$AH!==le&&this._$AR(),this._$AH=le):e!==this._$AH&&e!==ut&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):nd(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&&pi(this._$AH)?this._$AA.nextSibling.data=e:this.T(dt.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=gi.createElement(to(i.h,i.h[0]),this.options)),i);if(((n=this._$AH)==null?void 0:n._$AD)===r)this._$AH.p(t);else{const a=new od(r,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=vs.get(e.strings);return t===void 0&&vs.set(e.strings,t=new gi(e)),t}k(e){Sn(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 Si(this.O(ui()),this.O(ui()),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=ps(e).nextSibling;ps(e).remove(),e=r}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class cr{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 a=!1;if(n===void 0)e=Et(this,e,t,0),a=!pi(e)||e!==this._$AH&&e!==ut,a&&(this._$AH=e);else{const o=e;let l,c;for(e=n[0],l=0;l<n.length-1;l++)c=Et(this,o[i+l],t,l),c===ut&&(c=this._$AH[l]),a||(a=!pi(c)||c!==this._$AH[l]),c===le?e=le:e!==le&&(e+=(c??"")+n[l+1]),this._$AH[l]=c}a&&!r&&this.j(e)}j(e){e===le?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class ld extends cr{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===le?void 0:e}}class cd extends cr{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==le)}}class hd extends cr{constructor(e,t,i,r,n){super(e,t,i,r,n),this.type=5}_$AI(e,t=this){if((e=Et(this,e,t,0)??le)===ut)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 dd{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){Et(this,e)}}const Cr=ni.litHtmlPolyfillSupport;Cr==null||Cr(gi,Si),(ni.litHtmlVersions??(ni.litHtmlVersions=[])).push("3.3.2");const fi=(s,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 Si(e.insertBefore(ui(),n),n,void 0,t??{})}return r._$AI(s),r};/**
27
+ */const ai=globalThis,ms=s=>s,tr=ai.trustedTypes,ys=tr?tr.createPolicy("lit-html",{createHTML:s=>s}):void 0,ro="$lit$",Ze=`lit$${Math.random().toFixed(9).slice(2)}$`,no="?"+Ze,hd=`<${no}>`,dt=document,gi=()=>dt.createComment(""),fi=s=>s===null||typeof s!="object"&&typeof s!="function",Tn=Array.isArray,dd=s=>Tn(s)||typeof(s==null?void 0:s[Symbol.iterator])=="function",Tr=`[
28
+ \f\r]`,Vt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Ss=/-->/g,vs=/>/g,st=RegExp(`>|${Tr}(?:([^\\s"'>=/]+)(${Tr}*=${Tr}*(?:[^
29
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),Cs=/'/g,Ts=/"/g,so=/^(?:script|style|textarea|title)$/i,ud=s=>(e,...t)=>({_$litType$:s,strings:e,values:t}),j=ud(1),ut=Symbol.for("lit-noChange"),le=Symbol.for("lit-nothing"),bs=new WeakMap,ct=dt.createTreeWalker(dt,129);function ao(s,e){if(!Tn(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return ys!==void 0?ys.createHTML(e):e}const pd=(s,e)=>{const t=s.length-1,i=[];let r,n=e===2?"<svg>":e===3?"<math>":"",a=Vt;for(let o=0;o<t;o++){const l=s[o];let c,h,d=-1,u=0;for(;u<l.length&&(a.lastIndex=u,h=a.exec(l),h!==null);)u=a.lastIndex,a===Vt?h[1]==="!--"?a=Ss:h[1]!==void 0?a=vs:h[2]!==void 0?(so.test(h[2])&&(r=RegExp("</"+h[2],"g")),a=st):h[3]!==void 0&&(a=st):a===st?h[0]===">"?(a=r??Vt,d=-1):h[1]===void 0?d=-2:(d=a.lastIndex-h[2].length,c=h[1],a=h[3]===void 0?st:h[3]==='"'?Ts:Cs):a===Ts||a===Cs?a=st:a===Ss||a===vs?a=Vt:(a=st,r=void 0);const p=a===st&&s[o+1].startsWith("/>")?" ":"";n+=a===Vt?l+hd:d>=0?(i.push(c),l.slice(0,d)+ro+l.slice(d)+Ze+p):l+Ze+(d===-2?o:p)}return[ao(s,n+(s[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class mi{constructor({strings:e,_$litType$:t},i){let r;this.parts=[];let n=0,a=0;const o=e.length-1,l=this.parts,[c,h]=pd(e,t);if(this.el=mi.createElement(c,i),ct.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=ct.nextNode())!==null&&l.length<o;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(ro)){const u=h[a++],p=r.getAttribute(d).split(Ze),f=/([.?@])?(.*)/.exec(u);l.push({type:1,index:n,name:f[2],strings:p,ctor:f[1]==="."?fd:f[1]==="?"?md:f[1]==="@"?yd:dr}),r.removeAttribute(d)}else d.startsWith(Ze)&&(l.push({type:6,index:n}),r.removeAttribute(d));if(so.test(r.tagName)){const d=r.textContent.split(Ze),u=d.length-1;if(u>0){r.textContent=tr?tr.emptyScript:"";for(let p=0;p<u;p++)r.append(d[p],gi()),ct.nextNode(),l.push({type:2,index:++n});r.append(d[u],gi())}}}else if(r.nodeType===8)if(r.data===no)l.push({type:2,index:n});else{let d=-1;for(;(d=r.data.indexOf(Ze,d+1))!==-1;)l.push({type:7,index:n}),d+=Ze.length-1}n++}}static createElement(e,t){const i=dt.createElement("template");return i.innerHTML=e,i}}function Mt(s,e,t=s,i){var a,o;if(e===ut)return e;let r=i!==void 0?(a=t._$Co)==null?void 0:a[i]:t._$Cl;const n=fi(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(s),r._$AT(s,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=r:t._$Cl=r),r!==void 0&&(e=Mt(s,r._$AS(s,e.values),r,i)),e}class gd{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)??dt).importNode(t,!0);ct.currentNode=r;let n=ct.nextNode(),a=0,o=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new Ci(n,n.nextSibling,this,e):l.type===1?c=new l.ctor(n,l.name,l.strings,this,e):l.type===6&&(c=new Sd(n,this,e)),this._$AV.push(c),l=i[++o]}a!==(l==null?void 0:l.index)&&(n=ct.nextNode(),a++)}return ct.currentNode=dt,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 Ci{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=Mt(this,e,t),fi(e)?e===le||e==null||e===""?(this._$AH!==le&&this._$AR(),this._$AH=le):e!==this._$AH&&e!==ut&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):dd(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&&fi(this._$AH)?this._$AA.nextSibling.data=e:this.T(dt.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=mi.createElement(ao(i.h,i.h[0]),this.options)),i);if(((n=this._$AH)==null?void 0:n._$AD)===r)this._$AH.p(t);else{const a=new gd(r,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=bs.get(e.strings);return t===void 0&&bs.set(e.strings,t=new mi(e)),t}k(e){Tn(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 Ci(this.O(gi()),this.O(gi()),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=ms(e).nextSibling;ms(e).remove(),e=r}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class dr{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 a=!1;if(n===void 0)e=Mt(this,e,t,0),a=!fi(e)||e!==this._$AH&&e!==ut,a&&(this._$AH=e);else{const o=e;let l,c;for(e=n[0],l=0;l<n.length-1;l++)c=Mt(this,o[i+l],t,l),c===ut&&(c=this._$AH[l]),a||(a=!fi(c)||c!==this._$AH[l]),c===le?e=le:e!==le&&(e+=(c??"")+n[l+1]),this._$AH[l]=c}a&&!r&&this.j(e)}j(e){e===le?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class fd extends dr{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===le?void 0:e}}class md extends dr{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==le)}}class yd extends dr{constructor(e,t,i,r,n){super(e,t,i,r,n),this.type=5}_$AI(e,t=this){if((e=Mt(this,e,t,0)??le)===ut)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 Sd{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){Mt(this,e)}}const br=ai.litHtmlPolyfillSupport;br==null||br(mi,Ci),(ai.litHtmlVersions??(ai.litHtmlVersions=[])).push("3.3.2");const yi=(s,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 Ci(e.insertBefore(gi(),n),n,void 0,t??{})}return r._$AI(s),r};/**
30
30
  * @license
31
31
  * Copyright 2017 Google LLC
32
32
  * SPDX-License-Identifier: BSD-3-Clause
33
- */const ht=globalThis;let $i=class extends Tt{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=fi(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 ut}};var Xs;$i._$litElement$=!0,$i.finalized=!0,(Xs=ht.litElementHydrateSupport)==null||Xs.call(ht,{LitElement:$i});const br=ht.litElementPolyfillSupport;br==null||br({LitElement:$i});(ht.litElementVersions??(ht.litElementVersions=[])).push("4.2.2");class ud{constructor(){p(this,"container",null)}mount(e,t){return this.container=e,fi(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&&fi(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`
33
+ */const ht=globalThis;let Vi=class extends bt{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=yi(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 ut}};var Zs;Vi._$litElement$=!0,Vi.finalized=!0,(Zs=ht.litElementHydrateSupport)==null||Zs.call(ht,{LitElement:Vi});const kr=ht.litElementPolyfillSupport;kr==null||kr({LitElement:Vi});(ht.litElementVersions??(ht.litElementVersions=[])).push("4.2.2");class vd{constructor(){g(this,"container",null)}mount(e,t){return this.container=e,yi(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&&yi(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`
34
34
  <div
35
35
  class="timeline-manager-header-corner"
36
36
  data-layout-role="header-corner"
@@ -78,7 +78,7 @@ js: import "konva/skia-backend";
78
78
  data-layout-role="playhead-overlay"
79
79
  style=${["position:absolute",`left:${r}px`,"top:0","right:0","bottom:0","pointer-events:none","z-index:3"].join(";")}
80
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 mi=80,Zr=8,Cs="timeline-manager-managed-layout-styles";function pd(){if(typeof document>"u"||document.getElementById(Cs))return;const s=document.createElement("style");s.id=Cs,s.textContent=`
81
+ `}requireElement(e,t){const i=e.querySelector(t);if(!i)throw new Error(`Missing timeline manager layout element: ${t}`);return i}}const Si=80,Qr=8,ks="timeline-manager-managed-layout-styles";function Cd(){if(typeof document>"u"||document.getElementById(ks))return;const s=document.createElement("style");s.id=ks,s.textContent=`
82
82
  .timeline-manager-root {
83
83
  position: relative;
84
84
  overflow: hidden;
@@ -104,15 +104,15 @@ js: import "konva/skia-backend";
104
104
  height: 0;
105
105
  display: none;
106
106
  }
107
- `,document.head.appendChild(s)}function gd(s,e){pd();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??mi,scrollbarSize:e.scrollbarSize??Zr};return new ud().mount(s,t)}/**
107
+ `,document.head.appendChild(s)}function Td(s,e){Cd();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??Si,scrollbarSize:e.scrollbarSize??Qr};return new vd().mount(s,t)}/**
108
108
  * @license
109
109
  * Copyright 2017 Google LLC
110
110
  * SPDX-License-Identifier: BSD-3-Clause
111
- */const fd={CHILD:2},md=s=>(...e)=>({_$litDirective$:s,values:e});class yd{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)}}/**
111
+ */const bd={CHILD:2},kd=s=>(...e)=>({_$litDirective$:s,values:e});class wd{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)}}/**
112
112
  * @license
113
113
  * Copyright 2017 Google LLC
114
114
  * SPDX-License-Identifier: BSD-3-Clause
115
- */class Jr extends yd{constructor(e){if(super(e),this.it=le,e.type!==fd.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===ut)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:[]}}}Jr.directiveName="unsafeHTML",Jr.resultType=1;const er=md(Jr);function Ae(s){return s==="text"?Bi.TEXT:s==="video"?Bi.VIDEO:Bi.AUDIO}function zt(s,e,t){let i=t;for(const r of s){if(r.id===e)break;i+=Ae(r.type)}return i}function bs(s,e){return s.reduce((t,i)=>t+Ae(i.type),e)}function Sd(s,e){let t=e;return s.map(i=>{const r=Ae(i.type),n={trackId:i.id,y:t,height:r};return t+=r,n})}class io{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&&fi(le,this.container),this.container=null,this.viewModel=null}get mountedContainer(){return this.container}afterRender(e,t){}renderCurrent(){!this.container||!this.viewModel||(fi(this.renderTemplate(this.viewModel),this.container),this.afterRender(this.container,this.viewModel))}}class vd extends io{renderTemplate(e){const{theme:t,tracks:i,scrollTop:r,timeScaleHeight:n,includeTimeScaleSpacer:a,onMuteTrack:o,icons:l}=e;return j`
115
+ */class en extends wd{constructor(e){if(super(e),this.it=le,e.type!==bd.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===ut)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:[]}}}en.directiveName="unsafeHTML",en.resultType=1;const ir=kd(en);function Ae(s){return s==="text"?Ni.TEXT:s==="video"?Ni.VIDEO:Ni.AUDIO}function Ut(s,e,t){let i=t;for(const r of s){if(r.id===e)break;i+=Ae(r.type)}return i}function ws(s,e){return s.reduce((t,i)=>t+Ae(i.type),e)}function Pd(s,e){let t=e;return s.map(i=>{const r=Ae(i.type),n={trackId:i.id,y:t,height:r};return t+=r,n})}class oo{constructor(){g(this,"container",null);g(this,"viewModel",null)}mount(e){this.container=e,this.renderCurrent()}update(e){this.viewModel=e,this.renderCurrent()}destroy(){this.container&&yi(le,this.container),this.container=null,this.viewModel=null}get mountedContainer(){return this.container}afterRender(e,t){}renderCurrent(){!this.container||!this.viewModel||(yi(this.renderTemplate(this.viewModel),this.container),this.afterRender(this.container,this.viewModel))}}class xd extends oo{renderTemplate(e){const{theme:t,tracks:i,scrollTop:r,timeScaleHeight:n,includeTimeScaleSpacer:a,onMuteTrack:o,icons:l}=e;return j`
116
116
  <style>
117
117
  .track-info-item:hover {
118
118
  background: ${t.buttonHover};
@@ -140,7 +140,7 @@ js: import "konva/skia-backend";
140
140
  class="track-icon"
141
141
  style="user-select:none;display:flex;align-items:center;justify-content:flex-start;flex-shrink:0;"
142
142
  >
143
- ${o?er(this.resizeSvg(o,18)):e.type==="text"?"T":e.type==="video"?"🎬":"🎵"}
143
+ ${o?ir(this.resizeSvg(o,18)):e.type==="text"?"T":e.type==="video"?"🎬":"🎵"}
144
144
  </span>
145
145
  <button
146
146
  class="track-mute-btn"
@@ -148,10 +148,10 @@ js: import "konva/skia-backend";
148
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(";")}
149
149
  @click=${h=>{h.stopPropagation(),r==null||r(e.id,!e.isMuted)}}
150
150
  >
151
- ${l?er(this.resizeSvg(l,14)):e.isMuted?"🔇":"🔊"}
151
+ ${l?ir(this.resizeSvg(l,14)):e.isMuted?"🔇":"🔊"}
152
152
  </button>
153
153
  </div>
154
- `}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class ro{constructor(e,t,i,r){p(this,"container");p(this,"tracks",[]);p(this,"theme");p(this,"width",mi);p(this,"timeScaleHeight",40);p(this,"includeTimeScaleSpacer",!0);p(this,"scrollTop",0);p(this,"renderer",new vd);p(this,"iconCache",new Map);p(this,"onMuteTrack");var n,a,o,l,c,h;this.container=e.container,this.width=e.width??mi,this.timeScaleHeight=e.timeScaleHeight||40,this.includeTimeScaleSpacer=e.includeTimeScaleSpacer??!0,this.theme={background:((n=e.theme)==null?void 0:n.background)||be.background,border:((a=e.theme)==null?void 0:a.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 Cd={visual:"画面",audio:"音频",text:"文本",voice:"音色"},N={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"},Pt=class Pt extends io{renderTemplate(e){const{theme:t}=e;return j`
154
+ `}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class lo{constructor(e,t,i,r){g(this,"container");g(this,"tracks",[]);g(this,"theme");g(this,"width",Si);g(this,"timeScaleHeight",40);g(this,"includeTimeScaleSpacer",!0);g(this,"scrollTop",0);g(this,"renderer",new xd);g(this,"iconCache",new Map);g(this,"onMuteTrack");var n,a,o,l,c,h;this.container=e.container,this.width=e.width??Si,this.timeScaleHeight=e.timeScaleHeight||40,this.includeTimeScaleSpacer=e.includeTimeScaleSpacer??!0,this.theme={background:((n=e.theme)==null?void 0:n.background)||be.background,border:((a=e.theme)==null?void 0:a.border)||be.border,text:((o=e.theme)==null?void 0:o.text)||be.text,buttonBackground:((l=e.theme)==null?void 0:l.buttonBackground)||be.buttonBackground,buttonHover:((c=e.theme)==null?void 0:c.buttonHover)||be.buttonHover,buttonDanger:((h=e.theme)==null?void 0:h.buttonDanger)||be.buttonDanger},this.onMuteTrack=r,this.iconCache.set("OmAi-camera",Te("OmAi-camera")),this.iconCache.set("OmAi-display",Te("OmAi-display")),this.iconCache.set("OmAi-hide",Te("OmAi-hide")),this.iconCache.set("OmAi-music",Te("OmAi-music")),this.iconCache.set("OmAi-text",Te("OmAi-text")),this.iconCache.set("OmAi-volume",Te("OmAi-volume")),this.iconCache.set("OmAi-volume-mute",Te("OmAi-volume-mute")),this.init()}init(){this.container.className="track-info-panel",this.container.style.position="relative",this.container.style.overflow="hidden",this.container.style.width=`${this.width}px`,this.container.style.background=this.theme.background,this.container.style.borderRight=`1px solid ${this.theme.border}`,this.container.style.color=this.theme.text,this.renderer.mount(this.container),this.render()}setTracks(e){this.tracks=[...e],this.render()}getTracks(){return[...this.tracks]}render(){this.renderer.update({tracks:this.tracks,scrollTop:this.scrollTop,theme:this.theme,timeScaleHeight:this.timeScaleHeight,includeTimeScaleSpacer:this.includeTimeScaleSpacer,onMuteTrack:this.onMuteTrack,icons:{textTrack:this.iconCache.get("OmAi-text")??"",videoTrack:this.iconCache.get("OmAi-camera")??"",audioTrack:this.iconCache.get("OmAi-music")??"",display:this.iconCache.get("OmAi-display")??"",hide:this.iconCache.get("OmAi-hide")??"",volume:this.iconCache.get("OmAi-volume")??"",volumeMuted:this.iconCache.get("OmAi-volume-mute")??""}})}setScrollTop(e){this.scrollTop=Math.max(0,e),this.render()}destroy(){this.renderer.destroy(),this.container.innerHTML=""}}const _d={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"},xt=class xt extends oo{renderTemplate(e){const{theme:t}=e;return j`
155
155
  <style>
156
156
  @keyframes clip-config-voice-loading-spin {
157
157
  from { transform: rotate(0deg); }
@@ -211,10 +211,10 @@ js: import "konva/skia-backend";
211
211
  border-radius: 50%;
212
212
  appearance: none;
213
213
  -webkit-appearance: none;
214
- background: radial-gradient(circle at 32% 30%, ${I.sliderThumbGlowStart} 0%, ${I.sliderThumbGlowEnd} 74%);
214
+ background: radial-gradient(circle at 32% 30%, ${_.sliderThumbGlowStart} 0%, ${_.sliderThumbGlowEnd} 74%);
215
215
  box-shadow:
216
216
  var(--clip-slider-thumb-shadow),
217
- ${Pe.sliderThumbInnerShadow};
217
+ ${xe.sliderThumbInnerShadow};
218
218
  }
219
219
 
220
220
  .clip-config-panel .clip-config-slider::-moz-range-track {
@@ -234,10 +234,10 @@ js: import "konva/skia-backend";
234
234
  height: 9px;
235
235
  border: 1px solid var(--clip-slider-thumb-border);
236
236
  border-radius: 50%;
237
- background: radial-gradient(circle at 32% 30%, ${I.sliderThumbGlowStart} 0%, ${I.sliderThumbGlowEnd} 74%);
237
+ background: radial-gradient(circle at 32% 30%, ${_.sliderThumbGlowStart} 0%, ${_.sliderThumbGlowEnd} 74%);
238
238
  box-shadow:
239
239
  var(--clip-slider-thumb-shadow),
240
- ${Pe.sliderThumbInnerShadow};
240
+ ${xe.sliderThumbInnerShadow};
241
241
  }
242
242
  .clip-config-voice-card{
243
243
  border: 1px solid transparent;
@@ -265,7 +265,7 @@ js: import "konva/skia-backend";
265
265
  padding: 4px 10px;
266
266
  border-radius: 6px;
267
267
  background: #4e5569;
268
- color: ${I.white};
268
+ color: ${_.white};
269
269
  font-size: 11px;
270
270
  line-height: 1.3;
271
271
  font-weight: 500;
@@ -391,27 +391,27 @@ js: import "konva/skia-backend";
391
391
  transform: none;
392
392
  }
393
393
  </style>
394
- <div class=${N.container} style=${this.getContainerStyle(t)}>
394
+ <div class=${G.container} style=${this.getContainerStyle(t)}>
395
395
  ${e.emptyStateMessage?this.renderEmptyState(t,e.emptyStateMessage):this.renderPanel(e)}
396
396
  </div>
397
397
  ${this.renderVoiceLoadingOverlay(e)}
398
398
  `}renderVoiceLoadingOverlay(e){return e.isVoiceLoadingOverlayVisible?j`
399
399
  <div
400
- class=${N.voiceLoadingOverlay}
400
+ class=${G.voiceLoadingOverlay}
401
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(";")}
402
402
  >
403
403
  <div
404
- class=${N.voiceLoadingCard}
404
+ class=${G.voiceLoadingCard}
405
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(";")}
406
406
  >
407
407
  <div
408
- class=${N.voiceLoadingIcon}
408
+ class=${G.voiceLoadingIcon}
409
409
  style="width:24px;height:24px;display:flex;align-items:center;justify-content:center;animation:clip-config-voice-loading-spin 1s linear infinite;"
410
410
  >
411
- ${e.loadingIconSvg?er(this.resizeSvg(e.loadingIconSvg,24)):"⟳"}
411
+ ${e.loadingIconSvg?ir(this.resizeSvg(e.loadingIconSvg,24)):"⟳"}
412
412
  </div>
413
413
  <div
414
- class=${N.voiceLoadingText}
414
+ class=${G.voiceLoadingText}
415
415
  style="font-size:14px;line-height:24px;color:#c9cbd4;"
416
416
  >
417
417
  配音生成中...
@@ -420,7 +420,7 @@ js: import "konva/skia-backend";
420
420
  </div>
421
421
  `:null}renderEmptyState(e,t){return j`
422
422
  <div
423
- class=${N.emptyState}
423
+ class=${G.emptyState}
424
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;`}
425
425
  >
426
426
  <div style="font-size:13px;">${t}</div>
@@ -428,7 +428,7 @@ js: import "konva/skia-backend";
428
428
  `}renderPanel(e){const t=e.availableTabs,i=this.shouldUseVoiceInnerScroll(e);return j`
429
429
  ${t.length>1?this.renderTabBar(e,t):null}
430
430
  <div
431
- class=${N.content}
431
+ class=${G.content}
432
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;"}
433
433
  >
434
434
  ${t.map(r=>this.renderTabPanel(e,r))}
@@ -436,30 +436,30 @@ js: import "konva/skia-backend";
436
436
  ${this.renderActionBar(e)}
437
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`
438
438
  <div
439
- class=${N.tabBar}
440
- style=${`display:flex;gap:12px;padding:4px;background-color:${Pe.tabBarBackground};border-radius:4px 4px 0 0;height:32px;`}
439
+ class=${G.tabBar}
440
+ style=${`display:flex;gap:12px;padding:4px;background-color:${xe.tabBarBackground};border-radius:4px 4px 0 0;height:32px;`}
441
441
  >
442
442
  ${t.map(i=>{const r=e.activeTab===i;return j`
443
443
  <button
444
- class=${N.tabButton}
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?Pe.activeTabBackground:I.transparent}`,`color:${r?Pe.activeTabText:Pe.inactiveTabText}`,"border-radius:4px"].join(";")}
444
+ class=${G.tabButton}
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:_.transparent}`,`color:${r?xe.activeTabText:xe.inactiveTabText}`,"border-radius:4px"].join(";")}
446
446
  @click=${()=>e.callbacks.onTabChange(i)}
447
447
  >
448
- ${Cd[i]}
448
+ ${_d[i]}
449
449
  </button>
450
450
  `})}
451
451
  </div>
452
452
  `}renderActionBar(e){const t=e.activeTab==="voice"&&this.supportsVoicePanel(e.selectionState);return j`
453
453
  <div
454
- class=${N.actionBar}
455
- style=${[`border-top:1px solid ${e.theme.borderColor}`,"border-radius:0 0 4px 4px","min-height:32px",`background-color:${Pe.actionBarBackground}`,"padding:8px 10px"].join(";")}
454
+ class=${G.actionBar}
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(";")}
456
456
  >
457
457
  ${t?this.renderVoiceActionBar(e):null}
458
458
  </div>
459
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`
460
460
  <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
461
461
  <label
462
- class=${N.voiceCheckbox}
462
+ class=${G.voiceCheckbox}
463
463
  style="display:flex;align-items:center;gap:8px;cursor:pointer;"
464
464
  >
465
465
  <input
@@ -470,8 +470,8 @@ js: import "konva/skia-backend";
470
470
  <span style=${`font-size:12px;color:${e.theme.textColor};`}>${r}</span>
471
471
  </label>
472
472
  <button
473
- class=${N.primaryButton}
474
- style=${[`--clip-config-primary-bg:${i?e.theme.buttonBackground:Pe.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(";")}
473
+ class=${G.primaryButton}
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(";")}
475
475
  ?disabled=${i}
476
476
  @click=${()=>{e.callbacks.onGenerateVoice()}}
477
477
  >
@@ -479,12 +479,12 @@ js: import "konva/skia-backend";
479
479
  </button>
480
480
  </div>
481
481
  `}renderVisualPanel(e){const t=e.activeTab==="visual"?"block":"none";return j`
482
- <div class=${N.visualPanel} style=${`display:${t};`}>
482
+ <div class=${G.visualPanel} style=${`display:${t};`}>
483
483
  ${this.renderPositionSection(e)}
484
484
  ${this.renderScaleSection(e)}
485
485
  </div>
486
486
  `}renderPositionSection(e){return j`
487
- <div class=${N.section} style="margin-bottom:16px;">
487
+ <div class=${G.section} style="margin-bottom:16px;">
488
488
  ${this.renderSectionTitle("位置",e.theme)}
489
489
  ${this.renderPositionControl(e,"X","x")}
490
490
  ${this.renderPositionControl(e,"Y","y")}
@@ -492,15 +492,15 @@ js: import "konva/skia-backend";
492
492
  </div>
493
493
  `}renderScaleSection(e){const t=this.getTransform(e.clip);return j`
494
494
  <div
495
- class=${N.section}
495
+ class=${G.section}
496
496
  style=${`border-top:1px solid ${e.theme.borderColor};padding-top:16px;`}
497
497
  >
498
498
  ${this.renderSectionTitle("缩放",e.theme)}
499
- <div class=${N.row} style="display:flex;align-items:center;gap:8px;">
499
+ <div class=${G.row} style="display:flex;align-items:center;gap:8px;">
500
500
  ${this.renderRangeInput({min:"0.1",max:"8",step:"0.1",value:String(t.scale),onInput:i=>e.callbacks.onTransformChange("scale",i)})}
501
501
  ${this.renderNumberInput(e.theme,{min:"0.1",max:"8",step:"0.1",value:String(t.scale),onChange:i=>e.callbacks.onTransformChange("scale",i)})}
502
502
  <button
503
- class=${N.resetButton}
503
+ class=${G.resetButton}
504
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(";")}
505
505
  @click=${()=>e.callbacks.onTransformChange("scale",1)}
506
506
  >
@@ -509,10 +509,10 @@ js: import "konva/skia-backend";
509
509
  </div>
510
510
  </div>
511
511
  `}renderAudioPanel(e){var r;const t=e.activeTab==="audio"?"block":"none",i=((r=e.clip)==null?void 0:r.volume)??1;return j`
512
- <div class=${N.audioPanel} style=${`display:${t};`}>
513
- <div class=${N.section}>
512
+ <div class=${G.audioPanel} style=${`display:${t};`}>
513
+ <div class=${G.section}>
514
514
  ${this.renderSectionTitle("音量",e.theme)}
515
- <div class=${N.row} style="display:flex;align-items:center;gap:8px;">
515
+ <div class=${G.row} style="display:flex;align-items:center;gap:8px;">
516
516
  ${this.renderRangeInput({min:"0",max:"1",step:"0.01",value:String(i),onInput:n=>e.callbacks.onVolumeChange(n)})}
517
517
  ${this.renderNumberInput(e.theme,{min:"0",max:"100",step:"1",value:String(Math.round(i*100)),onChange:n=>e.callbacks.onVolumeChange(n/100)})}
518
518
  <span style=${`font-size:12px;color:${e.theme.labelColor};`}>%</span>
@@ -520,12 +520,12 @@ js: import "konva/skia-backend";
520
520
  </div>
521
521
  </div>
522
522
  `}renderTextPanel(e){const t=e.clip,i=this.getTransform(t),r=De(t==null?void 0:t.textStyle),n=e.activeTab==="text"?"block":"none";return j`
523
- <div class=${N.textPanel} style=${`display:${n};`}>
523
+ <div class=${G.textPanel} style=${`display:${n};`}>
524
524
  ${e.isTextContentEditable?j`
525
- <div class=${N.section} style="margin-bottom:16px;">
525
+ <div class=${G.section} style="margin-bottom:16px;">
526
526
  ${this.renderSectionTitle("文本",e.theme)}
527
527
  <textarea
528
- class=${N.textarea}
528
+ class=${G.textarea}
529
529
  rows="5"
530
530
  .value=${e.textDraftContent}
531
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(";")}
@@ -534,49 +534,49 @@ js: import "konva/skia-backend";
534
534
  ></textarea>
535
535
  </div>
536
536
  `:null}
537
- <div class=${N.section} style="margin-bottom:16px;">
537
+ <div class=${G.section} style="margin-bottom:16px;">
538
538
  ${this.renderSectionTitle("字号",e.theme)}
539
- <div class=${N.row} style="display:flex;align-items:center;gap:8px;">
539
+ <div class=${G.row} style="display:flex;align-items:center;gap:8px;">
540
540
  ${this.renderRangeInput({min:"5",max:"300",step:"1",value:String(r.fontSize),onInput:a=>e.callbacks.onTextStyleChange("fontSize",a)})}
541
541
  ${this.renderNumberInput(e.theme,{min:"5",max:"300",step:"1",value:String(r.fontSize),onChange:a=>e.callbacks.onTextStyleChange("fontSize",a)})}
542
542
  </div>
543
543
  </div>
544
- <div class=${N.section} style="margin-bottom:16px;">
544
+ <div class=${G.section} style="margin-bottom:16px;">
545
545
  ${this.renderSectionTitle("颜色",e.theme)}
546
546
  <input
547
547
  type="color"
548
- class=${N.colorInput}
548
+ class=${G.colorInput}
549
549
  .value=${r.color}
550
550
  style=${["width:108px","height:48px","padding:4px",`border:1px solid ${e.theme.inputBorder}`,"border-radius:8px",`background-color:${e.theme.inputBackground}`].join(";")}
551
- @input=${Pt.createColorInputHandler(e)}
551
+ @input=${xt.createColorInputHandler(e)}
552
552
  />
553
553
  </div>
554
- <div class=${N.section} style="margin-bottom:16px;">
554
+ <div class=${G.section} style="margin-bottom:16px;">
555
555
  ${this.renderSectionTitle("位置",e.theme)}
556
- <div class=${N.row} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:12px;">
556
+ <div class=${G.row} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:12px;">
557
557
  ${this.renderLabeledNumberInput(e,"X",i.x,a=>e.callbacks.onTextStyleChange("x",a),"0.01","0","1")}
558
558
  ${this.renderLabeledNumberInput(e,"Y",i.y,a=>e.callbacks.onTextStyleChange("y",a),"0.01","0","1")}
559
559
  </div>
560
560
  </div>
561
- <div class=${N.section}>
561
+ <div class=${G.section}>
562
562
  ${this.renderSectionTitle("旋转",e.theme)}
563
- <div class=${N.row} style="max-width:220px;">
563
+ <div class=${G.row} style="max-width:220px;">
564
564
  ${this.renderLabeledNumberInput(e,"角度",r.rotation,a=>e.callbacks.onTextStyleChange("rotation",a),"1")}
565
565
  </div>
566
566
  </div>
567
567
  </div>
568
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`
569
- <div class=${N.voicePanel} style=${o}>
570
- <div class=${N.section} style=${n?"flex-shrink:0;margin-bottom:12px;":"margin-bottom:16px;"}>
571
- <div class=${N.filterGroup} style="display:flex;gap:8px;flex-wrap:wrap;">
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;">
572
572
  ${i.map(l=>this.renderFilterButton(e,l.key,l.label,e.activeVoiceFilterTag===l.key,()=>e.callbacks.onVoiceFilterChange(l.key)))}
573
573
  </div>
574
574
  </div>
575
575
  <div
576
- class=${N.section}
576
+ class=${G.section}
577
577
  style=${n?"flex:1;min-height:0;overflow-y:auto;":""}
578
578
  >
579
- <div class=${N.voiceCardGrid} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px;">
579
+ <div class=${G.voiceCardGrid} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px;">
580
580
  ${r.map((l,c)=>this.renderVoiceCard(e,l,c))}
581
581
  </div>
582
582
  ${r.length===0?j`
@@ -586,8 +586,8 @@ js: import "konva/skia-backend";
586
586
  `:null}
587
587
  ${e.voiceErrorMessage?j`
588
588
  <div
589
- class=${N.errorText}
590
- style=${`padding-top:12px;font-size:12px;color:${I.accentDanger};`}
589
+ class=${G.errorText}
590
+ style=${`padding-top:12px;font-size:12px;color:${_.accentDanger};`}
591
591
  >
592
592
  ${e.voiceErrorMessage}
593
593
  </div>
@@ -596,8 +596,8 @@ js: import "konva/skia-backend";
596
596
  </div>
597
597
  `}renderFilterButton(e,t,i,r,n){return j`
598
598
  <button
599
- class=${N.filterButton}
600
- style=${["padding:6px 12px","border:none","border-radius:999px","cursor:pointer","font-size:12px",`background:${r?Pe.activeTabBackground:e.theme.buttonBackground}`,`color:${r?e.theme.buttonActiveText:e.theme.textColor}`].join(";")}
599
+ class=${G.filterButton}
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(";")}
601
601
  data-key=${t}
602
602
  @click=${n}
603
603
  >
@@ -605,54 +605,54 @@ js: import "konva/skia-backend";
605
605
  </button>
606
606
  `}renderVoiceCard(e,t,i){const r=e.selectedVoiceId===t.id,n=e.previewingVoiceId===t.id,a=t.avatar,o=i<2;return j`
607
607
  <button
608
- class=${[N.voiceCard,n?N.voiceCardPreviewing:""].filter(Boolean).join(" ")}
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?Pe.activeTabBackground:e.theme.buttonBackground}`,`color:${e.theme.textColor}`].join(";")}
608
+ class=${[G.voiceCard,n?G.voiceCardPreviewing:""].filter(Boolean).join(" ")}
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(";")}
610
610
  @click=${()=>e.callbacks.onVoiceSelect(t.id)}
611
611
  >
612
612
  ${a?j`
613
613
  <span
614
- class=${[N.voiceCardAvatarWrap,o?N.voiceCardAvatarWrapFirstRow:""].filter(Boolean).join(" ")}
614
+ class=${[G.voiceCardAvatarWrap,o?G.voiceCardAvatarWrapFirstRow:""].filter(Boolean).join(" ")}
615
615
  >
616
616
  <div
617
- class=${N.voiceCardAvatar}
618
- style=${["width:32px","height:32px","border-radius:8px","flex-shrink:0","display:flex","align-items:center","justify-content:center",`background:url(${a}) center / cover no-repeat`,`color:${I.white}`,"font-size:18px","font-weight:600"].join(";")}
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(${a}) center / cover no-repeat`,`color:${_.white}`,"font-size:18px","font-weight:600"].join(";")}
619
619
  >
620
620
  </div>
621
- <span class=${N.voiceCardAvatarMask} aria-hidden="true"></span>
621
+ <span class=${G.voiceCardAvatarMask} aria-hidden="true"></span>
622
622
  <span
623
- class=${N.voiceCardAvatarSpeaker}
623
+ class=${G.voiceCardAvatarSpeaker}
624
624
  aria-hidden="true"
625
625
  >
626
626
  <svg
627
627
  width="18"
628
628
  height="18"
629
629
  viewBox="0 0 24 24"
630
- fill=${I.white}
630
+ fill=${_.white}
631
631
  >
632
632
  <path
633
633
  d="M3 9v6h4l5 5V4L7 9H3zm13.5 3a4.5 4.5 0 0 0-2.5-4.03v8.05a4.5 4.5 0 0 0 2.5-4.02zM14 3.23v2.06a7 7 0 0 1 0 13.42v-2.06a5 5 0 0 0 0-9.3z"
634
634
  />
635
635
  </svg>
636
636
  </span>
637
- <span class=${N.voiceCardAvatarTooltip}>试听</span>
637
+ <span class=${G.voiceCardAvatarTooltip}>试听</span>
638
638
  </span>
639
639
  `:j`
640
640
  <div
641
- class=${N.voiceCardAvatar}
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(";")}
641
+ class=${G.voiceCardAvatar}
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:${_.white}`,"font-size:18px","font-weight:600"].join(";")}
643
643
  >
644
644
  ${t.name.slice(0,1)}
645
645
  </div>
646
646
  `}
647
- <div class=${N.voiceCardMeta} style="flex:1;min-width:0;">
647
+ <div class=${G.voiceCardMeta} style="flex:1;min-width:0;">
648
648
  <div
649
- class=${N.voiceCardTitle}
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(";")}
649
+ class=${G.voiceCardTitle}
650
+ style=${["display:flex","align-items:center","gap:6px","padding-right:24px","font-size:14px",`color:${_.white}`,"white-space:nowrap","overflow:hidden","text-overflow:ellipsis"].join(";")}
651
651
  >
652
652
  <span style="overflow:hidden;text-overflow:ellipsis;">${n?"试听中...":t.name}</span>
653
653
  </div>
654
654
  <div
655
- class=${N.voiceCardSubtitle}
655
+ class=${G.voiceCardSubtitle}
656
656
  style=${`padding-top: 2px;font-size:10px;color:${e.theme.labelColor};white-space:nowrap;overflow:hidden;text-overflow:ellipsis;`}
657
657
  >
658
658
  ${t.lang} · ${t.emotion}
@@ -660,20 +660,20 @@ js: import "konva/skia-backend";
660
660
  </div>
661
661
  ${r?j`
662
662
  <div
663
- class=${N.voiceCardCheck}
663
+ class=${G.voiceCardCheck}
664
664
  style="position:absolute;top:50%;right:8px;transform:translateY(-42%);"
665
665
  >
666
- ${e.selectedIconSvg?er(this.resizeSvg(e.selectedIconSvg,20)):"✓"}
666
+ ${e.selectedIconSvg?ir(this.resizeSvg(e.selectedIconSvg,20)):"✓"}
667
667
  </div>
668
668
  `:null}
669
669
  </button>
670
670
  `}renderPositionControl(e,t,i){const r=this.getTransform(e.clip),n=r.scale/2,a=-n,o=1+n;return j`
671
671
  <div
672
- class=${N.row}
672
+ class=${G.row}
673
673
  style="display:flex;align-items:center;gap:8px;margin-bottom:8px;"
674
674
  >
675
675
  <label
676
- class=${N.label}
676
+ class=${G.label}
677
677
  style=${`width:16px;font-size:13px;color:${e.theme.labelColor};`}
678
678
  >
679
679
  ${t}
@@ -683,12 +683,12 @@ js: import "konva/skia-backend";
683
683
  </div>
684
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`
685
685
  <div
686
- class=${N.presetGrid}
686
+ class=${G.presetGrid}
687
687
  style="display:grid;grid-template-columns:repeat(3, 1fr);gap:4px;"
688
688
  >
689
689
  ${t.map(i=>j`
690
690
  <button
691
- class=${N.presetButton}
691
+ class=${G.presetButton}
692
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(";")}
693
693
  @click=${()=>{const{x:r,y:n}=this.calculatePresetPosition(e.clip,i.x,i.y);e.callbacks.onPresetSelect(r,n)}}
694
694
  >
@@ -698,7 +698,7 @@ js: import "konva/skia-backend";
698
698
  </div>
699
699
  `}renderSectionTitle(e,t){return j`
700
700
  <div
701
- class=${N.sectionTitle}
701
+ class=${G.sectionTitle}
702
702
  style=${`font-size:12px;color:${t.labelColor};margin-bottom:8px;text-transform:uppercase;`}
703
703
  >
704
704
  ${e}
@@ -706,7 +706,7 @@ js: import "konva/skia-backend";
706
706
  `}renderRangeInput(e){return j`
707
707
  <input
708
708
  type="range"
709
- class=${N.slider}
709
+ class=${G.slider}
710
710
  min=${e.min}
711
711
  max=${e.max}
712
712
  step=${e.step}
@@ -717,7 +717,7 @@ js: import "konva/skia-backend";
717
717
  `}renderNumberInput(e,t){return j`
718
718
  <input
719
719
  type="number"
720
- class=${N.input}
720
+ class=${G.input}
721
721
  min=${t.min}
722
722
  max=${t.max}
723
723
  step=${t.step}
@@ -730,4 +730,4 @@ js: import "konva/skia-backend";
730
730
  <span style=${`min-width:18px;font-size:13px;color:${e.theme.labelColor};`}>${t}</span>
731
731
  ${this.renderNumberInput(e.theme,{min:a,max:o,step:n,value:String(i),onChange:r})}
732
732
  </label>
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:${Pe.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(";")}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,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}"`):""}static createColorInputHandler(e){return t=>{const i=t.target.value;cancelAnimationFrame(Pt.colorRafId),Pt.colorRafId=requestAnimationFrame(()=>{e.callbacks.onTextStyleChange("color",i)})}}};p(Pt,"colorRafId",0);let Qr=Pt;const bd={...fe};function Ts(s){return s?{primaryClip:s,selectedClips:[s],selectionCount:1,groupKind:s.type,supportsVoiceBatch:s.type==="text"||Le(s),supportsTextContentBatch:s.type==="text",supportsVisualBatch:s.type==="video",supportsVolumeBatch:s.type==="video"||s.type==="audio"}:{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1}}function Td(s,e){return s.groupKind!==e.groupKind||s.selectionCount!==e.selectionCount||s.supportsVoiceBatch!==e.supportsVoiceBatch||s.supportsTextContentBatch!==e.supportsTextContentBatch||s.supportsVisualBatch!==e.supportsVisualBatch||s.supportsVolumeBatch!==e.supportsVolumeBatch||s.selectedClips.length!==e.selectedClips.length?!1:s.selectedClips.every((t,i)=>{var r;return t.id===((r=e.selectedClips[i])==null?void 0:r.id)})}class no{constructor(e){p(this,"container");p(this,"theme");p(this,"renderer",new Qr);p(this,"onClipUpdate");p(this,"onGenerateVoice");p(this,"voiceCatalog");p(this,"currentClip",null);p(this,"selectionState",Ts(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??bd,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(Ts(e))}setSelectionState(e){var l,c,h,d,u,g;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,a=r!==n,o=!Td(i,t);a&&this.stopVoicePreview(!1),this.selectionState=t,this.currentClip=t.primaryClip,a||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??"":((g=this.currentClip)==null?void 0:g.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}showVoiceGenerationLoading(){this.setVoiceGenerationBusy(!0)}hideVoiceGenerationLoading(){this.setVoiceGenerationBusy(!1)}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.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={...De(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(ai.MIN,Math.min(ai.MAX,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 wd(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class ws{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:`${wd(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 f;const o=this.resolveTrackTargetByY(t,r,n,e.type);if(o.status==="create_track")return{status:"create_track",trackType:e.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const c=a.find(y=>this.resolveTrackId(y)===l);if(!c)return{status:"missing_target_track_view",targetTrackId:l};const h=this.resolveTrackType(c)??((f=n.find(y=>y.id===l))==null?void 0:f.type)??null;if(h!==e.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:h};if(!this.hasOverlapOnTrack(e,c))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(e.type,l,t,r,n);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=n.filter(y=>y.type===e.type).map(y=>y.id),g=u.indexOf(l);for(let y=1;y<=u.length;y+=1){const v=g-y;if(v>=0){const S=u[v],C=a.find(w=>this.resolveTrackId(w)===S);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:S}}const b=g+y;if(b<u.length){const S=u[b],C=a.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,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(Me.MIN,Math.min(Me.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=Ae(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,g=Ae(d.type),f=u+g;return a=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:g}}).filter(d=>d.type===e),l=o.findIndex(d=>d.id===t);if(l===-1)return null;const c=o[l],h=Math.min(12,Math.max(6,Math.floor(c.height/4)));return c.role==="primary"?{insertionPlacement:e==="text"||e==="video"?"before_track":"after_track",referenceTrackId:t}:l<o.length-1&&i>=c.endY-h?{insertionPlacement:"after_track",referenceTrackId:t}:{insertionPlacement:"before_track",referenceTrackId:t}}hasOverlapOnTrack(e,t){const i=e.startTime+e.duration;return t.getClips().some(r=>r.id===e.id?!1:e.startTime<r.endTime&&i>r.startTime)}}class en{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,t=null,i=null,r=null){return{type:"add_clip",data:{clip:e,targetTrackId:t,targetTrackSnapshot:i,targetTrackRestoreAnchor:r},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 ks{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(this.normalizeAddClipActionData(e.data).clip.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:B.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:e.type})}}executeRedoInternal(e,t){var i,r;switch(e.type){case"add_clip":{const n=this.normalizeAddClipActionData(e.data);let a=!1;const o=this.resolveTrackIdForHistorySnapshot(n.targetTrackSnapshot,n.targetTrackId,t,n.targetTrackRestoreAnchor);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"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:B.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}}normalizeAddClipActionData(e){return"clip"in e?e:{clip:e,targetTrackId:null,targetTrackSnapshot:null,targetTrackRestoreAnchor: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 kd=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],Pd=new Set(["thumbnails"]);function xd(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 Ps{constructor(e){p(this,"transactionStack",[]);this.history=e}createAddClipAction(e,t=null,i=null,r=null){return this.history.createAddClipAction(e,t,i,r)}recordAddClip(e,t=null,i=null,r=null){const n=this.history.createAddClipAction(e,t,i,r);return this.recordAction(n),n}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,a,o){const l=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,a,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(kd.forEach(d=>{xd(e[d],t[d])||(r[d]=e[d],n[d]=t[d])}),Object.keys(r).length===0)return null;const a=Object.keys(r);if(a.every(d=>Pd.has(d)))return null;const o=new Set(["startTime","endTime"]);if(a.includes("startTime")&&a.every(d=>o.has(d)))return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);const c=new Set(["duration","startTime","endTime"]);return a.includes("duration")&&a.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 Di(s){var e;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function _d(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 Ad(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 Kt(s){return s.length===0?0:Math.max(...s.map(e=>e.endTime))}function Id(s,e){return e<Kt(s)}function Ed(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 Rd(s){const e=!s.id&&s.startTime>0;return{shouldJumpToTime:e,jumpTime:e?s.startTime:null,shouldSelectClip:!!s.id}}function zi(s){var e;return s.applied?(s.isExecutingHistoryAction||(e=s.recordHistory)==null||e.call(s),s.applyEffects(),!0):!1}function Md(s){return zi({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 Dd(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 Ld={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function Od(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 Bd(s){const e=Od(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=Ld[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,"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=vi.background,this.container.style.color=vi.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("button");i.className="timeline-preview-pending-overlay__action",i.style.display="none",i.style.padding="6px 12px",i.style.border="0",i.style.borderRadius="6px",i.style.cursor="pointer",i.style.background=vi.actionBackground,i.style.color=vi.actionText,i.textContent="刷新重试",i.addEventListener("click",this.onRetry),this.container.appendChild(t),this.container.appendChild(i),this.statusElement=t,this.actionElement=i}update(e){if(!this.container||!this.statusElement||!this.actionElement)return;const{pendingState:t,runtimeState:i}=e,r=(t==null?void 0:t.loading)??i.loading;if(!t&&r.status!=="loading"){this.container.style.display="none",this.actionElement.style.display="none";return}if(this.container.style.display="inline-flex",t!=null&&t.errorMessage||i.phase==="failed"){this.statusElement.textContent="资源加载异常",this.actionElement.style.display="inline-flex";return}this.statusElement.textContent=this.resolveLoadingStatusText(r.reason),this.actionElement.style.display="none"}resolveLoadingStatusText(e){switch(e){case"syncing":case"resolving-source":return"资源加载中...";case"seeking":return"正在定位预览...";case"media-pending":return"等待资源加载...";case"failed":return"资源加载异常";default:return"资源加载中..."}}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.actionElement=null}}const Tr={x:.5,y:.5,scale:1},Gd=.1,Nd=8;function wr(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Hd(s){return Math.min(Nd,Math.max(Gd,s))}function ke(s){return{x:wr(s==null?void 0:s.x,Tr.x),y:wr(s==null?void 0:s.y,Tr.y),scale:Hd(wr(s==null?void 0:s.scale,Tr.scale))}}function vn(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 so(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 xs(s,e,t){const i=so(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 ao(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 $d(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 _s(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}class zd{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,n,a;const t=e;(t.button??0)!==0||!this.state||((i=t.preventDefault)==null||i.call(t),(r=t.stopPropagation)==null||r.call(t),this.state.clipType==="text"&&((a=(n=this.callbacks).onTextTransformInteractionStart)==null||a.call(n)),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 ${ot.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 ${ot.border}`,e.style.background=ot.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=ot.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,c,h;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),this.state.clipType==="text"&&((h=(c=this.callbacks).onTextTransformInteractionStart)==null||h.call(c));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 ${ot.border}`,i.style.background=ot.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,d,u;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=this.state.clipType==="text";r&&((u=(d=this.callbacks).onTextTransformInteractionStart)==null||u.call(d));const n=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize",a=r?this.state.displayRect.left+this.state.displayRect.width/2:void 0,o=r?this.state.displayRect.top+this.state.displayRect.height/2:void 0,l=r?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:n,clipType:this.state.clipType??"video",startFontSize:r?this.state.currentFontSize:void 0,nextFontSize:r?this.state.currentFontSize:void 0,centerX:a,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor(n),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,g=i.y-this.interaction.centerY,y=Math.atan2(g,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=(a=this.callbacks).onRotationChange)==null||o.call(a,this.interaction.clipId,v);return}if(this.interaction.clipType==="text"&&this.interaction.startFontSize!==void 0){const u=i.x-this.interaction.centerX,g=i.y-this.interaction.centerY,f=Math.sqrt(u*u+g*g),y=(this.interaction.startCenterDistance??0)>0?f/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=ao(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,g=this.interaction.startTransform.y*this.interaction.frameSize.height;r=$d(u,g,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!vn(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,g,f;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)),(f=(g=this.callbacks).onPreviewTransformChange)==null||f.call(g,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:_s(this.frameElement.style.left),top:_s(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||"")}}function Vd(s,e){var u;const t=s.activeClips.filter(g=>g.trackType!=="text"),i=s.nextClips.filter(g=>g.trackType!=="text"),r=s.interactionMode??"steady",n=new Map(t.map(g=>[g.trackId,g])),a=new Map(i.map(g=>[g.trackId,g])),o=new Map,l=t.filter(g=>g.trackType==="video"&&g.hasVisual).sort((g,f)=>g.trackOrder-f.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(g,f)=>!a.has(g)||r!=="steady"&&c?!1:c?s.playState==="playing"&&f==="video"&&g===h:s.playState!=="playing"||t.length<=1;return e.forEach(g=>{o.set(g.trackId,{kind:g.kind,order:g.order})}),t.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),i.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),Array.from(o.entries()).map(([g,f])=>{const y=n.get(g)||null,v=d(g,f.kind)&&a.get(g)||null;return{trackId:g,kind:f.kind,order:f.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:v,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:s.syncRequestId}}}).sort((g,f)=>g.order-f.order)}function tn(s,e){return s.entry?e?s.entry.clip.id===e:!0:!1}function Ud(s,e){return e?!tn(s.current,e.clip.id)&&tn(s.preload,e.clip.id):!1}function Wd(s){return s.current.role="preload",s.preload.role="current",{current:s.preload,preload:s.current}}function Yd(s){return`${s.trackId}:${s.role}`}function Xd(s,e){return s.role!=="preload"||!tn(s)?null:{role:"preload",entry:s.entry,playState:s.requestedPlayState,speed:1,visible:!1,zIndex:0,syncRequestId:e}}function qd(s,e){const t=e.lastIndexOf(":");if(t<=0)return null;const i=e.slice(0,t),r=e.slice(t+1);if(r!=="current"&&r!=="preload")return null;const n=s.get(i);return n?r==="current"?n.current:n.preload:null}function jd(s,e,t,i){const r=e||s.clip.src||"";switch(t){case"abort":case"emptied":return`${s.clip.id}:${r}:${t}`;case"error":case"reconcile":case"stalled":return`${s.clip.id}:${r}:${Math.floor(s.mediaTime/i)}`;default:return`${s.clip.id}:${r}`}}function Kd(s){if(!s.desiredSource||!s.stableSourceUrl||!s.currentSourceKey||s.currentSourceKey!==s.nextSourceKey)return null;const e=s.objectUrl??(s.desiredSource.startsWith("blob:")?s.desiredSource:null);return{stableSourceUrl:s.stableSourceUrl,url:s.desiredSource,objectUrl:e}}function Zd(s,e,t){return t?s===t||e===t:!1}function Jd(s){const e=s.configuredSource||null,t=e||s.assignedSource||null;let i=!1,r=null;return s.forceRecover?(i=!0,r="force-recover"):e?t!==s.desiredSource?(i=!0,r="source-mismatch"):s.networkState===s.networkEmptyState&&((s.readyState??0)>=s.haveCurrentDataState?(i=!1,r="network-empty-but-current-data-ready"):(i=!(s.isLoading||s.phase==="binding"||s.phase==="recovering"),r=i?"network-empty":"network-empty-binding-in-flight")):(i=!0,r="missing-src-attribute"),{needsRecovery:i,recoveryReason:r,actualSource:t,configuredSource:e,shouldWarn:i&&(r==="source-mismatch"||s.isActive&&s.phase!=="idle"&&s.phase!=="binding")}}function Qd(s,e){const t=s==="current"?Math.abs(e):1;return Math.max(.1,t*.15)}function eu(s,e,t){return!!s||e!=="reconcile"||t>1}function tu(s){return{role:s.role,entry:s.entry,playState:s.requestedPlayState,speed:s.isActive&&s.playbackRate||1,visible:s.isActive&&!!s.entry.hasVisual,zIndex:1e3-s.entry.trackOrder,syncRequestId:s.syncRequestId}}function iu(s){const e=jd(s.entry,s.desiredSource,s.reason,s.recoveryTimeBucketMs);return s.previousRecoveryKey===e?s.previousRetryCount>=s.maxImmediateRecoveryRetries?s.isBackgroundPreload?{status:"park",message:"媒体恢复失败,请等待下一次重建",parkReason:"retries-exhausted"}:{status:"fail",message:"媒体恢复失败,请刷新重试"}:{status:"continue",recoveryKey:e,retryCount:s.previousRetryCount+1}:{status:"continue",recoveryKey:e,retryCount:1}}function oo(s,e){s.phase="idle",s.errorMessage=null,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,Cn(s,e)}function Cn(s,e=!1){s.forceRecover=e,s.retryCount=0,s.recoveryKey=null,s.expectedEmptiedEvents=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}function ru(s){oo(s,!1)}function nu(s){oo(s,!0)}function su(s){s.phase==="binding"&&(s.phase=s.isActive?"active":"primed"),s.isResolvingSource=!1,s.isLoading=!1,s.isBuffering=!1,s.errorMessage=null}function au(s){!s.isLoading&&!s.isSeeking&&s.phase!=="failed"&&(s.phase=s.isActive?"active":"primed")}function ou(s,e){s.forceRecover=!0,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=null,e||(s.phase="idle")}function lu(s,e){const t=!!s.isSeeking&&!e.withinSeekThreshold,i=s.phase==="failed",r=s.isResolvingSource,n=!i&&!r&&e.hasDesiredSource&&e.sourceMatched&&!t&&e.readyState>=e.haveCurrentDataState,a=!n&&!i&&(!e.hasDesiredSource||!e.sourceMatched||s.phase==="binding"||s.phase==="recovering"||e.readyState<e.haveCurrentDataState);return s.isSeeking=t,n?(Cn(s),s.isLoading=!1,s.isBuffering=!1,s.errorMessage=null,s.phase!=="failed"&&(s.phase="active")):!i&&s.phase!=="recovering"&&s.phase!=="binding"&&(s.phase=s.isActive?"active":"primed"),{failed:i,resolving:r,seeking:t,mediaUnready:a,ready:n}}function cu(s,e){s.phase="failed",s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=e,s.forceRecover=!1,s.expectedEmptiedEvents=0}function hu(s){s.isActive=!1,s.isBuffering=!1,s.isSeeking=!1}function du(s,e){s.phase="recovering",s.errorMessage=null,s.forceRecover=!1,s.isLoading=!0,s.isResolvingSource=!1,s.isBuffering=s.isActive&&e==="playing",s.isSeeking=!1,s.consecutiveStalledCount=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}const uu=0,at=2,pu=3,gu=2,fu=250,mu=250,yu=100,Su=500,vu=700,As=.03,Cu=.5,bu=750,Is="Arial, sans-serif";function Tu(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 lo(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function kr(s){return`"${lo(s)}"`}function wu(s){return ln(s,an)}function ku(s,e){return!xt(s.mode)||!e?s:{mode:Oe.mode,width:e.width,height:e.height}}function xe(s){return s.getAttribute("src")||s.currentSrc||s.src||""}function tr(s){return s.getAttribute("src")||""}function Fe(s,e){const t=tr(s),i=s.currentSrc||"",r=s.src||"",n=xe(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 ir(s){return typeof HTMLVideoElement<"u"?s instanceof HTMLVideoElement:s.tagName==="VIDEO"}function We(s){try{s.load()}catch{}}function Ge(s){try{s.pause()}catch{}}function Pr(s){var e;try{const t=s.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function Es(s,e){try{s.currentTime=Math.max(0,e)}catch{}}function Li(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 Rs(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}function rn(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function Pu(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 ee(s){return{tsMs:rn(),currentTime:Number.isFinite(s.currentTime)?Number(s.currentTime.toFixed(3)):null,duration:Number.isFinite(s.duration)?Number(s.duration.toFixed(3)):null,currentSrc:xe(s)||null,srcAttribute:tr(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:Pu(s),videoWidth:ir(s)?s.videoWidth:null,videoHeight:ir(s)?s.videoHeight:null,error:s.error?{code:typeof s.error.code=="number"?s.error.code:null,message:s.error.message??null}:null}}function Ne(s){return typeof(s==null?void 0:s.then)=="function"}class xu{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,"loadingProbeTimeoutId",null);p(this,"clockProbeTimeoutId",null);p(this,"playbackGroupSuspended",!1);p(this,"lastRuntimeSignature",null);p(this,"lastRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},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",{...Oe});p(this,"resolvedAutoAspectRatio",null);p(this,"aspectRatioProbe",null);p(this,"aspectRatioProbeSrc",null);p(this,"aspectRatioProbeResolveToken",0);p(this,"pendingState",null);p(this,"activeSyncRequestId");p(this,"isSyncProjecting",!1);p(this,"deferredPreloadSlotKeys",new Set);p(this,"deferredPreloadFlushScheduled",!1);p(this,"lastSyncedPlayState","paused");p(this,"pendingClockAlignmentTargetTime",null);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 zd({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=`${De(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)},onTextTransformInteractionStart:()=>{this.requestPauseIfPlaying()}})}requestPauseIfPlaying(){var e,t;this.lastSyncedPlayState==="playing"&&((t=(e=this.callbacks).onPauseIfPlaying)==null||t.call(e))}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:Va(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:xe(e.element)||null,extra:{role:e.role,kind:e.kind,phase:e.phase,retryCount:e.retryCount,sourceState:Fe(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&&(Ge(this.aspectRatioProbe),this.aspectRatioProbe.src="",We(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.aspectRatioProbeResolveToken+=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.clearLoadingProbe(),this.clearClockProbe(),this.playbackGroupSuspended=!1,this.lastRuntimeSignature=null,this.lastSettledSyncRequestId=null,this.pendingClockAlignmentTargetTime=null,this.lastRuntimeState={phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},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.lastSyncedPlayState=e.playState,this.updatePendingClockAlignmentTarget(e),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=Vd(e,t).map(o=>this.applyTrackPlan(o)).filter(o=>Ne(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}),B.warn("TimelinePreviewSession","preview sync failed",{error:o,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=je(e),this.updateFrameLayout()}getAspectRatio(){return ku(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,ir(r)?(Mr(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 w,x;const r=this.createMediaElement(t,i),n=t==="video"?document.createElement("div"):null;if(n){const k=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";n.className=`${k} 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),(w=this.frameElement)==null||w.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,isResolvingSource:!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,hasReadyEventSinceSourceChange:!1,hasBufferingSignalSinceSourceChange:!1,lastPlaybackResumeAttemptAtMs:-1,lastPlaybackProgressCheckAtMs:-1,lastPlaybackProgressMediaTimeSeconds:Number.NaN,playbackProgressStalled:!1,resolveToken:0,applyToken:0,cleanup:[]},o=k=>{var D;if(!this.shouldIgnoreClearedSlotRecoverableEvent(a)){if(k==="abort"&&this.shouldIgnoreExpectedAbort(a)){this.emitDiagnostic("debug","playback","media.abort.ignored",this.buildSlotTraceData(a,{message:"Ignored expected media abort during source reset",mediaState:ee(a.element)}));return}if(k==="emptied"&&this.shouldIgnoreExpectedEmptied(a)){this.emitDiagnostic("debug","playback","media.emptied.ignored",this.buildSlotTraceData(a,{message:"Ignored expected media emptied during source reset",mediaState:ee(a.element)}));return}if(this.emitDiagnostic(k==="error"?"error":"warn","playback",`media.${k}`,this.buildSlotTraceData(a,{message:`Media event: ${k}`,mediaState:ee(a.element),error:a.element.error})),k==="error"&&B.error("TimelinePreviewSession",`media event: ${k}`,{trackId:a.trackId,role:a.role,clipId:((D=a.entry)==null?void 0:D.clip.id)??null,phase:a.phase,mediaState:ee(a.element)}),a.forceRecover=!0,a.expectedEmptiedEvents=0,a.isLoading=!1,a.isResolvingSource=!1,a.isSeeking=!1,a.isBuffering=!1,a.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(a),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:ee(a.element),extra:{reason:k,recoverableEventCount:a.recoverableEventCount,loadStartedSinceRecover:a.loadStartedSinceRecover}})),this.refreshRuntimeState();return}if(this.refreshRuntimeState(),this.shouldDeferPreloadRecovery(a)){this.deferPreloadRecovery(a,k);return}this.recoverSlot(a,k)}},l=()=>o("abort"),c=()=>o("emptied"),h=()=>o("error"),d=()=>{a.loadStartedSinceRecover=!0,a.isLoading=!0,a.hasReadyEventSinceSourceChange=!1,a.hasBufferingSignalSinceSourceChange=!1,a.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(a),this.emitDiagnostic("debug","playback","media.loadstart",this.buildSlotTraceData(a,{message:"Media event: loadstart",mediaState:ee(a.element)})),this.refreshRuntimeState()},u=()=>{a.hasReadyEventSinceSourceChange=!0,a.isBuffering=!1,a.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(a),this.maybeResumeRequestedPlayback(a,"canplay"),this.emitDiagnostic("debug","playback","media.canplay",this.buildSlotTraceData(a,{message:"Media event: canplay",mediaState:ee(a.element)})),this.refreshRuntimeState()},g=()=>{a.hasReadyEventSinceSourceChange=!0,a.isBuffering=!1,a.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(a),this.emitDiagnostic("debug","playback","media.playing",this.buildSlotTraceData(a,{message:"Media event: playing",mediaState:ee(a.element)})),this.refreshRuntimeState()},f=()=>{this.refreshRuntimeState()},y=()=>{this.emitDiagnostic("debug","playback","media.pause",this.buildSlotTraceData(a,{message:"Media event: pause",mediaState:ee(a.element)})),this.refreshRuntimeState()},v=()=>{a.isBuffering=a.role==="current"&&a.isActive&&a.requestedPlayState==="playing",a.hasBufferingSignalSinceSourceChange=a.isBuffering,this.emitDiagnostic("warn","playback","media.stalled",this.buildSlotTraceData(a,{message:"Media event: stalled",mediaState:ee(a.element)})),this.refreshRuntimeState()},b=()=>{a.isBuffering=a.role==="current"&&a.isActive&&a.requestedPlayState==="playing",a.hasBufferingSignalSinceSourceChange=a.isBuffering,this.emitDiagnostic("warn","playback","media.waiting",this.buildSlotTraceData(a,{message:"Media event: waiting",mediaState:ee(a.element)})),this.refreshRuntimeState()},S=()=>{a.isSeeking=!0,this.refreshRuntimeState()},C=()=>{a.isSeeking=!1,a.hasReadyEventSinceSourceChange=!0,a.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(a),this.maybeResumeRequestedPlayback(a,"seeked"),this.refreshRuntimeState()};return r.addEventListener("loadstart",d),r.addEventListener("canplay",u),r.addEventListener("playing",g),r.addEventListener("progress",f),r.addEventListener("pause",y),r.addEventListener("stalled",v),r.addEventListener("waiting",b),r.addEventListener("seeking",S),r.addEventListener("seeked",C),r.addEventListener("abort",l),r.addEventListener("emptied",c),r.addEventListener("error",h),a.cleanup.push(()=>r.removeEventListener("loadstart",d),()=>r.removeEventListener("canplay",u),()=>r.removeEventListener("playing",g),()=>r.removeEventListener("progress",f),()=>r.removeEventListener("pause",y),()=>r.removeEventListener("stalled",v),()=>r.removeEventListener("waiting",b),()=>r.removeEventListener("seeking",S),()=>r.removeEventListener("seeked",C),()=>r.removeEventListener("abort",l),()=>r.removeEventListener("emptied",c),()=>r.removeEventListener("error",h)),t==="audio"&&((x=this.rootElement)==null||x.appendChild(r)),a}resetSlotRecoveryTracking(e,t=!1){Cn(e,t)}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()),Ge(e.element),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.stableSourceUrl=null,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),e.element.removeAttribute("src"),We(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,e.isResolvingSource=!1}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&&this.trackSlots.set(e,Wd(t))}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);Ud(t,e.current.entry)&&(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(Ne(i)||Ne(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=xe(e.element)||null,a=r?this.buildPreviewSourceCacheKey(r.clip):null,o=t.entry?this.buildPreviewSourceCacheKey(t.entry.clip):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}})),Ge(e.element),e.stableSourceUrl=null,e.desiredSource=null,e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e),ru(e),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.element.removeAttribute("src"),We(e.element),this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}a&&o&&a!==o&&(this.releaseSlotObjectUrl(e),e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e));const l=this.resolveDesiredSource(e,t.entry,i,a);if(Ne(l))return l.then(c=>{if(!c||!this.isCurrentSourceTarget(e,t.entry,c.stableSourceUrl)){this.revokeResolvedObjectUrl(c);return}const h=this.buildCurrentTargetForSlot(e)??t;if(!h.entry){this.revokeResolvedObjectUrl(c);return}if(e.stableSourceUrl=c.stableSourceUrl,e.desiredSource=c.url,this.configureAudioRouting(e,h.entry),this.slotNeedsRecovery(e,c.url)){if(this.shouldDeferPreloadTarget(e,h,c.url)){this.deferPreloadTarget(e,h,c,"current-loading");return}return Promise.resolve(this.recoverSlot(e,"reconcile",h,void 0,c)).then(()=>{})}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,c.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,h)});if(!l||!this.isCurrentRequest(e,i,t.entry)){this.revokeResolvedObjectUrl(l);return}if(e.stableSourceUrl=l.stableSourceUrl,e.desiredSource=l.url,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,l.url)){if(this.shouldDeferPreloadTarget(e,t,l.url)){this.deferPreloadTarget(e,t,l,"current-loading");return}return this.recoverSlot(e,"reconcile",t,i,l)}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,l.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,t)}settleResolvedSourceWithoutRecovery(e){su(e)}resolveDesiredSource(e,t,i,r){const n=this.getReusableBoundSlotSource(e,t,r);if(n)return n;const a=this.dependencies.previewSourceResolver??Bd,o=this.dependencies.sourceMediaRegistry;let l=null;const c=()=>(l!==null||(e.resolveToken+=1,l=e.resolveToken,e.phase="binding",e.isResolvingSource=!0,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:l}})),this.refreshRuntimeState()),l);if(!a){const h={url:t.clip.src};return this.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),l)}try{const h=o?o.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>a(t.clip)):a(t.clip);if(Ne(h)){const d=c();return h.then(u=>d!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:u?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:u.url,extra:{mimeType:u.mimeType,mediaKind:u.kind}})),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,u),d)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(u=>(this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:u})),B.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:u}),this.failSlot(e,t,"预览源解析失败"),null))}return 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.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),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(h){return this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:h})),B.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:h}),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,sizeBytes: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,sizeBytes: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,sizeBytes:d.sizeBytes??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(Ne(c)){e.isResolvingSource=!0,e.isLoading=!0,e.phase="binding",this.refreshRuntimeState();const d=c.then(h).catch(()=>a()?null:l());return d.finally(()=>{e.pendingRuntimeSourcePromise===d&&(this.clearPendingRuntimeSource(e),this.refreshRuntimeState())}).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:xe(e.element)||null,mediaState:ee(e.element),extra:{stableSourceUrl:t,runtimeSourceUrl:(i==null?void 0:i.url)??null,objectUrl:(i==null?void 0:i.objectUrl)??null,sourceState:Fe(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,sizeBytes:null}}getReusableBoundSlotSource(e,t,i){const r=i??(e.entry?this.buildPreviewSourceCacheKey(e.entry.clip):null);if(!r)return null;const n=Kd({currentSourceKey:r,nextSourceKey:this.buildPreviewSourceCacheKey(t.clip),desiredSource:e.desiredSource,stableSourceUrl:e.stableSourceUrl,objectUrl:e.objectUrl});return n?{...n,sizeBytes:null}:null}slotNeedsRecovery(e,t){const i=Jd({desiredSource:t,configuredSource:tr(e.element)||null,assignedSource:xe(e.element)||null,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,phase:e.phase,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,networkEmptyState:uu,haveCurrentDataState:at});return this.emitDiagnostic(i.shouldWarn?"warn":"debug","recovery","slot.recovery-check",this.buildSlotTraceData(e,{message:i.needsRecovery?"Preview slot needs recovery":"Preview slot source is reusable",desiredSourceUrl:t,actualSourceUrl:i.actualSource,mediaState:ee(e.element),extra:{needsRecovery:i.needsRecovery,recoveryReason:i.recoveryReason,configuredSource:i.configuredSource,actualSource:i.actualSource,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:Fe(e.element,t)}})),i.needsRecovery}recoverSlot(e,t,i,r,n){const a=i??(e.entry?{...tu({role:e.role,entry:e.entry,requestedPlayState:e.requestedPlayState,isActive:e.isActive,playbackRate:e.element.playbackRate||1,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,sizeBytes:null}:this.resolveDesiredSource(e,e.entry,e.applyToken));if(Ne(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=iu({entry:e.entry,desiredSource:o,reason:t,previousRecoveryKey:e.recoveryKey,previousRetryCount:e.retryCount,maxImmediateRecoveryRetries:gu,recoveryTimeBucketMs:fu,isBackgroundPreload:this.isBackgroundPreloadSlot(e)});if(l.status==="park"){this.parkPreloadSlot(e,l.message,l.parkReason);return}if(l.status==="fail"){this.failSlot(e,e.entry,l.message);return}e.recoveryKey=l.recoveryKey,e.retryCount=l.retryCount,du(e,i.playState),this.refreshRuntimeState(),this.emitDiagnostic(t==="reconcile"?"info":"warn","recovery","slot.recover",this.buildSlotTraceData(e,{message:"Recovering preview slot",desiredSourceUrl:o,mediaState:ee(e.element),extra:{reason:t,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState}})),e.retryCount>1&&B.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:o,mediaState:ee(e.element)});const c=xe(e.element),h=Fe(e.element,o),d=eu(c||null,t,e.retryCount);Ge(e.element),e.expectedEmptiedEvents=d?2:1,e.stableSourceUrl=a.stableSourceUrl,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),this.rememberSlotObjectUrl(e,a.objectUrl),d&&(e.element.removeAttribute("src"),We(e.element)),e.element.setAttribute("src",o),We(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:Fe(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 Yd(e)}isActiveCurrentSlot(e){return e.role==="current"&&e.isActive&&!!e.entry}isTrackedActiveCurrentVideoSlot(e){return this.isActiveCurrentSlot(e)&&e.kind==="video"}hasBlockingActiveCurrentSlot(e){for(const{current:t}of this.trackSlots.values()){if(e&&this.getSlotKey(t)===e||!this.isTrackedActiveCurrentVideoSlot(t))continue;const i=this.evaluateTrackedCurrentVideoSlot(t);if(!i.ready&&!i.failed)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 Xd(e,this.activeSyncRequestId)}deferPreloadTarget(e,t,i,r){const n=i.url;e.desiredSource=n,this.rememberSlotObjectUrl(e,i.objectUrl),e.element.getAttribute("src")&&e.element.getAttribute("src")!==n&&(Ge(e.element),e.element.removeAttribute("src"),We(e.element)),xe(e.element)||(e.hasReadyEventSinceSourceChange=!1),ou(e,!!xe(e.element)),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=qd(this.trackSlots,t);if(!i||i.role!=="preload"||!i.entry)continue;const r=this.buildDeferredPreloadTarget(i);if(r){if(this.emitDiagnostic("info","recovery","preload.recovery.resumed",this.buildSlotTraceData(i,{message:"Resumed deferred preload recovery",desiredSourceUrl:i.desiredSource,extra:{requestedPlayState:i.requestedPlayState}})),i.desiredSource&&this.slotNeedsRecovery(i,i.desiredSource)){this.recoverSlot(i,"reconcile",r);continue}this.resetSlotRecoveryTracking(i),this.applyResolvedSlotState(i,r)}}}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),au(e),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){Ge(e.element),this.releaseSlotObjectUrl(e),e.element.removeAttribute("src"),We(e.element),e.hasReadyEventSinceSourceChange=!1,nu(e),this.emitDiagnostic("warn","recovery","preload.recovery.parked",this.buildSlotTraceData(e,{message:"Background preload parked until next steady sync",mediaState:ee(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}cu(e,i),this.emitDiagnostic("error","recovery","slot.failed",this.buildSlotTraceData(e,{message:"Preview slot failed",mediaState:ee(e.element),extra:{errorMessage:i}})),B.error("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,mediaState:ee(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(r==="playing"?Cu:.1,i*.15),o=r==="playing"&&!e.element.ended,l=this.doesSlotSourceMatchDesired(e,e.desiredSource),c=typeof e.element.readyState=="number"?e.element.readyState:0;if(this.updateSlotPlaybackProgressState(e,{shouldBePlaying:o,sourceMatched:l,readyState:c,speed:i}),!e.playbackProgressStalled&&Math.abs(e.element.currentTime-n)>a&&(this.emitDiagnostic("debug","playback","media.current-slot.seek",this.buildSlotTraceData(e,{message:"Current slot seek applied",mediaState:ee(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,Es(e.element,n)),r==="playing"){this.resumeAudioContext();const d=Fe(e.element,e.desiredSource);e.element.paused&&(this.emitDiagnostic(d.hasSrcAttribute?"debug":"warn","playback","media.play.requested",this.buildSlotTraceData(e,{message:d.hasSrcAttribute?"Media play requested":"Media play requested without configured src attribute",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:d}})),Pr(e.element))}else this.emitDiagnostic("debug","playback","media.pause.requested",this.buildSlotTraceData(e,{message:"Media pause requested",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:Fe(e.element,e.desiredSource)}})),Ge(e.element);this.setSlotVisible(e,t.hasVisual,1e3-t.trackOrder)}resetSlotPlaybackProgressProbe(e){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN,e.playbackProgressStalled=!1}updateSlotPlaybackProgressState(e,t){const i=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN;if(!(t.shouldBePlaying&&e.role==="current"&&e.isActive&&t.sourceMatched&&t.readyState>=at&&!e.element.paused&&!e.element.ended&&!e.isSeeking&&Number.isFinite(i))){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN;return}const n=rn(),a=e.lastPlaybackProgressMediaTimeSeconds,o=e.lastPlaybackProgressCheckAtMs;if(o<0||!Number.isFinite(a)){e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}const l=i-a;if(l>As||l<-As){e.playbackProgressStalled&&this.emitDiagnostic("info","playback","media.progress.recovered",this.buildSlotTraceData(e,{message:"Media playback progress recovered",mediaState:ee(e.element),extra:{previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3)),advancedSeconds:Number(l.toFixed(3))}})),e.playbackProgressStalled=!1,e.hasBufferingSignalSinceSourceChange||(e.isBuffering=!1),e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}n-o<vu||(e.playbackProgressStalled||this.emitDiagnostic("warn","playback","media.progress.stalled",this.buildSlotTraceData(e,{message:"Media playback progress stalled without waiting event",mediaState:ee(e.element),extra:{stalledForMs:n-o,speed:t.speed,previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3))}})),e.playbackProgressStalled=!0,e.isBuffering=!0)}maybeResumeRequestedPlayback(e,t){if(e.role!=="current"||!e.isActive||!e.entry||e.requestedPlayState!=="playing"||e.element.paused!==!0||this.playbackGroupSuspended)return;const i=Fe(e.element,e.desiredSource);if(!i.hasSrcAttribute)return;const r=rn();t==="runtime-check"&&(e.hasBufferingSignalSinceSourceChange||e.lastPlaybackResumeAttemptAtMs>=0&&r-e.lastPlaybackResumeAttemptAtMs<Su)||(e.lastPlaybackResumeAttemptAtMs=r,this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.play.retried",this.buildSlotTraceData(e,{message:"Retried media play after ready event",mediaState:ee(e.element),extra:{reason:t,playState:e.requestedPlayState,speed:e.element.playbackRate||1,sourceState:i}})),Pr(e.element))}preparePreloadSlot(e,t){hu(e),e.entry=t,e.element.playbackRate=1,e.hasReadyEventSinceSourceChange=!1,this.emitDiagnostic("debug","playback","media.preload-slot.seek",this.buildSlotTraceData(e,{message:"Preload slot primed",mediaState:ee(e.element),extra:{toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3))}})),Es(e.element,t.clip.startTimeAtSource/1e3),Ge(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(!xt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=Li(e,"sys_width"),i=Li(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.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,We(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(!Ne(n))return(n==null?void 0:n.url)??null;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");Mr(e);const t=()=>{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.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(!xt(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(),xt(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var y,v,b,S,C,w,x,k;const e=[];let t=null,i=!1,r=0,n=0,a=!1,o=!1,l=!1,c=!1;for(const{current:D,preload:P}of this.trackSlots.values())for(const A of[D,P]){const O=this.isTrackedActiveCurrentVideoSlot(A),$=O?this.evaluateTrackedCurrentVideoSlot(A):null,F=xe(A.element)||null;e.push({trackId:A.trackId,role:A.role,kind:A.kind,clipId:((y=A.entry)==null?void 0:y.clip.id)??null,desiredSource:A.desiredSource,actualSource:F,phase:A.phase,retryCount:A.retryCount,errorMessage:A.errorMessage}),A.phase!=="idle"&&(i=!0),O&&(r+=1,$!=null&&$.failed&&(n+=1,a=!0,t||(t=A.errorMessage||"资源加载异常,请刷新重试")),$!=null&&$.resolving&&(o=!0),$!=null&&$.seeking&&(l=!0),$!=null&&$.mediaUnready&&(c=!0))}const h=this.buildPreviewLoadingState({trackedActiveCurrentVideoSlotCount:r,failedTrackedCurrentVideoSlotCount:n,hasFailedTrackedVideoSlot:a,hasResolvingTrackedVideoSlot:o,hasSeekingTrackedVideoSlot:l,hasMediaUnreadyTrackedVideoSlot:c});this.syncActivePlaybackGroupSuspension(h,r);let d="idle";h.status==="failed"?d="failed":h.status==="loading"&&h.reason==="syncing"?d="awaiting-sync":h.status==="loading"?d="awaiting-media":(r>0&&h.status==="ready"||i)&&(d="ready"),h.status!=="failed"&&(t=null);const u={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:d,loading:h,clock:this.buildPreviewClockState(h),errorMessage:t,slots:e},g=this.lastRuntimeState,f=JSON.stringify(u);f!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=f,this.lastRuntimeState=u,(g.phase!==u.phase||g.loading.status!==u.loading.status||g.loading.reason!==u.loading.reason||g.loading.isLoading!==u.loading.isLoading||g.errorMessage!==u.errorMessage)&&this.emitDiagnostic(u.phase==="failed"?"error":"info","runtime","runtime.state",{message:"Preview runtime state updated",syncRequestId:u.syncRequestId??null,runtimeState:{runtimePhase:u.phase,loadingStatus:u.loading.status,loadingReason:u.loading.reason,isLoading:u.loading.isLoading,clockStatus:((v=u.clock)==null?void 0:v.status)??"unavailable",clockReason:((b=u.clock)==null?void 0:b.reason)??null,clockTimelineTime:((S=u.clock)==null?void 0:S.timelineTime)??null},extra:{previousPhase:g.phase,phase:u.phase,errorMessage:u.errorMessage,loading:u.loading,slots:u.slots.map(D=>({trackId:D.trackId,role:D.role,clipId:D.clipId,phase:D.phase,retryCount:D.retryCount,desiredSource:D.desiredSource,actualSource:D.actualSource}))}}),(w=(C=this.callbacks).onRuntimeStateChange)==null||w.call(C,u)),(h.status==="ready"||h.status==="failed"||h.status==="idle")&&u.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==u.syncRequestId&&(this.lastSettledSyncRequestId=u.syncRequestId,(k=(x=this.callbacks).onSyncProcessed)==null||k.call(x,u.syncRequestId)),h.status!=="loading"&&this.deferredPreloadSlotKeys.size>0&&this.scheduleDeferredPreloadFlush(),this.syncLoadingProbe(h),this.syncClockProbe(u.clock),this.refreshPendingOverlay()}buildPreviewClockState(e){const t=this.getPreviewClockSourceSlot();if(!(t!=null&&t.entry))return this.buildPreviewClockStateFromSlot(null,"unavailable","no-video-clock");const i=this.doesSlotSourceMatchDesired(t,t.desiredSource),r=this.getSlotMediaTimeMs(t),n=this.getSlotTimelineTime(t,r),a=t.requestedPlayState==="playing"&&!t.element.ended;return e.status==="failed"||t.phase==="failed"?this.buildPreviewClockStateFromSlot(t,"failed","failed",n,r):a?!i||t.isResolvingSource||t.phase==="binding"?this.buildPreviewClockStateFromSlot(t,"priming","resolving-source",n,r):t.isSeeking||e.reason==="seeking"?this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):t.isBuffering||t.playbackProgressStalled?this.buildPreviewClockStateFromSlot(t,"blocked","media-stalled",n,r):this.isPreviewClockSlotAlignedToPendingTarget(t,n)?e.status==="loading"?this.buildPreviewClockStateFromSlot(t,"blocked",this.resolveClockBlockedReason(e.reason),n,r):t.element.paused?this.buildPreviewClockStateFromSlot(t,"blocked","media-paused",n,r):n===null||r===null?this.buildPreviewClockStateFromSlot(t,"priming","media-pending",n,r):(this.pendingClockAlignmentTargetTime=null,this.buildPreviewClockStateFromSlot(t,"running",null,n,r)):this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):this.buildPreviewClockStateFromSlot(t,"unavailable",null,n,r)}buildPreviewClockStateFromSlot(e,t,i,r=null,n=null){var a;return{status:t,timelineTime:r,mediaTime:n,clipId:((a=e==null?void 0:e.entry)==null?void 0:a.clip.id)??null,trackId:(e==null?void 0:e.trackId)??null,reason:i}}resolveClockBlockedReason(e){return e==="syncing"||e==="resolving-source"||e==="seeking"||e==="media-pending"||e==="failed"?e:"media-pending"}getPreviewClockSourceSlot(){var t,i;const e=[];for(const{current:r}of this.trackSlots.values())this.isTrackedActiveCurrentVideoSlot(r)&&((t=r.entry)!=null&&t.hasVisual)&&e.push(this.buildPreviewClockSourceCandidate(r));return e.length===0?(this.pendingClockAlignmentTargetTime=null,null):(e.sort((r,n)=>this.comparePreviewClockSourceCandidates(r,n)),((i=e[0])==null?void 0:i.slot)??null)}buildPreviewClockSourceCandidate(e){const t=this.getSlotMediaTimeMs(e),i=this.getSlotTimelineTime(e,t),r=this.doesSlotSourceMatchDesired(e,e.desiredSource),n=typeof e.element.readyState=="number"?e.element.readyState:0,a=this.pendingClockAlignmentTargetTime===null||i===null?Number.POSITIVE_INFINITY:Math.abs(i-this.pendingClockAlignmentTargetTime),o=e.requestedPlayState==="playing"&&!e.element.ended,l=n>=at||e.hasReadyEventSinceSourceChange,c=!!e.entry&&r&&l&&!e.isResolvingSource&&e.phase!=="binding"&&e.phase!=="failed"&&!e.isSeeking&&!e.isBuffering&&!e.playbackProgressStalled&&(!o||!e.element.paused)&&t!==null&&i!==null;return{slot:e,timelineTime:i,targetDistance:a,sourceMatched:r,readyState:n,usable:c}}comparePreviewClockSourceCandidates(e,t){var n,a;const i=this.isPreviewClockCandidateAlignedToTarget(e),r=this.isPreviewClockCandidateAlignedToTarget(t);return i!==r?i?-1:1:this.pendingClockAlignmentTargetTime!==null&&e.targetDistance!==t.targetDistance?e.targetDistance-t.targetDistance:e.usable!==t.usable?e.usable?-1:1:e.sourceMatched!==t.sourceMatched?e.sourceMatched?-1:1:e.readyState!==t.readyState?t.readyState-e.readyState:(((n=e.slot.entry)==null?void 0:n.trackOrder)??0)-(((a=t.slot.entry)==null?void 0:a.trackOrder)??0)}isPreviewClockCandidateAlignedToTarget(e){return this.pendingClockAlignmentTargetTime!==null&&e.usable&&e.targetDistance<=this.getPreviewClockTargetAlignmentThresholdMs(e.slot)}getPreviewClockTargetAlignmentThresholdMs(e){return Math.max(bu,this.getSlotSeekThresholdSeconds(e)*1e3)}isPreviewClockSlotAlignedToPendingTarget(e,t){return this.pendingClockAlignmentTargetTime===null||t===null?!0:Math.abs(t-this.pendingClockAlignmentTargetTime)<=this.getPreviewClockTargetAlignmentThresholdMs(e)}updatePendingClockAlignmentTarget(e){if(!e.activeClips.some(i=>i.trackType==="video"&&i.hasVisual)){this.pendingClockAlignmentTargetTime=null;return}(e.interactionMode==="seek"||e.interactionMode==="scrub")&&(this.pendingClockAlignmentTargetTime=e.currentTime)}syncActivePlaybackGroupSuspension(e,t){if(t>1&&(e.status==="loading"||e.status==="failed")){this.playbackGroupSuspended=!0;for(const{current:r}of this.trackSlots.values())!this.isActiveCurrentSlot(r)||r.requestedPlayState!=="playing"||r.element.paused||(this.emitDiagnostic("debug","playback","media.group-pause.requested",this.buildSlotTraceData(r,{message:"Paused active media while preview playback group is blocked",mediaState:ee(r.element),extra:{loadingStatus:e.status,loadingReason:e.reason}})),Ge(r.element));return}if(this.playbackGroupSuspended){this.playbackGroupSuspended=!1;for(const{current:r}of this.trackSlots.values()){if(!this.isActiveCurrentSlot(r)||r.requestedPlayState!=="playing"||!r.element.paused||r.element.ended)continue;const n=Fe(r.element,r.desiredSource);n.hasSrcAttribute&&(this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.group-play.requested",this.buildSlotTraceData(r,{message:"Resumed active media after preview playback group became ready",mediaState:ee(r.element),extra:{loadingStatus:e.status,loadingReason:e.reason,sourceState:n}})),Pr(r.element))}}}getSlotMediaTimeMs(e){return Number.isFinite(e.element.currentTime)?Math.max(0,e.element.currentTime*1e3):null}getSlotTimelineTime(e,t=this.getSlotMediaTimeMs(e)){if(!e.entry||t===null)return null;const i=e.entry.clip,r=i.startTime+(t-i.startTimeAtSource);return Math.max(i.startTime,Math.min(i.endTime,r))}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.lastRuntimeState})}buildPreviewLoadingState(e){return e.trackedActiveCurrentVideoSlotCount<=0?{status:"idle",isLoading:!1,reason:null}:e.hasFailedTrackedVideoSlot&&e.failedTrackedCurrentVideoSlotCount>=e.trackedActiveCurrentVideoSlotCount?{status:"failed",isLoading:!1,reason:"failed"}:this.activeSyncRequestId!==void 0&&this.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:e.hasResolvingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"resolving-source"}:e.hasSeekingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"seeking"}:e.hasMediaUnreadyTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}evaluateTrackedCurrentVideoSlot(e){if(!this.isTrackedActiveCurrentVideoSlot(e)||!e.entry)return{failed:!1,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1};const t=e.desiredSource,i=this.doesSlotSourceMatchDesired(e,t),r=typeof e.element.readyState=="number"?e.element.readyState:0,n=e.entry.mediaTime/1e3,a=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN,o=this.getSlotSeekThresholdSeconds(e),l=Number.isFinite(a)&&Math.abs(a-n)<=o,c=e.requestedPlayState==="playing"&&!e.element.ended,h=r>=at;let d=c&&e.element.paused&&!this.playbackGroupSuspended;d&&(this.maybeResumeRequestedPlayback(e,"runtime-check"),d=c&&e.element.paused&&!this.playbackGroupSuspended),this.playbackGroupSuspended&&e.playbackProgressStalled&&!e.hasBufferingSignalSinceSourceChange&&r>=pu&&(e.playbackProgressStalled=!1,e.isBuffering=!1),this.updateSlotPlaybackProgressState(e,{shouldBePlaying:c,sourceMatched:i,readyState:r,speed:e.element.playbackRate||1}),c&&e.isBuffering&&!e.hasBufferingSignalSinceSourceChange&&!e.playbackProgressStalled&&h&&!d&&(e.isBuffering=!1);const u=e.hasReadyEventSinceSourceChange&&!e.isBuffering,f=!(c&&(e.isBuffering||e.playbackProgressStalled))&&!d&&(h||!c&&e.hasReadyEventSinceSourceChange||c&&u),y=lu(e,{hasDesiredSource:!!t,sourceMatched:i,withinSeekThreshold:l,readyState:f?at:Math.min(r,at-1),haveCurrentDataState:at});return y.ready&&this.tryResolveAutoAspectRatioFromSlot(e),y}doesSlotSourceMatchDesired(e,t){return Zd(tr(e.element)||null,xe(e.element)||null,t)}getSlotSeekThresholdSeconds(e){return Qd(e.role,e.element.playbackRate||1)}finalizeSourceResolutionResult(e,t,i){return i===null?(e.isResolvingSource=!1,t):Ne(t)?t.finally(()=>{e.resolveToken===i&&(e.isResolvingSource=!1,this.refreshRuntimeState())}):(e.resolveToken===i&&(e.isResolvingSource=!1),t)}syncLoadingProbe(e){if(e.status!=="loading"){this.clearLoadingProbe();return}this.loadingProbeTimeoutId||(this.loadingProbeTimeoutId=setTimeout(()=>{this.loadingProbeTimeoutId=null,this.refreshRuntimeState()},mu))}syncClockProbe(e){if(!((e==null?void 0:e.status)==="running"||(e==null?void 0:e.status)==="blocked"||(e==null?void 0:e.status)==="priming")){this.clearClockProbe();return}this.clockProbeTimeoutId||(this.clockProbeTimeoutId=setTimeout(()=>{this.clockProbeTimeoutId=null,this.refreshRuntimeState()},yu))}clearLoadingProbe(){this.loadingProbeTimeoutId&&(clearTimeout(this.loadingProbeTimeoutId),this.loadingProbeTimeoutId=null)}clearClockProbe(){this.clockProbeTimeoutId&&(clearTimeout(this.clockProbeTimeoutId),this.clockProbeTimeoutId=null)}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=De(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=Tu(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=De(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.requestPauseIfPlaying(),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=ao(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=a,t.changed=!vn(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 ${ot.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"?Is:`${kr(e.fontName)}, ${Is}`}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: ${kr(e.fontName)};`,`src: url("${lo(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 ${kr(e.fontName)}`)).then(()=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="loaded",this.refreshTextPreviewEntries())}).catch(n=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="failed",B.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=xs(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:so(e,n),displayRect:xs(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=De(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,g=(n.element.offsetHeight||0)*d,f=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:f-u/2,top:y-g/2,width:u,height:g,centerX:f,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:Rs((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:Rs((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=wu(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(ir(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=Li(t,"sys_width"),n=Li(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 _u extends xu{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 Au(s){return"dom"}const Iu=36e5,Eu=3e5;function nn(s){return s.length===0?0:s.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function Ms(s){return nn(s)}function Ds(s){return Math.max(s+Eu,Iu)}class Ls{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){B.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function Ru(s){return[...s].sort((e,t)=>e.order-t.order)}function Mu(s){return[...s].sort((e,t)=>e.startTime-t.startTime)}function xr(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 Du{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t){const i=Ru(e),r=[],n=[];let a=null;for(const o of i){const l=Mu(o.clips),c=l.find(d=>t>=d.startTime&&t<d.endTime);if(c){const d=c.startTimeAtSource+(t-c.startTime);r.push(xr(o,c,d))}const h=l.find(d=>d.startTime>t);if(h&&n.push(xr(o,h,h.startTimeAtSource)),!a&&o.type==="video"){const d=l[0];d&&(a=xr(o,d,d.startTimeAtSource))}}return{activeClips:r,nextClips:n,firstVideoClip:a}}}class Lu{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 Ou=1e3;class Bu{constructor(e){p(this,"callbacks");p(this,"failedOverlayDelayMs");p(this,"_previewLoadingState",{status:"idle",isLoading:!1,reason:null});p(this,"_pendingPreviewState",null);p(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.failedOverlayDelayMs=e.failedOverlayDelayMs??Ou}get previewLoadingState(){return this._previewLoadingState}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)}handleRuntimeStateChange(e){const t=this._previewLoadingState;this._previewLoadingState=e.loading,this._pendingPreviewState&&e.syncRequestId===this._pendingPreviewState.syncRequestId&&(e.loading.reason!=="syncing"&&(this._pendingPreviewState.awaitingSync=!1),e.loading.status==="failed"?this.scheduleFailedOverlay(e.errorMessage||"资源加载异常,请刷新重试"):(this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.errorMessage=null)),Os(t,e.loading)||this.callbacks.emitLoadingStateChange(e.loading),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,loading:this.resolvePendingLoadingState(),errorMessage:this._pendingPreviewState.errorMessage}:this.buildPlaybackLoadingOverlayState()}updatePendingPreviewState(){if(!this._pendingPreviewState){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const t=this.resolvePendingLoadingState().status==="loading";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(t){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const i=this._pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),i&&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={status:"idle",isLoading:!1,reason:null};Os(this._previewLoadingState,e)||(this._previewLoadingState=e,this.callbacks.emitLoadingStateChange(e))}resolvePendingLoadingState(){var e;return(e=this._pendingPreviewState)!=null&&e.awaitingSync?{status:"loading",isLoading:!0,reason:"syncing"}:this._previewLoadingState}buildPlaybackLoadingOverlayState(){return this._previewLoadingState.status!=="loading"||this._previewLoadingState.reason!=="media-pending"?null:{mode:"playback",targetTime:0,loading:this._previewLoadingState,errorMessage:null}}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)}}function Os(s,e){return s.status===e.status&&s.isLoading===e.isLoading&&s.reason===e.reason}const Fu=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Gu={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 Nu(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function Hu(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 $u(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=Hu(c);if(!h||r)return null;r=h}}return r?{action:s,code:r,altKey:n,ctrlKey:a,metaKey:o,shiftKey:l}:null}function zu(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 Vu(s,e){return s.code===e.code&&s.altKey===e.altKey&&s.ctrlKey===e.ctrlKey&&s.metaKey===e.metaKey&&s.shiftKey===e.shiftKey}function Uu(s,e){return s===!1||(s==null?void 0:s.enabled)===!1?[]:Fu.flatMap(t=>{var n;const i=(n=s==null?void 0:s.bindings)==null?void 0:n[t];return(i===void 0?Gu[t]:Array.isArray(i)?i:[i]).map(a=>$u(t,a,e)).filter(a=>a!==null)})}class Wu{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??Nu();e.root,this.callbacks=e.callbacks,this.bindings=Uu(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(zu(e.target))return;const t=this.bindings.find(i=>Vu(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 co(s){var t;const e=s.getPrimarySelectedClip()||((t=s.findFallbackSelectedClip)==null?void 0:t.call(s))||null;return{clip:e,hasSelectedClip:!!e}}function Yu(s){const e=co(s),t=s.getSelectedClipIds(),i=s.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:s.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function Xu(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 qu(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 ju(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=qu(s.trackCollection,e);return t?s.trackCollection.addClipToTrack(t,s.clip):!1}function Bs(s,e,t){return e.trackId?s.removeClipFromTrack(e.trackId,t):!1}function Ku(s){return s.trackCollection.moveClipToTrack(s.command.clip,s.command.sourceTrackId,s.command.targetTrackId)}function Ye(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 Zu(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 ho{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 no({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,this.resolveUpdateTargets(i,r).forEach(a=>{e.updateClip(a.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)}showVoiceGenerationLoading(){var e;(e=this.panel)==null||e.showVoiceGenerationLoading()}hideVoiceGenerationLoading(){var e;(e=this.panel)==null||e.hideVoiceGenerationLoading()}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 a=new Set(i.map(c=>c.type)).size>1?"mixed":r.type,o=i.length>1,l=a==="audio"&&i.every(c=>Le(c));return{primaryClip:r,selectedClips:i,selectionCount:i.length,groupKind:a,supportsVoiceBatch:a==="text"||l,supportsTextContentBatch:a==="text"&&!o,supportsVisualBatch:a==="video",supportsVolumeBatch:a==="video"||a==="audio"}}resolveUpdateTargets(e,t){const{primaryClip:i,selectedClips:r,groupKind:n,supportsVoiceBatch:a}=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")?a&&n==="audio"?r.filter(l=>Le(l)):[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: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}}}class Ju{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 ro({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:mi,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 Fs{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 Qu=100*1024*1024,ep=10*1024*1024*1024,tp=30*24*60*60*1e3,ip=["video/mp4","audio/aac","audio/mpeg","audio/mp4","audio/mp3","audio/ogg","audio/wav","audio/x-wav"],si={enabled:!1,maxEntryBytes:Qu,maxTotalBytes:ep,ttlMs:tp,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:ip},rp="timeline-preview-resource-cache",np=1,me="metadata";function sp(){return new Promise((s,e)=>{const t=indexedDB.open(rp,np);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=()=>s(t.result)})}function _r(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class ap{constructor(){p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=sp().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 _r(i)}async delete(e){const i=(await this.getDb()).transaction(me,"readwrite");i.objectStore(me).delete(e),await _r(i)}async clear(){const t=(await this.getDb()).transaction(me,"readwrite");t.objectStore(me).clear(),await _r(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 op="timeline-preview-resource-cache",lp="timeline-preview-resource-cache-blobs",cp=1,Re="blobs";function hp(){return new Promise((s,e)=>{const t=indexedDB.open(lp,cp);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Re)||i.createObjectStore(Re)},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function Ar(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class dp{constructor(){p(this,"kind","indexeddb");p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=hp().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(Re,"readonly").objectStore(Re).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Re,"readwrite");r.objectStore(Re).put(t,e),await Ar(r)}async delete(e){const i=(await this.getDb()).transaction(Re,"readwrite");i.objectStore(Re).delete(e),await Ar(i)}async clear(){const t=(await this.getDb()).transaction(Re,"readwrite");t.objectStore(Re).clear(),await Ar(t)}}class up{constructor(){p(this,"kind","opfs");p(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(op,{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 pp(s){var e;if(s.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new up;if(await t.ensureReady())return t}return new dp}function gp(s){return Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function Gs(s){return s.split(";",1)[0].trim().toLowerCase()}async function fp(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 gp(new Uint8Array(t))}function Ir(s){return s?[...s]:[...si.allowedMimeTypes]}function mp(s){return s?s===!0?{...si,enabled:!0,allowedMimeTypes:Ir(void 0)}:{...si,...s,enabled:s.enabled??!0,allowedMimeTypes:Ir(s.allowedMimeTypes)}:{...si,allowedMimeTypes:Ir(void 0)}}function yp(s){try{const e=new URL(s);return e.hash="",e.toString()}catch{return s.trim()}}async function Sp(s){var t;const e=((t=s.sourceKey)==null?void 0:t.trim())||yp(s.url);return fp(e)}function Ns(s,e=si.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=Gs(s.mimeType);return!e.some(r=>Gs(r)===i)}function vp(s){return s&&s.split(";",1)[0].trim().toLowerCase()||null}function Hs(s){if(!s)return null;const e=Number(s);return Number.isSafeInteger(e)&&e>=0?e:null}function Cp(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 $s(s,e,t){return{url:e,ok:s.ok,status:s.status,mimeType:vp(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 bp{async probe(e){var r;try{const n=await fetch(e,{method:"HEAD"}),a=Hs(n.headers.get("content-length"));if(n.ok&&a!==null)return $s(n,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=Cp(t.headers.get("content-range"))??Hs(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return $s(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 Tp={createObjectURL(s){return URL.createObjectURL(s)},revokeObjectURL(s){URL.revokeObjectURL(s)}};function bt(s,e){return{url:s.url,cacheStatus:e,sourceUrl:s.url}}function wp(s,e){return s.etag||e.etag?s.etag===e.etag&&s.sizeBytes===e.contentLength:s.sizeBytes===e.contentLength&&s.lastModified===e.lastModified}class kp{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=mp(e.options),this.metadataStore=e.metadataStore??new ap,this.storagePromise=e.storage?Promise.resolve(e.storage):pp({preferStorage:this.options.preferStorage}),this.http=e.http??new bp,this.objectUrl=e.objectUrl??Tp,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??Sp,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Ns(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),bt(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}),bt(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}),bt(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(wp(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:bt(e,"fallback")}):Ns({...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:bt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:bt(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 Pp(s){return!!s&&typeof s.then=="function"}class Er{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(!Pp(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 zs{constructor(e,t=Ji){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 xp{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 _p(s){return s==="text"?"文本":s==="video"?"视频":"音频"}function Oi(s){return s==="text"?0:s==="video"?1:2}class uo{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||`${_p(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),B.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?(B.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(B.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),B.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,B.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(B.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),B.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(B.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=>Oi(l.type)>Oi(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)=>Oi(c.type)<=Oi(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,B.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(B.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,B.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}class Ap{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 po{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 Ip{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 Vs{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new po,this.playbackStore=new Ap({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new Ip({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 Ep{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||Zt,zoom:i.zoom||Me.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Ui(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(),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=or({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(lr({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),a=U.msToSeconds(r),o=U.msToSeconds(n),{majorStep:l,minorStep:c}=U.getTickConfig(this.config.zoom),h=U.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,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,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(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=or({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(lr({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=bn.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",bn.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 sn=q;class Us{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,Mt.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||Mt.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Mt.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=or({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(lr({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||Mt.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Mt.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 Ws{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()}}const Rp="@linker-design-plus/timeline-track",Mp="2.1.0",Vt={name:Rp,version:Mp},Dp=1,Lp=2,Op=250;function Ys(s){return s==null?s:JSON.parse(JSON.stringify(s))}function Bp(s,e){return s.length!==e.length?!1:s.every((t,i)=>t===e[i])}function Fp(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class Gp{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 Er);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,"lastSelectedClipId",null);p(this,"previewAspectRatio",{...Oe});p(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});p(this,"stageMouseDownListener",null);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 Ws);p(this,"pendingDraftData",null);p(this,"selectionStore",new po);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);p(this,"splitOperationDepth",0);p(this,"diagnostics");p(this,"previewRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},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||Zt,zoom:e.zoom||Me.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:Ui(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 za(this.config.diagnostics),this.resourceCacheManager=this.config.resourceCache?new kp({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:Vt.name,packageVersion:Vt.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 Ju,this.eventDispatcher=new Ls({can_play_change:()=>({canPlay:this.canPlay}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new en(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Ps(this.history),this.timelineHistoryExecutor=new ks({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 uo,this.timelineStore=new Vs({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new ws(this.timelineStore),this.timelinePresentationAdapter=new Fs,this.timelineTrackBridge=new zs({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.handleTimeChange.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,sourceLoadingPending:this.getSourceLoadingState().pending,loadingStatus:this.getPreviewLoadingState().status,loadingReason:this.getPreviewLoadingState().reason,isLoading:this.getPreviewLoadingState().isLoading,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)||Me.MEDIUM,h=((n=this.config)==null?void 0:n.duration)||Zt;this.timelineStore=new Vs({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new ws(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new xp(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new Fs),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new zs({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.handleTimeChange.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 Du),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}getPreviewLoadingState(){return this.getPreviewStateController().previewLoadingState}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 Bu({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitLoadingStateChange:e=>{this.syncPlaybackClockToPreviewLoadingState(e),this.emitEvent("loading_state_change",e)},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new Lu({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new _u({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||Au(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewRuntimeState=t,this.getPreviewStateController().handleRuntimeStateChange(t),this.handlePreviewClockStateChange(t.clock))},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=je(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()},onPauseIfPlaying:()=>{this.isActivePreviewCallbackToken(e)&&this.getPlayStateState()==="playing"&&this.pause()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Ls({can_play_change:()=>({canPlay:this.canPlay??!1}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new en(()=>{},()=>{})),this.timelineHistoryRecorder=new Ps(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new ks({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 a=t,o=i;if(!o)throw new Error("transaction history boundary requires a callback");return this.getTimelineHistoryRecorder().withTransaction(a,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 a=r();return a instanceof Promise?a.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),a)}catch(a){throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),a}}const n=this.isExecutingHistoryAction??!1;this.isExecutingHistoryAction=!0;try{const a=r();return a instanceof Promise?a.then(o=>(this.isExecutingHistoryAction=n,o),o=>{throw this.isExecutingHistoryAction=n,o}):(this.isExecutingHistoryAction=n,a)}catch(a){throw this.isExecutingHistoryAction=n,a}}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:Zt,zoom:Me.MEDIUM,currentTime:0,playState:"paused",theme:Ui(),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 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)}playbackPlanHasActiveVideoClip(e){return e.activeClips.some(t=>t.trackType==="video")}hasActiveTimelineVideoClip(e=this.getCurrentTimeState()){return this.playbackPlanHasActiveVideoClip(this.buildPlaybackPlan(e))}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((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.getPreviewLoadingState().isLoading||this.lastPreviewSyncedPlayState!=="playing"||this.lastPreviewSyncSignature!==e?!1:Date.now()-this.lastSteadyPlaybackPreviewSyncAt<Op}syncPreviewSession(e){var h,d,u,g;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(f=>f.clip.id);const i=this.getAutoAspectRatioClip(),r=je(this.previewAspectRatio),n=this.resolvePreviewSyncPlayState(e),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,(g=(u=this.previewSession).setPendingState)==null||g.call(u,this.buildPreviewPendingState()),this.lastPreviewSyncedPlayState=n,this.lastPreviewSyncSignature=c,this.lastSteadyPlaybackPreviewSyncAt=n==="playing"&&o==="steady"?Date.now():0}resolvePreviewSyncPlayState(e){return e||this.getPlayStateState()}syncPreviewPlaybackStateIfNeeded(e){this.lastPreviewSyncedPlayState!==e&&this.syncPreviewSession(e)}shouldUsePreviewClockPlayback(){var e;try{return!!((e=this.previewSession)!=null&&e.hasPreview())&&this.hasActiveTimelineVideoClip()&&!this.pendingPreviewState}catch{return!1}}handlePreviewClockStateChange(e){if(!(!e||this.getPlayStateState()!=="playing")){if(!this.shouldUsePreviewClockPlayback()){this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState());return}if(this.isPreviewClockForCurrentActiveClip(e)){if(e.status!=="running"||e.timelineTime===null){this.cancelPlaybackAnimationFrame(),this.shouldCommitUnavailablePreviewClock(e)&&this.commitPlaybackTimeFromPreviewClock(e);return}this.commitPlaybackTimeFromPreviewClock(e)}}}isPreviewClockForCurrentActiveClip(e){return!e.clipId||!Array.isArray(this.previewActiveClipIds)?!0:this.previewActiveClipIds.includes(e.clipId)}shouldCommitUnavailablePreviewClock(e){return e.status!=="unavailable"||e.timelineTime===null?!1:this.isPreviewClockForCurrentActiveClip(e)}commitPlaybackTimeFromPreviewClock(e){if(e.timelineTime===null)return;const t=this.clampPlaybackSeekTime(e.timelineTime),i=this.getTimelineCommands().setCurrentTime(t);if(!i.changed){this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(i.nextValue,e);return}const r=i.nextValue;this.ensureConfigState().currentTime=r,this.syncCurrentTimeToScene(r),this.emitEvent("time_change",{time:r}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(r,e)}syncPreviewAfterPreviewClockCommitIfNeeded(e,t){if(this.getPlayStateState()!=="playing"||this.pendingPreviewState)return;const i=this.buildPlaybackPlan(e),r=i.activeClips.map(n=>n.clip.id);if(!Bp(r,this.previewActiveClipIds)){this.syncPreviewSession(),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i);return}t.clipId&&(r.includes(t.clipId)||this.syncPreviewSession()),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i)}resumeWallClockPlaybackIfPreviewClockUnavailable(e,t=this.buildPlaybackPlan(e)){this.getPlayStateState()!=="playing"||this.pendingPreviewState||this.animationFrameId||this.playbackPlanHasActiveVideoClip(t)||!this.canPlay||(this.lastUpdateTime=Date.now(),this.animate())}beginPendingPreview(e,t="seek"){var r,n,a,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;if(!this.hasActiveTimelineVideoClip(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.getPreviewStateController().buildPreviewPendingState()}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",loading:{status:"idle",isLoading:!1,reason:null},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(je(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){B.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=gd(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:mi,scrollbarSize:Zr}),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&&(this.stageMouseDownListener||(this.stageMouseDownListener=h=>{this.handleStageMouseDown(h)}),t.addEventListener("mousedown",this.stageMouseDownListener)),this.timeline=new Ep(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new sn(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 Us({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:Te,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Us({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=>{B.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,n){var d,u,g;if(!this.trackLayer)return B.error("TimelineManager","Track layer not initialized"),"";const a=this.trackManager.createTrack(e,t,i,r,n),o=a.id,l=Ae(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(),(g=this.stage)==null||g.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 B.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return B.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 zt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return bs(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=Sd(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=zt(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+Ae(c.type)}}if(t==="top_of_type_region"&&a)return zt(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return zt(r,o.id,this.getTrackContentTopOffset())+Ae(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():bs(r,this.getTrackContentTopOffset());const l=zt(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+Ae(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=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||te.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===Dp)return e*16;if(t===Lp){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*Rr.SENSITIVITY_FACTOR),n=Math.max(Me.MIN,Math.min(Me.MAX,i*r));Math.abs(n-i)<Rr.CONVERGENCE_THRESHOLD||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")return;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 t=this.getClips();if(t.length>0&&this.getCurrentTime()>=Kt(t)){if(this.setCurrentTime(0),!this.canPlay)return}else{B.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}}this.refreshPlaybackAttempt("play"),this.setPlayStateState("playing"),this.lastUpdateTime=Date.now();const e=this.shouldUsePreviewClockPlayback();e?(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame()):this.getPreviewLoadingState().isLoading?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitPlayStateChangeEvent(),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"play.started",message:"Playback started",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}),this.syncPreviewSession(!e&&this.getPreviewLoadingState().isLoading?"paused":void 0)}pause(){if(this.getPlayStateState()==="paused"){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused");return}this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.emitPlayStateChangeEvent(),this.syncPreviewSession()}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused"){this.animationFrameId=null;return}if(this.shouldUsePreviewClockPlayback()){this.animationFrameId=null;return}if(this.getPreviewLoadingState().status==="loading"){!this.previewPlaybackSuspendedByBuffering&&this.getPlayStateState()==="playing"&&this.suspendPlaybackForMediaPending(),this.animationFrameId=null;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();if(this.setCurrentTime(i),this.getPlayStateState()==="paused"){this.animationFrameId=null;return}this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}cancelPlaybackAnimationFrame(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}emitPlayStateChangeEvent(){this.emitEvent("play_state_change",{playState:this.getPlayStateState()})}suspendPlaybackForMediaPending(){this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering=!0,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused")}resumePlaybackAfterMediaPending(){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.syncPreviewPlaybackStateIfNeeded("playing"),this.lastUpdateTime=Date.now(),this.animationFrameId||this.animate()}shouldSuspendPreviewPlaybackForLoadingState(e){return e.status==="loading"}syncPlaybackClockToPreviewLoadingState(e){if(this.shouldUsePreviewClockPlayback()){this.cancelPlaybackAnimationFrame(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,e.status==="failed"&&this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.emitPlayStateChangeEvent());return}if(this.shouldSuspendPreviewPlaybackForLoadingState(e)){if(this.previewPlaybackSuspendedByBuffering){this.syncPreviewPlaybackStateIfNeeded("paused");return}if(this.getPlayStateState()!=="playing"){this.syncPreviewPlaybackStateIfNeeded("paused");return}this.suspendPlaybackForMediaPending();return}if(!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&(e.status==="ready"||e.status==="idle")&&!this.pendingPreviewState,i=this.previewPlaybackAutoResume&&e.status==="failed"&&this.getPlayStateState()!=="paused";if(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,i){this.setPlayStateState("paused"),this.emitPlayStateChangeEvent();return}!t||this.animationFrameId||this.resumePlaybackAfterMediaPending()}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=Kt(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.updateCanPlayState(),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 a=this.timeline.getScrollLeft(),o=U.timeToPixels(i,t),c=U.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=U.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=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>0}getSourceLoadingState(){const e=this.sourceLoadingCount;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}),B.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return B.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{return await this.withHistoryTransaction("add_clips",async()=>{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?nn(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??"",a=e.duration??(r?Zs: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 U.getVideoDuration(n,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(S){B.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)}`,g=cn({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?De(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});if(B.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:g.id,type:g.type,startTime:g.startTime,duration:g.duration})),e.trackId){const S=this.getTrackCollection().findById(e.trackId);if(S)return this.registerPreviewAutoAspectRatioClip(g),(b=S.addClip)==null||b.call(S,g),zi({applied:!0,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const C=e.trackId;this.getTimelineHistoryRecorder().recordAddClip(g,C,this.cloneTrackSnapshot(C),this.getTrackRestoreAnchor(C))},applyEffects:()=>Ye({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(g),g.id}const f=this.getTimelineCommands().planTrackPlacement(g,this.getTracksSortedByOrder()),y=this.getTrackCollection(),v=ju({clip:g,placement:f,trackCollection:y,createTrack:this.createTrack.bind(this)});return zi({applied:v,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const S=this.resolveTrackIdByClipId(g.id);this.getTimelineHistoryRecorder().recordAddClip(g,S,S?this.cloneTrackSnapshot(S):null,S?this.getTrackRestoreAnchor(S):null)},applyEffects:()=>Ye({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.primeOrLoadClipThumbnails(g),g.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),zi({applied:Bs(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:()=>Ye({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 a=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);a.exists&&(r=Bs(this.getTrackCollection(),a,n)||r)}})}),r?(Di({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Ye({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)}Ye({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)}),Ye({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)}),Ye({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(xt(e.mode)&&t===Oe.width&&i===Oe.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=ln({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){B.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),a=this.resolveImportedTrackRoles(n);let o;for(const c of n){const h=this.createTrack(c.type,c.name,o?"after_track":void 0,o,a.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 g=d.separatedFromVideoClipId;g&&l.has(g)&&(g=l.get(g));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:g,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,ttsSourceTextClipId:d.ttsSourceTextClipId,ttsVoiceId:d.ttsVoiceId,ttsVoiceName:d.ttsVoiceName,ttsFollowTextUpdates:d.ttsFollowTextUpdates,trackId:h},y=await this.addClip(f);l.set(d.id,y)}catch(u){t.push({clipId:d.id,error:u}),B.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 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.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 Vt.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;B.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:a}));const o=Math.min(a/r,Me.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),this.getPlayStateState()==="playing"&&this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState()),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;_d({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}),Di({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)&&Di({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}))}reloadClipThumbnailsIfNeeded(e,t){Ad(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{B.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){const e=this.getClips(),t=this.getCurrentTime(),i=Id(e,t),r=this.canPlay;this.canPlay=Ed({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:Kt(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&&B.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))}resolveVoiceTextContent(e){return e.textContent??e.name??""}findSourceTextClipForTtsAudio(e){if(!e.ttsSourceTextClipId)return null;const t=this.findClipById(e.ttsSourceTextClipId);return(t==null?void 0:t.type)!=="text"?null:t}resolveTtsAudioVoiceGenerationSource(e){const t=this.findSourceTextClipForTtsAudio(e),i=t?this.resolveVoiceTextContent(t):"",r=typeof e.textContent=="string"?e.textContent:"",n=i.trim().length>0?i:r.trim().length>0?r:"";if(n.length===0)throw new Error("替换音色失败:缺少可用的配音文本");return{requestSourceTextClipId:(t==null?void 0:t.id)??e.ttsSourceTextClipId??e.id,persistedSourceTextClipId:t==null?void 0:t.id,text:n}}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(a=>{B.error("TimelineManager","Failed to flush pending linked voice regeneration",{error:a,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(a=>{B.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:a,clipId:e})})},Js)}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 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.type!=="text"||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")}selectBestClipboardPasteStartIndex(e,t){var r;if(t.length===0)return null;const i=t.filter(n=>n.newTrackCount===0).sort((n,a)=>n.score-a.score)[0];if(i)return i.startIndex;if(e==="text"){const n=t.filter(a=>a.startIndex<0).sort((a,o)=>a.newTrackCount!==o.newTrackCount?a.newTrackCount-o.newTrackCount:a.score-o.score)[0];if(n)return n.startIndex}return((r=t.slice().sort((n,a)=>n.score-a.score)[0])==null?void 0:r.startIndex)??null}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(C=>{var w;return C.type===((w=e[0])==null?void 0:w.type)}).sort((C,w)=>C.order-w.order);if(a.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 x=this.createTrack(e[w].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");x&&n.set(e[w].key,x)}return n}const o=new Set(e.flatMap(C=>C.clipIds)),l=e.map(C=>{const w=this.buildClipboardPasteGroupPlacementClips(C,t,i,r);if(w.length===0)return null;const x=this.resolvePreferredTrackIndexForPasteGroup(C,a,Math.min(C.sourceOrder,Math.max(a.length-1,0)));return{...C,preferredTrackIndex:x,clips:w}}).filter(C=>C!==null);if(l.length===0)return n;const c=l.map(C=>C.preferredTrackIndex),h=Math.min(...c),d=a.length,u=-l.length,g=[];for(let C=u;C<=d;C+=1){let w=!0,x=0,k=0;for(let D=0;D<l.length;D+=1){const P=l[D];if(!P)continue;const A=C+D;if(x+=Math.abs(A-P.preferredTrackIndex),A<0||A>=a.length){k+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[A].id,P.clips,o)){w=!1;break}}w&&(x+=k*.1,x+=Math.abs(C-h)*Qs.ANCHOR_INDEX_WEIGHT,g.push({startIndex:C,score:x,newTrackCount:k}))}const f=this.selectBestClipboardPasteStartIndex(l[0].type,g);if(f===null)return n;const y=Math.max(0,-f),v=Math.max(0,f+l.length-a.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=f+y;return l.forEach((C,w)=>{const x=b[S+w];x&&n.set(C.key,x.id)}),n}resolvePreferredTrackIndexForPasteGroup(e,t,i){if(e.sourceTrackId){const r=t.findIndex(n=>n.id===e.sourceTrackId);if(r!==-1)return r}if(Number.isFinite(e.sourceTrackOrder)){const r=t.findIndex(n=>n.order>=e.sourceTrackOrder);return r!==-1?r:t.length}return i}resolveClipboardPasteTrackAssignments(e,t,i){const r=this.buildClipboardPasteGroups(e,t),n=new Map;r.forEach(o=>{const l=n.get(o.type)??[];l.push(o),n.set(o.type,l)});const 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]}getSelectedTtsAudioClipsForVoiceGeneration(e){if(e.type!=="audio"||!Le(e))return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(n=>Le(n))))return[e];const r=t.filter(n=>Le(n));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((f,y)=>({requestId:`create:${f.id}:${i.id}:${h}:${y}`,sourceTextClipId:f.id,text:f.textContent??f.name??"",voiceId:i.id,followTextUpdates:r,mode:"create"}));e.setPreferredTab("voice");const u=[];if(await this.withHistoryTransaction("generate_voice_from_text_clips",async()=>{const f=await n(d),y=new Map(f.map(v=>[v.requestId,v]));for(const v of d){const b=y.get(v.requestId);if(!b)continue;const S=c.find(k=>k.id===v.sourceTextClipId);if(!S)continue;const C=this.normalizeGeneratedAudioDuration(b.duration),w=S.textContent??S.name??"";this.syncTextClipDurationToAudio(S.id,C);const x=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(x)}if(u.length===0)throw new Error("生成音频失败:未返回音频结果")}),u.length===1){this.scrollToClip(u[0],{selectClip:!0,setCurrentTime:!0});return}const g=u[0]??null;this.scrollToClip(g,{setCurrentTime:!0}),this.setSelection(u,{preferredPrimaryClipId:g});return}if(t.type!=="audio"||!Le(t))return;const a=this.getSelectedTtsAudioClipsForVoiceGeneration(t),o=Date.now(),l=a.map((c,h)=>{const d=this.resolveTtsAudioVoiceGenerationSource(c);return{requestId:`replace:${c.id}:${i.id}:${o}:${h}`,sourceTextClipId:d.requestSourceTextClipId,targetAudioClipId:c.id,text:d.text,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 g=h.get(u.requestId);if(!g||!u.targetAudioClipId)continue;const f=a.find(v=>v.id===u.targetAudioClipId);if(!f)continue;const y=this.resolveTtsAudioVoiceGenerationSource(f);if(this.applyGeneratedAudioClipResult(u.targetAudioClipId,y.persistedSourceTextClipId,y.text,g,r),this.relocateClipIfNeeded(u.targetAudioClipId),y.persistedSourceTextClipId){const v=d.get(y.persistedSourceTextClipId)??0;d.set(y.persistedSourceTextClipId,Math.max(v,g.duration))}}d.forEach((u,g)=>{this.syncTextClipDurationToAudio(g,u)}),this.handleClipChange()})}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{B.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){B.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 Er.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return Er.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){Dd({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:()=>Di({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=Rd(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),B.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){B.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.getTimelineHistoryExecutor().executeUndo(e)}),this.checkTrackDurationChange()}handleActionRedo(e){B.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=Xu({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1)}handleClipOverlap(e,t,i){var h,d,u,g;B.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=`${Fp(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))||((g=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:g.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){B.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"?(B.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(B.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()+Zr}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(f=>f.id===u)??null)&&r.push(u)}}),r.length===0)return!1;const a=e.primaryClipId?t.get(e.primaryClipId)??r[0]??null:r[0]??null;return this.setSelection(r,{preferredPrimaryClipId:a}),!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:Ys(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:Ys(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=je({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 ho,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(),getSelectedClips:()=>this.getSelectedClips(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c),u=d?{...d}:null,g=typeof h.textContent=="string"?h.textContent:null;if(n&&(u==null?void 0:u.type)==="text"&&g!==null&&g!==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,g,n);return}this.updateClip(c,h),this.handleClipChange()},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 g;const d=new Set(this.getSelectedClipIds()),u=this.getPrimarySelectedClip();d.size===0&&(u!=null&&u.id)&&d.add(u.id),(g=h==null?void 0:h.clip)!=null&&g.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 je(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:Vt.name,packageVersion:Vt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=je({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={...Oe},(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.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 a=this.getClips().find(c=>c.id===e),o=this.getClips().find(c=>c.id===r)??null,l=this.resolveTrackIdByClipId(r);return a?(n&&this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,a,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,a=!this.shouldSkipHistoryRecording();this.withHistoryBoundary("suppressed",()=>{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})});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(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 B.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(n.status==="noop")return B.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(n.status==="missing_target_track")return B.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(n.status==="track_type_mismatch")return B.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var f,y,v;return{targetTrackType:(y=(f=this.getTrackCollection().findById(t))==null?void 0:f.getTrackType)==null?void 0:y.call(f),clipType:(v=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:v.clip.type}}),!1;if(n.status!=="ready")return!1;const{sourceTrackId:a,targetTrackId:o}=n,l=i?{...i}:{...n.clip},c=r?{...r}:{...n.clip},h=this.cloneTrackSnapshot(a),d=this.cloneTrackSnapshot(o),u=Ku({command:{...n,clip:c},trackCollection:this.getTrackCollection()}),g=this.getClips().find(f=>f.id===e)??null;return Md({applied:u,clipId:e,sourceTrackId:a,targetTrackId:o,clipBefore:l,clipAfter:g??l,sourceTrackSnapshot:h,targetTrackSnapshot:d,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>Zu({notifySelectionChange:this.notifySelectionChange.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),batchDraw:()=>{var f;(f=this.stage)==null||f.batchDraw()},syncPreviewSession:this.syncPreviewSession.bind(this)})})?(this.clearAllTrackDropPreviews(),!0):!1}getTrackTotalDuration(){return Ms(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 t,i,r,n,a,o,l,c,h,d,u,g,f,y,v;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPendingPreviewState(),(t=this.resourceCacheManager)==null||t.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(),(i=this.layout)==null||i.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(a=(r=this.layout)==null?void 0:(n=r.bodyCanvasHost).removeEventListener)==null||a.call(n,"click",this.bodyCanvasHostClickListener);const e=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);e&&this.stageMouseDownListener&&((c=e.removeEventListener)==null||c.call(e,"mousedown",this.stageMouseDownListener)),(d=(h=this.rootContainer)==null?void 0:h.removeEventListener)==null||d.call(h,"wheel",this.rootWheelListener),(u=this.horizontalScrollbar)==null||u.destroy(),(g=this.verticalScrollbar)==null||g.destroy(),(f=this.playhead)==null||f.destroy(),(y=this.timeline)==null||y.destroy(),(v=this.stage)==null||v.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new Ws),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new Wu({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{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 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)}}createMultiDragPlacementContext(e){const t=new Map,i=new Map,r=[...this.getResolvedTracksSnapshot()].sort((n,a)=>(n.order??0)-(a.order??0));for(const n of r){const a=i.get(n.type)??[];a.push(n.id),i.set(n.type,a),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(a=>a.id!==i.id&&i.startTime<a.startTime+a.duration&&n>a.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 a=e.orderedTrackIdsByType.get(i)??[];if(!a.includes(t)){if(r==="before_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o,0,t):a.unshift(t)}else if(r==="after_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o+1,0,t):a.push(t)}else r==="top_of_type_region"?a.unshift(t):a.push(t);e.orderedTrackIdsByType.set(i,a)}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 a=t.type==="audio"?"bottom_of_type_region":"top_of_type_region",o=this.createTrack(t.type,void 0,a);return o?(this.registerMultiDragPlacementTrack(e,o,t.type,a),o):null}commitMultiDragPlacements(e,t,i){const r=[],n=this.createMultiDragPlacementContext(new Set(e.selectedClipIds));for(const a of e.selectedClipIds){const o=e.clips.get(a);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 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);return o===null?!1:this.commitMultiDragPlacements(e,t,(l,c)=>l.clipId===t.draggedClipId?a:this.resolveMultiDragTargetTrackId(l,o,c))}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 B.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return B.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return B.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:e.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};B.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):[]}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:Tn.fill,stroke:Tn.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=pe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ye(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=pe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ye(o.duration,this.getZoomState()),h=n+2,d=a-4,u=l+c,g=h+d,f=e.x+e.width,y=e.y+e.height;l<f&&u>e.x&&h<y&&g>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return Ae(e.getTrackType())}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Ye({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(r=>r.id===e);return t?{...t,clips:t.clips.map(r=>({...r}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const r=this.resolveTrackInsertionFromRestoreAnchor(t);if(r){const u=this.createTrack(e.type,e.name,r.insertionPlacement,r.referenceTrackId);return this.muteTrack(u,e.isMuted??!1),u}const n=[...this.getTracks()].sort((u,g)=>u.order-g.order),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 a;const t=this.getTimelineCommands();if(typeof t.findClipById=="function")return((a=t.findClipById(this.tracks,e))==null?void 0:a.trackId)??null;const i=this.getTrackCollection();if(typeof i.findTrackByClipId=="function"){const o=i.findTrackByClipId(e);if(o)return o.getId()}const n=(Array.isArray(this.tracks)?this.tracks:[]).find(o=>o.getClips().some(l=>l.id===e));return(n==null?void 0:n.getId())??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var a;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=nn(e),n=Ms(e);if(r!==t){this.lastTrackDuration=r;const o=Ds(r);this.setDurationState(o),(a=this.timeline)==null||a.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=Kt(e);o>0&&this.getCurrentTimeState()>o&&this.setCurrentTime(o)}r===t&&n===i||B.debugLazy("TimelineManager",()=>`Track duration changed: total=${n}ms, extent=${r}ms, timeline=${Ds(r)}ms`)}resolveSelectedClipSnapshot(){return co({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 Yu({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);vn(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=De(i.textStyle),n=Math.max(ai.MIN,Math.min(ai.MAX,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=De(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 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(),this.clearHistory()})}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=an;exports.CLIP_LAYER=yo;exports.Clip=Ni;exports.ClipConfigPanel=no;exports.DEFAULT_CLIP_VIEW_STATE=Ks;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Oe;exports.DEFAULT_TEXT_CLIP_DURATION_MS=Zs;exports.DEFAULT_TEXT_CLIP_STYLE=qs;exports.DEFAULT_TIMELINE_DURATION_MS=Zt;exports.DiagnosticsCenter=za;exports.HistoryManager=en;exports.MIN_CLIP_LINE_WIDTH=oi;exports.PREVIEW_ASPECT_RATIO_PRESETS=mo;exports.SNAP_SCORING=Qs;exports.TEXT_CLIP_FONT_SIZE_LIMITS=ai;exports.TIMELINE_LEFT_PADDING=Te;exports.TIME_SCALE=vo;exports.TRACK_HEIGHT=Bi;exports.TimeUtils=U;exports.TimelineClipConfigController=ho;exports.TimelineManager=Gp;exports.Track=Ji;exports.TrackInfoPanel=ro;exports.TrackManager=uo;exports.VOICE_LINKED_TEXT_REGEN_DEBOUNCE_MS=Js;exports.ZOOM_ANIMATION=So;exports.ZOOM_GESTURE=Rr;exports.ZOOM_PRESETS=Me;exports.createClipViewState=ea;exports.createClipWithViewState=cn;exports.defaultDarkTheme=Vi;exports.devConsole=B;exports.isAudioOnlyTtsClipCandidate=js;exports.isAutoPreviewAspectRatioMode=xt;exports.isTtsAudioClip=Le;exports.mergeDiagnosticRuntimeState=Va;exports.normalizePreviewAspectRatio=je;exports.normalizePreviewAspectRatioMode=on;exports.resolveAspectRatioBaselineDimensions=ln;exports.resolveTextClipStyle=De;exports.resolveTheme=Ui;
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:${_.sliderFillStart}`,`--clip-slider-fill-end:${_.sliderFillEnd}`,`--clip-slider-road:${_.sliderRoad}`,`--clip-slider-thumb-border:${_.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(";")}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,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}"`):""}static createColorInputHandler(e){return t=>{const i=t.target.value;cancelAnimationFrame(xt.colorRafId),xt.colorRafId=requestAnimationFrame(()=>{e.callbacks.onTextStyleChange("color",i)})}}};g(xt,"colorRafId",0);let tn=xt;const Ad={...me};function Ps(s){return s?{primaryClip:s,selectedClips:[s],selectionCount:1,groupKind:s.type,supportsVoiceBatch:s.type==="text"||Le(s),supportsTextContentBatch:s.type==="text",supportsVisualBatch:s.type==="video",supportsVolumeBatch:s.type==="video"||s.type==="audio"}:{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1}}function Id(s,e){return s.groupKind!==e.groupKind||s.selectionCount!==e.selectionCount||s.supportsVoiceBatch!==e.supportsVoiceBatch||s.supportsTextContentBatch!==e.supportsTextContentBatch||s.supportsVisualBatch!==e.supportsVisualBatch||s.supportsVolumeBatch!==e.supportsVolumeBatch||s.selectedClips.length!==e.selectedClips.length?!1:s.selectedClips.every((t,i)=>{var r;return t.id===((r=e.selectedClips[i])==null?void 0:r.id)})}class co{constructor(e){g(this,"container");g(this,"theme");g(this,"renderer",new tn);g(this,"onClipUpdate");g(this,"onGenerateVoice");g(this,"voiceCatalog");g(this,"currentClip",null);g(this,"selectionState",Ps(null));g(this,"activeTab","visual");g(this,"iconCache",new Map);g(this,"pendingPreferredTab",null);g(this,"selectedVoiceId",null);g(this,"activeVoiceFilterTag","男");g(this,"textDraftContent","");g(this,"followTextUpdates",!0);g(this,"voiceLoadingBusyCount",0);g(this,"isVoiceLoadingOverlayRendered",!1);g(this,"isVoiceLoadingOverlayExiting",!1);g(this,"voiceLoadingOverlayHideTimer",null);g(this,"voiceErrorMessage",null);g(this,"voicePreviewAudio",null);g(this,"previewingVoiceId",null);g(this,"handleVoicePreviewEnded",()=>{this.stopVoicePreview()});this.container=e.container,this.theme=e.theme??Ad,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",Te("OmAi-camera")),this.iconCache.set("OmAi-accept",Te("OmAi-accept")),this.iconCache.set("OmAi-loading",Te("OmAi-loading")),this.iconCache.set("OmAi-text",Te("OmAi-text")),this.renderer.mount(this.container),this.render()}setClip(e){this.setSelectionState(Ps(e))}setSelectionState(e){var l,c,h,d,u,p;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,a=r!==n,o=!Id(i,t);a&&this.stopVoicePreview(!1),this.selectionState=t,this.currentClip=t.primaryClip,a||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??"":((p=this.currentClip)==null?void 0:p.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}showVoiceGenerationLoading(){this.setVoiceGenerationBusy(!0)}hideVoiceGenerationLoading(){this.setVoiceGenerationBusy(!1)}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.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={...De(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(li.MIN,Math.min(li.MAX,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 xs{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 f;const o=this.resolveTrackTargetByY(t,r,n,e.type);if(o.status==="create_track")return{status:"create_track",trackType:e.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const c=a.find(m=>this.resolveTrackId(m)===l);if(!c)return{status:"missing_target_track_view",targetTrackId:l};const h=this.resolveTrackType(c)??((f=n.find(m=>m.id===l))==null?void 0:f.type)??null;if(h!==e.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:h};if(!this.hasOverlapOnTrack(e,c))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(e.type,l,t,r,n);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=n.filter(m=>m.type===e.type).map(m=>m.id),p=u.indexOf(l);for(let m=1;m<=u.length;m+=1){const v=p-m;if(v>=0){const S=u[v],C=a.find(k=>this.resolveTrackId(k)===S);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:S}}const T=p+m;if(T<u.length){const S=u[T],C=a.find(k=>this.resolveTrackId(k)===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,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(Me.MIN,Math.min(Me.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=Ae(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,p=Ae(d.type),f=u+p;return a=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:p}}).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 rn{constructor(e,t,i,r=100){g(this,"state");g(this,"maxHistorySize",100);g(this,"onActionUndo");g(this,"onActionRedo");g(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,t=null,i=null,r=null){return{type:"add_clip",data:{clip:e,targetTrackId:t,targetTrackSnapshot:i,targetTrackRestoreAnchor:r},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,r){return{type:"split_clip",data:{originalClip:e,clip1:t,clip2:i,sourceTrackId:(r==null?void 0:r.trackId)??null,sourceTrackSnapshot:(r==null?void 0:r.trackSnapshot)??null,sourceTrackRestoreAnchor:(r==null?void 0:r.trackRestoreAnchor)??null},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,l=null,c=null){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:r,clipAfter:n,sourceTrackSnapshot:a,targetTrackSnapshot:o,sourceTrackRestoreAnchor:l,targetTrackRestoreAnchor:c},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 _s{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(this.normalizeAddClipActionData(e.data).clip.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":{this.withClipRemovalBatch(()=>{const n=this.normalizeSplitClipActionData(e.data),a=this.target.findTrackByClipId(e.data.clip1.id)||this.target.getDefaultTrack(),o=this.resolveTrackIdForHistorySnapshot(n.sourceTrackSnapshot,n.sourceTrackId,t,n.sourceTrackRestoreAnchor);if(this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id),o){this.target.addClipToTrack(o,e.data.originalClip);return}a==null||a.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":{const n=this.normalizeMoveClipBetweenTracksActionData(e.data);this.restoreMovedClip(n.clipId,n.sourceTrackId,n.sourceTrackSnapshot,n.sourceTrackRestoreAnchor,n.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=this.normalizeAddClipActionData(e.data);let a=!1;const o=this.resolveTrackIdForHistorySnapshot(n.targetTrackSnapshot,n.targetTrackId,t,n.targetTrackRestoreAnchor);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"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.withClipRemovalBatch(()=>{const n=this.normalizeSplitClipActionData(e.data),a=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack(),o=this.resolveTrackIdForHistorySnapshot(n.sourceTrackSnapshot,n.sourceTrackId,t,n.sourceTrackRestoreAnchor);if(this.target.removeClip(e.data.originalClip.id),o){this.target.addClipToTrack(o,e.data.clip1),this.target.addClipToTrack(o,e.data.clip2);return}a==null||a.addClip(e.data.clip1),a==null||a.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":{const n=this.normalizeMoveClipBetweenTracksActionData(e.data);this.restoreMovedClip(n.clipId,n.targetTrackId,n.targetTrackSnapshot,n.targetTrackRestoreAnchor,n.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,n,a){const o=this.resolveTrackIdForHistorySnapshot(i,t??(i==null?void 0:i.id)??null,a,r);o&&this.target.moveClipToTrack(e,o),this.target.updateClip(e,n)}withClipRemovalBatch(e){return this.target.withClipRemovalBatch?this.target.withClipRemovalBatch(e):e()}normalizeRemoveClipActionData(e){return"clip"in e?e:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null}}normalizeAddClipActionData(e){return"clip"in e?e:{clip:e,targetTrackId:null,targetTrackSnapshot:null,targetTrackRestoreAnchor:null}}normalizeSplitClipActionData(e){return{...e,sourceTrackId:e.sourceTrackId??null,sourceTrackSnapshot:e.sourceTrackSnapshot??null,sourceTrackRestoreAnchor:e.sourceTrackRestoreAnchor??null}}normalizeMoveClipBetweenTracksActionData(e){return{...e,sourceTrackRestoreAnchor:e.sourceTrackRestoreAnchor??null,targetTrackRestoreAnchor:e.targetTrackRestoreAnchor??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 Rd=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],Md=new Set(["thumbnails"]);function Dd(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 As{constructor(e){g(this,"transactionStack",[]);this.history=e}createAddClipAction(e,t=null,i=null,r=null){return this.history.createAddClipAction(e,t,i,r)}recordAddClip(e,t=null,i=null,r=null){const n=this.history.createAddClipAction(e,t,i,r);return this.recordAction(n),n}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,i=null,r=null,n=null){const a={...e,duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},o={trackId:i,trackSnapshot:r,trackRestoreAnchor:n},l=this.history.createSplitClipAction(a,e,t,o);return this.recordAction(l),l}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,a,o,l=null,c=null){const h=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,a,o,l,c);return this.recordAction(h),h}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(Rd.forEach(d=>{Dd(e[d],t[d])||(r[d]=e[d],n[d]=t[d])}),Object.keys(r).length===0)return null;const a=Object.keys(r);if(a.every(d=>Md.has(d)))return null;const o=new Set(["startTime","endTime"]);if(a.includes("startTime")&&a.every(d=>o.has(d)))return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);const c=new Set(["duration","startTime","endTime"]);return a.includes("duration")&&a.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 Li(s){var e;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function Ld(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 Bd(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 kt(s){return s.length===0?0:Math.max(...s.map(e=>e.endTime))}function Od(s,e){return e<kt(s)}function Fd(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 Nd(s){const e=!s.id&&s.startTime>0;return{shouldJumpToTime:e,jumpTime:e?s.startTime:null,shouldSelectClip:!!s.id}}function Ui(s){var e;return s.applied?(s.isExecutingHistoryAction||(e=s.recordHistory)==null||e.call(s),s.applyEffects(),!0):!1}function Gd(s){return Ui({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 $d={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function zd(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 Vd(s){const e=zd(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=$d[e];return t?{url:s.src,mimeType:t,kind:"audio"}:null}class Ud{constructor(e){g(this,"container",null);g(this,"statusElement",null);g(this,"actionElement",null);g(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=Ue.background,this.container.style.color=Ue.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("button");i.className="timeline-preview-pending-overlay__action",i.style.display="none",i.style.padding="6px 12px",i.style.border="0",i.style.borderRadius="6px",i.style.cursor="pointer",i.style.background=Ue.actionBackground,i.style.color=Ue.actionText,i.textContent="刷新重试",i.addEventListener("click",this.onRetry),this.container.appendChild(t),this.container.appendChild(i),this.statusElement=t,this.actionElement=i}update(e){if(!this.container||!this.statusElement||!this.actionElement)return;const{pendingState:t,runtimeState:i}=e,r=(t==null?void 0:t.loading)??i.loading,n=!!(t!=null&&t.errorMessage)||r.status==="failed"||i.phase==="failed";if(!t&&r.status!=="loading"){this.container.style.display="none",this.actionElement.style.display="none";return}if(this.container.style.display="inline-flex",this.container.style.background=n?Ue.failedBackground:Ue.background,this.container.style.color=n?Ue.failedText:Ue.text,n){this.statusElement.textContent="媒体丢失",this.actionElement.style.display="inline-flex";return}this.statusElement.textContent=this.resolveLoadingStatusText(r.reason),this.actionElement.style.display="none"}resolveLoadingStatusText(e){switch(e){case"syncing":case"resolving-source":return"资源加载中...";case"seeking":return"正在定位预览...";case"media-pending":return"等待资源加载...";case"failed":return"媒体丢失";default:return"资源加载中..."}}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.actionElement=null}}const wr={x:.5,y:.5,scale:1},Wd=.1,Yd=8;function Pr(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function Xd(s){return Math.min(Yd,Math.max(Wd,s))}function Pe(s){return{x:Pr(s==null?void 0:s.x,wr.x),y:Pr(s==null?void 0:s.y,wr.y),scale:Xd(Pr(s==null?void 0:s.scale,wr.scale))}}function bn(s,e,t=1e-4){const i=Pe(s),r=Pe(e);return Math.abs(i.x-r.x)<=t&&Math.abs(i.y-r.y)<=t&&Math.abs(i.scale-r.scale)<=t}function ho(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 Is(s,e,t){const i=ho(s,e),r=Pe(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 uo(s,e,t,i){const r=Pe(s),n=i.width>0?i.width:1,a=i.height>0?i.height:1;return Pe({x:r.x+e/n,y:r.y+t/a,scale:r.scale})}function qd(s,e,t,i,r,n){const a=Pe(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 Pe({x:a.x,y:a.y,scale:Math.max(c,h)})}function Es(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}class jd{constructor(e={}){g(this,"frameElement",null);g(this,"overlayElement",null);g(this,"boxElement",null);g(this,"rotateHandleElement",null);g(this,"rotateHandlePointerDownHandler",null);g(this,"handleElements",new Map);g(this,"handlePointerDownHandlers",new Map);g(this,"state",null);g(this,"interaction",null);g(this,"callbacks");g(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});g(this,"boundPointerUp",()=>{this.finishInteraction(!0)});g(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});g(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});g(this,"handleMovePointerDown",e=>{var i,r,n,a;const t=e;(t.button??0)!==0||!this.state||((i=t.preventDefault)==null||i.call(t),(r=t.stopPropagation)==null||r.call(t),this.state.clipType==="text"&&((a=(n=this.callbacks).onTextTransformInteractionStart)==null||a.call(n)),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 ${ot.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 ${ot.border}`,e.style.background=ot.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=ot.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,c,h;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),this.state.clipType==="text"&&((h=(c=this.callbacks).onTextTransformInteractionStart)==null||h.call(c));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 ${ot.border}`,i.style.background=ot.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,d,u;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=this.state.clipType==="text";r&&((u=(d=this.callbacks).onTextTransformInteractionStart)==null||u.call(d));const n=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize",a=r?this.state.displayRect.left+this.state.displayRect.width/2:void 0,o=r?this.state.displayRect.top+this.state.displayRect.height/2:void 0,l=r?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:n,clipType:this.state.clipType??"video",startFontSize:r?this.state.currentFontSize:void 0,nextFontSize:r?this.state.currentFontSize:void 0,centerX:a,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor(n),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,p=i.y-this.interaction.centerY,m=Math.atan2(p,u)*(180/Math.PI)-this.interaction.startAngle,v=Math.round(this.interaction.startRotation+m);this.interaction.nextRotation=v,this.interaction.changed=v!==this.interaction.startRotation,(o=(a=this.callbacks).onRotationChange)==null||o.call(a,this.interaction.clipId,v);return}if(this.interaction.clipType==="text"&&this.interaction.startFontSize!==void 0){const u=i.x-this.interaction.centerX,p=i.y-this.interaction.centerY,f=Math.sqrt(u*u+p*p),m=(this.interaction.startCenterDistance??0)>0?f/this.interaction.startCenterDistance:1,v=Math.max(5,Math.min(300,Math.round(this.interaction.startFontSize*m)));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=uo(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,p=this.interaction.startTransform.y*this.interaction.frameSize.height;r=qd(u,p,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!bn(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,p,f;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)),(f=(p=this.callbacks).onPreviewTransformChange)==null||f.call(p,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:Es(this.frameElement.style.left),top:Es(this.frameElement.style.top),width:this.frameElement.clientWidth,height:this.frameElement.clientHeight}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}setGlobalCursor(e){var i;const t=(i=this.getDocument())==null?void 0:i.body;t&&(t.style.cursor=e||"")}}function Kd(s,e){var u;const t=s.activeClips.filter(p=>p.trackType!=="text"),i=s.nextClips.filter(p=>p.trackType!=="text"),r=s.interactionMode??"steady",n=new Map(t.map(p=>[p.trackId,p])),a=new Map(i.map(p=>[p.trackId,p])),o=new Map,l=t.filter(p=>p.trackType==="video"&&p.hasVisual).sort((p,f)=>p.trackOrder-f.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(p,f)=>!a.has(p)||r!=="steady"&&c?!1:c?s.playState==="playing"&&f==="video"&&p===h:s.playState!=="playing"||t.length<=1;return e.forEach(p=>{o.set(p.trackId,{kind:p.kind,order:p.order})}),t.forEach(p=>{o.set(p.trackId,{kind:p.trackType,order:p.trackOrder})}),i.forEach(p=>{o.set(p.trackId,{kind:p.trackType,order:p.trackOrder})}),Array.from(o.entries()).map(([p,f])=>{const m=n.get(p)||null,v=d(p,f.kind)&&a.get(p)||null;return{trackId:p,kind:f.kind,order:f.order,current:{role:"current",entry:m,playState:s.requestedPlayState??s.playState,speed:s.speed,visible:!!(m!=null&&m.hasVisual),zIndex:m?1e3-m.trackOrder:0,syncRequestId:s.syncRequestId},preload:{role:"preload",entry:v,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:s.syncRequestId}}}).sort((p,f)=>p.order-f.order)}function nn(s,e){return s.entry?e?s.entry.clip.id===e:!0:!1}function Zd(s,e){return e?!nn(s.current,e.clip.id)&&nn(s.preload,e.clip.id):!1}function Jd(s){return s.current.role="preload",s.preload.role="current",{current:s.preload,preload:s.current}}function Qd(s){return`${s.trackId}:${s.role}`}function eu(s,e){return s.role!=="preload"||!nn(s)?null:{role:"preload",entry:s.entry,playState:s.requestedPlayState,speed:1,visible:!1,zIndex:0,syncRequestId:e}}function tu(s,e){const t=e.lastIndexOf(":");if(t<=0)return null;const i=e.slice(0,t),r=e.slice(t+1);if(r!=="current"&&r!=="preload")return null;const n=s.get(i);return n?r==="current"?n.current:n.preload:null}function iu(s,e,t,i){const r=e||s.clip.src||"";switch(t){case"abort":case"emptied":return`${s.clip.id}:${r}:${t}`;case"error":case"reconcile":case"stalled":return`${s.clip.id}:${r}:${Math.floor(s.mediaTime/i)}`;default:return`${s.clip.id}:${r}`}}function ru(s){if(!s.desiredSource||!s.stableSourceUrl||!s.currentSourceKey||s.currentSourceKey!==s.nextSourceKey)return null;const e=s.objectUrl??(s.desiredSource.startsWith("blob:")?s.desiredSource:null);return{stableSourceUrl:s.stableSourceUrl,url:s.desiredSource,objectUrl:e}}function nu(s,e,t){return t?s===t||e===t:!1}function su(s){const e=s.configuredSource||null,t=e||s.assignedSource||null;let i=!1,r=null;return s.forceRecover?(i=!0,r="force-recover"):e?t!==s.desiredSource?(i=!0,r="source-mismatch"):s.networkState===s.networkEmptyState&&((s.readyState??0)>=s.haveCurrentDataState?(i=!1,r="network-empty-but-current-data-ready"):(i=!(s.isLoading||s.phase==="binding"||s.phase==="recovering"),r=i?"network-empty":"network-empty-binding-in-flight")):(i=!0,r="missing-src-attribute"),{needsRecovery:i,recoveryReason:r,actualSource:t,configuredSource:e,shouldWarn:i&&(r==="source-mismatch"||s.isActive&&s.phase!=="idle"&&s.phase!=="binding")}}function au(s,e){const t=s==="current"?Math.abs(e):1;return Math.max(.1,t*.15)}function ou(s,e,t){return!!s||e!=="reconcile"||t>1}function lu(s){return{role:s.role,entry:s.entry,playState:s.requestedPlayState,speed:s.isActive&&s.playbackRate||1,visible:s.isActive&&!!s.entry.hasVisual,zIndex:1e3-s.entry.trackOrder,syncRequestId:s.syncRequestId}}function cu(s){const e=iu(s.entry,s.desiredSource,s.reason,s.recoveryTimeBucketMs);return s.previousRecoveryKey===e?s.previousRetryCount>=s.maxImmediateRecoveryRetries?s.isBackgroundPreload?{status:"park",message:"媒体恢复失败,请等待下一次重建",parkReason:"retries-exhausted"}:{status:"fail",message:"媒体恢复失败,请刷新重试"}:{status:"continue",recoveryKey:e,retryCount:s.previousRetryCount+1}:{status:"continue",recoveryKey:e,retryCount:1}}function po(s,e){s.phase="idle",s.errorMessage=null,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,kn(s,e)}function kn(s,e=!1){s.forceRecover=e,s.retryCount=0,s.recoveryKey=null,s.expectedEmptiedEvents=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}function hu(s){po(s,!1)}function du(s){po(s,!0)}function uu(s){s.phase==="binding"&&(s.phase=s.isActive?"active":"primed"),s.isResolvingSource=!1,s.isLoading=!1,s.isBuffering=!1,s.errorMessage=null}function pu(s){!s.isLoading&&!s.isSeeking&&s.phase!=="failed"&&(s.phase=s.isActive?"active":"primed")}function gu(s,e){s.forceRecover=!0,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=null,e||(s.phase="idle")}function fu(s,e){const t=!!s.isSeeking&&!e.withinSeekThreshold,i=s.phase==="failed",r=s.isResolvingSource,n=!i&&!r&&e.hasDesiredSource&&e.sourceMatched&&!t&&e.readyState>=e.haveCurrentDataState,a=!n&&!i&&(!e.hasDesiredSource||!e.sourceMatched||s.phase==="binding"||s.phase==="recovering"||e.readyState<e.haveCurrentDataState);return s.isSeeking=t,n?(kn(s),s.isLoading=!1,s.isBuffering=!1,s.errorMessage=null,s.phase!=="failed"&&(s.phase="active")):!i&&s.phase!=="recovering"&&s.phase!=="binding"&&(s.phase=s.isActive?"active":"primed"),{failed:i,resolving:r,seeking:t,mediaUnready:a,ready:n}}function mu(s,e){s.phase="failed",s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=e,s.forceRecover=!1,s.expectedEmptiedEvents=0}function yu(s){s.isActive=!1,s.isBuffering=!1,s.isSeeking=!1}function Su(s,e){s.phase="recovering",s.errorMessage=null,s.forceRecover=!1,s.isLoading=!0,s.isResolvingSource=!1,s.isBuffering=s.isActive&&e==="playing",s.isSeeking=!1,s.consecutiveStalledCount=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}const vu=0,at=2,xr=3,Cu=2,Tu=250,bu=250,ku=100,wu=500,Pu=700,Rs=.03,xu=.5,_u=750,Ms="Arial, sans-serif",Ds="媒体丢失";function Au(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 go(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _r(s){return`"${go(s)}"`}function Iu(s){return hn(s,ln)}function Eu(s,e){return!_t(s.mode)||!e?s:{mode:Be.mode,width:e.width,height:e.height}}function _e(s){return s.getAttribute("src")||s.currentSrc||s.src||""}function rr(s){return s.getAttribute("src")||""}function Fe(s,e){const t=rr(s),i=s.currentSrc||"",r=s.src||"",n=_e(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 nr(s){return typeof HTMLVideoElement<"u"?s instanceof HTMLVideoElement:s.tagName==="VIDEO"}function Ye(s){try{s.load()}catch{}}function Ne(s){try{s.pause()}catch{}}function Ar(s){var e;try{const t=s.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function Ls(s,e){try{s.currentTime=Math.max(0,e)}catch{}}function Bi(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 Bs(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}function sn(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function Ru(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 ee(s){return{tsMs:sn(),currentTime:Number.isFinite(s.currentTime)?Number(s.currentTime.toFixed(3)):null,duration:Number.isFinite(s.duration)?Number(s.duration.toFixed(3)):null,currentSrc:_e(s)||null,srcAttribute:rr(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:Ru(s),videoWidth:nr(s)?s.videoWidth:null,videoHeight:nr(s)?s.videoHeight:null,error:s.error?{code:typeof s.error.code=="number"?s.error.code:null,message:s.error.message??null}:null}}function Ge(s){return typeof(s==null?void 0:s.then)=="function"}class Mu{constructor(e={},t={}){g(this,"container",null);g(this,"rootElement",null);g(this,"frameElement",null);g(this,"textOverlayRoot",null);g(this,"pendingOverlayElement",null);g(this,"pendingOverlayRenderer");g(this,"resizeObserver",null);g(this,"trackSlots",new Map);g(this,"textPreviewEntries",new Map);g(this,"audioContext",null);g(this,"masterGainNode",null);g(this,"loadingProbeTimeoutId",null);g(this,"clockProbeTimeoutId",null);g(this,"playbackGroupSuspended",!1);g(this,"lastRuntimeSignature",null);g(this,"lastRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});g(this,"lastSettledSyncRequestId",null);g(this,"primarySelectedClipId",null);g(this,"transientVisualTransform",null);g(this,"transientFontSize",null);g(this,"transientRotation",null);g(this,"textPreviewDragState",null);g(this,"textPreviewFontStyleElement",null);g(this,"textPreviewFontSignature",null);g(this,"textPreviewFontLoadState","idle");g(this,"textPreviewFontLoadToken",0);g(this,"callbacks");g(this,"dependencies");g(this,"transformOverlay");g(this,"boundTextPreviewPointerMove",e=>{this.handleTextPreviewPointerMove(e)});g(this,"boundTextPreviewPointerUp",()=>{this.finishTextPreviewDrag(!0)});g(this,"boundTextPreviewVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishTextPreviewDrag(!1)});g(this,"boundTextPreviewWindowBlur",()=>{this.finishTextPreviewDrag(!1)});g(this,"requestedAspectRatio",{...Be});g(this,"resolvedAutoAspectRatio",null);g(this,"aspectRatioProbe",null);g(this,"aspectRatioProbeSrc",null);g(this,"aspectRatioProbeResolveToken",0);g(this,"pendingState",null);g(this,"activeSyncRequestId");g(this,"isSyncProjecting",!1);g(this,"deferredPreloadSlotKeys",new Set);g(this,"deferredPreloadFlushScheduled",!1);g(this,"lastSyncedPlayState","paused");g(this,"pendingClockAlignmentTargetTime",null);this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new Ud(()=>{var i,r;(r=(i=this.callbacks).onPendingPreviewRetry)==null||r.call(i)}),this.transformOverlay=new jd({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=`${De(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)},onTextTransformInteractionStart:()=>{this.requestPauseIfPlaying()}})}requestPauseIfPlaying(){var e,t;this.lastSyncedPlayState==="playing"&&((t=(e=this.callbacks).onPauseIfPlaying)==null||t.call(e))}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:Xa(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:_e(e.element)||null,extra:{role:e.role,kind:e.kind,phase:e.phase,retryCount:e.retryCount,sourceState:Fe(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=_.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&&(Ne(this.aspectRatioProbe),this.aspectRatioProbe.src="",Ye(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.aspectRatioProbeResolveToken+=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.clearLoadingProbe(),this.clearClockProbe(),this.playbackGroupSuspended=!1,this.lastRuntimeSignature=null,this.lastSettledSyncRequestId=null,this.pendingClockAlignmentTargetTime=null,this.lastRuntimeState={phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},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.lastSyncedPlayState=e.playState,this.updatePendingClockAlignmentTarget(e),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=Kd(e,t).map(o=>this.applyTrackPlan(o)).filter(o=>Ge(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=je(e),this.updateFrameLayout()}getAspectRatio(){return Eu(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,nr(r)?(Br(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=_.black,r.style.pointerEvents="none"):r.style.display="none",r}createSlot(e,t,i){var P,D;const r=this.createMediaElement(t,i),n=t==="video"?document.createElement("div"):null,a=t==="video"?document.createElement("div"):null,o=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=_.black,n.style.pointerEvents="none",n.style.display="none",n.appendChild(r),a&&o&&(a.className="timeline-preview-slot__failure",a.style.position="absolute",a.style.inset="0",a.style.display="none",a.style.alignItems="center",a.style.justifyContent="center",a.style.padding="12px",a.style.boxSizing="border-box",a.style.background=_.mediaClipFailedBackground,a.style.color=_.white,a.style.pointerEvents="none",o.className="timeline-preview-slot__failure-label",o.style.fontSize="18px",o.style.fontWeight="600",o.style.lineHeight="1.2",o.style.textAlign="center",o.textContent=Ds,a.appendChild(o),n.appendChild(a)),(P=this.frameElement)==null||P.appendChild(n)}const l={role:i,trackId:e,kind:t,wrapper:n,failureOverlay:a,failureLabel:o,element:r,entry:null,stableSourceUrl:null,desiredSource:null,objectUrl:null,pendingRuntimeSourceUrl:null,pendingRuntimeSourcePromise:null,requestedPlayState:"paused",isActive:!1,isLoading:!1,isResolvingSource:!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,hasReadyEventSinceSourceChange:!1,hasBufferingSignalSinceSourceChange:!1,lastPlaybackResumeAttemptAtMs:-1,lastPlaybackProgressCheckAtMs:-1,lastPlaybackProgressMediaTimeSeconds:Number.NaN,playbackProgressStalled:!1,resolveToken:0,applyToken:0,cleanup:[]},c=w=>{var A;if(!this.shouldIgnoreClearedSlotRecoverableEvent(l)){if(w==="abort"&&this.shouldIgnoreExpectedAbort(l)){this.emitDiagnostic("debug","playback","media.abort.ignored",this.buildSlotTraceData(l,{message:"Ignored expected media abort during source reset",mediaState:ee(l.element)}));return}if(w==="emptied"&&this.shouldIgnoreExpectedEmptied(l)){this.emitDiagnostic("debug","playback","media.emptied.ignored",this.buildSlotTraceData(l,{message:"Ignored expected media emptied during source reset",mediaState:ee(l.element)}));return}if(this.emitDiagnostic(w==="error"?"error":"warn","playback",`media.${w}`,this.buildSlotTraceData(l,{message:`Media event: ${w}`,mediaState:ee(l.element),error:l.element.error})),w==="error"&&O.error("TimelinePreviewSession",`media event: ${w}`,{trackId:l.trackId,role:l.role,clipId:((A=l.entry)==null?void 0:A.clip.id)??null,phase:l.phase,mediaState:ee(l.element)}),l.forceRecover=!0,l.expectedEmptiedEvents=0,l.isLoading=!1,l.isResolvingSource=!1,l.isSeeking=!1,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),l.recoverableEventCount+=1,this.shouldSkipImmediatePreloadRecovery(l)){l.phase="idle",this.emitDiagnostic("info","recovery","preload.recovery.skipped",this.buildSlotTraceData(l,{message:"Skipped immediate preload recovery after recoverable media event",mediaState:ee(l.element),extra:{reason:w,recoverableEventCount:l.recoverableEventCount,loadStartedSinceRecover:l.loadStartedSinceRecover}})),this.refreshRuntimeState();return}if(this.refreshRuntimeState(),this.shouldDeferPreloadRecovery(l)){this.deferPreloadRecovery(l,w);return}this.recoverSlot(l,w)}},h=()=>c("abort"),d=()=>c("emptied"),u=()=>c("error"),p=()=>{l.loadStartedSinceRecover=!0,l.isLoading=!0,l.hasReadyEventSinceSourceChange=!1,l.hasBufferingSignalSinceSourceChange=!1,l.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(l),this.emitDiagnostic("debug","playback","media.loadstart",this.buildSlotTraceData(l,{message:"Media event: loadstart",mediaState:ee(l.element)})),this.refreshRuntimeState()},f=()=>{l.hasReadyEventSinceSourceChange=!0,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.maybeResumeRequestedPlayback(l,"canplay"),this.emitDiagnostic("debug","playback","media.canplay",this.buildSlotTraceData(l,{message:"Media event: canplay",mediaState:ee(l.element)})),this.refreshRuntimeState()},m=()=>{l.hasReadyEventSinceSourceChange=!0,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.emitDiagnostic("debug","playback","media.playing",this.buildSlotTraceData(l,{message:"Media event: playing",mediaState:ee(l.element)})),this.refreshRuntimeState()},v=()=>{this.refreshRuntimeState()},T=()=>{this.emitDiagnostic("debug","playback","media.pause",this.buildSlotTraceData(l,{message:"Media event: pause",mediaState:ee(l.element)})),this.refreshRuntimeState()},S=()=>{l.isBuffering=l.role==="current"&&l.isActive&&l.requestedPlayState==="playing",l.hasBufferingSignalSinceSourceChange=l.isBuffering,l.lastPlaybackResumeAttemptAtMs=-1,this.emitDiagnostic("warn","playback","media.stalled",this.buildSlotTraceData(l,{message:"Media event: stalled",mediaState:ee(l.element)})),this.refreshRuntimeState()},C=()=>{l.isBuffering=l.role==="current"&&l.isActive&&l.requestedPlayState==="playing",l.hasBufferingSignalSinceSourceChange=l.isBuffering,l.lastPlaybackResumeAttemptAtMs=-1,this.emitDiagnostic("warn","playback","media.waiting",this.buildSlotTraceData(l,{message:"Media event: waiting",mediaState:ee(l.element)})),this.refreshRuntimeState()},k=()=>{l.isSeeking=!0,this.refreshRuntimeState()},x=()=>{l.isSeeking=!1,l.hasReadyEventSinceSourceChange=!0,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.maybeResumeRequestedPlayback(l,"seeked"),this.refreshRuntimeState()};return r.addEventListener("loadstart",p),r.addEventListener("canplay",f),r.addEventListener("playing",m),r.addEventListener("progress",v),r.addEventListener("pause",T),r.addEventListener("stalled",S),r.addEventListener("waiting",C),r.addEventListener("seeking",k),r.addEventListener("seeked",x),r.addEventListener("abort",h),r.addEventListener("emptied",d),r.addEventListener("error",u),l.cleanup.push(()=>r.removeEventListener("loadstart",p),()=>r.removeEventListener("canplay",f),()=>r.removeEventListener("playing",m),()=>r.removeEventListener("progress",v),()=>r.removeEventListener("pause",T),()=>r.removeEventListener("stalled",S),()=>r.removeEventListener("waiting",C),()=>r.removeEventListener("seeking",k),()=>r.removeEventListener("seeked",x),()=>r.removeEventListener("abort",h),()=>r.removeEventListener("emptied",d),()=>r.removeEventListener("error",u)),t==="audio"&&((D=this.rootElement)==null||D.appendChild(r)),l}resetSlotRecoveryTracking(e,t=!1){kn(e,t)}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()),Ne(e.element),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.stableSourceUrl=null,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),e.element.removeAttribute("src"),Ye(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,e.isResolvingSource=!1}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&&this.trackSlots.set(e,Jd(t))}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);Zd(t,e.current.entry)&&(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(Ge(i)||Ge(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=_e(e.element)||null,a=r?this.buildPreviewSourceCacheKey(r.clip):null,o=t.entry?this.buildPreviewSourceCacheKey(t.entry.clip):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}})),Ne(e.element),e.stableSourceUrl=null,e.desiredSource=null,e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e),hu(e),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.element.removeAttribute("src"),Ye(e.element),this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}a&&o&&a!==o&&(this.releaseSlotObjectUrl(e),e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e));const l=this.resolveDesiredSource(e,t.entry,i,a);if(Ge(l))return l.then(c=>{if(!c||!this.isCurrentSourceTarget(e,t.entry,c.stableSourceUrl)){this.revokeResolvedObjectUrl(c);return}const h=this.buildCurrentTargetForSlot(e)??t;if(!h.entry){this.revokeResolvedObjectUrl(c);return}if(e.stableSourceUrl=c.stableSourceUrl,e.desiredSource=c.url,this.configureAudioRouting(e,h.entry),this.slotNeedsRecovery(e,c.url)){if(this.shouldDeferPreloadTarget(e,h,c.url)){this.deferPreloadTarget(e,h,c,"current-loading");return}return Promise.resolve(this.recoverSlot(e,"reconcile",h,void 0,c)).then(()=>{})}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,c.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,h)});if(!l||!this.isCurrentRequest(e,i,t.entry)){this.revokeResolvedObjectUrl(l);return}if(e.stableSourceUrl=l.stableSourceUrl,e.desiredSource=l.url,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,l.url)){if(this.shouldDeferPreloadTarget(e,t,l.url)){this.deferPreloadTarget(e,t,l,"current-loading");return}return this.recoverSlot(e,"reconcile",t,i,l)}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,l.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,t)}settleResolvedSourceWithoutRecovery(e){uu(e)}resolveDesiredSource(e,t,i,r){const n=this.getReusableBoundSlotSource(e,t,r);if(n)return n;const a=this.dependencies.previewSourceResolver??Vd,o=this.dependencies.sourceMediaRegistry;let l=null;const c=()=>(l!==null||(e.resolveToken+=1,l=e.resolveToken,e.phase="binding",e.isResolvingSource=!0,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:l}})),this.refreshRuntimeState()),l);if(!a){const h={url:t.clip.src};return this.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),l)}try{const h=o?o.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>a(t.clip)):a(t.clip);if(Ge(h)){const d=c();return h.then(u=>d!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:u?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:u.url,extra:{mimeType:u.mimeType,mediaKind:u.kind}})),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,u),d)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(u=>(this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:u})),O.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:u}),this.failSlot(e,t,"预览源解析失败"),null))}return 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.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),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(h){return 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}}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,sizeBytes: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,sizeBytes: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,sizeBytes:d.sizeBytes??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(Ge(c)){e.isResolvingSource=!0,e.isLoading=!0,e.phase="binding",this.refreshRuntimeState();const d=c.then(h).catch(()=>a()?null:l());return d.finally(()=>{e.pendingRuntimeSourcePromise===d&&(this.clearPendingRuntimeSource(e),this.refreshRuntimeState())}).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:_e(e.element)||null,mediaState:ee(e.element),extra:{stableSourceUrl:t,runtimeSourceUrl:(i==null?void 0:i.url)??null,objectUrl:(i==null?void 0:i.objectUrl)??null,sourceState:Fe(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,sizeBytes:null}}getReusableBoundSlotSource(e,t,i){const r=i??(e.entry?this.buildPreviewSourceCacheKey(e.entry.clip):null);if(!r)return null;const n=ru({currentSourceKey:r,nextSourceKey:this.buildPreviewSourceCacheKey(t.clip),desiredSource:e.desiredSource,stableSourceUrl:e.stableSourceUrl,objectUrl:e.objectUrl});return n?{...n,sizeBytes:null}:null}slotNeedsRecovery(e,t){const i=su({desiredSource:t,configuredSource:rr(e.element)||null,assignedSource:_e(e.element)||null,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,phase:e.phase,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,networkEmptyState:vu,haveCurrentDataState:at});return this.emitDiagnostic(i.shouldWarn?"warn":"debug","recovery","slot.recovery-check",this.buildSlotTraceData(e,{message:i.needsRecovery?"Preview slot needs recovery":"Preview slot source is reusable",desiredSourceUrl:t,actualSourceUrl:i.actualSource,mediaState:ee(e.element),extra:{needsRecovery:i.needsRecovery,recoveryReason:i.recoveryReason,configuredSource:i.configuredSource,actualSource:i.actualSource,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:Fe(e.element,t)}})),i.needsRecovery}recoverSlot(e,t,i,r,n){const a=i??(e.entry?{...lu({role:e.role,entry:e.entry,requestedPlayState:e.requestedPlayState,isActive:e.isActive,playbackRate:e.element.playbackRate||1,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,sizeBytes:null}:this.resolveDesiredSource(e,e.entry,e.applyToken));if(Ge(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=cu({entry:e.entry,desiredSource:o,reason:t,previousRecoveryKey:e.recoveryKey,previousRetryCount:e.retryCount,maxImmediateRecoveryRetries:Cu,recoveryTimeBucketMs:Tu,isBackgroundPreload:this.isBackgroundPreloadSlot(e)});if(l.status==="park"){this.parkPreloadSlot(e,l.message,l.parkReason);return}if(l.status==="fail"){this.failSlot(e,e.entry,l.message);return}e.recoveryKey=l.recoveryKey,e.retryCount=l.retryCount,Su(e,i.playState),this.refreshRuntimeState(),this.emitDiagnostic(t==="reconcile"?"info":"warn","recovery","slot.recover",this.buildSlotTraceData(e,{message:"Recovering preview slot",desiredSourceUrl:o,mediaState:ee(e.element),extra:{reason:t,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState}})),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:ee(e.element)});const c=_e(e.element),h=Fe(e.element,o),d=ou(c||null,t,e.retryCount);Ne(e.element),e.expectedEmptiedEvents=d?2:1,e.stableSourceUrl=a.stableSourceUrl,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),this.rememberSlotObjectUrl(e,a.objectUrl),d&&(e.element.removeAttribute("src"),Ye(e.element)),e.element.setAttribute("src",o),Ye(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:Fe(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 Qd(e)}isActiveCurrentSlot(e){return e.role==="current"&&e.isActive&&!!e.entry}isTrackedActiveCurrentVideoSlot(e){return this.isActiveCurrentSlot(e)&&e.kind==="video"}hasBlockingActiveCurrentSlot(e){for(const{current:t}of this.trackSlots.values()){if(e&&this.getSlotKey(t)===e||!this.isTrackedActiveCurrentVideoSlot(t))continue;const i=this.evaluateTrackedCurrentVideoSlot(t);if(!i.ready&&!i.failed)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 eu(e,this.activeSyncRequestId)}deferPreloadTarget(e,t,i,r){const n=i.url;e.desiredSource=n,this.rememberSlotObjectUrl(e,i.objectUrl),e.element.getAttribute("src")&&e.element.getAttribute("src")!==n&&(Ne(e.element),e.element.removeAttribute("src"),Ye(e.element)),_e(e.element)||(e.hasReadyEventSinceSourceChange=!1),gu(e,!!_e(e.element)),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=tu(this.trackSlots,t);if(!i||i.role!=="preload"||!i.entry)continue;const r=this.buildDeferredPreloadTarget(i);if(r){if(this.emitDiagnostic("info","recovery","preload.recovery.resumed",this.buildSlotTraceData(i,{message:"Resumed deferred preload recovery",desiredSourceUrl:i.desiredSource,extra:{requestedPlayState:i.requestedPlayState}})),i.desiredSource&&this.slotNeedsRecovery(i,i.desiredSource)){this.recoverSlot(i,"reconcile",r);continue}this.resetSlotRecoveryTracking(i),this.applyResolvedSlotState(i,r)}}}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),pu(e),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){Ne(e.element),this.releaseSlotObjectUrl(e),e.element.removeAttribute("src"),Ye(e.element),e.hasReadyEventSinceSourceChange=!1,du(e),this.emitDiagnostic("warn","recovery","preload.recovery.parked",this.buildSlotTraceData(e,{message:"Background preload parked until next steady sync",mediaState:ee(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}mu(e,i),this.emitDiagnostic("error","recovery","slot.failed",this.buildSlotTraceData(e,{message:"Preview slot failed",mediaState:ee(e.element),extra:{errorMessage:i}})),O.error("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,mediaState:ee(e.element)}),this.refreshVisualLayout(),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(r==="playing"?xu:.1,i*.15),o=r==="playing"&&!e.element.ended,l=this.doesSlotSourceMatchDesired(e,e.desiredSource),c=typeof e.element.readyState=="number"?e.element.readyState:0;if(this.updateSlotPlaybackProgressState(e,{shouldBePlaying:o,sourceMatched:l,readyState:c,speed:i}),!e.playbackProgressStalled&&Math.abs(e.element.currentTime-n)>a&&(this.emitDiagnostic("debug","playback","media.current-slot.seek",this.buildSlotTraceData(e,{message:"Current slot seek applied",mediaState:ee(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,Ls(e.element,n)),r==="playing"){this.resumeAudioContext();const d=Fe(e.element,e.desiredSource);e.element.paused&&(this.emitDiagnostic(d.hasSrcAttribute?"debug":"warn","playback","media.play.requested",this.buildSlotTraceData(e,{message:d.hasSrcAttribute?"Media play requested":"Media play requested without configured src attribute",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:d}})),Ar(e.element))}else this.emitDiagnostic("debug","playback","media.pause.requested",this.buildSlotTraceData(e,{message:"Media pause requested",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:Fe(e.element,e.desiredSource)}})),Ne(e.element);this.setSlotVisible(e,t.hasVisual,1e3-t.trackOrder)}resetSlotPlaybackProgressProbe(e){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN,e.playbackProgressStalled=!1}updateSlotPlaybackProgressState(e,t){const i=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN;if(!(t.shouldBePlaying&&e.role==="current"&&e.isActive&&t.sourceMatched&&t.readyState>=at&&!e.element.paused&&!e.element.ended&&!e.isSeeking&&Number.isFinite(i))){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN;return}const n=sn(),a=e.lastPlaybackProgressMediaTimeSeconds,o=e.lastPlaybackProgressCheckAtMs;if(o<0||!Number.isFinite(a)){e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}const l=i-a;if(l>Rs||l<-Rs){e.playbackProgressStalled&&this.emitDiagnostic("info","playback","media.progress.recovered",this.buildSlotTraceData(e,{message:"Media playback progress recovered",mediaState:ee(e.element),extra:{previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3)),advancedSeconds:Number(l.toFixed(3))}})),e.playbackProgressStalled=!1,e.hasBufferingSignalSinceSourceChange||(e.isBuffering=!1),e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}n-o<Pu||(e.playbackProgressStalled||this.emitDiagnostic("warn","playback","media.progress.stalled",this.buildSlotTraceData(e,{message:"Media playback progress stalled without waiting event",mediaState:ee(e.element),extra:{stalledForMs:n-o,speed:t.speed,previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3))}})),e.playbackProgressStalled=!0,e.isBuffering=!0)}maybeResumeRequestedPlayback(e,t){if(e.role!=="current"||!e.isActive||!e.entry||e.requestedPlayState!=="playing"||e.element.paused!==!0||this.playbackGroupSuspended)return;const i=Fe(e.element,e.desiredSource);if(!i.hasSrcAttribute)return;const r=sn();t==="runtime-check"&&(!this.canRuntimeCheckRetryBufferedPlayback(e)||e.lastPlaybackResumeAttemptAtMs>=0&&r-e.lastPlaybackResumeAttemptAtMs<wu)||(e.lastPlaybackResumeAttemptAtMs=r,this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.play.retried",this.buildSlotTraceData(e,{message:"Retried media play after ready event",mediaState:ee(e.element),extra:{reason:t,playState:e.requestedPlayState,speed:e.element.playbackRate||1,sourceState:i}})),Ar(e.element))}canRuntimeCheckRetryBufferedPlayback(e){return e.hasBufferingSignalSinceSourceChange?(typeof e.element.readyState=="number"?e.element.readyState:0)>=xr&&!e.isSeeking&&!e.playbackProgressStalled:!0}shouldClearRecoveredBufferingSignal(e,t){return t.shouldBePlaying&&e.hasBufferingSignalSinceSourceChange&&e.lastPlaybackResumeAttemptAtMs>=0&&!e.playbackProgressStalled&&!e.isSeeking&&t.readyState>=xr&&!t.pausedWhilePlaying}preparePreloadSlot(e,t){yu(e),e.entry=t,e.element.playbackRate=1,e.hasReadyEventSinceSourceChange=!1,this.emitDiagnostic("debug","playback","media.preload-slot.seek",this.buildSlotTraceData(e,{message:"Preload slot primed",mediaState:ee(e.element),extra:{toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3))}})),Ls(e.element,t.clip.startTimeAtSource/1e3),Ne(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),this.syncSlotFailureVisualState(e)}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(!_t(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=Bi(e,"sys_width"),i=Bi(e,"sys_height");if(t&&i){this.handleResolvedAutoAspectRatio(t,i);return}if(this.aspectRatioProbeSrc===e.clip.id)return;const r=++this.aspectRatioProbeResolveToken;(async()=>{const a=await this.resolveAspectRatioProbeSource(e,r);if(!a||r!==this.aspectRatioProbeResolveToken)return;const o=this.getAspectRatioProbe();this.aspectRatioProbeSrc=e.clip.id,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,Ye(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(!Ge(n))return(n==null?void 0:n.url)??null;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");Br(e);const t=()=>{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.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(!_t(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(),_t(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var m,v,T,S,C,k,x,P;const e=[];let t=null,i=!1,r=0,n=0,a=!1,o=!1,l=!1,c=!1;for(const{current:D,preload:w}of this.trackSlots.values())for(const A of[D,w]){const B=this.isTrackedActiveCurrentVideoSlot(A),$=B?this.evaluateTrackedCurrentVideoSlot(A):null,F=_e(A.element)||null;e.push({trackId:A.trackId,role:A.role,kind:A.kind,clipId:((m=A.entry)==null?void 0:m.clip.id)??null,desiredSource:A.desiredSource,actualSource:F,phase:A.phase,retryCount:A.retryCount,errorMessage:A.errorMessage}),A.phase!=="idle"&&(i=!0),B&&(r+=1,$!=null&&$.failed&&(n+=1,a=!0,t||(t=A.errorMessage||"资源加载异常,请刷新重试")),$!=null&&$.resolving&&(o=!0),$!=null&&$.seeking&&(l=!0),$!=null&&$.mediaUnready&&(c=!0))}const h=this.buildPreviewLoadingState({trackedActiveCurrentVideoSlotCount:r,failedTrackedCurrentVideoSlotCount:n,hasFailedTrackedVideoSlot:a,hasResolvingTrackedVideoSlot:o,hasSeekingTrackedVideoSlot:l,hasMediaUnreadyTrackedVideoSlot:c});this.syncActivePlaybackGroupSuspension(h,r);let d="idle";h.status==="failed"?d="failed":h.status==="loading"&&h.reason==="syncing"?d="awaiting-sync":h.status==="loading"?d="awaiting-media":(r>0&&h.status==="ready"||i)&&(d="ready"),h.status!=="failed"&&(t=null);const u={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:d,loading:h,clock:this.buildPreviewClockState(h),errorMessage:t,slots:e},p=this.lastRuntimeState,f=JSON.stringify(u);f!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=f,this.lastRuntimeState=u,(p.phase!==u.phase||p.loading.status!==u.loading.status||p.loading.reason!==u.loading.reason||p.loading.isLoading!==u.loading.isLoading||p.errorMessage!==u.errorMessage)&&this.emitDiagnostic(u.phase==="failed"?"error":"info","runtime","runtime.state",{message:"Preview runtime state updated",syncRequestId:u.syncRequestId??null,runtimeState:{runtimePhase:u.phase,loadingStatus:u.loading.status,loadingReason:u.loading.reason,isLoading:u.loading.isLoading,clockStatus:((v=u.clock)==null?void 0:v.status)??"unavailable",clockReason:((T=u.clock)==null?void 0:T.reason)??null,clockTimelineTime:((S=u.clock)==null?void 0:S.timelineTime)??null},extra:{previousPhase:p.phase,phase:u.phase,errorMessage:u.errorMessage,loading:u.loading,slots:u.slots.map(D=>({trackId:D.trackId,role:D.role,clipId:D.clipId,phase:D.phase,retryCount:D.retryCount,desiredSource:D.desiredSource,actualSource:D.actualSource}))}}),(k=(C=this.callbacks).onRuntimeStateChange)==null||k.call(C,u)),(h.status==="ready"||h.status==="failed"||h.status==="idle")&&u.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==u.syncRequestId&&(this.lastSettledSyncRequestId=u.syncRequestId,(P=(x=this.callbacks).onSyncProcessed)==null||P.call(x,u.syncRequestId)),h.status!=="loading"&&this.deferredPreloadSlotKeys.size>0&&this.scheduleDeferredPreloadFlush(),this.syncLoadingProbe(h),this.syncClockProbe(u.clock),this.refreshPendingOverlay()}buildPreviewClockState(e){const t=this.getPreviewClockSourceSlot();if(!(t!=null&&t.entry))return this.buildPreviewClockStateFromSlot(null,"unavailable","no-video-clock");const i=this.doesSlotSourceMatchDesired(t,t.desiredSource),r=this.getSlotMediaTimeMs(t),n=this.getSlotTimelineTime(t,r),a=t.requestedPlayState==="playing"&&!t.element.ended;return e.status==="failed"||t.phase==="failed"?this.buildPreviewClockStateFromSlot(t,"failed","failed",n,r):a?!i||t.isResolvingSource||t.phase==="binding"?this.buildPreviewClockStateFromSlot(t,"priming","resolving-source",n,r):t.isSeeking||e.reason==="seeking"?this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):t.isBuffering||t.playbackProgressStalled?this.buildPreviewClockStateFromSlot(t,"blocked","media-stalled",n,r):this.isPreviewClockSlotAlignedToPendingTarget(t,n)?e.status==="loading"?this.buildPreviewClockStateFromSlot(t,"blocked",this.resolveClockBlockedReason(e.reason),n,r):t.element.paused?this.buildPreviewClockStateFromSlot(t,"blocked","media-paused",n,r):n===null||r===null?this.buildPreviewClockStateFromSlot(t,"priming","media-pending",n,r):(this.pendingClockAlignmentTargetTime=null,this.buildPreviewClockStateFromSlot(t,"running",null,n,r)):this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):this.buildPreviewClockStateFromSlot(t,"unavailable",null,n,r)}buildPreviewClockStateFromSlot(e,t,i,r=null,n=null){var a;return{status:t,timelineTime:r,mediaTime:n,clipId:((a=e==null?void 0:e.entry)==null?void 0:a.clip.id)??null,trackId:(e==null?void 0:e.trackId)??null,reason:i}}resolveClockBlockedReason(e){return e==="syncing"||e==="resolving-source"||e==="seeking"||e==="media-pending"||e==="failed"?e:"media-pending"}getPreviewClockSourceSlot(){var t,i;const e=[];for(const{current:r}of this.trackSlots.values())this.isTrackedActiveCurrentVideoSlot(r)&&((t=r.entry)!=null&&t.hasVisual)&&e.push(this.buildPreviewClockSourceCandidate(r));return e.length===0?(this.pendingClockAlignmentTargetTime=null,null):(e.sort((r,n)=>this.comparePreviewClockSourceCandidates(r,n)),((i=e[0])==null?void 0:i.slot)??null)}buildPreviewClockSourceCandidate(e){const t=this.getSlotMediaTimeMs(e),i=this.getSlotTimelineTime(e,t),r=this.doesSlotSourceMatchDesired(e,e.desiredSource),n=typeof e.element.readyState=="number"?e.element.readyState:0,a=this.pendingClockAlignmentTargetTime===null||i===null?Number.POSITIVE_INFINITY:Math.abs(i-this.pendingClockAlignmentTargetTime),o=e.requestedPlayState==="playing"&&!e.element.ended,l=n>=at||e.hasReadyEventSinceSourceChange,c=!!e.entry&&r&&l&&!e.isResolvingSource&&e.phase!=="binding"&&e.phase!=="failed"&&!e.isSeeking&&!e.isBuffering&&!e.playbackProgressStalled&&(!o||!e.element.paused)&&t!==null&&i!==null;return{slot:e,timelineTime:i,targetDistance:a,sourceMatched:r,readyState:n,usable:c}}comparePreviewClockSourceCandidates(e,t){var n,a;const i=this.isPreviewClockCandidateAlignedToTarget(e),r=this.isPreviewClockCandidateAlignedToTarget(t);return i!==r?i?-1:1:this.pendingClockAlignmentTargetTime!==null&&e.targetDistance!==t.targetDistance?e.targetDistance-t.targetDistance:e.usable!==t.usable?e.usable?-1:1:e.sourceMatched!==t.sourceMatched?e.sourceMatched?-1:1:e.readyState!==t.readyState?t.readyState-e.readyState:(((n=e.slot.entry)==null?void 0:n.trackOrder)??0)-(((a=t.slot.entry)==null?void 0:a.trackOrder)??0)}isPreviewClockCandidateAlignedToTarget(e){return this.pendingClockAlignmentTargetTime!==null&&e.usable&&e.targetDistance<=this.getPreviewClockTargetAlignmentThresholdMs(e.slot)}getPreviewClockTargetAlignmentThresholdMs(e){return Math.max(_u,this.getSlotSeekThresholdSeconds(e)*1e3)}isPreviewClockSlotAlignedToPendingTarget(e,t){return this.pendingClockAlignmentTargetTime===null||t===null?!0:Math.abs(t-this.pendingClockAlignmentTargetTime)<=this.getPreviewClockTargetAlignmentThresholdMs(e)}updatePendingClockAlignmentTarget(e){if(!e.activeClips.some(i=>i.trackType==="video"&&i.hasVisual)){this.pendingClockAlignmentTargetTime=null;return}(e.interactionMode==="seek"||e.interactionMode==="scrub")&&(this.pendingClockAlignmentTargetTime=e.currentTime)}syncActivePlaybackGroupSuspension(e,t){var n;const i=((n=this.pendingState)==null?void 0:n.mode)==="seek";if(t>1&&!i&&(e.status==="loading"||e.status==="failed")){this.playbackGroupSuspended=!0;for(const{current:a}of this.trackSlots.values())!this.isActiveCurrentSlot(a)||a.requestedPlayState!=="playing"||a.isBuffering||a.playbackProgressStalled||a.isSeeking||a.isResolvingSource||a.phase==="binding"||a.phase==="recovering"||a.element.paused||(this.emitDiagnostic("debug","playback","media.group-pause.requested",this.buildSlotTraceData(a,{message:"Paused active media while preview playback group is blocked",mediaState:ee(a.element),extra:{loadingStatus:e.status,loadingReason:e.reason}})),Ne(a.element));return}if(this.playbackGroupSuspended){this.playbackGroupSuspended=!1;for(const{current:a}of this.trackSlots.values()){if(!this.isActiveCurrentSlot(a)||a.requestedPlayState!=="playing"||!a.element.paused||a.element.ended)continue;const o=Fe(a.element,a.desiredSource);o.hasSrcAttribute&&(this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.group-play.requested",this.buildSlotTraceData(a,{message:"Resumed active media after preview playback group became ready",mediaState:ee(a.element),extra:{loadingStatus:e.status,loadingReason:e.reason,sourceState:o}})),Ar(a.element))}}}getSlotMediaTimeMs(e){return Number.isFinite(e.element.currentTime)?Math.max(0,e.element.currentTime*1e3):null}getSlotTimelineTime(e,t=this.getSlotMediaTimeMs(e)){if(!e.entry||t===null)return null;const i=e.entry.clip,r=i.startTime+(t-i.startTimeAtSource);return Math.max(i.startTime,Math.min(i.endTime,r))}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.lastRuntimeState})}buildPreviewLoadingState(e){return e.trackedActiveCurrentVideoSlotCount<=0?{status:"idle",isLoading:!1,reason:null}:e.hasFailedTrackedVideoSlot&&e.failedTrackedCurrentVideoSlotCount>=e.trackedActiveCurrentVideoSlotCount?{status:"failed",isLoading:!1,reason:"failed"}:this.activeSyncRequestId!==void 0&&this.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:e.hasResolvingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"resolving-source"}:e.hasSeekingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"seeking"}:e.hasMediaUnreadyTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}evaluateTrackedCurrentVideoSlot(e){if(!this.isTrackedActiveCurrentVideoSlot(e)||!e.entry)return{failed:!1,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1};const t=e.desiredSource,i=this.doesSlotSourceMatchDesired(e,t),r=typeof e.element.readyState=="number"?e.element.readyState:0,n=e.entry.mediaTime/1e3,a=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN,o=this.getSlotSeekThresholdSeconds(e),l=Number.isFinite(a)&&Math.abs(a-n)<=o,c=e.requestedPlayState==="playing"&&!e.element.ended,h=r>=at;let d=c&&e.element.paused&&!this.playbackGroupSuspended;d&&(this.maybeResumeRequestedPlayback(e,"runtime-check"),d=c&&e.element.paused&&!this.playbackGroupSuspended),this.shouldClearRecoveredBufferingSignal(e,{shouldBePlaying:c,readyState:r,pausedWhilePlaying:d})&&(e.hasBufferingSignalSinceSourceChange=!1,e.isBuffering=!1),this.playbackGroupSuspended&&e.playbackProgressStalled&&!e.hasBufferingSignalSinceSourceChange&&r>=xr&&(e.playbackProgressStalled=!1,e.isBuffering=!1),this.updateSlotPlaybackProgressState(e,{shouldBePlaying:c,sourceMatched:i,readyState:r,speed:e.element.playbackRate||1}),c&&e.isBuffering&&!e.hasBufferingSignalSinceSourceChange&&!e.playbackProgressStalled&&h&&!d&&(e.isBuffering=!1);const u=e.hasReadyEventSinceSourceChange&&!e.isBuffering,f=!(c&&(e.isBuffering||e.playbackProgressStalled))&&!d&&(h||!c&&e.hasReadyEventSinceSourceChange||c&&u),m=fu(e,{hasDesiredSource:!!t,sourceMatched:i,withinSeekThreshold:l,readyState:f?at:Math.min(r,at-1),haveCurrentDataState:at});return m.ready&&this.tryResolveAutoAspectRatioFromSlot(e),m}doesSlotSourceMatchDesired(e,t){return nu(rr(e.element)||null,_e(e.element)||null,t)}getSlotSeekThresholdSeconds(e){return au(e.role,e.element.playbackRate||1)}finalizeSourceResolutionResult(e,t,i){return i===null?(e.isResolvingSource=!1,t):Ge(t)?t.finally(()=>{e.resolveToken===i&&(e.isResolvingSource=!1,this.refreshRuntimeState())}):(e.resolveToken===i&&(e.isResolvingSource=!1),t)}syncLoadingProbe(e){if(e.status!=="loading"){this.clearLoadingProbe();return}this.loadingProbeTimeoutId||(this.loadingProbeTimeoutId=setTimeout(()=>{this.loadingProbeTimeoutId=null,this.refreshRuntimeState()},bu))}syncClockProbe(e){if(!((e==null?void 0:e.status)==="running"||(e==null?void 0:e.status)==="blocked"||(e==null?void 0:e.status)==="priming")){this.clearClockProbe();return}this.clockProbeTimeoutId||(this.clockProbeTimeoutId=setTimeout(()=>{this.clockProbeTimeoutId=null,this.refreshRuntimeState()},ku))}clearLoadingProbe(){this.loadingProbeTimeoutId&&(clearTimeout(this.loadingProbeTimeoutId),this.loadingProbeTimeoutId=null)}clearClockProbe(){this.clockProbeTimeoutId&&(clearTimeout(this.clockProbeTimeoutId),this.clockProbeTimeoutId=null)}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=De(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=Au(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=De(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.requestPauseIfPlaying(),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=uo(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=a,t.changed=!bn(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 ${ot.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"?Ms:`${_r(e.fontName)}, ${Ms}`}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: ${_r(e.fontName)};`,`src: url("${go(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 ${_r(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=Is(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`,this.syncSlotFailureVisualState(e)}syncSlotFailureVisualState(e){if(e.kind!=="video"||!e.wrapper||!e.failureOverlay||!e.failureLabel)return;const t=e.phase==="failed"&&!!e.entry;e.wrapper.style.background=t?_.mediaClipFailedBackground:_.black,e.failureOverlay.style.display=t?"flex":"none",e.failureLabel.textContent=Ds,e.element.style.visibility=t?"hidden":"visible"}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:ho(e,n),displayRect:Is(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=De(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,p=(n.element.offsetHeight||0)*d,f=e.width*a.x,m=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:f-u/2,top:m-p/2,width:u,height:p,centerX:f,centerY:m},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:Bs((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:Bs((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=Iu(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(nr(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=Bi(t,"sys_width"),n=Bi(t,"sys_height");return r&&n?{width:r,height:n}:{width:i.width,height:i.height}}getEffectiveVisualTransform(e){var t;return((t=this.transientVisualTransform)==null?void 0:t.clipId)===e.clip.id?this.transientVisualTransform.transform:Pe(e.clip.visualTransform)}}class Du extends Mu{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 Lu(s){return"dom"}const Bu=36e5,Ou=3e5;function an(s){return s.length===0?0:s.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function Os(s){return an(s)}function Fs(s){return Math.max(s+Ou,Bu)}class Ns{constructor(e={}){g(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(r){O.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function Fu(s){return[...s].sort((e,t)=>e.order-t.order)}function Nu(s){return[...s].sort((e,t)=>e.startTime-t.startTime)}function Ir(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 Gu{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t,i={}){const r=Fu(e),n=[],a=[];let o=null;for(const l of r){const c=Nu(l.clips),h=c.find(u=>t>=u.startTime&&t<u.endTime?!0:!!i.includeEndedClipsAtTime&&t>=u.startTime&&t===u.endTime);if(h){const u=h.startTimeAtSource+(t-h.startTime);n.push(Ir(l,h,u))}const d=c.find(u=>u.startTime>t);if(d&&a.push(Ir(l,d,d.startTimeAtSource)),!o&&l.type==="video"){const u=c[0];u&&(o=Ir(l,u,u.startTimeAtSource))}}return{activeClips:n,nextClips:a,firstVideoClip:o}}}class Hu{constructor(e){g(this,"options");g(this,"_previewSession");g(this,"_previewMountContainer",null);g(this,"_resolvedPreviewBackend","dom");g(this,"_runtimePreviewBackendOverride",null);g(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const $u=1e3;class zu{constructor(e){g(this,"callbacks");g(this,"failedOverlayDelayMs");g(this,"_previewLoadingState",{status:"idle",isLoading:!1,reason:null});g(this,"_pendingPreviewState",null);g(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.failedOverlayDelayMs=e.failedOverlayDelayMs??$u}get previewLoadingState(){return this._previewLoadingState}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)}handleRuntimeStateChange(e){const t=this._previewLoadingState;this._previewLoadingState=e.loading,this._pendingPreviewState&&e.syncRequestId===this._pendingPreviewState.syncRequestId&&(e.loading.reason!=="syncing"&&(this._pendingPreviewState.awaitingSync=!1),e.loading.status==="failed"?this.scheduleFailedOverlay(e.errorMessage||"资源加载异常,请刷新重试"):(this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.errorMessage=null)),Gs(t,e.loading)||this.callbacks.emitLoadingStateChange(e.loading),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,loading:this.resolvePendingLoadingState(),errorMessage:this._pendingPreviewState.errorMessage}:this.buildPlaybackLoadingOverlayState()}updatePendingPreviewState(){if(!this._pendingPreviewState){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const t=this.resolvePendingLoadingState().status==="loading";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(t){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const i=this._pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),i&&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={status:"idle",isLoading:!1,reason:null};Gs(this._previewLoadingState,e)||(this._previewLoadingState=e,this.callbacks.emitLoadingStateChange(e))}resolvePendingLoadingState(){var e;return(e=this._pendingPreviewState)!=null&&e.awaitingSync?{status:"loading",isLoading:!0,reason:"syncing"}:this._previewLoadingState}buildPlaybackLoadingOverlayState(){return this._previewLoadingState.status!=="loading"||this._previewLoadingState.reason!=="media-pending"?null:{mode:"playback",targetTime:0,loading:this._previewLoadingState,errorMessage:null}}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)}}function Gs(s,e){return s.status===e.status&&s.isLoading===e.isLoading&&s.reason===e.reason}const Vu=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Uu={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 Wu(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function Yu(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 Xu(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=Yu(c);if(!h||r)return null;r=h}}return r?{action:s,code:r,altKey:n,ctrlKey:a,metaKey:o,shiftKey:l}:null}function qu(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 ju(s,e){return s.code===e.code&&s.altKey===e.altKey&&s.ctrlKey===e.ctrlKey&&s.metaKey===e.metaKey&&s.shiftKey===e.shiftKey}function Ku(s,e){return s===!1||(s==null?void 0:s.enabled)===!1?[]:Vu.flatMap(t=>{var n;const i=(n=s==null?void 0:s.bindings)==null?void 0:n[t];return(i===void 0?Uu[t]:Array.isArray(i)?i:[i]).map(a=>Xu(t,a,e)).filter(a=>a!==null)})}class Zu{constructor(e){g(this,"callbacks");g(this,"bindings");g(this,"enabled");g(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??Wu();e.root,this.callbacks=e.callbacks,this.bindings=Ku(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(qu(e.target))return;const t=this.bindings.find(i=>ju(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 fo(s){var t;const e=s.getPrimarySelectedClip()||((t=s.findFallbackSelectedClip)==null?void 0:t.call(s))||null;return{clip:e,hasSelectedClip:!!e}}function Ju(s){const e=fo(s),t=s.getSelectedClipIds(),i=s.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:s.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function Qu(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)}class ep{constructor(e){g(this,"cleanupEmptyTracks",!1);g(this,"durationDirty",!1);g(this,"canPlayDirty",!1);g(this,"selectionDirty",!1);g(this,"trackLayoutDirty",!1);g(this,"trackInfoDirty",!1);g(this,"stageDirty",!1);g(this,"previewDirty",!1);g(this,"committed",!1);g(this,"events",[]);this.options=e}addClipToTrack(e,t){const i=this.options.addClipToTrack?this.options.addClipToTrack(e,t):this.options.trackCollection.addClipToTrack(e,t);return i&&this.markStructureMutation(),i}removeClip(e){this.options.removeClip?this.options.removeClip(e):this.options.trackCollection.removeClip(e),this.markStructureMutation()}removeClipFromTrack(e,t){const i=this.options.removeClipFromTrack?this.options.removeClipFromTrack(e,t):this.options.trackCollection.removeClipFromTrack(e,t);return i&&this.markStructureMutation(),i}updateClip(e,t){this.options.updateClip?this.options.updateClip(e,t):this.options.trackCollection.updateClip(e,t),this.markClipStateMutation()}moveClipToTrack(e,t){const i=this.findTrackByClipId(e),r=this.getClips().find(o=>o.id===e)??null,n=i?this.resolveTrackId(i):null;if(!r||!n)return!1;const a=this.options.moveClipToTrack?this.options.moveClipToTrack(r,n,t):this.options.trackCollection.moveClipToTrack(r,n,t);return a&&this.markStructureMutation(),a}ensureTrackFromHistorySnapshot(e,t){const i=this.options.ensureTrackFromHistorySnapshot(e,t);return i&&this.markTrackLayoutMutation(),i}removeClipGaps(){this.options.removeClipGaps(),this.markStructureMutation()}getClips(){return this.options.getClips?this.options.getClips():this.options.trackCollection.getAllClips()}findTrackByClipId(e){return this.options.findTrackByClipId?this.options.findTrackByClipId(e):this.options.trackCollection.findTrackByClipId(e)}getDefaultTrack(){return this.options.getDefaultTrack?this.options.getDefaultTrack():this.options.trackCollection.getDefaultTrack()}queueEvent(e,t){this.events.push({type:e,payload:t})}markStructureMutation(){this.cleanupEmptyTracks=!0,this.durationDirty=!0,this.canPlayDirty=!0,this.selectionDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}markClipStateMutation(){this.durationDirty=!0,this.canPlayDirty=!0,this.selectionDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}markTrackLayoutMutation(){this.trackLayoutDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}commit(){this.committed||(this.committed=!0,this.options.onCommit({cleanupEmptyTracks:this.cleanupEmptyTracks,durationDirty:this.durationDirty,canPlayDirty:this.canPlayDirty,selectionDirty:this.selectionDirty,trackLayoutDirty:this.trackLayoutDirty,trackInfoDirty:this.trackInfoDirty,stageDirty:this.stageDirty,previewDirty:this.previewDirty,events:[...this.events]}))}createHistoryExecutionTarget(){return{removeClip:e=>{this.removeClip(e)},addClipToTrack:(e,t)=>this.addClipToTrack(e,t),updateClip:(e,t)=>{this.updateClip(e,t)},moveClipToTrack:(e,t)=>this.moveClipToTrack(e,t),ensureTrackFromHistorySnapshot:(e,t)=>this.ensureTrackFromHistorySnapshot(e,t),removeClipGaps:()=>{this.removeClipGaps()},getClips:()=>this.getClips(),findTrackByClipId:e=>{const t=this.findTrackByClipId(e);return t!=null&&t.addClip?t:null},getDefaultTrack:()=>{const e=this.getDefaultTrack();return e!=null&&e.addClip?e:null},loadClipThumbnails:this.options.loadClipThumbnails,withClipRemovalBatch:e=>e()}}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}function tp(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 ip(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=tp(s.trackCollection,e);return t?s.trackCollection.addClipToTrack(t,s.clip):!1}function Hs(s,e,t){return e.trackId?s.removeClipFromTrack(e.trackId,t):!1}function rp(s){return s.trackCollection.moveClipToTrack(s.command.clip,s.command.sourceTrackId,s.command.targetTrackId)}function Oi(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)}class mo{constructor(){g(this,"panel",null);g(this,"config",null);g(this,"currentSelectionState",this.buildSelectionState(null,[]));g(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new co({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,this.resolveUpdateTargets(i,r).forEach(a=>{e.updateClip(a.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)}showVoiceGenerationLoading(){var e;(e=this.panel)==null||e.showVoiceGenerationLoading()}hideVoiceGenerationLoading(){var e;(e=this.panel)==null||e.hideVoiceGenerationLoading()}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 a=new Set(i.map(c=>c.type)).size>1?"mixed":r.type,o=i.length>1,l=a==="audio"&&i.every(c=>Le(c));return{primaryClip:r,selectedClips:i,selectionCount:i.length,groupKind:a,supportsVoiceBatch:a==="text"||l,supportsTextContentBatch:a==="text"&&!o,supportsVisualBatch:a==="video",supportsVolumeBatch:a==="video"||a==="audio"}}resolveUpdateTargets(e,t){const{primaryClip:i,selectedClips:r,groupKind:n,supportsVoiceBatch:a}=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")?a&&n==="audio"?r.filter(l=>Le(l)):[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:me.backgroundColor,borderColor:e.border||me.borderColor,textColor:e.clipName||me.textColor,labelColor:e.timeText||me.labelColor,inputBackground:e.trackBackground||me.inputBackground,inputBorder:e.trackBorder||me.inputBorder,inputFocusBorder:me.inputFocusBorder,buttonBackground:e.clipBackground||me.buttonBackground,buttonBorder:e.clipBorder||me.buttonBorder,buttonActiveBackground:me.buttonActiveBackground,buttonActiveBorder:e.clipSelectedBorder||me.buttonActiveBorder,buttonActiveText:me.buttonActiveText}}}class np{constructor(){g(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 lo({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:Si,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 $s{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 sp=100*1024*1024,ap=10*1024*1024*1024,op=30*24*60*60*1e3,lp=["video/mp4","audio/aac","audio/mpeg","audio/mp4","audio/mp3","audio/ogg","audio/wav","audio/x-wav"],oi={enabled:!1,maxEntryBytes:sp,maxTotalBytes:ap,ttlMs:op,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:lp},cp="timeline-preview-resource-cache",hp=1,ye="metadata";function dp(){return new Promise((s,e)=>{const t=indexedDB.open(cp,hp);t.onupgradeneeded=()=>{const i=t.result,r=i.objectStoreNames.contains(ye)?t.transaction.objectStore(ye):i.createObjectStore(ye,{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 Er(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class up{constructor(){g(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=dp().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(ye,"readonly").objectStore(ye).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async put(e){const i=(await this.getDb()).transaction(ye,"readwrite");i.objectStore(ye).put(e),await Er(i)}async delete(e){const i=(await this.getDb()).transaction(ye,"readwrite");i.objectStore(ye).delete(e),await Er(i)}async clear(){const t=(await this.getDb()).transaction(ye,"readwrite");t.objectStore(ye).clear(),await Er(t)}async list(){const e=await this.getDb();return new Promise((t,i)=>{const r=e.transaction(ye,"readonly").objectStore(ye).getAll();r.onerror=()=>i(r.error),r.onsuccess=()=>t(r.result)})}}const pp="timeline-preview-resource-cache",gp="timeline-preview-resource-cache-blobs",fp=1,Re="blobs";function mp(){return new Promise((s,e)=>{const t=indexedDB.open(gp,fp);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Re)||i.createObjectStore(Re)},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function Rr(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class yp{constructor(){g(this,"kind","indexeddb");g(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=mp().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(Re,"readonly").objectStore(Re).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Re,"readwrite");r.objectStore(Re).put(t,e),await Rr(r)}async delete(e){const i=(await this.getDb()).transaction(Re,"readwrite");i.objectStore(Re).delete(e),await Rr(i)}async clear(){const t=(await this.getDb()).transaction(Re,"readwrite");t.objectStore(Re).clear(),await Rr(t)}}class Sp{constructor(){g(this,"kind","opfs");g(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(pp,{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 vp(s){var e;if(s.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new Sp;if(await t.ensureReady())return t}return new yp}function Cp(s){return Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function zs(s){return s.split(";",1)[0].trim().toLowerCase()}async function Tp(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 Cp(new Uint8Array(t))}function Mr(s){return s?[...s]:[...oi.allowedMimeTypes]}function bp(s){return s?s===!0?{...oi,enabled:!0,allowedMimeTypes:Mr(void 0)}:{...oi,...s,enabled:s.enabled??!0,allowedMimeTypes:Mr(s.allowedMimeTypes)}:{...oi,allowedMimeTypes:Mr(void 0)}}function kp(s){try{const e=new URL(s);return e.hash="",e.toString()}catch{return s.trim()}}async function wp(s){var t;const e=((t=s.sourceKey)==null?void 0:t.trim())||kp(s.url);return Tp(e)}function Vs(s,e=oi.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=zs(s.mimeType);return!e.some(r=>zs(r)===i)}function Pp(s){return s&&s.split(";",1)[0].trim().toLowerCase()||null}function Us(s){if(!s)return null;const e=Number(s);return Number.isSafeInteger(e)&&e>=0?e:null}function xp(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 Ws(s,e,t){return{url:e,ok:s.ok,status:s.status,mimeType:Pp(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 _p{async probe(e){var r;try{const n=await fetch(e,{method:"HEAD"}),a=Us(n.headers.get("content-length"));if(n.ok&&a!==null)return Ws(n,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=xp(t.headers.get("content-range"))??Us(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return Ws(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 Ap={createObjectURL(s){return URL.createObjectURL(s)},revokeObjectURL(s){URL.revokeObjectURL(s)}};function Tt(s,e){return{url:s.url,cacheStatus:e,sourceUrl:s.url}}function Ip(s,e){return s.etag||e.etag?s.etag===e.etag&&s.sizeBytes===e.contentLength:s.sizeBytes===e.contentLength&&s.lastModified===e.lastModified}class Ep{constructor(e={}){g(this,"options");g(this,"metadataStore");g(this,"storagePromise");g(this,"http");g(this,"objectUrl");g(this,"now");g(this,"cacheKeyBuilder");g(this,"onEvent");g(this,"objectUrls",new Set);g(this,"inflightDownloads",new Map);this.options=bp(e.options),this.metadataStore=e.metadataStore??new up,this.storagePromise=e.storage?Promise.resolve(e.storage):vp({preferStorage:this.options.preferStorage}),this.http=e.http??new _p,this.objectUrl=e.objectUrl??Ap,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??wp,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Vs(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),Tt(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}),Tt(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}),Tt(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(Ip(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:Tt(e,"fallback")}):Vs({...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:Tt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:Tt(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 Rp(s){return!!s&&typeof s.then=="function"}class Dr{constructor(){g(this,"durationCache",new Map);g(this,"thumbnailCache",new Map);g(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(!Rp(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 Ys{constructor(e,t=er){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 Mp{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 Dp(s){return s==="text"?"文本":s==="video"?"视频":"音频"}function Fi(s){return s==="text"?0:s==="video"?1:2}class yo{constructor(e=[]){g(this,"tracks",[]);g(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,r,n,a){this.trackCounter++;const o=t||`${Dp(e)}轨道 ${this.trackCounter}`,l=n??(this.tracks.length===0?"primary":"normal");l==="primary"&&this.tracks.forEach(h=>{h.role==="primary"&&(h.role="normal")});const c={id:a||`track_${Date.now()}_${this.trackCounter}`,type:e,name:o,order:this.tracks.length,role:l,clips:[]};return this.insertTrack(c,i,r),O.debugLazy("TrackManager",()=>`创建轨道: ${o}`,()=>({trackId:c.id,type:e,order:c.order})),c}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(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=>Fi(l.type)>Fi(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)=>Fi(c.type)<=Fi(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 Lp{constructor(e){g(this,"currentTime");g(this,"playState");g(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class So{constructor(){g(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class Bp{constructor(e){g(this,"zoom");g(this,"duration");g(this,"scrollLeft");g(this,"scrollTop");g(this,"viewportWidth");g(this,"viewportHeight");g(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class Xs{constructor(e){g(this,"selectionStore");g(this,"playbackStore");g(this,"viewportStore");this.selectionStore=new So,this.playbackStore=new Lp({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new Bp({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 Op{constructor(e,t,i,r,n){g(this,"stage");g(this,"layer");g(this,"onTimeChange");g(this,"onScrollChange");g(this,"config");g(this,"theme");g(this,"scrollLeft",0);g(this,"timeScaleHeight",40);g(this,"isDragging",!1);g(this,"dragStartX",0);g(this,"isPointerInsideTimeline",!1);g(this,"lastPointerXInTimeline",null);g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=r,this.onScrollChange=n,this.config={duration:i.duration||Jt,zoom:i.zoom||Me.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Yi(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(),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=cr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(hr({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-ke+this.scrollLeft,this.config.zoom)}timeToPixel(e){return U.timeToPixels(e,this.config.zoom)-this.scrollLeft+ke}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),a=U.msToSeconds(r),o=U.msToSeconds(n),{majorStep:l,minorStep:c}=U.getTickConfig(this.config.zoom),h=U.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,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,a,o){g(this,"container");g(this,"visualElement");g(this,"lineHitAreaElement");g(this,"theme");g(this,"onTimeChange");g(this,"onHorizontalAutoScroll");g(this,"currentTime");g(this,"zoom");g(this,"scrollLeft",0);g(this,"height");g(this,"isDragging",!1);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"lastPointerClientX",null);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});g(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});g(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const 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(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=cr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(hr({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-ke+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+ke,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=wn.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",wn.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}};g(q,"SVG_NS","http://www.w3.org/2000/svg"),g(q,"VISUAL_WIDTH",14),g(q,"HANDLE_HEIGHT",16),g(q,"HANDLE_LINE_START",13),g(q,"LINE_WIDTH",1),g(q,"LINE_HIT_WIDTH",12),g(q,"END_CAP_WIDTH",8),g(q,"END_CAP_HEIGHT",1),g(q,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(q,"AUTO_SCROLL_MAX_SPEED",18);let on=q;class qs{constructor(e){g(this,"container");g(this,"orientation");g(this,"theme");g(this,"onScrollChange");g(this,"leadingInset");g(this,"trailingInset");g(this,"stage");g(this,"layer");g(this,"hitAreaRect");g(this,"thumbRect");g(this,"viewportSize",0);g(this,"contentSize",0);g(this,"scrollOffset",0);g(this,"isDragging",!1);g(this,"dragStartClient",0);g(this,"dragStartOffset",0);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleStageMouseDown",e=>{var 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()});g(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});g(this,"handleStageMouseEnter",()=>{this.updateCursor()});g(this,"handleStageMouseMove",()=>{this.updateCursor()});g(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new Z.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new Z.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=de.createRect(0,0,0,0,Lt.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||Lt.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Lt.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=cr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(hr({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||Lt.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Lt.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 js{constructor(){g(this,"entries",new Map)}register(e,t){const i=this.entries.get(e);i&&i.destroy(),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()}}const Fp="@linker-design-plus/timeline-track",Np="2.1.2",Wt={name:Fp,version:Np},Gp=1,Hp=2,$p=250,zp=750,Vp=1500;function Ks(s){return s==null?s:JSON.parse(JSON.stringify(s))}function Up(s,e){return s.length!==e.length?!1:s.every((t,i)=>t===e[i])}function Wp(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class Yp{constructor(e={}){g(this,"timeline",null);g(this,"tracks",[]);g(this,"trackManager");g(this,"trackInfoPanelController");g(this,"playhead",null);g(this,"history");g(this,"config");g(this,"eventDispatcher");g(this,"animationFrameId",null);g(this,"lastUpdateTime",0);g(this,"isInitialized",!1);g(this,"stage",null);g(this,"headerStage",null);g(this,"headerLayer",null);g(this,"backgroundLayer",null);g(this,"trackLayer",null);g(this,"dragOverlayLayer",null);g(this,"snapGuideLayer",null);g(this,"selectionBoxLayer",null);g(this,"selectionBoxRect",null);g(this,"isBoxSelecting",!1);g(this,"boxSelectStartX",0);g(this,"boxSelectStartY",0);g(this,"resizeObserver",null);g(this,"rootContainer",null);g(this,"layout",null);g(this,"bodyBackgroundRect",null);g(this,"snapGuideLine",null);g(this,"trackInsertionPreviewLine",null);g(this,"trackInsertionPreviewY",null);g(this,"snapGuideTime",null);g(this,"horizontalScrollbar",null);g(this,"verticalScrollbar",null);g(this,"isExecutingHistoryAction",!1);g(this,"lastTrackDuration",0);g(this,"lastReportedTrackDuration",0);g(this,"thumbnailProvider",null);g(this,"thumbnailProviderVersion",0);g(this,"clipThumbnailLoadStates",new Map);g(this,"sourceMediaRegistry",new Dr);g(this,"canPlay",!1);g(this,"sourceLoadingCount",0);g(this,"timelineStore");g(this,"timelineCommands");g(this,"timelineHistoryRecorder");g(this,"timelinePresentationAdapter");g(this,"timelineTrackBridge");g(this,"timelinePlaybackResolver");g(this,"previewRuntimeController");g(this,"previewStateController");g(this,"previewPlaybackSuspendedByBuffering",!1);g(this,"previewPlaybackAutoResume",!1);g(this,"lastSelectedClipId",null);g(this,"previewAspectRatio",{...Be});g(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});g(this,"stageMouseDownListener",null);g(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});g(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});g(this,"keyboardShortcutsController",null);g(this,"clipClipboard",null);g(this,"mountManager",new js);g(this,"pendingDraftData",null);g(this,"selectionStore",new So);g(this,"multiDragSession",null);g(this,"clipRemovalBatchDepth",0);g(this,"splitOperationDepth",0);g(this,"diagnostics");g(this,"previewRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});g(this,"failedPreviewClipIds");g(this,"previewActiveClipIds",[]);g(this,"previewClockSeekAlignmentTargetTime",null);g(this,"previewClockSeekAlignmentDeadlineMs",0);g(this,"playbackAttemptId",this.createPlaybackAttemptId("initial"));g(this,"lastPreviewSyncedPlayState",null);g(this,"lastPreviewSyncSignature",null);g(this,"lastSteadyPlaybackPreviewSyncAt",0);g(this,"previewSyncInteractionMode",null);g(this,"resourceCacheManager");g(this,"voiceLinkedTextRegenerationTimer",null);g(this,"pendingVoiceLinkedTextRegeneration",null);g(this,"historyRecordingSuppressionDepth",0);g(this,"activeStructureSession",null);g(this,"structureSessionDepth",0);g(this,"preserveEmptyTracksDepth",0);this.config={duration:e.duration||Jt,zoom:e.zoom||Me.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:Yi(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 Ya(this.config.diagnostics),this.resourceCacheManager=this.config.resourceCache?new Ep({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:Wt.name,packageVersion:Wt.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 np,this.eventDispatcher=new Ns({can_play_change:()=>({canPlay:this.canPlay}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new rn(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new As(this.history),this.trackManager=new yo,this.timelineStore=new Xs({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new xs(this.timelineStore),this.timelinePresentationAdapter=new $s,this.timelineTrackBridge=new Ys({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.handleTimeChange.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,sourceLoadingPending:this.getSourceLoadingState().pending,loadingStatus:this.getPreviewLoadingState().status,loadingReason:this.getPreviewLoadingState().reason,isLoading:this.getPreviewLoadingState().isLoading,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)||Me.MEDIUM,h=((n=this.config)==null?void 0:n.duration)||Jt;this.timelineStore=new Xs({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new xs(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Mp(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new $s),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Ys({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.handleTimeChange.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 Gu),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}getPreviewLoadingState(){return this.getPreviewStateController().previewLoadingState}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 zu({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitLoadingStateChange:e=>{this.syncPlaybackClockToPreviewLoadingState(e),this.emitEvent("loading_state_change",e)},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new Hu({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Du({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||Lu(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewRuntimeState=t,this.syncTimelineClipMediaStateFromPreview(t),this.getPreviewStateController().handleRuntimeStateChange(t),this.handlePreviewClockStateChange(t.clock))},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=je(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()},onPauseIfPlaying:()=>{this.isActivePreviewCallbackToken(e)&&this.getPlayStateState()==="playing"&&this.pause()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Ns({can_play_change:()=>({canPlay:this.canPlay??!1}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new rn(()=>{},()=>{})),this.timelineHistoryRecorder=new As(this.history)),this.timelineHistoryRecorder}withStructureSession(e){const t=this.activeStructureSession;if(t)return e(t);const i=new ep({trackCollection:this.getTrackCollection(),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),loadClipThumbnails:this.loadClipThumbnails.bind(this),addClipToTrack:(n,a)=>this.getTrackCollection().addClipToTrack(n,a),removeClip:n=>{const a=this.getTrackCollection();if(typeof a.removeClip=="function"){a.removeClip(n);return}this.tracks.forEach(o=>{var l;return(l=o.removeClip)==null?void 0:l.call(o,n)})},removeClipFromTrack:(n,a)=>this.getTrackCollection().removeClipFromTrack(n,a),updateClip:(n,a)=>{const o=this.getTrackCollection();if(typeof o.updateClip=="function"){o.updateClip(n,a);return}this.tracks.forEach(l=>{var c;return(c=l.updateClip)==null?void 0:c.call(l,n,a)})},moveClipToTrack:(n,a,o)=>{const l=this.getTrackCollection();if(typeof l.moveClipToTrack=="function")return l.moveClipToTrack(n,a,o);const c=l.findById(a),h=l.findById(o);return!(c!=null&&c.removeClip)||!(h!=null&&h.addClip)?!1:(c.removeClip(n.id),h.addClip(n),!0)},getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),onCommit:this.applyStructureSessionSummary.bind(this)});this.activeStructureSession=i,this.structureSessionDepth=(this.structureSessionDepth??0)+1;const r=()=>{this.structureSessionDepth=Math.max(0,(this.structureSessionDepth??1)-1),this.activeStructureSession=null,i.commit()};try{const n=e(i);return n instanceof Promise?n.finally(r):(r(),n)}catch(n){throw r(),n}}getActiveStructureSession(){return this.activeStructureSession??null}withPreservedEmptyTracks(e){this.preserveEmptyTracksDepth+=1;const t=()=>{this.preserveEmptyTracksDepth=Math.max(0,this.preserveEmptyTracksDepth-1)};try{const i=e();return i instanceof Promise?i.finally(t):(t(),i)}catch(i){throw t(),i}}applyStructureSessionSummary(e){var i;((e.cleanupEmptyTracks&&this.preserveEmptyTracksDepth===0?this.removeEmptyTracksFromStructure():!1)||e.trackLayoutDirty)&&this.updateAllTrackPositions(),e.durationDirty&&this.checkTrackDurationChange(),e.canPlayDirty&&this.updateCanPlayState(),e.events.forEach(r=>{this.emitEvent(r.type,r.payload)}),e.selectionDirty&&(this.notifySelectionChange(),this.emitSelectionChangeEvent(),this.emitSelectedClipChangeIfNeeded()),e.trackInfoDirty&&this.updateTrackInfoPanel(),e.stageDirty&&((i=this.stage)==null||i.batchDraw()),e.previewDirty&&this.syncPreviewSession()}withHistoryBoundary(e,t,i){if(e==="transaction"){const a=t,o=i;if(!o)throw new Error("transaction history boundary requires a callback");return this.getTimelineHistoryRecorder().withTransaction(a,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 a=r();return a instanceof Promise?a.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),a)}catch(a){throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),a}}const n=this.isExecutingHistoryAction??!1;this.isExecutingHistoryAction=!0;try{const a=r();return a instanceof Promise?a.then(o=>(this.isExecutingHistoryAction=n,o),o=>{throw this.isExecutingHistoryAction=n,o}):(this.isExecutingHistoryAction=n,a)}catch(a){throw this.isExecutingHistoryAction=n,a}}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:Jt,zoom:Me.MEDIUM,currentTime:0,playState:"paused",theme:Yi(),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 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)}buildPreviewPlaybackPlan(e,t=this.getCurrentTimeState()){const i=this.buildPlaybackPlan(t);if(e!=="paused"||i.activeClips.length>0)return i;let r;try{r=this.getClips()}catch{return i}if(r.length===0)return i;const n=kt(r);return n<=0||t!==n?i:this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),t,{includeEndedClipsAtTime:!0})}playbackPlanHasActiveVideoClip(e){return e.activeClips.some(t=>t.trackType==="video")}hasActiveTimelineVideoClip(e=this.getCurrentTimeState()){return this.playbackPlanHasActiveVideoClip(this.buildPlaybackPlan(e))}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((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,requestedPlayState:e.requestedPlayState,speed:e.speed,interactionMode:e.interactionMode,primarySelectedClipId:e.primarySelectedClipId})}shouldSkipSteadyPlaybackPreviewSync(e,t,i){return t!=="playing"||i!=="steady"||this.pendingPreviewState||this.getPreviewLoadingState().isLoading||this.lastPreviewSyncedPlayState!=="playing"||this.lastPreviewSyncSignature!==e?!1:Date.now()-this.lastSteadyPlaybackPreviewSyncAt<$p}syncPreviewSession(e){var d,u,p,f;if(!((d=this.previewSession)!=null&&d.hasPreview())){this.previewSyncInteractionMode=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0;return}const t=this.resolvePreviewSyncPlayState(e),i=this.resolvePreviewRequestedPlayState(t),r=this.buildPreviewPlaybackPlan(t);this.previewActiveClipIds=r.activeClips.map(m=>m.clip.id);const n=this.getAutoAspectRatioClip(),a=je(this.previewAspectRatio),o=this.getSpeedState(),l=this.previewSyncInteractionMode??((u=this.pendingPreviewState)==null?void 0:u.mode)??"steady",c=this.getPrimarySelectedClipId(),h=this.buildPreviewSyncSignature({playbackPlan:r,autoAspectRatioClip:n,previewAspectRatio:a,targetPlayState:t,requestedPlayState:i,speed:o,interactionMode:l,primarySelectedClipId:c});if(this.shouldSkipSteadyPlaybackPreviewSync(h,t,l)){this.previewSyncInteractionMode=null;return}this.previewAspectRatio=a,this.previewSession.applyAspectRatio(a),(f=(p=this.previewSession).setPendingState)==null||f.call(p,this.buildPreviewPendingState()),this.previewSession.sync({...r,autoAspectRatioClip:n,currentTime:this.getCurrentTimeState(),playState:t,...i!==t?{requestedPlayState:i}:{},speed:o,interactionMode:l,primarySelectedClipId:c,...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),this.previewSyncInteractionMode=null,this.lastPreviewSyncedPlayState=t,this.lastPreviewSyncSignature=h,this.lastSteadyPlaybackPreviewSyncAt=t==="playing"&&l==="steady"?Date.now():0}resolvePreviewSyncPlayState(e){return e||this.getPlayStateState()}resolvePreviewRequestedPlayState(e){var t;return((t=this.pendingPreviewState)==null?void 0:t.mode)==="seek"&&this.pendingPreviewState.resumePlayOnReady&&e==="paused"?"playing":e}syncPreviewPlaybackStateIfNeeded(e){this.lastPreviewSyncedPlayState!==e&&this.syncPreviewSession(e)}shouldUsePreviewClockPlayback(){var e;try{return!!((e=this.previewSession)!=null&&e.hasPreview())&&this.hasActiveTimelineVideoClip()&&!this.pendingPreviewState}catch{return!1}}handlePreviewClockStateChange(e){if(!(!e||this.getPlayStateState()!=="playing")){if(!this.shouldUsePreviewClockPlayback()){this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState());return}if(this.isPreviewClockForCurrentActiveClip(e)&&!this.shouldIgnorePreviewClockUntilSeekTargetAligned(e)){if(e.status!=="running"||e.timelineTime===null){this.cancelPlaybackAnimationFrame(),this.shouldCommitUnavailablePreviewClock(e)&&this.commitPlaybackTimeFromPreviewClock(e);return}this.commitPlaybackTimeFromPreviewClock(e)}}}isPreviewClockForCurrentActiveClip(e){return!e.clipId||!Array.isArray(this.previewActiveClipIds)?!0:this.previewActiveClipIds.includes(e.clipId)}shouldCommitUnavailablePreviewClock(e){return e.status!=="unavailable"||e.timelineTime===null?!1:this.isPreviewClockForCurrentActiveClip(e)}shouldIgnorePreviewClockUntilSeekTargetAligned(e){return this.previewClockSeekAlignmentTargetTime==null||e.timelineTime===null?!1:Date.now()>this.previewClockSeekAlignmentDeadlineMs?(this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,!1):Math.abs(e.timelineTime-this.previewClockSeekAlignmentTargetTime)<=zp?(this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,!1):!0}commitPlaybackTimeFromPreviewClock(e){if(e.timelineTime===null)return;const t=this.clampPlaybackSeekTime(e.timelineTime),i=this.getTimelineCommands().setCurrentTime(t);if(!i.changed){this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(i.nextValue,e);return}const r=i.nextValue;this.ensureConfigState().currentTime=r,this.syncCurrentTimeToScene(r),this.emitEvent("time_change",{time:r}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(r,e)}syncPreviewAfterPreviewClockCommitIfNeeded(e,t){if(this.getPlayStateState()!=="playing"||this.pendingPreviewState)return;const i=this.buildPlaybackPlan(e),r=i.activeClips.map(n=>n.clip.id);if(!Up(r,this.previewActiveClipIds)){this.syncPreviewSession(),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i);return}t.clipId&&(r.includes(t.clipId)||this.syncPreviewSession()),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i)}resumeWallClockPlaybackIfPreviewClockUnavailable(e,t=this.buildPlaybackPlan(e)){this.getPlayStateState()!=="playing"||this.pendingPreviewState||this.animationFrameId||this.playbackPlanHasActiveVideoClip(t)||!this.canPlay||(this.lastUpdateTime=Date.now(),this.animate())}beginPendingPreview(e,t="seek"){var r,n,a,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;if(!this.hasActiveTimelineVideoClip(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.getPreviewStateController().beginPendingPreview(e,t,i),this.getPlayStateState()==="playing"&&this.pause(),t!=="scrub"&&this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"pending-preview.begin",message:"Pending preview started",playbackAttemptId:this.playbackAttemptId,syncRequestId:((o=this.pendingPreviewState)==null?void 0:o.syncRequestId)??null,runtimeState:{...this.buildDiagnosticsRuntimeState(),pendingMode:t},extra:{targetTime:e,resumePlayOnReady:i}})}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState(),this.previewActiveClipIds=[],this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,this.lastPreviewSyncedPlayState=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0,this.previewSyncInteractionMode=null,this.previewRuntimeState={phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},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(je(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){O.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=Td(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Si,scrollbarSize:Qr}),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 Z.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new Z.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new Z.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new Z.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new Z.Layer({name:"trackLayer"}),this.dragOverlayLayer=new Z.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new Z.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new Z.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&&(this.stageMouseDownListener||(this.stageMouseDownListener=h=>{this.handleStageMouseDown(h)}),t.addEventListener("mousedown",this.stageMouseDownListener)),this.timeline=new Op(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new on(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 qs({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:ke,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new qs({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,a){var u,p,f,m;if(!this.trackLayer)return O.error("TimelineManager","Track layer not initialized"),"";const o=this.trackManager.createTrack(e,t,i,r,n,a),l=o.id,c=Ae(e),h=this.calculateTrackY(l),d=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:l,clips:[],role:o.role},trackType:e,zoom:this.getZoomState(),trackY:h,trackHeight:c,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(u=d.setSnapTargetResolver)==null||u.call(d,()=>this.getClips()),(p=d.setDragOverlayLayer)==null||p.call(d,this.dragOverlayLayer),this.getTrackCollection().add(d),this.getActiveStructureSession()?(f=this.getActiveStructureSession())==null||f.markTrackLayoutMutation():(this.updateAllTrackPositions(),(m=this.stage)==null||m.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),l}removeTrack(e){var r,n,a,o,l;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&&((a=(n=t.getTrackGroup)==null?void 0:n.call(t))==null||a.destroy(),this.getTrackCollection().removeById(e),this.getActiveStructureSession()?(o=this.getActiveStructureSession())==null||o.markTrackLayoutMutation():(this.updateAllTrackPositions(),(l=this.stage)==null||l.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession())),i}renameTrack(e,t){var r,n;if(!((r=this.trackManager)!=null&&r.renameTrack))return!1;const i=this.trackManager.renameTrack(e,t);return i&&(this.getActiveStructureSession()?(n=this.getActiveStructureSession())==null||n.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}getTracks(){return this.getResolvedTracksSnapshot()}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){var r,n;if(!((r=this.trackManager)!=null&&r.muteTrack))return!1;const i=this.trackManager.muteTrack(e,t);return i&&(this.getActiveStructureSession()?(n=this.getActiveStructureSession())==null||n.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return Ut(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return ws(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=Pd(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()}removeEmptyTracksFromStructure(){var i,r,n;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return!1;const e=this.getTrackCollection();if(typeof e.removeEmptyNonPrimaryTracks!="function")return!1;const t=e.removeEmptyNonPrimaryTracks();if(t.length===0)return!1;for(const a of t){const o=(i=a.getId)==null?void 0:i.call(a);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(n=(r=a.getTrackGroup)==null?void 0:r.call(a))==null||n.destroy(),this.getTrackCollection().removeById(o))}return!0}cleanupEmptyTracks(){var e;this.clipRemovalBatchDepth>0||this.getActiveStructureSession()||this.removeEmptyTracksFromStructure()&&(this.updateAllTrackPositions(),(e=this.stage)==null||e.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=Ut(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+Ae(c.type)}}if(t==="top_of_type_region"&&a)return Ut(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Ut(r,o.id,this.getTrackContentTopOffset())+Ae(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():ws(r,this.getTrackContentTopOffset());const l=Ut(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+Ae(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 Z.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-ke+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||te.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=ge(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===Gp)return e*16;if(t===Hp){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*Lr.SENSITIVITY_FACTOR),n=Math.max(Me.MIN,Math.min(Me.MAX,i*r));Math.abs(n-i)<Lr.CONVERGENCE_THRESHOLD||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")return;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 t=this.getClips();if(t.length>0&&this.getCurrentTime()>=kt(t)){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();const e=this.shouldUsePreviewClockPlayback();e?(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame()):this.getPreviewLoadingState().isLoading?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitPlayStateChangeEvent(),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"play.started",message:"Playback started",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}),this.syncPreviewSession(!e&&this.getPreviewLoadingState().isLoading?"paused":void 0)}pause(){if(this.getPlayStateState()==="paused"){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused");return}this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.emitPlayStateChangeEvent(),this.syncPreviewSession()}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused"){this.animationFrameId=null;return}if(this.shouldUsePreviewClockPlayback()){this.animationFrameId=null;return}if(this.getPreviewLoadingState().status==="loading"){!this.previewPlaybackSuspendedByBuffering&&this.getPlayStateState()==="playing"&&this.suspendPlaybackForMediaPending(),this.animationFrameId=null;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();if(this.setCurrentTime(i),this.getPlayStateState()==="paused"){this.animationFrameId=null;return}this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}cancelPlaybackAnimationFrame(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}emitPlayStateChangeEvent(){this.emitEvent("play_state_change",{playState:this.getPlayStateState()})}suspendPlaybackForMediaPending(){this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering=!0,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused")}resumePlaybackAfterMediaPending(){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.syncPreviewPlaybackStateIfNeeded("playing"),this.lastUpdateTime=Date.now(),this.animationFrameId||this.animate()}shouldSuspendPreviewPlaybackForLoadingState(e){return e.status==="loading"}syncPlaybackClockToPreviewLoadingState(e){if(this.shouldUsePreviewClockPlayback()){this.cancelPlaybackAnimationFrame(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,e.status==="failed"&&this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.emitPlayStateChangeEvent());return}if(this.shouldSuspendPreviewPlaybackForLoadingState(e)){if(this.previewPlaybackSuspendedByBuffering){this.syncPreviewPlaybackStateIfNeeded("paused");return}if(this.getPlayStateState()!=="playing"){this.syncPreviewPlaybackStateIfNeeded("paused");return}this.suspendPlaybackForMediaPending();return}if(!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&(e.status==="ready"||e.status==="idle")&&!this.pendingPreviewState,i=this.previewPlaybackAutoResume&&e.status==="failed"&&this.getPlayStateState()!=="paused";if(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,i){this.setPlayStateState("paused"),this.emitPlayStateChangeEvent();return}!t||this.animationFrameId||this.resumePlaybackAfterMediaPending()}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=kt(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.updateCanPlayState(),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 a=this.timeline.getScrollLeft(),o=U.timeToPixels(i,t),c=U.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=U.pixelsToTime(t-ke+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=U.timeToPixels(n,o)-(t-ke);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>0}getSourceLoadingState(){const e=this.sourceLoadingCount;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}),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=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{return await this.withHistoryTransaction("add_clips",async()=>{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?an(t.getClips()):0}async addClipInternal(e){return this.withStructureSession(async()=>{var T;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?ta: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 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)}`,p=dn({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"?Pe(e.visualTransform):e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1,textContent:e.textContent??(r?"默认文本":void 0),textStyle:r?De(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});if(O.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:p.id,type:p.type,startTime:p.startTime,duration:p.duration})),e.trackId){const S=this.getTrackCollection().findById(e.trackId);if(S)return this.registerPreviewAutoAspectRatioClip(p),(T=S.addClip)==null||T.call(S,p),Ui({applied:!0,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const C=e.trackId;this.getTimelineHistoryRecorder().recordAddClip(p,C,this.cloneTrackSnapshot(C),this.getTrackRestoreAnchor(C))},applyEffects:()=>{}}),this.primeOrLoadClipThumbnails(p),p.id}const f=this.getTimelineCommands().planTrackPlacement(p,this.getTracksSortedByOrder()),m=this.getTrackCollection(),v=ip({clip:p,placement:f,trackCollection:m,createTrack:this.createTrack.bind(this)});return Ui({applied:v,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const S=this.resolveTrackIdByClipId(p.id);this.getTimelineHistoryRecorder().recordAddClip(p,S,S?this.cloneTrackSnapshot(S):null,S?this.getTrackRestoreAnchor(S):null)},applyEffects:()=>{}}),this.primeOrLoadClipThumbnails(p),p.id})}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),this.withStructureSession(()=>{Ui({applied:Hs(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:()=>{}})}))}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 a=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);a.exists&&(r=Hs(this.getTrackCollection(),a,n)||r)}})}),r?(Li({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Oi({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)}Oi({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)}),Oi({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)}),Oi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}syncTimelineClipMediaStateFromPreview(e){const t=this.getFailedPreviewClipIds(),i=new Set;e.slots.forEach(r=>{const n=r.clipId;if(!n)return;const a=this.findClipById(n);if(!a||a.type!=="video"&&a.type!=="audio")return;if(i.add(n),r.phase==="failed"||e.phase==="failed"&&e.loading.status==="failed"&&r.role==="current"){this.applyTimelineClipMediaStatus(n,"failed","媒体丢失");return}(r.phase==="active"||r.phase==="primed")&&!!r.actualSource&&this.clearTimelineClipMediaStatus(n)}),Array.from(t).forEach(r=>{if(i.has(r))return;this.findClipById(r)||t.delete(r)})}applyTimelineClipMediaStatus(e,t,i){const r=this.getFailedPreviewClipIds(),n=this.findClipById(e);if(!n){r.delete(e);return}if(n.mediaStatus===t&&n.mediaStatusMessage===i){r.add(e);return}r.add(e),this.updateClip(e,{mediaStatus:t,mediaStatusMessage:i})}clearTimelineClipMediaStatus(e){const t=this.getFailedPreviewClipIds();if(!t.has(e))return;t.delete(e);const i=this.findClipById(e);!i||i.mediaStatus!=="failed"&&i.mediaStatusMessage==null||this.updateClip(e,{mediaStatus:"ready",mediaStatusMessage:null})}getFailedPreviewClipIds(){return this.failedPreviewClipIds||(this.failedPreviewClipIds=new Set),this.failedPreviewClipIds}getExportComposition(){var n,a,o;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(_t(e.mode)&&t===Be.width&&i===Be.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=hn({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"?Pe(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){O.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}const t=[];await this.withHistoryBoundary("reset",async()=>{await this.withPreservedEmptyTracks(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),a=this.resolveImportedTrackRoles(n);let o;for(const c of n){const h=this.createTrack(c.type,c.name,o?"after_track":void 0,o,a.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 p=d.separatedFromVideoClipId;p&&l.has(p)&&(p=l.get(p));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:p,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,ttsSourceTextClipId:d.ttsSourceTextClipId,ttsVoiceId:d.ttsVoiceId,ttsVoiceName:d.ttsVoiceName,ttsFollowTextUpdates:d.ttsFollowTextUpdates,trackId:h},m=await this.addClip(f);l.set(d.id,m)}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 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.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 Wt.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-ke*2;O.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:a}));const o=Math.min(a/r,Me.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.previewClockSeekAlignmentTargetTime=t==="seek"?this.clampPlaybackSeekTime(e):null,this.previewClockSeekAlignmentDeadlineMs=t==="seek"?Date.now()+Vp:0,this.beginPendingPreview(e,t),this.setCurrentTime(e),this.getPlayStateState()==="playing"&&this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState()),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);const r=this.getActiveStructureSession();if(r){r.queueEvent("clip_updated",{clip:e}),r.markClipStateMutation();return}this.emitEvent("clip_updated",{clip:e});const n=this.selectedClipId===e.id;Ld({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)}),n&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){if(this.splitOperationDepth>0)return;const t=this.getActiveStructureSession();if(this.registerPreviewAutoAspectRatioClip(e),t){t.queueEvent("clip_added",{clip:e}),t.markStructureMutation();return}this.emitEvent("clip_added",{clip:e}),Li({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(e){if(this.clipThumbnailLoadStates.delete(e),this.splitOperationDepth>0)return;const t=this.getActiveStructureSession();if(t){t.queueEvent("clip_removed",{clipId:e}),t.markStructureMutation();return}this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Li({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){Bd(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=Od(e,t),r=this.canPlay;this.canPlay=Fd({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:kt(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))}resolveVoiceTextContent(e){return e.textContent??e.name??""}findSourceTextClipForTtsAudio(e){if(!e.ttsSourceTextClipId)return null;const t=this.findClipById(e.ttsSourceTextClipId);return(t==null?void 0:t.type)!=="text"?null:t}resolveTtsAudioVoiceGenerationSource(e){const t=this.findSourceTextClipForTtsAudio(e),i=t?this.resolveVoiceTextContent(t):"",r=typeof e.textContent=="string"?e.textContent:"",n=i.trim().length>0?i:r.trim().length>0?r:"";if(n.length===0)throw new Error("替换音色失败:缺少可用的配音文本");return{requestSourceTextClipId:(t==null?void 0:t.id)??e.ttsSourceTextClipId??e.id,persistedSourceTextClipId:t==null?void 0:t.id,text:n}}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(a=>{O.error("TimelineManager","Failed to flush pending linked voice regeneration",{error:a,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(a=>{O.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:a,clipId:e})})},ia)}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 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.type!=="text"||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")}selectBestClipboardPasteStartIndex(e,t){var r;if(t.length===0)return null;const i=t.filter(n=>n.newTrackCount===0).sort((n,a)=>n.score-a.score)[0];if(i)return i.startIndex;if(e==="text"){const n=t.filter(a=>a.startIndex<0).sort((a,o)=>a.newTrackCount!==o.newTrackCount?a.newTrackCount-o.newTrackCount:a.score-o.score)[0];if(n)return n.startIndex}return((r=t.slice().sort((n,a)=>n.score-a.score)[0])==null?void 0:r.startIndex)??null}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(C=>{var k;return C.type===((k=e[0])==null?void 0:k.type)}).sort((C,k)=>C.order-k.order);if(a.length===0){const C=this.createTrack(e[0].type);C&&n.set(e[0].key,C);for(let k=1;k<e.length;k+=1){const x=this.createTrack(e[k].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");x&&n.set(e[k].key,x)}return n}const o=new Set(e.flatMap(C=>C.clipIds)),l=e.map(C=>{const k=this.buildClipboardPasteGroupPlacementClips(C,t,i,r);if(k.length===0)return null;const x=this.resolvePreferredTrackIndexForPasteGroup(C,a,Math.min(C.sourceOrder,Math.max(a.length-1,0)));return{...C,preferredTrackIndex:x,clips:k}}).filter(C=>C!==null);if(l.length===0)return n;const c=l.map(C=>C.preferredTrackIndex),h=Math.min(...c),d=a.length,u=-l.length,p=[];for(let C=u;C<=d;C+=1){let k=!0,x=0,P=0;for(let D=0;D<l.length;D+=1){const w=l[D];if(!w)continue;const A=C+D;if(x+=Math.abs(A-w.preferredTrackIndex),A<0||A>=a.length){P+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[A].id,w.clips,o)){k=!1;break}}k&&(x+=P*.1,x+=Math.abs(C-h)*ra.ANCHOR_INDEX_WEIGHT,p.push({startIndex:C,score:x,newTrackCount:P}))}const f=this.selectBestClipboardPasteStartIndex(l[0].type,p);if(f===null)return n;const m=Math.max(0,-f),v=Math.max(0,f+l.length-a.length);m>0&&this.createTracksForTypeBoundary(l[0].type,m,"before"),v>0&&this.createTracksForTypeBoundary(l[0].type,v,"after");const T=[...this.getResolvedTracksSnapshot()].filter(C=>{var k;return C.type===((k=l[0])==null?void 0:k.type)}).sort((C,k)=>C.order-k.order),S=f+m;return l.forEach((C,k)=>{const x=T[S+k];x&&n.set(C.key,x.id)}),n}resolvePreferredTrackIndexForPasteGroup(e,t,i){if(e.sourceTrackId){const r=t.findIndex(n=>n.id===e.sourceTrackId);if(r!==-1)return r}if(Number.isFinite(e.sourceTrackOrder)){const r=t.findIndex(n=>n.order>=e.sourceTrackOrder);return r!==-1?r:t.length}return i}resolveClipboardPasteTrackAssignments(e,t,i){const r=this.buildClipboardPasteGroups(e,t),n=new Map;r.forEach(o=>{const l=n.get(o.type)??[];l.push(o),n.set(o.type,l)});const 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]}getSelectedTtsAudioClipsForVoiceGeneration(e){if(e.type!=="audio"||!Le(e))return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(n=>Le(n))))return[e];const r=t.filter(n=>Le(n));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((f,m)=>({requestId:`create:${f.id}:${i.id}:${h}:${m}`,sourceTextClipId:f.id,text:f.textContent??f.name??"",voiceId:i.id,followTextUpdates:r,mode:"create"}));e.setPreferredTab("voice");const u=[];if(await this.withHistoryTransaction("generate_voice_from_text_clips",async()=>{const f=await n(d),m=new Map(f.map(v=>[v.requestId,v]));for(const v of d){const T=m.get(v.requestId);if(!T)continue;const S=c.find(P=>P.id===v.sourceTextClipId);if(!S)continue;const C=this.normalizeGeneratedAudioDuration(T.duration),k=S.textContent??S.name??"";this.syncTextClipDurationToAudio(S.id,C);const x=await this.addClip({type:"audio",src:T.audioSrc,name:this.buildGeneratedAudioClipName(T.voiceName),textContent:k,startTime:S.startTime,duration:C,startTimeAtSource:0,endTimeAtSource:C,sourceDuration:C,ttsSourceTextClipId:S.id,ttsVoiceId:T.voiceId,ttsVoiceName:T.voiceName,ttsFollowTextUpdates:r});u.push(x)}if(u.length===0)throw new Error("生成音频失败:未返回音频结果")}),u.length===1){this.scrollToClip(u[0],{selectClip:!0,setCurrentTime:!0});return}const p=u[0]??null;this.scrollToClip(p,{setCurrentTime:!0}),this.setSelection(u,{preferredPrimaryClipId:p});return}if(t.type!=="audio"||!Le(t))return;const a=this.getSelectedTtsAudioClipsForVoiceGeneration(t),o=Date.now(),l=a.map((c,h)=>{const d=this.resolveTtsAudioVoiceGenerationSource(c);return{requestId:`replace:${c.id}:${i.id}:${o}:${h}`,sourceTextClipId:d.requestSourceTextClipId,targetAudioClipId:c.id,text:d.text,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 p=h.get(u.requestId);if(!p||!u.targetAudioClipId)continue;const f=a.find(v=>v.id===u.targetAudioClipId);if(!f)continue;const m=this.resolveTtsAudioVoiceGenerationSource(f);if(this.applyGeneratedAudioClipResult(u.targetAudioClipId,m.persistedSourceTextClipId,m.text,p,r),this.relocateClipIfNeeded(u.targetAudioClipId),m.persistedSourceTextClipId){const v=d.get(m.persistedSourceTextClipId)??0;d.set(m.persistedSourceTextClipId,Math.max(v,p.duration))}}d.forEach((u,p)=>{this.syncTextClipDurationToAudio(p,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 Dr.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return Dr.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){const i=this.resolveTrackIdByClipId(e.id),r=i?this.cloneTrackSnapshot(i):null,n=i?this.getTrackRestoreAnchor(i):null;Hd({clip1:e,clip2:t,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordSplitClip:(a,o)=>{this.getTimelineHistoryRecorder().recordSplitClip(a,o,i,r,n)},emitClipUpdated:a=>{this.emitEvent("clip_updated",{clip:a})},emitClipAdded:a=>{this.emitEvent("clip_added",{clip:a})},applyEffects:()=>Li({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=Nd(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.withStructureSession(t=>{new _s(t.createHistoryExecutionTarget()).executeUndo(e)})})}handleActionRedo(e){O.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new _s(t.createHistoryExecutionTarget()).executeRedo(e)})})}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=Qu({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1)}handleClipOverlap(e,t,i){var h,d,u,p;O.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=`${Wp(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))||((p=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:p.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()+Qr}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(f=>f.id===u)??null)&&r.push(u)}}),r.length===0)return!1;const a=e.primaryClipId?t.get(e.primaryClipId)??r[0]??null:r[0]??null;return this.setSelection(r,{preferredPrimaryClipId:a}),!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:Ks(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:Ks(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=je({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 mo,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(),getSelectedClips:()=>this.getSelectedClips(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c),u=d?{...d}:null,p=typeof h.textContent=="string"?h.textContent:null;if(n&&(u==null?void 0:u.type)==="text"&&p!==null&&p!==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,p,n);return}this.updateClip(c,h),this.handleClipChange()},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 p;const d=new Set(this.getSelectedClipIds()),u=this.getPrimarySelectedClip();d.size===0&&(u!=null&&u.id)&&d.add(u.id),(p=h==null?void 0:h.clip)!=null&&p.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 je(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:Wt.name,packageVersion:Wt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=je({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...Be},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}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.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 a=this.getClips().find(c=>c.id===e),o=this.getClips().find(c=>c.id===r)??null,l=this.resolveTrackIdByClipId(r);return a?(n&&this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,a,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,a=!this.shouldSkipHistoryRecording();this.withHistoryBoundary("suppressed",()=>{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})});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(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){return this.withStructureSession(()=>{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 v,T,S;return{targetTrackType:(T=(v=this.getTrackCollection().findById(t))==null?void 0:v.getTrackType)==null?void 0:T.call(v),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=this.getTrackRestoreAnchor(a),p=this.getTrackRestoreAnchor(o),f=rp({command:{...n,clip:c},trackCollection:this.getTrackCollection()}),m=this.getClips().find(v=>v.id===e)??null;return Gd({applied:f,clipId:e,sourceTrackId:a,targetTrackId:o,clipBefore:l,clipAfter:m??l,sourceTrackSnapshot:h,targetTrackSnapshot:d,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordMoveClipBetweenTracks:(v,T,S,C,k,x,P)=>{this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks(v,T,S,C,k,x,P,u,p)},applyEffects:()=>{}})?(this.clearAllTrackDropPreviews(),!0):!1})}getTrackTotalDuration(){return Os(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 t,i,r,n,a,o,l,c,h,d,u,p,f,m,v;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPendingPreviewState(),(t=this.resourceCacheManager)==null||t.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(),(i=this.layout)==null||i.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(a=(r=this.layout)==null?void 0:(n=r.bodyCanvasHost).removeEventListener)==null||a.call(n,"click",this.bodyCanvasHostClickListener);const e=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);e&&this.stageMouseDownListener&&((c=e.removeEventListener)==null||c.call(e,"mousedown",this.stageMouseDownListener)),(d=(h=this.rootContainer)==null?void 0:h.removeEventListener)==null||d.call(h,"wheel",this.rootWheelListener),(u=this.horizontalScrollbar)==null||u.destroy(),(p=this.verticalScrollbar)==null||p.destroy(),(f=this.playhead)==null||f.destroy(),(m=this.timeline)==null||m.destroy(),(v=this.stage)==null||v.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new js),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new Zu({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{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 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)}}createMultiDragPlacementContext(e){const t=new Map,i=new Map,r=[...this.getResolvedTracksSnapshot()].sort((n,a)=>(n.order??0)-(a.order??0));for(const n of r){const a=i.get(n.type)??[];a.push(n.id),i.set(n.type,a),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(a=>a.id!==i.id&&i.startTime<a.startTime+a.duration&&n>a.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 a=e.orderedTrackIdsByType.get(i)??[];if(!a.includes(t)){if(r==="before_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o,0,t):a.unshift(t)}else if(r==="after_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o+1,0,t):a.push(t)}else r==="top_of_type_region"?a.unshift(t):a.push(t);e.orderedTrackIdsByType.set(i,a)}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 a=t.type==="audio"?"bottom_of_type_region":"top_of_type_region",o=this.createTrack(t.type,void 0,a);return o?(this.registerMultiDragPlacementTrack(e,o,t.type,a),o):null}commitMultiDragPlacements(e,t,i){const r=[],n=this.createMultiDragPlacementContext(new Set(e.selectedClipIds));for(const a of e.selectedClipIds){const o=e.clips.get(a);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 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);return o===null?!1:this.commitMultiDragPlacements(e,t,(l,c)=>l.clipId===t.draggedClipId?a:this.resolveMultiDragTargetTrackId(l,o,c))}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 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 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):[]}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 Z.Rect({fill:Pn.fill,stroke:Pn.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=ge(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Se(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=ge(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Se(o.duration,this.getZoomState()),h=n+2,d=a-4,u=l+c,p=h+d,f=e.x+e.width,m=e.y+e.height;l<f&&u>e.x&&h<m&&p>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return Ae(e.getTrackType())}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,void 0,e.id);return this.muteTrack(u,e.isMuted??!1),u}const n=[...this.getTracks()].sort((u,p)=>u.order-p.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,void 0,e.id);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 a;const t=this.getTimelineCommands();if(typeof t.findClipById=="function")return((a=t.findClipById(this.tracks,e))==null?void 0:a.trackId)??null;const i=this.getTrackCollection();if(typeof i.findTrackByClipId=="function"){const o=i.findTrackByClipId(e);if(o)return o.getId()}const n=(Array.isArray(this.tracks)?this.tracks:[]).find(o=>o.getClips().some(l=>l.id===e));return(n==null?void 0:n.getId())??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var a;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=an(e),n=Os(e);if(r!==t){this.lastTrackDuration=r;const o=Fs(r);this.setDurationState(o),(a=this.timeline)==null||a.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=kt(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=${Fs(r)}ms`)}resolveSelectedClipSnapshot(){return fo({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 Ju({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=Pe(i.visualTransform),n=Pe(t);bn(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=De(i.textStyle),n=Math.max(li.MIN,Math.min(li.MAX,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=De(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 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(),this.clearHistory()})}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=ln;exports.CLIP_LAYER=bo;exports.Clip=$i;exports.ClipConfigPanel=co;exports.DEFAULT_CLIP_VIEW_STATE=ea;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Be;exports.DEFAULT_TEXT_CLIP_DURATION_MS=ta;exports.DEFAULT_TEXT_CLIP_STYLE=Js;exports.DEFAULT_TIMELINE_DURATION_MS=Jt;exports.DiagnosticsCenter=Ya;exports.HistoryManager=rn;exports.MIN_CLIP_LINE_WIDTH=ci;exports.PREVIEW_ASPECT_RATIO_PRESETS=To;exports.SNAP_SCORING=ra;exports.TEXT_CLIP_FONT_SIZE_LIMITS=li;exports.TIMELINE_LEFT_PADDING=ke;exports.TIME_SCALE=wo;exports.TRACK_HEIGHT=Ni;exports.TimeUtils=U;exports.TimelineClipConfigController=mo;exports.TimelineManager=Yp;exports.Track=er;exports.TrackInfoPanel=lo;exports.TrackManager=yo;exports.VOICE_LINKED_TEXT_REGEN_DEBOUNCE_MS=ia;exports.ZOOM_ANIMATION=ko;exports.ZOOM_GESTURE=Lr;exports.ZOOM_PRESETS=Me;exports.createClipViewState=na;exports.createClipWithViewState=dn;exports.defaultDarkTheme=Wi;exports.devConsole=O;exports.isAudioOnlyTtsClipCandidate=Qs;exports.isAutoPreviewAspectRatioMode=_t;exports.isTtsAudioClip=Le;exports.mergeDiagnosticRuntimeState=Xa;exports.normalizePreviewAspectRatio=je;exports.normalizePreviewAspectRatioMode=cn;exports.resolveAspectRatioBaselineDimensions=hn;exports.resolveTextClipStyle=De;exports.resolveTheme=Yi;