@linker-design-plus/timeline-track 2.0.9 → 2.0.10
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 +1 -1
- package/dist/index.es.js +2 -2
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -108,4 +108,4 @@ js: import "konva/skia-backend";
|
|
|
108
108
|
height: 0;
|
|
109
109
|
display: none;
|
|
110
110
|
}
|
|
111
|
-
`,document.head.appendChild(a)}function ph(a,e){uh();const t=e.leftPanelWidth??Ws,i=e.scrollbarSize??Ys;a.innerHTML="",a.classList.add("timeline-manager-root"),a.style.gridTemplateColumns=`${t}px minmax(0, 1fr)`,a.style.gridTemplateRows=`${e.timeScaleHeight}px minmax(0, 1fr)`,a.style.background=e.theme.background;const n=ke("div");n.className="timeline-manager-header-corner",qt(n,e.theme),n.style.gridColumn="1",n.style.gridRow="1",n.style.borderBottom=`1px solid ${e.theme.border}`;const s=ke("div");s.className="timeline-manager-header-viewport",qt(s,e.theme),s.style.gridColumn="2",s.style.gridRow="1",s.style.borderBottom=`1px solid ${e.theme.border}`,s.style.overflow="hidden";const r=ke("div");r.className="timeline-manager-header-canvas-host",r.style.width="100%",r.style.height="100%",s.appendChild(r);const o=ke("div");o.className="timeline-manager-track-info-viewport",qt(o,e.theme),o.style.gridColumn="1",o.style.gridRow="2",o.style.overflow="hidden",o.style.borderRight=`1px solid ${e.theme.border}`;const l=ke("div");l.className="timeline-manager-scroll-viewport timeline-manager-body-viewport",qt(l,e.theme),l.style.gridColumn="2",l.style.gridRow="2",l.style.overflowX="hidden",l.style.overflowY="auto";const h=ke("div");h.className="timeline-manager-body-canvas-host",h.style.width="100%",h.style.height="100%",h.style.position="relative",h.style.background=e.theme.background,l.appendChild(h);const c=ke("div");c.className="timeline-manager-v-scrollbar-canvas-host",c.style.position="absolute",c.style.top=`${e.timeScaleHeight}px`,c.style.right="0",c.style.bottom="0",c.style.width=`${i}px`,c.style.zIndex="5";const d=ke("div");d.className="timeline-manager-h-scrollbar-canvas-host",d.style.position="absolute",d.style.left=`${t}px`,d.style.right="0",d.style.bottom="0",d.style.height=`${i}px`,d.style.zIndex="4";const u=ke("div");return u.className="timeline-manager-playhead-overlay",u.style.position="absolute",u.style.left=`${t}px`,u.style.top="0",u.style.right="0",u.style.bottom="0",u.style.pointerEvents="none",u.style.zIndex="3",a.appendChild(n),a.appendChild(s),a.appendChild(o),a.appendChild(l),a.appendChild(c),a.appendChild(d),a.appendChild(u),{headerCorner:n,headerViewport:s,headerCanvasHost:r,trackInfoViewport:o,bodyViewport:l,bodyCanvasHost:h,verticalScrollbarCanvasHost:c,horizontalScrollbarCanvasHost:d,playheadOverlay:u}}function ke(a){return document.createElement(a)}function qt(a,e){a.style.position="relative",a.style.minWidth="0",a.style.minHeight="0",a.style.maxWidth="100%",a.style.boxSizing="border-box",a.style.background=e.background,a.style.color=e.clipName}class gh{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 Xs{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 fh{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 Xn{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new Xs,this.playbackStore=new gh({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new fh({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 mh{constructor(e,t,i,n,s){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=n,this.onScrollChange=s,this.config={duration:i.duration||36e5,zoom:i.zoom||de.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:It(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(e){}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setScrollLeft(e){this.scrollLeft=this.clampScrollLeft(e),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(e){const t=H.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=H.timeToPixels(e.startTime,this.config.zoom),n=H.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,s=this.stage.width(),r=n<=s?Math.max(0,t-(s-n)/2):Math.max(0,t);this.setScrollLeft(r)}resize(e){this.stage.width(e),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",e=>{e.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(e.evt.offsetX),"seek")}),this.stage.on("mousedown",e=>{e.target.getLayer()===this.layer&&(this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Rt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(e){const t=e.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-t),n=this.scrollLeft;this.dragStartX=e.clientX,this.scrollLeft=i,this.render(),n!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(e){return H.pixelsToTime(e-le+this.scrollLeft,this.config.zoom)}timeToPixel(e){return H.timeToPixels(e,this.config.zoom)-this.scrollLeft+le}render(){const e=this.stage.width(),t=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const n=ie.createRect(0,0,e,t,this.theme.background,this.theme.border,1);n.name("timeline-header-background"),this.layer.add(n)}this.layer.find(".time-tick-line").forEach(n=>n.remove()),this.layer.find(".time-tick-text").forEach(n=>n.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,n=H.pixelsToTime(t,this.config.zoom),s=H.pixelsToTime(i,this.config.zoom),r=H.msToSeconds(n),o=H.msToSeconds(s),{majorStep:l,minorStep:h}=H.getTickConfig(this.config.zoom),c=H.generateVisibleTicks(r-10,o+10,l,h);for(const d of c){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&ie.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,H.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const V=class V{constructor(e,t,i,n,s,r,o){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 n=this.scrollLeft,s=this.onHorizontalAutoScroll(this.scrollLeft+i),r=typeof s=="number"?s:this.scrollLeft;if(this.scrollLeft=Math.max(0,r),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-n)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=e,this.currentTime=t,this.zoom=i,this.height=n,this.theme=s,this.onTimeChange=r,this.onHorizontalAutoScroll=o,this.container.innerHTML="",this.container.style.position="absolute",this.container.style.pointerEvents="none",this.container.style.overflow="visible",this.visualElement=document.createElementNS(V.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${V.VISUAL_WIDTH}`),this.visualElement.style.position="absolute",this.visualElement.style.top="0",this.visualElement.style.marginLeft=`${-14/2}px`,this.visualElement.style.pointerEvents="none",this.visualElement.style.overflow="visible",this.lineHitAreaElement=document.createElement("div"),this.lineHitAreaElement.className="timeline-manager-playhead-hit-area",this.lineHitAreaElement.style.position="absolute",this.lineHitAreaElement.style.top="0",this.lineHitAreaElement.style.width=`${V.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Rt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,n=H.pixelsToTime(i-le+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,n),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(V.AUTO_SCROLL_EDGE_THRESHOLD,t/2),n=V.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-n;if(e>=t)return n;if(e<i){const s=(i-e)/i;return-Math.max(1,Math.round(s*n))}if(e>t-i){const s=(e-(t-i))/i;return Math.max(1,Math.round(s*n))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const e=H.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+le,t=e>=0&&e<=this.container.clientWidth,i=Math.max(V.HANDLE_HEIGHT+V.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${V.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=this.theme.clipSelectedBackground||"#8c90ff",i=Math.max(V.HANDLE_HEIGHT,e-V.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i,this.theme.playhead))}createHandleShadowPath(){const e=document.createElementNS(V.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill","rgba(0, 0, 0, 0.22)"),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(V.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(V.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(V.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),t.setAttribute("y",`${V.HANDLE_LINE_START}`),t.setAttribute("width",`${V.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-V.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e,t){const i=document.createElementNS(V.SVG_NS,"g");i.setAttribute("class","timeline-manager-playhead-end-cap"),i.setAttribute("transform",`translate(0 ${e})`);const n=document.createElementNS(V.SVG_NS,"rect");n.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),n.setAttribute("y","0"),n.setAttribute("width",`${V.LINE_WIDTH}`),n.setAttribute("height","7"),n.setAttribute("rx","1"),n.setAttribute("fill",t);const s=document.createElementNS(V.SVG_NS,"rect");return s.setAttribute("x",`${(V.VISUAL_WIDTH-V.END_CAP_WIDTH)/2}`),s.setAttribute("y","7"),s.setAttribute("width",`${V.END_CAP_WIDTH}`),s.setAttribute("height","3"),s.setAttribute("rx","1.5"),s.setAttribute("fill",t),i.appendChild(n),i.appendChild(s),i}};p(V,"SVG_NS","http://www.w3.org/2000/svg"),p(V,"VISUAL_WIDTH",14),p(V,"HANDLE_HEIGHT",16),p(V,"HANDLE_LINE_START",13),p(V,"LINE_WIDTH",2),p(V,"LINE_HIT_WIDTH",12),p(V,"END_CAP_WIDTH",14),p(V,"END_CAP_HEIGHT",10),p(V,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(V,"AUTO_SCROLL_MAX_SPEED",18);let Oi=V;class Un{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 n;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((n=e.target)==null?void 0:n.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});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 U.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new U.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=ie.createRect(0,0,0,0,"rgba(0, 0, 0, 0.001)","transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=ie.createRect(0,0,0,0,this.theme.scrollbarThumb||"#444444",this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555",1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Rt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(e){const i=(this.orientation==="horizontal"?e.clientX:e.clientY)-this.dragStartClient,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),r=Math.max(1,n-s),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/r*o;this.emitScrollChange(l)}jumpToPointer(e){const t=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?e-t.left:e-t.top,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),r=Math.max(1,n-s),o=Math.max(0,Math.min(n,i-this.leadingInset)),l=Math.max(0,Math.min(r,o-s/2)),h=this.getMaxScrollOffset(),c=r<=0?0:l/r*h;this.emitScrollChange(c)}emitScrollChange(e){const t=this.clampScrollOffset(e);this.scrollOffset=t,this.render(),this.onScrollChange(t)}render(){const e=Math.max(0,this.container.clientWidth),t=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(e),this.stage.height(t),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(e),this.hitAreaRect.height(t),this.thumbRect.fill(this.theme.scrollbarThumb||"#444444"),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555");const n=this.getAvailableTrackSize();if(n<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const s=this.getThumbSize(n),r=this.leadingInset+this.getThumbPosition(n,s);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(r),this.thumbRect.y(0),this.thumbRect.width(s),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(r),this.thumbRect.width(e),this.thumbRect.height(s)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const n=Math.max(1,e-t);return this.scrollOffset/i*n}}class yh{constructor(){p(this,"entries",new Map)}register(e,t){this.entries.set(e,{id:e,destroy:t})}unregister(e){this.entries.delete(e)}destroyAll(){for(const e of this.entries.values())e.destroy();this.entries.clear()}}class Sh{constructor(){p(this,"panel",null);p(this,"config",null);p(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new Hs({container:e.container,theme:t,onClipUpdate:(i,n)=>{this.isInternalUpdate=!0,e.updateClip(i,n),setTimeout(()=>{this.isInternalUpdate=!1},0)}})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip();this.panel.setClip(e)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}convertTheme(e){return{backgroundColor:e.background||"#1e1e1e",borderColor:e.border||"#333",textColor:e.clipName||"#e0e0e0",labelColor:e.timeText||"#999",inputBackground:e.trackBackground||"#2d2d2d",inputBorder:e.trackBorder||"#444",inputFocusBorder:"#409eff",buttonBackground:e.clipBackground||"#2d2d2d",buttonBorder:e.clipBorder||"#444",buttonActiveBackground:e.clipSelectedBackground||"#409eff",buttonActiveBorder:e.clipSelectedBorder||"#409eff",buttonActiveText:e.clipSelectedName||"#fff"}}}const Ch="2.0.8",vh={version:Ch},Th=1,bh=2,wh=120;class kh{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,"lastEffectiveTrackDuration",0);p(this,"thumbnailProvider",null);p(this,"canPlay",!1);p(this,"sourceLoadingCount",0);p(this,"timelineStore");p(this,"timelineCommands");p(this,"timelineHistoryExecutor");p(this,"timelineHistoryRecorder");p(this,"timelinePresentationAdapter");p(this,"timelineTrackBridge");p(this,"timelinePlaybackResolver");p(this,"previewRuntimeController");p(this,"previewStateController");p(this,"previewPlaybackSuspendedByBuffering",!1);p(this,"previewPlaybackAutoResume",!1);p(this,"previewBufferingSuspendTimeoutId",null);p(this,"lastSelectedClipId",null);p(this,"previewAspectRatio",{...be});p(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});p(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});p(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});p(this,"mountManager",new yh);p(this,"pendingDraftData",null);p(this,"selectionStore",new Xs);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);this.config={duration:e.duration||36e5,zoom:e.zoom||de.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:It(e.theme),timeScaleHeight:e.timeScaleHeight,logConfig:e.logConfig,speed:e.speed||1,dragActivationThreshold:e.dragActivationThreshold??4,enableClipSnap:e.enableClipSnap??!1,clipSnapThreshold:e.clipSnapThreshold??8,thumbnailProvider:e.thumbnailProvider,previewBackend:e.previewBackend??"dom",previewSourceResolver:e.previewSourceResolver},M.setConfig(this.config.logConfig),M.debug("TimelineManager","日志系统初始化完成",{logConfig:this.config.logConfig}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new hh,this.eventDispatcher=new Nn({can_play_change:()=>({canPlay:this.canPlay}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new Di(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Ln(this.history),this.timelineHistoryExecutor=new En({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 Vs,this.timelineStore=new Xn({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new An(this.timelineStore),this.timelinePresentationAdapter=new zn,this.timelineTrackBridge=new Vn({onClipUpdate:(t,i,n)=>this.handleClipUpdate(t,i,n),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),e.draftData&&(this.pendingDraftData=e.draftData),this.config.container&&this.init(this.config.container)}getTimelineStore(){var e,t,i,n,s;if(!this.timelineStore){const r=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,h=((n=this.config)==null?void 0:n.zoom)||de.MEDIUM,c=((s=this.config)==null?void 0:s.duration)||36e5;this.timelineStore=new Xn({currentTime:r,playState:o,speed:l,zoom:h,duration:c})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new An(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new ch(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new zn),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Vn({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this)})),this.timelineTrackBridge}getTimelinePlaybackResolver(){return this.timelinePlaybackResolver||(this.timelinePlaybackResolver=new Jl),this.timelinePlaybackResolver}get previewSession(){return this.getPreviewRuntimeController().previewSession}set previewSession(e){this.getPreviewRuntimeController().previewSession=e}get previewMountContainer(){return this.getPreviewRuntimeController().previewMountContainer}set previewMountContainer(e){this.getPreviewRuntimeController().previewMountContainer=e}get resolvedPreviewBackend(){return this.getPreviewRuntimeController().resolvedPreviewBackend}set resolvedPreviewBackend(e){this.getPreviewRuntimeController().resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this.getPreviewRuntimeController().runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this.getPreviewRuntimeController().runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this.getPreviewRuntimeController().activePreviewCallbackToken}set activePreviewCallbackToken(e){this.getPreviewRuntimeController().activePreviewCallbackToken=e}get previewSourceLoadingCount(){return this.getPreviewStateController().previewSourceLoadingCount}set previewSourceLoadingCount(e){this.getPreviewStateController().previewSourceLoadingCount=e}get previewBuffering(){return this.getPreviewStateController().previewBuffering}set previewBuffering(e){this.getPreviewStateController().previewBuffering=e}get pendingPreviewState(){return this.getPreviewStateController().pendingPreviewState}set pendingPreviewState(e){this.getPreviewStateController().pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this.getPreviewStateController().nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this.getPreviewStateController().nextPendingPreviewSyncRequestId=e}getPreviewStateController(){return this.previewStateController||(this.previewStateController=new ih({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitBufferingStateChange:e=>{this.syncPlaybackClockToPreviewBuffering(e),this.emitEvent("buffering_state_change",{isBuffering:e})},emitSourceLoadingStateChange:()=>{this.emitEvent("source_loading_change",this.getSourceLoadingState())},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new Ql({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Xl({callbacks:t,previewSourceResolver:this.config.previewSourceResolver}),resolveConfiguredBackend:e=>e||Ul(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onBufferingStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleBufferingStateChange(t)},onSourceLoadingChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleSourceLoadingChange(t)},onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleRuntimeStateChange(t)},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=De(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(e)&&this.retryPendingPreview()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Nn({can_play_change:()=>({canPlay:this.canPlay??!1}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new Di(()=>{},()=>{})),this.timelineHistoryRecorder=new Ln(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new En({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)})),this.timelineHistoryExecutor}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:36e5,zoom:de.MEDIUM,currentTime:0,playState:"paused",theme:It(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,clipSnapThreshold:8,previewBackend:"dom"}),this.config}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(e){this.getTimelineStore().setPlayState(e),this.ensureConfigState().playState=e}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(e){this.getTimelineStore().setDuration(e),this.ensureConfigState().duration=e}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(e){this.getTimelineStore().setScrollLeft(e)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(e){this.getTimelineStore().setScrollTop(e)}setViewportMetrics(e,t,i){const n=this.getTimelineStore();n.setViewportWidth(e),n.setViewportHeight(t),n.setContentHeight(i)}syncCurrentTimeToScene(e){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncZoomToScene(e){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncScrollTopPresentation(e){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,e)}refreshScrollbarMetrics(){var i,n,s,r;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(n=this.verticalScrollbar)==null||n.resize(),(s=this.horizontalScrollbar)==null||s.setViewportMetrics(e,this.getHorizontalContentWidth()),(r=this.verticalScrollbar)==null||r.setViewportMetrics(t,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientWidth)||0}getViewportHeight(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return H.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(e){const t=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(t,e))}clampScrollTop(e){const t=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(t,e))}syncScrollLeft(e){var i,n;const t=this.clampScrollLeft(e);this.setScrollLeftState(t),(i=this.timeline)==null||i.setScrollLeft(t),(n=this.horizontalScrollbar)==null||n.setScrollLeft(t),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),t),this.refreshSnapGuideLine()}syncScrollTop(e){var i;const t=this.clampScrollTop(e);this.setScrollTopState(t),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-t)>.5&&(this.layout.bodyViewport.scrollTop=t),this.syncScrollTopPresentation(t)}getResolvedTracksSnapshot(){const e=this.getTrackCollection();return this.trackManager.getTracks().map(t=>{const i=e.findById(t.id);return{...t,clips:i?i.getClips():[...t.clips]}})}getTracksSortedByOrder(){const e=this.getTrackCollection();return this.trackManager.getTracks().slice().sort((t,i)=>t.order-i.order).map(t=>e.findById(t.id)).filter(t=>t!==null)}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(e=>({id:e.id,type:e.type,order:e.order,isMuted:e.isMuted??!1,clips:e.clips}))}buildPlaybackPlan(e=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),e)}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((r,o)=>r.order-o.order);let i=null,n=null,s=Number.POSITIVE_INFINITY;for(const r of t){if(r.type!=="video")continue;const o=[...r.clips].sort((l,h)=>l.startTime-h.startTime);for(const l of o){const h={trackId:r.id,trackType:r.type,trackOrder:r.order,clip:l,mediaTime:l.startTimeAtSource,muted:(r.isMuted??!1)||(l.isMuted??!1),kind:r.type,hasVisual:!0,hasAudio:!0};i||(i=h);const c=e.get(l.id);c===void 0||c>=s||(n=h,s=c)}}return n||i}registerPreviewAutoAspectRatioClip(e){const t=this,i=this.getPreviewAutoAspectRatioClipOrderMap();e.type!=="video"||i.has(e.id)||(i.set(e.id,this.getNextPreviewAutoAspectRatioOrder()),t.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}syncPreviewSession(){var n,s,r;if(!((n=this.previewSession)!=null&&n.hasPreview()))return;const e=this.buildPlaybackPlan(),t=this.getAutoAspectRatioClip(),i=De(this.previewAspectRatio);this.previewAspectRatio=i,this.previewSession.applyAspectRatio(i),this.previewSession.sync({...e,autoAspectRatioClip:t,currentTime:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),primarySelectedClipId:this.getPrimarySelectedClipId(),...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),(r=(s=this.previewSession).setPendingState)==null||r.call(s,this.buildPreviewPendingState())}beginPendingPreview(e,t="seek"){var n,s;if(!((n=this.previewSession)!=null&&n.hasPreview()))return;const i=((s=this.pendingPreviewState)==null?void 0:s.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPlayStateState()==="playing"&&this.pause(),this.getPreviewStateController().beginPendingPreview(e,t,i)}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState()}destroyPreviewSession(e=!1){this.getPreviewRuntimeController().destroyPreviewSession(e),this.resetPreviewRuntimeState()}retryPendingPreview(){this.getPreviewStateController().retryPendingPreview()}handlePreviewBackendRuntimeError(){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();const e=this.getPreviewRuntimeController().fallbackToDom(De(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,n,s,r,o,l,h;if(this.isInitialized){M.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=ph(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Ws,scrollbarSize:Ys}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(n=(i=this.layout.bodyCanvasHost).addEventListener)==null||n.call(i,"click",this.bodyCanvasHostClickListener),(r=(s=this.rootContainer)==null?void 0:s.addEventListener)==null||r.call(s,"wheel",this.rootWheelListener,{passive:!1}),this.headerStage=new U.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new U.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new U.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new U.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new U.Layer({name:"trackLayer"}),this.dragOverlayLayer=new U.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new U.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new U.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const t=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(t&&t.addEventListener("mousedown",this.handleStageMouseDown.bind(this)),this.timeline=new mh(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new Oi(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 Un({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:le,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Un({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:c=>{this.syncScrollTop(c)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(e),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(h=this.stage)==null||h.batchDraw(),this.pendingDraftData){const c=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(c).catch(d=>{M.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,n,s){var d,u,g;if(!this.trackLayer)return M.error("TimelineManager","Track layer not initialized"),"";const r=this.trackManager.createTrack(e,t,i,n,s),o=r.id,l=Xe(e),h=this.calculateTrackY(o),c=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:o,clips:[],role:r.role},trackType:e,zoom:this.getZoomState(),trackY:h,trackHeight:l,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(d=c.setSnapTargetResolver)==null||d.call(c,()=>this.getClips()),(u=c.setDragOverlayLayer)==null||u.call(c,this.dragOverlayLayer),this.getTrackCollection().add(c),this.updateAllTrackPositions(),(g=this.stage)==null||g.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),o}removeTrack(e){var n,s,r,o;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return M.warn("TimelineManager","Cannot remove track with clips"),!1;if(((n=t.getRole)==null?void 0:n.call(t))==="primary")return M.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((r=(s=t.getTrackGroup)==null?void 0:s.call(t))==null||r.destroy(),this.getTrackCollection().removeById(e),this.updateAllTrackPositions(),(o=this.stage)==null||o.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),i}renameTrack(e,t){const i=this.trackManager.renameTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}getTracks(){return this.getResolvedTracksSnapshot()}initTrackInfoPanel(e){M.warn("TimelineManager","initTrackInfoPanel() is deprecated. TimelineManager now manages the frozen track-info panel inside the root container.")}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){const i=this.trackManager.muteTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return gt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return Wn(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=dh(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const n of e){const s=this.getTrackCollection().findById(n.trackId);s&&((t=s.setTrackY)==null||t.call(s,n.y),(i=s.setTrackHeight)==null||i.call(s,n.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}cleanupEmptyTracks(){var t,i,n,s;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return;const e=this.getTrackCollection().removeEmptyNonPrimaryTracks();if(e.length!==0){for(const r of e){const o=(t=r.getId)==null?void 0:t.call(r);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(n=(i=r.getTrackGroup)==null?void 0:i.call(r))==null||n.destroy(),this.getTrackCollection().removeById(o))}this.updateAllTrackPositions(),(s=this.stage)==null||s.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()}}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDropPreview)==null?void 0:t.call(e)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(e,t){this.showClipDropPreviews(new Map([[t,[e]]]))}showClipDropPreviews(e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(t=>{var s,r,o,l;const i=(s=t.getId)==null?void 0:s.call(t),n=i?e.get(i)??[]:[];if(n.length>0){n.length===1?(r=t.showClipDropPreview)==null||r.call(t,n[0]):(o=t.showClipDropPreviews)==null||o.call(t,n);return}(l=t.clearClipDropPreview)==null||l.call(t)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const e=ie.createLine([0,0,0,0],this.config.theme.clipSelectedBorder,2);e.name("timeline-track-insertion-preview-line"),e.dash([8,4]),e.visible(!1),e.listening(!1),this.snapGuideLayer.add(e),this.trackInsertionPreviewLine=e}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(e=!0){var i,n,s;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),e&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const t=((n=this.stage)==null?void 0:n.width())??0;this.trackInsertionPreviewLine.stroke(this.config.theme.clipSelectedBorder),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,t,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(t>0),this.trackInsertionPreviewLine.moveToTop(),e&&((s=this.snapGuideLayer)==null||s.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(s=>{var r;return(r=s.clearClipDropPreview)==null?void 0:r.call(s)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const n=this.trackManager.getTracks(),s=n.find(h=>h.role==="primary"),r=n.find(h=>h.type===e),o=[...n].reverse().find(h=>h.type===e);if((t==="before_track"||t==="after_track")&&i){const h=n.find(c=>c.id===i);if(h){const c=gt(n,h.id,this.getTrackContentTopOffset());return t==="before_track"?c:c+Xe(h.type)}}if(t==="top_of_type_region"&&r)return gt(n,r.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return gt(n,o.id,this.getTrackContentTopOffset())+Xe(o.type);if(!s)return e==="video"?this.getTrackContentTopOffset():Wn(n,this.getTrackContentTopOffset());const l=gt(n,s.id,this.getTrackContentTopOffset());return e==="video"?l:l+Xe(s.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),n=Math.max(i,t),s=this.clampScrollLeft(this.getScrollLeftState()),r=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(e,t,n),this.headerStage.width(e),this.timeline.resize(e),this.stage.width(e),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${n}px`,this.renderBodyBackground(e,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+t),this.refreshScrollbarMetrics(),this.syncScrollLeft(s),this.syncScrollTop(r),this.stage.batchDraw()}renderBodyBackground(e,t,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(e),this.bodyBackgroundRect.height(t),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const n=new U.Rect({x:0,y:0,width:e,height:t,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});n.on("click",s=>{this.handleBodyBackgroundClick(s.evt.offsetX)}),this.bodyBackgroundRect=n,this.backgroundLayer.add(n),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(e){const t=H.pixelsToTime(e-le+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,t))}handleBodyCanvasHostClick(e){if(!this.layout||e.target!==this.layout.bodyCanvasHost)return;const t=this.layout.bodyCanvasHost.getBoundingClientRect(),i=e.clientX-t.left;this.handleBodyBackgroundClick(i)}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=ie.createLine([0,0,0,this.calculateTotalHeight()],e.snapGuideLineColor||e.clipSelectedBorder,e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var n,s;if(!this.snapGuideLine)return;const t=this.config.theme;if(this.snapGuideLine.stroke(t.snapGuideLineColor||t.clipSelectedBorder),this.snapGuideLine.strokeWidth(t.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),e&&((n=this.snapGuideLayer)==null||n.batchDraw());return}const i=ce(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((s=this.snapGuideLayer)==null||s.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const s=this.getPrimaryWheelDelta(t,i);if(s===0)return;e.preventDefault(),this.handleWheelZoom(s,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const s=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(s===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+s);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===Th)return e*16;if(t===bh){const n=i==="x"?this.getViewportWidth():this.getViewportHeight();return e*(n||1)}return e}getPrimaryWheelDelta(e,t){return Math.abs(t)>=Math.abs(e)?t:e}isHorizontalWheelGesture(e,t){const i=Math.abs(e);if(i<.5)return!1;const n=Math.abs(t);return n<.5?!0:i>n*1.2}getHorizontalScrollDelta(e,t,i){return i&&Math.abs(t)>=Math.abs(e)?t:e}handleWheelZoom(e,t){const i=this.getZoomState(),n=Math.exp(-e*.002),s=Math.max(de.MIN,Math.min(de.MAX,i*n));Math.abs(s-i)<1e-4||this.setZoomCenteredOnTimelinePointer(s,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var s;const t=(s=this.layout)==null?void 0:s.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const n=e-t.left;return Math.max(0,Math.min(i,n))}play(){if(this.getPlayStateState()!=="playing"){if(this.pendingPreviewState){M.debugLazy("TimelineManager",()=>"Play blocked by pending preview state");return}if(!this.canPlay){M.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}this.setPlayStateState("playing"),this.lastUpdateTime=Date.now(),this.previewBuffering?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession()}}pause(){this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession())}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused")return;if(this.previewBuffering){this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0,this.animationFrameId=null;return}const e=Date.now(),t=e-this.lastUpdateTime;this.lastUpdateTime=e;const i=this.getCurrentTimeState()+t*this.getSpeedState();this.setCurrentTime(i),this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}syncPlaybackClockToPreviewBuffering(e){if(e){if(this.getPlayStateState()!=="playing"||(this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering||this.previewBufferingSuspendTimeoutId))return;this.previewBufferingSuspendTimeoutId=setTimeout(()=>{this.previewBufferingSuspendTimeoutId=null,!(this.getPlayStateState()!=="playing"||!this.previewBuffering||this.previewPlaybackSuspendedByBuffering)&&(this.previewPlaybackSuspendedByBuffering=!0,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null))},wh);return}if(this.clearPreviewBufferingSuspendTimeout(),!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&this.getPlayStateState()==="playing"&&!this.pendingPreviewState;this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,!(!t||this.animationFrameId)&&(this.lastUpdateTime=Date.now(),this.animate())}clearPreviewBufferingSuspendTimeout(){this.previewBufferingSuspendTimeoutId&&(clearTimeout(this.previewBufferingSuspendTimeoutId),this.previewBufferingSuspendTimeoutId=null)}setCurrentTime(e){const t=this.getTimelineCommands().setCurrentTime(e);if(!t.changed){this.pendingPreviewState&&this.pendingPreviewState.targetTime===t.nextValue&&this.syncPreviewSession();return}const i=t.nextValue;this.ensureConfigState().currentTime=i,this.syncCurrentTimeToScene(i),this.emitEvent("time_change",{time:i}),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(e){this.ensureConfigState().enableClipSnap=e,e||this.updateSnapGuideLine(null),this.tracks.forEach(t=>{t.setClipSnapEnabled(e)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setZoom(e){const t=this.getTimelineCommands().setZoom(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(e){const t=this.getZoomState(),i=this.getCurrentTimeState(),n=this.getTimelineCommands().setZoom(e);if(!n.changed)return;const s=n.nextValue;if(this.ensureConfigState().zoom=s,this.syncZoomToScene(s),this.refreshScrollbarMetrics(),this.timeline){const r=this.timeline.getScrollLeft(),o=H.timeToPixels(i,t),h=H.timeToPixels(i,s)-o+r;this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft())}this.emitEvent("zoom_change",{zoom:s})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),n=this.timeline.getScrollLeft(),s=H.pixelsToTime(t-le+n,i),r=this.getTimelineCommands().setZoom(e);if(!r.changed)return;const o=r.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const h=H.timeToPixels(s,o)-(t-le);this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft()),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(e){const t=this.getTimelineCommands().setSpeed(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount+this.previewSourceLoadingCount>0}getSourceLoadingState(){const e=this.sourceLoadingCount+this.previewSourceLoadingCount;return{isLoading:e>0,pending:e}}setThumbnailProvider(e){this.thumbnailProvider=e,this.config.thumbnailProvider=e,this.getClips().forEach(i=>{i.thumbnails||this.loadClipThumbnails(i)})}async loadClipThumbnails(e){if(!this.thumbnailProvider||e.type==="audio")return!1;try{const t=this.thumbnailProvider.getThumbnails(e);if(Array.isArray(t))return this.updateClip(e.id,{thumbnails:t}),!0;if(t instanceof Promise){const i=await t;if(Array.isArray(i))return this.updateClip(e.id,{thumbnails:i}),M.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:i.length})),!0}}catch(t){M.warn("TimelineManager","Error loading clip thumbnails:",{error:t,clipId:e.id})}return!1}async refreshClipThumbnails(e){const t=this.getClips().find(i=>i.id===e);return t?this.loadClipThumbnails(t):!1}async refreshAllClipThumbnails(){const e=this.getClips();return await Promise.all(e.map(i=>this.loadClipThumbnails(i)))}async addClip(e){this.beginSourceLoading();try{return await this.addClipInternal(e)}finally{this.endSourceLoading()}}async addClips(e){if(e.length===0)return[];this.beginSourceLoading();try{const t=[];for(const i of e){const n=await this.addClipInternal(i);t.push(n)}return t}finally{this.endSourceLoading()}}async addClipInternal(e){var f;let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.startTimeAtSource||0,n=e.duration,s=e.endTimeAtSource||i+n;let r=e.sourceDuration;if(!r)try{r=await H.getVideoDuration(e.src),r<=0&&(r=s)}catch(y){M.error("TimelineManager","Failed to get video duration:",{error:y}),r=s}let o=e.thumbnails;const l=e.id||`clip_${e.name}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=e.type||"video",c=Gi({id:l,type:h,externalId:e.externalId,src:e.src,name:e.name,isMuted:e.isMuted??!1,startTime:t,duration:n,startTimeAtSource:i,endTimeAtSource:s,sourceDuration:r,endTime:t+n,thumbnails:o,style:e.style,visualTransform:e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1});if(M.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:c.id,type:c.type,startTime:c.startTime,duration:c.duration})),e.trackId){const y=this.getTrackCollection().findById(e.trackId);if(y){if(this.registerPreviewAutoAspectRatioClip(c),(f=y.addClip)==null||f.call(y,c),Jt({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{M.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(S){M.warn("TimelineManager","Error loading clip thumbnails:",{error:S})}return c.id}}const d=this.getTimelineCommands().planTrackPlacement(c,this.getTracksSortedByOrder()),u=this.getTrackCollection(),g=rh({clip:c,placement:d,trackCollection:u,createTrack:this.createTrack.bind(this)});if(Jt({applied:g,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{M.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(y){M.warn("TimelineManager","Error loading clip thumbnails:",{error:y})}return c.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),Jt({applied:Fn(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)})}))}removeClipsByExternalId(e){if(!e)return!1;const t=this.resolveClipIdsForExternalIdRemoval(e);if(t.length===0)return!1;const i=new Set(t);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let n=!1;return this.withClipRemovalBatch(()=>{for(const s of t){const r=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);r.exists&&(n=Fn(this.getTrackCollection(),r,s)||n)}}),n?(Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){this.getTimelineCommands().findClipById(this.tracks,e)&&(this.getTrackCollection().updateClip(e,t),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);i!=null&&i.track.splitSelectedClip&&(i.track.splitSelectedClip(t),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e)??this.getTimelineCommands().findClipAtTime(this.tracks,e);t!=null&&t.track.splitSelectedClip&&(t.track.splitSelectedClip(e),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var n,s,r;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(rt(e.mode)&&t===be.width&&i===be.height){const o=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,l=(s=o==null?void 0:o.style)==null?void 0:s.sys_width,h=(r=o==null?void 0:o.style)==null?void 0:r.sys_height;typeof l=="number"&&l>0&&typeof h=="number"&&h>0&&(t=l,i=h)}return{width:t,height:i,aspectRatio:`${t}:${i}`,mode:e.mode}}exportTimeline(){var i,n,s;const e=this.getResolvedTracksSnapshot().slice().sort((r,o)=>r.order-o.order).map(r=>{const o=r.clips.map(l=>({id:l.id,type:l.type,externalId:l.externalId,src:l.src,name:l.name,isMuted:l.isMuted??!1,startTime:Math.round(l.startTime),duration:Math.round(l.duration),endTime:Math.round(l.endTime),startTimeAtSource:Math.round(l.startTimeAtSource),endTimeAtSource:Math.round(l.endTimeAtSource),sourceDuration:Math.round(l.sourceDuration),thumbnails:l.thumbnails,visualTransform:l.type==="video"?fe(l.visualTransform):void 0,separatedAudioClipId:l.separatedAudioClipId,separatedFromVideoClipId:l.separatedFromVideoClipId,volume:l.volume??1})).sort((l,h)=>l.startTime-h.startTime);return{id:r.id,type:r.type,name:r.name||"未命名轨道",order:r.order,role:r.role??"normal",isMuted:r.isMuted??!1,clips:o}}),t=((s=(n=(i=e[0].clips)==null?void 0:i[0])==null?void 0:n.thumbnails)==null?void 0:s[0])||"";return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){M.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const t=new Map,i=[...e.tracks].sort((h,c)=>h.order-c.order),n=this.resolveImportedTrackRoles(i);let s;for(const h of i){const c=this.createTrack(h.type,h.name,s?"after_track":void 0,s,n.get(h.id));c&&(this.muteTrack(c,h.isMuted),t.set(h.id,c),s=c)}const r=new Map,o=[];for(const h of i){const c=t.get(h.id);if(c)for(const d of h.clips)try{let u=d.separatedAudioClipId;u&&r.has(u)&&(u=r.get(u));let g=d.separatedFromVideoClipId;g&&r.has(g)&&(g=r.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,trackId:c},y=await this.addClip(f);r.set(d.id,y)}catch(u){o.push({clipId:d.id,error:u}),M.error("TimelineManager",`Failed to import clip ${d.id}:`,{error:u})}}this.clearHistory();const l={errors:o};this.emitEvent("draft_loaded",l)}resolveImportedTrackRoles(e){const t=new Map;let i=!1;for(const s of e){const r=s.role==="primary"&&!i?"primary":"normal";r==="primary"&&(i=!0),t.set(s.id,r)}if(i)return t;const n=this.inferImportedPrimaryTrackIndex(e);return n>=0&&t.set(e[n].id,"primary"),t}inferImportedPrimaryTrackIndex(e){var t;for(let i=e.length-1;i>=0;i-=1)if(((t=e[i])==null?void 0:t.type)==="video")return i;return e.length>0?0:-1}stopPlaybackForImport(){var i;const e=this.getPlayStateState()==="playing",t=(i=this.previewSession)!=null&&i.hasPreview()?this.previewMountContainer:null;this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),e?this.pause():this.setPlayStateState("paused"),this.destroyPreviewSession(!0),t&&(this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t,this.previewAspectRatio)),this.syncPreviewSession()}getClipsData(){return this.getClips()}getVersion(){return vh.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(h=>h.startTime)),n=(Math.max(...e.map(h=>h.endTime))-t)/1e3,s=((l=this.stage)==null?void 0:l.width())||0,r=s-le*2;M.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:n,containerWidth:s,availableWidth:r}));const o=Math.min(r/n,de.MAX);if(this.setZoom(o),this.timeline){const h=e.reduce((c,d)=>d.startTime<c.startTime?d:c);this.scrollToClip(h.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){this.beginPendingPreview(e,t),this.setCurrentTime(e)}handleScrollChange(e){this.syncScrollLeft(e)}handleClipUpdate(e,t,i){this.isExecutingHistoryAction||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i),this.emitEvent("clip_updated",{clip:e});const n=this.selectedClipId===e.id;Cl({notifySelectionChange:this.notifySelectionChange.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),n&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){this.registerPreviewAutoAspectRatioClip(e),this.emitEvent("clip_added",{clip:e}),Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(e){this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){vl(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{M.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){var s;const e=this.getClips(),t=this.getCurrentTime(),i=Tl(e,t),n=this.canPlay;this.canPlay=bl({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:((s=e[e.length-1])==null?void 0:s.endTime)||1,setCanPlay:r=>{this.canPlay=r},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:r=>{this.emitEvent("can_play_change",{canPlay:r})}}),n!==this.canPlay&&M.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:n,newState:this.canPlay}))}handleClipSplit(e,t){Pl({clip1:e,clip2:t,isExecutingHistoryAction:this.isExecutingHistoryAction,recordSplitClip:this.getTimelineHistoryRecorder().recordSplitClip.bind(this.getTimelineHistoryRecorder()),emitClipUpdated:i=>{this.emitEvent("clip_updated",{clip:i})},emitClipAdded:i=>{this.emitEvent("clip_added",{clip:i})},applyEffects:()=>Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=wl(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),M.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){M.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeUndo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}handleActionRedo(e){M.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeRedo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}on(e,t){this.getEventDispatcher().on(e,t)}off(e,t){this.getEventDispatcher().off(e,t)}emitEvent(e,t){this.getEventDispatcher().emit(e,t)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=sh({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}handleClipOverlap(e,t){M.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const i=this.getTrackCollection();if(!i.findById(t))return;const n=e.type,s=this.trackManager.getTracksByType(n).length+1,r=n==="video"?`视频轨道 ${s}`:`音频轨道 ${s}`;oh({clip:e,currentTrackId:t,trackType:n,trackName:r,trackCollection:i,createTrack:this.createTrack.bind(this)}),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const n=this.resolveCrossTrackPreviewDestination(e,t,i);return n.status==="existing_track"?(this.showClipDropPreview(e,n.targetTrackId),n.targetTrackId===i?"self":"external"):n.status==="new_track_insertion"?(this.showTrackInsertionPreview(n.trackType,n.insertionPlacement,n.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,n){M.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:n}));const s=this.resolveCrossTrackMoveDestination(e,i,n);return s.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):s.status==="same_track"?(M.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,n),!1):(M.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:s.targetTrackId})),this.showClipDropPreview(e,s.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,s.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}resize(e,t){this.rootContainer&&(this.rootContainer.style.width=`${e}px`,this.rootContainer.style.height=`${t}px`,this.updateViewportLayout())}scrollToTime(e,t=!1){this.timeline&&(this.timeline.scrollToTime(e),this.handleScrollChange(this.timeline.getScrollLeft()),t&&this.setCurrentTime(e))}notifySelectionChange(){const e=this.getSelectedClipIds();this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),e)}syncPrimarySelectionFromSelectionStore(){var t,i,n,s;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((s=(n=this.selectionStore)==null?void 0:n.getSelectedClipId)==null?void 0:s.call(n))??null;this.selectedClipId=e}getOrderedSelectionClipIds(e,t){const i=Array.from(new Set(e));if(i.length<=1)return i;const n=t&&i.includes(t)&&t||this.selectedClipId&&i.includes(this.selectedClipId)&&this.selectedClipId||i[0]||null;return n?[n,...i.filter(s=>s!==n)]:i}setSelection(e,t={}){this.resetMultiDragSession();const i=this.getOrderedSelectionClipIds(e,t.preferredPrimaryClipId);this.selectionStore.setSelection(i),this.syncPrimarySelectionFromSelectionStore(),this.notifySelectionChange(),this.emitSelectionChangeEvent(),t.selectedClipEventClip&&this.emitEvent("clip_selected",{clip:t.selectedClipEventClip}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}selectClip(e,t){var n;const i=t||((n=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:n.clip);this.setSelection([e],{preferredPrimaryClipId:e,selectedClipEventClip:i??null})}clearSelection(){this.setSelection([])}getSelectedClipIds(){var e,t;return((t=(e=this.selectionStore)==null?void 0:e.getSelectedClipIds)==null?void 0:t.call(e))??(this.selectedClipId?[this.selectedClipId]:[])}getPrimarySelectedClipId(){return this.getSelectedClipIds()[0]??null}addToSelection(e){this.setSelection([...this.selectionStore.getSelectedClipIds(),e],{preferredPrimaryClipId:this.selectedClipId??e})}removeFromSelection(e){this.setSelection(this.selectionStore.getSelectedClipIds().filter(t=>t!==e))}toggleSelection(e){const t=this.selectionStore.getSelectedClipIds(),i=t.includes(e);this.setSelection(i?t.filter(n=>n!==e):[...t,e],{preferredPrimaryClipId:i?void 0:e})}isClipSelected(e){return this.selectionStore.isSelected(e)}deleteSelectedClips(){this.resetMultiDragSession();const e=this.selectionStore.getSelectedClipIds();if(e.length===0)return;const t=this.getTimelineHistoryRecorder(),i=e.map(s=>{const r=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);return!r.exists||!r.clip?null:t.createRemoveClipAction({...r.clip},r.trackId,r.trackId?this.cloneTrackSnapshot(r.trackId):null,r.trackId?this.getTrackRestoreAnchor(r.trackId):null)}).filter(s=>s!==null);this.clearSelection();const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const s of e)this.removeClip(s)}finally{this.isExecutingHistoryAction=n}n||t.recordCompoundAction(i,"delete_selected_clips"),this.emitSelectionChangeEvent()}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.setSelection(this.tracks.flatMap(e=>e.getClips().map(t=>t.id)),{preferredPrimaryClipId:this.selectedClipId})}emitSelectionChangeEvent(){this.emitEvent("selection_change",{selectedClipIds:this.selectionStore.getSelectedClipIds()})}scrollToClip(e,t={}){const{selectClip:i=!1,setCurrentTime:n=!1}=t,s=this.getClips().find(r=>r.id===e);!s||!this.timeline||(this.timeline.scrollToClip(s),this.handleScrollChange(this.timeline.getScrollLeft()),n&&this.setCurrentTime(s.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}canDeleteSelectedClips(){return this.getSelectedClipIds().length>0}getSelectedClipAudioAction(){const e=this.getSelectedClips().filter(n=>n.type==="video");return e.length===0?null:e.some(n=>this.canSeparateClipAudio(n.id))?"separate":e.some(n=>this.canRestoreClipAudio(n.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const e=this.getSelectedClipAudioAction();return e?this.applySelectedClipAudioAction(e):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(e){return this.buildPlaybackPlan(e)}getActiveClipsAtTime(e){return this.buildPlaybackPlan(e).activeClips}attachPreview(e){const t=e instanceof HTMLElement?{container:e}:e;t.aspectRatio&&(this.previewAspectRatio=De({mode:t.aspectRatio.mode??(t.aspectRatio.width&&t.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:t.aspectRatio.width??this.previewAspectRatio.width,height:t.aspectRatio.height??this.previewAspectRatio.height})),this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t.container,this.previewAspectRatio),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){this.getPreviewRuntimeController().detachPreviewSession()&&(this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),M.debugLazy("TimelineManager",()=>"TimelineManager detached from preview container"))}attachClipConfig(e){const t=new Sh;t.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),updateClip:(s,r)=>{this.updateClip(s,r),this.handleClipChange()}});const i=()=>t.update(),n=(s,r)=>{var l;const o=this.getPrimarySelectedClip();o&&((l=r==null?void 0:r.clip)==null?void 0:l.id)===o.id&&t.updateFromExternal()};return this.on("selected_clip_change",i),this.on("clip_updated",n),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",i),this.off("clip_updated",n),t.destroy()}),t.update(),t}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return De(this.previewAspectRatio)}setPreviewAspectRatio(e){var t;this.previewAspectRatio=De({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...be},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}resolvePreferredSeparatedAudioTrackId(e,t){var l;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return null;const i=this.resolveTrackIdByClipId(e);if(!i)return null;const n=[...this.getResolvedTracksSnapshot()].sort((h,c)=>h.order-c.order),s=n.findIndex(h=>h.id===i);if(s===-1)return null;const r=t.startTime+t.duration,o=n.map((h,c)=>({track:h,index:c})).filter(({track:h})=>h.type==="audio").filter(({track:h})=>!h.clips.some(c=>t.startTime<c.endTime&&r>c.startTime));return o.length===0?null:(o.sort((h,c)=>{const d=Math.abs(h.index-s)-Math.abs(c.index-s);return d!==0?d:h.index-c.index}),((l=o[0])==null?void 0:l.track.id)??null)}async separateClipAudio(e){if(!this.canSeparateClipAudio(e))return null;const t=this.getClips().find(h=>h.id===e);if(!t||t.type!=="video")return null;const i=this.isExecutingHistoryAction,n=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let s=null;this.isExecutingHistoryAction=!0;try{if(s=await this.addClip({type:"audio",src:t.src,name:t.name,startTime:t.startTime,duration:t.duration,startTimeAtSource:t.startTimeAtSource,endTimeAtSource:t.endTimeAtSource,sourceDuration:t.sourceDuration,separatedFromVideoClipId:t.id,isMuted:!1,volume:t.volume??1,trackId:n??void 0}),!s)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:s})}finally{this.isExecutingHistoryAction=i}if(!s)return null;const r=this.getClips().find(h=>h.id===e),o=this.getClips().find(h=>h.id===s)??null,l=this.resolveTrackIdByClipId(s);return r?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,r,o,l),s):null}restoreClipAudio(e){if(!this.canRestoreClipAudio(e))return!1;const t=this.getClips().find(l=>l.id===e);if(!t||t.type!=="video")return!1;const i=t.separatedAudioClipId??null,n=i?this.getClips().find(l=>l.id===i)??null:null,s=i?this.resolveTrackIdByClipId(i):null,r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=r}const o=this.getClips().find(l=>l.id===e);return o?(r||this.getTimelineHistoryRecorder().recordRestoreClipAudio(t,o,n,s),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(o=>o.type==="video"),i=e==="separate"?t.filter(o=>this.canSeparateClipAudio(o.id)):t.filter(o=>this.canRestoreClipAudio(o.id));if(i.length===0)return!1;if(i.length===1){const[o]=i;return e==="separate"?!!await this.separateClipAudio(o.id):this.restoreClipAudio(o.id)}const n=this.getTimelineHistoryRecorder(),s=[],r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{if(e==="restore")for(const o of i){const l=this.getClips().find(f=>f.id===o.id);if(!l||l.type!=="video")continue;const h=l.separatedAudioClipId??null,c=h?this.getClips().find(f=>f.id===h)??null:null,d=h?this.resolveTrackIdByClipId(h):null,u=this.restoreClipAudio(o.id),g=this.getClips().find(f=>f.id===o.id);!u||!g||s.push(n.createRestoreClipAudioAction({...l},{...g},c?{...c}:null,d))}else for(const o of i){const l=this.getClips().find(g=>g.id===o.id);if(!l||l.type!=="video")continue;const h=await this.separateClipAudio(o.id),c=this.getClips().find(g=>g.id===o.id),d=h?this.getClips().find(g=>g.id===h)??null:null,u=h?this.resolveTrackIdByClipId(h):null;!h||!c||s.push(n.createSeparateClipAudioAction({...l},{...c},d?{...d}:null,u))}}finally{this.isExecutingHistoryAction=r}return r||n.recordCompoundAction(s,`selected_clips_audio_${e}`),s.length>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,n=null){const s=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(s.status==="missing_source_track")return M.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(s.status==="noop")return M.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(s.status==="missing_target_track")return M.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(s.status==="track_type_mismatch")return M.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var f,y,S;return{targetTrackType:(y=(f=this.getTrackCollection().findById(t))==null?void 0:f.getTrackType)==null?void 0:y.call(f),clipType:(S=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:S.clip.type}}),!1;if(s.status!=="ready")return!1;const{sourceTrackId:r,targetTrackId:o}=s,l=i?{...i}:{...s.clip},h=n?{...n}:{...s.clip},c=this.cloneTrackSnapshot(r),d=this.cloneTrackSnapshot(o),u=ah({command:{...s,clip:h},trackCollection:this.getTrackCollection()}),g=this.getClips().find(f=>f.id===e)??null;return kl({applied:u,clipId:e,sourceTrackId:r,targetTrackId:o,clipBefore:l,clipAfter:g??l,sourceTrackSnapshot:c,targetTrackSnapshot:d,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>lh({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 Gn(this.getClips())}destroy(){var e,t,i,n,s,r,o,l,h,c,d;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPreviewBufferingSuspendTimeout(),this.clearPendingPreviewState(),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(e=this.layout)==null||e.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(n=(t=this.layout)==null?void 0:(i=t.bodyCanvasHost).removeEventListener)==null||n.call(i,"click",this.bodyCanvasHostClickListener),(r=(s=this.rootContainer)==null?void 0:s.removeEventListener)==null||r.call(s,"wheel",this.rootWheelListener),(o=this.horizontalScrollbar)==null||o.destroy(),(l=this.verticalScrollbar)==null||l.destroy(),(h=this.playhead)==null||h.destroy(),(c=this.timeline)==null||c.destroy(),(d=this.stage)==null||d.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(e){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return e()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(e){const t=this.getClips(),i=new Map(t.map(r=>[r.id,r])),n=new Set,s=t.filter(r=>r.externalId===e).map(r=>r.id);for(let r=0;r<s.length;r+=1){const o=s[r];if(n.has(o))continue;n.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!n.has(l.separatedAudioClipId)&&s.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!n.has(l.separatedFromVideoClipId)&&s.push(l.separatedFromVideoClipId))}return t.filter(r=>n.has(r.id)).map(r=>r.id)}shouldClearSelectionForClipIds(e){return this.selectedClipId&&e.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(t=>e.has(t))}resolveSelectedClipAtTime(e){var i;const t=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const n of t){const s=this.getTimelineCommands().findClipById(this.tracks,n),r=s==null?void 0:s.clip;if(r&&e>=r.startTime&&e<r.endTime)return s}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{if(e.isFinal){const i=this.finalizeMultiDragCrossTrack(t,e);return i||this.syncMultiDragPeerClips(t,e,!0),i}return this.syncMultiDragOverlayState(t,e.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(t,e,!1),e.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(t,e.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(t,e)}finally{e.isFinal&&(this.syncMultiDragOverlayState(t,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((e,t)=>{var i;(i=e.setTrackStackOrder)==null||i.call(e,t)})}elevateMultiDragTrackGroups(e,t){var o,l,h;const i=this.resolveMultiDragSessionTrackIds(e);if(i.length<=1)return;const n=i.indexOf(t);n>=0&&(i.splice(n,1),i.push(t));const s=new Set(i);let r=0;for(const c of this.tracks){const d=(o=c.getId)==null?void 0:o.call(c);!d||s.has(d)||(l=c.setTrackStackOrder)==null||l.call(c,r++)}for(const c of i){const d=this.getTrackCollection().findById(c);(h=d==null?void 0:d.setTrackStackOrder)==null||h.call(d,r++)}}resolveMultiDragSessionTrackIds(e){var i;const t=new Set;for(const n of this.tracks){const s=(i=n.getId)==null?void 0:i.call(n);if(!s)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===s})&&t.add(s)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const n of e.selectedClipIds){const s=e.clips.get(n);if(!s)continue;const r=i.get(s.trackId);r?r.push(n):i.set(s.trackId,[n])}i.forEach((n,s)=>{var o;const r=this.getTrackCollection().findById(s);(o=r==null?void 0:r.setClipsDragOverlayActive)==null||o.call(r,n,t)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDragOverlay)==null?void 0:t.call(e)})}ensureMultiDragSession(e){var n;const t=this.selectionStore.getSelectedClipIds();if(t.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===e.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,t))return this.multiDragSession;const i=new Map;for(const s of t){const r=this.findTrackByClipId(s),o=((n=r==null?void 0:r.getId)==null?void 0:n.call(r))??this.resolveTrackIdByClipId(s),l=r==null?void 0:r.getClips().find(c=>c.id===s);if(!o||!l)continue;const h=s===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(s,{clipId:s,trackId:o,clip:h})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:e.draggedClipId,selectedClipIds:t.slice(),clips:i},this.multiDragSession)}haveSameClipIds(e,t){if(e.length!==t.length)return!1;const i=new Set(t);return e.every(n=>i.has(n))}restoreDraggedClipSnapshot(e,t){const i=Math.max(0,e.startTime-t);return{...e,startTime:i,endTime:i+e.duration}}syncMultiDragPeerClips(e,t,i){for(const n of e.selectedClipIds){if(n===t.draggedClipId)continue;const s=e.clips.get(n);if(!s||s.trackId===t.currentTrackId)continue;const r=this.getTrackCollection().findById(s.trackId);if(!(r!=null&&r.updateClipPosition))continue;const o=Math.max(0,s.clip.startTime+t.deltaTime);r.updateClipPosition(n,o,i,i?0:t.crossTrackOffsetY)}}previewMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const n=this.buildMovedClipSnapshot(i.clip,t.deltaTime),s=this.resolveCrossTrackPreviewDestination(n,t.targetTrackY,i.trackId);if(s.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(s.trackType,s.insertionPlacement,s.referenceTrackId),!0;if(s.status!=="existing_track"||s.targetTrackId===i.trackId)return!1;const r=this.resolveTrackIndexDelta(i.trackId,s.targetTrackId,i.clip.type);if(r===null)return!1;const o=new Map;this.appendPreviewClip(o,s.targetTrackId,n);for(const l of e.selectedClipIds){if(l===t.draggedClipId)continue;const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(h,r,c);!d||d===h.trackId||this.appendPreviewClip(o,d,c)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const n=this.buildMovedClipSnapshot(i.clip,t.deltaTime),s=this.resolveCrossTrackMoveDestination(n,t.targetTrackY,i.trackId);if(s.status==="blocked"||s.status==="same_track")return!1;const r=s.targetTrackId;if(!r)return!1;const o=this.resolveTrackIndexDelta(i.trackId,r,i.clip.type);if(o===null)return!1;for(const l of e.selectedClipIds){const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=c.startTime,u=l===t.draggedClipId?r:this.resolveMultiDragTargetTrackId(h,o,c);if(u){if(u===h.trackId){this.updateClipPositionWithHistory(h.trackId,h.clipId,d);continue}this.updateClipPositionSilently(h.trackId,h.clipId,d),this.moveClipToTrackWithHistorySnapshot(h.clipId,u,h.clip,c)}}return!0}resolveTrackIndexDelta(e,t,i){const n=this.getTrackIdsByType(i),s=n.indexOf(e),r=n.indexOf(t);return s===-1||r===-1?null:r-s}resolveMultiDragTargetTrackId(e,t,i){const n=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!n)return e.trackId;const s=this.calculateTrackY(n)+1,r=this.resolveCrossTrackMoveDestination(i,s,e.trackId);return r.status==="blocked"?n:r.targetTrackId}resolveMultiDragPreviewTargetTrackId(e,t,i){const n=this.findTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!n)return null;const s=this.calculateTrackY(n)+1,r=this.resolveCrossTrackPreviewDestination(i,s,e.trackId);return r.status==="existing_track"?r.targetTrackId:null}buildMovedClipSnapshot(e,t){const i=Math.max(0,e.startTime+t);return{...e,startTime:i,endTime:i+e.duration}}appendPreviewClip(e,t,i){const n=e.get(t);if(n){n.push(i);return}e.set(t,[i])}resolveCrossTrackMoveDestination(e,t,i){const n=this.trackManager.getTracks(),s=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),n,this.tracks);if(s.status==="missing_target_track_by_position")return M.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(s.status==="same_track")return{status:"same_track",targetTrackId:s.targetTrackId};if(s.status==="missing_target_track_view")return M.warn("TimelineManager","目标轨道不存在",{targetTrackId:s.targetTrackId}),{status:"blocked"};if(s.status==="track_type_mismatch")return M.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:s.targetTrackType,clipType:e.type})),{status:"blocked"};if(s.status==="move_to_track")return{status:"move_to_track",targetTrackId:s.targetTrackId};M.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const r=this.createTrack(s.trackType,void 0,s.insertionPlacement,s.referenceTrackId);return r?{status:"move_to_track",targetTrackId:r}:{status:"blocked"}}resolveCrossTrackPreviewDestination(e,t,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const n=this.trackManager.getTracks();if(!Array.isArray(n)||n.length===0)return{status:"clear"};const s=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),n,this.tracks);return s.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:s.targetTrackId}:s.status==="new_track_insertion"?{status:"new_track_insertion",trackType:s.trackType,insertionPlacement:s.insertionPlacement,referenceTrackId:s.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(e,t,i){let n=this.getTrackIdsByType(t);const s=n.indexOf(e);if(s===-1)return null;let r=s+i;for(;r<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;n=this.getTrackIdsByType(t),r+=1}for(;r>=n.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;n=this.getTrackIdsByType(t)}return n[r]??null}findTrackIdByRelativeIndex(e,t,i){const n=this.getTrackIdsByType(t),s=n.indexOf(e);if(s===-1)return null;const r=s+i;return r<0||r>=n.length?null:n[r]??null}getTrackIdsByType(e){return this.trackManager.getTracks().filter(t=>t.type===e).map(t=>t.id)}updateClipPositionWithHistory(e,t,i){var s;const n=this.getTrackCollection().findById(e);(s=n==null?void 0:n.updateClipPosition)==null||s.call(n,t,i,!0)}updateClipPositionSilently(e,t,i){const n=this.getTrackCollection().findById(e);if(!(n!=null&&n.updateClipPosition))return;const s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{n.updateClipPosition(t,i,!0)}finally{this.isExecutingHistoryAction=s}}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new U.Rect({fill:"rgba(80, 130, 230, 0.15)",stroke:"#5082e6",strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(t=this.selectionBoxLayer)==null||t.add(e),this.selectionBoxRect=e,e}showSelectionBoxRect(e,t,i,n){var r;const s=this.ensureSelectionBoxRect();s.x(e),s.y(t),s.width(Math.max(i,1)),s.height(Math.max(n,1)),s.visible(!0),(r=this.selectionBoxLayer)==null||r.batchDraw()}hideSelectionBoxRect(){var e;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(e=this.selectionBoxLayer)==null||e.batchDraw())}handleStageMouseDown(e){if(e.button!==0)return;const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top;if(this.isPointOnClip(s,r))return;this.isBoxSelecting=!1,this.boxSelectStartX=s,this.boxSelectStartY=r;const l=c=>{this.handleBoxSelectMove(c)},h=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",h)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",h)}handleBoxSelectMove(e){const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top,o=Math.abs(s-this.boxSelectStartX),l=Math.abs(r-this.boxSelectStartY);if(!this.isBoxSelecting&&(o>4||l>4)&&(this.isBoxSelecting=!0),!this.isBoxSelecting)return;const h=Math.min(this.boxSelectStartX,s),c=Math.min(this.boxSelectStartY,r),d=Math.abs(s-this.boxSelectStartX),u=Math.abs(r-this.boxSelectStartY);this.showSelectionBoxRect(h,c,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const e=this.selectionBoxRect;if(e){const t={x:e.x(),y:e.y(),width:e.width(),height:e.height()},i=this.getClipsIntersectingBox(t);this.setSelection(i,{preferredPrimaryClipId:this.selectedClipId})}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(e,t){for(const i of this.tracks){const n=i.getTrackGroup(),s=n.y(),r=n.height()||64;if(!(t<s||t>s+r))for(const o of i.getClips()){const l=ce(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=H.timeToPixels(o.duration,this.getZoomState());if(e>=l&&e<=l+h&&t>=s+2&&t<=s+r-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const n=i.getTrackGroup(),s=n.y(),r=n.height()||64;for(const o of i.getClips()){const l=ce(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=H.timeToPixels(o.duration,this.getZoomState()),c=s+2,d=r-4,u=l+h,g=c+d,f=e.x+e.width,y=e.y+e.height;l<f&&u>e.x&&c<y&&g>e.y&&t.push(o.id)}}return t}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(n=>n.id===e);return t?{...t,clips:t.clips.map(n=>({...n}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const n=this.resolveTrackInsertionFromRestoreAnchor(t);if(n){const u=this.createTrack(e.type,e.name,n.insertionPlacement,n.referenceTrackId);return this.muteTrack(u,e.isMuted??!1),u}const s=[...this.getTracks()].sort((u,g)=>u.order-g.order),r=s.find(u=>u.order>=e.order),o=r?s[s.findIndex(u=>u.id===r.id)-1]??null:s[s.length-1]??null;let l,h;r?(l="before_track",h=r.id):o&&(l="after_track",h=o.id);const c=this.createTrack(e.type,e.name,l,h);return this.muteTrack(c,e.isMuted??!1),c}getTrackRestoreAnchor(e){var n,s,r;if(!((n=this.trackManager)!=null&&n.getTracks))return null;const t=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=t.findIndex(o=>o.id===e);return i===-1?null:{previousTrackId:((s=t[i-1])==null?void 0:s.id)??null,nextTrackId:((r=t[i+1])==null?void 0:r.id)??null}}resolveTrackInsertionFromRestoreAnchor(e){return e?e.previousTrackId&&this.getTrackCollection().findById(e.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:e.previousTrackId}:e.nextTrackId&&this.getTrackCollection().findById(e.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:e.nextTrackId}:null:null}resolveTrackIdByClipId(e){var t;return((t=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:t.trackId)??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var r;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastEffectiveTrackDuration,n=Kl(e),s=Gn(e);if(n!==t){this.lastTrackDuration=n;const o=Hn(n);this.setDurationState(o),(r=this.timeline)==null||r.setDuration(o),this.updateViewportLayout()}s!==i&&(this.lastEffectiveTrackDuration=s,this.emitEvent("track_duration_change",{duration:s})),!(n===t&&s===i)&&M.debugLazy("TimelineManager",()=>`Track duration changed: effective=${s}ms, extent=${n}ms, timeline=${Hn(n)}ms`)}resolveSelectedClipSnapshot(){return nh({getPrimarySelectedClip:()=>{var e;return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null},findFallbackSelectedClip:()=>this.tracks?this.getTimelinePresentationAdapter().findSelectedClip(this.getTrackCollection()):null})}commitPreviewVisualTransform(e,t){const i=this.getClips().find(r=>r.id===e);if(!i||i.type!=="video")return;const n=fe(i.visualTransform),s=fe(t);Ns(n,s)||this.updateClip(e,{visualTransform:s})}clearAllTracksAndClips(){var t,i,n,s;const e=this.getTracks();for(const r of e){const o=this.getTrackCollection().findById(r.id);if(o){const l=[...o.getClips()];for(const h of l)(t=o.removeClip)==null||t.call(o,h.id)}}for(const r of e){const o=r.id,l=this.getTrackCollection().findById(o);(n=(i=l==null?void 0:l.getTrackGroup)==null?void 0:i.call(l))==null||n.destroy(),this.getTrackCollection().removeById(o)}this.trackManager.clearAllTracks(),this.updateAllTrackPositions(),(s=this.stage)==null||s.batchDraw()}}exports.CLIP_LAYER=Ks;exports.Clip=Zt;exports.ClipConfigPanel=Hs;exports.DEFAULT_CLIP_VIEW_STATE=$n;exports.DEFAULT_PREVIEW_ASPECT_RATIO=be;exports.HistoryManager=Di;exports.MIN_CLIP_LINE_WIDTH=At;exports.PREVIEW_ASPECT_RATIO_PRESETS=qs;exports.Playhead=rl;exports.TIMELINE_LEFT_PADDING=le;exports.TIME_SCALE=js;exports.TRACK_HEIGHT=_e;exports.TimeUtils=H;exports.Timeline=Qo;exports.TimelineManager=kh;exports.Track=ii;exports.TrackInfoPanel=Gs;exports.TrackManager=Vs;exports.ZOOM_ANIMATION=qn;exports.ZOOM_PRESETS=de;exports.createClipViewState=Kn;exports.createClipWithViewState=Gi;exports.defaultDarkTheme=Qt;exports.isAutoPreviewAspectRatioMode=rt;exports.normalizePreviewAspectRatio=De;exports.normalizePreviewAspectRatioMode=Bi;exports.resolveTheme=It;
|
|
111
|
+
`,document.head.appendChild(a)}function ph(a,e){uh();const t=e.leftPanelWidth??Ws,i=e.scrollbarSize??Ys;a.innerHTML="",a.classList.add("timeline-manager-root"),a.style.gridTemplateColumns=`${t}px minmax(0, 1fr)`,a.style.gridTemplateRows=`${e.timeScaleHeight}px minmax(0, 1fr)`,a.style.background=e.theme.background;const n=ke("div");n.className="timeline-manager-header-corner",qt(n,e.theme),n.style.gridColumn="1",n.style.gridRow="1",n.style.borderBottom=`1px solid ${e.theme.border}`;const s=ke("div");s.className="timeline-manager-header-viewport",qt(s,e.theme),s.style.gridColumn="2",s.style.gridRow="1",s.style.borderBottom=`1px solid ${e.theme.border}`,s.style.overflow="hidden";const r=ke("div");r.className="timeline-manager-header-canvas-host",r.style.width="100%",r.style.height="100%",s.appendChild(r);const o=ke("div");o.className="timeline-manager-track-info-viewport",qt(o,e.theme),o.style.gridColumn="1",o.style.gridRow="2",o.style.overflow="hidden",o.style.borderRight=`1px solid ${e.theme.border}`;const l=ke("div");l.className="timeline-manager-scroll-viewport timeline-manager-body-viewport",qt(l,e.theme),l.style.gridColumn="2",l.style.gridRow="2",l.style.overflowX="hidden",l.style.overflowY="auto";const h=ke("div");h.className="timeline-manager-body-canvas-host",h.style.width="100%",h.style.height="100%",h.style.position="relative",h.style.background=e.theme.background,l.appendChild(h);const c=ke("div");c.className="timeline-manager-v-scrollbar-canvas-host",c.style.position="absolute",c.style.top=`${e.timeScaleHeight}px`,c.style.right="0",c.style.bottom="0",c.style.width=`${i}px`,c.style.zIndex="5";const d=ke("div");d.className="timeline-manager-h-scrollbar-canvas-host",d.style.position="absolute",d.style.left=`${t}px`,d.style.right="0",d.style.bottom="0",d.style.height=`${i}px`,d.style.zIndex="4";const u=ke("div");return u.className="timeline-manager-playhead-overlay",u.style.position="absolute",u.style.left=`${t}px`,u.style.top="0",u.style.right="0",u.style.bottom="0",u.style.pointerEvents="none",u.style.zIndex="3",a.appendChild(n),a.appendChild(s),a.appendChild(o),a.appendChild(l),a.appendChild(c),a.appendChild(d),a.appendChild(u),{headerCorner:n,headerViewport:s,headerCanvasHost:r,trackInfoViewport:o,bodyViewport:l,bodyCanvasHost:h,verticalScrollbarCanvasHost:c,horizontalScrollbarCanvasHost:d,playheadOverlay:u}}function ke(a){return document.createElement(a)}function qt(a,e){a.style.position="relative",a.style.minWidth="0",a.style.minHeight="0",a.style.maxWidth="100%",a.style.boxSizing="border-box",a.style.background=e.background,a.style.color=e.clipName}class gh{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 Xs{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 fh{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 Xn{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new Xs,this.playbackStore=new gh({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new fh({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 mh{constructor(e,t,i,n,s){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=n,this.onScrollChange=s,this.config={duration:i.duration||36e5,zoom:i.zoom||de.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:It(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(e){}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setScrollLeft(e){this.scrollLeft=this.clampScrollLeft(e),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(e){const t=H.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=H.timeToPixels(e.startTime,this.config.zoom),n=H.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,s=this.stage.width(),r=n<=s?Math.max(0,t-(s-n)/2):Math.max(0,t);this.setScrollLeft(r)}resize(e){this.stage.width(e),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",e=>{e.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(e.evt.offsetX),"seek")}),this.stage.on("mousedown",e=>{e.target.getLayer()===this.layer&&(this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(Rt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(e){const t=e.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-t),n=this.scrollLeft;this.dragStartX=e.clientX,this.scrollLeft=i,this.render(),n!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(e){return H.pixelsToTime(e-le+this.scrollLeft,this.config.zoom)}timeToPixel(e){return H.timeToPixels(e,this.config.zoom)-this.scrollLeft+le}render(){const e=this.stage.width(),t=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const n=ie.createRect(0,0,e,t,this.theme.background,this.theme.border,1);n.name("timeline-header-background"),this.layer.add(n)}this.layer.find(".time-tick-line").forEach(n=>n.remove()),this.layer.find(".time-tick-text").forEach(n=>n.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,n=H.pixelsToTime(t,this.config.zoom),s=H.pixelsToTime(i,this.config.zoom),r=H.msToSeconds(n),o=H.msToSeconds(s),{majorStep:l,minorStep:h}=H.getTickConfig(this.config.zoom),c=H.generateVisibleTicks(r-10,o+10,l,h);for(const d of c){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&ie.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,H.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const V=class V{constructor(e,t,i,n,s,r,o){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 n=this.scrollLeft,s=this.onHorizontalAutoScroll(this.scrollLeft+i),r=typeof s=="number"?s:this.scrollLeft;if(this.scrollLeft=Math.max(0,r),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-n)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=e,this.currentTime=t,this.zoom=i,this.height=n,this.theme=s,this.onTimeChange=r,this.onHorizontalAutoScroll=o,this.container.innerHTML="",this.container.style.position="absolute",this.container.style.pointerEvents="none",this.container.style.overflow="visible",this.visualElement=document.createElementNS(V.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${V.VISUAL_WIDTH}`),this.visualElement.style.position="absolute",this.visualElement.style.top="0",this.visualElement.style.marginLeft=`${-14/2}px`,this.visualElement.style.pointerEvents="none",this.visualElement.style.overflow="visible",this.lineHitAreaElement=document.createElement("div"),this.lineHitAreaElement.className="timeline-manager-playhead-hit-area",this.lineHitAreaElement.style.position="absolute",this.lineHitAreaElement.style.top="0",this.lineHitAreaElement.style.width=`${V.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Rt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,n=H.pixelsToTime(i-le+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,n),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(V.AUTO_SCROLL_EDGE_THRESHOLD,t/2),n=V.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-n;if(e>=t)return n;if(e<i){const s=(i-e)/i;return-Math.max(1,Math.round(s*n))}if(e>t-i){const s=(e-(t-i))/i;return Math.max(1,Math.round(s*n))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const e=H.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+le,t=e>=0&&e<=this.container.clientWidth,i=Math.max(V.HANDLE_HEIGHT+V.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${V.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=this.theme.clipSelectedBackground||"#8c90ff",i=Math.max(V.HANDLE_HEIGHT,e-V.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i,this.theme.playhead))}createHandleShadowPath(){const e=document.createElementNS(V.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill","rgba(0, 0, 0, 0.22)"),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(V.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(V.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(V.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),t.setAttribute("y",`${V.HANDLE_LINE_START}`),t.setAttribute("width",`${V.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-V.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e,t){const i=document.createElementNS(V.SVG_NS,"g");i.setAttribute("class","timeline-manager-playhead-end-cap"),i.setAttribute("transform",`translate(0 ${e})`);const n=document.createElementNS(V.SVG_NS,"rect");n.setAttribute("x",`${(V.VISUAL_WIDTH-V.LINE_WIDTH)/2}`),n.setAttribute("y","0"),n.setAttribute("width",`${V.LINE_WIDTH}`),n.setAttribute("height","7"),n.setAttribute("rx","1"),n.setAttribute("fill",t);const s=document.createElementNS(V.SVG_NS,"rect");return s.setAttribute("x",`${(V.VISUAL_WIDTH-V.END_CAP_WIDTH)/2}`),s.setAttribute("y","7"),s.setAttribute("width",`${V.END_CAP_WIDTH}`),s.setAttribute("height","3"),s.setAttribute("rx","1.5"),s.setAttribute("fill",t),i.appendChild(n),i.appendChild(s),i}};p(V,"SVG_NS","http://www.w3.org/2000/svg"),p(V,"VISUAL_WIDTH",14),p(V,"HANDLE_HEIGHT",16),p(V,"HANDLE_LINE_START",13),p(V,"LINE_WIDTH",2),p(V,"LINE_HIT_WIDTH",12),p(V,"END_CAP_WIDTH",14),p(V,"END_CAP_HEIGHT",10),p(V,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(V,"AUTO_SCROLL_MAX_SPEED",18);let Oi=V;class Un{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 n;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((n=e.target)==null?void 0:n.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});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 U.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new U.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=ie.createRect(0,0,0,0,"rgba(0, 0, 0, 0.001)","transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=ie.createRect(0,0,0,0,this.theme.scrollbarThumb||"#444444",this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555",1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=Mt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(Rt({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(e){const i=(this.orientation==="horizontal"?e.clientX:e.clientY)-this.dragStartClient,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),r=Math.max(1,n-s),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/r*o;this.emitScrollChange(l)}jumpToPointer(e){const t=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?e-t.left:e-t.top,n=this.getAvailableTrackSize(),s=this.getThumbSize(n),r=Math.max(1,n-s),o=Math.max(0,Math.min(n,i-this.leadingInset)),l=Math.max(0,Math.min(r,o-s/2)),h=this.getMaxScrollOffset(),c=r<=0?0:l/r*h;this.emitScrollChange(c)}emitScrollChange(e){const t=this.clampScrollOffset(e);this.scrollOffset=t,this.render(),this.onScrollChange(t)}render(){const e=Math.max(0,this.container.clientWidth),t=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(e),this.stage.height(t),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(e),this.hitAreaRect.height(t),this.thumbRect.fill(this.theme.scrollbarThumb||"#444444"),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||"#555555");const n=this.getAvailableTrackSize();if(n<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const s=this.getThumbSize(n),r=this.leadingInset+this.getThumbPosition(n,s);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(r),this.thumbRect.y(0),this.thumbRect.width(s),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(r),this.thumbRect.width(e),this.thumbRect.height(s)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const n=Math.max(1,e-t);return this.scrollOffset/i*n}}class yh{constructor(){p(this,"entries",new Map)}register(e,t){this.entries.set(e,{id:e,destroy:t})}unregister(e){this.entries.delete(e)}destroyAll(){for(const e of this.entries.values())e.destroy();this.entries.clear()}}class Sh{constructor(){p(this,"panel",null);p(this,"config",null);p(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new Hs({container:e.container,theme:t,onClipUpdate:(i,n)=>{this.isInternalUpdate=!0,e.updateClip(i,n),setTimeout(()=>{this.isInternalUpdate=!1},0)}})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip();this.panel.setClip(e)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}convertTheme(e){return{backgroundColor:e.background||"#1e1e1e",borderColor:e.border||"#333",textColor:e.clipName||"#e0e0e0",labelColor:e.timeText||"#999",inputBackground:e.trackBackground||"#2d2d2d",inputBorder:e.trackBorder||"#444",inputFocusBorder:"#409eff",buttonBackground:e.clipBackground||"#2d2d2d",buttonBorder:e.clipBorder||"#444",buttonActiveBackground:e.clipSelectedBackground||"#409eff",buttonActiveBorder:e.clipSelectedBorder||"#409eff",buttonActiveText:e.clipSelectedName||"#fff"}}}const Ch="2.0.9",vh={version:Ch},Th=1,bh=2,wh=120;class kh{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,"lastEffectiveTrackDuration",0);p(this,"thumbnailProvider",null);p(this,"canPlay",!1);p(this,"sourceLoadingCount",0);p(this,"timelineStore");p(this,"timelineCommands");p(this,"timelineHistoryExecutor");p(this,"timelineHistoryRecorder");p(this,"timelinePresentationAdapter");p(this,"timelineTrackBridge");p(this,"timelinePlaybackResolver");p(this,"previewRuntimeController");p(this,"previewStateController");p(this,"previewPlaybackSuspendedByBuffering",!1);p(this,"previewPlaybackAutoResume",!1);p(this,"previewBufferingSuspendTimeoutId",null);p(this,"lastSelectedClipId",null);p(this,"previewAspectRatio",{...be});p(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});p(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});p(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});p(this,"mountManager",new yh);p(this,"pendingDraftData",null);p(this,"selectionStore",new Xs);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);this.config={duration:e.duration||36e5,zoom:e.zoom||de.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:It(e.theme),timeScaleHeight:e.timeScaleHeight,logConfig:e.logConfig,speed:e.speed||1,dragActivationThreshold:e.dragActivationThreshold??4,enableClipSnap:e.enableClipSnap??!1,clipSnapThreshold:e.clipSnapThreshold??8,thumbnailProvider:e.thumbnailProvider,previewBackend:e.previewBackend??"dom",previewSourceResolver:e.previewSourceResolver},M.setConfig(this.config.logConfig),M.debug("TimelineManager","日志系统初始化完成",{logConfig:this.config.logConfig}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new hh,this.eventDispatcher=new Nn({can_play_change:()=>({canPlay:this.canPlay}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new Di(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Ln(this.history),this.timelineHistoryExecutor=new En({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 Vs,this.timelineStore=new Xn({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new An(this.timelineStore),this.timelinePresentationAdapter=new zn,this.timelineTrackBridge=new Vn({onClipUpdate:(t,i,n)=>this.handleClipUpdate(t,i,n),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),e.draftData&&(this.pendingDraftData=e.draftData),this.config.container&&this.init(this.config.container)}getTimelineStore(){var e,t,i,n,s;if(!this.timelineStore){const r=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,h=((n=this.config)==null?void 0:n.zoom)||de.MEDIUM,c=((s=this.config)==null?void 0:s.duration)||36e5;this.timelineStore=new Xn({currentTime:r,playState:o,speed:l,zoom:h,duration:c})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new An(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new ch(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new zn),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Vn({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.setCurrentTime.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this)})),this.timelineTrackBridge}getTimelinePlaybackResolver(){return this.timelinePlaybackResolver||(this.timelinePlaybackResolver=new Jl),this.timelinePlaybackResolver}get previewSession(){return this.getPreviewRuntimeController().previewSession}set previewSession(e){this.getPreviewRuntimeController().previewSession=e}get previewMountContainer(){return this.getPreviewRuntimeController().previewMountContainer}set previewMountContainer(e){this.getPreviewRuntimeController().previewMountContainer=e}get resolvedPreviewBackend(){return this.getPreviewRuntimeController().resolvedPreviewBackend}set resolvedPreviewBackend(e){this.getPreviewRuntimeController().resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this.getPreviewRuntimeController().runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this.getPreviewRuntimeController().runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this.getPreviewRuntimeController().activePreviewCallbackToken}set activePreviewCallbackToken(e){this.getPreviewRuntimeController().activePreviewCallbackToken=e}get previewSourceLoadingCount(){return this.getPreviewStateController().previewSourceLoadingCount}set previewSourceLoadingCount(e){this.getPreviewStateController().previewSourceLoadingCount=e}get previewBuffering(){return this.getPreviewStateController().previewBuffering}set previewBuffering(e){this.getPreviewStateController().previewBuffering=e}get pendingPreviewState(){return this.getPreviewStateController().pendingPreviewState}set pendingPreviewState(e){this.getPreviewStateController().pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this.getPreviewStateController().nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this.getPreviewStateController().nextPendingPreviewSyncRequestId=e}getPreviewStateController(){return this.previewStateController||(this.previewStateController=new ih({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitBufferingStateChange:e=>{this.syncPlaybackClockToPreviewBuffering(e),this.emitEvent("buffering_state_change",{isBuffering:e})},emitSourceLoadingStateChange:()=>{this.emitEvent("source_loading_change",this.getSourceLoadingState())},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new Ql({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Xl({callbacks:t,previewSourceResolver:this.config.previewSourceResolver}),resolveConfiguredBackend:e=>e||Ul(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onBufferingStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleBufferingStateChange(t)},onSourceLoadingChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleSourceLoadingChange(t)},onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().handleRuntimeStateChange(t)},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=De(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(e)&&this.retryPendingPreview()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Nn({can_play_change:()=>({canPlay:this.canPlay??!1}),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),source_loading_change:()=>this.getSourceLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new Di(()=>{},()=>{})),this.timelineHistoryRecorder=new Ln(this.history)),this.timelineHistoryRecorder}getTimelineHistoryExecutor(){return this.timelineHistoryExecutor||(this.timelineHistoryExecutor=new En({removeClip:this.removeClip.bind(this),addClipToTrack:this.addClipToTrack.bind(this),updateClip:this.updateClip.bind(this),moveClipToTrack:this.moveClipToTrack.bind(this),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),loadClipThumbnails:this.loadClipThumbnails.bind(this)})),this.timelineHistoryExecutor}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:36e5,zoom:de.MEDIUM,currentTime:0,playState:"paused",theme:It(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,clipSnapThreshold:8,previewBackend:"dom"}),this.config}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(e){this.getTimelineStore().setPlayState(e),this.ensureConfigState().playState=e}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(e){this.getTimelineStore().setDuration(e),this.ensureConfigState().duration=e}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(e){this.getTimelineStore().setScrollLeft(e)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(e){this.getTimelineStore().setScrollTop(e)}setViewportMetrics(e,t,i){const n=this.getTimelineStore();n.setViewportWidth(e),n.setViewportHeight(t),n.setContentHeight(i)}syncCurrentTimeToScene(e){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncZoomToScene(e){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncScrollTopPresentation(e){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,e)}refreshScrollbarMetrics(){var i,n,s,r;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(n=this.verticalScrollbar)==null||n.resize(),(s=this.horizontalScrollbar)==null||s.setViewportMetrics(e,this.getHorizontalContentWidth()),(r=this.verticalScrollbar)==null||r.setViewportMetrics(t,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientWidth)||0}getViewportHeight(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return H.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(e){const t=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(t,e))}clampScrollTop(e){const t=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(t,e))}syncScrollLeft(e){var i,n;const t=this.clampScrollLeft(e);this.setScrollLeftState(t),(i=this.timeline)==null||i.setScrollLeft(t),(n=this.horizontalScrollbar)==null||n.setScrollLeft(t),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),t),this.refreshSnapGuideLine()}syncScrollTop(e){var i;const t=this.clampScrollTop(e);this.setScrollTopState(t),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-t)>.5&&(this.layout.bodyViewport.scrollTop=t),this.syncScrollTopPresentation(t)}getResolvedTracksSnapshot(){const e=this.getTrackCollection();return this.trackManager.getTracks().map(t=>{const i=e.findById(t.id);return{...t,clips:i?i.getClips():[...t.clips]}})}getTracksSortedByOrder(){const e=this.getTrackCollection();return this.trackManager.getTracks().slice().sort((t,i)=>t.order-i.order).map(t=>e.findById(t.id)).filter(t=>t!==null)}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(e=>({id:e.id,type:e.type,order:e.order,isMuted:e.isMuted??!1,clips:e.clips}))}buildPlaybackPlan(e=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),e)}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((r,o)=>r.order-o.order);let i=null,n=null,s=Number.POSITIVE_INFINITY;for(const r of t){if(r.type!=="video")continue;const o=[...r.clips].sort((l,h)=>l.startTime-h.startTime);for(const l of o){const h={trackId:r.id,trackType:r.type,trackOrder:r.order,clip:l,mediaTime:l.startTimeAtSource,muted:(r.isMuted??!1)||(l.isMuted??!1),kind:r.type,hasVisual:!0,hasAudio:!0};i||(i=h);const c=e.get(l.id);c===void 0||c>=s||(n=h,s=c)}}return n||i}registerPreviewAutoAspectRatioClip(e){const t=this,i=this.getPreviewAutoAspectRatioClipOrderMap();e.type!=="video"||i.has(e.id)||(i.set(e.id,this.getNextPreviewAutoAspectRatioOrder()),t.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}syncPreviewSession(){var n,s,r;if(!((n=this.previewSession)!=null&&n.hasPreview()))return;const e=this.buildPlaybackPlan(),t=this.getAutoAspectRatioClip(),i=De(this.previewAspectRatio);this.previewAspectRatio=i,this.previewSession.applyAspectRatio(i),this.previewSession.sync({...e,autoAspectRatioClip:t,currentTime:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),primarySelectedClipId:this.getPrimarySelectedClipId(),...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),(r=(s=this.previewSession).setPendingState)==null||r.call(s,this.buildPreviewPendingState())}beginPendingPreview(e,t="seek"){var n,s;if(!((n=this.previewSession)!=null&&n.hasPreview()))return;const i=((s=this.pendingPreviewState)==null?void 0:s.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPlayStateState()==="playing"&&this.pause(),this.getPreviewStateController().beginPendingPreview(e,t,i)}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState()}destroyPreviewSession(e=!1){this.getPreviewRuntimeController().destroyPreviewSession(e),this.resetPreviewRuntimeState()}retryPendingPreview(){this.getPreviewStateController().retryPendingPreview()}handlePreviewBackendRuntimeError(){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();const e=this.getPreviewRuntimeController().fallbackToDom(De(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,n,s,r,o,l,h;if(this.isInitialized){M.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=ph(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Ws,scrollbarSize:Ys}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(n=(i=this.layout.bodyCanvasHost).addEventListener)==null||n.call(i,"click",this.bodyCanvasHostClickListener),(r=(s=this.rootContainer)==null?void 0:s.addEventListener)==null||r.call(s,"wheel",this.rootWheelListener,{passive:!1}),this.headerStage=new U.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new U.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new U.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new U.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new U.Layer({name:"trackLayer"}),this.dragOverlayLayer=new U.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new U.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new U.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const t=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(t&&t.addEventListener("mousedown",this.handleStageMouseDown.bind(this)),this.timeline=new mh(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new Oi(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 Un({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:le,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Un({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:c=>{this.syncScrollTop(c)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(e),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(h=this.stage)==null||h.batchDraw(),this.pendingDraftData){const c=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(c).catch(d=>{M.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,n,s){var d,u,g;if(!this.trackLayer)return M.error("TimelineManager","Track layer not initialized"),"";const r=this.trackManager.createTrack(e,t,i,n,s),o=r.id,l=Xe(e),h=this.calculateTrackY(o),c=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:o,clips:[],role:r.role},trackType:e,zoom:this.getZoomState(),trackY:h,trackHeight:l,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(d=c.setSnapTargetResolver)==null||d.call(c,()=>this.getClips()),(u=c.setDragOverlayLayer)==null||u.call(c,this.dragOverlayLayer),this.getTrackCollection().add(c),this.updateAllTrackPositions(),(g=this.stage)==null||g.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession(),o}removeTrack(e){var n,s,r,o;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return M.warn("TimelineManager","Cannot remove track with clips"),!1;if(((n=t.getRole)==null?void 0:n.call(t))==="primary")return M.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((r=(s=t.getTrackGroup)==null?void 0:s.call(t))==null||r.destroy(),this.getTrackCollection().removeById(e),this.updateAllTrackPositions(),(o=this.stage)==null||o.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),i}renameTrack(e,t){const i=this.trackManager.renameTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}getTracks(){return this.getResolvedTracksSnapshot()}initTrackInfoPanel(e){M.warn("TimelineManager","initTrackInfoPanel() is deprecated. TimelineManager now manages the frozen track-info panel inside the root container.")}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){const i=this.trackManager.muteTrack(e,t);return i&&(this.updateTrackInfoPanel(),this.syncPreviewSession()),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return gt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return Wn(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=dh(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const n of e){const s=this.getTrackCollection().findById(n.trackId);s&&((t=s.setTrackY)==null||t.call(s,n.y),(i=s.setTrackHeight)==null||i.call(s,n.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}cleanupEmptyTracks(){var t,i,n,s;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return;const e=this.getTrackCollection().removeEmptyNonPrimaryTracks();if(e.length!==0){for(const r of e){const o=(t=r.getId)==null?void 0:t.call(r);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(n=(i=r.getTrackGroup)==null?void 0:i.call(r))==null||n.destroy(),this.getTrackCollection().removeById(o))}this.updateAllTrackPositions(),(s=this.stage)==null||s.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()}}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDropPreview)==null?void 0:t.call(e)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(e,t){this.showClipDropPreviews(new Map([[t,[e]]]))}showClipDropPreviews(e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(t=>{var s,r,o,l;const i=(s=t.getId)==null?void 0:s.call(t),n=i?e.get(i)??[]:[];if(n.length>0){n.length===1?(r=t.showClipDropPreview)==null||r.call(t,n[0]):(o=t.showClipDropPreviews)==null||o.call(t,n);return}(l=t.clearClipDropPreview)==null||l.call(t)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const e=ie.createLine([0,0,0,0],this.config.theme.clipSelectedBorder,2);e.name("timeline-track-insertion-preview-line"),e.dash([8,4]),e.visible(!1),e.listening(!1),this.snapGuideLayer.add(e),this.trackInsertionPreviewLine=e}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(e=!0){var i,n,s;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),e&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const t=((n=this.stage)==null?void 0:n.width())??0;this.trackInsertionPreviewLine.stroke(this.config.theme.clipSelectedBorder),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,t,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(t>0),this.trackInsertionPreviewLine.moveToTop(),e&&((s=this.snapGuideLayer)==null||s.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(s=>{var r;return(r=s.clearClipDropPreview)==null?void 0:r.call(s)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const n=this.trackManager.getTracks(),s=n.find(h=>h.role==="primary"),r=n.find(h=>h.type===e),o=[...n].reverse().find(h=>h.type===e);if((t==="before_track"||t==="after_track")&&i){const h=n.find(c=>c.id===i);if(h){const c=gt(n,h.id,this.getTrackContentTopOffset());return t==="before_track"?c:c+Xe(h.type)}}if(t==="top_of_type_region"&&r)return gt(n,r.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return gt(n,o.id,this.getTrackContentTopOffset())+Xe(o.type);if(!s)return e==="video"?this.getTrackContentTopOffset():Wn(n,this.getTrackContentTopOffset());const l=gt(n,s.id,this.getTrackContentTopOffset());return e==="video"?l:l+Xe(s.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),n=Math.max(i,t),s=this.clampScrollLeft(this.getScrollLeftState()),r=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(e,t,n),this.headerStage.width(e),this.timeline.resize(e),this.stage.width(e),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${n}px`,this.renderBodyBackground(e,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+t),this.refreshScrollbarMetrics(),this.syncScrollLeft(s),this.syncScrollTop(r),this.stage.batchDraw()}renderBodyBackground(e,t,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(e),this.bodyBackgroundRect.height(t),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const n=new U.Rect({x:0,y:0,width:e,height:t,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});n.on("click",s=>{this.handleBodyBackgroundClick(s.evt.offsetX)}),this.bodyBackgroundRect=n,this.backgroundLayer.add(n),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(e){const t=H.pixelsToTime(e-le+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,t))}handleBodyCanvasHostClick(e){if(!this.layout||e.target!==this.layout.bodyCanvasHost)return;const t=this.layout.bodyCanvasHost.getBoundingClientRect(),i=e.clientX-t.left;this.handleBodyBackgroundClick(i)}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=ie.createLine([0,0,0,this.calculateTotalHeight()],e.snapGuideLineColor||e.clipSelectedBorder,e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var n,s;if(!this.snapGuideLine)return;const t=this.config.theme;if(this.snapGuideLine.stroke(t.snapGuideLineColor||t.clipSelectedBorder),this.snapGuideLine.strokeWidth(t.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),e&&((n=this.snapGuideLayer)==null||n.batchDraw());return}const i=ce(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((s=this.snapGuideLayer)==null||s.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const s=this.getPrimaryWheelDelta(t,i);if(s===0)return;e.preventDefault(),this.handleWheelZoom(s,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const s=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(s===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+s);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===Th)return e*16;if(t===bh){const n=i==="x"?this.getViewportWidth():this.getViewportHeight();return e*(n||1)}return e}getPrimaryWheelDelta(e,t){return Math.abs(t)>=Math.abs(e)?t:e}isHorizontalWheelGesture(e,t){const i=Math.abs(e);if(i<.5)return!1;const n=Math.abs(t);return n<.5?!0:i>n*1.2}getHorizontalScrollDelta(e,t,i){return i&&Math.abs(t)>=Math.abs(e)?t:e}handleWheelZoom(e,t){const i=this.getZoomState(),n=Math.exp(-e*.002),s=Math.max(de.MIN,Math.min(de.MAX,i*n));Math.abs(s-i)<1e-4||this.setZoomCenteredOnTimelinePointer(s,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var s;const t=(s=this.layout)==null?void 0:s.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const n=e-t.left;return Math.max(0,Math.min(i,n))}play(){if(this.getPlayStateState()!=="playing"){if(this.pendingPreviewState){M.debugLazy("TimelineManager",()=>"Play blocked by pending preview state");return}if(!this.canPlay){M.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}this.setPlayStateState("playing"),this.lastUpdateTime=Date.now(),this.previewBuffering?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession()}}pause(){this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.emitEvent("play_state_change",{playState:this.getPlayStateState()}),this.syncPreviewSession())}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused")return;if(this.previewBuffering){this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0,this.animationFrameId=null;return}const e=Date.now(),t=e-this.lastUpdateTime;this.lastUpdateTime=e;const i=this.getCurrentTimeState()+t*this.getSpeedState();this.setCurrentTime(i),this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}syncPlaybackClockToPreviewBuffering(e){if(e){if(this.getPlayStateState()!=="playing"||(this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering||this.previewBufferingSuspendTimeoutId))return;this.previewBufferingSuspendTimeoutId=setTimeout(()=>{this.previewBufferingSuspendTimeoutId=null,!(this.getPlayStateState()!=="playing"||!this.previewBuffering||this.previewPlaybackSuspendedByBuffering)&&(this.previewPlaybackSuspendedByBuffering=!0,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null))},wh);return}if(this.clearPreviewBufferingSuspendTimeout(),!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&this.getPlayStateState()==="playing"&&!this.pendingPreviewState;this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,!(!t||this.animationFrameId)&&(this.lastUpdateTime=Date.now(),this.animate())}clearPreviewBufferingSuspendTimeout(){this.previewBufferingSuspendTimeoutId&&(clearTimeout(this.previewBufferingSuspendTimeoutId),this.previewBufferingSuspendTimeoutId=null)}setCurrentTime(e){const t=this.getTimelineCommands().setCurrentTime(e);if(!t.changed){this.pendingPreviewState&&this.pendingPreviewState.targetTime===t.nextValue&&this.syncPreviewSession();return}const i=t.nextValue;this.ensureConfigState().currentTime=i,this.syncCurrentTimeToScene(i),this.emitEvent("time_change",{time:i}),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(e){this.ensureConfigState().enableClipSnap=e,e||this.updateSnapGuideLine(null),this.tracks.forEach(t=>{t.setClipSnapEnabled(e)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setZoom(e){const t=this.getTimelineCommands().setZoom(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(e){const t=this.getZoomState(),i=this.getCurrentTimeState(),n=this.getTimelineCommands().setZoom(e);if(!n.changed)return;const s=n.nextValue;if(this.ensureConfigState().zoom=s,this.syncZoomToScene(s),this.refreshScrollbarMetrics(),this.timeline){const r=this.timeline.getScrollLeft(),o=H.timeToPixels(i,t),h=H.timeToPixels(i,s)-o+r;this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft())}this.emitEvent("zoom_change",{zoom:s})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),n=this.timeline.getScrollLeft(),s=H.pixelsToTime(t-le+n,i),r=this.getTimelineCommands().setZoom(e);if(!r.changed)return;const o=r.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const h=H.timeToPixels(s,o)-(t-le);this.timeline.setScrollLeft(h),this.handleScrollChange(this.timeline.getScrollLeft()),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(e){const t=this.getTimelineCommands().setSpeed(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount+this.previewSourceLoadingCount>0}getSourceLoadingState(){const e=this.sourceLoadingCount+this.previewSourceLoadingCount;return{isLoading:e>0,pending:e}}setThumbnailProvider(e){this.thumbnailProvider=e,this.config.thumbnailProvider=e,this.getClips().forEach(i=>{i.thumbnails||this.loadClipThumbnails(i)})}async loadClipThumbnails(e){if(!this.thumbnailProvider||e.type==="audio")return!1;try{const t=this.thumbnailProvider.getThumbnails(e);if(Array.isArray(t))return this.updateClip(e.id,{thumbnails:t}),!0;if(t instanceof Promise){const i=await t;if(Array.isArray(i))return this.updateClip(e.id,{thumbnails:i}),M.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:i.length})),!0}}catch(t){M.warn("TimelineManager","Error loading clip thumbnails:",{error:t,clipId:e.id})}return!1}async refreshClipThumbnails(e){const t=this.getClips().find(i=>i.id===e);return t?this.loadClipThumbnails(t):!1}async refreshAllClipThumbnails(){const e=this.getClips();return await Promise.all(e.map(i=>this.loadClipThumbnails(i)))}async addClip(e){this.beginSourceLoading();try{return await this.addClipInternal(e)}finally{this.endSourceLoading()}}async addClips(e){if(e.length===0)return[];this.beginSourceLoading();try{const t=[];for(const i of e){const n=await this.addClipInternal(i);t.push(n)}return t}finally{this.endSourceLoading()}}async addClipInternal(e){var f;let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.startTimeAtSource||0,n=e.duration,s=e.endTimeAtSource||i+n;let r=e.sourceDuration;if(!r)try{r=await H.getVideoDuration(e.src),r<=0&&(r=s)}catch(y){M.error("TimelineManager","Failed to get video duration:",{error:y}),r=s}let o=e.thumbnails;const l=e.id||`clip_${e.name}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,h=e.type||"video",c=Gi({id:l,type:h,externalId:e.externalId,src:e.src,name:e.name,isMuted:e.isMuted??!1,startTime:t,duration:n,startTimeAtSource:i,endTimeAtSource:s,sourceDuration:r,endTime:t+n,thumbnails:o,style:e.style,visualTransform:e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1});if(M.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:c.id,type:c.type,startTime:c.startTime,duration:c.duration})),e.trackId){const y=this.getTrackCollection().findById(e.trackId);if(y){if(this.registerPreviewAutoAspectRatioClip(c),(f=y.addClip)==null||f.call(y,c),Jt({applied:!0,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{M.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(S){M.warn("TimelineManager","Error loading clip thumbnails:",{error:S})}return c.id}}const d=this.getTimelineCommands().planTrackPlacement(c,this.getTracksSortedByOrder()),u=this.getTrackCollection(),g=rh({clip:c,placement:d,trackCollection:u,createTrack:this.createTrack.bind(this)});if(Jt({applied:g,isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordAddClip(c)},applyEffects:()=>Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.thumbnailProvider)try{M.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:l})),this.loadClipThumbnails(c)}catch(y){M.warn("TimelineManager","Error loading clip thumbnails:",{error:y})}return c.id}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);t.exists&&(t.shouldClearSelection&&this.clearSelection(),Jt({applied:Fn(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.isExecutingHistoryAction,recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)})}))}removeClipsByExternalId(e){if(!e)return!1;const t=this.resolveClipIdsForExternalIdRemoval(e);if(t.length===0)return!1;const i=new Set(t);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let n=!1;return this.withClipRemovalBatch(()=>{for(const s of t){const r=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);r.exists&&(n=Fn(this.getTrackCollection(),r,s)||n)}}),n?(Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){this.getTimelineCommands().findClipById(this.tracks,e)&&(this.getTrackCollection().updateClip(e,t),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);i!=null&&i.track.splitSelectedClip&&(i.track.splitSelectedClip(t),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e)??this.getTimelineCommands().findClipAtTime(this.tracks,e);t!=null&&t.track.splitSelectedClip&&(t.track.splitSelectedClip(e),Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)}))}getClips(){return this.getTrackCollection().getAllClips()}getExportComposition(){var n,s,r;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(rt(e.mode)&&t===be.width&&i===be.height){const o=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,l=(s=o==null?void 0:o.style)==null?void 0:s.sys_width,h=(r=o==null?void 0:o.style)==null?void 0:r.sys_height;typeof l=="number"&&l>0&&typeof h=="number"&&h>0&&(t=l,i=h)}return{width:t,height:i,aspectRatio:`${t}:${i}`,mode:e.mode}}exportTimeline(){var i,n,s;const e=this.getResolvedTracksSnapshot().slice().sort((r,o)=>r.order-o.order).map(r=>{const o=r.clips.map(l=>({id:l.id,type:l.type,externalId:l.externalId,src:l.src,name:l.name,isMuted:l.isMuted??!1,startTime:Math.round(l.startTime),duration:Math.round(l.duration),endTime:Math.round(l.endTime),startTimeAtSource:Math.round(l.startTimeAtSource),endTimeAtSource:Math.round(l.endTimeAtSource),sourceDuration:Math.round(l.sourceDuration),thumbnails:l.thumbnails,visualTransform:l.type==="video"?fe(l.visualTransform):void 0,separatedAudioClipId:l.separatedAudioClipId,separatedFromVideoClipId:l.separatedFromVideoClipId,volume:l.volume??1})).sort((l,h)=>l.startTime-h.startTime);return{id:r.id,type:r.type,name:r.name||"未命名轨道",order:r.order,role:r.role??"normal",isMuted:r.isMuted??!1,clips:o}}),t=((s=(n=(i=e[0].clips)==null?void 0:i[0])==null?void 0:n.thumbnails)==null?void 0:s[0])||"";return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){M.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const t=new Map,i=[...e.tracks].sort((h,c)=>h.order-c.order),n=this.resolveImportedTrackRoles(i);let s;for(const h of i){const c=this.createTrack(h.type,h.name,s?"after_track":void 0,s,n.get(h.id));c&&(this.muteTrack(c,h.isMuted),t.set(h.id,c),s=c)}const r=new Map,o=[];for(const h of i){const c=t.get(h.id);if(c)for(const d of h.clips)try{let u=d.separatedAudioClipId;u&&r.has(u)&&(u=r.get(u));let g=d.separatedFromVideoClipId;g&&r.has(g)&&(g=r.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,trackId:c},y=await this.addClip(f);r.set(d.id,y)}catch(u){o.push({clipId:d.id,error:u}),M.error("TimelineManager",`Failed to import clip ${d.id}:`,{error:u})}}this.clearHistory();const l={errors:o};this.emitEvent("draft_loaded",l)}resolveImportedTrackRoles(e){const t=new Map;let i=!1;for(const s of e){const r=s.role==="primary"&&!i?"primary":"normal";r==="primary"&&(i=!0),t.set(s.id,r)}if(i)return t;const n=this.inferImportedPrimaryTrackIndex(e);return n>=0&&t.set(e[n].id,"primary"),t}inferImportedPrimaryTrackIndex(e){var t;for(let i=e.length-1;i>=0;i-=1)if(((t=e[i])==null?void 0:t.type)==="video")return i;return e.length>0?0:-1}stopPlaybackForImport(){var i;const e=this.getPlayStateState()==="playing",t=(i=this.previewSession)!=null&&i.hasPreview()?this.previewMountContainer:null;this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.clearPreviewBufferingSuspendTimeout(),this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),e?this.pause():this.setPlayStateState("paused"),this.destroyPreviewSession(!0),t&&(this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t,this.previewAspectRatio)),this.syncPreviewSession()}getClipsData(){return this.getClips()}getVersion(){return vh.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(h=>h.startTime)),n=(Math.max(...e.map(h=>h.endTime))-t)/1e3,s=((l=this.stage)==null?void 0:l.width())||0,r=s-le*2;M.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:n,containerWidth:s,availableWidth:r}));const o=Math.min(r/n,de.MAX);if(this.setZoom(o),this.timeline){const h=e.reduce((c,d)=>d.startTime<c.startTime?d:c);this.scrollToClip(h.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){this.beginPendingPreview(e,t),this.setCurrentTime(e)}handleScrollChange(e){this.syncScrollLeft(e)}handleClipUpdate(e,t,i){this.isExecutingHistoryAction||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i),this.emitEvent("clip_updated",{clip:e});const n=this.selectedClipId===e.id;Cl({notifySelectionChange:this.notifySelectionChange.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),n&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){this.registerPreviewAutoAspectRatioClip(e),this.emitEvent("clip_added",{clip:e}),Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(e){this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){vl(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{M.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){var s;const e=this.getClips(),t=this.getCurrentTime(),i=Tl(e,t),n=this.canPlay;this.canPlay=bl({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:((s=e[e.length-1])==null?void 0:s.endTime)||1,setCanPlay:r=>{this.canPlay=r},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:r=>{this.emitEvent("can_play_change",{canPlay:r})}}),n!==this.canPlay&&M.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:n,newState:this.canPlay}))}handleClipSplit(e,t){Pl({clip1:e,clip2:t,isExecutingHistoryAction:this.isExecutingHistoryAction,recordSplitClip:this.getTimelineHistoryRecorder().recordSplitClip.bind(this.getTimelineHistoryRecorder()),emitClipUpdated:i=>{this.emitEvent("clip_updated",{clip:i})},emitClipAdded:i=>{this.emitEvent("clip_added",{clip:i})},applyEffects:()=>Ut({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})})}handleClipSelect(e){const t=wl(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),M.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){M.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeUndo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}handleActionRedo(e){M.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.isExecutingHistoryAction=!0,this.getTimelineHistoryExecutor().executeRedo(e),this.isExecutingHistoryAction=!1,this.checkTrackDurationChange()}on(e,t){this.getEventDispatcher().on(e,t)}off(e,t){this.getEventDispatcher().off(e,t)}emitEvent(e,t){this.getEventDispatcher().emit(e,t)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=sh({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1,this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1),this.emitEvent("source_loading_change",{isLoading:this.sourceLoadingCount>0,pending:this.sourceLoadingCount})}handleClipOverlap(e,t){M.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const i=this.getTrackCollection();if(!i.findById(t))return;const n=e.type,s=this.trackManager.getTracksByType(n).length+1,r=n==="video"?`视频轨道 ${s}`:`音频轨道 ${s}`;oh({clip:e,currentTrackId:t,trackType:n,trackName:r,trackCollection:i,createTrack:this.createTrack.bind(this)}),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const n=this.resolveCrossTrackPreviewDestination(e,t,i);return n.status==="existing_track"?(this.showClipDropPreview(e,n.targetTrackId),n.targetTrackId===i?"self":"external"):n.status==="new_track_insertion"?(this.showTrackInsertionPreview(n.trackType,n.insertionPlacement,n.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,n){M.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:n}));const s=this.resolveCrossTrackMoveDestination(e,i,n);return s.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):s.status==="same_track"?(M.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,n),!1):(M.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:s.targetTrackId})),this.showClipDropPreview(e,s.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,s.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}resize(e,t){this.rootContainer&&(this.rootContainer.style.width=`${e}px`,this.rootContainer.style.height=`${t}px`,this.updateViewportLayout())}scrollToTime(e,t=!1){this.timeline&&(this.timeline.scrollToTime(e),this.handleScrollChange(this.timeline.getScrollLeft()),t&&this.setCurrentTime(e))}notifySelectionChange(){const e=this.getSelectedClipIds();this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),e)}syncPrimarySelectionFromSelectionStore(){var t,i,n,s;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((s=(n=this.selectionStore)==null?void 0:n.getSelectedClipId)==null?void 0:s.call(n))??null;this.selectedClipId=e}getOrderedSelectionClipIds(e,t){const i=Array.from(new Set(e));if(i.length<=1)return i;const n=t&&i.includes(t)&&t||this.selectedClipId&&i.includes(this.selectedClipId)&&this.selectedClipId||i[0]||null;return n?[n,...i.filter(s=>s!==n)]:i}setSelection(e,t={}){this.resetMultiDragSession();const i=this.getOrderedSelectionClipIds(e,t.preferredPrimaryClipId);this.selectionStore.setSelection(i),this.syncPrimarySelectionFromSelectionStore(),this.notifySelectionChange(),this.emitSelectionChangeEvent(),t.selectedClipEventClip&&this.emitEvent("clip_selected",{clip:t.selectedClipEventClip}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}selectClip(e,t){var n;const i=t||((n=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:n.clip);this.setSelection([e],{preferredPrimaryClipId:e,selectedClipEventClip:i??null})}clearSelection(){this.setSelection([])}getSelectedClipIds(){var e,t;return((t=(e=this.selectionStore)==null?void 0:e.getSelectedClipIds)==null?void 0:t.call(e))??(this.selectedClipId?[this.selectedClipId]:[])}getPrimarySelectedClipId(){return this.getSelectedClipIds()[0]??null}addToSelection(e){this.setSelection([...this.selectionStore.getSelectedClipIds(),e],{preferredPrimaryClipId:this.selectedClipId??e})}removeFromSelection(e){this.setSelection(this.selectionStore.getSelectedClipIds().filter(t=>t!==e))}toggleSelection(e){const t=this.selectionStore.getSelectedClipIds(),i=t.includes(e);this.setSelection(i?t.filter(n=>n!==e):[...t,e],{preferredPrimaryClipId:i?void 0:e})}isClipSelected(e){return this.selectionStore.isSelected(e)}deleteSelectedClips(){this.resetMultiDragSession();const e=this.selectionStore.getSelectedClipIds();if(e.length===0)return;const t=this.getTimelineHistoryRecorder(),i=e.map(s=>{const r=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);return!r.exists||!r.clip?null:t.createRemoveClipAction({...r.clip},r.trackId,r.trackId?this.cloneTrackSnapshot(r.trackId):null,r.trackId?this.getTrackRestoreAnchor(r.trackId):null)}).filter(s=>s!==null);this.clearSelection();const n=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{for(const s of e)this.removeClip(s)}finally{this.isExecutingHistoryAction=n}n||t.recordCompoundAction(i,"delete_selected_clips"),this.emitSelectionChangeEvent()}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.setSelection(this.tracks.flatMap(e=>e.getClips().map(t=>t.id)),{preferredPrimaryClipId:this.selectedClipId})}emitSelectionChangeEvent(){this.emitEvent("selection_change",{selectedClipIds:this.selectionStore.getSelectedClipIds()})}scrollToClip(e,t={}){const{selectClip:i=!1,setCurrentTime:n=!1}=t,s=this.getClips().find(r=>r.id===e);!s||!this.timeline||(this.timeline.scrollToClip(s),this.handleScrollChange(this.timeline.getScrollLeft()),n&&this.setCurrentTime(s.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}canDeleteSelectedClips(){return this.getSelectedClipIds().length>0}getSelectedClipAudioAction(){const e=this.getSelectedClips().filter(n=>n.type==="video");return e.length===0?null:e.some(n=>this.canSeparateClipAudio(n.id))?"separate":e.some(n=>this.canRestoreClipAudio(n.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const e=this.getSelectedClipAudioAction();return e?this.applySelectedClipAudioAction(e):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(e){return this.buildPlaybackPlan(e)}getActiveClipsAtTime(e){return this.buildPlaybackPlan(e).activeClips}attachPreview(e){const t=e instanceof HTMLElement?{container:e}:e;t.aspectRatio&&(this.previewAspectRatio=De({mode:t.aspectRatio.mode??(t.aspectRatio.width&&t.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:t.aspectRatio.width??this.previewAspectRatio.width,height:t.aspectRatio.height??this.previewAspectRatio.height})),this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t.container,this.previewAspectRatio),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){this.getPreviewRuntimeController().detachPreviewSession()&&(this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),M.debugLazy("TimelineManager",()=>"TimelineManager detached from preview container"))}attachClipConfig(e){const t=new Sh;t.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),updateClip:(s,r)=>{this.updateClip(s,r),this.handleClipChange()}});const i=()=>t.updateFromExternal(),n=(s,r)=>{var l;const o=this.getPrimarySelectedClip();o&&((l=r==null?void 0:r.clip)==null?void 0:l.id)===o.id&&t.updateFromExternal()};return this.on("selected_clip_change",i),this.on("clip_updated",n),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",i),this.off("clip_updated",n),t.destroy()}),t.update(),t}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return De(this.previewAspectRatio)}setPreviewAspectRatio(e){var t;this.previewAspectRatio=De({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...be},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}resolvePreferredSeparatedAudioTrackId(e,t){var l;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return null;const i=this.resolveTrackIdByClipId(e);if(!i)return null;const n=[...this.getResolvedTracksSnapshot()].sort((h,c)=>h.order-c.order),s=n.findIndex(h=>h.id===i);if(s===-1)return null;const r=t.startTime+t.duration,o=n.map((h,c)=>({track:h,index:c})).filter(({track:h})=>h.type==="audio").filter(({track:h})=>!h.clips.some(c=>t.startTime<c.endTime&&r>c.startTime));return o.length===0?null:(o.sort((h,c)=>{const d=Math.abs(h.index-s)-Math.abs(c.index-s);return d!==0?d:h.index-c.index}),((l=o[0])==null?void 0:l.track.id)??null)}async separateClipAudio(e){if(!this.canSeparateClipAudio(e))return null;const t=this.getClips().find(h=>h.id===e);if(!t||t.type!=="video")return null;const i=this.isExecutingHistoryAction,n=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let s=null;this.isExecutingHistoryAction=!0;try{if(s=await this.addClip({type:"audio",src:t.src,name:t.name,startTime:t.startTime,duration:t.duration,startTimeAtSource:t.startTimeAtSource,endTimeAtSource:t.endTimeAtSource,sourceDuration:t.sourceDuration,separatedFromVideoClipId:t.id,isMuted:!1,volume:t.volume??1,trackId:n??void 0}),!s)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:s})}finally{this.isExecutingHistoryAction=i}if(!s)return null;const r=this.getClips().find(h=>h.id===e),o=this.getClips().find(h=>h.id===s)??null,l=this.resolveTrackIdByClipId(s);return r?(i||this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,r,o,l),s):null}restoreClipAudio(e){if(!this.canRestoreClipAudio(e))return!1;const t=this.getClips().find(l=>l.id===e);if(!t||t.type!=="video")return!1;const i=t.separatedAudioClipId??null,n=i?this.getClips().find(l=>l.id===i)??null:null,s=i?this.resolveTrackIdByClipId(i):null,r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})}finally{this.isExecutingHistoryAction=r}const o=this.getClips().find(l=>l.id===e);return o?(r||this.getTimelineHistoryRecorder().recordRestoreClipAudio(t,o,n,s),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(o=>o.type==="video"),i=e==="separate"?t.filter(o=>this.canSeparateClipAudio(o.id)):t.filter(o=>this.canRestoreClipAudio(o.id));if(i.length===0)return!1;if(i.length===1){const[o]=i;return e==="separate"?!!await this.separateClipAudio(o.id):this.restoreClipAudio(o.id)}const n=this.getTimelineHistoryRecorder(),s=[],r=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{if(e==="restore")for(const o of i){const l=this.getClips().find(f=>f.id===o.id);if(!l||l.type!=="video")continue;const h=l.separatedAudioClipId??null,c=h?this.getClips().find(f=>f.id===h)??null:null,d=h?this.resolveTrackIdByClipId(h):null,u=this.restoreClipAudio(o.id),g=this.getClips().find(f=>f.id===o.id);!u||!g||s.push(n.createRestoreClipAudioAction({...l},{...g},c?{...c}:null,d))}else for(const o of i){const l=this.getClips().find(g=>g.id===o.id);if(!l||l.type!=="video")continue;const h=await this.separateClipAudio(o.id),c=this.getClips().find(g=>g.id===o.id),d=h?this.getClips().find(g=>g.id===h)??null:null,u=h?this.resolveTrackIdByClipId(h):null;!h||!c||s.push(n.createSeparateClipAudioAction({...l},{...c},d?{...d}:null,u))}}finally{this.isExecutingHistoryAction=r}return r||n.recordCompoundAction(s,`selected_clips_audio_${e}`),s.length>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,n=null){const s=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(s.status==="missing_source_track")return M.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(s.status==="noop")return M.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(s.status==="missing_target_track")return M.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(s.status==="track_type_mismatch")return M.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var f,y,S;return{targetTrackType:(y=(f=this.getTrackCollection().findById(t))==null?void 0:f.getTrackType)==null?void 0:y.call(f),clipType:(S=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:S.clip.type}}),!1;if(s.status!=="ready")return!1;const{sourceTrackId:r,targetTrackId:o}=s,l=i?{...i}:{...s.clip},h=n?{...n}:{...s.clip},c=this.cloneTrackSnapshot(r),d=this.cloneTrackSnapshot(o),u=ah({command:{...s,clip:h},trackCollection:this.getTrackCollection()}),g=this.getClips().find(f=>f.id===e)??null;return kl({applied:u,clipId:e,sourceTrackId:r,targetTrackId:o,clipBefore:l,clipAfter:g??l,sourceTrackSnapshot:c,targetTrackSnapshot:d,isExecutingHistoryAction:this.isExecutingHistoryAction,recordMoveClipBetweenTracks:this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks.bind(this.getTimelineHistoryRecorder()),applyEffects:()=>lh({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 Gn(this.getClips())}destroy(){var e,t,i,n,s,r,o,l,h,c,d;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPreviewBufferingSuspendTimeout(),this.clearPendingPreviewState(),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(e=this.layout)==null||e.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(n=(t=this.layout)==null?void 0:(i=t.bodyCanvasHost).removeEventListener)==null||n.call(i,"click",this.bodyCanvasHostClickListener),(r=(s=this.rootContainer)==null?void 0:s.removeEventListener)==null||r.call(s,"wheel",this.rootWheelListener),(o=this.horizontalScrollbar)==null||o.destroy(),(l=this.verticalScrollbar)==null||l.destroy(),(h=this.playhead)==null||h.destroy(),(c=this.timeline)==null||c.destroy(),(d=this.stage)==null||d.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(e){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return e()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(e){const t=this.getClips(),i=new Map(t.map(r=>[r.id,r])),n=new Set,s=t.filter(r=>r.externalId===e).map(r=>r.id);for(let r=0;r<s.length;r+=1){const o=s[r];if(n.has(o))continue;n.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!n.has(l.separatedAudioClipId)&&s.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!n.has(l.separatedFromVideoClipId)&&s.push(l.separatedFromVideoClipId))}return t.filter(r=>n.has(r.id)).map(r=>r.id)}shouldClearSelectionForClipIds(e){return this.selectedClipId&&e.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(t=>e.has(t))}resolveSelectedClipAtTime(e){var i;const t=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const n of t){const s=this.getTimelineCommands().findClipById(this.tracks,n),r=s==null?void 0:s.clip;if(r&&e>=r.startTime&&e<r.endTime)return s}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{if(e.isFinal){const i=this.finalizeMultiDragCrossTrack(t,e);return i||this.syncMultiDragPeerClips(t,e,!0),i}return this.syncMultiDragOverlayState(t,e.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(t,e,!1),e.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(t,e.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(t,e)}finally{e.isFinal&&(this.syncMultiDragOverlayState(t,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((e,t)=>{var i;(i=e.setTrackStackOrder)==null||i.call(e,t)})}elevateMultiDragTrackGroups(e,t){var o,l,h;const i=this.resolveMultiDragSessionTrackIds(e);if(i.length<=1)return;const n=i.indexOf(t);n>=0&&(i.splice(n,1),i.push(t));const s=new Set(i);let r=0;for(const c of this.tracks){const d=(o=c.getId)==null?void 0:o.call(c);!d||s.has(d)||(l=c.setTrackStackOrder)==null||l.call(c,r++)}for(const c of i){const d=this.getTrackCollection().findById(c);(h=d==null?void 0:d.setTrackStackOrder)==null||h.call(d,r++)}}resolveMultiDragSessionTrackIds(e){var i;const t=new Set;for(const n of this.tracks){const s=(i=n.getId)==null?void 0:i.call(n);if(!s)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===s})&&t.add(s)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const n of e.selectedClipIds){const s=e.clips.get(n);if(!s)continue;const r=i.get(s.trackId);r?r.push(n):i.set(s.trackId,[n])}i.forEach((n,s)=>{var o;const r=this.getTrackCollection().findById(s);(o=r==null?void 0:r.setClipsDragOverlayActive)==null||o.call(r,n,t)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDragOverlay)==null?void 0:t.call(e)})}ensureMultiDragSession(e){var n;const t=this.selectionStore.getSelectedClipIds();if(t.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===e.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,t))return this.multiDragSession;const i=new Map;for(const s of t){const r=this.findTrackByClipId(s),o=((n=r==null?void 0:r.getId)==null?void 0:n.call(r))??this.resolveTrackIdByClipId(s),l=r==null?void 0:r.getClips().find(c=>c.id===s);if(!o||!l)continue;const h=s===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(s,{clipId:s,trackId:o,clip:h})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:e.draggedClipId,selectedClipIds:t.slice(),clips:i},this.multiDragSession)}haveSameClipIds(e,t){if(e.length!==t.length)return!1;const i=new Set(t);return e.every(n=>i.has(n))}restoreDraggedClipSnapshot(e,t){const i=Math.max(0,e.startTime-t);return{...e,startTime:i,endTime:i+e.duration}}syncMultiDragPeerClips(e,t,i){for(const n of e.selectedClipIds){if(n===t.draggedClipId)continue;const s=e.clips.get(n);if(!s||s.trackId===t.currentTrackId)continue;const r=this.getTrackCollection().findById(s.trackId);if(!(r!=null&&r.updateClipPosition))continue;const o=Math.max(0,s.clip.startTime+t.deltaTime);r.updateClipPosition(n,o,i,i?0:t.crossTrackOffsetY)}}previewMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const n=this.buildMovedClipSnapshot(i.clip,t.deltaTime),s=this.resolveCrossTrackPreviewDestination(n,t.targetTrackY,i.trackId);if(s.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(s.trackType,s.insertionPlacement,s.referenceTrackId),!0;if(s.status!=="existing_track"||s.targetTrackId===i.trackId)return!1;const r=this.resolveTrackIndexDelta(i.trackId,s.targetTrackId,i.clip.type);if(r===null)return!1;const o=new Map;this.appendPreviewClip(o,s.targetTrackId,n);for(const l of e.selectedClipIds){if(l===t.draggedClipId)continue;const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(h,r,c);!d||d===h.trackId||this.appendPreviewClip(o,d,c)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const n=this.buildMovedClipSnapshot(i.clip,t.deltaTime),s=this.resolveCrossTrackMoveDestination(n,t.targetTrackY,i.trackId);if(s.status==="blocked"||s.status==="same_track")return!1;const r=s.targetTrackId;if(!r)return!1;const o=this.resolveTrackIndexDelta(i.trackId,r,i.clip.type);if(o===null)return!1;for(const l of e.selectedClipIds){const h=e.clips.get(l);if(!h)continue;const c=this.buildMovedClipSnapshot(h.clip,t.deltaTime),d=c.startTime,u=l===t.draggedClipId?r:this.resolveMultiDragTargetTrackId(h,o,c);if(u){if(u===h.trackId){this.updateClipPositionWithHistory(h.trackId,h.clipId,d);continue}this.updateClipPositionSilently(h.trackId,h.clipId,d),this.moveClipToTrackWithHistorySnapshot(h.clipId,u,h.clip,c)}}return!0}resolveTrackIndexDelta(e,t,i){const n=this.getTrackIdsByType(i),s=n.indexOf(e),r=n.indexOf(t);return s===-1||r===-1?null:r-s}resolveMultiDragTargetTrackId(e,t,i){const n=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!n)return e.trackId;const s=this.calculateTrackY(n)+1,r=this.resolveCrossTrackMoveDestination(i,s,e.trackId);return r.status==="blocked"?n:r.targetTrackId}resolveMultiDragPreviewTargetTrackId(e,t,i){const n=this.findTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!n)return null;const s=this.calculateTrackY(n)+1,r=this.resolveCrossTrackPreviewDestination(i,s,e.trackId);return r.status==="existing_track"?r.targetTrackId:null}buildMovedClipSnapshot(e,t){const i=Math.max(0,e.startTime+t);return{...e,startTime:i,endTime:i+e.duration}}appendPreviewClip(e,t,i){const n=e.get(t);if(n){n.push(i);return}e.set(t,[i])}resolveCrossTrackMoveDestination(e,t,i){const n=this.trackManager.getTracks(),s=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),n,this.tracks);if(s.status==="missing_target_track_by_position")return M.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(s.status==="same_track")return{status:"same_track",targetTrackId:s.targetTrackId};if(s.status==="missing_target_track_view")return M.warn("TimelineManager","目标轨道不存在",{targetTrackId:s.targetTrackId}),{status:"blocked"};if(s.status==="track_type_mismatch")return M.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:s.targetTrackType,clipType:e.type})),{status:"blocked"};if(s.status==="move_to_track")return{status:"move_to_track",targetTrackId:s.targetTrackId};M.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const r=this.createTrack(s.trackType,void 0,s.insertionPlacement,s.referenceTrackId);return r?{status:"move_to_track",targetTrackId:r}:{status:"blocked"}}resolveCrossTrackPreviewDestination(e,t,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const n=this.trackManager.getTracks();if(!Array.isArray(n)||n.length===0)return{status:"clear"};const s=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),n,this.tracks);return s.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:s.targetTrackId}:s.status==="new_track_insertion"?{status:"new_track_insertion",trackType:s.trackType,insertionPlacement:s.insertionPlacement,referenceTrackId:s.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(e,t,i){let n=this.getTrackIdsByType(t);const s=n.indexOf(e);if(s===-1)return null;let r=s+i;for(;r<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;n=this.getTrackIdsByType(t),r+=1}for(;r>=n.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;n=this.getTrackIdsByType(t)}return n[r]??null}findTrackIdByRelativeIndex(e,t,i){const n=this.getTrackIdsByType(t),s=n.indexOf(e);if(s===-1)return null;const r=s+i;return r<0||r>=n.length?null:n[r]??null}getTrackIdsByType(e){return this.trackManager.getTracks().filter(t=>t.type===e).map(t=>t.id)}updateClipPositionWithHistory(e,t,i){var s;const n=this.getTrackCollection().findById(e);(s=n==null?void 0:n.updateClipPosition)==null||s.call(n,t,i,!0)}updateClipPositionSilently(e,t,i){const n=this.getTrackCollection().findById(e);if(!(n!=null&&n.updateClipPosition))return;const s=this.isExecutingHistoryAction;this.isExecutingHistoryAction=!0;try{n.updateClipPosition(t,i,!0)}finally{this.isExecutingHistoryAction=s}}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new U.Rect({fill:"rgba(80, 130, 230, 0.15)",stroke:"#5082e6",strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(t=this.selectionBoxLayer)==null||t.add(e),this.selectionBoxRect=e,e}showSelectionBoxRect(e,t,i,n){var r;const s=this.ensureSelectionBoxRect();s.x(e),s.y(t),s.width(Math.max(i,1)),s.height(Math.max(n,1)),s.visible(!0),(r=this.selectionBoxLayer)==null||r.batchDraw()}hideSelectionBoxRect(){var e;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(e=this.selectionBoxLayer)==null||e.batchDraw())}handleStageMouseDown(e){if(e.button!==0)return;const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top;if(this.isPointOnClip(s,r))return;this.isBoxSelecting=!1,this.boxSelectStartX=s,this.boxSelectStartY=r;const l=c=>{this.handleBoxSelectMove(c)},h=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",h)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",h)}handleBoxSelectMove(e){const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const n=i.getBoundingClientRect(),s=e.clientX-n.left,r=e.clientY-n.top,o=Math.abs(s-this.boxSelectStartX),l=Math.abs(r-this.boxSelectStartY);if(!this.isBoxSelecting&&(o>4||l>4)&&(this.isBoxSelecting=!0),!this.isBoxSelecting)return;const h=Math.min(this.boxSelectStartX,s),c=Math.min(this.boxSelectStartY,r),d=Math.abs(s-this.boxSelectStartX),u=Math.abs(r-this.boxSelectStartY);this.showSelectionBoxRect(h,c,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const e=this.selectionBoxRect;if(e){const t={x:e.x(),y:e.y(),width:e.width(),height:e.height()},i=this.getClipsIntersectingBox(t);this.setSelection(i,{preferredPrimaryClipId:this.selectedClipId})}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(e,t){for(const i of this.tracks){const n=i.getTrackGroup(),s=n.y(),r=n.height()||64;if(!(t<s||t>s+r))for(const o of i.getClips()){const l=ce(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=H.timeToPixels(o.duration,this.getZoomState());if(e>=l&&e<=l+h&&t>=s+2&&t<=s+r-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const n=i.getTrackGroup(),s=n.y(),r=n.height()||64;for(const o of i.getClips()){const l=ce(o.startTime,this.getZoomState(),this.getScrollLeftState()),h=H.timeToPixels(o.duration,this.getZoomState()),c=s+2,d=r-4,u=l+h,g=c+d,f=e.x+e.width,y=e.y+e.height;l<f&&u>e.x&&c<y&&g>e.y&&t.push(o.id)}}return t}addClipToTrack(e,t){return this.registerPreviewAutoAspectRatioClip(t),this.getTrackCollection().addClipToTrack(e,t)?(Le({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),handleClipChange:this.handleClipChange.bind(this)}),!0):!1}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(n=>n.id===e);return t?{...t,clips:t.clips.map(n=>({...n}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const n=this.resolveTrackInsertionFromRestoreAnchor(t);if(n){const u=this.createTrack(e.type,e.name,n.insertionPlacement,n.referenceTrackId);return this.muteTrack(u,e.isMuted??!1),u}const s=[...this.getTracks()].sort((u,g)=>u.order-g.order),r=s.find(u=>u.order>=e.order),o=r?s[s.findIndex(u=>u.id===r.id)-1]??null:s[s.length-1]??null;let l,h;r?(l="before_track",h=r.id):o&&(l="after_track",h=o.id);const c=this.createTrack(e.type,e.name,l,h);return this.muteTrack(c,e.isMuted??!1),c}getTrackRestoreAnchor(e){var n,s,r;if(!((n=this.trackManager)!=null&&n.getTracks))return null;const t=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=t.findIndex(o=>o.id===e);return i===-1?null:{previousTrackId:((s=t[i-1])==null?void 0:s.id)??null,nextTrackId:((r=t[i+1])==null?void 0:r.id)??null}}resolveTrackInsertionFromRestoreAnchor(e){return e?e.previousTrackId&&this.getTrackCollection().findById(e.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:e.previousTrackId}:e.nextTrackId&&this.getTrackCollection().findById(e.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:e.nextTrackId}:null:null}resolveTrackIdByClipId(e){var t;return((t=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:t.trackId)??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var r;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastEffectiveTrackDuration,n=Kl(e),s=Gn(e);if(n!==t){this.lastTrackDuration=n;const o=Hn(n);this.setDurationState(o),(r=this.timeline)==null||r.setDuration(o),this.updateViewportLayout()}s!==i&&(this.lastEffectiveTrackDuration=s,this.emitEvent("track_duration_change",{duration:s})),!(n===t&&s===i)&&M.debugLazy("TimelineManager",()=>`Track duration changed: effective=${s}ms, extent=${n}ms, timeline=${Hn(n)}ms`)}resolveSelectedClipSnapshot(){return nh({getPrimarySelectedClip:()=>{var e;return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null},findFallbackSelectedClip:()=>this.tracks?this.getTimelinePresentationAdapter().findSelectedClip(this.getTrackCollection()):null})}commitPreviewVisualTransform(e,t){const i=this.getClips().find(r=>r.id===e);if(!i||i.type!=="video")return;const n=fe(i.visualTransform),s=fe(t);Ns(n,s)||this.updateClip(e,{visualTransform:s})}clearAllTracksAndClips(){var t,i,n,s;const e=this.getTracks();for(const r of e){const o=this.getTrackCollection().findById(r.id);if(o){const l=[...o.getClips()];for(const h of l)(t=o.removeClip)==null||t.call(o,h.id)}}for(const r of e){const o=r.id,l=this.getTrackCollection().findById(o);(n=(i=l==null?void 0:l.getTrackGroup)==null?void 0:i.call(l))==null||n.destroy(),this.getTrackCollection().removeById(o)}this.trackManager.clearAllTracks(),this.updateAllTrackPositions(),(s=this.stage)==null||s.batchDraw()}}exports.CLIP_LAYER=Ks;exports.Clip=Zt;exports.ClipConfigPanel=Hs;exports.DEFAULT_CLIP_VIEW_STATE=$n;exports.DEFAULT_PREVIEW_ASPECT_RATIO=be;exports.HistoryManager=Di;exports.MIN_CLIP_LINE_WIDTH=At;exports.PREVIEW_ASPECT_RATIO_PRESETS=qs;exports.Playhead=rl;exports.TIMELINE_LEFT_PADDING=le;exports.TIME_SCALE=js;exports.TRACK_HEIGHT=_e;exports.TimeUtils=H;exports.Timeline=Qo;exports.TimelineManager=kh;exports.Track=ii;exports.TrackInfoPanel=Gs;exports.TrackManager=Vs;exports.ZOOM_ANIMATION=qn;exports.ZOOM_PRESETS=de;exports.createClipViewState=Kn;exports.createClipWithViewState=Gi;exports.defaultDarkTheme=Qt;exports.isAutoPreviewAspectRatioMode=rt;exports.normalizePreviewAspectRatio=De;exports.normalizePreviewAspectRatioMode=Bi;exports.resolveTheme=It;
|
package/dist/index.es.js
CHANGED
|
@@ -14633,7 +14633,7 @@ class ph {
|
|
|
14633
14633
|
};
|
|
14634
14634
|
}
|
|
14635
14635
|
}
|
|
14636
|
-
const gh = "2.0.
|
|
14636
|
+
const gh = "2.0.9", fh = {
|
|
14637
14637
|
version: gh
|
|
14638
14638
|
}, mh = 1, yh = 2, Sh = 120;
|
|
14639
14639
|
class Ph {
|
|
@@ -16489,7 +16489,7 @@ class Ph {
|
|
|
16489
16489
|
this.updateClip(s, r), this.handleClipChange();
|
|
16490
16490
|
}
|
|
16491
16491
|
});
|
|
16492
|
-
const i = () => t.
|
|
16492
|
+
const i = () => t.updateFromExternal(), n = (s, r) => {
|
|
16493
16493
|
var l;
|
|
16494
16494
|
const o = this.getPrimarySelectedClip();
|
|
16495
16495
|
o && ((l = r == null ? void 0 : r.clip) == null ? void 0 : l.id) === o.id && t.updateFromExternal();
|
package/package.json
CHANGED