@linker-design-plus/timeline-track 2.1.5 → 2.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -730,4 +730,4 @@ js: import "konva/skia-backend";
730
730
  <span style=${`min-width:18px;font-size:13px;color:${e.theme.labelColor};`}>${t}</span>
731
731
  ${this.renderNumberInput(e.theme,{min:a,max:o,step:n,value:String(i),onChange:r})}
732
732
  </label>
733
- `}getContainerStyle(e){return[`background-color:${e.backgroundColor}`,"border-radius:4px",`color:${e.textColor}`,'font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size:13px","display:flex","flex-direction:column","overflow:hidden","height:100%",`--clip-slider-fill-start:${_.sliderFillStart}`,`--clip-slider-fill-end:${_.sliderFillEnd}`,`--clip-slider-road:${_.sliderRoad}`,`--clip-slider-thumb-border:${_.sliderThumbBorder}`,`--clip-slider-thumb-shadow:${xe.sliderThumbShadow}`].join(";")}getSliderStyle(e,t,i){const r=Number(e||0),n=Number(t||100),a=Number(i||0),o=n-r,l=o<=0?0:(a-r)/o*100;return["flex:1","min-width:0",`--clip-slider-progress:${Math.max(0,Math.min(100,l))}%`].join(";")}supportsVoicePanel(e){return e.groupKind==="text"||e.groupKind==="audio"&&e.supportsVoiceBatch}getTransform(e){return(e==null?void 0:e.visualTransform)??{x:.5,y:.5,scale:1}}calculatePresetPosition(e,t,i){const n=this.getTransform(e).scale/2,a={left:n,center:.5,right:1-n},o={top:n,center:.5,bottom:1-n};return{x:a[t],y:o[i]}}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}static createColorInputHandler(e){return t=>{const i=t.target.value;cancelAnimationFrame(xt.colorRafId),xt.colorRafId=requestAnimationFrame(()=>{e.callbacks.onTextStyleChange("color",i)})}}};g(xt,"colorRafId",0);let sn=xt;const Ed={...ye};function xs(s){return s?{primaryClip:s,selectedClips:[s],selectionCount:1,groupKind:s.type,supportsVoiceBatch:s.type==="text"||Le(s),supportsTextContentBatch:s.type==="text",supportsVisualBatch:s.type==="video",supportsVolumeBatch:s.type==="video"||s.type==="audio"}:{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1}}function Rd(s,e){return s.groupKind!==e.groupKind||s.selectionCount!==e.selectionCount||s.supportsVoiceBatch!==e.supportsVoiceBatch||s.supportsTextContentBatch!==e.supportsTextContentBatch||s.supportsVisualBatch!==e.supportsVisualBatch||s.supportsVolumeBatch!==e.supportsVolumeBatch||s.selectedClips.length!==e.selectedClips.length?!1:s.selectedClips.every((t,i)=>{var r;return t.id===((r=e.selectedClips[i])==null?void 0:r.id)})}class uo{constructor(e){g(this,"container");g(this,"theme");g(this,"renderer",new sn);g(this,"onClipUpdate");g(this,"onGenerateVoice");g(this,"voiceCatalog");g(this,"currentClip",null);g(this,"selectionState",xs(null));g(this,"activeTab","visual");g(this,"iconCache",new Map);g(this,"pendingPreferredTab",null);g(this,"selectedVoiceId",null);g(this,"activeVoiceFilterTag","男");g(this,"textDraftContent","");g(this,"followTextUpdates",!0);g(this,"voiceLoadingBusyCount",0);g(this,"isVoiceLoadingOverlayRendered",!1);g(this,"isVoiceLoadingOverlayExiting",!1);g(this,"voiceLoadingOverlayHideTimer",null);g(this,"voiceErrorMessage",null);g(this,"voicePreviewAudio",null);g(this,"previewingVoiceId",null);g(this,"handleVoicePreviewEnded",()=>{this.stopVoicePreview()});this.container=e.container,this.theme=e.theme??Ed,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",be("OmAi-camera")),this.iconCache.set("OmAi-accept",be("OmAi-accept")),this.iconCache.set("OmAi-loading",be("OmAi-loading")),this.iconCache.set("OmAi-text",be("OmAi-text")),this.renderer.mount(this.container),this.render()}setClip(e){this.setSelectionState(xs(e))}setSelectionState(e){var l,c,h,d,u,p;const t=e,i=this.selectionState,r=((l=this.currentClip)==null?void 0:l.id)??null,n=((c=t.primaryClip)==null?void 0:c.id)??null,a=r!==n,o=!Rd(i,t);a&&this.stopVoicePreview(!1),this.selectionState=t,this.currentClip=t.primaryClip,a||o?(this.voiceErrorMessage=null,this.textDraftContent=((h=this.currentClip)==null?void 0:h.textContent)??((d=this.currentClip)==null?void 0:d.name)??"",this.syncVoiceStateForSelection(t)):((u=this.currentClip)==null?void 0:u.type)==="text"?this.textDraftContent=this.currentClip.textContent??this.currentClip.name??"":((p=this.currentClip)==null?void 0:p.type)==="audio"&&t.supportsVoiceBatch?(this.followTextUpdates=this.currentClip.ttsFollowTextUpdates??!1,this.ensureVoiceFilters()):this.currentClip||this.resetVoiceState(),this.syncActiveTab(t),this.render()}setPreferredTab(e){this.pendingPreferredTab=e}showVoiceGenerationLoading(){this.setVoiceGenerationBusy(!0)}hideVoiceGenerationLoading(){this.setVoiceGenerationBusy(!1)}setVoiceGenerationBusy(e){if(this.voiceLoadingBusyCount=Math.max(0,this.voiceLoadingBusyCount+(e?1:-1)),this.voiceLoadingBusyCount>0){this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.isVoiceLoadingOverlayRendered=!0,this.isVoiceLoadingOverlayExiting=!1,this.render();return}if(!this.isVoiceLoadingOverlayRendered){this.render();return}this.isVoiceLoadingOverlayExiting=!0,this.voiceLoadingOverlayHideTimer!==null&&window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=window.setTimeout(()=>{this.isVoiceLoadingOverlayRendered=!1,this.isVoiceLoadingOverlayExiting=!1,this.voiceLoadingOverlayHideTimer=null,this.render()},180),this.render()}destroy(){this.stopVoicePreview(!1),this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.renderer.destroy()}render(){const e=this.getAvailableTabs(this.selectionState);this.renderer.update({clip:this.currentClip,selectionState:this.selectionState,activeTab:this.activeTab,availableTabs:e,theme:this.theme,emptyStateMessage:this.getEmptyStateMessage(this.selectionState),isTextContentEditable:this.selectionState.supportsTextContentBatch,loadingIconSvg:this.iconCache.get("OmAi-loading")??"",selectedIconSvg:this.iconCache.get("OmAi-accept")??"",textDraftContent:this.textDraftContent,voiceCatalog:this.voiceCatalog,selectedVoiceId:this.selectedVoiceId,previewingVoiceId:this.previewingVoiceId,activeVoiceFilterTag:this.activeVoiceFilterTag,followTextUpdates:this.followTextUpdates,isVoiceLoadingOverlayVisible:this.isVoiceLoadingOverlayRendered,isVoiceLoadingOverlayExiting:this.isVoiceLoadingOverlayExiting,voiceErrorMessage:this.voiceErrorMessage,callbacks:{onTabChange:t=>{this.activeTab=t,this.render()},onTransformChange:(t,i)=>{this.handleTransformChange(t,i)},onPresetSelect:(t,i)=>{this.handleTransformChanges({x:t,y:i})},onVolumeChange:t=>{this.handleVolumeChange(t)},onTextContentInput:t=>{this.handleTextContentInput(t)},onTextContentCommit:()=>{this.handleTextContentCommit()},onTextStyleChange:(t,i)=>{this.handleTextStyleChange(t,i)},onVoiceFilterChange:t=>{this.handleVoiceFilterChange(t)},onVoiceSelect:t=>{this.handleVoiceSelect(t)},onVoiceFollowTextUpdatesChange:t=>{this.handleVoiceFollowTextUpdatesChange(t)},onGenerateVoice:async()=>{await this.handleGenerateVoice()}}})}getAvailableTabs(e=this.selectionState){return e.groupKind==="text"?["text","voice"]:e.groupKind==="audio"?e.supportsVoiceBatch?["voice","audio"]:["audio"]:e.groupKind==="video"?["visual","audio"]:[]}getEmptyStateMessage(e=this.selectionState){return e.groupKind==="empty"?"请选择一个片段":e.groupKind==="mixed"?"暂不支持跨类型批量配置":null}resetVoiceState(){this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=!1,this.stopVoicePreview(!1)}syncVoiceStateForSelection(e){if(!this.supportsVoicePanel(e)||!e.primaryClip){this.resetVoiceState();return}this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=e.primaryClip.type==="audio"?e.primaryClip.ttsFollowTextUpdates??!1:!0,this.ensureVoiceFilters()}syncActiveTab(e){const t=this.getAvailableTabs(e);if(t.length===0){this.activeTab="visual",this.pendingPreferredTab=null;return}if(this.pendingPreferredTab&&t.includes(this.pendingPreferredTab)){this.activeTab=this.pendingPreferredTab,this.pendingPreferredTab=null;return}t.includes(this.activeTab)||(this.activeTab=t[0],this.pendingPreferredTab=null)}supportsVoicePanel(e=this.selectionState){return e.groupKind==="text"||e.groupKind==="audio"&&e.supportsVoiceBatch}ensureVoiceFilters(){if(this.voiceCatalog.length===0){this.selectedVoiceId=null,this.stopVoicePreview(!1);return}this.selectedVoiceId&&!this.voiceCatalog.some(e=>e.id===this.selectedVoiceId)&&(this.selectedVoiceId=null,this.stopVoicePreview(!1))}handleVoiceFilterChange(e){const t=e==="男"||e==="女"||e==="普通话"||e==="粤语"?e:null;this.activeVoiceFilterTag=this.activeVoiceFilterTag===t?null:t,this.render()}async handleVoiceSelect(e){const t=this.voiceCatalog.find(r=>r.id===e)??null,i=this.previewingVoiceId===e;if(this.selectedVoiceId=e,this.voiceErrorMessage=null,this.render(),!(t!=null&&t.audiofile)){this.stopVoicePreview();return}if(i){this.stopVoicePreview();return}await this.playVoicePreview(t)}handleVoiceFollowTextUpdatesChange(e){var t;this.followTextUpdates=e,((t=this.currentClip)==null?void 0:t.type)==="audio"&&this.selectionState.supportsVoiceBatch&&this.onClipUpdate&&(this.currentClip={...this.currentClip,ttsFollowTextUpdates:e},this.onClipUpdate(this.currentClip.id,{ttsFollowTextUpdates:e})),this.render()}async handleGenerateVoice(){if(!this.currentClip||!this.onGenerateVoice)return;const e=this.voiceCatalog.find(t=>t.id===this.selectedVoiceId);if(!e){this.voiceErrorMessage="请选择一个音色",this.render();return}this.voiceErrorMessage=null,this.render();try{await this.onGenerateVoice(this.currentClip,e,this.followTextUpdates)}catch(t){this.voiceErrorMessage=t instanceof Error?t.message:"音色生成失败"}this.render()}handleVolumeChange(e){if(!this.currentClip||!this.onClipUpdate)return;const t=Math.max(0,Math.min(1,e));this.currentClip={...this.currentClip,volume:t},this.render(),this.onClipUpdate(this.currentClip.id,{volume:t})}clampValue(e,t){return e==="scale"?Math.max(.1,Math.min(8,t)):t}handleTransformChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(e,t),n={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:i};this.currentClip={...this.currentClip,visualTransform:n},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:n})}handleTransformChanges(e){if(!this.currentClip||!this.onClipUpdate)return;const i={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1}};e.x!==void 0&&(i.x=this.clampValue("x",e.x)),e.y!==void 0&&(i.y=this.clampValue("y",e.y)),e.scale!==void 0&&(i.scale=this.clampValue("scale",e.scale)),this.currentClip={...this.currentClip,visualTransform:i},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:i})}stopVoicePreview(e=!0){if(this.voicePreviewAudio){this.voicePreviewAudio.removeEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio.pause();try{this.voicePreviewAudio.currentTime=0}catch{}this.voicePreviewAudio=null}if(this.previewingVoiceId!==null){this.previewingVoiceId=null,e&&this.render();return}e&&this.render()}async playVoicePreview(e){if(!e.audiofile)return;this.stopVoicePreview(!1);const t=new Audio(e.audiofile);t.preload="auto",t.addEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio=t,this.previewingVoiceId=e.id,this.render();try{await t.play()}catch(i){this.voicePreviewAudio===t&&(this.stopVoicePreview(!1),this.voiceErrorMessage=i instanceof Error?i.message:"试听播放失败",this.render())}}handleTextContentInput(e){if(this.selectionState.supportsTextContentBatch){if(this.textDraftContent=e,!this.currentClip||!this.onClipUpdate){this.render();return}this.currentClip={...this.currentClip,textContent:e},this.onClipUpdate(this.currentClip.id,{textContent:e})}}handleTextContentCommit(){if(!this.currentClip||!this.onClipUpdate||!this.selectionState.supportsTextContentBatch)return;const e=this.textDraftContent,t=this.currentClip.textContent??this.currentClip.name??"";e!==t&&(this.currentClip={...this.currentClip,textContent:e},this.render(),this.onClipUpdate(this.currentClip.id,{textContent:e}))}handleTextStyleChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;if(e==="x"||e==="y"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;const o={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:Math.max(0,Math.min(1,n))};this.currentClip={...this.currentClip,visualTransform:o},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:o});return}const r={...De(this.currentClip.textStyle)};if(e==="fontSize"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.fontSize=Math.max(ci.MIN,Math.min(ci.MAX,n))}else if(e==="rotation"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.rotation=n}else r.color=String(t);this.currentClip={...this.currentClip,textStyle:r},this.render(),this.onClipUpdate(this.currentClip.id,{textStyle:r})}}function Md(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class _s{constructor(e){this.timelineStore=e}selectClip(e){return this.updateSelection(e)}clearSelection(){return this.updateSelection(null)}findClipById(e,t){for(const i of e){const r=i.getClips().find(n=>n.id===t);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}findClipAtTime(e,t){for(const i of e){const r=i.getClips().find(n=>t>=n.startTime&&t<n.startTime+n.duration);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}prepareRemoveClip(e,t){const i=this.findClipById(t,e);return i?{exists:!0,clip:i.clip,trackId:i.trackId,shouldClearSelection:this.timelineStore.getPrimarySelectedClipId()===e}:{exists:!1,clip:null,trackId:null,shouldClearSelection:!1}}prepareMoveClipToTrack(e,t,i){var h;const r=this.findClipById(i,e);if(!r||!r.trackId)return{status:"missing_source_track",clipId:e,targetTrackId:t};const{clip:n,track:a,trackId:o}=r;if(o===t)return{status:"noop",clipId:e,sourceTrackId:o,targetTrackId:t};const l=i.find(d=>this.resolveTrackId(d)===t);if(!l)return{status:"missing_target_track",clipId:e,targetTrackId:t,sourceTrackId:o};const c=(h=l.getTrackType)==null?void 0:h.call(l);return c&&c!==n.type?{status:"track_type_mismatch",clipId:e,targetTrackId:t,sourceTrackId:o}:{status:"ready",clip:n,sourceTrack:a,sourceTrackId:o,targetTrack:l,targetTrackId:t}}planTrackPlacement(e,t){var n;const i=e.startTime+e.duration;for(const a of t){if(((n=a.getTrackType)==null?void 0:n.call(a))!==e.type)continue;if(!a.getClips().some(l=>e.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(a);if(l)return{status:"use_existing_track",trackId:l}}}const r=t.filter(a=>{var o;return((o=a.getTrackType)==null?void 0:o.call(a))===e.type}).length+1;return{status:"create_track",trackType:e.type,suggestedTrackName:`${Md(e.type)}轨道 ${r}`,insertionPlacement:e.type==="text"||e.type==="video"?"top_of_type_region":"bottom_of_type_region"}}planCrossTrackMove(e,t,i,r,n,a){var f;const o=this.resolveTrackTargetByY(t,r,n,e.type);if(o.status==="create_track")return{status:"create_track",trackType:e.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const c=a.find(m=>this.resolveTrackId(m)===l);if(!c)return{status:"missing_target_track_view",targetTrackId:l};const h=this.resolveTrackType(c)??((f=n.find(m=>m.id===l))==null?void 0:f.type)??null;if(h!==e.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:h};if(!this.hasOverlapOnTrack(e,c))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(e.type,l,t,r,n);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=n.filter(m=>m.type===e.type).map(m=>m.id),p=u.indexOf(l);for(let m=1;m<=u.length;m+=1){const S=p-m;if(S>=0){const v=u[S],C=a.find(k=>this.resolveTrackId(k)===v);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:v}}const T=p+m;if(T<u.length){const v=u[T],C=a.find(k=>this.resolveTrackId(k)===v);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:v}}}return{status:"create_track",trackType:e.type,insertionPlacement:e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary"}}planCrossTrackPreview(e,t,i,r,n,a){const o=this.planCrossTrackMove(e,t,i,r,n,a);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(e){const t=Math.max(0,e);return this.updateCurrentTime(t)}setZoom(e){const t=Math.max(Me.MIN,Math.min(Me.MAX,e));return this.updateZoom(t)}setSpeed(e){const t=Math.max(.1,Math.min(10,e));return this.updateSpeed(t)}updateSelection(e){const t=this.timelineStore.getPrimarySelectedClipId();return t===e?{previousClipId:t,nextClipId:e,changed:!1}:(e===null?this.timelineStore.clearSelection():this.timelineStore.setPrimarySelectedClipId(e),{previousClipId:t,nextClipId:e,changed:!0})}updateCurrentTime(e){const t=this.timelineStore.getCurrentTime();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setCurrentTime(e),{previousValue:t,nextValue:e,changed:!0})}updateZoom(e){const t=this.timelineStore.getZoom();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setZoom(e),{previousValue:t,nextValue:e,changed:!0})}updateSpeed(e){const t=this.timelineStore.getSpeed();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setSpeed(e),{previousValue:t,nextValue:e,changed:!0})}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}resolveTrackType(e){return typeof e.getTrackType=="function"?e.getTrackType():e.type??null}resolveTrackTargetByY(e,t,i,r){let n=t,a=null,o=null;for(const l of i){const c=Ae(l.type),h=n+c;if(l.type===r&&(a===null&&(a=n),o=h),e>=n&&e<h)return{status:"existing_track",targetTrackId:l.id};n=h}return r==="text"&&a!==null&&e<a?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="video"&&a!==null&&e<a?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="audio"&&o!==null&&e>=o?{status:"create_track",insertionPlacement:"bottom_of_type_region"}:{status:"missing_target_track_by_position"}}resolvePreferredInsertionPlacement(e,t,i,r,n){let a=r;const o=n.map(d=>{const u=a,p=Ae(d.type),f=u+p;return a=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:p}}).filter(d=>d.type===e),l=o.findIndex(d=>d.id===t);if(l===-1)return null;const c=o[l],h=Math.min(12,Math.max(6,Math.floor(c.height/4)));return c.role==="primary"?{insertionPlacement:e==="text"||e==="video"?"before_track":"after_track",referenceTrackId:t}:l<o.length-1&&i>=c.endY-h?{insertionPlacement:"after_track",referenceTrackId:t}:{insertionPlacement:"before_track",referenceTrackId:t}}hasOverlapOnTrack(e,t){const i=e.startTime+e.duration;return t.getClips().some(r=>r.id===e.id?!1:e.startTime<r.endTime&&i>r.startTime)}}class an{constructor(e,t,i,r=100){g(this,"state");g(this,"maxHistorySize",100);g(this,"onActionUndo");g(this,"onActionRedo");g(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=r,this.onActionUndo=e,this.onActionRedo=t,this.onHistoryChange=i}addAction(e){this.state.past.length>=this.maxHistorySize&&this.state.past.shift(),this.state.past.push({...e,timestamp:Date.now()}),this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}undo(){if(this.state.past.length===0)return!1;const e=this.state.past.pop();return this.state.future.push(e),this.onActionUndo(e),this.onHistoryChange&&this.onHistoryChange(),!0}redo(){if(this.state.future.length===0)return!1;const e=this.state.future.pop();return this.state.past.push(e),this.onActionRedo(e),this.onHistoryChange&&this.onHistoryChange(),!0}clear(){this.state.past=[],this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}canUndo(){return this.state.past.length>0}canRedo(){return this.state.future.length>0}getState(){return{...this.state}}createAddClipAction(e,t=null,i=null,r=null){return{type:"add_clip",data:{clip:e,targetTrackId:t,targetTrackSnapshot:i,targetTrackRestoreAnchor:r},timestamp:Date.now()}}createRemoveClipAction(e){return{type:"remove_clip",data:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null},timestamp:Date.now()}}createRemoveClipActionWithTrackSnapshot(e,t,i,r=null){return{type:"remove_clip",data:{clip:e,sourceTrackId:t,sourceTrackSnapshot:i,sourceTrackRestoreAnchor:r},timestamp:Date.now()}}createUpdateClipAction(e,t,i){return{type:"update_clip",data:{clipId:e,updates:t,previousState:i},timestamp:Date.now()}}createSplitClipAction(e,t,i,r){return{type:"split_clip",data:{originalClip:e,clip1:t,clip2:i,sourceTrackId:(r==null?void 0:r.trackId)??null,sourceTrackSnapshot:(r==null?void 0:r.trackSnapshot)??null,sourceTrackRestoreAnchor:(r==null?void 0:r.trackRestoreAnchor)??null},timestamp:Date.now()}}createMoveClipAction(e,t,i){return{type:"move_clip",data:{clipId:e,newStartTime:t,previousStartTime:i},timestamp:Date.now()}}createResizeClipAction(e,t,i,r,n){return{type:"resize_clip",data:{clipId:e,newDuration:t,newStartTime:i,previousDuration:r,previousStartTime:n},timestamp:Date.now()}}createSetTimeAction(e,t){return{type:"set_time",data:{newTime:e,previousTime:t},timestamp:Date.now()}}createRemoveGapsAction(e){return{type:"remove_gaps",data:{clipsBefore:e},timestamp:Date.now()}}createMultiClipUpdateAction(e){return{type:"multi_clip_update",data:{clipUpdates:e},timestamp:Date.now()}}createMoveClipBetweenTracksAction(e,t,i,r,n,a,o,l=null,c=null){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:r,clipAfter:n,sourceTrackSnapshot:a,targetTrackSnapshot:o,sourceTrackRestoreAnchor:l,targetTrackRestoreAnchor:c},timestamp:Date.now()}}createSeparateClipAudioAction(e,t,i,r){return{type:"separate_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createRestoreClipAudioAction(e,t,i,r){return{type:"restore_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createSetPrimaryTrackMagnetAction(e,t){return{type:"set_primary_track_magnet",data:{previousEnabled:e,nextEnabled:t},timestamp:Date.now()}}createCompoundAction(e,t){return{type:"compound",data:{actions:e,...t?{label:t}:{}},timestamp:Date.now()}}}class As{constructor(e){this.target=e}executeUndo(e){this.executeUndoInternal(e,new Map)}executeRedo(e){this.executeRedoInternal(e,new Map)}executeUndoInternal(e,t){var i,r,n,a;switch(e.type){case"add_clip":this.target.removeClip(this.normalizeAddClipActionData(e.data).clip.id);break;case"remove_clip":{const o=this.normalizeRemoveClipActionData(e.data);let l=!1;const c=this.resolveTrackIdForHistorySnapshot(o.sourceTrackSnapshot,o.sourceTrackId,t,o.sourceTrackRestoreAnchor);if(c&&(l=this.target.addClipToTrack(c,o.clip)),!l){const h=this.target.findTrackByClipId(o.clip.id)||this.target.getDefaultTrack();h==null||h.addClip(o.clip)}(r=(i=this.target).loadClipThumbnails)==null||r.call(i,o.clip);break}case"update_clip":this.target.updateClip(e.data.clipId,e.data.previousState);break;case"split_clip":{this.withClipRemovalBatch(()=>{const o=this.normalizeSplitClipActionData(e.data),l=this.target.findTrackByClipId(e.data.clip1.id)||this.target.getDefaultTrack(),c=this.resolveTrackIdForHistorySnapshot(o.sourceTrackSnapshot,o.sourceTrackId,t,o.sourceTrackRestoreAnchor);if(this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id),c){this.target.addClipToTrack(c,e.data.originalClip);return}l==null||l.addClip(e.data.originalClip)});break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.previousStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.previousDuration,startTime:e.data.previousStartTime});break;case"remove_gaps":this.target.getClips().forEach(o=>this.target.removeClip(o.id)),e.data.clipsBefore.forEach(o=>{const l=this.target.findTrackByClipId(o.id)||this.target.getDefaultTrack();l==null||l.addClip(o)});break;case"multi_clip_update":e.data.clipUpdates.forEach(o=>{this.target.updateClip(o.clipId,o.previousState)});break;case"move_clip_between_tracks":{const o=this.normalizeMoveClipBetweenTracksActionData(e.data);this.restoreMovedClip(o.clipId,o.sourceTrackId,o.sourceTrackSnapshot,o.sourceTrackRestoreAnchor,o.clipBefore,t);break}case"separate_clip_audio":e.data.audioClip&&this.target.removeClip(e.data.audioClip.id),this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"set_primary_track_magnet":(a=(n=this.target).setPrimaryTrackMagnetEnabled)==null||a.call(n,e.data.previousEnabled);break;case"compound":[...e.data.actions].reverse().forEach(o=>{this.executeUndoInternal(o,t)});break;default:O.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:e.type})}}executeRedoInternal(e,t){var i,r,n,a;switch(e.type){case"add_clip":{const o=this.normalizeAddClipActionData(e.data);let l=!1;const c=this.resolveTrackIdForHistorySnapshot(o.targetTrackSnapshot,o.targetTrackId,t,o.targetTrackRestoreAnchor);if(c&&(l=this.target.addClipToTrack(c,o.clip)),!l){const h=this.target.findTrackByClipId(o.clip.id)||this.target.getDefaultTrack();h==null||h.addClip(o.clip)}(r=(i=this.target).loadClipThumbnails)==null||r.call(i,o.clip);break}case"remove_clip":this.target.removeClip(e.data.clip.id);break;case"update_clip":this.target.updateClip(e.data.clipId,e.data.updates);break;case"split_clip":{this.withClipRemovalBatch(()=>{const o=this.normalizeSplitClipActionData(e.data),l=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack(),c=this.resolveTrackIdForHistorySnapshot(o.sourceTrackSnapshot,o.sourceTrackId,t,o.sourceTrackRestoreAnchor);if(this.target.removeClip(e.data.originalClip.id),c){this.target.addClipToTrack(c,e.data.clip1),this.target.addClipToTrack(c,e.data.clip2);return}l==null||l.addClip(e.data.clip1),l==null||l.addClip(e.data.clip2)});break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.newStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.newDuration,startTime:e.data.newStartTime});break;case"remove_gaps":this.target.removeClipGaps();break;case"multi_clip_update":e.data.clipUpdates.forEach(o=>{this.target.updateClip(o.clipId,o.newState)});break;case"move_clip_between_tracks":{const o=this.normalizeMoveClipBetweenTracksActionData(e.data);this.restoreMovedClip(o.clipId,o.targetTrackId,o.targetTrackSnapshot,o.targetTrackRestoreAnchor,o.clipAfter,t);break}case"separate_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter),e.data.audioClip&&e.data.audioTrackId&&this.target.addClipToTrack(e.data.audioTrackId,e.data.audioClip);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter);break;case"set_primary_track_magnet":(a=(n=this.target).setPrimaryTrackMagnetEnabled)==null||a.call(n,e.data.nextEnabled);break;case"compound":e.data.actions.forEach(o=>{this.executeRedoInternal(o,t)});break;default:O.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:e.type})}}restoreMovedClip(e,t,i,r,n,a){const o=this.resolveTrackIdForHistorySnapshot(i,t??(i==null?void 0:i.id)??null,a,r);o&&this.target.moveClipToTrack(e,o),this.target.updateClip(e,n)}withClipRemovalBatch(e){return this.target.withClipRemovalBatch?this.target.withClipRemovalBatch(e):e()}normalizeRemoveClipActionData(e){return"clip"in e?e:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null}}normalizeAddClipActionData(e){return"clip"in e?e:{clip:e,targetTrackId:null,targetTrackSnapshot:null,targetTrackRestoreAnchor:null}}normalizeSplitClipActionData(e){return{...e,sourceTrackId:e.sourceTrackId??null,sourceTrackSnapshot:e.sourceTrackSnapshot??null,sourceTrackRestoreAnchor:e.sourceTrackRestoreAnchor??null}}normalizeMoveClipBetweenTracksActionData(e){return{...e,sourceTrackRestoreAnchor:e.sourceTrackRestoreAnchor??null,targetTrackRestoreAnchor:e.targetTrackRestoreAnchor??null}}resolveTrackIdForHistorySnapshot(e,t,i,r){const n=(e==null?void 0:e.id)??t??null;if(n){const o=i.get(n);if(o)return o}if(!e)return t;const a=this.target.ensureTrackFromHistorySnapshot(e,this.resolveRestoreAnchor(r,i))??t;return n&&a&&i.set(n,a),a}resolveRestoreAnchor(e,t){return e?{previousTrackId:e.previousTrackId?t.get(e.previousTrackId)??e.previousTrackId:null,nextTrackId:e.nextTrackId?t.get(e.nextTrackId)??e.nextTrackId:null}:null}}const Dd=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],Ld=new Set(["thumbnails"]);function Bd(s,e){return Object.is(s,e)?!0:s===void 0||e===void 0?!1:typeof s=="object"&&typeof e=="object"?JSON.stringify(s)===JSON.stringify(e):!1}class Is{constructor(e){g(this,"transactionStack",[]);this.history=e}createAddClipAction(e,t=null,i=null,r=null){return this.history.createAddClipAction(e,t,i,r)}recordAddClip(e,t=null,i=null,r=null){const n=this.history.createAddClipAction(e,t,i,r);return this.recordAction(n),n}createRemoveClipAction(e,t=null,i=null,r=null){return t||i?this.history.createRemoveClipActionWithTrackSnapshot(e,t,i,r):this.history.createRemoveClipAction(e)}recordRemoveClip(e,t=null,i=null,r=null){const n=this.createRemoveClipAction(e,t,i,r);return this.recordAction(n),n}recordClipUpdate(e,t,i){const r=this.createClipUpdateAction(e,t,i);return r?(this.recordAction(r),r):null}recordSplitClip(e,t,i=null,r=null,n=null){const a={...e,duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},o={trackId:i,trackSnapshot:r,trackRestoreAnchor:n},l=this.history.createSplitClipAction(a,e,t,o);return this.recordAction(l),l}recordRemoveGaps(e){if(e.length===0)return null;const t=this.history.createRemoveGapsAction(e);return this.recordAction(t),t}recordMoveClipBetweenTracks(e,t,i,r,n,a,o,l=null,c=null){const h=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,a,o,l,c);return this.recordAction(h),h}recordSeparateClipAudio(e,t,i,r){const n=this.history.createSeparateClipAudioAction(e,t,i,r);return this.recordAction(n),n}recordRestoreClipAudio(e,t,i,r){const n=this.history.createRestoreClipAudioAction(e,t,i,r);return this.recordAction(n),n}createSeparateClipAudioAction(e,t,i,r){return this.history.createSeparateClipAudioAction(e,t,i,r)}createRestoreClipAudioAction(e,t,i,r){return this.history.createRestoreClipAudioAction(e,t,i,r)}recordSetPrimaryTrackMagnet(e,t){const i=this.history.createSetPrimaryTrackMagnetAction(e,t);return this.recordAction(i),i}recordCompoundAction(e,t){if(e.length===0)return null;const i=this.history.createCompoundAction(e,t);return this.recordAction(i),i}createClipUpdateAction(e,t,i){if(i&&i.length>0)return this.history.createMultiClipUpdateAction(i);if(!t)return null;const r={},n={};if(Dd.forEach(d=>{Bd(e[d],t[d])||(r[d]=e[d],n[d]=t[d])}),Object.keys(r).length===0)return null;const a=Object.keys(r);if(a.every(d=>Ld.has(d)))return null;const o=new Set(["startTime","endTime"]);if(a.includes("startTime")&&a.every(d=>o.has(d)))return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);const c=new Set(["duration","startTime","endTime"]);return a.includes("duration")&&a.every(d=>c.has(d))?this.history.createResizeClipAction(e.id,e.duration,e.startTime,t.duration,t.startTime):this.history.createUpdateClipAction(e.id,r,n)}withTransaction(e,t){this.transactionStack.push({label:e,actions:[]});try{const i=t();return i instanceof Promise?i.then(r=>(this.finalizeTransaction(),r),r=>{throw this.finalizeTransaction(),r}):(this.finalizeTransaction(),i)}catch(i){throw this.finalizeTransaction(),i}}recordAction(e){const t=this.transactionStack[this.transactionStack.length-1];return t?(t.actions.push(e),e):(this.history.addAction(e),e)}finalizeTransaction(){const e=this.transactionStack.pop();if(!e)return;const t=this.normalizeTransactionActions(e.actions,e.label);if(!t)return;const i=this.transactionStack[this.transactionStack.length-1];if(i){i.actions.push(t);return}this.history.addAction(t)}normalizeTransactionActions(e,t){return e.length===0?null:e.length===1?e[0]??null:this.history.createCompoundAction(e,t)}}function Bi(s){var e;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function Od(s){var e,t,i;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),(t=s.reloadClipThumbnailsIfNeeded)==null||t.call(s),(i=s.checkTrackDurationChange)==null||i.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function Fd(s,e,t=!1){if(!e||!t||s.type==="audio")return!1;const i=e.duration!==s.duration,r=e.startTimeAtSource!==s.startTimeAtSource||e.endTimeAtSource!==s.endTimeAtSource;return i||r}function kt(s){return s.length===0?0:Math.max(...s.map(e=>e.endTime))}function Nd(s,e){return e<kt(s)}function Gd(s){return s.currentCanPlay===s.nextCanPlay?s.currentCanPlay:(s.setCanPlay(s.nextCanPlay),s.currentCanPlay&&!s.nextCanPlay&&s.playState==="playing"&&(s.pauseTimeline(),s.setCurrentTime(s.clipEndTime||1)),s.emitCanPlayChange(s.nextCanPlay),s.nextCanPlay)}function Hd(s){const e=!s.id&&s.startTime>0;return{shouldJumpToTime:e,jumpTime:e?s.startTime:null,shouldSelectClip:!!s.id}}function Wi(s){var e;return s.applied?(s.isExecutingHistoryAction||(e=s.recordHistory)==null||e.call(s),s.applyEffects(),!0):!1}function zd(s){return Wi({applied:s.applied,isExecutingHistoryAction:s.isExecutingHistoryAction,recordHistory:()=>{var e;(e=s.recordMoveClipBetweenTracks)==null||e.call(s,s.clipId,s.sourceTrackId,s.targetTrackId,s.clipBefore,s.clipAfter,s.sourceTrackSnapshot,s.targetTrackSnapshot)},applyEffects:s.applyEffects})}function $d(s){var e;s.isExecutingHistoryAction||(e=s.recordSplitClip)==null||e.call(s,s.clip1,s.clip2),s.emitClipUpdated(s.clip1),s.emitClipAdded(s.clip2),s.applyEffects()}const Vd={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function Ud(s){var e,t;try{const i=typeof location<"u"?location.href:"http://localhost/";return((e=new URL(s,i).pathname.split(".").pop())==null?void 0:e.toLowerCase())??""}catch{return((t=(s.split(/[?#]/,1)[0]??"").split(".").pop())==null?void 0:t.toLowerCase())??""}}function Wd(s){const e=Ud(s.src);if(e==="mp4")return{url:s.src,mimeType:"video/mp4",kind:"mp4"};if(e==="m3u8")return{url:s.src,mimeType:"application/vnd.apple.mpegurl",kind:"hls-fmp4"};const t=Vd[e];return t?{url:s.src,mimeType:t,kind:"audio"}:null}class Yd{constructor(e){g(this,"container",null);g(this,"statusElement",null);g(this,"actionElement",null);g(this,"onRetry");this.onRetry=e}mount(e){this.container=e,this.container.className="timeline-preview-pending-overlay",this.container.style.position="absolute",this.container.style.top="12px",this.container.style.left="12px",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="flex-start",this.container.style.flexDirection="row",this.container.style.gap="8px",this.container.style.background=Ue.background,this.container.style.color=Ue.text,this.container.style.fontSize="13px",this.container.style.lineHeight="1",this.container.style.padding="8px 10px",this.container.style.borderRadius="6px",this.container.style.zIndex="2000",this.container.style.pointerEvents="auto";const t=document.createElement("div");t.className="timeline-preview-pending-overlay__status",t.style.fontWeight="600";const i=document.createElement("button");i.className="timeline-preview-pending-overlay__action",i.style.display="none",i.style.padding="6px 12px",i.style.border="0",i.style.borderRadius="6px",i.style.cursor="pointer",i.style.background=Ue.actionBackground,i.style.color=Ue.actionText,i.textContent="刷新重试",i.addEventListener("click",this.onRetry),this.container.appendChild(t),this.container.appendChild(i),this.statusElement=t,this.actionElement=i}update(e){if(!this.container||!this.statusElement||!this.actionElement)return;const{pendingState:t,runtimeState:i}=e,r=(t==null?void 0:t.loading)??i.loading,n=!!(t!=null&&t.errorMessage)||r.status==="failed"||i.phase==="failed";if(!t&&r.status!=="loading"){this.container.style.display="none",this.actionElement.style.display="none";return}if(this.container.style.display="inline-flex",this.container.style.background=n?Ue.failedBackground:Ue.background,this.container.style.color=n?Ue.failedText:Ue.text,n){this.statusElement.textContent="媒体丢失",this.actionElement.style.display="inline-flex";return}this.statusElement.textContent=this.resolveLoadingStatusText(r.reason),this.actionElement.style.display="none"}resolveLoadingStatusText(e){switch(e){case"syncing":case"resolving-source":return"资源加载中...";case"seeking":return"正在定位预览...";case"media-pending":return"等待资源加载...";case"failed":return"媒体丢失";default:return"资源加载中..."}}destroy(){var e,t;(e=this.actionElement)==null||e.removeEventListener("click",this.onRetry),(t=this.container)==null||t.remove(),this.container=null,this.statusElement=null,this.actionElement=null}}const _r={x:.5,y:.5,scale:1},Xd=.1,qd=8;function Ar(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function jd(s){return Math.min(qd,Math.max(Xd,s))}function Pe(s){return{x:Ar(s==null?void 0:s.x,_r.x),y:Ar(s==null?void 0:s.y,_r.y),scale:jd(Ar(s==null?void 0:s.scale,_r.scale))}}function wn(s,e,t=1e-4){const i=Pe(s),r=Pe(e);return Math.abs(i.x-r.x)<=t&&Math.abs(i.y-r.y)<=t&&Math.abs(i.scale-r.scale)<=t}function po(s,e){if(s.width<=0||s.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const t=e.width>0?e.width:s.width,i=e.height>0?e.height:s.height,r=t/i,n=s.width/s.height;let a=s.width,o=s.height;r>n?o=a/r:a=o*r;const l=(s.width-a)/2,c=(s.height-o)/2;return{left:l,top:c,width:a,height:o,centerX:l+a/2,centerY:c+o/2}}function Es(s,e,t){const i=po(s,e),r=Pe(t),n=i.width*r.scale,a=i.height*r.scale,o=s.width*r.x,l=s.height*r.y;return{left:o-n/2,top:l-a/2,width:n,height:a,centerX:o,centerY:l}}function go(s,e,t,i){const r=Pe(s),n=i.width>0?i.width:1,a=i.height>0?i.height:1;return Pe({x:r.x+e/n,y:r.y+t/a,scale:r.scale})}function Kd(s,e,t,i,r,n){const a=Pe(n),o=Math.max(r.width/2,1),l=Math.max(r.height/2,1),c=Math.abs(t-s)/o,h=Math.abs(i-e)/l;return Pe({x:a.x,y:a.y,scale:Math.max(c,h)})}function Rs(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}class Zd{constructor(e={}){g(this,"frameElement",null);g(this,"overlayElement",null);g(this,"boxElement",null);g(this,"rotateHandleElement",null);g(this,"rotateHandlePointerDownHandler",null);g(this,"handleElements",new Map);g(this,"handlePointerDownHandlers",new Map);g(this,"state",null);g(this,"interaction",null);g(this,"callbacks");g(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});g(this,"boundPointerUp",()=>{this.finishInteraction(!0)});g(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});g(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});g(this,"handleMovePointerDown",e=>{var i,r,n,a;const t=e;(t.button??0)!==0||!this.state||((i=t.preventDefault)==null||i.call(t),(r=t.stopPropagation)==null||r.call(t),this.state.clipType==="text"&&((a=(n=this.callbacks).onTextTransformInteractionStart)==null||a.call(n)),this.interaction={clipId:this.state.clipId,mode:"move",pointerStart:this.toLocalPoint(t),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing",clipType:this.state.clipType??"video",startFontSize:void 0,nextFontSize:void 0,centerX:void 0,centerY:void 0,startCenterDistance:void 0,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor("grabbing"),this.bindDocumentListeners())});this.callbacks=e}attach(e){if(this.frameElement===e&&this.overlayElement){this.render();return}this.detach(),this.frameElement=e;const t=document.createElement("div");t.className="timeline-preview-transform-overlay",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="3000";const i=document.createElement("div");i.className="timeline-preview-transform-box",i.style.position="absolute",i.style.display="none",i.style.boxSizing="border-box",i.style.border=`1px solid ${ot.border}`,i.style.cursor="grab",i.style.pointerEvents="auto",i.style.userSelect="none",i.addEventListener("pointerdown",this.handleMovePointerDown),t.appendChild(i),this.overlayElement=t,this.boxElement=i,this.createHandle("top-left","nwse-resize"),this.createHandle("top-right","nesw-resize"),this.createHandle("bottom-right","nwse-resize"),this.createHandle("bottom-left","nesw-resize"),this.createRotateHandle(),e.appendChild(t),this.render()}detach(){var e,t;this.finishInteraction(!1),(e=this.boxElement)==null||e.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,r)=>{const n=this.handlePointerDownHandlers.get(r);n&&i.removeEventListener("pointerdown",n)}),this.handleElements.clear(),this.handlePointerDownHandlers.clear(),this.rotateHandleElement&&this.rotateHandlePointerDownHandler&&this.rotateHandleElement.removeEventListener("pointerdown",this.rotateHandlePointerDownHandler),this.rotateHandleElement=null,this.rotateHandlePointerDownHandler=null,(t=this.overlayElement)==null||t.remove(),this.overlayElement=null,this.boxElement=null,this.frameElement=null,this.state=null}sync(e){if(!e){this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==e.clipId&&this.finishInteraction(!1),this.state=e,this.render()}createRotateHandle(){if(!this.overlayElement)return;const e=document.createElement("div");e.className="timeline-preview-transform-rotate-handle",e.style.position="absolute",e.style.display="none",e.style.width="20px",e.style.height="20px",e.style.borderRadius="999px",e.style.border=`1px solid ${ot.border}`,e.style.background=ot.handleBackground,e.style.pointerEvents="auto",e.style.cursor="grab",e.style.boxSizing="border-box",e.style.transform="translate(-50%, -50%)",e.style.display="none",e.style.alignItems="center",e.style.justifyContent="center",e.style.fontSize="12px",e.style.color=ot.border,e.style.userSelect="none",e.textContent="↺";const t=this.getRotateHandlePointerDown();e.addEventListener("pointerdown",t),this.rotateHandleElement=e,this.rotateHandlePointerDownHandler=t,this.overlayElement.appendChild(e)}getRotateHandlePointerDown(){return e=>{var o,l,c,h;const t=e;if((t.button??0)!==0||!this.state)return;(o=t.preventDefault)==null||o.call(t),(l=t.stopPropagation)==null||l.call(t),this.state.clipType==="text"&&((h=(c=this.callbacks).onTextTransformInteractionStart)==null||h.call(c));const i=this.state.displayRect.left+this.state.displayRect.width/2,r=this.state.displayRect.top+this.state.displayRect.height/2,n=this.toLocalPoint(t),a=Math.atan2(n.y-r,n.x-i)*(180/Math.PI);this.interaction={clipId:this.state.clipId,mode:"rotate",pointerStart:n,startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing",clipType:"text",startFontSize:void 0,nextFontSize:void 0,centerX:i,centerY:r,startCenterDistance:void 0,startRotation:this.state.currentRotation??0,nextRotation:this.state.currentRotation??0,startAngle:a},this.setGlobalCursor("grabbing"),this.bindDocumentListeners()}}createHandle(e,t){if(!this.boxElement)return;const i=document.createElement("div");i.className=`timeline-preview-transform-handle timeline-preview-transform-handle--${e}`,i.style.position="absolute",i.style.width="10px",i.style.height="10px",i.style.border=`1px solid ${ot.border}`,i.style.background=ot.handleBackground,i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=t,i.style.boxSizing="border-box",i.style.transform="translate(-50%, -50%)";const r=this.getHandlePointerDown(e);i.addEventListener("pointerdown",r),this.handleElements.set(e,i),this.handlePointerDownHandlers.set(e,r),this.boxElement.appendChild(i)}getHandlePointerDown(e){return t=>{var c,h,d,u;const i=t;if((i.button??0)!==0||!this.state)return;(c=i.preventDefault)==null||c.call(i),(h=i.stopPropagation)==null||h.call(i);const r=this.state.clipType==="text";r&&((u=(d=this.callbacks).onTextTransformInteractionStart)==null||u.call(d));const n=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize",a=r?this.state.displayRect.left+this.state.displayRect.width/2:void 0,o=r?this.state.displayRect.top+this.state.displayRect.height/2:void 0,l=r?Math.sqrt(Math.pow(this.state.displayRect.width/2,2)+Math.pow(this.state.displayRect.height/2,2)):void 0;this.interaction={clipId:this.state.clipId,mode:"scale",pointerStart:this.toLocalPoint(i),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:n,clipType:this.state.clipType??"video",startFontSize:r?this.state.currentFontSize:void 0,nextFontSize:r?this.state.currentFontSize:void 0,centerX:a,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor(n),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,r,n,a;const e=this.getDocument();e&&((t=e.addEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.addEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.addEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(a=(n=globalThis.window)==null?void 0:n.addEventListener)==null||a.call(n,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,r,n,a;const e=this.getDocument();e&&((t=e.removeEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.removeEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.removeEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(a=(n=globalThis.window)==null?void 0:n.removeEventListener)==null||a.call(n,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var n,a,o,l,c,h,d;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const t=e;(n=t.preventDefault)==null||n.call(t);const i=this.toLocalPoint(t);if(this.interaction.mode==="rotate"&&this.interaction.startRotation!==void 0){const u=i.x-this.interaction.centerX,p=i.y-this.interaction.centerY,m=Math.atan2(p,u)*(180/Math.PI)-this.interaction.startAngle,S=Math.round(this.interaction.startRotation+m);this.interaction.nextRotation=S,this.interaction.changed=S!==this.interaction.startRotation,(o=(a=this.callbacks).onRotationChange)==null||o.call(a,this.interaction.clipId,S);return}if(this.interaction.clipType==="text"&&this.interaction.startFontSize!==void 0){const u=i.x-this.interaction.centerX,p=i.y-this.interaction.centerY,f=Math.sqrt(u*u+p*p),m=(this.interaction.startCenterDistance??0)>0?f/this.interaction.startCenterDistance:1,S=Math.max(5,Math.min(300,Math.round(this.interaction.startFontSize*m)));this.interaction.nextFontSize=S,this.interaction.changed=S!==this.interaction.startFontSize,(c=(l=this.callbacks).onFontSizeChange)==null||c.call(l,this.interaction.clipId,S);return}let r=this.interaction.startTransform;if(this.interaction.mode==="move")r=go(this.interaction.startTransform,i.x-this.interaction.pointerStart.x,i.y-this.interaction.pointerStart.y,this.interaction.frameSize);else{const u=this.interaction.startTransform.x*this.interaction.frameSize.width,p=this.interaction.startTransform.y*this.interaction.frameSize.height;r=Kd(u,p,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!wn(this.interaction.startTransform,r),(d=(h=this.callbacks).onPreviewTransformChange)==null||d.call(h,this.interaction.clipId,r)}finishInteraction(e){var i,r,n,a,o,l,c,h,d,u,p,f;const t=this.interaction;if(!t){this.setGlobalCursor(null),this.unbindDocumentListeners();return}t.mode==="rotate"?(e&&t.changed&&t.nextRotation!==void 0&&((r=(i=this.callbacks).onRotationCommit)==null||r.call(i,t.clipId,t.nextRotation)),(a=(n=this.callbacks).onRotationChange)==null||a.call(n,t.clipId,null)):t.clipType==="text"?(e&&t.changed&&t.nextFontSize!==void 0&&((l=(o=this.callbacks).onFontSizeCommit)==null||l.call(o,t.clipId,t.nextFontSize)),(h=(c=this.callbacks).onFontSizeChange)==null||h.call(c,t.clipId,null)):(e&&t.changed&&((u=(d=this.callbacks).onPreviewTransformCommit)==null||u.call(d,t.clipId,t.nextTransform)),(f=(p=this.callbacks).onPreviewTransformChange)==null||f.call(p,t.clipId,null)),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners(),this.render()}render(){var r;if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none"),this.rotateHandleElement&&(this.rotateHandleElement.style.display="none");return}const e=this.state.clipType==="text";this.boxElement.style.pointerEvents=e?"none":"auto",this.boxElement.style.cursor=e?"default":"grab";const{displayRect:t}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${t.left}px`,this.boxElement.style.top=`${t.top}px`,this.boxElement.style.width=`${t.width}px`,this.boxElement.style.height=`${t.height}px`;const i=e?this.state.currentRotation??0:0;if(this.boxElement.style.transformOrigin="center",this.boxElement.style.transform=i!==0?`rotate(${i}deg)`:"",this.positionHandle("top-left",0,0),this.positionHandle("top-right",t.width,0),this.positionHandle("bottom-right",t.width,t.height),this.positionHandle("bottom-left",0,t.height),this.rotateHandleElement)if(e){if(!(((r=this.interaction)==null?void 0:r.mode)==="rotate")){const a=t.left+t.width/2,o=t.top+t.height/2,l=t.height/2+20,c=i*(Math.PI/180),h=a-l*Math.sin(c),d=o+l*Math.cos(c);this.rotateHandleElement.style.left=`${h}px`,this.rotateHandleElement.style.top=`${d}px`}this.rotateHandleElement.style.display="flex"}else this.rotateHandleElement.style.display="none"}positionHandle(e,t,i){const r=this.handleElements.get(e);r&&(r.style.left=`${t}px`,r.style.top=`${i}px`)}toLocalPoint(e){const t=this.getFrameBounds();return{x:(e.clientX??0)-t.left,y:(e.clientY??0)-t.top}}getFrameBounds(){var t,i;if(!this.frameElement)return{left:0,top:0,width:0,height:0};const e=(i=(t=this.frameElement).getBoundingClientRect)==null?void 0:i.call(t);return e&&Number.isFinite(e.width)&&Number.isFinite(e.height)?{left:e.left,top:e.top,width:e.width,height:e.height}:{left:Rs(this.frameElement.style.left),top:Rs(this.frameElement.style.top),width:this.frameElement.clientWidth,height:this.frameElement.clientHeight}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}setGlobalCursor(e){var i;const t=(i=this.getDocument())==null?void 0:i.body;t&&(t.style.cursor=e||"")}}function Jd(s,e){var u;const t=s.activeClips.filter(p=>p.trackType!=="text"),i=s.nextClips.filter(p=>p.trackType!=="text"),r=s.interactionMode??"steady",n=new Map(t.map(p=>[p.trackId,p])),a=new Map(i.map(p=>[p.trackId,p])),o=new Map,l=t.filter(p=>p.trackType==="video"&&p.hasVisual).sort((p,f)=>p.trackOrder-f.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(p,f)=>!a.has(p)||r!=="steady"&&c?!1:c?s.playState==="playing"&&f==="video"&&p===h:s.playState!=="playing"||t.length<=1;return e.forEach(p=>{o.set(p.trackId,{kind:p.kind,order:p.order})}),t.forEach(p=>{o.set(p.trackId,{kind:p.trackType,order:p.trackOrder})}),i.forEach(p=>{o.set(p.trackId,{kind:p.trackType,order:p.trackOrder})}),Array.from(o.entries()).map(([p,f])=>{const m=n.get(p)||null,S=d(p,f.kind)&&a.get(p)||null;return{trackId:p,kind:f.kind,order:f.order,current:{role:"current",entry:m,playState:s.requestedPlayState??s.playState,speed:s.speed,visible:!!(m!=null&&m.hasVisual),zIndex:m?1e3-m.trackOrder:0,syncRequestId:s.syncRequestId},preload:{role:"preload",entry:S,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:s.syncRequestId}}}).sort((p,f)=>p.order-f.order)}function on(s,e){return s.entry?e?s.entry.clip.id===e:!0:!1}function Qd(s,e){return e?!on(s.current,e.clip.id)&&on(s.preload,e.clip.id):!1}function eu(s){return s.current.role="preload",s.preload.role="current",{current:s.preload,preload:s.current}}function tu(s){return`${s.trackId}:${s.role}`}function iu(s,e){return s.role!=="preload"||!on(s)?null:{role:"preload",entry:s.entry,playState:s.requestedPlayState,speed:1,visible:!1,zIndex:0,syncRequestId:e}}function ru(s,e){const t=e.lastIndexOf(":");if(t<=0)return null;const i=e.slice(0,t),r=e.slice(t+1);if(r!=="current"&&r!=="preload")return null;const n=s.get(i);return n?r==="current"?n.current:n.preload:null}function nu(s,e,t,i){const r=e||s.clip.src||"";switch(t){case"abort":case"emptied":return`${s.clip.id}:${r}:${t}`;case"error":case"reconcile":case"stalled":return`${s.clip.id}:${r}:${Math.floor(s.mediaTime/i)}`;default:return`${s.clip.id}:${r}`}}function su(s){if(!s.desiredSource||!s.stableSourceUrl||!s.currentSourceKey||s.currentSourceKey!==s.nextSourceKey)return null;const e=s.objectUrl??(s.desiredSource.startsWith("blob:")?s.desiredSource:null);return{stableSourceUrl:s.stableSourceUrl,url:s.desiredSource,objectUrl:e}}function au(s,e,t){return t?s===t||e===t:!1}function ou(s){const e=s.configuredSource||null,t=e||s.assignedSource||null;let i=!1,r=null;return s.forceRecover?(i=!0,r="force-recover"):e?t!==s.desiredSource?(i=!0,r="source-mismatch"):s.networkState===s.networkEmptyState&&((s.readyState??0)>=s.haveCurrentDataState?(i=!1,r="network-empty-but-current-data-ready"):(i=!(s.isLoading||s.phase==="binding"||s.phase==="recovering"),r=i?"network-empty":"network-empty-binding-in-flight")):(i=!0,r="missing-src-attribute"),{needsRecovery:i,recoveryReason:r,actualSource:t,configuredSource:e,shouldWarn:i&&(r==="source-mismatch"||s.isActive&&s.phase!=="idle"&&s.phase!=="binding")}}function lu(s,e){const t=s==="current"?Math.abs(e):1;return Math.max(.1,t*.15)}function cu(s,e,t){return!!s||e!=="reconcile"||t>1}function hu(s){return{role:s.role,entry:s.entry,playState:s.requestedPlayState,speed:s.isActive&&s.playbackRate||1,visible:s.isActive&&!!s.entry.hasVisual,zIndex:1e3-s.entry.trackOrder,syncRequestId:s.syncRequestId}}function du(s){const e=nu(s.entry,s.desiredSource,s.reason,s.recoveryTimeBucketMs);return s.previousRecoveryKey===e?s.previousRetryCount>=s.maxImmediateRecoveryRetries?s.isBackgroundPreload?{status:"park",message:"媒体恢复失败,请等待下一次重建",parkReason:"retries-exhausted"}:{status:"fail",message:"媒体恢复失败,请刷新重试"}:{status:"continue",recoveryKey:e,retryCount:s.previousRetryCount+1}:{status:"continue",recoveryKey:e,retryCount:1}}function fo(s,e){s.phase="idle",s.errorMessage=null,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,gr(s,e)}function uu(s){s.phase==="failed"&&(s.phase="binding",s.errorMessage=null,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,gr(s))}function gr(s,e=!1){s.forceRecover=e,s.retryCount=0,s.recoveryKey=null,s.expectedEmptiedEvents=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}function pu(s){fo(s,!1)}function gu(s){fo(s,!0)}function fu(s){s.phase==="binding"&&(s.phase=s.isActive?"active":"primed"),s.isResolvingSource=!1,s.isLoading=!1,s.isBuffering=!1,(s.phase!=="failed"||!s.errorMessage)&&(s.errorMessage=null)}function mu(s){s.isLoading||s.isSeeking||s.phase==="failed"&&s.errorMessage||(s.phase=s.isActive?"active":"primed")}function yu(s,e){s.forceRecover=!0,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=null,e||(s.phase="idle")}function Su(s,e){const t=!!s.isSeeking&&!e.withinSeekThreshold,i=s.isResolvingSource,r=!i&&e.hasDesiredSource&&e.sourceMatched&&!t&&e.readyState>=e.haveCurrentDataState,n=s.phase==="failed"&&!r,a=!r&&!n&&(!e.hasDesiredSource||!e.sourceMatched||s.phase==="binding"||s.phase==="recovering"||e.readyState<e.haveCurrentDataState);return s.isSeeking=t,r?(gr(s),s.isLoading=!1,s.isBuffering=!1,s.errorMessage=null,s.phase=s.isActive?"active":"primed"):!n&&s.phase!=="recovering"&&s.phase!=="binding"&&(s.phase=s.isActive?"active":"primed"),{failed:n,resolving:i,seeking:t,mediaUnready:a,ready:r}}function Ms(s,e){s.phase="failed",s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=e,s.forceRecover=!1,s.expectedEmptiedEvents=0}function vu(s){s.isActive=!1,s.isBuffering=!1,s.isSeeking=!1}function Cu(s,e){s.phase="recovering",s.errorMessage=null,s.forceRecover=!1,s.isLoading=!0,s.isResolvingSource=!1,s.isBuffering=s.isActive&&e==="playing",s.isSeeking=!1,s.consecutiveStalledCount=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}const Tu=0,at=2,Ir=3,bu=2,ku=250,wu=250,Pu=100,xu=500,_u=700,Ds=.03,Ls=8e3,Au=.5,Iu=750,Bs="Arial, sans-serif",Wt="媒体丢失";function Eu(s,e){const t=Math.max(0,Math.round(s));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let n=-t;n<=t;n+=1)n===0&&r===0||i.push(`${n}px ${r}px 0 ${e}`);return i.join(", ")}function mo(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Er(s){return`"${mo(s)}"`}function Ru(s){return un(s,hn)}function Mu(s,e){return!_t(s.mode)||!e?s:{mode:Be.mode,width:e.width,height:e.height}}function _e(s){return s.getAttribute("src")||s.currentSrc||s.src||""}function sr(s){return s.getAttribute("src")||""}function Fe(s,e){const t=sr(s),i=s.currentSrc||"",r=s.src||"",n=_e(s);return{desiredSource:e||null,srcAttribute:t||null,currentSrc:i||null,elementSrc:r||null,assignedSrc:n||null,hasSrcAttribute:!!t,matchesDesiredByAttribute:!!e&&t===e,matchesDesiredByAssigned:!!e&&n===e}}function ar(s){return typeof HTMLVideoElement<"u"?s instanceof HTMLVideoElement:s.tagName==="VIDEO"}function Ye(s){try{s.load()}catch{}}function Ne(s){try{s.pause()}catch{}}function Rr(s){var e;try{const t=s.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function Os(s,e){try{s.currentTime=Math.max(0,e)}catch{}}function Oi(s,e){var i;const t=(i=s==null?void 0:s.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function Fs(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}function Yi(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function Du(s){const e=s.buffered;if(!e||typeof e.length!="number"||e.length<=0)return null;try{return Number(e.end(e.length-1).toFixed(3))}catch{return null}}function ee(s){return{tsMs:Yi(),currentTime:Number.isFinite(s.currentTime)?Number(s.currentTime.toFixed(3)):null,duration:Number.isFinite(s.duration)?Number(s.duration.toFixed(3)):null,currentSrc:_e(s)||null,srcAttribute:sr(s)||null,elementSrc:s.src||null,rawCurrentSrc:s.currentSrc||null,readyState:typeof s.readyState=="number"?s.readyState:null,networkState:typeof s.networkState=="number"?s.networkState:null,paused:typeof s.paused=="boolean"?s.paused:null,ended:typeof s.ended=="boolean"?s.ended:null,playbackRate:typeof s.playbackRate=="number"?Number(s.playbackRate.toFixed(3)):null,bufferedEnd:Du(s),videoWidth:ar(s)?s.videoWidth:null,videoHeight:ar(s)?s.videoHeight:null,error:s.error?{code:typeof s.error.code=="number"?s.error.code:null,message:s.error.message??null}:null}}function Ge(s){return typeof(s==null?void 0:s.then)=="function"}class Lu{constructor(e={},t={}){g(this,"container",null);g(this,"rootElement",null);g(this,"frameElement",null);g(this,"textOverlayRoot",null);g(this,"pendingOverlayElement",null);g(this,"pendingOverlayRenderer");g(this,"resizeObserver",null);g(this,"trackSlots",new Map);g(this,"textPreviewEntries",new Map);g(this,"audioContext",null);g(this,"masterGainNode",null);g(this,"loadingProbeTimeoutId",null);g(this,"clockProbeTimeoutId",null);g(this,"playbackGroupSuspended",!1);g(this,"lastRuntimeSignature",null);g(this,"lastRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});g(this,"lastSettledSyncRequestId",null);g(this,"primarySelectedClipId",null);g(this,"transientVisualTransform",null);g(this,"transientFontSize",null);g(this,"transientRotation",null);g(this,"textPreviewDragState",null);g(this,"textPreviewFontStyleElement",null);g(this,"textPreviewFontSignature",null);g(this,"textPreviewFontLoadState","idle");g(this,"textPreviewFontLoadToken",0);g(this,"callbacks");g(this,"dependencies");g(this,"transformOverlay");g(this,"boundTextPreviewPointerMove",e=>{this.handleTextPreviewPointerMove(e)});g(this,"boundTextPreviewPointerUp",()=>{this.finishTextPreviewDrag(!0)});g(this,"boundTextPreviewVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishTextPreviewDrag(!1)});g(this,"boundTextPreviewWindowBlur",()=>{this.finishTextPreviewDrag(!1)});g(this,"requestedAspectRatio",{...Be});g(this,"resolvedAutoAspectRatio",null);g(this,"aspectRatioProbe",null);g(this,"aspectRatioProbeSrc",null);g(this,"aspectRatioProbeResolveToken",0);g(this,"pendingState",null);g(this,"activeSyncRequestId");g(this,"isSyncProjecting",!1);g(this,"deferredPreloadSlotKeys",new Set);g(this,"deferredPreloadFlushScheduled",!1);g(this,"lastSyncedPlayState","paused");g(this,"pendingClockAlignmentTargetTime",null);this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new Yd(()=>{var i,r;(r=(i=this.callbacks).onPendingPreviewRetry)==null||r.call(i)}),this.transformOverlay=new Zd({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onVisualTransformCommit)==null||a.call(n,i,r)},onFontSizeChange:(i,r)=>{var a;if(r===null){if(((a=this.transientFontSize)==null?void 0:a.clipId)===i){this.transientFontSize=null;const o=this.textPreviewEntries.get(i);o&&(o.element.style.fontSize=`${De(o.entry.clip.textStyle).fontSize}px`),this.refreshVisualLayout()}return}this.transientFontSize={clipId:i,fontSize:r};const n=this.textPreviewEntries.get(i);n&&(n.element.style.fontSize=`${r}px`),this.refreshVisualLayout()},onFontSizeCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onTextFontSizeCommit)==null||a.call(n,i,r)},onRotationChange:(i,r)=>{var n;if(r===null){((n=this.transientRotation)==null?void 0:n.clipId)===i&&(this.transientRotation=null,this.refreshVisualLayout());return}this.transientRotation={clipId:i,rotation:r},this.refreshVisualLayout()},onRotationCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onTextRotationCommit)==null||a.call(n,i,r)},onTextTransformInteractionStart:()=>{this.requestPauseIfPlaying()}})}requestPauseIfPlaying(){var e,t;this.lastSyncedPlayState==="playing"&&((t=(e=this.callbacks).onPauseIfPlaying)==null||t.call(e))}emitDiagnostic(e,t,i,r={}){var o,l;const n=this.dependencies.diagnostics;if(!n)return;const a=((l=(o=this.dependencies).getDiagnosticsContext)==null?void 0:l.call(o))??{};n.emit({...a,...r,severity:e,category:t,eventName:i,runtimeState:ja(a.runtimeState,r.runtimeState)})}buildSlotTraceData(e,t={}){var i;return{...t,trackId:e.trackId,clipId:((i=e.entry)==null?void 0:i.clip.id)??null,slotKey:`${e.trackId}:${e.role}`,desiredSourceUrl:e.desiredSource,actualSourceUrl:_e(e.element)||null,extra:{role:e.role,kind:e.kind,phase:e.phase,retryCount:e.retryCount,sourceState:Fe(e.element,e.desiredSource),...t.extra??{}}}}hasPreview(){return!!this.container}attach(e){if(this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e;const t=document.createElement("div");t.className=this.dependencies.rootClassName??"timeline-preview-root",t.style.position="relative",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden";const i=document.createElement("div");i.className=this.dependencies.frameClassName??"timeline-preview-frame",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.overflow="hidden",i.style.background=_.black,t.appendChild(i);const r=document.createElement("div");r.className="timeline-preview-text-layer",r.style.position="absolute",r.style.inset="0",r.style.pointerEvents="none",r.style.zIndex="2000",i.appendChild(r);const n=document.createElement("div");t.appendChild(n),this.pendingOverlayRenderer.mount(n),e.appendChild(t),this.rootElement=t,this.frameElement=i,this.textOverlayRoot=r,this.pendingOverlayElement=n,this.transformOverlay.attach(i),this.ensureTextPreviewFontReady(),this.emitDiagnostic("info","session","preview.attach",{message:"Preview attached",extra:{containerWidth:e.clientWidth,containerHeight:e.clientHeight}}),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(e)),this.updateFrameLayout(),this.refreshPendingOverlay(),this.refreshRuntimeState()}detach(){var e,t,i,r,n,a;this.emitDiagnostic("info","session","preview.detach",{message:"Preview detached",extra:{slotCount:this.trackSlots.size}}),(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,this.transformOverlay.detach(),this.finishTextPreviewDrag(!1),this.pendingOverlayRenderer.destroy();for(const o of this.trackSlots.values())this.destroySlot(o.current),this.destroySlot(o.preload);this.trackSlots.clear(),this.clearTextPreviewEntries(),this.resetTextPreviewFontState(),this.aspectRatioProbe&&(Ne(this.aspectRatioProbe),this.aspectRatioProbe.src="",Ye(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.aspectRatioProbeResolveToken+=1,this.audioContext&&((n=(i=(t=this.audioContext).close)==null?void 0:(r=i.call(t)).catch)==null||n.call(r,()=>{}),this.audioContext=null,this.masterGainNode=null),(a=this.rootElement)==null||a.remove(),this.rootElement=null,this.frameElement=null,this.textOverlayRoot=null,this.pendingOverlayElement=null,this.container=null,this.primarySelectedClipId=null,this.transientVisualTransform=null,this.transientFontSize=null,this.transientRotation=null,this.pendingState=null,this.activeSyncRequestId=void 0,this.isSyncProjecting=!1,this.clearLoadingProbe(),this.clearClockProbe(),this.playbackGroupSuspended=!1,this.lastRuntimeSignature=null,this.lastSettledSyncRequestId=null,this.pendingClockAlignmentTargetTime=null,this.lastRuntimeState={phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]},this.refreshPendingOverlay(),this.refreshRuntimeState()}setPendingState(e){this.pendingState=e,this.refreshPendingOverlay()}sync(e){var a;if(!this.rootElement||!this.frameElement)return;this.lastSyncedPlayState=e.playState,this.updatePendingClockAlignmentTarget(e),this.primarySelectedClipId=e.primarySelectedClipId??null,this.activeSyncRequestId=e.syncRequestId,this.emitDiagnostic("info","playback","preview.sync.requested",{message:"Preview sync requested",syncRequestId:e.syncRequestId??null,runtimeState:{currentTimeMs:e.currentTime,playState:e.playState,speed:e.speed,activeClipIds:e.activeClips.map(o=>o.clip.id)},extra:{activeClipCount:e.activeClips.length,nextClipCount:e.nextClips.length,autoAspectRatioClipId:((a=e.autoAspectRatioClip)==null?void 0:a.clip.id)??null}}),this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.transientFontSize&&this.transientFontSize.clipId!==this.primarySelectedClipId&&(this.transientFontSize=null),this.transientRotation&&this.transientRotation.clipId!==this.primarySelectedClipId&&(this.transientRotation=null),this.textPreviewDragState&&this.textPreviewDragState.clipId!==this.primarySelectedClipId&&this.finishTextPreviewDrag(!1),this.maybeResolveAutoAspectRatio(e.autoAspectRatioClip),this.syncTextPreviewEntries(e.activeClips.filter(o=>o.trackType==="text"));const t=Array.from(this.trackSlots.entries()).map(([o,l],c)=>{var h,d;return{trackId:o,kind:l.current.kind,order:((h=l.current.entry)==null?void 0:h.trackOrder)??((d=l.preload.entry)==null?void 0:d.trackOrder)??1e4+c}}),n=Jd(e,t).map(o=>this.applyTrackPlan(o)).filter(o=>Ge(o));if(this.isSyncProjecting=n.length>0,this.refreshVisualLayout(),this.refreshRuntimeState(),n.length===0){this.refreshVisualLayout(),this.refreshRuntimeState();return}Promise.all(n).then(()=>{this.activeSyncRequestId===e.syncRequestId&&(this.isSyncProjecting=!1,this.refreshVisualLayout(),this.refreshRuntimeState())}).catch(o=>{this.emitDiagnostic("error","playback","preview.sync.failed",{message:"Preview sync failed",syncRequestId:e.syncRequestId??null,error:o}),O.warn("TimelinePreviewSession","preview sync failed",{error:o,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=je(e),this.updateFrameLayout()}getAspectRatio(){return Mu(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}createMediaElement(e,t){const i=this.dependencies.createMediaElement,r=i?i(e,t):document.createElement(e==="video"?"video":"audio");return r.preload=t==="preload"?"auto":"metadata",r.crossOrigin="anonymous",r.loop=!1,r.controls=!1,ar(r)?(Nr(r),r.playsInline=!0,r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.objectFit="fill",r.style.background=_.black,r.style.pointerEvents="none"):r.style.display="none",r}createSlot(e,t,i){var x,D;const r=this.createMediaElement(t,i),n=t==="video"?document.createElement("div"):null,a=t==="video"?document.createElement("div"):null,o=t==="video"?document.createElement("div"):null;if(n){const w=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";n.className=`${w} timeline-preview-slot--${e} timeline-preview-slot--${i}`,n.style.position="absolute",n.style.overflow="hidden",n.style.background=_.black,n.style.pointerEvents="none",n.style.display="none",n.appendChild(r),a&&o&&(a.className="timeline-preview-slot__failure",a.style.position="absolute",a.style.inset="0",a.style.display="none",a.style.alignItems="center",a.style.justifyContent="center",a.style.padding="12px",a.style.boxSizing="border-box",a.style.background=_.mediaClipFailedBackground,a.style.color=_.white,a.style.pointerEvents="none",o.className="timeline-preview-slot__failure-label",o.style.fontSize="18px",o.style.fontWeight="600",o.style.lineHeight="1.2",o.style.textAlign="center",o.textContent=Wt,a.appendChild(o),n.appendChild(a)),(x=this.frameElement)==null||x.appendChild(n)}const l={role:i,trackId:e,kind:t,wrapper:n,failureOverlay:a,failureLabel:o,element:r,entry:null,stableSourceUrl:null,desiredSource:null,objectUrl:null,pendingRuntimeSourceUrl:null,pendingRuntimeSourcePromise:null,requestedPlayState:"paused",isActive:!1,isLoading:!1,isResolvingSource:!1,isBuffering:!1,isSeeking:!1,phase:"idle",errorMessage:null,retryCount:0,recoveryKey:null,sourceNode:null,gainNode:null,audioRoutingFailed:!1,consecutiveStalledCount:0,forceRecover:!1,expectedEmptiedEvents:0,recoverableEventCount:0,loadStartedSinceRecover:!1,hasReadyEventSinceSourceChange:!1,hasBufferingSignalSinceSourceChange:!1,lastPlaybackResumeAttemptAtMs:-1,lastPlaybackProgressCheckAtMs:-1,lastPlaybackProgressMediaTimeSeconds:Number.NaN,playbackProgressStalled:!1,mediaPendingSinceMs:-1,mediaPendingFailureKey:null,resolveToken:0,applyToken:0,cleanup:[]},c=w=>{var A;if(!this.shouldIgnoreClearedSlotRecoverableEvent(l)){if(w==="abort"&&this.shouldIgnoreExpectedAbort(l)){this.emitDiagnostic("debug","playback","media.abort.ignored",this.buildSlotTraceData(l,{message:"Ignored expected media abort during source reset",mediaState:ee(l.element)}));return}if(w==="emptied"&&this.shouldIgnoreExpectedEmptied(l)){this.emitDiagnostic("debug","playback","media.emptied.ignored",this.buildSlotTraceData(l,{message:"Ignored expected media emptied during source reset",mediaState:ee(l.element)}));return}if(this.emitDiagnostic(w==="error"?"error":"warn","playback",`media.${w}`,this.buildSlotTraceData(l,{message:`Media event: ${w}`,mediaState:ee(l.element),error:l.element.error})),w==="error"&&O.error("TimelinePreviewSession",`media event: ${w}`,{trackId:l.trackId,role:l.role,clipId:((A=l.entry)==null?void 0:A.clip.id)??null,phase:l.phase,mediaState:ee(l.element)}),l.forceRecover=!0,l.expectedEmptiedEvents=0,l.isLoading=!1,l.isResolvingSource=!1,l.isSeeking=!1,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),l.recoverableEventCount+=1,this.shouldSkipImmediatePreloadRecovery(l)){l.phase="idle",this.emitDiagnostic("info","recovery","preload.recovery.skipped",this.buildSlotTraceData(l,{message:"Skipped immediate preload recovery after recoverable media event",mediaState:ee(l.element),extra:{reason:w,recoverableEventCount:l.recoverableEventCount,loadStartedSinceRecover:l.loadStartedSinceRecover}})),this.refreshRuntimeState();return}if(this.refreshRuntimeState(),this.shouldDeferPreloadRecovery(l)){this.deferPreloadRecovery(l,w);return}this.recoverSlot(l,w)}},h=()=>c("abort"),d=()=>c("emptied"),u=()=>c("error"),p=()=>{l.loadStartedSinceRecover=!0,l.isLoading=!0,l.hasReadyEventSinceSourceChange=!1,l.hasBufferingSignalSinceSourceChange=!1,l.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.emitDiagnostic("debug","playback","media.loadstart",this.buildSlotTraceData(l,{message:"Media event: loadstart",mediaState:ee(l.element)})),this.refreshRuntimeState()},f=()=>{l.hasReadyEventSinceSourceChange=!0,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.maybeResumeRequestedPlayback(l,"canplay"),this.emitDiagnostic("debug","playback","media.canplay",this.buildSlotTraceData(l,{message:"Media event: canplay",mediaState:ee(l.element)})),this.refreshRuntimeState()},m=()=>{l.hasReadyEventSinceSourceChange=!0,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.emitDiagnostic("debug","playback","media.playing",this.buildSlotTraceData(l,{message:"Media event: playing",mediaState:ee(l.element)})),this.refreshRuntimeState()},S=()=>{this.refreshRuntimeState()},T=()=>{this.emitDiagnostic("debug","playback","media.pause",this.buildSlotTraceData(l,{message:"Media event: pause",mediaState:ee(l.element)})),this.refreshRuntimeState()},v=()=>{l.isBuffering=l.role==="current"&&l.isActive&&l.requestedPlayState==="playing",l.hasBufferingSignalSinceSourceChange=l.isBuffering,l.lastPlaybackResumeAttemptAtMs=-1,this.emitDiagnostic("warn","playback","media.stalled",this.buildSlotTraceData(l,{message:"Media event: stalled",mediaState:ee(l.element)})),this.refreshRuntimeState()},C=()=>{l.isBuffering=l.role==="current"&&l.isActive&&l.requestedPlayState==="playing",l.hasBufferingSignalSinceSourceChange=l.isBuffering,l.lastPlaybackResumeAttemptAtMs=-1,this.emitDiagnostic("warn","playback","media.waiting",this.buildSlotTraceData(l,{message:"Media event: waiting",mediaState:ee(l.element)})),this.refreshRuntimeState()},k=()=>{l.isSeeking=!0,this.refreshRuntimeState()},P=()=>{l.isSeeking=!1,l.hasReadyEventSinceSourceChange=!0,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.maybeResumeRequestedPlayback(l,"seeked"),this.refreshRuntimeState()};return r.addEventListener("loadstart",p),r.addEventListener("canplay",f),r.addEventListener("playing",m),r.addEventListener("progress",S),r.addEventListener("pause",T),r.addEventListener("stalled",v),r.addEventListener("waiting",C),r.addEventListener("seeking",k),r.addEventListener("seeked",P),r.addEventListener("abort",h),r.addEventListener("emptied",d),r.addEventListener("error",u),l.cleanup.push(()=>r.removeEventListener("loadstart",p),()=>r.removeEventListener("canplay",f),()=>r.removeEventListener("playing",m),()=>r.removeEventListener("progress",S),()=>r.removeEventListener("pause",T),()=>r.removeEventListener("stalled",v),()=>r.removeEventListener("waiting",C),()=>r.removeEventListener("seeking",k),()=>r.removeEventListener("seeked",P),()=>r.removeEventListener("abort",h),()=>r.removeEventListener("emptied",d),()=>r.removeEventListener("error",u)),t==="audio"&&((D=this.rootElement)==null||D.appendChild(r)),l}resetSlotRecoveryTracking(e,t=!1){gr(e,t)}destroySlot(e){var t,i,r,n,a;this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.resolveToken+=1,e.applyToken+=1,e.cleanup.forEach(o=>o()),Ne(e.element),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.stableSourceUrl=null,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),e.element.removeAttribute("src"),Ye(e.element),(i=(t=e.gainNode)==null?void 0:t.disconnect)==null||i.call(t),(n=(r=e.sourceNode)==null?void 0:r.disconnect)==null||n.call(r),e.gainNode=null,e.sourceNode=null,(a=e.wrapper)==null||a.remove(),e.element.remove()}releaseSlotObjectUrl(e){var t;e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl),e.objectUrl=null)}clearPendingRuntimeSource(e){e.pendingRuntimeSourceUrl=null,e.pendingRuntimeSourcePromise=null,e.isResolvingSource=!1}rememberSlotObjectUrl(e,t){e.objectUrl&&e.objectUrl!==t&&this.releaseSlotObjectUrl(e),e.objectUrl=t??null}revokeResolvedObjectUrl(e){var t;e!=null&&e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl))}getTrackSlots(e,t){const i=this.trackSlots.get(e);if(i&&i.current.kind===t&&i.preload.kind===t)return i;i&&(this.destroySlot(i.current),this.destroySlot(i.preload),this.trackSlots.delete(e));const r={current:this.createSlot(e,t,"current"),preload:this.createSlot(e,t,"preload")};return this.trackSlots.set(e,r),r}swapTrackSlots(e){const t=this.trackSlots.get(e);t&&this.trackSlots.set(e,eu(t))}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);Qd(t,e.current.entry)&&(this.swapTrackSlots(e.trackId),t=this.getTrackSlots(e.trackId,e.kind));const i=this.applySlotTarget(t.current,e.current),r=this.applySlotTarget(t.preload,e.preload);if(Ge(i)||Ge(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=_e(e.element)||null,a=r?this.buildPreviewSourceCacheKey(r.clip):null,o=t.entry?this.buildPreviewSourceCacheKey(t.entry.clip):null;if(!!r&&!!t.entry&&r.clip.id!==t.entry.clip.id&&(uu(e),e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e),this.resetSlotMediaPendingProbe(e)),e.entry=t.entry,e.requestedPlayState=t.playState,e.isActive=t.role==="current"&&!!t.entry,e.errorMessage=t.entry?e.errorMessage:null,e.isBuffering=t.entry?e.isBuffering:!1,e.isSeeking=t.entry?e.isSeeking:!1,e.consecutiveStalledCount=t.entry?e.consecutiveStalledCount:0,!t.entry){this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),(r||n)&&this.emitDiagnostic("info","playback","slot.cleared",this.buildSlotTraceData(e,{message:"Preview slot cleared",extra:{previousClipId:(r==null?void 0:r.clip.id)??null,previousSource:n}})),Ne(e.element),e.stableSourceUrl=null,e.desiredSource=null,e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e),pu(e),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.element.removeAttribute("src"),Ye(e.element),this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}a&&o&&a!==o&&(this.releaseSlotObjectUrl(e),e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e));const c=this.resolveDesiredSource(e,t.entry,i,a);if(Ge(c))return c.then(h=>{if(!h||!this.isCurrentSourceTarget(e,t.entry,h.stableSourceUrl)){this.revokeResolvedObjectUrl(h);return}const d=this.buildCurrentTargetForSlot(e)??t;if(!d.entry){this.revokeResolvedObjectUrl(h);return}if(e.stableSourceUrl=h.stableSourceUrl,e.desiredSource=h.url,this.configureAudioRouting(e,d.entry),this.slotNeedsRecovery(e,h.url)){if(this.shouldDeferPreloadTarget(e,d,h.url)){this.deferPreloadTarget(e,d,h,"current-loading");return}return Promise.resolve(this.recoverSlot(e,"reconcile",d,void 0,h)).then(()=>{})}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,h.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,d)});if(!c||!this.isCurrentRequest(e,i,t.entry)){this.revokeResolvedObjectUrl(c);return}if(e.stableSourceUrl=c.stableSourceUrl,e.desiredSource=c.url,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,c.url)){if(this.shouldDeferPreloadTarget(e,t,c.url)){this.deferPreloadTarget(e,t,c,"current-loading");return}return this.recoverSlot(e,"reconcile",t,i,c)}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,c.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,t)}settleResolvedSourceWithoutRecovery(e){fu(e)}resolveDesiredSource(e,t,i,r){const n=this.getReusableBoundSlotSource(e,t,r);if(n)return n;const a=this.dependencies.previewSourceResolver??Wd,o=this.dependencies.sourceMediaRegistry;let l=null;const c=()=>(l!==null||(e.resolveToken+=1,l=e.resolveToken,e.phase="binding",e.isResolvingSource=!0,e.isLoading=!0,this.emitDiagnostic("info","resource","source.resolve.pending",this.buildSlotTraceData(e,{message:"Preview source resolving",sourceUrl:t.clip.src,extra:{requestToken:i,resolveToken:l}})),this.refreshRuntimeState()),l);if(!a){const h={url:t.clip.src};return this.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),l)}try{const h=o?o.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>a(t.clip)):a(t.clip);if(Ge(h)){const d=c();return h.then(u=>d!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:u?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:u.url,extra:{mimeType:u.mimeType,mediaKind:u.kind}})),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,u),d)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(u=>(this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:u})),O.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:u}),this.failSlot(e,t,"预览源解析失败"),null))}return h?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:h.url,extra:{mimeType:h.mimeType,mediaKind:h.kind}})),this.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),l)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)}catch(h){return this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:h})),O.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:h}),this.failSlot(e,t,"预览源解析失败"),null}}decorateSlotSourceUrl(e,t){return t}resolvePlayableSlotSource(e,t,i){const r=this.dependencies.resourceCacheManager,n=this.getReusableResolvedSlotSource(e,i);if(n)return this.emitRuntimeSourceDiagnostic(e,i.url,n,"source.runtime.reused","Reused existing runtime preview source"),n;if(e.pendingRuntimeSourceUrl===i.url&&e.pendingRuntimeSourcePromise)return this.emitRuntimeSourceDiagnostic(e,i.url,null,"source.runtime.pending-reused","Reused pending runtime preview source resolution"),e.pendingRuntimeSourcePromise;if(!r)return{stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null,sizeBytes:null};const a=()=>!this.isCurrentSourceTarget(e,t,i.url),o={url:i.url,mimeType:i.mimeType,kind:i.kind,sourceKey:this.buildPreviewSourceCacheKey(t.clip)},l=()=>({stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null,sizeBytes:null});try{const c=r.resolvePlayableUrl(o),h=d=>{if(!(d!=null&&d.url))return a()?null:l();const u={stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,d.url),objectUrl:d.objectUrl??null,sizeBytes:d.sizeBytes??null};return a()?(this.revokeResolvedObjectUrl(u),null):(this.emitRuntimeSourceDiagnostic(e,i.url,u,"source.runtime.resolved","Resolved runtime playable source",{cacheStatus:d.cacheStatus}),u)};if(Ge(c)){e.isResolvingSource=!0,e.isLoading=!0,e.phase="binding",this.refreshRuntimeState();const d=c.then(h).catch(()=>a()?null:l());return d.finally(()=>{e.pendingRuntimeSourcePromise===d&&(this.clearPendingRuntimeSource(e),this.refreshRuntimeState())}).catch(()=>{}),e.pendingRuntimeSourceUrl=i.url,e.pendingRuntimeSourcePromise=d,d}return h(c)}catch{return a()?null:l()}}emitRuntimeSourceDiagnostic(e,t,i,r,n,a={}){const o=(i==null?void 0:i.url)??t;this.emitDiagnostic("debug","resource",r,this.buildSlotTraceData(e,{message:n,desiredSourceUrl:o,actualSourceUrl:_e(e.element)||null,mediaState:ee(e.element),extra:{stableSourceUrl:t,runtimeSourceUrl:(i==null?void 0:i.url)??null,objectUrl:(i==null?void 0:i.objectUrl)??null,sourceState:Fe(e.element,o),...a}}))}getReusableResolvedSlotSource(e,t){if(!e.desiredSource||e.stableSourceUrl!==t.url)return null;const i=e.objectUrl??(e.desiredSource.startsWith("blob:")?e.desiredSource:null);return{stableSourceUrl:t.url,url:e.desiredSource,objectUrl:i,sizeBytes:null}}getReusableBoundSlotSource(e,t,i){const r=i??(e.entry?this.buildPreviewSourceCacheKey(e.entry.clip):null);if(!r)return null;const n=su({currentSourceKey:r,nextSourceKey:this.buildPreviewSourceCacheKey(t.clip),desiredSource:e.desiredSource,stableSourceUrl:e.stableSourceUrl,objectUrl:e.objectUrl});return n?{...n,sizeBytes:null}:null}slotNeedsRecovery(e,t){const i=ou({desiredSource:t,configuredSource:sr(e.element)||null,assignedSource:_e(e.element)||null,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,phase:e.phase,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,networkEmptyState:Tu,haveCurrentDataState:at});return this.emitDiagnostic(i.shouldWarn?"warn":"debug","recovery","slot.recovery-check",this.buildSlotTraceData(e,{message:i.needsRecovery?"Preview slot needs recovery":"Preview slot source is reusable",desiredSourceUrl:t,actualSourceUrl:i.actualSource,mediaState:ee(e.element),extra:{needsRecovery:i.needsRecovery,recoveryReason:i.recoveryReason,configuredSource:i.configuredSource,actualSource:i.actualSource,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,sourceState:Fe(e.element,t)}})),i.needsRecovery}recoverSlot(e,t,i,r,n){const a=i??(e.entry?{...hu({role:e.role,entry:e.entry,requestedPlayState:e.requestedPlayState,isActive:e.isActive,playbackRate:e.element.playbackRate||1,syncRequestId:this.activeSyncRequestId})}:null);if(!e.entry||!a||r!==void 0&&!this.isCurrentRequest(e,r,e.entry))return;const o=n??(e.desiredSource?{stableSourceUrl:e.stableSourceUrl??e.desiredSource,url:e.desiredSource,objectUrl:e.objectUrl,sizeBytes:null}:this.resolveDesiredSource(e,e.entry,e.applyToken));if(Ge(o))return o.then(l=>{l&&this.finishSlotRecovery(e,t,a,l,r)});o&&this.finishSlotRecovery(e,t,a,o,r)}finishSlotRecovery(e,t,i,r,n){if(!e.entry)return;const a=typeof r=="string"?{stableSourceUrl:e.stableSourceUrl??r,url:r,objectUrl:e.objectUrl}:r,o=a.url,l=du({entry:e.entry,desiredSource:o,reason:t,previousRecoveryKey:e.recoveryKey,previousRetryCount:e.retryCount,maxImmediateRecoveryRetries:bu,recoveryTimeBucketMs:ku,isBackgroundPreload:this.isBackgroundPreloadSlot(e)});if(l.status==="park"){this.parkPreloadSlot(e,l.message,l.parkReason);return}if(l.status==="fail"){this.failSlot(e,e.entry,l.message);return}e.recoveryKey=l.recoveryKey,e.retryCount=l.retryCount,Cu(e,i.playState),this.refreshRuntimeState(),this.emitDiagnostic(t==="reconcile"?"info":"warn","recovery","slot.recover",this.buildSlotTraceData(e,{message:"Recovering preview slot",desiredSourceUrl:o,mediaState:ee(e.element),extra:{reason:t,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState}})),e.retryCount>1&&O.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:o,mediaState:ee(e.element)});const c=_e(e.element),h=Fe(e.element,o),d=cu(c||null,t,e.retryCount);Ne(e.element),e.expectedEmptiedEvents=d?2:1,e.stableSourceUrl=a.stableSourceUrl,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),this.resetSlotMediaPendingProbe(e),this.rememberSlotObjectUrl(e,a.objectUrl),d&&(e.element.removeAttribute("src"),Ye(e.element)),e.element.setAttribute("src",o),Ye(e.element),this.emitDiagnostic("info","resource","source.assigned",this.buildSlotTraceData(e,{message:"Preview source assigned",desiredSourceUrl:o,actualSourceUrl:o,extra:{reason:t,hardReset:d,previousSourceState:h,nextSourceState:Fe(e.element,o),objectUrl:a.objectUrl,stableSourceUrl:a.stableSourceUrl}})),!(n!==void 0&&!this.isCurrentRequest(e,n,e.entry))&&this.applyResolvedSlotState(e,i)}getSlotKey(e){return tu(e)}isActiveCurrentSlot(e){return e.role==="current"&&e.isActive&&!!e.entry}isTrackedActiveCurrentVideoSlot(e){return this.isActiveCurrentSlot(e)&&e.kind==="video"}hasBlockingActiveCurrentSlot(e){for(const{current:t}of this.trackSlots.values()){if(e&&this.getSlotKey(t)===e||!this.isTrackedActiveCurrentVideoSlot(t))continue;const i=this.evaluateTrackedCurrentVideoSlot(t);if(!i.ready&&!i.failed)return!0}return!1}shouldDeferPreloadTarget(e,t,i){return t.role!=="preload"||!t.entry||!this.slotNeedsRecovery(e,i)?!1:this.hasBlockingActiveCurrentSlot()}shouldDeferPreloadRecovery(e){return e.role!=="preload"||e.isActive||!e.entry?!1:this.hasBlockingActiveCurrentSlot()}buildDeferredPreloadTarget(e){return iu(e,this.activeSyncRequestId)}deferPreloadTarget(e,t,i,r){const n=i.url;e.desiredSource=n,this.rememberSlotObjectUrl(e,i.objectUrl),e.element.getAttribute("src")&&e.element.getAttribute("src")!==n&&(Ne(e.element),e.element.removeAttribute("src"),Ye(e.element)),_e(e.element)||(e.hasReadyEventSinceSourceChange=!1),yu(e,!!_e(e.element)),this.deferredPreloadSlotKeys.add(this.getSlotKey(e)),this.emitDiagnostic("info","recovery","preload.recovery.deferred",this.buildSlotTraceData(e,{message:"Deferred preload recovery until active current media settles",desiredSourceUrl:n,extra:{reason:r,currentLoading:!0,requestedPlayState:t.playState}})),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState()}deferPreloadRecovery(e,t){this.deferredPreloadSlotKeys.add(this.getSlotKey(e)),this.emitDiagnostic("info","recovery","preload.recovery.deferred",this.buildSlotTraceData(e,{message:"Deferred preload recovery until active current media settles",extra:{reason:t,currentLoading:!0,requestedPlayState:e.requestedPlayState}})),this.scheduleDeferredPreloadFlush()}scheduleDeferredPreloadFlush(){this.deferredPreloadFlushScheduled||this.deferredPreloadSlotKeys.size===0||(this.deferredPreloadFlushScheduled=!0,queueMicrotask(()=>{this.deferredPreloadFlushScheduled=!1,this.flushDeferredPreloads()}))}flushDeferredPreloads(){if(this.deferredPreloadSlotKeys.size===0||this.hasBlockingActiveCurrentSlot())return;const e=Array.from(this.deferredPreloadSlotKeys);this.deferredPreloadSlotKeys.clear();for(const t of e){const i=ru(this.trackSlots,t);if(!i||i.role!=="preload"||!i.entry)continue;const r=this.buildDeferredPreloadTarget(i);if(r){if(this.emitDiagnostic("info","recovery","preload.recovery.resumed",this.buildSlotTraceData(i,{message:"Resumed deferred preload recovery",desiredSourceUrl:i.desiredSource,extra:{requestedPlayState:i.requestedPlayState}})),i.desiredSource&&this.slotNeedsRecovery(i,i.desiredSource)){this.recoverSlot(i,"reconcile",r);continue}this.resetSlotRecoveryTracking(i),this.applyResolvedSlotState(i,r)}}}applyResolvedSlotState(e,t){if(!t.entry)return;e.phase==="failed"&&!!e.errorMessage||(e.errorMessage=null),e.element.playbackRate=t.role==="current"?t.speed:1,t.role==="current"?this.syncCurrentSlot(e,t.entry,t.speed,t.playState):this.preparePreloadSlot(e,t.entry),mu(e),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState()}buildCurrentTargetForSlot(e){return e.entry?{role:e.role,entry:e.entry,playState:e.requestedPlayState,speed:e.isActive&&e.element.playbackRate||1,visible:e.isActive&&!!e.entry.hasVisual,zIndex:e.isActive?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null}isCurrentRequest(e,t,i){var r;return e.applyToken===t&&((r=e.entry)==null?void 0:r.clip.id)===i.clip.id}isCurrentSourceTarget(e,t,i){return!e.entry||e.entry.clip.id!==t.clip.id?!1:this.buildPreviewSourceCacheKey(e.entry.clip)===this.buildPreviewSourceCacheKey(t.clip)||e.stableSourceUrl===i||e.desiredSource===i}shouldIgnoreExpectedEmptied(e){return e.phase==="recovering"&&!e.loadStartedSinceRecover?!0:e.expectedEmptiedEvents<=0?!1:e.phase!=="recovering"&&!e.isLoading?(e.expectedEmptiedEvents=0,!1):(e.expectedEmptiedEvents-=1,!0)}shouldIgnoreExpectedAbort(e){return e.phase==="recovering"&&!e.loadStartedSinceRecover}shouldIgnoreClearedSlotRecoverableEvent(e){return!e.entry&&e.phase==="idle"}shouldSkipImmediatePreloadRecovery(e){return this.isBackgroundPreloadSlot(e)?!e.loadStartedSinceRecover&&e.recoverableEventCount<2:!1}isBackgroundPreloadSlot(e){return e.role==="preload"&&!e.isActive&&!!e.entry}parkPreloadSlot(e,t,i){Ne(e.element),this.releaseSlotObjectUrl(e),e.element.removeAttribute("src"),Ye(e.element),e.hasReadyEventSinceSourceChange=!1,gu(e),this.emitDiagnostic("warn","recovery","preload.recovery.parked",this.buildSlotTraceData(e,{message:"Background preload parked until next steady sync",mediaState:ee(e.element),extra:{reason:i,errorMessage:t}})),this.refreshVisualLayout(),this.refreshRuntimeState()}failSlot(e,t,i){if(this.isBackgroundPreloadSlot(e)){this.parkPreloadSlot(e,i,"failed");return}Ms(e,i),this.emitDiagnostic("error","recovery","slot.failed",this.buildSlotTraceData(e,{message:"Preview slot failed",mediaState:ee(e.element),extra:{errorMessage:i}})),O.error("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,mediaState:ee(e.element)}),this.refreshVisualLayout(),this.refreshRuntimeState()}configureAudioRouting(e,t){const i=Math.max(0,Math.min(1,t.clip.volume??1)),r=t.muted?0:i;if(!t.hasAudio){e.element.muted=!0,e.element.volume=0;return}const n=this.getAudioContext();if(!n||e.audioRoutingFailed){e.element.muted=t.muted,e.element.volume=r;return}if(!e.sourceNode||!e.gainNode)try{e.sourceNode=n.createMediaElementSource(e.element),e.gainNode=n.createGain(),e.sourceNode.connect(e.gainNode),e.gainNode.connect(this.getMasterGainNode(n))}catch{e.audioRoutingFailed=!0,e.element.muted=t.muted,e.element.volume=r;return}e.element.muted=!1,e.element.volume=1,e.gainNode.gain.value=r}syncCurrentSlot(e,t,i,r){e.isActive=!0,e.entry=t,e.element.playbackRate=i;const n=t.mediaTime/1e3,a=Math.max(r==="playing"?Au:.1,i*.15),o=r==="playing"&&!e.element.ended,l=this.doesSlotSourceMatchDesired(e,e.desiredSource),c=typeof e.element.readyState=="number"?e.element.readyState:0;if(this.updateSlotPlaybackProgressState(e,{shouldBePlaying:o,sourceMatched:l,readyState:c,speed:i}),!e.playbackProgressStalled&&Math.abs(e.element.currentTime-n)>a&&(this.emitDiagnostic("debug","playback","media.current-slot.seek",this.buildSlotTraceData(e,{message:"Current slot seek applied",mediaState:ee(e.element),extra:{playState:r,speed:i,fromSeconds:Number(e.element.currentTime.toFixed(3)),toSeconds:Number(n.toFixed(3)),deltaSeconds:Number(Math.abs(e.element.currentTime-n).toFixed(3)),thresholdSeconds:Number(a.toFixed(3))}})),e.isSeeking=!0,Os(e.element,n)),r==="playing"){this.resumeAudioContext();const d=Fe(e.element,e.desiredSource);e.element.paused&&(this.emitDiagnostic(d.hasSrcAttribute?"debug":"warn","playback","media.play.requested",this.buildSlotTraceData(e,{message:d.hasSrcAttribute?"Media play requested":"Media play requested without configured src attribute",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:d}})),Rr(e.element))}else this.emitDiagnostic("debug","playback","media.pause.requested",this.buildSlotTraceData(e,{message:"Media pause requested",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:Fe(e.element,e.desiredSource)}})),Ne(e.element);this.setSlotVisible(e,t.hasVisual,1e3-t.trackOrder)}resetSlotPlaybackProgressProbe(e){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN,e.playbackProgressStalled=!1}updateSlotPlaybackProgressState(e,t){const i=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN;if(!(t.shouldBePlaying&&e.role==="current"&&e.isActive&&t.sourceMatched&&t.readyState>=at&&!e.element.paused&&!e.element.ended&&!e.isSeeking&&Number.isFinite(i))){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN;return}const n=Yi(),a=e.lastPlaybackProgressMediaTimeSeconds,o=e.lastPlaybackProgressCheckAtMs;if(o<0||!Number.isFinite(a)){e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}const l=i-a;if(l>Ds||l<-Ds){e.playbackProgressStalled&&this.emitDiagnostic("info","playback","media.progress.recovered",this.buildSlotTraceData(e,{message:"Media playback progress recovered",mediaState:ee(e.element),extra:{previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3)),advancedSeconds:Number(l.toFixed(3))}})),e.playbackProgressStalled=!1,e.hasBufferingSignalSinceSourceChange||(e.isBuffering=!1),e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}n-o<_u||(e.playbackProgressStalled||this.emitDiagnostic("warn","playback","media.progress.stalled",this.buildSlotTraceData(e,{message:"Media playback progress stalled without waiting event",mediaState:ee(e.element),extra:{stalledForMs:n-o,speed:t.speed,previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3))}})),e.playbackProgressStalled=!0,e.isBuffering=!0)}maybeResumeRequestedPlayback(e,t){if(e.role!=="current"||!e.isActive||!e.entry||e.requestedPlayState!=="playing"||e.element.paused!==!0||this.playbackGroupSuspended)return;const i=Fe(e.element,e.desiredSource);if(!i.hasSrcAttribute)return;const r=Yi();t==="runtime-check"&&(!this.canRuntimeCheckRetryBufferedPlayback(e)||e.lastPlaybackResumeAttemptAtMs>=0&&r-e.lastPlaybackResumeAttemptAtMs<xu)||(e.lastPlaybackResumeAttemptAtMs=r,this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.play.retried",this.buildSlotTraceData(e,{message:"Retried media play after ready event",mediaState:ee(e.element),extra:{reason:t,playState:e.requestedPlayState,speed:e.element.playbackRate||1,sourceState:i}})),Rr(e.element))}canRuntimeCheckRetryBufferedPlayback(e){return e.hasBufferingSignalSinceSourceChange?(typeof e.element.readyState=="number"?e.element.readyState:0)>=Ir&&!e.isSeeking&&!e.playbackProgressStalled:!0}shouldClearRecoveredBufferingSignal(e,t){return t.shouldBePlaying&&e.hasBufferingSignalSinceSourceChange&&e.lastPlaybackResumeAttemptAtMs>=0&&!e.playbackProgressStalled&&!e.isSeeking&&t.readyState>=Ir&&!t.pausedWhilePlaying}preparePreloadSlot(e,t){vu(e),e.entry=t,e.element.playbackRate=1,e.hasReadyEventSinceSourceChange=!1,this.emitDiagnostic("debug","playback","media.preload-slot.seek",this.buildSlotTraceData(e,{message:"Preload slot primed",mediaState:ee(e.element),extra:{toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3))}})),Os(e.element,t.clip.startTimeAtSource/1e3),Ne(e.element),this.setSlotVisible(e,!1,0)}setSlotVisible(e,t,i){if(e.kind!=="video"||!e.wrapper){e.element.style.display="none";return}e.wrapper.style.display=t?"block":"none",e.wrapper.style.zIndex=String(i),e.wrapper.style.pointerEvents="none",e.element.style.display=t?"block":"none",e.element.style.zIndex=String(i),this.syncSlotFailureVisualState(e)}getAudioContext(){if(this.audioContext)return this.audioContext;const e=this.dependencies.createAudioContext;if(e)return this.audioContext=e(),this.audioContext;if(typeof window>"u")return null;const t=window.AudioContext||window.webkitAudioContext;return t?(this.audioContext=new t,this.audioContext):null}getMasterGainNode(e){if(this.masterGainNode)return this.masterGainNode;const t=e.createGain();return t.gain.value=1,t.connect(e.destination),this.masterGainNode=t,t}resumeAudioContext(){var e,t,i,r;!this.audioContext||this.audioContext.state!=="suspended"||(r=(t=(e=this.audioContext).resume)==null?void 0:(i=t.call(e)).catch)==null||r.call(i,()=>{})}updateFrameLayout(){if(!this.container||!this.frameElement)return;const{width:e,height:t}=this.getAspectRatio(),i=this.container.clientWidth,r=this.container.clientHeight;if(i<=0||r<=0||e<=0||t<=0)return;const n=e/t,a=i/r;let o=i,l=r;n>a?l=i/n:o=r*n,this.frameElement.style.width=`${o}px`,this.frameElement.style.height=`${l}px`,this.frameElement.style.left=`${(i-o)/2}px`,this.frameElement.style.top=`${(r-l)/2}px`,this.refreshVisualLayout()}maybeResolveAutoAspectRatio(e){if(!_t(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=Oi(e,"sys_width"),i=Oi(e,"sys_height");if(t&&i){this.handleResolvedAutoAspectRatio(t,i);return}if(this.aspectRatioProbeSrc===e.clip.id)return;const r=++this.aspectRatioProbeResolveToken;(async()=>{const a=await this.resolveAspectRatioProbeSource(e,r);if(!a||r!==this.aspectRatioProbeResolveToken)return;const o=this.getAspectRatioProbe();this.aspectRatioProbeSrc=e.clip.id,this.emitDiagnostic("info","resource","aspect-ratio.probe.start",{message:"Aspect ratio probe started",clipId:e.clip.id,sourceUrl:a}),this.refreshRuntimeState(),o.crossOrigin="anonymous",o.preload="metadata",o.muted=!0,o.src=a,Ye(o)})().catch(()=>{})}async resolveAspectRatioProbeSource(e,t){const i=this.dependencies.previewSourceResolver,r=this.dependencies.sourceMediaRegistry;if(!i)return e.clip.src;const n=r?r.getPreviewSource(this.buildPreviewSourceCacheKey(e.clip),()=>i(e.clip)):i(e.clip);if(!Ge(n))return(n==null?void 0:n.url)??null;const a=await n;return t!==this.aspectRatioProbeResolveToken?null:(a==null?void 0:a.url)??null}buildPreviewSourceCacheKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src}getAspectRatioProbe(){var r,n;if(this.aspectRatioProbe)return this.aspectRatioProbe;const e=((n=(r=this.dependencies).createAspectRatioProbe)==null?void 0:n.call(r))||document.createElement("video");Nr(e);const t=()=>{this.emitDiagnostic("info","resource","aspect-ratio.probe.loadedmetadata",{message:"Aspect ratio probe resolved",clipId:this.aspectRatioProbeSrc,extra:{videoWidth:e.videoWidth,videoHeight:e.videoHeight}}),this.refreshRuntimeState(),e.videoWidth>0&&e.videoHeight>0&&this.handleResolvedAutoAspectRatio(e.videoWidth,e.videoHeight)},i=()=>{this.emitDiagnostic("warn","resource","aspect-ratio.probe.error",{message:"Aspect ratio probe failed",clipId:this.aspectRatioProbeSrc,actualSourceUrl:e.currentSrc||e.src||null}),this.refreshRuntimeState()};return e.addEventListener("loadedmetadata",t),e.addEventListener("error",i),this.aspectRatioProbe=e,e}tryResolveAutoAspectRatioFromSlot(e){if(!_t(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const t=e.element;t.videoWidth>0&&t.videoHeight>0&&this.handleResolvedAutoAspectRatio(t.videoWidth,t.videoHeight)}handleResolvedAutoAspectRatio(e,t){var i,r;e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),_t(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var m,S,T,v,C,k,P,x;const e=[];let t=null,i=!1,r=0,n=0,a=!1,o=!1,l=!1,c=!1;for(const{current:D,preload:w}of this.trackSlots.values())for(const A of[D,w]){const B=this.isTrackedActiveCurrentVideoSlot(A),z=B?this.evaluateTrackedCurrentVideoSlot(A):null,F=_e(A.element)||null;e.push({trackId:A.trackId,role:A.role,kind:A.kind,clipId:((m=A.entry)==null?void 0:m.clip.id)??null,desiredSource:A.desiredSource,actualSource:F,phase:A.phase,retryCount:A.retryCount,errorMessage:A.errorMessage}),A.phase!=="idle"&&(i=!0),B&&(r+=1,z!=null&&z.failed&&(n+=1,a=!0,t||(t=A.errorMessage||"资源加载异常,请刷新重试")),z!=null&&z.resolving&&(o=!0),z!=null&&z.seeking&&(l=!0),z!=null&&z.mediaUnready&&(c=!0))}const h=this.buildPreviewLoadingState({trackedActiveCurrentVideoSlotCount:r,failedTrackedCurrentVideoSlotCount:n,hasFailedTrackedVideoSlot:a,hasResolvingTrackedVideoSlot:o,hasSeekingTrackedVideoSlot:l,hasMediaUnreadyTrackedVideoSlot:c});this.syncActivePlaybackGroupSuspension(h,r);let d="idle";h.status==="failed"?d="failed":h.status==="loading"&&h.reason==="syncing"?d="awaiting-sync":h.status==="loading"?d="awaiting-media":(r>0&&h.status==="ready"||i)&&(d="ready"),h.status!=="failed"&&(t=null);const u={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:d,loading:h,clock:this.buildPreviewClockState(h),errorMessage:t,slots:e},p=this.lastRuntimeState,f=JSON.stringify(u);f!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=f,this.lastRuntimeState=u,(p.phase!==u.phase||p.loading.status!==u.loading.status||p.loading.reason!==u.loading.reason||p.loading.isLoading!==u.loading.isLoading||p.errorMessage!==u.errorMessage)&&this.emitDiagnostic(u.phase==="failed"?"error":"info","runtime","runtime.state",{message:"Preview runtime state updated",syncRequestId:u.syncRequestId??null,runtimeState:{runtimePhase:u.phase,loadingStatus:u.loading.status,loadingReason:u.loading.reason,isLoading:u.loading.isLoading,clockStatus:((S=u.clock)==null?void 0:S.status)??"unavailable",clockReason:((T=u.clock)==null?void 0:T.reason)??null,clockTimelineTime:((v=u.clock)==null?void 0:v.timelineTime)??null},extra:{previousPhase:p.phase,phase:u.phase,errorMessage:u.errorMessage,loading:u.loading,slots:u.slots.map(D=>({trackId:D.trackId,role:D.role,clipId:D.clipId,phase:D.phase,retryCount:D.retryCount,desiredSource:D.desiredSource,actualSource:D.actualSource}))}}),(k=(C=this.callbacks).onRuntimeStateChange)==null||k.call(C,u)),(h.status==="ready"||h.status==="failed"||h.status==="idle")&&u.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==u.syncRequestId&&(this.lastSettledSyncRequestId=u.syncRequestId,(x=(P=this.callbacks).onSyncProcessed)==null||x.call(P,u.syncRequestId)),h.status!=="loading"&&this.deferredPreloadSlotKeys.size>0&&this.scheduleDeferredPreloadFlush(),this.syncLoadingProbe(h),this.syncClockProbe(u.clock),this.refreshPendingOverlay()}buildPreviewClockState(e){const t=this.getPreviewClockSourceSlot();if(!(t!=null&&t.entry))return this.buildPreviewClockStateFromSlot(null,"unavailable","no-video-clock");const i=this.doesSlotSourceMatchDesired(t,t.desiredSource),r=this.getSlotMediaTimeMs(t),n=this.getSlotTimelineTime(t,r),a=t.requestedPlayState==="playing"&&!t.element.ended;return e.status==="failed"||t.phase==="failed"?this.buildPreviewClockStateFromSlot(t,"failed","failed",n,r):a?!i||t.isResolvingSource||t.phase==="binding"?this.buildPreviewClockStateFromSlot(t,"priming","resolving-source",n,r):t.isSeeking||e.reason==="seeking"?this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):t.isBuffering||t.playbackProgressStalled?this.buildPreviewClockStateFromSlot(t,"blocked","media-stalled",n,r):this.isPreviewClockSlotAlignedToPendingTarget(t,n)?e.status==="loading"?this.buildPreviewClockStateFromSlot(t,"blocked",this.resolveClockBlockedReason(e.reason),n,r):t.element.paused?this.buildPreviewClockStateFromSlot(t,"blocked","media-paused",n,r):n===null||r===null?this.buildPreviewClockStateFromSlot(t,"priming","media-pending",n,r):(this.pendingClockAlignmentTargetTime=null,this.buildPreviewClockStateFromSlot(t,"running",null,n,r)):this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):this.buildPreviewClockStateFromSlot(t,"unavailable",null,n,r)}buildPreviewClockStateFromSlot(e,t,i,r=null,n=null){var a;return{status:t,timelineTime:r,mediaTime:n,clipId:((a=e==null?void 0:e.entry)==null?void 0:a.clip.id)??null,trackId:(e==null?void 0:e.trackId)??null,reason:i}}resolveClockBlockedReason(e){return e==="syncing"||e==="resolving-source"||e==="seeking"||e==="media-pending"||e==="failed"?e:"media-pending"}getPreviewClockSourceSlot(){var t,i;const e=[];for(const{current:r}of this.trackSlots.values())this.isTrackedActiveCurrentVideoSlot(r)&&((t=r.entry)!=null&&t.hasVisual)&&e.push(this.buildPreviewClockSourceCandidate(r));return e.length===0?(this.pendingClockAlignmentTargetTime=null,null):(e.sort((r,n)=>this.comparePreviewClockSourceCandidates(r,n)),((i=e[0])==null?void 0:i.slot)??null)}buildPreviewClockSourceCandidate(e){const t=this.getSlotMediaTimeMs(e),i=this.getSlotTimelineTime(e,t),r=this.doesSlotSourceMatchDesired(e,e.desiredSource),n=typeof e.element.readyState=="number"?e.element.readyState:0,a=this.pendingClockAlignmentTargetTime===null||i===null?Number.POSITIVE_INFINITY:Math.abs(i-this.pendingClockAlignmentTargetTime),o=e.requestedPlayState==="playing"&&!e.element.ended,l=n>=at||e.hasReadyEventSinceSourceChange,c=!!e.entry&&r&&l&&!e.isResolvingSource&&e.phase!=="binding"&&e.phase!=="failed"&&!e.isSeeking&&!e.isBuffering&&!e.playbackProgressStalled&&(!o||!e.element.paused)&&t!==null&&i!==null;return{slot:e,timelineTime:i,targetDistance:a,sourceMatched:r,readyState:n,usable:c}}comparePreviewClockSourceCandidates(e,t){var n,a;const i=this.isPreviewClockCandidateAlignedToTarget(e),r=this.isPreviewClockCandidateAlignedToTarget(t);return i!==r?i?-1:1:this.pendingClockAlignmentTargetTime!==null&&e.targetDistance!==t.targetDistance?e.targetDistance-t.targetDistance:e.usable!==t.usable?e.usable?-1:1:e.sourceMatched!==t.sourceMatched?e.sourceMatched?-1:1:e.readyState!==t.readyState?t.readyState-e.readyState:(((n=e.slot.entry)==null?void 0:n.trackOrder)??0)-(((a=t.slot.entry)==null?void 0:a.trackOrder)??0)}isPreviewClockCandidateAlignedToTarget(e){return this.pendingClockAlignmentTargetTime!==null&&e.usable&&e.targetDistance<=this.getPreviewClockTargetAlignmentThresholdMs(e.slot)}getPreviewClockTargetAlignmentThresholdMs(e){return Math.max(Iu,this.getSlotSeekThresholdSeconds(e)*1e3)}isPreviewClockSlotAlignedToPendingTarget(e,t){return this.pendingClockAlignmentTargetTime===null||t===null?!0:Math.abs(t-this.pendingClockAlignmentTargetTime)<=this.getPreviewClockTargetAlignmentThresholdMs(e)}updatePendingClockAlignmentTarget(e){if(!e.activeClips.some(i=>i.trackType==="video"&&i.hasVisual)){this.pendingClockAlignmentTargetTime=null;return}(e.interactionMode==="seek"||e.interactionMode==="scrub")&&(this.pendingClockAlignmentTargetTime=e.currentTime)}syncActivePlaybackGroupSuspension(e,t){var n;const i=((n=this.pendingState)==null?void 0:n.mode)==="seek";if(t>1&&!i&&(e.status==="loading"||e.status==="failed")){this.playbackGroupSuspended=!0;for(const{current:a}of this.trackSlots.values())!this.isActiveCurrentSlot(a)||a.requestedPlayState!=="playing"||a.isBuffering||a.playbackProgressStalled||a.isSeeking||a.isResolvingSource||a.phase==="binding"||a.phase==="recovering"||a.element.paused||(this.emitDiagnostic("debug","playback","media.group-pause.requested",this.buildSlotTraceData(a,{message:"Paused active media while preview playback group is blocked",mediaState:ee(a.element),extra:{loadingStatus:e.status,loadingReason:e.reason}})),Ne(a.element));return}if(this.playbackGroupSuspended){this.playbackGroupSuspended=!1;for(const{current:a}of this.trackSlots.values()){if(!this.isActiveCurrentSlot(a)||a.requestedPlayState!=="playing"||!a.element.paused||a.element.ended)continue;const o=Fe(a.element,a.desiredSource);o.hasSrcAttribute&&(this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.group-play.requested",this.buildSlotTraceData(a,{message:"Resumed active media after preview playback group became ready",mediaState:ee(a.element),extra:{loadingStatus:e.status,loadingReason:e.reason,sourceState:o}})),Rr(a.element))}}}getSlotMediaTimeMs(e){return Number.isFinite(e.element.currentTime)?Math.max(0,e.element.currentTime*1e3):null}getSlotTimelineTime(e,t=this.getSlotMediaTimeMs(e)){if(!e.entry||t===null)return null;const i=e.entry.clip,r=i.startTime+(t-i.startTimeAtSource);return Math.max(i.startTime,Math.min(i.endTime,r))}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.lastRuntimeState})}buildPreviewLoadingState(e){return e.trackedActiveCurrentVideoSlotCount<=0?{status:"idle",isLoading:!1,reason:null}:e.hasFailedTrackedVideoSlot&&e.failedTrackedCurrentVideoSlotCount>=e.trackedActiveCurrentVideoSlotCount?{status:"failed",isLoading:!1,reason:"failed"}:this.activeSyncRequestId!==void 0&&this.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:e.hasResolvingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"resolving-source"}:e.hasSeekingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"seeking"}:e.hasMediaUnreadyTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}evaluateTrackedCurrentVideoSlot(e){if(!this.isTrackedActiveCurrentVideoSlot(e)||!e.entry)return{failed:!1,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1};const t=e.desiredSource,i=this.doesSlotSourceMatchDesired(e,t),r=typeof e.element.readyState=="number"?e.element.readyState:0,n=e.entry.mediaTime/1e3,a=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN,o=this.getSlotSeekThresholdSeconds(e),l=Number.isFinite(a)&&Math.abs(a-n)<=o,c=e.requestedPlayState==="playing"&&!e.element.ended,h=r>=at;let d=c&&e.element.paused&&!this.playbackGroupSuspended;d&&(this.maybeResumeRequestedPlayback(e,"runtime-check"),d=c&&e.element.paused&&!this.playbackGroupSuspended),this.shouldClearRecoveredBufferingSignal(e,{shouldBePlaying:c,readyState:r,pausedWhilePlaying:d})&&(e.hasBufferingSignalSinceSourceChange=!1,e.isBuffering=!1),this.playbackGroupSuspended&&e.playbackProgressStalled&&!e.hasBufferingSignalSinceSourceChange&&r>=Ir&&(e.playbackProgressStalled=!1,e.isBuffering=!1),this.updateSlotPlaybackProgressState(e,{shouldBePlaying:c,sourceMatched:i,readyState:r,speed:e.element.playbackRate||1}),c&&e.isBuffering&&!e.hasBufferingSignalSinceSourceChange&&!e.playbackProgressStalled&&h&&!d&&(e.isBuffering=!1);const u=e.hasReadyEventSinceSourceChange&&!e.isBuffering,f=!(c&&(e.isBuffering||e.playbackProgressStalled))&&!d&&(h||!c&&e.hasReadyEventSinceSourceChange||c&&u),m=Su(e,{hasDesiredSource:!!t,sourceMatched:i,withinSeekThreshold:l,readyState:f?at:Math.min(r,at-1),haveCurrentDataState:at});return this.failStalledMediaPendingSlotIfNeeded(e,m,i)?{failed:!0,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1}:(m.ready?(this.resetSlotMediaPendingProbe(e),this.tryResolveAutoAspectRatioFromSlot(e)):m.mediaUnready||this.resetSlotMediaPendingProbe(e),m)}failStalledMediaPendingSlotIfNeeded(e,t,i){if(!t.mediaUnready||t.failed||t.resolving||t.seeking||!e.entry||e.role!=="current"||!e.isActive||!e.desiredSource||!i)return this.resetSlotMediaPendingProbe(e),!1;const r=`${e.entry.clip.id}:${e.desiredSource}`,n=Yi();if(e.mediaPendingFailureKey!==r)return e.mediaPendingFailureKey=r,e.mediaPendingSinceMs=n,!1;if(e.mediaPendingSinceMs<0||n-e.mediaPendingSinceMs<Ls)return!1;const a=n-e.mediaPendingSinceMs;return Ms(e,Wt),this.resetSlotMediaPendingProbe(e),this.emitDiagnostic("error","recovery","slot.failed",this.buildSlotTraceData(e,{message:"Preview slot failed after media pending timeout",mediaState:ee(e.element),extra:{errorMessage:Wt,pendingForMs:a,timeoutMs:Ls}})),O.error("TimelinePreviewSession","preview slot failed after media pending timeout",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,errorMessage:Wt,mediaState:ee(e.element)}),this.refreshVisualLayout(),!0}resetSlotMediaPendingProbe(e){e.mediaPendingSinceMs=-1,e.mediaPendingFailureKey=null}doesSlotSourceMatchDesired(e,t){return au(sr(e.element)||null,_e(e.element)||null,t)}getSlotSeekThresholdSeconds(e){return lu(e.role,e.element.playbackRate||1)}finalizeSourceResolutionResult(e,t,i){return i===null?(e.isResolvingSource=!1,t):Ge(t)?t.finally(()=>{e.resolveToken===i&&(e.isResolvingSource=!1,this.refreshRuntimeState())}):(e.resolveToken===i&&(e.isResolvingSource=!1),t)}syncLoadingProbe(e){if(e.status!=="loading"){this.clearLoadingProbe();return}this.loadingProbeTimeoutId||(this.loadingProbeTimeoutId=setTimeout(()=>{this.loadingProbeTimeoutId=null,this.refreshRuntimeState()},wu))}syncClockProbe(e){if(!((e==null?void 0:e.status)==="running"||(e==null?void 0:e.status)==="blocked"||(e==null?void 0:e.status)==="priming")){this.clearClockProbe();return}this.clockProbeTimeoutId||(this.clockProbeTimeoutId=setTimeout(()=>{this.clockProbeTimeoutId=null,this.refreshRuntimeState()},Pu))}clearLoadingProbe(){this.loadingProbeTimeoutId&&(clearTimeout(this.loadingProbeTimeoutId),this.loadingProbeTimeoutId=null)}clearClockProbe(){this.clockProbeTimeoutId&&(clearTimeout(this.clockProbeTimeoutId),this.clockProbeTimeoutId=null)}handlePreviewTransformChange(e,t){var i;if(!t){((i=this.transientVisualTransform)==null?void 0:i.clipId)===e&&(this.transientVisualTransform=null,this.refreshVisualLayout());return}this.transientVisualTransform={clipId:e,transform:t},this.refreshVisualLayout()}refreshVisualLayout(){for(const{current:e,preload:t}of this.trackSlots.values())this.refreshSlotVisualLayout(e),this.refreshSlotVisualLayout(t);this.refreshTextPreviewLayout(),this.transformOverlay.sync(this.buildSelectedOverlayState())}syncTextPreviewEntries(e){this.ensureTextPreviewFontReady();const t=e.filter(r=>!r.muted&&r.hasVisual).sort((r,n)=>r.trackOrder-n.trackOrder),i=new Set(t.map(r=>r.clip.id));for(const[r]of this.textPreviewEntries)i.has(r)||this.removeTextPreviewEntry(r);t.forEach(r=>{var c;const n=this.textPreviewEntries.get(r.clip.id);if(n){n.entry=r,this.applyTextPreviewEntry(n);return}const a=document.createElement("div");a.className="timeline-preview-text-entry",a.style.position="absolute",a.style.left="0",a.style.top="0",a.style.transformOrigin="center center",a.style.whiteSpace="pre",a.style.wordBreak="normal",a.style.overflowWrap="normal",a.style.pointerEvents="none",a.style.userSelect="none",a.style.boxSizing="border-box",a.style.border="1px solid transparent";const o=this.createTextPreviewPointerDownHandler(r.clip.id);a.addEventListener("pointerdown",o),(c=this.textOverlayRoot)==null||c.appendChild(a);const l={entry:r,element:a,handlePointerDown:o};this.textPreviewEntries.set(r.clip.id,l),this.applyTextPreviewEntry(l)}),this.refreshTextPreviewInteractionState()}clearTextPreviewEntries(){for(const e of Array.from(this.textPreviewEntries.keys()))this.removeTextPreviewEntry(e)}removeTextPreviewEntry(e){var i;const t=this.textPreviewEntries.get(e);t&&(((i=this.textPreviewDragState)==null?void 0:i.clipId)===e&&this.finishTextPreviewDrag(!1),t.element.removeEventListener("pointerdown",t.handlePointerDown),t.element.remove(),this.textPreviewEntries.delete(e))}applyTextPreviewEntry(e){const t=De(e.entry.clip.textStyle),i=e.entry.clip.textContent||e.entry.clip.name||"";e.element.textContent=i,e.element.style.color=t.color,e.element.style.fontFamily=this.getTextPreviewFontFamily(),e.element.style.fontSize=`${t.fontSize}px`,e.element.style.textShadow=Eu(t.strokeWidth,t.strokeColor),e.element.style.padding=`0 ${t.paddingX}px`,e.element.style.textAlign="left",e.element.style.zIndex=String(2e3-e.entry.trackOrder)}refreshTextPreviewLayout(){var i;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return;const t=this.getTextPreviewBaselineMetrics(e);for(const r of this.textPreviewEntries.values()){const n=this.getEffectiveVisualTransform(r.entry),a=r.entry.clip.id,o=De(r.entry.clip.textStyle).rotation,l=((i=this.transientRotation)==null?void 0:i.clipId)===a?this.transientRotation.rotation:o;r.element.style.left=`${e.width*n.x}px`,r.element.style.top=`${e.height*n.y}px`,r.element.style.transform=["translate(-50%, -50%)",`scale(${t.scale*n.scale})`,`rotate(${l}deg)`].join(" ")}}refreshTextPreviewEntries(){for(const e of this.textPreviewEntries.values())this.applyTextPreviewEntry(e);this.refreshTextPreviewLayout(),this.refreshTextPreviewInteractionState()}createTextPreviewPointerDownHandler(e){return t=>{var a,o,l,c;const i=t;if((i.button??0)!==0)return;if((a=i.preventDefault)==null||a.call(i),(o=i.stopPropagation)==null||o.call(i),this.requestPauseIfPlaying(),this.primarySelectedClipId!==e){(c=(l=this.callbacks).onPreviewClipSelect)==null||c.call(l,e);return}this.textPreviewDragState&&this.finishTextPreviewDrag(!1);const r=this.textPreviewEntries.get(e);if(!r)return;const n=this.getEffectiveVisualTransform(r.entry);this.textPreviewDragState={clipId:e,pointerStart:this.toFrameLocalPoint(i),startTransform:n,nextTransform:n,changed:!1},this.bindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}}bindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.addEventListener("pointermove",this.boundTextPreviewPointerMove),e.addEventListener("pointerup",this.boundTextPreviewPointerUp),e.addEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.addEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}unbindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.removeEventListener("pointermove",this.boundTextPreviewPointerMove),e.removeEventListener("pointerup",this.boundTextPreviewPointerUp),e.removeEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.removeEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}handleTextPreviewPointerMove(e){var o;const t=this.textPreviewDragState;if(!t)return;if(!this.textPreviewEntries.get(t.clipId)){this.finishTextPreviewDrag(!1);return}const r=e;(o=r.preventDefault)==null||o.call(r);const n=this.toFrameLocalPoint(r),a=go(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=a,t.changed=!wn(t.startTransform,a),this.handlePreviewTransformChange(t.clipId,a),this.refreshTextPreviewInteractionState()}finishTextPreviewDrag(e){var i,r;const t=this.textPreviewDragState;if(!t){this.unbindTextPreviewDocumentListeners();return}e&&t.changed&&((r=(i=this.callbacks).onVisualTransformCommit)==null||r.call(i,t.clipId,t.nextTransform)),this.handlePreviewTransformChange(t.clipId,null),this.textPreviewDragState=null,this.unbindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}refreshTextPreviewInteractionState(){var e;for(const t of this.textPreviewEntries.values()){const i=t.entry.clip.id===this.primarySelectedClipId,r=t.entry.clip.id===((e=this.textPreviewDragState)==null?void 0:e.clipId);t.element.style.pointerEvents="auto",t.element.style.cursor=i?r?"grabbing":"grab":"pointer",t.element.style.border=i?`1px solid ${ot.border}`:"1px solid transparent"}}getTextPreviewFontConfig(){const e=this.dependencies.textPreviewFont;return!(e!=null&&e.fontName)||!e.fontSourceUrl?null:e}getTextPreviewFontFamily(){const e=this.getTextPreviewFontConfig();return!e||this.textPreviewFontLoadState==="failed"?Bs:`${Er(e.fontName)}, ${Bs}`}ensureTextPreviewFontReady(){const e=this.getTextPreviewFontConfig();if(!e||!this.rootElement||typeof document>"u")return;const t=`${e.fontName}::${e.fontSourceUrl}`;if(this.textPreviewFontSignature!==t){this.resetTextPreviewFontState();const n=document.createElement("style");n.textContent=["@font-face {",`font-family: ${Er(e.fontName)};`,`src: url("${mo(e.fontSourceUrl)}");`,"font-display: swap;","}"].join(""),this.rootElement.appendChild(n),this.textPreviewFontStyleElement=n,this.textPreviewFontSignature=t,this.textPreviewFontLoadState="idle"}const i=document.fonts;if(typeof(i==null?void 0:i.load)!="function"||this.textPreviewFontLoadState==="loading"||this.textPreviewFontLoadState==="loaded")return;const r=++this.textPreviewFontLoadToken;this.textPreviewFontLoadState="loading",Promise.resolve(i.load(`1em ${Er(e.fontName)}`)).then(()=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="loaded",this.refreshTextPreviewEntries())}).catch(n=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="failed",O.warn("TimelinePreviewSession","Failed to load text preview font",{fontName:e.fontName,fontSourceUrl:e.fontSourceUrl,error:n}),this.refreshTextPreviewEntries())})}resetTextPreviewFontState(){var e;this.textPreviewFontLoadToken+=1,this.textPreviewFontLoadState="idle",this.textPreviewFontSignature=null,(e=this.textPreviewFontStyleElement)==null||e.remove(),this.textPreviewFontStyleElement=null}refreshSlotVisualLayout(e){if(e.kind!=="video"||!e.wrapper||!e.entry||!this.frameElement)return;const t=this.getFrameSize();if(t.width<=0||t.height<=0)return;const i=this.getMediaSize(e,e.entry,t),r=this.getEffectiveVisualTransform(e.entry),n=Es(t,i,r);e.wrapper.style.left=`${n.left}px`,e.wrapper.style.top=`${n.top}px`,e.wrapper.style.width=`${n.width}px`,e.wrapper.style.height=`${n.height}px`,this.syncSlotFailureVisualState(e)}syncSlotFailureVisualState(e){if(e.kind!=="video"||!e.wrapper||!e.failureOverlay||!e.failureLabel)return;const t=e.phase==="failed"&&!!e.entry;e.wrapper.style.background=t?_.mediaClipFailedBackground:_.black,e.failureOverlay.style.display=t?"flex":"none",e.failureLabel.textContent=Wt,e.element.style.visibility=t?"hidden":"visible"}buildSelectedOverlayState(){var t,i;if(!this.primarySelectedClipId)return null;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return null;for(const{current:r}of this.trackSlots.values()){if(r.kind!=="video"||!r.isActive||!r.entry||r.entry.clip.id!==this.primarySelectedClipId)continue;const n=this.getMediaSize(r,r.entry,e),a=this.getEffectiveVisualTransform(r.entry);return{clipId:r.entry.clip.id,transform:a,frameSize:e,baseRect:po(e,n),displayRect:Es(e,n,a),clipType:"video"}}if(this.frameElement)for(const[r,n]of this.textPreviewEntries){if(r!==this.primarySelectedClipId)continue;const a=this.getEffectiveVisualTransform(n.entry),o=De(n.entry.clip.textStyle),l=((t=this.transientFontSize)==null?void 0:t.clipId)===r?this.transientFontSize.fontSize:o.fontSize,c=((i=this.transientRotation)==null?void 0:i.clipId)===r?this.transientRotation.rotation:o.rotation,d=this.getTextPreviewBaselineMetrics(e).scale*a.scale,u=(n.element.offsetWidth||0)*d,p=(n.element.offsetHeight||0)*d,f=e.width*a.x,m=e.height*a.y;return{clipId:r,transform:a,frameSize:e,baseRect:{left:0,top:0,width:e.width,height:e.height,centerX:e.width/2,centerY:e.height/2},displayRect:{left:f-u/2,top:m-p/2,width:u,height:p,centerX:f,centerY:m},clipType:"text",currentFontSize:l,currentRotation:c}}return null}getFrameSize(){var i,r,n,a;const e=((i=this.frameElement)==null?void 0:i.clientWidth)??0,t=((r=this.frameElement)==null?void 0:r.clientHeight)??0;return{width:e>0?e:Fs((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:Fs((a=this.frameElement)==null?void 0:a.style.height)}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}toFrameLocalPoint(e){var i;const t=(i=this.frameElement)==null?void 0:i.getBoundingClientRect();return{x:(e.clientX??0)-((t==null?void 0:t.left)??0),y:(e.clientY??0)-((t==null?void 0:t.top)??0)}}getTextPreviewBaselineMetrics(e){const t=Ru(this.getAspectRatio());return t.width<=0||t.height<=0||e.width<=0||e.height<=0?{width:t.width,height:t.height,scale:1}:{width:t.width,height:t.height,scale:Math.min(e.width/t.width,e.height/t.height)}}getMediaSize(e,t,i){if(ar(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=Oi(t,"sys_width"),n=Oi(t,"sys_height");return r&&n?{width:r,height:n}:{width:i.width,height:i.height}}getEffectiveVisualTransform(e){var t;return((t=this.transientVisualTransform)==null?void 0:t.clipId)===e.clip.id?this.transientVisualTransform.transform:Pe(e.clip.visualTransform)}}class Bu extends Lu{constructor(e={}){super(e.callbacks,{diagnostics:e.diagnostics,getDiagnosticsContext:e.getDiagnosticsContext,previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont,sourceMediaRegistry:e.sourceMediaRegistry,resourceCacheManager:e.resourceCacheManager,rootClassName:e.rootClassName,frameClassName:e.frameClassName,slotClassNamePrefix:e.slotClassNamePrefix})}destroy(){this.detach()}}function Ou(s){return"dom"}const Fu=36e5,Nu=3e5;function ln(s){return s.length===0?0:s.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function Ns(s){return ln(s)}function Gs(s){return Math.max(s+Nu,Fu)}class Hs{constructor(e={}){g(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(r){O.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function Gu(s){return[...s].sort((e,t)=>e.order-t.order)}function Hu(s){return[...s].sort((e,t)=>e.startTime-t.startTime)}function Mr(s,e,t){const i=s.type==="video"||s.type==="text",r=s.type!=="text";return{trackId:s.id,trackType:s.type,trackOrder:s.order,clip:e,mediaTime:t,muted:(s.isMuted??!1)||(e.isMuted??!1),kind:s.type,hasVisual:i,hasAudio:r}}class zu{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t,i={}){const r=Gu(e),n=[],a=[];let o=null;for(const l of r){const c=Hu(l.clips),h=c.find(u=>t>=u.startTime&&t<u.endTime?!0:!!i.includeEndedClipsAtTime&&t>=u.startTime&&t===u.endTime);if(h){const u=h.startTimeAtSource+(t-h.startTime);n.push(Mr(l,h,u))}const d=c.find(u=>u.startTime>t);if(d&&a.push(Mr(l,d,d.startTimeAtSource)),!o&&l.type==="video"){const u=c[0];u&&(o=Mr(l,u,u.startTimeAtSource))}}return{activeClips:n,nextClips:a,firstVideoClip:o}}}class $u{constructor(e){g(this,"options");g(this,"_previewSession");g(this,"_previewMountContainer",null);g(this,"_resolvedPreviewBackend","dom");g(this,"_runtimePreviewBackendOverride",null);g(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const Vu=1e3;class Uu{constructor(e){g(this,"callbacks");g(this,"failedOverlayDelayMs");g(this,"_previewLoadingState",{status:"idle",isLoading:!1,reason:null});g(this,"_pendingPreviewState",null);g(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.failedOverlayDelayMs=e.failedOverlayDelayMs??Vu}get previewLoadingState(){return this._previewLoadingState}get pendingPreviewState(){return this._pendingPreviewState}set pendingPreviewState(e){this._pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this._nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this._nextPendingPreviewSyncRequestId=Math.max(0,e)}handleRuntimeStateChange(e){const t=this._previewLoadingState;this._previewLoadingState=e.loading;const i=this._pendingPreviewState;i&&(e.syncRequestId===i.syncRequestId||e.syncRequestId===void 0)&&(e.loading.reason!=="syncing"&&(i.awaitingSync=!1),e.loading.status==="failed"?this.scheduleFailedOverlay(e.errorMessage||"资源加载异常,请刷新重试"):(this.clearFailedOverlayTimeout(),i.pendingFailedMessage=null,i.errorMessage=null)),zs(t,e.loading)||this.callbacks.emitLoadingStateChange(e.loading),this.updatePendingPreviewState()}markSyncProcessed(e){this._pendingPreviewState&&e===this._pendingPreviewState.syncRequestId&&(this._pendingPreviewState.awaitingSync=!1),this.updatePendingPreviewState()}beginPendingPreview(e,t,i){this.clearPendingPreviewTimeout(),this._pendingPreviewState={mode:t,targetTime:e,resumePlayOnReady:i,errorMessage:null,timeoutId:null,failedTimeoutId:null,pendingFailedMessage:null,awaitingSync:!0,syncRequestId:++this._nextPendingPreviewSyncRequestId}}buildPreviewPendingState(){return this._pendingPreviewState?this._pendingPreviewState.mode==="scrub"?null:{mode:this._pendingPreviewState.mode,targetTime:this._pendingPreviewState.targetTime,loading:this.resolvePendingLoadingState(),errorMessage:this._pendingPreviewState.errorMessage}:this.buildPlaybackLoadingOverlayState()}updatePendingPreviewState(){if(!this._pendingPreviewState){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const t=this.resolvePendingLoadingState().status==="loading";if(this._pendingPreviewState.errorMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.pendingFailedMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.awaitingSync){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(t){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const i=this._pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),i&&this.callbacks.resumePlayback()}retryPendingPreview(){this._pendingPreviewState&&(this._pendingPreviewState.errorMessage=null,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.awaitingSync=!0,this._pendingPreviewState.syncRequestId=++this._nextPendingPreviewSyncRequestId,this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this.callbacks.requestPreviewSync())}clearPendingPreviewState(){this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this._pendingPreviewState=null,this.callbacks.applyPendingState(null)}resetPreviewRuntimeState(){const e={status:"idle",isLoading:!1,reason:null};zs(this._previewLoadingState,e)||(this._previewLoadingState=e,this.callbacks.emitLoadingStateChange(e))}resolvePendingLoadingState(){var e;return(e=this._pendingPreviewState)!=null&&e.awaitingSync?{status:"loading",isLoading:!0,reason:"syncing"}:this._previewLoadingState}buildPlaybackLoadingOverlayState(){return this._previewLoadingState.status!=="loading"||this._previewLoadingState.reason!=="media-pending"?null:{mode:"playback",targetTime:0,loading:this._previewLoadingState,errorMessage:null}}clearPendingPreviewTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.timeoutId&&(clearTimeout(this._pendingPreviewState.timeoutId),this._pendingPreviewState.timeoutId=null)}scheduleFailedOverlay(e){if(!this._pendingPreviewState||this._pendingPreviewState.errorMessage===e||this._pendingPreviewState.pendingFailedMessage===e&&this._pendingPreviewState.failedTimeoutId)return;this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=e;const t=this._pendingPreviewState.syncRequestId;this._pendingPreviewState.failedTimeoutId=setTimeout(()=>{!this._pendingPreviewState||this._pendingPreviewState.syncRequestId!==t||(this._pendingPreviewState.errorMessage=e,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.failedTimeoutId=null,this.callbacks.applyPendingState(this.buildPreviewPendingState()))},this.failedOverlayDelayMs)}clearFailedOverlayTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.failedTimeoutId&&(clearTimeout(this._pendingPreviewState.failedTimeoutId),this._pendingPreviewState.failedTimeoutId=null)}}function zs(s,e){return s.status===e.status&&s.isLoading===e.isLoading&&s.reason===e.reason}const Wu=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Yu={togglePlay:["Space"],deleteSelectedClips:["Delete","Backspace"],copySelectedClips:["Mod+C"],cutSelectedClips:["Mod+X"],pasteClipboardClips:["Mod+V"],toggleSelectedClipsAudio:["Mod+Alt+A"],splitCurrentClip:["Mod+B"],undo:["Mod+Z"],redo:["Mod+Shift+Z","Ctrl+Y"]};function Xu(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function qu(s){const e=s.trim();if(!e)return null;const t=e.toLowerCase();return t==="space"||t==="spacebar"?"Space":t==="delete"?"Delete":t==="backspace"?"Backspace":/^[a-z]$/i.test(e)?`Key${e.toUpperCase()}`:/^key[a-z]$/i.test(e)?`Key${e.slice(-1).toUpperCase()}`:/^[0-9]$/.test(e)?`Digit${e}`:/^digit[0-9]$/i.test(e)?`Digit${e.slice(-1)}`:null}function ju(s,e,t){const i=e.split("+").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return null;let r=null,n=!1,a=!1,o=!1,l=!1;for(const c of i)switch(c.toLowerCase()){case"mod":t?o=!0:a=!0;break;case"alt":case"option":n=!0;break;case"ctrl":case"control":a=!0;break;case"cmd":case"command":case"meta":o=!0;break;case"shift":l=!0;break;default:{const h=qu(c);if(!h||r)return null;r=h}}return r?{action:s,code:r,altKey:n,ctrlKey:a,metaKey:o,shiftKey:l}:null}function Ku(s){if(!(s instanceof HTMLElement))return!1;if(s.isContentEditable)return!0;const e=s.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:!!s.closest('[contenteditable=""], [contenteditable="true"], input, textarea, select')}function Zu(s,e){return s.code===e.code&&s.altKey===e.altKey&&s.ctrlKey===e.ctrlKey&&s.metaKey===e.metaKey&&s.shiftKey===e.shiftKey}function Ju(s,e){return s===!1||(s==null?void 0:s.enabled)===!1?[]:Wu.flatMap(t=>{var n;const i=(n=s==null?void 0:s.bindings)==null?void 0:n[t];return(i===void 0?Yu[t]:Array.isArray(i)?i:[i]).map(a=>ju(t,a,e)).filter(a=>a!==null)})}class Qu{constructor(e){g(this,"callbacks");g(this,"bindings");g(this,"enabled");g(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??Xu();e.root,this.callbacks=e.callbacks,this.bindings=Ju(e.config,t),this.enabled=e.config!==!1&&((i=e.config)==null?void 0:i.enabled)!==!1&&this.bindings.length>0}init(){var e,t;this.enabled&&((t=(e=globalThis.window)==null?void 0:e.addEventListener)==null||t.call(e,"keydown",this.keydownListener))}destroy(){var e,t;(t=(e=globalThis.window)==null?void 0:e.removeEventListener)==null||t.call(e,"keydown",this.keydownListener)}handleKeydown(e){if(Ku(e.target))return;const t=this.bindings.find(i=>Zu(e,i));t&&(e.preventDefault(),e.stopPropagation(),this.dispatchAction(t.action))}dispatchAction(e){switch(e){case"togglePlay":this.callbacks.togglePlay();return;case"deleteSelectedClips":this.callbacks.canDeleteSelectedClips()&&this.callbacks.deleteSelectedClips();return;case"copySelectedClips":this.callbacks.canCopySelectedClips()&&this.callbacks.copySelectedClips();return;case"cutSelectedClips":this.callbacks.canCutSelectedClips()&&this.callbacks.cutSelectedClips();return;case"pasteClipboardClips":this.callbacks.canPasteClipboardClips()&&this.callbacks.pasteClipboardClips();return;case"toggleSelectedClipsAudio":this.callbacks.canToggleSelectedClipsAudio()&&this.callbacks.toggleSelectedClipsAudio();return;case"splitCurrentClip":this.callbacks.canSplitSelectedClip()&&this.callbacks.splitCurrentClip();return;case"undo":this.callbacks.undo();return;case"redo":this.callbacks.redo();return}}}function yo(s){var t;const e=s.getPrimarySelectedClip()||((t=s.findFallbackSelectedClip)==null?void 0:t.call(s))||null;return{clip:e,hasSelectedClip:!!e}}function ep(s){const e=yo(s),t=s.getSelectedClipIds(),i=s.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:s.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function tp(s){var i;const e=s.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===s.lastSelectedClipId?s.lastSelectedClipId:(s.emitSelectedClipChange(e),t)}class ip{constructor(e){g(this,"cleanupEmptyTracks",!1);g(this,"durationDirty",!1);g(this,"canPlayDirty",!1);g(this,"selectionDirty",!1);g(this,"trackLayoutDirty",!1);g(this,"trackInfoDirty",!1);g(this,"stageDirty",!1);g(this,"previewDirty",!1);g(this,"committed",!1);g(this,"events",[]);this.options=e}addClipToTrack(e,t){const i=this.options.addClipToTrack?this.options.addClipToTrack(e,t):this.options.trackCollection.addClipToTrack(e,t);return i&&this.markStructureMutation(),i}removeClip(e){this.options.removeClip?this.options.removeClip(e):this.options.trackCollection.removeClip(e),this.markStructureMutation()}removeClipFromTrack(e,t){const i=this.options.removeClipFromTrack?this.options.removeClipFromTrack(e,t):this.options.trackCollection.removeClipFromTrack(e,t);return i&&this.markStructureMutation(),i}updateClip(e,t){this.options.updateClip?this.options.updateClip(e,t):this.options.trackCollection.updateClip(e,t),this.markClipStateMutation()}moveClipToTrack(e,t){const i=this.findTrackByClipId(e),r=this.getClips().find(o=>o.id===e)??null,n=i?this.resolveTrackId(i):null;if(!r||!n)return!1;const a=this.options.moveClipToTrack?this.options.moveClipToTrack(r,n,t):this.options.trackCollection.moveClipToTrack(r,n,t);return a&&this.markStructureMutation(),a}ensureTrackFromHistorySnapshot(e,t){const i=this.options.ensureTrackFromHistorySnapshot(e,t);return i&&this.markTrackLayoutMutation(),i}removeClipGaps(){this.options.removeClipGaps(),this.markStructureMutation()}getClips(){return this.options.getClips?this.options.getClips():this.options.trackCollection.getAllClips()}findTrackByClipId(e){return this.options.findTrackByClipId?this.options.findTrackByClipId(e):this.options.trackCollection.findTrackByClipId(e)}getDefaultTrack(){return this.options.getDefaultTrack?this.options.getDefaultTrack():this.options.trackCollection.getDefaultTrack()}queueEvent(e,t){this.events.push({type:e,payload:t})}markStructureMutation(){this.cleanupEmptyTracks=!0,this.durationDirty=!0,this.canPlayDirty=!0,this.selectionDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}markClipStateMutation(){this.durationDirty=!0,this.canPlayDirty=!0,this.selectionDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}markTrackLayoutMutation(){this.trackLayoutDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}commit(){this.committed||(this.committed=!0,this.options.onCommit({cleanupEmptyTracks:this.cleanupEmptyTracks,durationDirty:this.durationDirty,canPlayDirty:this.canPlayDirty,selectionDirty:this.selectionDirty,trackLayoutDirty:this.trackLayoutDirty,trackInfoDirty:this.trackInfoDirty,stageDirty:this.stageDirty,previewDirty:this.previewDirty,events:[...this.events]}))}createHistoryExecutionTarget(){return{removeClip:e=>{this.removeClip(e)},addClipToTrack:(e,t)=>this.addClipToTrack(e,t),updateClip:(e,t)=>{this.updateClip(e,t)},moveClipToTrack:(e,t)=>this.moveClipToTrack(e,t),setPrimaryTrackMagnetEnabled:e=>{this.options.setPrimaryTrackMagnetEnabled(e)},ensureTrackFromHistorySnapshot:(e,t)=>this.ensureTrackFromHistorySnapshot(e,t),removeClipGaps:()=>{this.removeClipGaps()},getClips:()=>this.getClips(),findTrackByClipId:e=>{const t=this.findTrackByClipId(e);return t!=null&&t.addClip?t:null},getDefaultTrack:()=>{const e=this.getDefaultTrack();return e!=null&&e.addClip?e:null},loadClipThumbnails:this.options.loadClipThumbnails,withClipRemovalBatch:e=>e()}}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}function rp(s,e){var t,i,r,n;return((i=(t=s.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((n=(r=s.getLastTrack())==null?void 0:r.getId)==null?void 0:n.call(r))||e}function np(s){if(s.placement.status==="use_existing_track")return s.trackCollection.addClipToTrack(s.placement.trackId,s.clip);const e=s.createTrack(s.placement.trackType,s.placement.suggestedTrackName,s.placement.insertionPlacement),t=rp(s.trackCollection,e);return t?s.trackCollection.addClipToTrack(t,s.clip):!1}function $s(s,e,t){return e.trackId?s.removeClipFromTrack(e.trackId,t):!1}function sp(s){return s.trackCollection.moveClipToTrack(s.command.clip,s.command.sourceTrackId,s.command.targetTrackId)}function Fi(s){var e,t,i,r,n;(e=s.checkTrackDurationChange)==null||e.call(s),(t=s.updateCanPlayState)==null||t.call(s),(i=s.updateTrackInfoPanel)==null||i.call(s),(r=s.handleClipChange)==null||r.call(s),(n=s.cleanupEmptyTracks)==null||n.call(s)}class So{constructor(){g(this,"panel",null);g(this,"config",null);g(this,"currentSelectionState",this.buildSelectionState(null,[]));g(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new uo({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,this.resolveUpdateTargets(i,r).forEach(a=>{e.updateClip(a.id,r)}),setTimeout(()=>{this.isInternalUpdate=!1},0)},onGenerateVoice:e.onGenerateVoice})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip(),t=this.config.getSelectedClips();this.currentSelectionState=this.buildSelectionState(e,t),this.panel.setSelectionState(this.currentSelectionState)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}setPreferredTab(e){var t;(t=this.panel)==null||t.setPreferredTab(e)}showVoiceGenerationLoading(){var e;(e=this.panel)==null||e.showVoiceGenerationLoading()}hideVoiceGenerationLoading(){var e;(e=this.panel)==null||e.hideVoiceGenerationLoading()}setVoiceGenerationBusy(e){var t;(t=this.panel)==null||t.setVoiceGenerationBusy(e)}buildSelectionState(e,t){const i=t.length>0?t:e?[e]:[],r=e??i[0]??null;if(!r||i.length===0)return{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1};const a=new Set(i.map(c=>c.type)).size>1?"mixed":r.type,o=i.length>1,l=a==="audio"&&i.every(c=>Le(c));return{primaryClip:r,selectedClips:i,selectionCount:i.length,groupKind:a,supportsVoiceBatch:a==="text"||l,supportsTextContentBatch:a==="text"&&!o,supportsVisualBatch:a==="video",supportsVolumeBatch:a==="video"||a==="audio"}}resolveUpdateTargets(e,t){const{primaryClip:i,selectedClips:r,groupKind:n,supportsVoiceBatch:a}=this.currentSelectionState,o=r.find(l=>l.id===e)??i;return o?Object.prototype.hasOwnProperty.call(t,"textContent")?[o]:Object.prototype.hasOwnProperty.call(t,"ttsFollowTextUpdates")?a&&n==="audio"?r.filter(l=>Le(l)):[o]:Object.prototype.hasOwnProperty.call(t,"textStyle")?n==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"visualTransform")?n==="video"||n==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"volume")?n==="video"||n==="audio"?r:[o]:[o]:[]}convertTheme(e){return{backgroundColor:ye.backgroundColor,borderColor:e.border||ye.borderColor,textColor:e.clipName||ye.textColor,labelColor:e.timeText||ye.labelColor,inputBackground:e.trackBackground||ye.inputBackground,inputBorder:e.trackBorder||ye.inputBorder,inputFocusBorder:ye.inputFocusBorder,buttonBackground:e.clipBackground||ye.buttonBackground,buttonBorder:e.clipBorder||ye.buttonBorder,buttonActiveBackground:ye.buttonActiveBackground,buttonActiveBorder:e.clipSelectedBorder||ye.buttonActiveBorder,buttonActiveText:ye.buttonActiveText}}}class ap{constructor(){g(this,"panel",null)}init(e){var i,r,n,a;const t=((i=e.theme)==null?void 0:i.background)||ke.background;this.panel=new ho({container:e.container,theme:{background:t,border:((r=e.theme)==null?void 0:r.border)||ke.border,text:((n=e.theme)==null?void 0:n.clipName)||ke.text,buttonBackground:((a=e.theme)==null?void 0:a.clipBackground)||ke.buttonBackground,buttonHover:ke.buttonHover,buttonDanger:ke.buttonDanger},width:vi,timeScaleHeight:e.timeScaleHeight||40,includeTimeScaleSpacer:e.includeTimeScaleSpacer},e.onRenameTrack,e.onRemoveTrack,e.onMuteTrack)}hasPanel(){return!!this.panel}update(e){var t;(t=this.panel)==null||t.setTracks(e)}setScrollTop(e){var t;(t=this.panel)==null||t.setScrollTop(e)}destroy(){var e;(e=this.panel)==null||e.destroy(),this.panel=null}}class Vs{syncCurrentTime(e,t,i,r){e==null||e.setCurrentTime(r),t==null||t.setCurrentTime(r)}syncZoom(e,t,i,r){e==null||e.setZoom(r),t==null||t.setZoom(r),i.syncZoom(r)}syncScrollLeft(e,t,i){e==null||e.setScrollLeft(i),t.syncScrollLeft(i)}syncScrollTop(e,t,i){e==null||e.setScrollTop(i),t==null||t.setScrollTop(i)}syncSelection(e,t){e.syncSelection(t,t[0]??null)}findSelectedClip(e){return e.findPrimarySelectedClip()}}const op=100*1024*1024,lp=10*1024*1024*1024,cp=30*24*60*60*1e3,hp=["video/mp4","audio/aac","audio/mpeg","audio/mp4","audio/mp3","audio/ogg","audio/wav","audio/x-wav"],li={enabled:!1,maxEntryBytes:op,maxTotalBytes:lp,ttlMs:cp,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:hp},dp="timeline-preview-resource-cache",up=1,Se="metadata";function pp(){return new Promise((s,e)=>{const t=indexedDB.open(dp,up);t.onupgradeneeded=()=>{const i=t.result,r=i.objectStoreNames.contains(Se)?t.transaction.objectStore(Se):i.createObjectStore(Se,{keyPath:"cacheKey"});r.indexNames.contains("sourceUrl")||r.createIndex("sourceUrl","sourceUrl"),r.indexNames.contains("expiresAt")||r.createIndex("expiresAt","expiresAt"),r.indexNames.contains("lastAccessedAt")||r.createIndex("lastAccessedAt","lastAccessedAt"),r.indexNames.contains("storageKind")||r.createIndex("storageKind","storageKind")},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function Dr(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class gp{constructor(){g(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=pp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async get(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(Se,"readonly").objectStore(Se).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async put(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).put(e),await Dr(i)}async delete(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).delete(e),await Dr(i)}async clear(){const t=(await this.getDb()).transaction(Se,"readwrite");t.objectStore(Se).clear(),await Dr(t)}async list(){const e=await this.getDb();return new Promise((t,i)=>{const r=e.transaction(Se,"readonly").objectStore(Se).getAll();r.onerror=()=>i(r.error),r.onsuccess=()=>t(r.result)})}}const fp="timeline-preview-resource-cache",mp="timeline-preview-resource-cache-blobs",yp=1,Re="blobs";function Sp(){return new Promise((s,e)=>{const t=indexedDB.open(mp,yp);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Re)||i.createObjectStore(Re)},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function Lr(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class vp{constructor(){g(this,"kind","indexeddb");g(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=Sp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async read(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(Re,"readonly").objectStore(Re).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Re,"readwrite");r.objectStore(Re).put(t,e),await Lr(r)}async delete(e){const i=(await this.getDb()).transaction(Re,"readwrite");i.objectStore(Re).delete(e),await Lr(i)}async clear(){const t=(await this.getDb()).transaction(Re,"readwrite");t.objectStore(Re).clear(),await Lr(t)}}class Cp{constructor(){g(this,"kind","opfs");g(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(fp,{create:!0})).catch(e=>{throw this.directoryPromise=null,e})),this.directoryPromise}async ensureReady(){try{return await this.getDirectory(),!0}catch{return!1}}async read(e){try{return await(await(await this.getDirectory()).getFileHandle(e)).getFile()}catch{return null}}async write(e,t){const n=await(await(await this.getDirectory()).getFileHandle(e,{create:!0})).createWritable();try{await n.write(t),await n.close()}catch(a){try{typeof n.abort=="function"&&await n.abort()}catch{}throw a}}async delete(e){const t=await this.getDirectory();try{await t.removeEntry(e)}catch{}}async clear(){const e=await this.getDirectory();for await(const[t]of e)await e.removeEntry(t)}}async function Tp(s){var e;if(s.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new Cp;if(await t.ensureReady())return t}return new vp}function bp(s){return Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function Us(s){return s.split(";",1)[0].trim().toLowerCase()}async function kp(s){const e=globalThis.crypto;if(!(e!=null&&e.subtle))throw new Error("Resource cache key generation requires Web Crypto SHA-256 support.");const t=await e.subtle.digest("SHA-256",new TextEncoder().encode(s));return bp(new Uint8Array(t))}function Br(s){return s?[...s]:[...li.allowedMimeTypes]}function wp(s){return s?s===!0?{...li,enabled:!0,allowedMimeTypes:Br(void 0)}:{...li,...s,enabled:s.enabled??!0,allowedMimeTypes:Br(s.allowedMimeTypes)}:{...li,allowedMimeTypes:Br(void 0)}}function Pp(s){try{const e=new URL(s);return e.hash="",e.toString()}catch{return s.trim()}}async function xp(s){var t;const e=((t=s.sourceKey)==null?void 0:t.trim())||Pp(s.url);return kp(e)}function Ws(s,e=li.allowedMimeTypes){if(!s.url)return!0;let t;try{t=new URL(s.url)}catch{return!0}if(t.protocol!=="http:"&&t.protocol!=="https:"||s.kind==="hls-fmp4"||/\.m3u8(?:$|\?|#)/i.test(t.pathname))return!0;if(!s.mimeType)return!1;const i=Us(s.mimeType);return!e.some(r=>Us(r)===i)}function _p(s){return s&&s.split(";",1)[0].trim().toLowerCase()||null}function Ys(s){if(!s)return null;const e=Number(s);return Number.isSafeInteger(e)&&e>=0?e:null}function Ap(s){if(!s)return null;const e=s.match(/^bytes\s+(?:\d+-\d+|\*)\/(\d+|\*)$/i);if(!e||e[1]==="*")return null;const t=Number(e[1]);return Number.isSafeInteger(t)&&t>=0?t:null}function Xs(s,e,t){return{url:e,ok:s.ok,status:s.status,mimeType:_p(s.headers.get("content-type")),sizeBytes:t,etag:s.headers.get("etag"),lastModified:s.headers.get("last-modified"),acceptRanges:s.headers.get("accept-ranges")}}class Ip{async probe(e){var r;try{const n=await fetch(e,{method:"HEAD"}),a=Ys(n.headers.get("content-length"));if(n.ok&&a!==null)return Xs(n,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=Ap(t.headers.get("content-range"))??Ys(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return Xs(t,e,i)}async download(e){const t=await fetch(e);if(!t.ok)throw new Error(`Resource cache download failed with HTTP ${t.status}.`);return t.blob()}}const Ep={createObjectURL(s){return URL.createObjectURL(s)},revokeObjectURL(s){URL.revokeObjectURL(s)}};function Tt(s,e){return{url:s.url,cacheStatus:e,sourceUrl:s.url}}function Rp(s,e){return s.etag||e.etag?s.etag===e.etag&&s.sizeBytes===e.contentLength:s.sizeBytes===e.contentLength&&s.lastModified===e.lastModified}class Mp{constructor(e={}){g(this,"options");g(this,"metadataStore");g(this,"storagePromise");g(this,"http");g(this,"objectUrl");g(this,"now");g(this,"cacheKeyBuilder");g(this,"onEvent");g(this,"objectUrls",new Set);g(this,"inflightDownloads",new Map);this.options=wp(e.options),this.metadataStore=e.metadataStore??new gp,this.storagePromise=e.storage?Promise.resolve(e.storage):Tp({preferStorage:this.options.preferStorage}),this.http=e.http??new Ip,this.objectUrl=e.objectUrl??Ep,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??xp,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Ws(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),Tt(e,"bypass");try{const t=await this.cacheKeyBuilder(e),i=await this.storagePromise,r=await this.metadataStore.get(t);if(r){const l=await i.read(t);if(l){if(r.expiresAt>this.now()){const c={...r,lastAccessedAt:this.now()};return await this.metadataStore.put(c),this.emitEvent("resource-cache.hit",{sourceUrl:e.url,sizeBytes:c.sizeBytes}),this.blobResult(e.url,l,c,"hit")}return await this.resolveExpired(e,t,r,l,i)}await this.metadataStore.delete(t)}if(this.options.resolveMode==="prefer-fast-start")return this.probeAndDownload(t,e,i).catch(()=>{}),this.emitEvent("resource-cache.miss",{sourceUrl:e.url}),Tt(e,"miss");const n=await this.probeCacheable(e);if(n.cacheStatus!=="miss")return n.result;const{blob:a,metadata:o}=await this.getOrCreateDownload(t,e,n.probe,i);return this.emitEvent("resource-cache.miss",{sourceUrl:e.url,sizeBytes:o.sizeBytes}),this.blobResult(e.url,a,o,"miss")}catch{return this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),Tt(e,"fallback")}}revokeObjectUrl(e){this.objectUrls.delete(e)&&this.objectUrl.revokeObjectURL(e)}async cleanupExpired(){const e=await this.storagePromise,t=this.now(),i=await this.metadataStore.list();await Promise.all(i.filter(r=>r.expiresAt<=t).map(r=>this.deleteEntry(r.cacheKey,e)))}async clear(){const e=await this.storagePromise;await Promise.all([e.clear(),this.metadataStore.clear()]);for(const t of[...this.objectUrls])this.revokeObjectUrl(t)}async getStats(){const e=await this.metadataStore.list();return{entryCount:e.length,totalBytes:e.reduce((t,i)=>t+i.sizeBytes,0),maxTotalBytes:this.options.maxTotalBytes}}async resolveExpired(e,t,i,r,n){const a=await this.probeCacheable(e);if(a.cacheStatus!=="miss")return a.result;if(Rp(a.probe,i)){const c=this.now(),h={...i,updatedAt:c,lastAccessedAt:c,expiresAt:c+this.options.ttlMs};return await this.metadataStore.put(h),this.emitEvent("resource-cache.revalidate.success",{sourceUrl:e.url,sizeBytes:h.sizeBytes}),this.blobResult(e.url,r,h,"stale-revalidated")}this.emitEvent("resource-cache.revalidate.stale",{sourceUrl:e.url}),await this.deleteEntry(t,n);const{blob:o,metadata:l}=await this.getOrCreateDownload(t,e,a.probe,n);return this.blobResult(e.url,o,l,"miss")}async probeCacheable(e){const t=await this.http.probe(e.url);return t.ok?t.sizeBytes===null?(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:Tt(e,"fallback")}):Ws({...e,mimeType:e.mimeType??t.mimeType},this.options.allowedMimeTypes)||t.sizeBytes>this.options.maxEntryBytes||t.sizeBytes>this.options.maxTotalBytes?(this.emitEvent("resource-cache.bypass",{sourceUrl:e.url,sizeBytes:t.sizeBytes,mimeType:t.mimeType}),{cacheStatus:"bypass",result:Tt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:Tt(e,"fallback")})}async probeAndDownload(e,t,i){const r=await this.probeCacheable(t);r.cacheStatus==="miss"&&await this.getOrCreateDownload(e,t,r.probe,i)}getOrCreateDownload(e,t,i,r){const n=this.inflightDownloads.get(e);if(n)return n;const a=this.downloadAndStore(e,t,i,r).finally(()=>{this.inflightDownloads.delete(e)});return this.inflightDownloads.set(e,a),a}async downloadAndStore(e,t,i,r){this.emitEvent("resource-cache.download.start",{sourceUrl:t.url});try{const n=await this.http.download(t.url),a=n.size;if(a>this.options.maxEntryBytes||a>this.options.maxTotalBytes)throw new Error("Resource exceeds cache capacity.");await this.evictForWrite(e,a,r),await r.write(e,n);const o=this.now(),l={cacheKey:e,sourceUrl:t.url,mimeType:i.mimeType??t.mimeType??null,sizeBytes:a,etag:i.etag,lastModified:i.lastModified,contentLength:a,storageKind:r.kind,createdAt:o,updatedAt:o,lastAccessedAt:o,expiresAt:o+this.options.ttlMs};return await this.metadataStore.put(l),this.emitEvent("resource-cache.download.success",{sourceUrl:t.url,sizeBytes:a}),{blob:n,metadata:l}}catch(n){throw this.emitEvent("resource-cache.download.failed",{sourceUrl:t.url,error:n instanceof Error?n.message:String(n)}),n}}async evictForWrite(e,t,i){const r=(await this.metadataStore.list()).filter(a=>a.cacheKey!==e);let n=r.reduce((a,o)=>a+o.sizeBytes,0);for(const a of r.sort((o,l)=>o.lastAccessedAt-l.lastAccessedAt)){if(n+t<=this.options.maxTotalBytes)return;await this.deleteEntry(a.cacheKey,i),n-=a.sizeBytes}}async deleteEntry(e,t){await Promise.all([t.delete(e),this.metadataStore.delete(e)]),this.emitEvent("resource-cache.cleanup.deleted",{cacheKey:e})}blobResult(e,t,i,r){const n=this.objectUrl.createObjectURL(t);return this.objectUrls.add(n),{url:n,cacheStatus:r,sourceUrl:e,sizeBytes:i.sizeBytes,objectUrl:n}}emitEvent(e,t){var i;(i=this.onEvent)==null||i.call(this,e,t)}}function Dp(s){return!!s&&typeof s.then=="function"}class Or{constructor(){g(this,"durationCache",new Map);g(this,"thumbnailCache",new Map);g(this,"previewSourceCache",new Map)}static buildSourceKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src||""}static buildThumbnailKey(e){return[this.buildSourceKey(e),e.type,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}getDuration(e,t,i={}){const r=this.durationCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(typeof(r==null?void 0:r.value)=="number")return Promise.resolve(r.value)}const n=t().then(a=>(this.durationCache.set(e,{value:a,promise:null}),a)).catch(a=>{throw this.durationCache.delete(e),a});return this.durationCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeDuration(e,t){this.durationCache.set(e,{value:t,promise:null})}getThumbnails(e,t,i={}){const r=this.thumbnailCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.value)return Promise.resolve(r.value)}const n=t().then(a=>(this.thumbnailCache.set(e,{value:a,promise:null}),a)).catch(a=>{throw this.thumbnailCache.delete(e),a});return this.thumbnailCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeThumbnails(e,t){this.thumbnailCache.set(e,{value:t,promise:null})}clearThumbnailCache(){this.thumbnailCache.clear()}getPreviewSource(e,t,i={}){const r=this.previewSourceCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.resolved)return r.value}const n=t();if(!Dp(n))return this.previewSourceCache.set(e,{value:n,promise:null,resolved:!0}),n;const a=n.then(o=>(this.previewSourceCache.set(e,{value:o,promise:null,resolved:!0}),o)).catch(o=>{throw this.previewSourceCache.delete(e),o});return this.previewSourceCache.set(e,{value:(r==null?void 0:r.value)??null,promise:a,resolved:!1}),a}primePreviewSource(e,t){this.previewSourceCache.set(e,{value:t,promise:null,resolved:!0})}}class qs{constructor(e,t=ir){this.handlers=e,this.TrackCtor=t}createTrack(e){return new this.TrackCtor(e.layer,e.config,e.trackType,e.zoom,e.trackY,e.trackHeight,e.theme,this.handlers.onClipUpdate,this.handlers.onClipAdd,this.handlers.onClipRemove,this.handlers.onClipSplit,this.handlers.onClipSelect,this.handlers.onTimeJump,this.handlers.onHorizontalDragAutoScroll,this.handlers.onClipOverlap,this.handlers.onPrimaryTrackMagnetMove,this.handlers.onClipCrossTrackPreview,this.handlers.onClipCrossTrack,this.handlers.onClearDropPreview,this.handlers.onClearSelection,this.handlers.onSnapGuideChange,this.handlers.onClipToggleSelection,this.handlers.onSetSingleSelection,this.handlers.getMultiDragClipIds,this.handlers.onMultiDragMove,this.handlers.onMultiDragInteractionEnd,e.dragActivationThreshold,e.enableClipSnap,e.clipSnapThreshold)}}class Lp{constructor(e){this.tracks=e}getAll(){return this.tracks}getDefaultTrack(){return this.tracks[0]||null}getPrimaryTrack(){return this.tracks.find(e=>{var t;return((t=e.getRole)==null?void 0:t.call(e))==="primary"})||this.getDefaultTrack()}getLastTrack(){return this.tracks.length>0?this.tracks[this.tracks.length-1]:null}add(e){this.tracks.push(e)}findById(e){return this.tracks.find(t=>this.resolveTrackId(t)===e)||null}removeById(e){const t=this.findIndexById(e);if(t===-1)return null;const[i]=this.tracks.splice(t,1);return i||null}removeEmptyNonPrimaryTracks(){var t;const e=[];for(let i=this.tracks.length-1;i>=0;i-=1){const r=this.tracks[i];if(((t=r.getRole)==null?void 0:t.call(r))==="primary"||(typeof r.getClips=="function"?r.getClips():[]).length>0)continue;const[a]=this.tracks.splice(i,1);a&&e.push(a)}return e.reverse()}findTrackByClipId(e){return this.tracks.find(t=>t.getClips().some(i=>i.id===e))||null}getAllClips(){return this.tracks.flatMap(e=>e.getClips())}syncCurrentTime(e){this.tracks.forEach(t=>{var i;return(i=t.setCurrentTime)==null?void 0:i.call(t,e)})}syncZoom(e){this.tracks.forEach(t=>{var i;return(i=t.setZoom)==null?void 0:i.call(t,e)})}syncScrollLeft(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollLeft)==null?void 0:i.call(t,e)})}syncScrollTop(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollTop)==null?void 0:i.call(t,e)})}updateClip(e,t){this.tracks.forEach(i=>{var r;return(r=i.updateClip)==null?void 0:r.call(i,e,t)})}removeClip(e){this.tracks.forEach(t=>{var i;return(i=t.removeClip)==null?void 0:i.call(t,e)})}addClipToTrack(e,t){const i=this.findById(e);return i!=null&&i.addClip?(i.addClip(t),!0):!1}removeClipFromTrack(e,t){const i=this.findById(e);return i!=null&&i.removeClip?(i.removeClip(t),!0):!1}moveClipToTrack(e,t,i){if(t===i)return!0;const r=this.findById(t),n=this.findById(i);return!(r!=null&&r.removeClip)||!(n!=null&&n.addClip)?!1:(r.removeClip(e.id),n.addClip(e),!0)}removeClipGaps(){this.tracks.forEach(e=>{var t;return(t=e.removeClipGaps)==null?void 0:t.call(e)})}clearSelection(){this.tracks.forEach(e=>{var t;return(t=e.clearSelection)==null?void 0:t.call(e)})}syncSelection(e,t=e[0]??null){this.tracks.forEach(i=>{var r;(r=i.setSelection)==null||r.call(i,e,t)})}findPrimarySelectedClip(){var e;for(const t of this.tracks){const i=(e=t.getPrimarySelectedClip)==null?void 0:e.call(t);if(i)return i}return null}forEach(e){this.tracks.forEach(e)}findIndexById(e){return this.tracks.findIndex(t=>this.resolveTrackId(t)===e)}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}function Bp(s){return s==="text"?"文本":s==="video"?"视频":"音频"}function Ni(s){return s==="text"?0:s==="video"?1:2}class vo{constructor(e=[]){g(this,"tracks",[]);g(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,r,n,a){this.trackCounter++;const o=t||`${Bp(e)}轨道 ${this.trackCounter}`,l=n??(this.tracks.length===0?"primary":"normal");l==="primary"&&this.tracks.forEach(h=>{h.role==="primary"&&(h.role="normal")});const c={id:a||`track_${Date.now()}_${this.trackCounter}`,type:e,name:o,order:this.tracks.length,role:l,clips:[]};return this.insertTrack(c,i,r),O.debugLazy("TrackManager",()=>`创建轨道: ${o}`,()=>({trackId:c.id,type:e,order:c.order})),c}removeTrack(e){var i;const t=this.tracks.findIndex(r=>r.id===e);return t===-1?(O.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(O.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),O.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,O.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(O.warn("TrackManager",`轨道不存在: ${e}`),!1)}getTracks(){return[...this.tracks]}getTrack(e){return this.tracks.find(t=>t.id===e)}getTracksByType(e){return this.tracks.filter(t=>t.type===e)}updateTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(Object.assign(i,t),O.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(O.warn("TrackManager",`轨道不存在: ${e}`),!1)}recalculateOrder(){this.tracks.forEach((e,t)=>{e.order=t})}insertTrack(e,t,i){const r=this.tracks.findIndex(a=>a.role==="primary"),n=t??(e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary");if(r===-1||e.role==="primary"){this.tracks.push(e),this.recalculateOrder();return}if((n==="before_track"||n==="after_track")&&i){const a=this.tracks.findIndex(o=>o.id===i);if(a!==-1){this.tracks.splice(a+(n==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(n==="top_of_type_region"){const a=this.tracks.findIndex(l=>l.type===e.type);if(a!==-1){this.tracks.splice(a,0,e),this.recalculateOrder();return}const o=this.tracks.findIndex(l=>Ni(l.type)>Ni(e.type));if(o!==-1){this.tracks.splice(o,0,e),this.recalculateOrder();return}}if(n==="bottom_of_type_region"){const a=this.tracks.reduce((l,c,h)=>c.type===e.type?h:l,-1);if(a!==-1){this.tracks.splice(a+1,0,e),this.recalculateOrder();return}const o=this.tracks.reduce((l,c,h)=>Ni(c.type)<=Ni(e.type)?h:l,-1);if(o!==-1){this.tracks.splice(o+1,0,e),this.recalculateOrder();return}}n==="before_primary"?this.tracks.splice(r,0,e):this.tracks.splice(r+1,0,e),this.recalculateOrder()}muteTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.isMuted=t,O.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(O.warn("TrackManager",`轨道不存在:${e}`),!1)}isTrackMuted(e){const t=this.tracks.find(i=>i.id===e);return(t==null?void 0:t.isMuted)??!1}clearAllTracks(){this.tracks=[],this.trackCounter=0,O.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}class Op{constructor(e){g(this,"currentTime");g(this,"playState");g(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class Co{constructor(){g(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class Fp{constructor(e){g(this,"zoom");g(this,"duration");g(this,"scrollLeft");g(this,"scrollTop");g(this,"viewportWidth");g(this,"viewportHeight");g(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class js{constructor(e){g(this,"selectionStore");g(this,"playbackStore");g(this,"viewportStore");this.selectionStore=new Co,this.playbackStore=new Op({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new Fp({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 Np{constructor(e,t,i,r,n){g(this,"stage");g(this,"layer");g(this,"onTimeChange");g(this,"onScrollChange");g(this,"config");g(this,"theme");g(this,"scrollLeft",0);g(this,"timeScaleHeight",40);g(this,"isDragging",!1);g(this,"dragStartX",0);g(this,"isPointerInsideTimeline",!1);g(this,"lastPointerXInTimeline",null);g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=r,this.onScrollChange=n,this.config={duration:i.duration||Qt,zoom:i.zoom||Me.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:qi(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(e){}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setScrollLeft(e){this.scrollLeft=this.clampScrollLeft(e),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(e){const t=U.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=U.timeToPixels(e.startTime,this.config.zoom),r=U.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,n=this.stage.width(),a=r<=n?Math.max(0,t-(n-r)/2):Math.max(0,t);this.setScrollLeft(a)}resize(e){this.stage.width(e),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",e=>{e.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(e.evt.offsetX),"seek")}),this.stage.on("mousedown",e=>{e.target.getLayer()===this.layer&&(this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(e){const t=e.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-t),r=this.scrollLeft;this.dragStartX=e.clientX,this.scrollLeft=i,this.render(),r!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(e){return U.pixelsToTime(e-pe+this.scrollLeft,this.config.zoom)}timeToPixel(e){return U.timeToPixels(e,this.config.zoom)-this.scrollLeft+pe}render(){const e=this.stage.width(),t=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const r=de.createRect(0,0,e,t,this.theme.background,this.theme.border,1);r.name("timeline-header-background"),this.layer.add(r)}this.layer.find(".time-tick-line").forEach(r=>r.remove()),this.layer.find(".time-tick-text").forEach(r=>r.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,r=U.pixelsToTime(t,this.config.zoom),n=U.pixelsToTime(i,this.config.zoom),a=U.msToSeconds(r),o=U.msToSeconds(n),{majorStep:l,minorStep:c}=U.getTickConfig(this.config.zoom),h=U.generateVisibleTicks(a-10,o+10,l,c);for(const d of h){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&de.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,U.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const q=class q{constructor(e,t,i,r,n,a,o){g(this,"container");g(this,"visualElement");g(this,"lineHitAreaElement");g(this,"theme");g(this,"onTimeChange");g(this,"onHorizontalAutoScroll");g(this,"currentTime");g(this,"zoom");g(this,"scrollLeft",0);g(this,"height");g(this,"isDragging",!1);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"lastPointerClientX",null);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});g(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});g(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const r=this.scrollLeft,n=this.onHorizontalAutoScroll(this.scrollLeft+i),a=typeof n=="number"?n:this.scrollLeft;if(this.scrollLeft=Math.max(0,a),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-r)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=e,this.currentTime=t,this.zoom=i,this.height=r,this.theme=n,this.onTimeChange=a,this.onHorizontalAutoScroll=o,this.container.innerHTML="",this.container.style.position="absolute",this.container.style.pointerEvents="none",this.container.style.overflow="visible",this.visualElement=document.createElementNS(q.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${q.VISUAL_WIDTH}`),this.visualElement.style.position="absolute",this.visualElement.style.top="0",this.visualElement.style.marginLeft=`${-14/2}px`,this.visualElement.style.pointerEvents="none",this.visualElement.style.overflow="visible",this.lineHitAreaElement=document.createElement("div"),this.lineHitAreaElement.className="timeline-manager-playhead-hit-area",this.lineHitAreaElement.style.position="absolute",this.lineHitAreaElement.style.top="0",this.lineHitAreaElement.style.width=`${q.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,r=U.pixelsToTime(i-pe+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,r),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(q.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=q.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const n=(i-e)/i;return-Math.max(1,Math.round(n*r))}if(e>t-i){const n=(e-(t-i))/i;return Math.max(1,Math.round(n*r))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const e=U.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+pe,t=e>=0&&e<=this.container.clientWidth,i=Math.max(q.HANDLE_HEIGHT+q.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${q.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=Pn.grip,i=Math.max(q.HANDLE_HEIGHT,e-q.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i))}createHandleShadowPath(){const e=document.createElementNS(q.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill",Pn.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(q.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(q.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(q.VISUAL_WIDTH-q.LINE_WIDTH)/2}`),t.setAttribute("y",`${q.HANDLE_LINE_START}`),t.setAttribute("width",`${q.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-q.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e){const t=document.createElementNS(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-end-cap"),t.setAttribute("x","3"),t.setAttribute("y",`${e}`),t.setAttribute("width",`${q.END_CAP_WIDTH}`),t.setAttribute("height",`${q.END_CAP_HEIGHT}`),t.setAttribute("rx","1.5"),t.setAttribute("fill","#ffffff"),t}};g(q,"SVG_NS","http://www.w3.org/2000/svg"),g(q,"VISUAL_WIDTH",14),g(q,"HANDLE_HEIGHT",16),g(q,"HANDLE_LINE_START",13),g(q,"LINE_WIDTH",1),g(q,"LINE_HIT_WIDTH",12),g(q,"END_CAP_WIDTH",8),g(q,"END_CAP_HEIGHT",1),g(q,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(q,"AUTO_SCROLL_MAX_SPEED",18);let cn=q;class Ks{constructor(e){g(this,"container");g(this,"orientation");g(this,"theme");g(this,"onScrollChange");g(this,"leadingInset");g(this,"trailingInset");g(this,"stage");g(this,"layer");g(this,"hitAreaRect");g(this,"thumbRect");g(this,"viewportSize",0);g(this,"contentSize",0);g(this,"scrollOffset",0);g(this,"isDragging",!1);g(this,"dragStartClient",0);g(this,"dragStartOffset",0);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleStageMouseDown",e=>{var r;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((r=e.target)==null?void 0:r.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});g(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});g(this,"handleStageMouseEnter",()=>{this.updateCursor()});g(this,"handleStageMouseMove",()=>{this.updateCursor()});g(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new Z.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new Z.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=de.createRect(0,0,0,0,Lt.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||Lt.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Lt.border,1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(e){const i=(this.orientation==="horizontal"?e.clientX:e.clientY)-this.dragStartClient,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),a=Math.max(1,r-n),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/a*o;this.emitScrollChange(l)}jumpToPointer(e){const t=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?e-t.left:e-t.top,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),a=Math.max(1,r-n),o=Math.max(0,Math.min(r,i-this.leadingInset)),l=Math.max(0,Math.min(a,o-n/2)),c=this.getMaxScrollOffset(),h=a<=0?0:l/a*c;this.emitScrollChange(h)}emitScrollChange(e){const t=this.clampScrollOffset(e);this.scrollOffset=t,this.render(),this.onScrollChange(t)}render(){const e=Math.max(0,this.container.clientWidth),t=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(e),this.stage.height(t),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(e),this.hitAreaRect.height(t),this.thumbRect.fill(this.theme.scrollbarThumb||Lt.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Lt.border);const r=this.getAvailableTrackSize();if(r<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const n=this.getThumbSize(r),a=this.leadingInset+this.getThumbPosition(r,n);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(a),this.thumbRect.y(0),this.thumbRect.width(n),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(a),this.thumbRect.width(e),this.thumbRect.height(n)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const r=Math.max(1,e-t);return this.scrollOffset/i*r}}const Gp=48;function Hp(s,e,t){return U.timeToPixels(s,e)-t+pe}function zp(s,e,t){const i=Math.max(0,t-e);return Math.max(0,Math.min(i,s))}function $p(s){const{time:e,zoom:t,scrollLeft:i,viewportWidth:r,contentWidth:n,margin:a=Gp}=s;if(r<=0||Math.max(0,n-r)<=0)return null;const l=Hp(e,t,i),c=r-a;if(l>=a&&l<=c)return null;const h=U.timeToPixels(e,t),d=l<a?h+pe-a:h+pe-c,u=zp(d,r,n);return Math.abs(u-i)<=.5?null:u}class Zs{constructor(){g(this,"entries",new Map)}register(e,t){const i=this.entries.get(e);i&&i.destroy(),this.entries.set(e,{id:e,destroy:t})}unregister(e){this.entries.delete(e)}destroyAll(){for(const e of this.entries.values())e.destroy();this.entries.clear()}}const Vp="@linker-design-plus/timeline-track",Up="2.1.4",Yt={name:Vp,version:Up},Wp=1,Yp=2,Xp=250,qp=750,jp=1500;function Js(s){return s==null?s:JSON.parse(JSON.stringify(s))}function Kp(s,e){return s.length!==e.length?!1:s.every((t,i)=>t===e[i])}function Zp(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class Jp{constructor(e={}){g(this,"timeline",null);g(this,"tracks",[]);g(this,"trackManager");g(this,"trackInfoPanelController");g(this,"playhead",null);g(this,"history");g(this,"config");g(this,"eventDispatcher");g(this,"animationFrameId",null);g(this,"lastUpdateTime",0);g(this,"isInitialized",!1);g(this,"stage",null);g(this,"headerStage",null);g(this,"headerLayer",null);g(this,"backgroundLayer",null);g(this,"trackLayer",null);g(this,"dragOverlayLayer",null);g(this,"snapGuideLayer",null);g(this,"selectionBoxLayer",null);g(this,"selectionBoxRect",null);g(this,"isBoxSelecting",!1);g(this,"boxSelectStartX",0);g(this,"boxSelectStartY",0);g(this,"resizeObserver",null);g(this,"rootContainer",null);g(this,"layout",null);g(this,"bodyBackgroundRect",null);g(this,"snapGuideLine",null);g(this,"trackInsertionPreviewLine",null);g(this,"trackInsertionPreviewY",null);g(this,"snapGuideTime",null);g(this,"horizontalScrollbar",null);g(this,"verticalScrollbar",null);g(this,"isExecutingHistoryAction",!1);g(this,"lastTrackDuration",0);g(this,"lastReportedTrackDuration",0);g(this,"thumbnailProvider",null);g(this,"thumbnailProviderVersion",0);g(this,"clipThumbnailLoadStates",new Map);g(this,"sourceMediaRegistry",new Or);g(this,"canPlay",!1);g(this,"sourceLoadingCount",0);g(this,"timelineStore");g(this,"timelineCommands");g(this,"timelineHistoryRecorder");g(this,"timelinePresentationAdapter");g(this,"timelineTrackBridge");g(this,"timelinePlaybackResolver");g(this,"previewRuntimeController");g(this,"previewStateController");g(this,"previewPlaybackSuspendedByBuffering",!1);g(this,"previewPlaybackAutoResume",!1);g(this,"lastSelectedClipId",null);g(this,"previewAspectRatio",{...Be});g(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});g(this,"stageMouseDownListener",null);g(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});g(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});g(this,"keyboardShortcutsController",null);g(this,"clipClipboard",null);g(this,"mountManager",new Zs);g(this,"pendingDraftData",null);g(this,"selectionStore",new Co);g(this,"multiDragSession",null);g(this,"clipRemovalBatchDepth",0);g(this,"splitOperationDepth",0);g(this,"diagnostics");g(this,"previewRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});g(this,"failedPreviewClipIds");g(this,"previewActiveClipIds",[]);g(this,"previewClockSeekAlignmentTargetTime",null);g(this,"previewClockSeekAlignmentDeadlineMs",0);g(this,"playbackAttemptId",this.createPlaybackAttemptId("initial"));g(this,"lastPreviewSyncedPlayState",null);g(this,"lastPreviewSyncSignature",null);g(this,"lastSteadyPlaybackPreviewSyncAt",0);g(this,"previewSyncInteractionMode",null);g(this,"resourceCacheManager");g(this,"voiceLinkedTextRegenerationTimer",null);g(this,"pendingVoiceLinkedTextRegeneration",null);g(this,"historyRecordingSuppressionDepth",0);g(this,"activeStructureSession",null);g(this,"structureSessionDepth",0);g(this,"preserveEmptyTracksDepth",0);g(this,"playbackViewportFollowSuspended",!1);g(this,"isProgrammaticScrollChange",!1);this.config={duration:e.duration||Qt,zoom:e.zoom||Me.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:qi(e.theme),timeScaleHeight:e.timeScaleHeight,diagnostics:e.diagnostics,speed:e.speed||1,dragActivationThreshold:e.dragActivationThreshold??4,enableClipSnap:e.enableClipSnap??!1,enablePrimaryTrackMagnet:e.enablePrimaryTrackMagnet??!0,clipSnapThreshold:e.clipSnapThreshold??8,thumbnailProvider:e.thumbnailProvider,previewBackend:e.previewBackend??"dom",previewSourceResolver:e.previewSourceResolver,resourceCache:e.resourceCache,textPreviewFont:e.textPreviewFont??null,keyboardShortcuts:e.keyboardShortcuts,playbackViewportFollow:e.playbackViewportFollow??!0},this.diagnostics=new qa(this.config.diagnostics),this.resourceCacheManager=this.config.resourceCache?new Mp({options:this.config.resourceCache,onEvent:(t,i)=>{this.emitDiagnostic({...this.buildPreviewDiagnosticsContext(),severity:t.endsWith(".failed")||t.endsWith(".fallback")?"warn":"info",category:"resource",eventName:t,message:t,extra:i})}}):null,this.diagnostics.startSession({packageName:Yt.name,packageVersion:Yt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.config.previewBackend}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new ap,this.eventDispatcher=new Hs({can_play_change:()=>({canPlay:this.canPlay}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new an(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Is(this.history),this.trackManager=new vo,this.timelineStore=new js({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new _s(this.timelineStore),this.timelinePresentationAdapter=new Vs,this.timelineTrackBridge=new qs({onClipUpdate:(t,i,r)=>this.handleClipUpdate(t,i,r),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.handleTimeChange.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onPrimaryTrackMagnetMove:this.handlePrimaryTrackMagnetMove.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),e.draftData&&(this.pendingDraftData=e.draftData),this.config.container&&this.init(this.config.container)}createPlaybackAttemptId(e){return`playback-${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}refreshPlaybackAttempt(e){this.playbackAttemptId=this.createPlaybackAttemptId(e)}emitDiagnostic(e){var t;(t=this.diagnostics)==null||t.emit(e)}buildDiagnosticsRuntimeState(){var e,t;return{currentTimeMs:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),pendingMode:((e=this.pendingPreviewState)==null?void 0:e.mode)??null,sourceLoadingPending:this.getSourceLoadingState().pending,loadingStatus:this.getPreviewLoadingState().status,loadingReason:this.getPreviewLoadingState().reason,isLoading:this.getPreviewLoadingState().isLoading,runtimePhase:((t=this.previewRuntimeState)==null?void 0:t.phase)??"idle",selectedClipId:this.getPrimarySelectedClipId(),activeClipIds:Array.isArray(this.previewActiveClipIds)?[...this.previewActiveClipIds]:[],previewAspectRatio:this.getPreviewAspectRatio()}}buildPreviewDiagnosticsContext(){return{playbackAttemptId:this.playbackAttemptId,previewBackend:this.getPreviewBackendType(),runtimeState:this.buildDiagnosticsRuntimeState()}}getTimelineStore(){var e,t,i,r,n;if(!this.timelineStore){const a=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,c=((r=this.config)==null?void 0:r.zoom)||Me.MEDIUM,h=((n=this.config)==null?void 0:n.duration)||Qt;this.timelineStore=new js({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new _s(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Lp(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new Vs),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new qs({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.handleTimeChange.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onPrimaryTrackMagnetMove:this.handlePrimaryTrackMagnetMove.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 zu),this.timelinePlaybackResolver}get previewSession(){return this.getPreviewRuntimeController().previewSession}set previewSession(e){this.getPreviewRuntimeController().previewSession=e}get previewMountContainer(){return this.getPreviewRuntimeController().previewMountContainer}set previewMountContainer(e){this.getPreviewRuntimeController().previewMountContainer=e}get resolvedPreviewBackend(){return this.getPreviewRuntimeController().resolvedPreviewBackend}set resolvedPreviewBackend(e){this.getPreviewRuntimeController().resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this.getPreviewRuntimeController().runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this.getPreviewRuntimeController().runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this.getPreviewRuntimeController().activePreviewCallbackToken}set activePreviewCallbackToken(e){this.getPreviewRuntimeController().activePreviewCallbackToken=e}getPreviewLoadingState(){return this.getPreviewStateController().previewLoadingState}get pendingPreviewState(){return this.getPreviewStateController().pendingPreviewState}set pendingPreviewState(e){this.getPreviewStateController().pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this.getPreviewStateController().nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this.getPreviewStateController().nextPendingPreviewSyncRequestId=e}getPreviewStateController(){return this.previewStateController||(this.previewStateController=new Uu({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitLoadingStateChange:e=>{this.syncPlaybackClockToPreviewLoadingState(e),this.emitEvent("loading_state_change",e)},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new $u({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Bu({callbacks:t,diagnostics:this.diagnostics,getDiagnosticsContext:()=>this.buildPreviewDiagnosticsContext(),previewSourceResolver:this.config.previewSourceResolver,resourceCacheManager:this.resourceCacheManager,textPreviewFont:this.config.textPreviewFont,sourceMediaRegistry:this.sourceMediaRegistry}),resolveConfiguredBackend:e=>e||Ou(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewRuntimeState=t,this.syncTimelineClipMediaStateFromPreview(t),this.getPreviewStateController().handleRuntimeStateChange(t),this.handlePreviewClockStateChange(t.clock))},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=je(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onPreviewClipSelect:t=>{this.isActivePreviewCallbackToken(e)&&this.selectClip(t)},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onTextFontSizeCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextFontSize(t,i)},onTextRotationCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextRotation(t,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(e)&&this.retryPendingPreview()},onPauseIfPlaying:()=>{this.isActivePreviewCallbackToken(e)&&this.getPlayStateState()==="playing"&&this.pause()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Hs({can_play_change:()=>({canPlay:this.canPlay??!1}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new an(()=>{},()=>{})),this.timelineHistoryRecorder=new Is(this.history)),this.timelineHistoryRecorder}withStructureSession(e){const t=this.activeStructureSession;if(t)return e(t);const i=new ip({trackCollection:this.getTrackCollection(),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),setPrimaryTrackMagnetEnabled:this.setPrimaryTrackMagnetEnabledFromHistory.bind(this),loadClipThumbnails:this.loadClipThumbnails.bind(this),addClipToTrack:(n,a)=>this.getTrackCollection().addClipToTrack(n,a),removeClip:n=>{const a=this.getTrackCollection();if(typeof a.removeClip=="function"){a.removeClip(n);return}this.tracks.forEach(o=>{var l;return(l=o.removeClip)==null?void 0:l.call(o,n)})},removeClipFromTrack:(n,a)=>this.getTrackCollection().removeClipFromTrack(n,a),updateClip:(n,a)=>{const o=this.getTrackCollection();if(typeof o.updateClip=="function"){o.updateClip(n,a);return}this.tracks.forEach(l=>{var c;return(c=l.updateClip)==null?void 0:c.call(l,n,a)})},moveClipToTrack:(n,a,o)=>{const l=this.getTrackCollection();if(typeof l.moveClipToTrack=="function")return l.moveClipToTrack(n,a,o);const c=l.findById(a),h=l.findById(o);return!(c!=null&&c.removeClip)||!(h!=null&&h.addClip)?!1:(c.removeClip(n.id),h.addClip(n),!0)},getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),onCommit:this.applyStructureSessionSummary.bind(this)});this.activeStructureSession=i,this.structureSessionDepth=(this.structureSessionDepth??0)+1;const r=()=>{this.structureSessionDepth=Math.max(0,(this.structureSessionDepth??1)-1),this.activeStructureSession=null,i.commit()};try{const n=e(i);return n instanceof Promise?n.finally(r):(r(),n)}catch(n){throw r(),n}}getActiveStructureSession(){return this.activeStructureSession??null}withPreservedEmptyTracks(e){this.preserveEmptyTracksDepth+=1;const t=()=>{this.preserveEmptyTracksDepth=Math.max(0,this.preserveEmptyTracksDepth-1)};try{const i=e();return i instanceof Promise?i.finally(t):(t(),i)}catch(i){throw t(),i}}applyStructureSessionSummary(e){var i;((e.cleanupEmptyTracks&&this.preserveEmptyTracksDepth===0?this.removeEmptyTracksFromStructure():!1)||e.trackLayoutDirty)&&this.updateAllTrackPositions(),e.durationDirty&&this.checkTrackDurationChange(),e.canPlayDirty&&this.updateCanPlayState(),e.events.forEach(r=>{this.emitEvent(r.type,r.payload)}),e.selectionDirty&&(this.notifySelectionChange(),this.emitSelectionChangeEvent(),this.emitSelectedClipChangeIfNeeded()),e.trackInfoDirty&&this.updateTrackInfoPanel(),e.stageDirty&&((i=this.stage)==null||i.batchDraw()),e.previewDirty&&this.syncPreviewSession()}withHistoryBoundary(e,t,i){if(e==="transaction"){const a=t,o=i;if(!o)throw new Error("transaction history boundary requires a callback");return this.getTimelineHistoryRecorder().withTransaction(a,o)}const r=typeof t=="function"?t:i;if(!r)throw new Error(`history boundary "${e}" requires a callback`);if(e==="record")return r();if(e==="suppressed"||e==="reset"){this.historyRecordingSuppressionDepth=(this.historyRecordingSuppressionDepth??0)+1;try{const a=r();return a instanceof Promise?a.then(o=>(this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),o),o=>{throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),o}):(this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),a)}catch(a){throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),a}}const n=this.isExecutingHistoryAction??!1;this.isExecutingHistoryAction=!0;try{const a=r();return a instanceof Promise?a.then(o=>(this.isExecutingHistoryAction=n,o),o=>{throw this.isExecutingHistoryAction=n,o}):(this.isExecutingHistoryAction=n,a)}catch(a){throw this.isExecutingHistoryAction=n,a}}shouldSkipHistoryRecording(){return this.isExecutingHistoryAction||this.historyRecordingSuppressionDepth>0}withHistoryTransaction(e,t){return this.withHistoryBoundary("transaction",e,t)}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:Qt,zoom:Me.MEDIUM,currentTime:0,playState:"paused",theme:qi(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,enablePrimaryTrackMagnet:!0,clipSnapThreshold:8,previewBackend:"dom",textPreviewFont:null,playbackViewportFollow:!0}),this.config}isPlaybackViewportFollowEnabled(){return this.ensureConfigState().playbackViewportFollow!==!1}suspendPlaybackViewportFollowIfUserScrolling(){this.getPlayStateState()==="playing"&&!this.isProgrammaticScrollChange&&(this.playbackViewportFollowSuspended=!0)}runProgrammaticScrollChange(e){this.isProgrammaticScrollChange=!0;try{e()}finally{this.isProgrammaticScrollChange=!1}}followPlaybackViewportIfNeeded(e){if(!this.isPlaybackViewportFollowEnabled()||this.getPlayStateState()!=="playing"||this.playbackViewportFollowSuspended)return;const t=this.getViewportWidth(),i=this.getZoomState(),r=this.getScrollLeftState(),n=this.getHorizontalContentWidth(),a=$p({time:e,zoom:i,scrollLeft:r,viewportWidth:t,contentWidth:n});if(a!==null){this.isProgrammaticScrollChange=!0;try{this.syncScrollLeft(a)}finally{this.isProgrammaticScrollChange=!1}}}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(e){this.getTimelineStore().setPlayState(e),this.ensureConfigState().playState=e}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(e){this.getTimelineStore().setDuration(e),this.ensureConfigState().duration=e}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(e){this.getTimelineStore().setScrollLeft(e)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(e){this.getTimelineStore().setScrollTop(e)}setViewportMetrics(e,t,i){const r=this.getTimelineStore();r.setViewportWidth(e),r.setViewportHeight(t),r.setContentHeight(i)}syncCurrentTimeToScene(e){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncZoomToScene(e){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncScrollTopPresentation(e){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,e)}refreshScrollbarMetrics(){var i,r,n,a;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(r=this.verticalScrollbar)==null||r.resize(),(n=this.horizontalScrollbar)==null||n.setViewportMetrics(e,this.getHorizontalContentWidth()),(a=this.verticalScrollbar)==null||a.setViewportMetrics(t,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientWidth)||0}getViewportHeight(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return U.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(e){const t=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(t,e))}clampScrollTop(e){const t=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(t,e))}syncScrollLeft(e){var i,r;const t=this.clampScrollLeft(e);this.setScrollLeftState(t),(i=this.timeline)==null||i.setScrollLeft(t),(r=this.horizontalScrollbar)==null||r.setScrollLeft(t),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),t),this.refreshSnapGuideLine()}syncScrollTop(e){var i;const t=this.clampScrollTop(e);this.setScrollTopState(t),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-t)>.5&&(this.layout.bodyViewport.scrollTop=t),this.syncScrollTopPresentation(t)}getResolvedTracksSnapshot(){const e=this.getTrackCollection();return this.trackManager.getTracks().map(t=>{const i=e.findById(t.id);return{...t,clips:i?i.getClips():[...t.clips]}})}getTracksSortedByOrder(){const e=this.getTrackCollection();return this.trackManager.getTracks().slice().sort((t,i)=>t.order-i.order).map(t=>e.findById(t.id)).filter(t=>t!==null)}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(e=>({id:e.id,type:e.type,order:e.order,isMuted:e.isMuted??!1,clips:e.clips}))}buildPlaybackPlan(e=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),e)}buildPreviewPlaybackPlan(e,t=this.getCurrentTimeState()){const i=this.buildPlaybackPlan(t);if(e!=="paused"||i.activeClips.length>0)return i;let r;try{r=this.getClips()}catch{return i}if(r.length===0)return i;const n=kt(r);return n<=0||t!==n?i:this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),t,{includeEndedClipsAtTime:!0})}playbackPlanHasActiveVideoClip(e){return e.activeClips.some(t=>t.trackType==="video")}hasActiveTimelineVideoClip(e=this.getCurrentTimeState()){return this.playbackPlanHasActiveVideoClip(this.buildPlaybackPlan(e))}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((a,o)=>a.order-o.order);let i=null,r=null,n=Number.POSITIVE_INFINITY;for(const a of t){if(a.type!=="video")continue;const o=[...a.clips].sort((l,c)=>l.startTime-c.startTime);for(const l of o){const c={trackId:a.id,trackType:a.type,trackOrder:a.order,clip:l,mediaTime:l.startTimeAtSource,muted:(a.isMuted??!1)||(l.isMuted??!1),kind:a.type,hasVisual:!0,hasAudio:!0};i||(i=c);const h=e.get(l.id);h===void 0||h>=n||(r=c,n=h)}}return r||i}registerPreviewAutoAspectRatioClip(e){const t=this,i=this.getPreviewAutoAspectRatioClipOrderMap();e.type!=="video"||i.has(e.id)||(i.set(e.id,this.getNextPreviewAutoAspectRatioOrder()),t.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}buildPreviewSyncSignature(e){var i,r;const t=n=>[n.trackId,n.clip.id,n.trackType,n.trackOrder,n.clip.startTime,n.clip.endTime,n.clip.startTimeAtSource,n.muted?1:0,n.clip.volume??""].join(":");return JSON.stringify({active:e.playbackPlan.activeClips.map(t),next:e.playbackPlan.nextClips.map(t),firstVideoClipId:((i=e.playbackPlan.firstVideoClip)==null?void 0:i.clip.id)??null,autoAspectRatioClipId:((r=e.autoAspectRatioClip)==null?void 0:r.clip.id)??null,previewAspectRatio:e.previewAspectRatio,playState:e.targetPlayState,requestedPlayState:e.requestedPlayState,speed:e.speed,interactionMode:e.interactionMode,primarySelectedClipId:e.primarySelectedClipId})}shouldSkipSteadyPlaybackPreviewSync(e,t,i){return t!=="playing"||i!=="steady"||this.pendingPreviewState||this.getPreviewLoadingState().isLoading||this.lastPreviewSyncedPlayState!=="playing"||this.lastPreviewSyncSignature!==e?!1:Date.now()-this.lastSteadyPlaybackPreviewSyncAt<Xp}syncPreviewSession(e){var d,u,p,f;if(!((d=this.previewSession)!=null&&d.hasPreview())){this.previewSyncInteractionMode=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0;return}const t=this.resolvePreviewSyncPlayState(e),i=this.resolvePreviewRequestedPlayState(t),r=this.buildPreviewPlaybackPlan(t);this.previewActiveClipIds=r.activeClips.map(m=>m.clip.id);const n=this.getAutoAspectRatioClip(),a=je(this.previewAspectRatio),o=this.getSpeedState(),l=this.previewSyncInteractionMode??((u=this.pendingPreviewState)==null?void 0:u.mode)??"steady",c=this.getPrimarySelectedClipId(),h=this.buildPreviewSyncSignature({playbackPlan:r,autoAspectRatioClip:n,previewAspectRatio:a,targetPlayState:t,requestedPlayState:i,speed:o,interactionMode:l,primarySelectedClipId:c});if(this.shouldSkipSteadyPlaybackPreviewSync(h,t,l)){this.previewSyncInteractionMode=null;return}this.previewAspectRatio=a,this.previewSession.applyAspectRatio(a),(f=(p=this.previewSession).setPendingState)==null||f.call(p,this.buildPreviewPendingState()),this.previewSession.sync({...r,autoAspectRatioClip:n,currentTime:this.getCurrentTimeState(),playState:t,...i!==t?{requestedPlayState:i}:{},speed:o,interactionMode:l,primarySelectedClipId:c,...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),this.previewSyncInteractionMode=null,this.lastPreviewSyncedPlayState=t,this.lastPreviewSyncSignature=h,this.lastSteadyPlaybackPreviewSyncAt=t==="playing"&&l==="steady"?Date.now():0}resolvePreviewSyncPlayState(e){return e||this.getPlayStateState()}resolvePreviewRequestedPlayState(e){var t;return((t=this.pendingPreviewState)==null?void 0:t.mode)==="seek"&&this.pendingPreviewState.resumePlayOnReady&&e==="paused"?"playing":e}syncPreviewPlaybackStateIfNeeded(e){this.lastPreviewSyncedPlayState!==e&&this.syncPreviewSession(e)}shouldUsePreviewClockPlayback(){var e;try{return!!((e=this.previewSession)!=null&&e.hasPreview())&&this.hasActiveTimelineVideoClip()&&!this.pendingPreviewState}catch{return!1}}handlePreviewClockStateChange(e){if(!(!e||this.getPlayStateState()!=="playing")){if(!this.shouldUsePreviewClockPlayback()){this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState());return}if(this.isPreviewClockForCurrentActiveClip(e)&&!this.shouldIgnorePreviewClockUntilSeekTargetAligned(e)){if(e.status!=="running"||e.timelineTime===null){this.cancelPlaybackAnimationFrame(),this.shouldCommitUnavailablePreviewClock(e)&&this.commitPlaybackTimeFromPreviewClock(e);return}this.commitPlaybackTimeFromPreviewClock(e)}}}isPreviewClockForCurrentActiveClip(e){return!e.clipId||!Array.isArray(this.previewActiveClipIds)?!0:this.previewActiveClipIds.includes(e.clipId)}shouldCommitUnavailablePreviewClock(e){return e.status!=="unavailable"||e.timelineTime===null?!1:this.isPreviewClockForCurrentActiveClip(e)}shouldIgnorePreviewClockUntilSeekTargetAligned(e){return this.previewClockSeekAlignmentTargetTime==null||e.timelineTime===null?!1:Date.now()>this.previewClockSeekAlignmentDeadlineMs?(this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,!1):Math.abs(e.timelineTime-this.previewClockSeekAlignmentTargetTime)<=qp?(this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,!1):!0}commitPlaybackTimeFromPreviewClock(e){if(e.timelineTime===null)return;const t=this.clampPlaybackSeekTime(e.timelineTime),i=this.getTimelineCommands().setCurrentTime(t);if(!i.changed){this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(i.nextValue,e);return}const r=i.nextValue;this.ensureConfigState().currentTime=r,this.syncCurrentTimeToScene(r),this.followPlaybackViewportIfNeeded(r),this.emitEvent("time_change",{time:r}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(r,e)}syncPreviewAfterPreviewClockCommitIfNeeded(e,t){if(this.getPlayStateState()!=="playing"||this.pendingPreviewState)return;const i=this.buildPlaybackPlan(e),r=i.activeClips.map(n=>n.clip.id);if(!Kp(r,this.previewActiveClipIds)){this.syncPreviewSession(),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i);return}t.clipId&&(r.includes(t.clipId)||this.syncPreviewSession()),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i)}resumeWallClockPlaybackIfPreviewClockUnavailable(e,t=this.buildPlaybackPlan(e)){this.getPlayStateState()!=="playing"||this.pendingPreviewState||this.animationFrameId||this.playbackPlanHasActiveVideoClip(t)||!this.canPlay||(this.lastUpdateTime=Date.now(),this.animate())}beginPendingPreview(e,t="seek"){var r,n,a,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;if(!this.hasActiveTimelineVideoClip(e)){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();return}(t!=="scrub"||((n=this.pendingPreviewState)==null?void 0:n.mode)!=="scrub")&&this.refreshPlaybackAttempt(t);const i=((a=this.pendingPreviewState)==null?void 0:a.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPreviewStateController().beginPendingPreview(e,t,i),this.getPlayStateState()==="playing"&&this.pause(),t!=="scrub"&&this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"pending-preview.begin",message:"Pending preview started",playbackAttemptId:this.playbackAttemptId,syncRequestId:((o=this.pendingPreviewState)==null?void 0:o.syncRequestId)??null,runtimeState:{...this.buildDiagnosticsRuntimeState(),pendingMode:t},extra:{targetTime:e,resumePlayOnReady:i}})}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState(),this.previewActiveClipIds=[],this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,this.lastPreviewSyncedPlayState=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0,this.previewSyncInteractionMode=null,this.previewRuntimeState={phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},errorMessage:null,slots:[]}}destroyPreviewSession(e=!1){this.getPreviewRuntimeController().destroyPreviewSession(e),this.lastPreviewSyncedPlayState=null,this.resetPreviewRuntimeState()}retryPendingPreview(){var e;this.refreshPlaybackAttempt("retry"),this.getPreviewStateController().retryPendingPreview(),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"pending-preview.retry",message:"Pending preview retried",playbackAttemptId:this.playbackAttemptId,syncRequestId:((e=this.pendingPreviewState)==null?void 0:e.syncRequestId)??null,runtimeState:this.buildDiagnosticsRuntimeState()})}handlePreviewBackendRuntimeError(){this.emitDiagnostic({severity:"error",category:"runtime",eventName:"preview.runtime.error",message:"Preview backend runtime error",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState(),extra:{resolvedBackend:this.getPreviewBackendType()}}),this.clearPendingPreviewState(),this.resetPreviewRuntimeState();const e=this.getPreviewRuntimeController().fallbackToDom(je(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,r,n,a,o,l,c;if(this.isInitialized){O.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=kd(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:vi,scrollbarSize:rn}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(r=(i=this.layout.bodyCanvasHost).addEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(a=(n=this.rootContainer)==null?void 0:n.addEventListener)==null||a.call(n,"wheel",this.rootWheelListener,{passive:!1}),this.initKeyboardShortcuts(),this.headerStage=new Z.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new Z.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new Z.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new Z.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new Z.Layer({name:"trackLayer"}),this.dragOverlayLayer=new Z.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new Z.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new Z.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const t=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(t&&(this.stageMouseDownListener||(this.stageMouseDownListener=h=>{this.handleStageMouseDown(h)}),t.addEventListener("mousedown",this.stageMouseDownListener)),this.timeline=new Np(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new cn(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 Ks({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:pe,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Ks({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:h=>{this.syncScrollTop(h)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(e),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(c=this.stage)==null||c.batchDraw(),this.pendingDraftData){const h=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(h).catch(d=>{O.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,n,a){var u,p,f,m;if(!this.trackLayer)return O.error("TimelineManager","Track layer not initialized"),"";const o=this.trackManager.createTrack(e,t,i,r,n,a),l=o.id,c=Ae(e),h=this.calculateTrackY(l),d=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:l,clips:[],role:o.role},trackType:e,zoom:this.getZoomState(),trackY:h,trackHeight:c,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(u=d.setSnapTargetResolver)==null||u.call(d,()=>this.getClips()),(p=d.setDragOverlayLayer)==null||p.call(d,this.dragOverlayLayer),this.getTrackCollection().add(d),this.getActiveStructureSession()?(f=this.getActiveStructureSession())==null||f.markTrackLayoutMutation():(this.updateAllTrackPositions(),(m=this.stage)==null||m.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),l}removeTrack(e){var r,n,a,o,l;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return O.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return O.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((a=(n=t.getTrackGroup)==null?void 0:n.call(t))==null||a.destroy(),this.getTrackCollection().removeById(e),this.getActiveStructureSession()?(o=this.getActiveStructureSession())==null||o.markTrackLayoutMutation():(this.updateAllTrackPositions(),(l=this.stage)==null||l.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession())),i}renameTrack(e,t){var r,n;if(!((r=this.trackManager)!=null&&r.renameTrack))return!1;const i=this.trackManager.renameTrack(e,t);return i&&(this.getActiveStructureSession()?(n=this.getActiveStructureSession())==null||n.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}getTracks(){return this.getResolvedTracksSnapshot()}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){var r,n;if(!((r=this.trackManager)!=null&&r.muteTrack))return!1;const i=this.trackManager.muteTrack(e,t);return i&&(this.getActiveStructureSession()?(n=this.getActiveStructureSession())==null||n.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return Ut(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return Ps(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=_d(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const r of e){const n=this.getTrackCollection().findById(r.trackId);n&&((t=n.setTrackY)==null||t.call(n,r.y),(i=n.setTrackHeight)==null||i.call(n,r.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}removeEmptyTracksFromStructure(){var i,r,n;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return!1;const e=this.getTrackCollection();if(typeof e.removeEmptyNonPrimaryTracks!="function")return!1;const t=e.removeEmptyNonPrimaryTracks();if(t.length===0)return!1;for(const a of t){const o=(i=a.getId)==null?void 0:i.call(a);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(n=(r=a.getTrackGroup)==null?void 0:r.call(a))==null||n.destroy(),this.getTrackCollection().removeById(o))}return!0}cleanupEmptyTracks(){var e;this.clipRemovalBatchDepth>0||this.getActiveStructureSession()||this.removeEmptyTracksFromStructure()&&(this.updateAllTrackPositions(),(e=this.stage)==null||e.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession())}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDropPreview)==null?void 0:t.call(e)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(e,t){this.showClipDropPreviews(new Map([[t,[e]]]))}showClipDropPreviews(e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(t=>{var n,a,o,l;const i=(n=t.getId)==null?void 0:n.call(t),r=i?e.get(i)??[]:[];if(r.length>0){r.length===1?(a=t.showClipDropPreview)==null||a.call(t,r[0]):(o=t.showClipDropPreviews)==null||o.call(t,r);return}(l=t.clearClipDropPreview)==null||l.call(t)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const e=de.createLine([0,0,0,0],this.getSnapGuideAccentColor(),2);e.name("timeline-track-insertion-preview-line"),e.dash([8,4]),e.visible(!1),e.listening(!1),this.snapGuideLayer.add(e),this.trackInsertionPreviewLine=e}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(e=!0){var i,r,n;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),e&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const t=((r=this.stage)==null?void 0:r.width())??0;this.trackInsertionPreviewLine.stroke(this.getSnapGuideAccentColor()),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,t,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(t>0),this.trackInsertionPreviewLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(n=>{var a;return(a=n.clearClipDropPreview)==null?void 0:a.call(n)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const r=this.trackManager.getTracks(),n=r.find(c=>c.role==="primary"),a=r.find(c=>c.type===e),o=[...r].reverse().find(c=>c.type===e);if((t==="before_track"||t==="after_track")&&i){const c=r.find(h=>h.id===i);if(c){const h=Ut(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+Ae(c.type)}}if(t==="top_of_type_region"&&a)return Ut(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Ut(r,o.id,this.getTrackContentTopOffset())+Ae(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():Ps(r,this.getTrackContentTopOffset());const l=Ut(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+Ae(n.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),r=Math.max(i,t),n=this.clampScrollLeft(this.getScrollLeftState()),a=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(e,t,r),this.headerStage.width(e),this.timeline.resize(e),this.stage.width(e),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${r}px`,this.renderBodyBackground(e,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+t),this.refreshScrollbarMetrics(),this.syncScrollLeft(n),this.syncScrollTop(a),this.stage.batchDraw()}renderBodyBackground(e,t,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(e),this.bodyBackgroundRect.height(t),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const r=new Z.Rect({x:0,y:0,width:e,height:t,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});r.on("click",n=>{this.handleBodyBackgroundClick(n.evt.offsetX)}),this.bodyBackgroundRect=r,this.backgroundLayer.add(r),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(e){const t=U.pixelsToTime(e-pe+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,t))}handleBodyCanvasHostClick(e){if(!this.layout||e.target!==this.layout.bodyCanvasHost)return;const t=this.layout.bodyCanvasHost.getBoundingClientRect(),i=e.clientX-t.left;this.handleBodyBackgroundClick(i)}getSnapGuideAccentColor(){return this.config.theme.snapGuideLineColor||te.snapGuideLineColor}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=de.createLine([0,0,0,this.calculateTotalHeight()],this.getSnapGuideAccentColor(),e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var r,n;if(!this.snapGuideLine)return;const t=this.config.theme;if(this.snapGuideLine.stroke(this.getSnapGuideAccentColor()),this.snapGuideLine.strokeWidth(t.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),e&&((r=this.snapGuideLayer)==null||r.batchDraw());return}const i=fe(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const n=this.getPrimaryWheelDelta(t,i);if(n===0)return;e.preventDefault(),this.handleWheelZoom(n,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const n=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(n===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+n);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===Wp)return e*16;if(t===Yp){const r=i==="x"?this.getViewportWidth():this.getViewportHeight();return e*(r||1)}return e}getPrimaryWheelDelta(e,t){return Math.abs(t)>=Math.abs(e)?t:e}isHorizontalWheelGesture(e,t){const i=Math.abs(e);if(i<.5)return!1;const r=Math.abs(t);return r<.5?!0:i>r*1.2}getHorizontalScrollDelta(e,t,i){return i&&Math.abs(t)>=Math.abs(e)?t:e}handleWheelZoom(e,t){const i=this.getZoomState(),r=Math.exp(-e*Fr.SENSITIVITY_FACTOR),n=Math.max(Me.MIN,Math.min(Me.MAX,i*r));Math.abs(n-i)<Fr.CONVERGENCE_THRESHOLD||this.setZoomCenteredOnTimelinePointer(n,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var n;const t=(n=this.layout)==null?void 0:n.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const r=e-t.left;return Math.max(0,Math.min(i,r))}play(){if(this.getPlayStateState()==="playing")return;if(this.pendingPreviewState){this.emitDiagnostic({severity:"warn",category:"ui-trigger",eventName:"play.blocked.pending-preview",message:"Play blocked by pending preview state",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()});return}if(!this.canPlay){const t=this.getClips();if(t.length>0&&this.getCurrentTime()>=kt(t)){if(this.setCurrentTime(0),!this.canPlay)return}else{O.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}}this.refreshPlaybackAttempt("play"),this.playbackViewportFollowSuspended=!1,this.setPlayStateState("playing"),this.followPlaybackViewportIfNeeded(this.getCurrentTimeState()),this.lastUpdateTime=Date.now();const e=this.shouldUsePreviewClockPlayback();e?(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame()):this.getPreviewLoadingState().isLoading?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitPlayStateChangeEvent(),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"play.started",message:"Playback started",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}),this.syncPreviewSession(!e&&this.getPreviewLoadingState().isLoading?"paused":void 0)}pause(){if(this.getPlayStateState()==="paused"){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused");return}this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.emitPlayStateChangeEvent(),this.syncPreviewSession()}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused"){this.animationFrameId=null;return}if(this.shouldUsePreviewClockPlayback()){this.animationFrameId=null;return}if(this.getPreviewLoadingState().status==="loading"){!this.previewPlaybackSuspendedByBuffering&&this.getPlayStateState()==="playing"&&this.suspendPlaybackForMediaPending(),this.animationFrameId=null;return}if(this.previewPlaybackSuspendedByBuffering){this.animationFrameId=null;return}const e=Date.now(),t=e-this.lastUpdateTime;this.lastUpdateTime=e;const i=this.getCurrentTimeState()+t*this.getSpeedState();if(this.setCurrentTime(i),this.getPlayStateState()==="paused"){this.animationFrameId=null;return}this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}cancelPlaybackAnimationFrame(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}emitPlayStateChangeEvent(){this.emitEvent("play_state_change",{playState:this.getPlayStateState()})}suspendPlaybackForMediaPending(){this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering=!0,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused")}resumePlaybackAfterMediaPending(){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.syncPreviewPlaybackStateIfNeeded("playing"),this.lastUpdateTime=Date.now(),this.animationFrameId||this.animate()}shouldSuspendPreviewPlaybackForLoadingState(e){return e.status==="loading"}syncPlaybackClockToPreviewLoadingState(e){if(this.shouldUsePreviewClockPlayback()){this.cancelPlaybackAnimationFrame(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,e.status==="failed"&&this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.emitPlayStateChangeEvent());return}if(this.shouldSuspendPreviewPlaybackForLoadingState(e)){if(this.previewPlaybackSuspendedByBuffering){this.syncPreviewPlaybackStateIfNeeded("paused");return}if(this.getPlayStateState()!=="playing"){this.syncPreviewPlaybackStateIfNeeded("paused");return}this.suspendPlaybackForMediaPending();return}if(!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&(e.status==="ready"||e.status==="idle")&&!this.pendingPreviewState,i=this.previewPlaybackAutoResume&&e.status==="failed"&&this.getPlayStateState()!=="paused";if(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,i){this.setPlayStateState("paused"),this.emitPlayStateChangeEvent();return}!t||this.animationFrameId||this.resumePlaybackAfterMediaPending()}clampPlaybackSeekTime(e){const t=Math.max(0,e);let i;try{const n=this.getClips();i=Array.isArray(n)?n:[]}catch{return t}if(i.length===0)return t;const r=kt(i);return!Number.isFinite(r)||r<=0?t:Math.min(t,r)}setCurrentTime(e){const t=this.clampPlaybackSeekTime(e),i=this.getTimelineCommands().setCurrentTime(t);if(!i.changed){this.updateCanPlayState(),this.pendingPreviewState&&this.pendingPreviewState.targetTime===i.nextValue&&this.syncPreviewSession();return}const r=i.nextValue;this.ensureConfigState().currentTime=r,this.syncCurrentTimeToScene(r),this.followPlaybackViewportIfNeeded(r),this.emitEvent("time_change",{time:r}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(e){this.ensureConfigState().enableClipSnap=e,e||this.updateSnapGuideLine(null),this.tracks.forEach(t=>{t.setClipSnapEnabled(e)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setEnablePrimaryTrackMagnet(e){const t=this.getEnablePrimaryTrackMagnet();t!==e&&this.withHistoryTransaction("set_primary_track_magnet",()=>{this.setPrimaryTrackMagnetEnabledState(e),this.shouldSkipHistoryRecording()||this.getTimelineHistoryRecorder().recordSetPrimaryTrackMagnet(t,e),e&&this.withStructureSession(i=>{this.normalizePrimaryTrackInSession(i)})})}getEnablePrimaryTrackMagnet(){return this.ensureConfigState().enablePrimaryTrackMagnet!==!1}setPrimaryTrackMagnetEnabledFromHistory(e){this.setPrimaryTrackMagnetEnabledState(e)}setPrimaryTrackMagnetEnabledState(e){this.ensureConfigState().enablePrimaryTrackMagnet=e}getPrimaryTrackId(){var i,r;const e=this.getTrackCollection();if(typeof e.getPrimaryTrack=="function"){const n=e.getPrimaryTrack();return((i=n==null?void 0:n.getId)==null?void 0:i.call(n))??null}const t=Array.isArray(this.tracks)?this.tracks.find(n=>{var a;return((a=n.getRole)==null?void 0:a.call(n))==="primary"}):null;return((r=t==null?void 0:t.getId)==null?void 0:r.call(t))??null}isPrimaryTrackId(e){var r,n,a,o;if(!e)return!1;const t=this.getTrackCollection(),i=typeof t.findById=="function"?t.findById(e):null;return((r=i==null?void 0:i.getRole)==null?void 0:r.call(i))==="primary"?!0:((o=(a=(n=this.trackManager)==null?void 0:n.getTrack)==null?void 0:a.call(n,e))==null?void 0:o.role)==="primary"}shouldNormalizePrimaryTrackForTrackIds(e){return this.getEnablePrimaryTrackMagnet()&&e.some(t=>this.isPrimaryTrackId(t))}getStableStartOrderedClips(e){return e.map((t,i)=>({clip:t,index:i})).sort((t,i)=>t.clip.startTime===i.clip.startTime?t.index-i.index:t.clip.startTime-i.clip.startTime).map(t=>t.clip)}buildPrimaryTrackContinuousClips(e){if(e.length===0)return[];let t=e[0].startTime;return e.map(i=>{const r={...i,startTime:t,endTime:t+i.duration};return t+=i.duration,r})}buildPrimaryTrackMultiDragOrderedClips(e,t){return e.map((i,r)=>({clip:t.get(i.id)??i,index:r,isMoved:t.has(i.id)})).sort((i,r)=>i.clip.startTime!==r.clip.startTime?i.clip.startTime-r.clip.startTime:i.isMoved!==r.isMoved?i.isMoved?-1:1:i.index-r.index).map(i=>i.clip)}normalizePrimaryTrackInSession(e,t={}){var c;if(!this.getEnablePrimaryTrackMagnet())return[];const i=this.getPrimaryTrackId();if(!this.isPrimaryTrackId(i))return[];const r=i?this.getTrackCollection().findById(i):null,n=t.orderedClips?[...t.orderedClips]:this.getStableStartOrderedClips(((c=r==null?void 0:r.getClips)==null?void 0:c.call(r))??[]);if(n.length===0)return[];const a=this.buildPrimaryTrackContinuousClips(n),o=new Set(t.forceClipIds??[]),l=[];return a.forEach((h,d)=>{const u=n[d];if(!u)return;const p=u.startTime!==h.startTime||u.endTime!==h.endTime;p&&l.push({clipId:u.id,previousState:u,newState:h}),(p||o.has(u.id))&&e.updateClip(u.id,{startTime:h.startTime,endTime:h.endTime})}),l.length>0&&!this.shouldSkipHistoryRecording()&&this.getTimelineHistoryRecorder().recordClipUpdate(l[0].newState,void 0,l),l}setZoom(e){const t=this.getTimelineCommands().setZoom(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(e){const t=this.getZoomState(),i=this.getCurrentTimeState(),r=this.getTimelineCommands().setZoom(e);if(!r.changed)return;const n=r.nextValue;if(this.ensureConfigState().zoom=n,this.syncZoomToScene(n),this.refreshScrollbarMetrics(),this.timeline){const a=this.timeline.getScrollLeft(),o=U.timeToPixels(i,t),c=U.timeToPixels(i,n)-o+a;this.timeline.setScrollLeft(c),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())})}this.emitEvent("zoom_change",{zoom:n})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),r=this.timeline.getScrollLeft(),n=U.pixelsToTime(t-pe+r,i),a=this.getTimelineCommands().setZoom(e);if(!a.changed)return;const o=a.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const c=U.timeToPixels(n,o)-(t-pe);this.timeline.setScrollLeft(c),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(e){const t=this.getTimelineCommands().setSpeed(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount>0}getSourceLoadingState(){const e=this.sourceLoadingCount;return{isLoading:e>0,pending:e}}setThumbnailProvider(e){this.thumbnailProvider=e,this.thumbnailProviderVersion+=1,this.config.thumbnailProvider=e,this.clipThumbnailLoadStates.clear(),this.sourceMediaRegistry.clearThumbnailCache(),this.getClips().forEach(i=>{this.primeOrLoadClipThumbnails(i,{allowPrimeExisting:!1,force:!0})})}async loadClipThumbnails(e,t={}){if(!this.thumbnailProvider||e.type!=="video")return!1;const i=this.thumbnailProvider,r=this.buildClipThumbnailLoadSignature(e,this.thumbnailProviderVersion),n=this.clipThumbnailLoadStates.get(e.id);if((n==null?void 0:n.signature)===r){if(n.promise)return n.promise;if(n.completed&&!t.force)return!0}let a=!1;const o=this.sourceMediaRegistry.getThumbnails(this.buildClipThumbnailResourceKey(e),async()=>{const l=await Promise.resolve(i.getThumbnails(e));return Array.isArray(l)?l:[]},{force:t.force}).then(l=>{try{if(!Array.isArray(l))return!1;a=!0;const c=this.findClipById(e.id)??e;return this.isClipThumbnailLoadCurrent(e.id,r)?(this.areThumbnailArraysEqual(c.thumbnails,l)||this.updateClip(e.id,{thumbnails:l}),O.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return O.warn("TimelineManager","Error loading clip thumbnails:",{error:c,clipId:e.id}),!1}}).finally(()=>{const l=this.clipThumbnailLoadStates.get(e.id);(l==null?void 0:l.signature)===r&&(l.promise=null,l.completed=a,a||this.clipThumbnailLoadStates.delete(e.id))});this.clipThumbnailLoadStates.set(e.id,{signature:r,promise:o,completed:!1});try{return await o}catch{return!1}}async refreshClipThumbnails(e){const t=this.getClips().find(i=>i.id===e);return t?this.loadClipThumbnails(t,{force:!0}):!1}async refreshAllClipThumbnails(){const e=this.getClips();return await Promise.all(e.map(i=>this.loadClipThumbnails(i,{force:!0})))}async addClip(e){this.beginSourceLoading();try{return await this.addClipInternal(e)}finally{this.endSourceLoading()}}async addClips(e){if(e.length===0)return[];this.beginSourceLoading();try{return await this.withHistoryTransaction("add_clips",async()=>{const t=[],i=new Map,r=new Map,n=!!this.trackManager;for(const a of e){const o=n?this.resolveBatchClipConfig(a,i,r):a,l=await this.addClipInternal(o);if(t.push(l),!n||a.startTime!==void 0||a.trackId)continue;const c=this.getClips().find(d=>d.id===l),h=this.resolveTrackIdByClipId(l);!c||!h||(i.set(c.type,h),r.set(h,c.endTime))}return t})}finally{this.endSourceLoading()}}resolveBatchClipConfig(e,t,i){if(e.startTime!==void 0||e.trackId)return e;const r=e.type||"video",n=t.get(r)||this.resolveBatchAppendTrackId(r);if(!n)return e;const a=i.get(n)??this.getTrackTimelineExtentById(n);return{...e,trackId:n,startTime:a}}resolveBatchAppendTrackId(e){const t=this.getTracksSortedByOrder(),i=t.find(a=>{var o,l;return((o=a.getRole)==null?void 0:o.call(a))==="primary"&&((l=a.getTrackType)==null?void 0:l.call(a))===e});if(i)return i.getId();const r=t.find(a=>{var o;return((o=a.getTrackType)==null?void 0:o.call(a))===e});return r?r.getId():this.createTrack(e)||null}getTrackTimelineExtentById(e){const t=this.getTrackCollection().findById(e);return t?ln(t.getClips()):0}async addClipInternal(e){return this.withStructureSession(async()=>{let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.type||"video",r=i==="text",n=e.src??"",a=e.duration??(r?ra:0),o=e.name??(r?"文本":`${i}_${Date.now()}`);if(!r&&(!e.name||a<=0))throw new Error(`addClip requires name and duration for ${i} clips`);const l=r?0:e.startTimeAtSource||0,c=r?a:e.endTimeAtSource||l+a;let h=r?a:e.sourceDuration;if(!h)try{h=await U.getVideoDuration(n,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(S){O.error("TimelineManager","Failed to get video duration:",{error:S}),h=c}!r&&h>0&&this.sourceMediaRegistry.primeDuration(this.buildSourceMediaKey(e),h);let d=e.thumbnails;const u=e.id||`clip_${o}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=pn({id:u,type:i,externalId:e.externalId,src:n,name:o,isMuted:e.isMuted??!1,startTime:t,duration:a,startTimeAtSource:l,endTimeAtSource:c,sourceDuration:h,endTime:t+a,thumbnails:d,style:e.style,visualTransform:r||i==="video"?Pe(e.visualTransform):e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1,textContent:e.textContent??(r?"默认文本":void 0),textStyle:r?De(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});O.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:p.id,type:p.type,startTime:p.startTime,duration:p.duration}));const f=()=>{var k;if(e.trackId){const P=this.getTrackCollection().findById(e.trackId);if(P){if(this.registerPreviewAutoAspectRatioClip(p),(k=P.addClip)==null||k.call(P,p),Wi({applied:!0,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const x=e.trackId;this.getTimelineHistoryRecorder().recordAddClip(p,x,this.cloneTrackSnapshot(x),this.getTrackRestoreAnchor(x))},applyEffects:()=>{}}),this.shouldNormalizePrimaryTrackForTrackIds([e.trackId])){const x=this.getActiveStructureSession();x&&this.normalizePrimaryTrackInSession(x)}return this.primeOrLoadClipThumbnails(p),p.id}}const S=this.getTimelineCommands().planTrackPlacement(p,this.getTracksSortedByOrder()),T=this.getTrackCollection(),v=np({clip:p,placement:S,trackCollection:T,createTrack:this.createTrack.bind(this)});Wi({applied:v,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const P=this.resolveTrackIdByClipId(p.id);this.getTimelineHistoryRecorder().recordAddClip(p,P,P?this.cloneTrackSnapshot(P):null,P?this.getTrackRestoreAnchor(P):null)},applyEffects:()=>{}});const C=this.resolveTrackIdByClipId(p.id);if(this.shouldNormalizePrimaryTrackForTrackIds([C])){const P=this.getActiveStructureSession();P&&this.normalizePrimaryTrackInSession(P)}return this.primeOrLoadClipThumbnails(p),p.id},m=e.trackId?[e.trackId]:[this.getPrimaryTrackId()];return this.shouldNormalizePrimaryTrackForTrackIds(m)?this.withHistoryTransaction("add_primary_track_clip",f):f()})}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);if(!t.exists)return;t.shouldClearSelection&&this.clearSelection();const i=()=>this.withStructureSession(r=>{Wi({applied:$s(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>{}}),this.shouldNormalizePrimaryTrackForTrackIds([t.trackId])&&this.normalizePrimaryTrackInSession(r)});if(this.shouldNormalizePrimaryTrackForTrackIds([t.trackId])){this.withHistoryTransaction("remove_primary_track_clip",i);return}i()}removeClipsByExternalId(e){if(!e)return!1;const t=this.resolveClipIdsForExternalIdRemoval(e);if(t.length===0)return!1;const i=new Set(t);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let r=!1;return this.withHistoryBoundary("suppressed",()=>{this.withClipRemovalBatch(()=>{for(const n of t){const a=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);a.exists&&(r=$s(this.getTrackCollection(),a,n)||r)}})}),r?(Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){if(this.getTimelineCommands().findClipById(this.tracks,e)){if(this.getTrackCollection().updateClip(e,t),Object.prototype.hasOwnProperty.call(t,"thumbnails")){const i=this.findClipById(e);i&&this.markClipThumbnailLoadCompleted(i)}Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);if((i==null?void 0:i.clip.type)==="text")return;const r=i==null?void 0:i.track.splitSelectedClip;if(r){const n=()=>{this.withSplitOperation(()=>{r.call(i.track,t)})};this.shouldNormalizePrimaryTrackForTrackIds([i.trackId])?this.withHistoryTransaction("split_primary_track_clip",n):n(),Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e);if((t==null?void 0:t.clip.type)==="text")return;const i=t==null?void 0:t.track.splitSelectedClip;if(i){const r=()=>{this.withSplitOperation(()=>{i.call(t.track,e)})};this.shouldNormalizePrimaryTrackForTrackIds([t.trackId])?this.withHistoryTransaction("split_primary_track_clip",r):r(),Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}getClips(){return this.getTrackCollection().getAllClips()}syncTimelineClipMediaStateFromPreview(e){const t=this.getFailedPreviewClipIds(),i=new Set;e.slots.forEach(r=>{const n=r.clipId;if(!n)return;const a=this.findClipById(n);if(!a||a.type!=="video"&&a.type!=="audio")return;if(i.add(n),r.phase==="failed"&&r.role==="current"){this.applyTimelineClipMediaStatus(n,"failed","媒体丢失");return}(r.phase==="active"||r.phase==="primed")&&!!r.actualSource&&this.clearTimelineClipMediaStatus(n)}),Array.from(t).forEach(r=>{if(i.has(r))return;this.findClipById(r)||t.delete(r)})}applyTimelineClipMediaStatus(e,t,i){const r=this.getFailedPreviewClipIds(),n=this.findClipById(e);if(!n){r.delete(e);return}if(n.mediaStatus===t&&n.mediaStatusMessage===i){r.add(e);return}r.add(e),this.updateClip(e,{mediaStatus:t,mediaStatusMessage:i})}clearTimelineClipMediaStatus(e){const t=this.getFailedPreviewClipIds();if(!t.has(e))return;t.delete(e);const i=this.findClipById(e);!i||i.mediaStatus!=="failed"&&i.mediaStatusMessage==null||this.updateClip(e,{mediaStatus:"ready",mediaStatusMessage:null})}getFailedPreviewClipIds(){return this.failedPreviewClipIds||(this.failedPreviewClipIds=new Set),this.failedPreviewClipIds}getExportComposition(){var n,a,o;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(_t(e.mode)&&t===Be.width&&i===Be.height){const l=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,c=(a=l==null?void 0:l.style)==null?void 0:a.sys_width,h=(o=l==null?void 0:l.style)==null?void 0:o.sys_height;typeof c=="number"&&c>0&&typeof h=="number"&&h>0&&(t=c,i=h)}const r=un({width:t,height:i});return{width:r.width,height:r.height,aspectRatio:`${r.width}:${r.height}`,mode:e.mode}}getExportCoverUrl(e){var r;let t=null,i=null;for(const n of e)for(const a of n.clips)if(a.type==="video"){if(!t||!i){t=n,i=a;continue}if(a.startTime<i.startTime){t=n,i=a;continue}a.startTime===i.startTime&&n.order<t.order&&(t=n,i=a)}return((r=i==null?void 0:i.thumbnails)==null?void 0:r[0])||""}exportTimeline(){const e=this.getResolvedTracksSnapshot().slice().sort((i,r)=>i.order-r.order).map(i=>{const r=i.clips.map(n=>({id:n.id,type:n.type,externalId:n.externalId,src:n.src,name:n.name,isMuted:n.isMuted??!1,startTime:Math.round(n.startTime),duration:Math.round(n.duration),endTime:Math.round(n.endTime),startTimeAtSource:Math.round(n.startTimeAtSource),endTimeAtSource:Math.round(n.endTimeAtSource),sourceDuration:Math.round(n.sourceDuration),thumbnails:n.thumbnails,visualTransform:n.type==="video"||n.type==="text"?Pe(n.visualTransform):void 0,separatedAudioClipId:n.separatedAudioClipId,separatedFromVideoClipId:n.separatedFromVideoClipId,volume:n.volume??1,textContent:n.textContent,textStyle:n.textStyle,ttsSourceTextClipId:n.ttsSourceTextClipId,ttsVoiceId:n.ttsVoiceId,ttsVoiceName:n.ttsVoiceName,ttsFollowTextUpdates:n.ttsFollowTextUpdates})).sort((n,a)=>n.startTime-a.startTime);return{id:i.id,type:i.type,name:i.name||"未命名轨道",order:i.order,role:i.role??"normal",isMuted:i.isMuted??!1,clips:r}}),t=this.getExportCoverUrl(e);return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){O.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}const t=[];await this.withHistoryBoundary("reset",async()=>{await this.withPreservedEmptyTracks(async()=>{this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const r=new Map,n=[...e.tracks].sort((c,h)=>c.order-h.order),a=this.resolveImportedTrackRoles(n);let o;for(const c of n){const h=this.createTrack(c.type,c.name,o?"after_track":void 0,o,a.get(c.id));h&&(this.muteTrack(h,c.isMuted),r.set(c.id,h),o=h)}const l=new Map;for(const c of n){const h=r.get(c.id);if(h)for(const d of c.clips)try{let u=d.separatedAudioClipId;u&&l.has(u)&&(u=l.get(u));let p=d.separatedFromVideoClipId;p&&l.has(p)&&(p=l.get(p));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:p,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,ttsSourceTextClipId:d.ttsSourceTextClipId,ttsVoiceId:d.ttsVoiceId,ttsVoiceName:d.ttsVoiceName,ttsFollowTextUpdates:d.ttsFollowTextUpdates,trackId:h},m=await this.addClip(f);l.set(d.id,m)}catch(u){t.push({clipId:d.id,error:u}),O.error("TimelineManager",`Failed to import clip ${d.id}:`,{error:u})}}})}),this.clearHistory();const i={errors:t};this.emitEvent("draft_loaded",i)}resolveImportedTrackRoles(e){const t=new Map;let i=!1;for(const n of e){const a=n.role==="primary"&&!i?"primary":"normal";a==="primary"&&(i=!0),t.set(n.id,a)}if(i)return t;const r=this.inferImportedPrimaryTrackIndex(e);return r>=0&&t.set(e[r].id,"primary"),t}inferImportedPrimaryTrackIndex(e){var t;for(let i=e.length-1;i>=0;i-=1)if(((t=e[i])==null?void 0:t.type)==="video")return i;return e.length>0?0:-1}stopPlaybackForImport(){var i;const e=this.getPlayStateState()==="playing",t=(i=this.previewSession)!=null&&i.hasPreview()?this.previewMountContainer:null;this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),e?this.pause():this.setPlayStateState("paused"),this.destroyPreviewSession(!0),t&&(this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t,this.previewAspectRatio)),this.syncPreviewSession()}getClipsData(){return this.getClips()}getVersion(){return Yt.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(c=>c.startTime)),r=(Math.max(...e.map(c=>c.endTime))-t)/1e3,n=((l=this.stage)==null?void 0:l.width())||0,a=n-pe*2;O.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:a}));const o=Math.min(a/r,Me.MAX);if(this.setZoom(o),this.timeline){const c=e.reduce((h,d)=>d.startTime<h.startTime?d:h);this.scrollToClip(c.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){var i;this.previewSyncInteractionMode=t,this.previewClockSeekAlignmentTargetTime=t==="seek"?this.clampPlaybackSeekTime(e):null,this.previewClockSeekAlignmentDeadlineMs=t==="seek"?Date.now()+jp:0,this.beginPendingPreview(e,t),this.setCurrentTime(e),this.getPlayStateState()==="playing"&&this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState()),t!=="scrub"&&this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"timeline.seek",message:"Timeline seek requested",playbackAttemptId:this.playbackAttemptId,syncRequestId:((i=this.pendingPreviewState)==null?void 0:i.syncRequestId)??null,runtimeState:this.buildDiagnosticsRuntimeState(),extra:{targetTime:e}})}handleScrollChange(e){this.suspendPlaybackViewportFollowIfUserScrolling(),this.syncScrollLeft(e)}handleClipUpdate(e,t,i){this.shouldSkipHistoryRecording()||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i);const r=this.getActiveStructureSession();if(r){r.queueEvent("clip_updated",{clip:e}),r.markClipStateMutation();return}this.emitEvent("clip_updated",{clip:e});const n=this.selectedClipId===e.id;Od({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),n&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){if(this.splitOperationDepth>0)return;const t=this.getActiveStructureSession();if(this.registerPreviewAutoAspectRatioClip(e),t){t.queueEvent("clip_added",{clip:e}),t.markStructureMutation();return}this.emitEvent("clip_added",{clip:e}),Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(e){if(this.clipThumbnailLoadStates.delete(e),this.splitOperationDepth>0)return;const t=this.getActiveStructureSession();if(t){t.queueEvent("clip_removed",{clipId:e}),t.markStructureMutation();return}this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){Fd(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{O.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){const e=this.getClips(),t=this.getCurrentTime(),i=Nd(e,t),r=this.canPlay;this.canPlay=Gd({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:kt(e)||1,setCanPlay:n=>{this.canPlay=n},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:n=>{this.emitEvent("can_play_change",{canPlay:n})}}),r!==this.canPlay&&O.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:r,newState:this.canPlay}))}findClipById(e){return this.getClips().find(t=>t.id===e)}buildGeneratedAudioClipName(e){return`配音 · ${e}`}normalizeGeneratedAudioDuration(e){return!Number.isFinite(e)||e<=0?1:Math.max(1,Math.round(e))}resolveVoiceTextContent(e){return e.textContent??e.name??""}findSourceTextClipForTtsAudio(e){if(!e.ttsSourceTextClipId)return null;const t=this.findClipById(e.ttsSourceTextClipId);return(t==null?void 0:t.type)!=="text"?null:t}resolveTtsAudioVoiceGenerationSource(e){const t=this.findSourceTextClipForTtsAudio(e),i=t?this.resolveVoiceTextContent(t):"",r=typeof e.textContent=="string"?e.textContent:"",n=i.trim().length>0?i:r.trim().length>0?r:"";if(n.length===0)throw new Error("替换音色失败:缺少可用的配音文本");return{requestSourceTextClipId:(t==null?void 0:t.id)??e.ttsSourceTextClipId??e.id,persistedSourceTextClipId:t==null?void 0:t.id,text:n}}getVoiceLinkedAudioClips(e){return this.getClips().filter(t=>t.type==="audio"&&t.ttsSourceTextClipId===e)}hasVoiceLinkedAudioClipsToRegenerate(e){return this.getVoiceLinkedAudioClips(e).some(t=>t.ttsFollowTextUpdates===!0&&!!t.ttsVoiceId)}scheduleVoiceLinkedTextRegeneration(e,t,i,r){var n;this.pendingVoiceLinkedTextRegeneration&&this.pendingVoiceLinkedTextRegeneration.clipId!==e&&(this.voiceLinkedTextRegenerationTimer!==null&&(clearTimeout(this.voiceLinkedTextRegenerationTimer),this.voiceLinkedTextRegenerationTimer=null),this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{O.error("TimelineManager","Failed to flush pending linked voice regeneration",{error:a,clipId:e})})),this.voiceLinkedTextRegenerationTimer!==null&&clearTimeout(this.voiceLinkedTextRegenerationTimer),this.pendingVoiceLinkedTextRegeneration={clipId:e,originalClip:((n=this.pendingVoiceLinkedTextRegeneration)==null?void 0:n.clipId)===e?this.pendingVoiceLinkedTextRegeneration.originalClip:{...t},nextText:i,generateVoiceBatch:r},this.voiceLinkedTextRegenerationTimer=setTimeout(()=>{this.voiceLinkedTextRegenerationTimer=null,this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{O.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:a,clipId:e})})},na)}async flushPendingVoiceLinkedTextRegeneration(){const e=this.pendingVoiceLinkedTextRegeneration;if(this.pendingVoiceLinkedTextRegeneration=null,!e)return;const t=this.findClipById(e.clipId),i=(t==null?void 0:t.type)==="text"?{...t,textContent:e.nextText}:null,r=e.nextText,n=i?this.getTimelineHistoryRecorder().createClipUpdateAction(i,e.originalClip):null;await this.withHistoryTransaction("update_text_with_voice_regeneration",async()=>{n&&this.getTimelineHistoryRecorder().recordAction(n),await this.regenerateVoiceLinkedAudioClips(e.clipId,r,e.generateVoiceBatch)})}applyGeneratedAudioClipResult(e,t,i,r,n){const a=this.normalizeGeneratedAudioDuration(r.duration);this.updateClip(e,{src:r.audioSrc,name:this.buildGeneratedAudioClipName(r.voiceName),textContent:i,duration:a,startTimeAtSource:0,endTimeAtSource:a,sourceDuration:a,ttsSourceTextClipId:t,ttsVoiceId:r.voiceId,ttsVoiceName:r.voiceName,ttsFollowTextUpdates:n})}syncTextClipDurationToAudio(e,t){const i=this.normalizeGeneratedAudioDuration(t),r=this.findClipById(e);!r||r.type!=="text"||r.duration===i&&r.endTimeAtSource===i&&r.sourceDuration===i||(this.updateClip(e,{duration:i,endTimeAtSource:i,sourceDuration:i}),this.relocateClipIfNeeded(e))}doesClipOverlapOnTrack(e,t){const i=this.getTrackCollection().findById(e);if(!i)return!1;const r=t.startTime+t.duration;return i.getClips().some(n=>n.id!==t.id&&t.startTime<n.endTime&&r>n.startTime)}doesClipGroupOverlapOnTrack(e,t,i=new Set){const r=this.getTrackCollection().findById(e);if(!r)return!1;const n=r.getClips().filter(a=>!i.has(a.id));return t.some(a=>{const o=a.startTime+a.duration;return n.some(l=>l.id!==a.id&&a.startTime<l.endTime&&o>l.startTime)})}findNearestAvailableTrackForClip(e,t){const i=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),r=i.findIndex(o=>o.id===t);if(r===-1)return null;const a=i.map((o,l)=>({track:o,index:l,distance:Math.abs(l-r)})).filter(({track:o})=>o.id!==t&&o.type===e.type).sort((o,l)=>{if(o.distance!==l.distance)return o.distance-l.distance;const c=o.index>r?0:1,h=l.index>r?0:1;return c-h}).find(({track:o})=>!this.doesClipOverlapOnTrack(o.id,e));return(a==null?void 0:a.track.id)??null}resolveOverlapRelocationTargetTrackId(e,t){const i=this.findNearestAvailableTrackForClip(e,t);if(i)return i;const r=e.type==="audio"?"bottom_of_type_region":"top_of_type_region";return this.createTrack(e.type,void 0,"after_track",t)||this.createTrack(e.type,void 0,r)||null}relocateClipToAvoidOverlap(e){const t=this.findClipById(e);if(!t)return!1;const i=this.resolveTrackIdByClipId(e);if(!i||!this.doesClipOverlapOnTrack(i,t))return!1;const r=this.resolveOverlapRelocationTargetTrackId(t,i);return!r||r===i?!1:this.moveClipToTrack(e,r)}buildClipboardPasteGroups(e,t){const i=new Map,r=new Map;e.trackReferences.slice().sort((o,l)=>{var c,h;return(((c=o.trackSnapshot)==null?void 0:c.order)??Number.MAX_SAFE_INTEGER)-(((h=l.trackSnapshot)==null?void 0:h.order)??Number.MAX_SAFE_INTEGER)}).forEach((o,l)=>{var c;i.set(o.sourceTrackId,l),r.set(o.sourceTrackId,((c=o.trackSnapshot)==null?void 0:c.order)??Number.MAX_SAFE_INTEGER)});let n=i.size;const a=new Map;return e.items.forEach(o=>{const l=o.sourceTrackId??`clipboard-orphan:${o.sourceClipId}`,c=t.get(o.sourceClipId);if(!c)return;let h=a.get(l);if(!h){const d=i.get(l);h={key:l,type:o.clip.type,sourceTrackId:o.sourceTrackId,sourceTrackOrder:r.get(l)??Number.MAX_SAFE_INTEGER,sourceOrder:d??n++,sourceClipIds:[],clipIds:[]},a.set(l,h)}h.sourceClipIds.push(o.sourceClipId),h.clipIds.push(c)}),Array.from(a.values()).sort((o,l)=>o.sourceOrder-l.sourceOrder)}createTracksForTypeBoundary(e,t,i){for(let r=0;r<t;r+=1)i==="before"?this.createTrack(e,void 0,"top_of_type_region"):this.createTrack(e,void 0,"bottom_of_type_region")}selectBestClipboardPasteStartIndex(e,t){var r;if(t.length===0)return null;const i=t.filter(n=>n.newTrackCount===0).sort((n,a)=>n.score-a.score)[0];if(i)return i.startIndex;if(e==="text"){const n=t.filter(a=>a.startIndex<0).sort((a,o)=>a.newTrackCount!==o.newTrackCount?a.newTrackCount-o.newTrackCount:a.score-o.score)[0];if(n)return n.startIndex}return((r=t.slice().sort((n,a)=>n.score-a.score)[0])==null?void 0:r.startIndex)??null}buildClipboardPasteGroupPlacementClips(e,t,i,r){const n=new Map(t.items.map(a=>[a.sourceClipId,a]));return e.sourceClipIds.map(a=>{const o=n.get(a),l=i.get(a);return!o||!l?null:{id:l,startTime:r+(o.clip.startTime-t.minStartTime),duration:o.clip.duration}}).filter(a=>a!==null)}ensureClipboardPasteSourceTracks(e,t){const i=e.trackReferences.filter(r=>{var n;return((n=r.trackSnapshot)==null?void 0:n.type)===t}).sort((r,n)=>{var a,o;return(((a=r.trackSnapshot)==null?void 0:a.order)??Number.MAX_SAFE_INTEGER)-(((o=n.trackSnapshot)==null?void 0:o.order)??Number.MAX_SAFE_INTEGER)});for(const r of i)!r.trackSnapshot||r.trackSnapshot.role==="primary"||this.getTrackCollection().findById(r.sourceTrackId)||this.ensureTrackFromHistorySnapshot(r.trackSnapshot,r.trackRestoreAnchor)}resolveClipboardPasteTypeGroupAssignments(e,t,i,r){const n=new Map;if(e.length===0)return n;this.ensureClipboardPasteSourceTracks(t,e[0].type);const a=[...this.getResolvedTracksSnapshot()].filter(C=>{var k;return C.type===((k=e[0])==null?void 0:k.type)}).sort((C,k)=>C.order-k.order);if(a.length===0){const C=this.createTrack(e[0].type);C&&n.set(e[0].key,C);for(let k=1;k<e.length;k+=1){const P=this.createTrack(e[k].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");P&&n.set(e[k].key,P)}return n}const o=new Set(e.flatMap(C=>C.clipIds)),l=e.map(C=>{const k=this.buildClipboardPasteGroupPlacementClips(C,t,i,r);if(k.length===0)return null;const P=this.resolvePreferredTrackIndexForPasteGroup(C,a,Math.min(C.sourceOrder,Math.max(a.length-1,0)));return{...C,preferredTrackIndex:P,clips:k}}).filter(C=>C!==null);if(l.length===0)return n;const c=l.map(C=>C.preferredTrackIndex),h=Math.min(...c),d=a.length,u=-l.length,p=[];for(let C=u;C<=d;C+=1){let k=!0,P=0,x=0;for(let D=0;D<l.length;D+=1){const w=l[D];if(!w)continue;const A=C+D;if(P+=Math.abs(A-w.preferredTrackIndex),A<0||A>=a.length){x+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[A].id,w.clips,o)){k=!1;break}}k&&(P+=x*.1,P+=Math.abs(C-h)*sa.ANCHOR_INDEX_WEIGHT,p.push({startIndex:C,score:P,newTrackCount:x}))}const f=this.selectBestClipboardPasteStartIndex(l[0].type,p);if(f===null)return n;const m=Math.max(0,-f),S=Math.max(0,f+l.length-a.length);m>0&&this.createTracksForTypeBoundary(l[0].type,m,"before"),S>0&&this.createTracksForTypeBoundary(l[0].type,S,"after");const T=[...this.getResolvedTracksSnapshot()].filter(C=>{var k;return C.type===((k=l[0])==null?void 0:k.type)}).sort((C,k)=>C.order-k.order),v=f+m;return l.forEach((C,k)=>{const P=T[v+k];P&&n.set(C.key,P.id)}),n}resolvePreferredTrackIndexForPasteGroup(e,t,i){if(e.sourceTrackId){const r=t.findIndex(n=>n.id===e.sourceTrackId);if(r!==-1)return r}if(Number.isFinite(e.sourceTrackOrder)){const r=t.findIndex(n=>n.order>=e.sourceTrackOrder);return r!==-1?r:t.length}return i}resolveClipboardPasteTrackAssignments(e,t,i){const r=this.buildClipboardPasteGroups(e,t),n=new Map;r.forEach(o=>{const l=n.get(o.type)??[];l.push(o),n.set(o.type,l)});const a=new Map;return n.forEach(o=>{this.resolveClipboardPasteTypeGroupAssignments(o,e,t,i).forEach((c,h)=>{a.set(h,c)})}),a}relocateClipIfNeeded(e){this.relocateClipToAvoidOverlap(e)}async regenerateVoiceLinkedAudioClips(e,t,i){const r=this.getVoiceLinkedAudioClips(e).filter(c=>c.ttsFollowTextUpdates===!0&&!!c.ttsVoiceId);if(r.length===0)return;const n=r.map((c,h)=>({requestId:`regen:${c.id}:${Date.now()}:${h}`,sourceTextClipId:e,targetAudioClipId:c.id,text:t,voiceId:c.ttsVoiceId,followTextUpdates:!0,mode:"replace"})),a=await i(n),o=new Map(a.map(c=>[c.requestId,c]));let l=0;n.forEach(c=>{const h=o.get(c.requestId);!h||!c.targetAudioClipId||(this.applyGeneratedAudioClipResult(c.targetAudioClipId,e,t,h,c.followTextUpdates),this.relocateClipIfNeeded(c.targetAudioClipId),l=Math.max(l,this.normalizeGeneratedAudioDuration(h.duration)))}),l>0&&this.syncTextClipDurationToAudio(e,l),this.handleClipChange()}getSelectedTextClipsForVoiceGeneration(e){if(e.type!=="text")return[e];const t=this.getSelectedClips().filter(i=>i.type==="text");return t.length===0?[e]:t.some(i=>i.id===e.id)?t:[e]}getSelectedTtsAudioClipsForVoiceGeneration(e){if(e.type!=="audio"||!Le(e))return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(n=>Le(n))))return[e];const r=t.filter(n=>Le(n));return r.some(n=>n.id===e.id)?r:[e]}async handleVoiceGenerateAction(e,t,i,r,n){if(t.type==="text"){const c=this.getSelectedTextClipsForVoiceGeneration(t),h=Date.now(),d=c.map((f,m)=>({requestId:`create:${f.id}:${i.id}:${h}:${m}`,sourceTextClipId:f.id,text:f.textContent??f.name??"",voiceId:i.id,followTextUpdates:r,mode:"create"}));e.setPreferredTab("voice");const u=[];if(await this.withHistoryTransaction("generate_voice_from_text_clips",async()=>{const f=await n(d),m=new Map(f.map(S=>[S.requestId,S]));for(const S of d){const T=m.get(S.requestId);if(!T)continue;const v=c.find(x=>x.id===S.sourceTextClipId);if(!v)continue;const C=this.normalizeGeneratedAudioDuration(T.duration),k=v.textContent??v.name??"";this.syncTextClipDurationToAudio(v.id,C);const P=await this.addClip({type:"audio",src:T.audioSrc,name:this.buildGeneratedAudioClipName(T.voiceName),textContent:k,startTime:v.startTime,duration:C,startTimeAtSource:0,endTimeAtSource:C,sourceDuration:C,ttsSourceTextClipId:v.id,ttsVoiceId:T.voiceId,ttsVoiceName:T.voiceName,ttsFollowTextUpdates:r});u.push(P)}if(u.length===0)throw new Error("生成音频失败:未返回音频结果")}),u.length===1){this.scrollToClip(u[0],{selectClip:!0,setCurrentTime:!0});return}const p=u[0]??null;this.scrollToClip(p,{setCurrentTime:!0}),this.setSelection(u,{preferredPrimaryClipId:p});return}if(t.type!=="audio"||!Le(t))return;const a=this.getSelectedTtsAudioClipsForVoiceGeneration(t),o=Date.now(),l=a.map((c,h)=>{const d=this.resolveTtsAudioVoiceGenerationSource(c);return{requestId:`replace:${c.id}:${i.id}:${o}:${h}`,sourceTextClipId:d.requestSourceTextClipId,targetAudioClipId:c.id,text:d.text,voiceId:i.id,followTextUpdates:r,mode:"replace"}});e.setPreferredTab("voice"),await this.withHistoryTransaction("replace_voice_for_tts_audio_clips",async()=>{const c=await n(l),h=new Map(c.map(u=>[u.requestId,u])),d=new Map;if(l.some(u=>!h.has(u.requestId)))throw new Error("替换音色失败:未返回音频结果");for(const u of l){const p=h.get(u.requestId);if(!p||!u.targetAudioClipId)continue;const f=a.find(S=>S.id===u.targetAudioClipId);if(!f)continue;const m=this.resolveTtsAudioVoiceGenerationSource(f);if(this.applyGeneratedAudioClipResult(u.targetAudioClipId,m.persistedSourceTextClipId,m.text,p,r),this.relocateClipIfNeeded(u.targetAudioClipId),m.persistedSourceTextClipId){const S=d.get(m.persistedSourceTextClipId)??0;d.set(m.persistedSourceTextClipId,Math.max(S,p.duration))}}d.forEach((u,p)=>{this.syncTextClipDurationToAudio(p,u)}),this.handleClipChange()})}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{O.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){O.warn("TimelineManager","Error loading clip thumbnails:",{error:i,clipId:e.id})}}markClipThumbnailLoadCompleted(e){return Array.isArray(e.thumbnails)?(this.sourceMediaRegistry.primeThumbnails(this.buildClipThumbnailResourceKey(e),e.thumbnails),this.clipThumbnailLoadStates.set(e.id,{signature:this.buildClipThumbnailLoadSignature(e),promise:null,completed:!0}),!0):!1}buildClipThumbnailLoadSignature(e,t=this.thumbnailProviderVersion){return[t,e.type,e.src,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}buildSourceMediaKey(e){return Or.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return Or.buildThumbnailKey({...e,externalId:e.externalId})}isClipThumbnailLoadCurrent(e,t){var i;return((i=this.clipThumbnailLoadStates.get(e))==null?void 0:i.signature)===t}areThumbnailArraysEqual(e,t){return!e||e.length!==t.length?!1:e.every((i,r)=>i===t[r])}handleClipSplit(e,t){const i=this.resolveTrackIdByClipId(e.id),r=i?this.cloneTrackSnapshot(i):null,n=i?this.getTrackRestoreAnchor(i):null;this.withStructureSession(a=>{$d({clip1:e,clip2:t,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordSplitClip:(o,l)=>{this.getTimelineHistoryRecorder().recordSplitClip(o,l,i,r,n)},emitClipUpdated:o=>{this.emitEvent("clip_updated",{clip:o})},emitClipAdded:o=>{this.emitEvent("clip_added",{clip:o})},applyEffects:()=>Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.shouldNormalizePrimaryTrackForTrackIds([i])&&this.normalizePrimaryTrackInSession(a)})}handleClipSelect(e){const t=Hd(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),O.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){O.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new As(t.createHistoryExecutionTarget()).executeUndo(e)})})}handleActionRedo(e){O.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new As(t.createHistoryExecutionTarget()).executeRedo(e)})})}on(e,t){this.getEventDispatcher().on(e,t)}off(e,t){this.getEventDispatcher().off(e,t)}emitEvent(e,t){this.getEventDispatcher().emit(e,t)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=tp({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1)}handlePrimaryTrackMagnetMove(e,t,i,r){if(!this.getEnablePrimaryTrackMagnet()||!this.isPrimaryTrackId(r))return!1;const n=this.getStableStartOrderedClips(i),a=n.findIndex(l=>l.startTime>=e.startTime),o=[...n];return o.splice(a===-1?o.length:a,0,e),this.withHistoryTransaction("move_primary_track_clips",()=>{this.withStructureSession(l=>{this.normalizePrimaryTrackInSession(l,{orderedClips:o,forceClipIds:[e.id]})})}),!0}handleClipOverlap(e,t,i){var h,d,u,p;O.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const r=this.getTrackCollection();if(!r.findById(t))return;const n=e.type,a=this.trackManager.getTracksByType(n).length+1,o=`${Zp(n)}轨道 ${a}`,l=this.createTrack(n,o);if(!l)return;const c=((d=(h=r.findById(l))==null?void 0:h.getId)==null?void 0:d.call(h))||((p=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:p.call(u))||l;this.moveClipToTrackWithHistorySnapshot(e.id,c,i??null,e),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const r=this.resolveCrossTrackPreviewDestination(e,t,i);return r.status==="existing_track"?(this.showClipDropPreview(e,r.targetTrackId),r.targetTrackId===i?"self":"external"):r.status==="new_track_insertion"?(this.showTrackInsertionPreview(r.trackType,r.insertionPlacement,r.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,r){O.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:r}));const n=this.resolveCrossTrackMoveDestination(e,i,r);return n.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):n.status==="same_track"?(O.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(O.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:n.targetTrackId})),this.showClipDropPreview(e,n.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,n.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}getRenderedHeight(){return this.getTimeScaleHeight()+this.calculateTotalHeight()+rn}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.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),t&&this.setCurrentTime(e))}notifySelectionChange(){const e=this.getSelectedClipIds();this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),e)}syncPrimarySelectionFromSelectionStore(){var t,i,r,n;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((n=(r=this.selectionStore)==null?void 0:r.getSelectedClipId)==null?void 0:n.call(r))??null;this.selectedClipId=e}getOrderedSelectionClipIds(e,t){const i=Array.from(new Set(e));if(i.length<=1)return i;const r=t&&i.includes(t)&&t||this.selectedClipId&&i.includes(this.selectedClipId)&&this.selectedClipId||i[0]||null;return r?[r,...i.filter(n=>n!==r)]:i}setSelection(e,t={}){this.resetMultiDragSession();const i=this.getOrderedSelectionClipIds(e,t.preferredPrimaryClipId);this.selectionStore.setSelection(i),this.syncPrimarySelectionFromSelectionStore(),this.notifySelectionChange(),this.emitSelectionChangeEvent(),t.selectedClipEventClip&&this.emitEvent("clip_selected",{clip:t.selectedClipEventClip}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}selectClip(e,t){var r;const i=t||((r=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:r.clip);this.setSelection([e],{preferredPrimaryClipId:e,selectedClipEventClip:i??null})}clearSelection(){this.setSelection([])}getSelectedClipIds(){var e,t;return((t=(e=this.selectionStore)==null?void 0:e.getSelectedClipIds)==null?void 0:t.call(e))??(this.selectedClipId?[this.selectedClipId]:[])}getPrimarySelectedClipId(){return this.getSelectedClipIds()[0]??null}addToSelection(e){this.setSelection([...this.selectionStore.getSelectedClipIds(),e],{preferredPrimaryClipId:this.selectedClipId??e})}removeFromSelection(e){this.setSelection(this.selectionStore.getSelectedClipIds().filter(t=>t!==e))}toggleSelection(e){const t=this.selectionStore.getSelectedClipIds(),i=t.includes(e);this.setSelection(i?t.filter(r=>r!==e):[...t,e],{preferredPrimaryClipId:i?void 0:e})}isClipSelected(e){return this.selectionStore.isSelected(e)}deleteSelectedClips(){this.deleteSelectedClipsWithHistoryLabel("delete_selected_clips")}copySelectedClips(){const e=this.captureSelectedClipsToClipboard();return e?(this.clipClipboard=e,!0):!1}cutSelectedClips(){return this.copySelectedClips()?this.deleteSelectedClipsWithHistoryLabel("cut_selected_clips"):!1}async pasteClipboardClips(){if(!this.clipClipboard||this.clipClipboard.items.length===0)return!1;const e=this.clipClipboard,t=new Map;for(const o of e.items)t.set(o.sourceClipId,this.generateClipId(o.clip.name));const i=this.resolveClipboardPasteTrackAssignments(e,t,this.getCurrentTime()),r=[],n=this.getCurrentTime();if(await this.withHistoryTransaction("paste_clipboard_clips",async()=>{for(const o of e.items){const l=this.buildClipboardPasteClipConfig(o,n,t),c=o.sourceTrackId??`clipboard-orphan:${o.sourceClipId}`,h=i.get(c)??this.resolveClipboardPasteTrackId(o,l,i),d=t.get(o.sourceClipId);if(!d)continue;const u=await this.addClipInternal({...l,id:d,...h?{trackId:h}:{}});(this.getClips().find(f=>f.id===u)??null)&&r.push(u)}}),r.length===0)return!1;const a=e.primaryClipId?t.get(e.primaryClipId)??r[0]??null:r[0]??null;return this.setSelection(r,{preferredPrimaryClipId:a}),!0}deleteSelectedClipsWithHistoryLabel(e){this.resetMultiDragSession();const t=this.selectionStore.getSelectedClipIds();return t.length===0?!1:(this.clearSelection(),this.withHistoryTransaction(e,()=>{for(const i of t)this.removeClip(i)}),this.emitSelectionChangeEvent(),!0)}captureSelectedClipsToClipboard(){const e=this.getSelectedClipIds();if(e.length===0)return null;const t=new Map,i=e.map(r=>{const n=this.getTimelineCommands().prepareRemoveClip(r,this.tracks);return!n.exists||!n.clip?null:(n.trackId&&!t.has(n.trackId)&&t.set(n.trackId,{sourceTrackId:n.trackId,trackSnapshot:this.cloneTrackSnapshot(n.trackId),trackRestoreAnchor:this.getTrackRestoreAnchor(n.trackId)}),{sourceClipId:r,sourceTrackId:n.trackId,clip:this.cloneClipForClipboard(n.clip)})}).filter(r=>r!==null);return i.length===0?null:{items:i,trackReferences:Array.from(t.values()),minStartTime:Math.min(...i.map(r=>r.clip.startTime)),primaryClipId:this.getPrimarySelectedClipId()}}cloneClipForClipboard(e){return{...e,thumbnails:e.thumbnails?[...e.thumbnails]:void 0,style:Js(e.style),visualTransform:e.visualTransform?{...e.visualTransform}:void 0,textStyle:e.textStyle?{...e.textStyle}:void 0}}buildClipboardPasteClipConfig(e,t,i){const r=e.clip,n=r.separatedAudioClipId?i.get(r.separatedAudioClipId)??void 0:void 0,a=r.separatedFromVideoClipId?i.get(r.separatedFromVideoClipId)??void 0:void 0,o=r.ttsSourceTextClipId?i.get(r.ttsSourceTextClipId)??void 0:void 0,l=t+(r.startTime-this.clipClipboard.minStartTime);return{type:r.type,externalId:r.externalId,src:r.src,name:r.name,isMuted:r.isMuted,startTime:l,duration:r.duration,startTimeAtSource:r.startTimeAtSource,endTimeAtSource:r.endTimeAtSource,sourceDuration:r.sourceDuration,thumbnails:r.thumbnails?[...r.thumbnails]:void 0,style:Js(r.style),visualTransform:r.visualTransform?{...r.visualTransform}:void 0,separatedAudioClipId:n,separatedFromVideoClipId:a,volume:r.volume,textContent:r.textContent,textStyle:r.textStyle?{...r.textStyle}:void 0,ttsSourceTextClipId:o,ttsVoiceId:r.ttsVoiceId,ttsVoiceName:r.ttsVoiceName,ttsFollowTextUpdates:r.ttsFollowTextUpdates}}resolveClipboardPasteTrackId(e,t,i){var l,c;const r=e.sourceTrackId??`clipboard-orphan:${e.sourceClipId}`,n=i.get(r);if(n)return n;if(e.sourceTrackId){const h=this.getTrackCollection().findById(e.sourceTrackId);if(h&&((l=h.getTrackType)==null?void 0:l.call(h))===t.type)return i.set(r,e.sourceTrackId),e.sourceTrackId;const d=((c=this.clipClipboard)==null?void 0:c.trackReferences.find(u=>u.sourceTrackId===e.sourceTrackId))??null;if(d!=null&&d.trackSnapshot&&d.trackSnapshot.role!=="primary"){const u=this.ensureTrackFromHistorySnapshot(d.trackSnapshot,d.trackRestoreAnchor);if(u)return i.set(r,u),u}}const a=this.getTimelineCommands().planTrackPlacement({type:t.type||"video",startTime:t.startTime??this.getCurrentTime(),duration:t.duration??0},this.getTracksSortedByOrder()),o=a.status==="use_existing_track"?a.trackId:this.createTrack(a.trackType,void 0,a.insertionPlacement);return o?(i.set(r,o),o):null}generateClipId(e){return`clip_${e}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.setSelection(this.tracks.flatMap(e=>e.getClips().map(t=>t.id)),{preferredPrimaryClipId:this.selectedClipId})}emitSelectionChangeEvent(){this.emitEvent("selection_change",this.resolveSelectionChangeData())}scrollToClip(e,t={}){const{selectClip:i=!1,setCurrentTime:r=!1}=t,n=this.getClips().find(a=>a.id===e);!n||!this.timeline||(this.timeline.scrollToClip(n),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),r&&this.setCurrentTime(n.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}canCopySelectedClips(){return this.getSelectedClipIds().length>0}canCutSelectedClips(){return this.canCopySelectedClips()}canPasteClipboardClips(){var e;return(((e=this.clipClipboard)==null?void 0:e.items.length)??0)>0}canDeleteSelectedClips(){return this.getSelectedClipIds().length>0}canSplitSelectedClip(){const e=this.resolveSelectedClipAtTime(this.getCurrentTime());return!!e&&e.clip.type!=="text"}getSelectedClipAudioAction(){const e=this.getSelectedClips().filter(r=>r.type==="video");return e.length===0?null:e.some(r=>this.canSeparateClipAudio(r.id))?"separate":e.some(r=>this.canRestoreClipAudio(r.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const e=this.getSelectedClipAudioAction();return e?this.applySelectedClipAudioAction(e):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(e){return this.buildPlaybackPlan(e)}getActiveClipsAtTime(e){return this.buildPlaybackPlan(e).activeClips}attachPreview(e){const t=e instanceof HTMLElement?{container:e}:e;t.aspectRatio&&(this.previewAspectRatio=je({mode:t.aspectRatio.mode??(t.aspectRatio.width&&t.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:t.aspectRatio.width??this.previewAspectRatio.width,height:t.aspectRatio.height??this.previewAspectRatio.height})),this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t.container,this.previewAspectRatio),this.emitDiagnostic({severity:"info",category:"session",eventName:"preview.mount.attached",message:"Preview mount attached",playbackAttemptId:this.playbackAttemptId,previewBackend:this.getPreviewBackendType(),runtimeState:this.buildDiagnosticsRuntimeState(),extra:{hasAspectRatioOverride:!!t.aspectRatio}}),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){this.getPreviewRuntimeController().detachPreviewSession()&&(this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.emitDiagnostic({severity:"info",category:"session",eventName:"preview.mount.detached",message:"Preview mount detached",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}))}attachClipConfig(e,t={}){const i=new So,r=t.generateVoiceBatch,n=r,a=r?async c=>{i.setVoiceGenerationBusy(!0);try{return await r(c)}finally{i.setVoiceGenerationBusy(!1)}}:void 0;i.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),getSelectedClips:()=>this.getSelectedClips(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c),u=d?{...d}:null,p=typeof h.textContent=="string"?h.textContent:null;if(n&&(u==null?void 0:u.type)==="text"&&p!==null&&p!==u.textContent&&this.hasVoiceLinkedAudioClipsToRegenerate(c)&&(u==null?void 0:u.type)==="text"){this.withHistoryBoundary("suppressed",()=>{this.updateClip(c,h)}),this.handleClipChange(),this.scheduleVoiceLinkedTextRegeneration(c,u,p,n);return}this.updateClip(c,h),this.handleClipChange()},onGenerateVoice:async(c,h,d)=>{if(!a)throw new Error("未配置音色生成回调");await this.handleVoiceGenerateAction(i,c,h,d,a)}});const o=()=>i.updateFromExternal(),l=(c,h)=>{var p;const d=new Set(this.getSelectedClipIds()),u=this.getPrimarySelectedClip();d.size===0&&(u!=null&&u.id)&&d.add(u.id),(p=h==null?void 0:h.clip)!=null&&p.id&&d.has(h.clip.id)&&i.updateFromExternal()};return this.on("selected_clip_change",o),this.on("clip_updated",l),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",o),this.off("clip_updated",l),i.destroy()}),i.update(),i}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return je(this.previewAspectRatio)}getDiagnosticsSnapshot(){return this.diagnostics.getSnapshot()}subscribeDiagnostics(e){return this.diagnostics.subscribe(e)}getDiagnosticsLiveSnapshot(e){return this.diagnostics.getLiveSnapshot(void 0,e)}subscribeDiagnosticsLive(e,t){return this.diagnostics.subscribeLive(e,t)}exportDiagnosticsPackage(){return this.diagnostics.exportPackage()}clearDiagnostics(e=!0){this.diagnostics.clear(e),e&&this.diagnostics.startSession({packageName:Yt.name,packageVersion:Yt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=je({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...Be},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}pausePlaybackForAudioSeparation(){var t,i,r;(((i=(t=this.timelineStore)==null?void 0:t.getPlayState)==null?void 0:i.call(t))??((r=this.config)==null?void 0:r.playState))==="playing"&&this.pause()}resolvePreferredSeparatedAudioTrackId(e,t){var l;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return null;const i=this.resolveTrackIdByClipId(e);if(!i)return null;const r=[...this.getResolvedTracksSnapshot()].sort((c,h)=>c.order-h.order),n=r.findIndex(c=>c.id===i);if(n===-1)return null;const a=t.startTime+t.duration,o=r.map((c,h)=>({track:c,index:h})).filter(({track:c})=>c.type==="audio").filter(({track:c})=>!c.clips.some(h=>t.startTime<h.endTime&&a>h.startTime));return o.length===0?null:(o.sort((c,h)=>{const d=Math.abs(c.index-n)-Math.abs(h.index-n);return d!==0?d:c.index-h.index}),((l=o[0])==null?void 0:l.track.id)??null)}async separateClipAudio(e){if(!this.canSeparateClipAudio(e))return null;this.pausePlaybackForAudioSeparation();const t=this.getClips().find(c=>c.id===e);if(!t||t.type!=="video")return null;const i=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let r=null;const n=!this.shouldSkipHistoryRecording();if(await this.withHistoryBoundary("suppressed",async()=>{if(r=await this.addClip({type:"audio",src:t.src,name:t.name,startTime:t.startTime,duration:t.duration,startTimeAtSource:t.startTimeAtSource,endTimeAtSource:t.endTimeAtSource,sourceDuration:t.sourceDuration,separatedFromVideoClipId:t.id,isMuted:!1,volume:t.volume??1,trackId:i??void 0}),!r)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:r})}),!r)return null;const a=this.getClips().find(c=>c.id===e),o=this.getClips().find(c=>c.id===r)??null,l=this.resolveTrackIdByClipId(r);return a?(n&&this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,a,o,l),r):null}restoreClipAudio(e){if(!this.canRestoreClipAudio(e))return!1;const t=this.getClips().find(l=>l.id===e);if(!t||t.type!=="video")return!1;const i=t.separatedAudioClipId??null,r=i?this.getClips().find(l=>l.id===i)??null:null,n=i?this.resolveTrackIdByClipId(i):null,a=!this.shouldSkipHistoryRecording();this.withHistoryBoundary("suppressed",()=>{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})});const o=this.getClips().find(l=>l.id===e);return o?(a&&this.getTimelineHistoryRecorder().recordRestoreClipAudio(t,o,r,n),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(n=>n.type==="video"),i=e==="separate"?t.filter(n=>this.canSeparateClipAudio(n.id)):t.filter(n=>this.canRestoreClipAudio(n.id));if(i.length===0)return!1;if(i.length===1){const[n]=i;return e==="separate"?!!await this.separateClipAudio(n.id):this.restoreClipAudio(n.id)}let r=0;return await this.withHistoryTransaction(`selected_clips_audio_${e}`,async()=>{if(e==="restore"){for(const n of i)this.restoreClipAudio(n.id)&&(r+=1);return}for(const n of i)await this.separateClipAudio(n.id)&&(r+=1)}),r>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,r=null){const n=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(n.status==="missing_source_track")return O.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(n.status==="noop")return O.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(n.status==="missing_target_track")return O.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var l,c,h;return{targetTrackType:(c=(l=this.getTrackCollection().findById(t))==null?void 0:l.getTrackType)==null?void 0:c.call(l),clipType:(h=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:h.clip.type}}),!1;if(n.status!=="ready")return!1;const a=this.shouldNormalizePrimaryTrackForTrackIds([n.sourceTrackId,n.targetTrackId]),o=()=>this.withStructureSession(l=>{const{sourceTrackId:c,targetTrackId:h}=n,d=i?{...i}:{...n.clip},u=r?{...r}:{...n.clip},p=this.cloneTrackSnapshot(c),f=this.cloneTrackSnapshot(h),m=this.getTrackRestoreAnchor(c),S=this.getTrackRestoreAnchor(h),T=sp({command:{...n,clip:u},trackCollection:this.getTrackCollection()}),v=this.getClips().find(C=>C.id===e)??null;return zd({applied:T,clipId:e,sourceTrackId:c,targetTrackId:h,clipBefore:d,clipAfter:v??d,sourceTrackSnapshot:p,targetTrackSnapshot:f,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordMoveClipBetweenTracks:(C,k,P,x,D,w,A)=>{this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks(C,k,P,x,D,w,A,m,S)},applyEffects:()=>{}})?(a&&this.normalizePrimaryTrackInSession(l),this.clearAllTrackDropPreviews(),!0):!1});return a?this.withHistoryTransaction("move_primary_track_clip_between_tracks",o):o()}getTrackTotalDuration(){return Ns(this.getClips())}async getResourceCacheStats(){return this.resourceCacheManager?{enabled:!0,...await this.resourceCacheManager.getStats()}:{enabled:!1,entryCount:0,totalBytes:0,maxTotalBytes:0}}async cleanupResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.cleanupExpired())}async clearResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.clear())}destroy(){var t,i,r,n,a,o,l,c,h,d,u,p,f,m,S;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPendingPreviewState(),(t=this.resourceCacheManager)==null||t.cleanupExpired().catch(()=>{}),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(i=this.layout)==null||i.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(a=(r=this.layout)==null?void 0:(n=r.bodyCanvasHost).removeEventListener)==null||a.call(n,"click",this.bodyCanvasHostClickListener);const e=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);e&&this.stageMouseDownListener&&((c=e.removeEventListener)==null||c.call(e,"mousedown",this.stageMouseDownListener)),(d=(h=this.rootContainer)==null?void 0:h.removeEventListener)==null||d.call(h,"wheel",this.rootWheelListener),(u=this.horizontalScrollbar)==null||u.destroy(),(p=this.verticalScrollbar)==null||p.destroy(),(f=this.playhead)==null||f.destroy(),(m=this.timeline)==null||m.destroy(),(S=this.stage)==null||S.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new Zs),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new Qu({root:this.rootContainer,config:this.config.keyboardShortcuts,callbacks:{togglePlay:()=>this.togglePlay(),deleteSelectedClips:()=>{this.removeSelectedClips()},copySelectedClips:()=>{this.copySelectedClips()},cutSelectedClips:()=>{this.cutSelectedClips()},pasteClipboardClips:()=>this.pasteClipboardClips(),toggleSelectedClipsAudio:()=>this.toggleSelectedClipsAudio(),splitCurrentClip:()=>this.splitCurrentClip(),undo:()=>this.undo(),redo:()=>this.redo(),canDeleteSelectedClips:()=>this.canDeleteSelectedClips(),canCopySelectedClips:()=>this.canCopySelectedClips(),canCutSelectedClips:()=>this.canCutSelectedClips(),canPasteClipboardClips:()=>this.canPasteClipboardClips(),canSplitSelectedClip:()=>this.canSplitSelectedClip(),canToggleSelectedClipsAudio:()=>this.canToggleSelectedClipsAudio()}}),this.keyboardShortcutsController.init(),this.mountManager.register("keyboardShortcuts",()=>{var t;(t=this.keyboardShortcutsController)==null||t.destroy(),this.keyboardShortcutsController=null}))}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(e){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return e()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}withSplitOperation(e){this.splitOperationDepth=(this.splitOperationDepth??0)+1;try{return e()}finally{this.splitOperationDepth=Math.max(0,(this.splitOperationDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(e){const t=this.getClips(),i=new Map(t.map(a=>[a.id,a])),r=new Set,n=t.filter(a=>a.externalId===e).map(a=>a.id);for(let a=0;a<n.length;a+=1){const o=n[a];if(r.has(o))continue;r.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!r.has(l.separatedAudioClipId)&&n.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!r.has(l.separatedFromVideoClipId)&&n.push(l.separatedFromVideoClipId))}return t.filter(a=>r.has(a.id)).map(a=>a.id)}shouldClearSelectionForClipIds(e){return this.selectedClipId&&e.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(t=>e.has(t))}resolveSelectedClipAtTime(e){var i;const t=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const r of t){const n=this.getTimelineCommands().findClipById(this.tracks,r),a=n==null?void 0:n.clip;if(a&&e>=a.startTime&&e<a.endTime)return n}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{return e.isFinal?this.withHistoryTransaction("move_selected_clips",()=>this.finalizeMultiDragCrossTrack(t,e)?!0:this.finalizeMultiDragSameTrack(t,e)):(this.syncMultiDragOverlayState(t,e.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(t,e,!1),e.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(t,e.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(t,e))}finally{e.isFinal&&(this.syncMultiDragOverlayState(t,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((e,t)=>{var i;(i=e.setTrackStackOrder)==null||i.call(e,t)})}elevateMultiDragTrackGroups(e,t){var o,l,c;const i=this.resolveMultiDragSessionTrackIds(e);if(i.length<=1)return;const r=i.indexOf(t);r>=0&&(i.splice(r,1),i.push(t));const n=new Set(i);let a=0;for(const h of this.tracks){const d=(o=h.getId)==null?void 0:o.call(h);!d||n.has(d)||(l=h.setTrackStackOrder)==null||l.call(h,a++)}for(const h of i){const d=this.getTrackCollection().findById(h);(c=d==null?void 0:d.setTrackStackOrder)==null||c.call(d,a++)}}resolveMultiDragSessionTrackIds(e){var i;const t=new Set;for(const r of this.tracks){const n=(i=r.getId)==null?void 0:i.call(r);if(!n)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===n})&&t.add(n)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const r of e.selectedClipIds){const n=e.clips.get(r);if(!n)continue;const a=i.get(n.trackId);a?a.push(r):i.set(n.trackId,[r])}i.forEach((r,n)=>{var o;const a=this.getTrackCollection().findById(n);(o=a==null?void 0:a.setClipsDragOverlayActive)==null||o.call(a,r,t)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDragOverlay)==null?void 0:t.call(e)})}ensureMultiDragSession(e){var r;const t=this.selectionStore.getSelectedClipIds();if(t.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===e.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,t))return this.multiDragSession;const i=new Map;for(const n of t){const a=this.findTrackByClipId(n),o=((r=a==null?void 0:a.getId)==null?void 0:r.call(a))??this.resolveTrackIdByClipId(n),l=a==null?void 0:a.getClips().find(h=>h.id===n);if(!o||!l)continue;const c=n===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(n,{clipId:n,trackId:o,clip:c})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:e.draggedClipId,selectedClipIds:t.slice(),clips:i},this.multiDragSession)}haveSameClipIds(e,t){if(e.length!==t.length)return!1;const i=new Set(t);return e.every(r=>i.has(r))}restoreDraggedClipSnapshot(e,t){const i=Math.max(0,e.startTime-t);return{...e,startTime:i,endTime:i+e.duration}}syncMultiDragPeerClips(e,t,i){for(const r of e.selectedClipIds){if(r===t.draggedClipId)continue;const n=e.clips.get(r);if(!n||n.trackId===t.currentTrackId)continue;const a=this.getTrackCollection().findById(n.trackId);if(!(a!=null&&a.updateClipPosition))continue;const o=Math.max(0,n.clip.startTime+t.deltaTime);a.updateClipPosition(r,o,i,i?0:t.crossTrackOffsetY)}}createMultiDragPlacementContext(e){const t=new Map,i=new Map,r=[...this.getResolvedTracksSnapshot()].sort((n,a)=>(n.order??0)-(a.order??0));for(const n of r){const a=i.get(n.type)??[];a.push(n.id),i.set(n.type,a),t.set(n.id,n.clips.filter(o=>!e.has(o.id)).map(o=>({id:o.id,startTime:o.startTime,duration:o.duration})))}return{occupancyByTrackId:t,orderedTrackIdsByType:i}}doesMultiDragPlacementOverlap(e,t,i){const r=e.occupancyByTrackId.get(t)??[],n=i.startTime+i.duration;return r.some(a=>a.id!==i.id&&i.startTime<a.startTime+a.duration&&n>a.startTime)}reserveMultiDragPlacement(e,t,i){const r=e.occupancyByTrackId.get(t)??[];r.push({id:i.id,startTime:i.startTime,duration:i.duration}),e.occupancyByTrackId.set(t,r)}registerMultiDragPlacementTrack(e,t,i,r,n){const a=e.orderedTrackIdsByType.get(i)??[];if(!a.includes(t)){if(r==="before_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o,0,t):a.unshift(t)}else if(r==="after_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o+1,0,t):a.push(t)}else r==="top_of_type_region"?a.unshift(t):a.push(t);e.orderedTrackIdsByType.set(i,a)}e.occupancyByTrackId.has(t)||e.occupancyByTrackId.set(t,[])}findNearestAvailableTrackForMultiDragPlacement(e,t,i){const r=e.orderedTrackIdsByType.get(t.type)??[],n=r.indexOf(i);if(n===-1)return null;const o=r.map((l,c)=>({trackId:l,index:c,distance:Math.abs(c-n)})).filter(({trackId:l})=>l!==i).sort((l,c)=>{if(l.distance!==c.distance)return l.distance-c.distance;const h=l.index>n?0:1,d=c.index>n?0:1;return h-d}).find(({trackId:l})=>!this.doesMultiDragPlacementOverlap(e,l,t));return(o==null?void 0:o.trackId)??null}resolveMultiDragOverlapTargetTrackId(e,t,i){const r=this.findNearestAvailableTrackForMultiDragPlacement(e,t,i);if(r)return r;const n=this.createTrack(t.type,void 0,"after_track",i);if(n)return this.registerMultiDragPlacementTrack(e,n,t.type,"after_track",i),n;const a=t.type==="audio"?"bottom_of_type_region":"top_of_type_region",o=this.createTrack(t.type,void 0,a);return o?(this.registerMultiDragPlacementTrack(e,o,t.type,a),o):null}commitMultiDragPlacements(e,t,i,r={}){const n=[],a=this.createMultiDragPlacementContext(new Set(e.selectedClipIds)),o=new Map,l=new Map;let c=null;for(const h of e.selectedClipIds){const d=e.clips.get(h);if(!d)continue;const u=this.buildMovedClipSnapshot(d.clip,t.deltaTime),p=i(d,u);if(!p)continue;if(r.compactSameTrackPrimary&&this.getEnablePrimaryTrackMagnet()&&p===d.trackId&&this.isPrimaryTrackId(d.trackId)){c=d.trackId,l.set(d.clipId,d.clip),o.set(d.clipId,u);continue}let f=p;if(!(this.doesMultiDragPlacementOverlap(a,p,u)&&(f=this.resolveMultiDragOverlapTargetTrackId(a,u,p),!f))){if(this.reserveMultiDragPlacement(a,f,u),f===d.trackId){if(u.startTime===d.clip.startTime&&u.endTime===d.clip.endTime)continue;this.updateClipPositionSilently(d.trackId,d.clipId,u.startTime),n.push({clipId:d.clipId,previousState:d.clip,newState:u});continue}this.updateClipPositionSilently(d.trackId,d.clipId,u.startTime),this.moveClipToTrackWithHistorySnapshot(d.clipId,f,d.clip,u)}}return c&&o.size>0&&n.push(...this.compactPrimaryTrackAfterMultiDrag(c,o,l)),n.length>0&&this.getTimelineHistoryRecorder().recordClipUpdate(n[0].newState,void 0,n),!0}finalizeMultiDragSameTrack(e,t){return this.commitMultiDragPlacements(e,t,i=>i.trackId,{compactSameTrackPrimary:!0})}compactPrimaryTrackAfterMultiDrag(e,t,i){var d;if(!this.getEnablePrimaryTrackMagnet()||!this.isPrimaryTrackId(e))return[];const r=this.getTrackCollection().findById(e),n=this.getStableStartOrderedClips(((d=r==null?void 0:r.getClips)==null?void 0:d.call(r))??[]);if(n.length===0)return[];const a=new Map(n.map(u=>[u.id,u])),o=new Map(a);i.forEach((u,p)=>{o.set(p,u)});const l=this.buildPrimaryTrackMultiDragOrderedClips(n,t),c=this.buildPrimaryTrackContinuousClips(l),h=[];return c.forEach(u=>{const p=a.get(u.id),f=o.get(u.id);!p||!f||((p.startTime!==u.startTime||p.endTime!==u.endTime)&&this.updateClipPositionSilently(e,u.id,u.startTime),(f.startTime!==u.startTime||f.endTime!==u.endTime)&&h.push({clipId:u.id,previousState:f,newState:u}))}),h}previewMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackPreviewDestination(r,t.targetTrackY,i.trackId);if(n.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(n.trackType,n.insertionPlacement,n.referenceTrackId),!0;if(n.status!=="existing_track"||n.targetTrackId===i.trackId)return!1;const a=this.resolveTrackIndexDelta(i.trackId,n.targetTrackId,i.clip.type);if(a===null)return!1;const o=new Map;this.appendPreviewClip(o,n.targetTrackId,r);for(const l of e.selectedClipIds){if(l===t.draggedClipId)continue;const c=e.clips.get(l);if(!c)continue;const h=this.buildMovedClipSnapshot(c.clip,t.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(c,a,h);!d||d===c.trackId||this.appendPreviewClip(o,d,h)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackMoveDestination(r,t.targetTrackY,i.trackId);if(n.status==="blocked"||n.status==="same_track")return!1;const a=n.targetTrackId;if(!a)return!1;const o=this.resolveTrackIndexDelta(i.trackId,a,i.clip.type);return o===null?!1:this.commitMultiDragPlacements(e,t,(l,c)=>l.clipId===t.draggedClipId?a:this.resolveMultiDragTargetTrackId(l,o,c))}resolveTrackIndexDelta(e,t,i){const r=this.getTrackIdsByType(i),n=r.indexOf(e),a=r.indexOf(t);return n===-1||a===-1?null:a-n}resolveMultiDragTargetTrackId(e,t,i){const r=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return e.trackId;const n=this.calculateTrackY(r)+1,a=this.resolveCrossTrackMoveDestination(i,n,e.trackId);return a.status==="blocked"?r:a.targetTrackId}resolveMultiDragPreviewTargetTrackId(e,t,i){const r=this.findTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return null;const n=this.calculateTrackY(r)+1,a=this.resolveCrossTrackPreviewDestination(i,n,e.trackId);return a.status==="existing_track"?a.targetTrackId:null}buildMovedClipSnapshot(e,t,i=!1){let r=e.startTime+t;if(i){const n=this.getDurationState();r=Math.max(0,Math.min(r,n-e.duration))}else r=Math.max(0,r);return{...e,startTime:r,endTime:r+e.duration}}appendPreviewClip(e,t,i){const r=e.get(t);if(r){r.push(i);return}e.set(t,[i])}resolveCrossTrackMoveDestination(e,t,i){if(!this.trackManager||!this.getTimelineCommands)return{status:"blocked"};const r=this.trackManager.getTracks(),n=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);if(n.status==="missing_target_track_by_position")return O.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return O.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:e.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};O.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const a=this.createTrack(n.trackType,void 0,n.insertionPlacement,n.referenceTrackId);return a?{status:"move_to_track",targetTrackId:a}:{status:"blocked"}}resolveCrossTrackPreviewDestination(e,t,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const r=this.trackManager.getTracks();if(!Array.isArray(r)||r.length===0)return{status:"clear"};const n=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);return n.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:n.targetTrackId}:n.status==="new_track_insertion"?{status:"new_track_insertion",trackType:n.trackType,insertionPlacement:n.insertionPlacement,referenceTrackId:n.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(e,t,i){let r=this.getTrackIdsByType(t);const n=r.indexOf(e);if(n===-1)return null;let a=n+i;for(;a<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;r=this.getTrackIdsByType(t),a+=1}for(;a>=r.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;r=this.getTrackIdsByType(t)}return r[a]??null}findTrackIdByRelativeIndex(e,t,i){const r=this.getTrackIdsByType(t),n=r.indexOf(e);if(n===-1)return null;const a=n+i;return a<0||a>=r.length?null:r[a]??null}getTrackIdsByType(e){if(!this.trackManager)return[];const t=this.trackManager.getTracks();return t?t.filter(i=>i.type===e).map(i=>i.id):[]}updateClipPositionSilently(e,t,i){const r=this.getTrackCollection().findById(e),n=r==null?void 0:r.updateClipPosition;n&&this.withHistoryBoundary("suppressed",()=>{n.call(r,t,i,!0)})}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new Z.Rect({fill:xn.fill,stroke:xn.stroke,strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(t=this.selectionBoxLayer)==null||t.add(e),this.selectionBoxRect=e,e}showSelectionBoxRect(e,t,i,r){var a;const n=this.ensureSelectionBoxRect();n.x(e),n.y(t),n.width(Math.max(i,1)),n.height(Math.max(r,1)),n.visible(!0),(a=this.selectionBoxLayer)==null||a.batchDraw()}hideSelectionBoxRect(){var e;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(e=this.selectionBoxLayer)==null||e.batchDraw())}handleStageMouseDown(e){if(e.button!==0)return;const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,a=e.clientY-r.top;if(this.isPointOnClip(n,a))return;this.isBoxSelecting=!1,this.boxSelectStartX=n,this.boxSelectStartY=a;const l=h=>{this.handleBoxSelectMove(h)},c=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",c)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",c)}handleBoxSelectMove(e){const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,a=e.clientY-r.top,o=Math.abs(n-this.boxSelectStartX),l=Math.abs(a-this.boxSelectStartY);if(!this.isBoxSelecting&&(o>4||l>4)&&(this.isBoxSelecting=!0),!this.isBoxSelecting)return;const c=Math.min(this.boxSelectStartX,n),h=Math.min(this.boxSelectStartY,a),d=Math.abs(n-this.boxSelectStartX),u=Math.abs(a-this.boxSelectStartY);this.showSelectionBoxRect(c,h,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const e=this.selectionBoxRect;if(e){const t={x:e.x(),y:e.y(),width:e.width(),height:e.height()},i=this.getClipsIntersectingBox(t);this.setSelection(i,{preferredPrimaryClipId:this.selectedClipId})}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(e,t){for(const i of this.tracks){const n=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);if(!(t<n||t>n+a))for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ve(o.duration,this.getZoomState());if(e>=l&&e<=l+c&&t>=n+2&&t<=n+a-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const n=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ve(o.duration,this.getZoomState()),h=n+2,d=a-4,u=l+c,p=h+d,f=e.x+e.width,m=e.y+e.height;l<f&&u>e.x&&h<m&&p>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return Ae(e.getTrackType())}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(r=>r.id===e);return t?{...t,clips:t.clips.map(r=>({...r}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const r=this.resolveTrackInsertionFromRestoreAnchor(t);if(r){const u=this.createTrack(e.type,e.name,r.insertionPlacement,r.referenceTrackId,void 0,e.id);return this.muteTrack(u,e.isMuted??!1),u}const n=[...this.getTracks()].sort((u,p)=>u.order-p.order),a=n.find(u=>u.order>=e.order),o=a?n[n.findIndex(u=>u.id===a.id)-1]??null:n[n.length-1]??null;let l,c;a?(l="before_track",c=a.id):o&&(l="after_track",c=o.id);const h=this.createTrack(e.type,e.name,l,c,void 0,e.id);return this.muteTrack(h,e.isMuted??!1),h}getTrackRestoreAnchor(e){var r,n,a;if(!((r=this.trackManager)!=null&&r.getTracks))return null;const t=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=t.findIndex(o=>o.id===e);return i===-1?null:{previousTrackId:((n=t[i-1])==null?void 0:n.id)??null,nextTrackId:((a=t[i+1])==null?void 0:a.id)??null}}resolveTrackInsertionFromRestoreAnchor(e){return e?e.previousTrackId&&this.getTrackCollection().findById(e.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:e.previousTrackId}:e.nextTrackId&&this.getTrackCollection().findById(e.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:e.nextTrackId}:null:null}resolveTrackIdByClipId(e){var a;const t=this.getTimelineCommands();if(typeof t.findClipById=="function")return((a=t.findClipById(this.tracks,e))==null?void 0:a.trackId)??null;const i=this.getTrackCollection();if(typeof i.findTrackByClipId=="function"){const o=i.findTrackByClipId(e);if(o)return o.getId()}const n=(Array.isArray(this.tracks)?this.tracks:[]).find(o=>o.getClips().some(l=>l.id===e));return(n==null?void 0:n.getId())??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var a;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=ln(e),n=Ns(e);if(r!==t){this.lastTrackDuration=r;const o=Gs(r);this.setDurationState(o),(a=this.timeline)==null||a.setDuration(o),this.updateViewportLayout()}if(n!==i&&(this.lastReportedTrackDuration=n,this.emitEvent("track_duration_change",{duration:n})),e.length===0&&this.getCurrentTimeState()!==0&&this.setCurrentTime(0),e.length>0){const o=kt(e);o>0&&this.getCurrentTimeState()>o&&this.setCurrentTime(o)}r===t&&n===i||O.debugLazy("TimelineManager",()=>`Track duration changed: total=${n}ms, extent=${r}ms, timeline=${Gs(r)}ms`)}resolveSelectedClipSnapshot(){return yo({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}}})}resolveSelectionChangeData(){return ep({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}},getSelectedClipIds:()=>{try{return this.getSelectedClipIds()}catch{return[]}},canSplitSelectedClip:()=>{try{return this.canSplitSelectedClip()}catch{return!1}},getSelectedClipAudioAction:()=>{try{return this.getSelectedClipAudioAction()}catch{return null}}})}commitPreviewVisualTransform(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="video"&&i.type!=="text")return;const r=Pe(i.visualTransform),n=Pe(t);wn(r,n)||this.updateClip(e,{visualTransform:n})}commitPreviewTextFontSize(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=De(i.textStyle),n=Math.max(ci.MIN,Math.min(ci.MAX,Math.round(t)));r.fontSize!==n&&this.updateClip(e,{textStyle:{...r,fontSize:n}})}commitPreviewTextRotation(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=De(i.textStyle),n=Math.round(t);r.rotation!==n&&this.updateClip(e,{textStyle:{...r,rotation:n}})}clearAllTracksAndClips(){this.withHistoryBoundary("reset",()=>{var t,i,r,n;const e=this.getTracks();for(const a of e){const o=this.getTrackCollection().findById(a.id);if(o){const l=[...o.getClips()];for(const c of l)(t=o.removeClip)==null||t.call(o,c.id)}}for(const a of e){const o=a.id,l=this.getTrackCollection().findById(o);(r=(i=l==null?void 0:l.getTrackGroup)==null?void 0:i.call(l))==null||r.destroy(),this.getTrackCollection().removeById(o)}this.trackManager.clearAllTracks(),this.updateAllTrackPositions(),(n=this.stage)==null||n.batchDraw(),this.clearHistory()})}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=hn;exports.CLIP_LAYER=wo;exports.Clip=$i;exports.ClipConfigPanel=uo;exports.DEFAULT_CLIP_VIEW_STATE=ia;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Be;exports.DEFAULT_TEXT_CLIP_DURATION_MS=ra;exports.DEFAULT_TEXT_CLIP_STYLE=ea;exports.DEFAULT_TIMELINE_DURATION_MS=Qt;exports.DiagnosticsCenter=qa;exports.HistoryManager=an;exports.MIN_CLIP_LINE_WIDTH=hi;exports.PREVIEW_ASPECT_RATIO_PRESETS=ko;exports.SNAP_SCORING=sa;exports.TEXT_CLIP_FONT_SIZE_LIMITS=ci;exports.TIMELINE_LEFT_PADDING=pe;exports.TIME_SCALE=xo;exports.TRACK_HEIGHT=Gi;exports.TimeUtils=U;exports.TimelineClipConfigController=So;exports.TimelineManager=Jp;exports.Track=ir;exports.TrackInfoPanel=ho;exports.TrackManager=vo;exports.VOICE_LINKED_TEXT_REGEN_DEBOUNCE_MS=na;exports.ZOOM_ANIMATION=Po;exports.ZOOM_GESTURE=Fr;exports.ZOOM_PRESETS=Me;exports.createClipViewState=aa;exports.createClipWithViewState=pn;exports.defaultDarkTheme=Xi;exports.devConsole=O;exports.isAudioOnlyTtsClipCandidate=ta;exports.isAutoPreviewAspectRatioMode=_t;exports.isTtsAudioClip=Le;exports.mergeDiagnosticRuntimeState=ja;exports.normalizePreviewAspectRatio=je;exports.normalizePreviewAspectRatioMode=dn;exports.resolveAspectRatioBaselineDimensions=un;exports.resolveTextClipStyle=De;exports.resolveTheme=qi;
733
+ `}getContainerStyle(e){return[`background-color:${e.backgroundColor}`,"border-radius:4px",`color:${e.textColor}`,'font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size:13px","display:flex","flex-direction:column","overflow:hidden","height:100%",`--clip-slider-fill-start:${_.sliderFillStart}`,`--clip-slider-fill-end:${_.sliderFillEnd}`,`--clip-slider-road:${_.sliderRoad}`,`--clip-slider-thumb-border:${_.sliderThumbBorder}`,`--clip-slider-thumb-shadow:${xe.sliderThumbShadow}`].join(";")}getSliderStyle(e,t,i){const r=Number(e||0),n=Number(t||100),a=Number(i||0),o=n-r,l=o<=0?0:(a-r)/o*100;return["flex:1","min-width:0",`--clip-slider-progress:${Math.max(0,Math.min(100,l))}%`].join(";")}supportsVoicePanel(e){return e.groupKind==="text"||e.groupKind==="audio"&&e.supportsVoiceBatch}getTransform(e){return(e==null?void 0:e.visualTransform)??{x:.5,y:.5,scale:1}}calculatePresetPosition(e,t,i){const n=this.getTransform(e).scale/2,a={left:n,center:.5,right:1-n},o={top:n,center:.5,bottom:1-n};return{x:a[t],y:o[i]}}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}static createColorInputHandler(e){return t=>{const i=t.target.value;cancelAnimationFrame(xt.colorRafId),xt.colorRafId=requestAnimationFrame(()=>{e.callbacks.onTextStyleChange("color",i)})}}};g(xt,"colorRafId",0);let sn=xt;const Ed={...ye};function xs(s){return s?{primaryClip:s,selectedClips:[s],selectionCount:1,groupKind:s.type,supportsVoiceBatch:s.type==="text"||Le(s),supportsTextContentBatch:s.type==="text",supportsVisualBatch:s.type==="video",supportsVolumeBatch:s.type==="video"||s.type==="audio"}:{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1}}function Rd(s,e){return s.groupKind!==e.groupKind||s.selectionCount!==e.selectionCount||s.supportsVoiceBatch!==e.supportsVoiceBatch||s.supportsTextContentBatch!==e.supportsTextContentBatch||s.supportsVisualBatch!==e.supportsVisualBatch||s.supportsVolumeBatch!==e.supportsVolumeBatch||s.selectedClips.length!==e.selectedClips.length?!1:s.selectedClips.every((t,i)=>{var r;return t.id===((r=e.selectedClips[i])==null?void 0:r.id)})}class uo{constructor(e){g(this,"container");g(this,"theme");g(this,"renderer",new sn);g(this,"onClipUpdate");g(this,"onGenerateVoice");g(this,"voiceCatalog");g(this,"currentClip",null);g(this,"selectionState",xs(null));g(this,"activeTab","visual");g(this,"iconCache",new Map);g(this,"pendingPreferredTab",null);g(this,"selectedVoiceId",null);g(this,"activeVoiceFilterTag","男");g(this,"textDraftContent","");g(this,"followTextUpdates",!0);g(this,"voiceLoadingBusyCount",0);g(this,"isVoiceLoadingOverlayRendered",!1);g(this,"isVoiceLoadingOverlayExiting",!1);g(this,"voiceLoadingOverlayHideTimer",null);g(this,"voiceErrorMessage",null);g(this,"voicePreviewAudio",null);g(this,"previewingVoiceId",null);g(this,"handleVoicePreviewEnded",()=>{this.stopVoicePreview()});this.container=e.container,this.theme=e.theme??Ed,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",be("OmAi-camera")),this.iconCache.set("OmAi-accept",be("OmAi-accept")),this.iconCache.set("OmAi-loading",be("OmAi-loading")),this.iconCache.set("OmAi-text",be("OmAi-text")),this.renderer.mount(this.container),this.render()}setClip(e){this.setSelectionState(xs(e))}setSelectionState(e){var l,c,h,d,u,p;const t=e,i=this.selectionState,r=((l=this.currentClip)==null?void 0:l.id)??null,n=((c=t.primaryClip)==null?void 0:c.id)??null,a=r!==n,o=!Rd(i,t);a&&this.stopVoicePreview(!1),this.selectionState=t,this.currentClip=t.primaryClip,a||o?(this.voiceErrorMessage=null,this.textDraftContent=((h=this.currentClip)==null?void 0:h.textContent)??((d=this.currentClip)==null?void 0:d.name)??"",this.syncVoiceStateForSelection(t)):((u=this.currentClip)==null?void 0:u.type)==="text"?this.textDraftContent=this.currentClip.textContent??this.currentClip.name??"":((p=this.currentClip)==null?void 0:p.type)==="audio"&&t.supportsVoiceBatch?(this.followTextUpdates=this.currentClip.ttsFollowTextUpdates??!1,this.ensureVoiceFilters()):this.currentClip||this.resetVoiceState(),this.syncActiveTab(t),this.render()}setPreferredTab(e){this.pendingPreferredTab=e}showVoiceGenerationLoading(){this.setVoiceGenerationBusy(!0)}hideVoiceGenerationLoading(){this.setVoiceGenerationBusy(!1)}setVoiceGenerationBusy(e){if(this.voiceLoadingBusyCount=Math.max(0,this.voiceLoadingBusyCount+(e?1:-1)),this.voiceLoadingBusyCount>0){this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.isVoiceLoadingOverlayRendered=!0,this.isVoiceLoadingOverlayExiting=!1,this.render();return}if(!this.isVoiceLoadingOverlayRendered){this.render();return}this.isVoiceLoadingOverlayExiting=!0,this.voiceLoadingOverlayHideTimer!==null&&window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=window.setTimeout(()=>{this.isVoiceLoadingOverlayRendered=!1,this.isVoiceLoadingOverlayExiting=!1,this.voiceLoadingOverlayHideTimer=null,this.render()},180),this.render()}destroy(){this.stopVoicePreview(!1),this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.renderer.destroy()}render(){const e=this.getAvailableTabs(this.selectionState);this.renderer.update({clip:this.currentClip,selectionState:this.selectionState,activeTab:this.activeTab,availableTabs:e,theme:this.theme,emptyStateMessage:this.getEmptyStateMessage(this.selectionState),isTextContentEditable:this.selectionState.supportsTextContentBatch,loadingIconSvg:this.iconCache.get("OmAi-loading")??"",selectedIconSvg:this.iconCache.get("OmAi-accept")??"",textDraftContent:this.textDraftContent,voiceCatalog:this.voiceCatalog,selectedVoiceId:this.selectedVoiceId,previewingVoiceId:this.previewingVoiceId,activeVoiceFilterTag:this.activeVoiceFilterTag,followTextUpdates:this.followTextUpdates,isVoiceLoadingOverlayVisible:this.isVoiceLoadingOverlayRendered,isVoiceLoadingOverlayExiting:this.isVoiceLoadingOverlayExiting,voiceErrorMessage:this.voiceErrorMessage,callbacks:{onTabChange:t=>{this.activeTab=t,this.render()},onTransformChange:(t,i)=>{this.handleTransformChange(t,i)},onPresetSelect:(t,i)=>{this.handleTransformChanges({x:t,y:i})},onVolumeChange:t=>{this.handleVolumeChange(t)},onTextContentInput:t=>{this.handleTextContentInput(t)},onTextContentCommit:()=>{this.handleTextContentCommit()},onTextStyleChange:(t,i)=>{this.handleTextStyleChange(t,i)},onVoiceFilterChange:t=>{this.handleVoiceFilterChange(t)},onVoiceSelect:t=>{this.handleVoiceSelect(t)},onVoiceFollowTextUpdatesChange:t=>{this.handleVoiceFollowTextUpdatesChange(t)},onGenerateVoice:async()=>{await this.handleGenerateVoice()}}})}getAvailableTabs(e=this.selectionState){return e.groupKind==="text"?["text","voice"]:e.groupKind==="audio"?e.supportsVoiceBatch?["voice","audio"]:["audio"]:e.groupKind==="video"?["visual","audio"]:[]}getEmptyStateMessage(e=this.selectionState){return e.groupKind==="empty"?"请选择一个片段":e.groupKind==="mixed"?"暂不支持跨类型批量配置":null}resetVoiceState(){this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=!1,this.stopVoicePreview(!1)}syncVoiceStateForSelection(e){if(!this.supportsVoicePanel(e)||!e.primaryClip){this.resetVoiceState();return}this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=e.primaryClip.type==="audio"?e.primaryClip.ttsFollowTextUpdates??!1:!0,this.ensureVoiceFilters()}syncActiveTab(e){const t=this.getAvailableTabs(e);if(t.length===0){this.activeTab="visual",this.pendingPreferredTab=null;return}if(this.pendingPreferredTab&&t.includes(this.pendingPreferredTab)){this.activeTab=this.pendingPreferredTab,this.pendingPreferredTab=null;return}t.includes(this.activeTab)||(this.activeTab=t[0],this.pendingPreferredTab=null)}supportsVoicePanel(e=this.selectionState){return e.groupKind==="text"||e.groupKind==="audio"&&e.supportsVoiceBatch}ensureVoiceFilters(){if(this.voiceCatalog.length===0){this.selectedVoiceId=null,this.stopVoicePreview(!1);return}this.selectedVoiceId&&!this.voiceCatalog.some(e=>e.id===this.selectedVoiceId)&&(this.selectedVoiceId=null,this.stopVoicePreview(!1))}handleVoiceFilterChange(e){const t=e==="男"||e==="女"||e==="普通话"||e==="粤语"?e:null;this.activeVoiceFilterTag=this.activeVoiceFilterTag===t?null:t,this.render()}async handleVoiceSelect(e){const t=this.voiceCatalog.find(r=>r.id===e)??null,i=this.previewingVoiceId===e;if(this.selectedVoiceId=e,this.voiceErrorMessage=null,this.render(),!(t!=null&&t.audiofile)){this.stopVoicePreview();return}if(i){this.stopVoicePreview();return}await this.playVoicePreview(t)}handleVoiceFollowTextUpdatesChange(e){var t;this.followTextUpdates=e,((t=this.currentClip)==null?void 0:t.type)==="audio"&&this.selectionState.supportsVoiceBatch&&this.onClipUpdate&&(this.currentClip={...this.currentClip,ttsFollowTextUpdates:e},this.onClipUpdate(this.currentClip.id,{ttsFollowTextUpdates:e})),this.render()}async handleGenerateVoice(){if(!this.currentClip||!this.onGenerateVoice)return;const e=this.voiceCatalog.find(t=>t.id===this.selectedVoiceId);if(!e){this.voiceErrorMessage="请选择一个音色",this.render();return}this.voiceErrorMessage=null,this.render();try{await this.onGenerateVoice(this.currentClip,e,this.followTextUpdates)}catch(t){this.voiceErrorMessage=t instanceof Error?t.message:"音色生成失败"}this.render()}handleVolumeChange(e){if(!this.currentClip||!this.onClipUpdate)return;const t=Math.max(0,Math.min(1,e));this.currentClip={...this.currentClip,volume:t},this.render(),this.onClipUpdate(this.currentClip.id,{volume:t})}clampValue(e,t){return e==="scale"?Math.max(.1,Math.min(8,t)):t}handleTransformChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(e,t),n={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:i};this.currentClip={...this.currentClip,visualTransform:n},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:n})}handleTransformChanges(e){if(!this.currentClip||!this.onClipUpdate)return;const i={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1}};e.x!==void 0&&(i.x=this.clampValue("x",e.x)),e.y!==void 0&&(i.y=this.clampValue("y",e.y)),e.scale!==void 0&&(i.scale=this.clampValue("scale",e.scale)),this.currentClip={...this.currentClip,visualTransform:i},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:i})}stopVoicePreview(e=!0){if(this.voicePreviewAudio){this.voicePreviewAudio.removeEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio.pause();try{this.voicePreviewAudio.currentTime=0}catch{}this.voicePreviewAudio=null}if(this.previewingVoiceId!==null){this.previewingVoiceId=null,e&&this.render();return}e&&this.render()}async playVoicePreview(e){if(!e.audiofile)return;this.stopVoicePreview(!1);const t=new Audio(e.audiofile);t.preload="auto",t.addEventListener("ended",this.handleVoicePreviewEnded),this.voicePreviewAudio=t,this.previewingVoiceId=e.id,this.render();try{await t.play()}catch(i){this.voicePreviewAudio===t&&(this.stopVoicePreview(!1),this.voiceErrorMessage=i instanceof Error?i.message:"试听播放失败",this.render())}}handleTextContentInput(e){if(this.selectionState.supportsTextContentBatch){if(this.textDraftContent=e,!this.currentClip||!this.onClipUpdate){this.render();return}this.currentClip={...this.currentClip,textContent:e},this.onClipUpdate(this.currentClip.id,{textContent:e})}}handleTextContentCommit(){if(!this.currentClip||!this.onClipUpdate||!this.selectionState.supportsTextContentBatch)return;const e=this.textDraftContent,t=this.currentClip.textContent??this.currentClip.name??"";e!==t&&(this.currentClip={...this.currentClip,textContent:e},this.render(),this.onClipUpdate(this.currentClip.id,{textContent:e}))}handleTextStyleChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;if(e==="x"||e==="y"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;const o={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:Math.max(0,Math.min(1,n))};this.currentClip={...this.currentClip,visualTransform:o},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:o});return}const r={...De(this.currentClip.textStyle)};if(e==="fontSize"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.fontSize=Math.max(ci.MIN,Math.min(ci.MAX,n))}else if(e==="rotation"){const n=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(n))return;r.rotation=n}else r.color=String(t);this.currentClip={...this.currentClip,textStyle:r},this.render(),this.onClipUpdate(this.currentClip.id,{textStyle:r})}}function Md(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class _s{constructor(e){this.timelineStore=e}selectClip(e){return this.updateSelection(e)}clearSelection(){return this.updateSelection(null)}findClipById(e,t){for(const i of e){const r=i.getClips().find(n=>n.id===t);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}findClipAtTime(e,t){for(const i of e){const r=i.getClips().find(n=>t>=n.startTime&&t<n.startTime+n.duration);if(r)return{clip:r,track:i,trackId:this.resolveTrackId(i)}}return null}prepareRemoveClip(e,t){const i=this.findClipById(t,e);return i?{exists:!0,clip:i.clip,trackId:i.trackId,shouldClearSelection:this.timelineStore.getPrimarySelectedClipId()===e}:{exists:!1,clip:null,trackId:null,shouldClearSelection:!1}}prepareMoveClipToTrack(e,t,i){var h;const r=this.findClipById(i,e);if(!r||!r.trackId)return{status:"missing_source_track",clipId:e,targetTrackId:t};const{clip:n,track:a,trackId:o}=r;if(o===t)return{status:"noop",clipId:e,sourceTrackId:o,targetTrackId:t};const l=i.find(d=>this.resolveTrackId(d)===t);if(!l)return{status:"missing_target_track",clipId:e,targetTrackId:t,sourceTrackId:o};const c=(h=l.getTrackType)==null?void 0:h.call(l);return c&&c!==n.type?{status:"track_type_mismatch",clipId:e,targetTrackId:t,sourceTrackId:o}:{status:"ready",clip:n,sourceTrack:a,sourceTrackId:o,targetTrack:l,targetTrackId:t}}planTrackPlacement(e,t){var n;const i=e.startTime+e.duration;for(const a of t){if(((n=a.getTrackType)==null?void 0:n.call(a))!==e.type)continue;if(!a.getClips().some(l=>e.startTime<l.endTime&&i>l.startTime)){const l=this.resolveTrackId(a);if(l)return{status:"use_existing_track",trackId:l}}}const r=t.filter(a=>{var o;return((o=a.getTrackType)==null?void 0:o.call(a))===e.type}).length+1;return{status:"create_track",trackType:e.type,suggestedTrackName:`${Md(e.type)}轨道 ${r}`,insertionPlacement:e.type==="text"||e.type==="video"?"top_of_type_region":"bottom_of_type_region"}}planCrossTrackMove(e,t,i,r,n,a){var f;const o=this.resolveTrackTargetByY(t,r,n,e.type);if(o.status==="create_track")return{status:"create_track",trackType:e.type,insertionPlacement:o.insertionPlacement};if(o.status==="missing_target_track_by_position")return{status:"missing_target_track_by_position"};const l=o.targetTrackId;if(l===i)return{status:"same_track",targetTrackId:l};const c=a.find(m=>this.resolveTrackId(m)===l);if(!c)return{status:"missing_target_track_view",targetTrackId:l};const h=this.resolveTrackType(c)??((f=n.find(m=>m.id===l))==null?void 0:f.type)??null;if(h!==e.type)return{status:"track_type_mismatch",targetTrackId:l,targetTrackType:h};if(!this.hasOverlapOnTrack(e,c))return{status:"move_to_track",targetTrackId:l};const d=this.resolvePreferredInsertionPlacement(e.type,l,t,r,n);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=n.filter(m=>m.type===e.type).map(m=>m.id),p=u.indexOf(l);for(let m=1;m<=u.length;m+=1){const S=p-m;if(S>=0){const v=u[S],C=a.find(k=>this.resolveTrackId(k)===v);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:v}}const T=p+m;if(T<u.length){const v=u[T],C=a.find(k=>this.resolveTrackId(k)===v);if(C&&!this.hasOverlapOnTrack(e,C))return{status:"move_to_track",targetTrackId:v}}}return{status:"create_track",trackType:e.type,insertionPlacement:e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary"}}planCrossTrackPreview(e,t,i,r,n,a){const o=this.planCrossTrackMove(e,t,i,r,n,a);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(e){const t=Math.max(0,e);return this.updateCurrentTime(t)}setZoom(e){const t=Math.max(Me.MIN,Math.min(Me.MAX,e));return this.updateZoom(t)}setSpeed(e){const t=Math.max(.1,Math.min(10,e));return this.updateSpeed(t)}updateSelection(e){const t=this.timelineStore.getPrimarySelectedClipId();return t===e?{previousClipId:t,nextClipId:e,changed:!1}:(e===null?this.timelineStore.clearSelection():this.timelineStore.setPrimarySelectedClipId(e),{previousClipId:t,nextClipId:e,changed:!0})}updateCurrentTime(e){const t=this.timelineStore.getCurrentTime();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setCurrentTime(e),{previousValue:t,nextValue:e,changed:!0})}updateZoom(e){const t=this.timelineStore.getZoom();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setZoom(e),{previousValue:t,nextValue:e,changed:!0})}updateSpeed(e){const t=this.timelineStore.getSpeed();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setSpeed(e),{previousValue:t,nextValue:e,changed:!0})}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}resolveTrackType(e){return typeof e.getTrackType=="function"?e.getTrackType():e.type??null}resolveTrackTargetByY(e,t,i,r){let n=t,a=null,o=null;for(const l of i){const c=Ae(l.type),h=n+c;if(l.type===r&&(a===null&&(a=n),o=h),e>=n&&e<h)return{status:"existing_track",targetTrackId:l.id};n=h}return r==="text"&&a!==null&&e<a?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="video"&&a!==null&&e<a?{status:"create_track",insertionPlacement:"top_of_type_region"}:r==="audio"&&o!==null&&e>=o?{status:"create_track",insertionPlacement:"bottom_of_type_region"}:{status:"missing_target_track_by_position"}}resolvePreferredInsertionPlacement(e,t,i,r,n){let a=r;const o=n.map(d=>{const u=a,p=Ae(d.type),f=u+p;return a=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:p}}).filter(d=>d.type===e),l=o.findIndex(d=>d.id===t);if(l===-1)return null;const c=o[l],h=Math.min(12,Math.max(6,Math.floor(c.height/4)));return c.role==="primary"?{insertionPlacement:e==="text"||e==="video"?"before_track":"after_track",referenceTrackId:t}:l<o.length-1&&i>=c.endY-h?{insertionPlacement:"after_track",referenceTrackId:t}:{insertionPlacement:"before_track",referenceTrackId:t}}hasOverlapOnTrack(e,t){const i=e.startTime+e.duration;return t.getClips().some(r=>r.id===e.id?!1:e.startTime<r.endTime&&i>r.startTime)}}class an{constructor(e,t,i,r=100){g(this,"state");g(this,"maxHistorySize",100);g(this,"onActionUndo");g(this,"onActionRedo");g(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=r,this.onActionUndo=e,this.onActionRedo=t,this.onHistoryChange=i}addAction(e){this.state.past.length>=this.maxHistorySize&&this.state.past.shift(),this.state.past.push({...e,timestamp:Date.now()}),this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}undo(){if(this.state.past.length===0)return!1;const e=this.state.past.pop();return this.state.future.push(e),this.onActionUndo(e),this.onHistoryChange&&this.onHistoryChange(),!0}redo(){if(this.state.future.length===0)return!1;const e=this.state.future.pop();return this.state.past.push(e),this.onActionRedo(e),this.onHistoryChange&&this.onHistoryChange(),!0}clear(){this.state.past=[],this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}canUndo(){return this.state.past.length>0}canRedo(){return this.state.future.length>0}getState(){return{...this.state}}createAddClipAction(e,t=null,i=null,r=null){return{type:"add_clip",data:{clip:e,targetTrackId:t,targetTrackSnapshot:i,targetTrackRestoreAnchor:r},timestamp:Date.now()}}createRemoveClipAction(e){return{type:"remove_clip",data:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null},timestamp:Date.now()}}createRemoveClipActionWithTrackSnapshot(e,t,i,r=null){return{type:"remove_clip",data:{clip:e,sourceTrackId:t,sourceTrackSnapshot:i,sourceTrackRestoreAnchor:r},timestamp:Date.now()}}createUpdateClipAction(e,t,i){return{type:"update_clip",data:{clipId:e,updates:t,previousState:i},timestamp:Date.now()}}createSplitClipAction(e,t,i,r){return{type:"split_clip",data:{originalClip:e,clip1:t,clip2:i,sourceTrackId:(r==null?void 0:r.trackId)??null,sourceTrackSnapshot:(r==null?void 0:r.trackSnapshot)??null,sourceTrackRestoreAnchor:(r==null?void 0:r.trackRestoreAnchor)??null},timestamp:Date.now()}}createMoveClipAction(e,t,i){return{type:"move_clip",data:{clipId:e,newStartTime:t,previousStartTime:i},timestamp:Date.now()}}createResizeClipAction(e,t,i,r,n){return{type:"resize_clip",data:{clipId:e,newDuration:t,newStartTime:i,previousDuration:r,previousStartTime:n},timestamp:Date.now()}}createSetTimeAction(e,t){return{type:"set_time",data:{newTime:e,previousTime:t},timestamp:Date.now()}}createRemoveGapsAction(e){return{type:"remove_gaps",data:{clipsBefore:e},timestamp:Date.now()}}createMultiClipUpdateAction(e){return{type:"multi_clip_update",data:{clipUpdates:e},timestamp:Date.now()}}createMoveClipBetweenTracksAction(e,t,i,r,n,a,o,l=null,c=null){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:r,clipAfter:n,sourceTrackSnapshot:a,targetTrackSnapshot:o,sourceTrackRestoreAnchor:l,targetTrackRestoreAnchor:c},timestamp:Date.now()}}createSeparateClipAudioAction(e,t,i,r){return{type:"separate_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createRestoreClipAudioAction(e,t,i,r){return{type:"restore_clip_audio",data:{videoClipBefore:e,videoClipAfter:t,audioClip:i,audioTrackId:r},timestamp:Date.now()}}createSetPrimaryTrackMagnetAction(e,t){return{type:"set_primary_track_magnet",data:{previousEnabled:e,nextEnabled:t},timestamp:Date.now()}}createCompoundAction(e,t){return{type:"compound",data:{actions:e,...t?{label:t}:{}},timestamp:Date.now()}}}class As{constructor(e){this.target=e}executeUndo(e){this.executeUndoInternal(e,new Map)}executeRedo(e){this.executeRedoInternal(e,new Map)}executeUndoInternal(e,t){var i,r,n,a;switch(e.type){case"add_clip":this.target.removeClip(this.normalizeAddClipActionData(e.data).clip.id);break;case"remove_clip":{const o=this.normalizeRemoveClipActionData(e.data);let l=!1;const c=this.resolveTrackIdForHistorySnapshot(o.sourceTrackSnapshot,o.sourceTrackId,t,o.sourceTrackRestoreAnchor);if(c&&(l=this.target.addClipToTrack(c,o.clip)),!l){const h=this.target.findTrackByClipId(o.clip.id)||this.target.getDefaultTrack();h==null||h.addClip(o.clip)}(r=(i=this.target).loadClipThumbnails)==null||r.call(i,o.clip);break}case"update_clip":this.target.updateClip(e.data.clipId,e.data.previousState);break;case"split_clip":{this.withClipRemovalBatch(()=>{const o=this.normalizeSplitClipActionData(e.data),l=this.target.findTrackByClipId(e.data.clip1.id)||this.target.getDefaultTrack(),c=this.resolveTrackIdForHistorySnapshot(o.sourceTrackSnapshot,o.sourceTrackId,t,o.sourceTrackRestoreAnchor);if(this.target.removeClip(e.data.clip1.id),this.target.removeClip(e.data.clip2.id),c){this.target.addClipToTrack(c,e.data.originalClip);return}l==null||l.addClip(e.data.originalClip)});break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.previousStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.previousDuration,startTime:e.data.previousStartTime});break;case"remove_gaps":this.target.getClips().forEach(o=>this.target.removeClip(o.id)),e.data.clipsBefore.forEach(o=>{const l=this.target.findTrackByClipId(o.id)||this.target.getDefaultTrack();l==null||l.addClip(o)});break;case"multi_clip_update":e.data.clipUpdates.forEach(o=>{this.target.updateClip(o.clipId,o.previousState)});break;case"move_clip_between_tracks":{const o=this.normalizeMoveClipBetweenTracksActionData(e.data);this.restoreMovedClip(o.clipId,o.sourceTrackId,o.sourceTrackSnapshot,o.sourceTrackRestoreAnchor,o.clipBefore,t);break}case"separate_clip_audio":e.data.audioClip&&this.target.removeClip(e.data.audioClip.id),this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipBefore.id,e.data.videoClipBefore);break;case"set_primary_track_magnet":(a=(n=this.target).setPrimaryTrackMagnetEnabled)==null||a.call(n,e.data.previousEnabled);break;case"compound":[...e.data.actions].reverse().forEach(o=>{this.executeUndoInternal(o,t)});break;default:O.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:e.type})}}executeRedoInternal(e,t){var i,r,n,a;switch(e.type){case"add_clip":{const o=this.normalizeAddClipActionData(e.data);let l=!1;const c=this.resolveTrackIdForHistorySnapshot(o.targetTrackSnapshot,o.targetTrackId,t,o.targetTrackRestoreAnchor);if(c&&(l=this.target.addClipToTrack(c,o.clip)),!l){const h=this.target.findTrackByClipId(o.clip.id)||this.target.getDefaultTrack();h==null||h.addClip(o.clip)}(r=(i=this.target).loadClipThumbnails)==null||r.call(i,o.clip);break}case"remove_clip":this.target.removeClip(e.data.clip.id);break;case"update_clip":this.target.updateClip(e.data.clipId,e.data.updates);break;case"split_clip":{this.withClipRemovalBatch(()=>{const o=this.normalizeSplitClipActionData(e.data),l=this.target.findTrackByClipId(e.data.originalClip.id)||this.target.getDefaultTrack(),c=this.resolveTrackIdForHistorySnapshot(o.sourceTrackSnapshot,o.sourceTrackId,t,o.sourceTrackRestoreAnchor);if(this.target.removeClip(e.data.originalClip.id),c){this.target.addClipToTrack(c,e.data.clip1),this.target.addClipToTrack(c,e.data.clip2);return}l==null||l.addClip(e.data.clip1),l==null||l.addClip(e.data.clip2)});break}case"move_clip":this.target.updateClip(e.data.clipId,{startTime:e.data.newStartTime});break;case"resize_clip":this.target.updateClip(e.data.clipId,{duration:e.data.newDuration,startTime:e.data.newStartTime});break;case"remove_gaps":this.target.removeClipGaps();break;case"multi_clip_update":e.data.clipUpdates.forEach(o=>{this.target.updateClip(o.clipId,o.newState)});break;case"move_clip_between_tracks":{const o=this.normalizeMoveClipBetweenTracksActionData(e.data);this.restoreMovedClip(o.clipId,o.targetTrackId,o.targetTrackSnapshot,o.targetTrackRestoreAnchor,o.clipAfter,t);break}case"separate_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter),e.data.audioClip&&e.data.audioTrackId&&this.target.addClipToTrack(e.data.audioTrackId,e.data.audioClip);break;case"restore_clip_audio":this.target.updateClip(e.data.videoClipAfter.id,e.data.videoClipAfter);break;case"set_primary_track_magnet":(a=(n=this.target).setPrimaryTrackMagnetEnabled)==null||a.call(n,e.data.nextEnabled);break;case"compound":e.data.actions.forEach(o=>{this.executeRedoInternal(o,t)});break;default:O.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:e.type})}}restoreMovedClip(e,t,i,r,n,a){const o=this.resolveTrackIdForHistorySnapshot(i,t??(i==null?void 0:i.id)??null,a,r);o&&this.target.moveClipToTrack(e,o),this.target.updateClip(e,n)}withClipRemovalBatch(e){return this.target.withClipRemovalBatch?this.target.withClipRemovalBatch(e):e()}normalizeRemoveClipActionData(e){return"clip"in e?e:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null}}normalizeAddClipActionData(e){return"clip"in e?e:{clip:e,targetTrackId:null,targetTrackSnapshot:null,targetTrackRestoreAnchor:null}}normalizeSplitClipActionData(e){return{...e,sourceTrackId:e.sourceTrackId??null,sourceTrackSnapshot:e.sourceTrackSnapshot??null,sourceTrackRestoreAnchor:e.sourceTrackRestoreAnchor??null}}normalizeMoveClipBetweenTracksActionData(e){return{...e,sourceTrackRestoreAnchor:e.sourceTrackRestoreAnchor??null,targetTrackRestoreAnchor:e.targetTrackRestoreAnchor??null}}resolveTrackIdForHistorySnapshot(e,t,i,r){const n=(e==null?void 0:e.id)??t??null;if(n){const o=i.get(n);if(o)return o}if(!e)return t;const a=this.target.ensureTrackFromHistorySnapshot(e,this.resolveRestoreAnchor(r,i))??t;return n&&a&&i.set(n,a),a}resolveRestoreAnchor(e,t){return e?{previousTrackId:e.previousTrackId?t.get(e.previousTrackId)??e.previousTrackId:null,nextTrackId:e.nextTrackId?t.get(e.nextTrackId)??e.nextTrackId:null}:null}}const Dd=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],Ld=new Set(["thumbnails"]);function Bd(s,e){return Object.is(s,e)?!0:s===void 0||e===void 0?!1:typeof s=="object"&&typeof e=="object"?JSON.stringify(s)===JSON.stringify(e):!1}class Is{constructor(e){g(this,"transactionStack",[]);this.history=e}createAddClipAction(e,t=null,i=null,r=null){return this.history.createAddClipAction(e,t,i,r)}recordAddClip(e,t=null,i=null,r=null){const n=this.history.createAddClipAction(e,t,i,r);return this.recordAction(n),n}createRemoveClipAction(e,t=null,i=null,r=null){return t||i?this.history.createRemoveClipActionWithTrackSnapshot(e,t,i,r):this.history.createRemoveClipAction(e)}recordRemoveClip(e,t=null,i=null,r=null){const n=this.createRemoveClipAction(e,t,i,r);return this.recordAction(n),n}recordClipUpdate(e,t,i){const r=this.createClipUpdateAction(e,t,i);return r?(this.recordAction(r),r):null}recordSplitClip(e,t,i=null,r=null,n=null){const a={...e,duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},o={trackId:i,trackSnapshot:r,trackRestoreAnchor:n},l=this.history.createSplitClipAction(a,e,t,o);return this.recordAction(l),l}recordRemoveGaps(e){if(e.length===0)return null;const t=this.history.createRemoveGapsAction(e);return this.recordAction(t),t}recordMoveClipBetweenTracks(e,t,i,r,n,a,o,l=null,c=null){const h=this.history.createMoveClipBetweenTracksAction(e,t,i,r,n,a,o,l,c);return this.recordAction(h),h}recordSeparateClipAudio(e,t,i,r){const n=this.history.createSeparateClipAudioAction(e,t,i,r);return this.recordAction(n),n}recordRestoreClipAudio(e,t,i,r){const n=this.history.createRestoreClipAudioAction(e,t,i,r);return this.recordAction(n),n}createSeparateClipAudioAction(e,t,i,r){return this.history.createSeparateClipAudioAction(e,t,i,r)}createRestoreClipAudioAction(e,t,i,r){return this.history.createRestoreClipAudioAction(e,t,i,r)}recordSetPrimaryTrackMagnet(e,t){const i=this.history.createSetPrimaryTrackMagnetAction(e,t);return this.recordAction(i),i}recordCompoundAction(e,t){if(e.length===0)return null;const i=this.history.createCompoundAction(e,t);return this.recordAction(i),i}createClipUpdateAction(e,t,i){if(i&&i.length>0)return this.history.createMultiClipUpdateAction(i);if(!t)return null;const r={},n={};if(Dd.forEach(d=>{Bd(e[d],t[d])||(r[d]=e[d],n[d]=t[d])}),Object.keys(r).length===0)return null;const a=Object.keys(r);if(a.every(d=>Ld.has(d)))return null;const o=new Set(["startTime","endTime"]);if(a.includes("startTime")&&a.every(d=>o.has(d)))return this.history.createMoveClipAction(e.id,e.startTime,t.startTime);const c=new Set(["duration","startTime","endTime"]);return a.includes("duration")&&a.every(d=>c.has(d))?this.history.createResizeClipAction(e.id,e.duration,e.startTime,t.duration,t.startTime):this.history.createUpdateClipAction(e.id,r,n)}withTransaction(e,t){this.transactionStack.push({label:e,actions:[]});try{const i=t();return i instanceof Promise?i.then(r=>(this.finalizeTransaction(),r),r=>{throw this.finalizeTransaction(),r}):(this.finalizeTransaction(),i)}catch(i){throw this.finalizeTransaction(),i}}recordAction(e){const t=this.transactionStack[this.transactionStack.length-1];return t?(t.actions.push(e),e):(this.history.addAction(e),e)}finalizeTransaction(){const e=this.transactionStack.pop();if(!e)return;const t=this.normalizeTransactionActions(e.actions,e.label);if(!t)return;const i=this.transactionStack[this.transactionStack.length-1];if(i){i.actions.push(t);return}this.history.addAction(t)}normalizeTransactionActions(e,t){return e.length===0?null:e.length===1?e[0]??null:this.history.createCompoundAction(e,t)}}function Bi(s){var e;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function Od(s){var e,t,i;s.notifySelectionChange(),(e=s.emitSelectionChangeEvent)==null||e.call(s),(t=s.reloadClipThumbnailsIfNeeded)==null||t.call(s),(i=s.checkTrackDurationChange)==null||i.call(s),s.emitSelectedClipChangeIfNeeded(),s.handleClipChange()}function Fd(s,e,t=!1){if(!e||!t||s.type==="audio")return!1;const i=e.duration!==s.duration,r=e.startTimeAtSource!==s.startTimeAtSource||e.endTimeAtSource!==s.endTimeAtSource;return i||r}function kt(s){return s.length===0?0:Math.max(...s.map(e=>e.endTime))}function Nd(s,e){return e<kt(s)}function Gd(s){return s.currentCanPlay===s.nextCanPlay?s.currentCanPlay:(s.setCanPlay(s.nextCanPlay),s.currentCanPlay&&!s.nextCanPlay&&s.playState==="playing"&&(s.pauseTimeline(),s.setCurrentTime(s.clipEndTime||1)),s.emitCanPlayChange(s.nextCanPlay),s.nextCanPlay)}function Hd(s){const e=!s.id&&s.startTime>0;return{shouldJumpToTime:e,jumpTime:e?s.startTime:null,shouldSelectClip:!!s.id}}function Wi(s){var e;return s.applied?(s.isExecutingHistoryAction||(e=s.recordHistory)==null||e.call(s),s.applyEffects(),!0):!1}function zd(s){return Wi({applied:s.applied,isExecutingHistoryAction:s.isExecutingHistoryAction,recordHistory:()=>{var e;(e=s.recordMoveClipBetweenTracks)==null||e.call(s,s.clipId,s.sourceTrackId,s.targetTrackId,s.clipBefore,s.clipAfter,s.sourceTrackSnapshot,s.targetTrackSnapshot)},applyEffects:s.applyEffects})}function $d(s){var e;s.isExecutingHistoryAction||(e=s.recordSplitClip)==null||e.call(s,s.clip1,s.clip2),s.emitClipUpdated(s.clip1),s.emitClipAdded(s.clip2),s.applyEffects()}const Vd={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function Ud(s){var e,t;try{const i=typeof location<"u"?location.href:"http://localhost/";return((e=new URL(s,i).pathname.split(".").pop())==null?void 0:e.toLowerCase())??""}catch{return((t=(s.split(/[?#]/,1)[0]??"").split(".").pop())==null?void 0:t.toLowerCase())??""}}function Wd(s){const e=Ud(s.src);if(e==="mp4")return{url:s.src,mimeType:"video/mp4",kind:"mp4"};if(e==="m3u8")return{url:s.src,mimeType:"application/vnd.apple.mpegurl",kind:"hls-fmp4"};const t=Vd[e];return t?{url:s.src,mimeType:t,kind:"audio"}:null}class Yd{constructor(e){g(this,"container",null);g(this,"statusElement",null);g(this,"actionElement",null);g(this,"onRetry");this.onRetry=e}mount(e){this.container=e,this.container.className="timeline-preview-pending-overlay",this.container.style.position="absolute",this.container.style.top="12px",this.container.style.left="12px",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="flex-start",this.container.style.flexDirection="row",this.container.style.gap="8px",this.container.style.background=Ue.background,this.container.style.color=Ue.text,this.container.style.fontSize="13px",this.container.style.lineHeight="1",this.container.style.padding="8px 10px",this.container.style.borderRadius="6px",this.container.style.zIndex="2000",this.container.style.pointerEvents="auto";const t=document.createElement("div");t.className="timeline-preview-pending-overlay__status",t.style.fontWeight="600";const i=document.createElement("button");i.className="timeline-preview-pending-overlay__action",i.style.display="none",i.style.padding="6px 12px",i.style.border="0",i.style.borderRadius="6px",i.style.cursor="pointer",i.style.background=Ue.actionBackground,i.style.color=Ue.actionText,i.textContent="刷新重试",i.addEventListener("click",this.onRetry),this.container.appendChild(t),this.container.appendChild(i),this.statusElement=t,this.actionElement=i}update(e){if(!this.container||!this.statusElement||!this.actionElement)return;const{pendingState:t,runtimeState:i}=e,r=(t==null?void 0:t.loading)??i.loading,n=!!(t!=null&&t.errorMessage)||r.status==="failed"||i.phase==="failed";if(!t&&r.status!=="loading"){this.container.style.display="none",this.actionElement.style.display="none";return}if(this.container.style.display="inline-flex",this.container.style.background=n?Ue.failedBackground:Ue.background,this.container.style.color=n?Ue.failedText:Ue.text,n){this.statusElement.textContent="媒体丢失",this.actionElement.style.display="inline-flex";return}this.statusElement.textContent=this.resolveLoadingStatusText(r.reason),this.actionElement.style.display="none"}resolveLoadingStatusText(e){switch(e){case"syncing":case"resolving-source":return"资源加载中...";case"seeking":return"正在定位预览...";case"media-pending":return"等待资源加载...";case"failed":return"媒体丢失";default:return"资源加载中..."}}destroy(){var e,t;(e=this.actionElement)==null||e.removeEventListener("click",this.onRetry),(t=this.container)==null||t.remove(),this.container=null,this.statusElement=null,this.actionElement=null}}const _r={x:.5,y:.5,scale:1},Xd=.1,qd=8;function Ar(s,e){return typeof s=="number"&&Number.isFinite(s)?s:e}function jd(s){return Math.min(qd,Math.max(Xd,s))}function Pe(s){return{x:Ar(s==null?void 0:s.x,_r.x),y:Ar(s==null?void 0:s.y,_r.y),scale:jd(Ar(s==null?void 0:s.scale,_r.scale))}}function wn(s,e,t=1e-4){const i=Pe(s),r=Pe(e);return Math.abs(i.x-r.x)<=t&&Math.abs(i.y-r.y)<=t&&Math.abs(i.scale-r.scale)<=t}function po(s,e){if(s.width<=0||s.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const t=e.width>0?e.width:s.width,i=e.height>0?e.height:s.height,r=t/i,n=s.width/s.height;let a=s.width,o=s.height;r>n?o=a/r:a=o*r;const l=(s.width-a)/2,c=(s.height-o)/2;return{left:l,top:c,width:a,height:o,centerX:l+a/2,centerY:c+o/2}}function Es(s,e,t){const i=po(s,e),r=Pe(t),n=i.width*r.scale,a=i.height*r.scale,o=s.width*r.x,l=s.height*r.y;return{left:o-n/2,top:l-a/2,width:n,height:a,centerX:o,centerY:l}}function go(s,e,t,i){const r=Pe(s),n=i.width>0?i.width:1,a=i.height>0?i.height:1;return Pe({x:r.x+e/n,y:r.y+t/a,scale:r.scale})}function Kd(s,e,t,i,r,n){const a=Pe(n),o=Math.max(r.width/2,1),l=Math.max(r.height/2,1),c=Math.abs(t-s)/o,h=Math.abs(i-e)/l;return Pe({x:a.x,y:a.y,scale:Math.max(c,h)})}function Rs(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}class Zd{constructor(e={}){g(this,"frameElement",null);g(this,"overlayElement",null);g(this,"boxElement",null);g(this,"rotateHandleElement",null);g(this,"rotateHandlePointerDownHandler",null);g(this,"handleElements",new Map);g(this,"handlePointerDownHandlers",new Map);g(this,"state",null);g(this,"interaction",null);g(this,"callbacks");g(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});g(this,"boundPointerUp",()=>{this.finishInteraction(!0)});g(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});g(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});g(this,"handleMovePointerDown",e=>{var i,r,n,a;const t=e;(t.button??0)!==0||!this.state||((i=t.preventDefault)==null||i.call(t),(r=t.stopPropagation)==null||r.call(t),this.state.clipType==="text"&&((a=(n=this.callbacks).onTextTransformInteractionStart)==null||a.call(n)),this.interaction={clipId:this.state.clipId,mode:"move",pointerStart:this.toLocalPoint(t),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing",clipType:this.state.clipType??"video",startFontSize:void 0,nextFontSize:void 0,centerX:void 0,centerY:void 0,startCenterDistance:void 0,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor("grabbing"),this.bindDocumentListeners())});this.callbacks=e}attach(e){if(this.frameElement===e&&this.overlayElement){this.render();return}this.detach(),this.frameElement=e;const t=document.createElement("div");t.className="timeline-preview-transform-overlay",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="3000";const i=document.createElement("div");i.className="timeline-preview-transform-box",i.style.position="absolute",i.style.display="none",i.style.boxSizing="border-box",i.style.border=`1px solid ${ot.border}`,i.style.cursor="grab",i.style.pointerEvents="auto",i.style.userSelect="none",i.addEventListener("pointerdown",this.handleMovePointerDown),t.appendChild(i),this.overlayElement=t,this.boxElement=i,this.createHandle("top-left","nwse-resize"),this.createHandle("top-right","nesw-resize"),this.createHandle("bottom-right","nwse-resize"),this.createHandle("bottom-left","nesw-resize"),this.createRotateHandle(),e.appendChild(t),this.render()}detach(){var e,t;this.finishInteraction(!1),(e=this.boxElement)==null||e.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,r)=>{const n=this.handlePointerDownHandlers.get(r);n&&i.removeEventListener("pointerdown",n)}),this.handleElements.clear(),this.handlePointerDownHandlers.clear(),this.rotateHandleElement&&this.rotateHandlePointerDownHandler&&this.rotateHandleElement.removeEventListener("pointerdown",this.rotateHandlePointerDownHandler),this.rotateHandleElement=null,this.rotateHandlePointerDownHandler=null,(t=this.overlayElement)==null||t.remove(),this.overlayElement=null,this.boxElement=null,this.frameElement=null,this.state=null}sync(e){if(!e){this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==e.clipId&&this.finishInteraction(!1),this.state=e,this.render()}createRotateHandle(){if(!this.overlayElement)return;const e=document.createElement("div");e.className="timeline-preview-transform-rotate-handle",e.style.position="absolute",e.style.display="none",e.style.width="20px",e.style.height="20px",e.style.borderRadius="999px",e.style.border=`1px solid ${ot.border}`,e.style.background=ot.handleBackground,e.style.pointerEvents="auto",e.style.cursor="grab",e.style.boxSizing="border-box",e.style.transform="translate(-50%, -50%)",e.style.display="none",e.style.alignItems="center",e.style.justifyContent="center",e.style.fontSize="12px",e.style.color=ot.border,e.style.userSelect="none",e.textContent="↺";const t=this.getRotateHandlePointerDown();e.addEventListener("pointerdown",t),this.rotateHandleElement=e,this.rotateHandlePointerDownHandler=t,this.overlayElement.appendChild(e)}getRotateHandlePointerDown(){return e=>{var o,l,c,h;const t=e;if((t.button??0)!==0||!this.state)return;(o=t.preventDefault)==null||o.call(t),(l=t.stopPropagation)==null||l.call(t),this.state.clipType==="text"&&((h=(c=this.callbacks).onTextTransformInteractionStart)==null||h.call(c));const i=this.state.displayRect.left+this.state.displayRect.width/2,r=this.state.displayRect.top+this.state.displayRect.height/2,n=this.toLocalPoint(t),a=Math.atan2(n.y-r,n.x-i)*(180/Math.PI);this.interaction={clipId:this.state.clipId,mode:"rotate",pointerStart:n,startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:"grabbing",clipType:"text",startFontSize:void 0,nextFontSize:void 0,centerX:i,centerY:r,startCenterDistance:void 0,startRotation:this.state.currentRotation??0,nextRotation:this.state.currentRotation??0,startAngle:a},this.setGlobalCursor("grabbing"),this.bindDocumentListeners()}}createHandle(e,t){if(!this.boxElement)return;const i=document.createElement("div");i.className=`timeline-preview-transform-handle timeline-preview-transform-handle--${e}`,i.style.position="absolute",i.style.width="10px",i.style.height="10px",i.style.border=`1px solid ${ot.border}`,i.style.background=ot.handleBackground,i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=t,i.style.boxSizing="border-box",i.style.transform="translate(-50%, -50%)";const r=this.getHandlePointerDown(e);i.addEventListener("pointerdown",r),this.handleElements.set(e,i),this.handlePointerDownHandlers.set(e,r),this.boxElement.appendChild(i)}getHandlePointerDown(e){return t=>{var c,h,d,u;const i=t;if((i.button??0)!==0||!this.state)return;(c=i.preventDefault)==null||c.call(i),(h=i.stopPropagation)==null||h.call(i);const r=this.state.clipType==="text";r&&((u=(d=this.callbacks).onTextTransformInteractionStart)==null||u.call(d));const n=e==="top-right"||e==="bottom-left"?"nesw-resize":"nwse-resize",a=r?this.state.displayRect.left+this.state.displayRect.width/2:void 0,o=r?this.state.displayRect.top+this.state.displayRect.height/2:void 0,l=r?Math.sqrt(Math.pow(this.state.displayRect.width/2,2)+Math.pow(this.state.displayRect.height/2,2)):void 0;this.interaction={clipId:this.state.clipId,mode:"scale",pointerStart:this.toLocalPoint(i),startTransform:this.state.transform,baseRect:this.state.baseRect,frameSize:this.state.frameSize,nextTransform:this.state.transform,changed:!1,cursor:n,clipType:this.state.clipType??"video",startFontSize:r?this.state.currentFontSize:void 0,nextFontSize:r?this.state.currentFontSize:void 0,centerX:a,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor(n),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,r,n,a;const e=this.getDocument();e&&((t=e.addEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.addEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.addEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(a=(n=globalThis.window)==null?void 0:n.addEventListener)==null||a.call(n,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,r,n,a;const e=this.getDocument();e&&((t=e.removeEventListener)==null||t.call(e,"pointermove",this.boundPointerMove),(i=e.removeEventListener)==null||i.call(e,"pointerup",this.boundPointerUp),(r=e.removeEventListener)==null||r.call(e,"visibilitychange",this.boundVisibilityChange),(a=(n=globalThis.window)==null?void 0:n.removeEventListener)==null||a.call(n,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var n,a,o,l,c,h,d;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const t=e;(n=t.preventDefault)==null||n.call(t);const i=this.toLocalPoint(t);if(this.interaction.mode==="rotate"&&this.interaction.startRotation!==void 0){const u=i.x-this.interaction.centerX,p=i.y-this.interaction.centerY,m=Math.atan2(p,u)*(180/Math.PI)-this.interaction.startAngle,S=Math.round(this.interaction.startRotation+m);this.interaction.nextRotation=S,this.interaction.changed=S!==this.interaction.startRotation,(o=(a=this.callbacks).onRotationChange)==null||o.call(a,this.interaction.clipId,S);return}if(this.interaction.clipType==="text"&&this.interaction.startFontSize!==void 0){const u=i.x-this.interaction.centerX,p=i.y-this.interaction.centerY,f=Math.sqrt(u*u+p*p),m=(this.interaction.startCenterDistance??0)>0?f/this.interaction.startCenterDistance:1,S=Math.max(5,Math.min(300,Math.round(this.interaction.startFontSize*m)));this.interaction.nextFontSize=S,this.interaction.changed=S!==this.interaction.startFontSize,(c=(l=this.callbacks).onFontSizeChange)==null||c.call(l,this.interaction.clipId,S);return}let r=this.interaction.startTransform;if(this.interaction.mode==="move")r=go(this.interaction.startTransform,i.x-this.interaction.pointerStart.x,i.y-this.interaction.pointerStart.y,this.interaction.frameSize);else{const u=this.interaction.startTransform.x*this.interaction.frameSize.width,p=this.interaction.startTransform.y*this.interaction.frameSize.height;r=Kd(u,p,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!wn(this.interaction.startTransform,r),(d=(h=this.callbacks).onPreviewTransformChange)==null||d.call(h,this.interaction.clipId,r)}finishInteraction(e){var i,r,n,a,o,l,c,h,d,u,p,f;const t=this.interaction;if(!t){this.setGlobalCursor(null),this.unbindDocumentListeners();return}t.mode==="rotate"?(e&&t.changed&&t.nextRotation!==void 0&&((r=(i=this.callbacks).onRotationCommit)==null||r.call(i,t.clipId,t.nextRotation)),(a=(n=this.callbacks).onRotationChange)==null||a.call(n,t.clipId,null)):t.clipType==="text"?(e&&t.changed&&t.nextFontSize!==void 0&&((l=(o=this.callbacks).onFontSizeCommit)==null||l.call(o,t.clipId,t.nextFontSize)),(h=(c=this.callbacks).onFontSizeChange)==null||h.call(c,t.clipId,null)):(e&&t.changed&&((u=(d=this.callbacks).onPreviewTransformCommit)==null||u.call(d,t.clipId,t.nextTransform)),(f=(p=this.callbacks).onPreviewTransformChange)==null||f.call(p,t.clipId,null)),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners(),this.render()}render(){var r;if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none"),this.rotateHandleElement&&(this.rotateHandleElement.style.display="none");return}const e=this.state.clipType==="text";this.boxElement.style.pointerEvents=e?"none":"auto",this.boxElement.style.cursor=e?"default":"grab";const{displayRect:t}=this.state;this.boxElement.style.display="block",this.boxElement.style.left=`${t.left}px`,this.boxElement.style.top=`${t.top}px`,this.boxElement.style.width=`${t.width}px`,this.boxElement.style.height=`${t.height}px`;const i=e?this.state.currentRotation??0:0;if(this.boxElement.style.transformOrigin="center",this.boxElement.style.transform=i!==0?`rotate(${i}deg)`:"",this.positionHandle("top-left",0,0),this.positionHandle("top-right",t.width,0),this.positionHandle("bottom-right",t.width,t.height),this.positionHandle("bottom-left",0,t.height),this.rotateHandleElement)if(e){if(!(((r=this.interaction)==null?void 0:r.mode)==="rotate")){const a=t.left+t.width/2,o=t.top+t.height/2,l=t.height/2+20,c=i*(Math.PI/180),h=a-l*Math.sin(c),d=o+l*Math.cos(c);this.rotateHandleElement.style.left=`${h}px`,this.rotateHandleElement.style.top=`${d}px`}this.rotateHandleElement.style.display="flex"}else this.rotateHandleElement.style.display="none"}positionHandle(e,t,i){const r=this.handleElements.get(e);r&&(r.style.left=`${t}px`,r.style.top=`${i}px`)}toLocalPoint(e){const t=this.getFrameBounds();return{x:(e.clientX??0)-t.left,y:(e.clientY??0)-t.top}}getFrameBounds(){var t,i;if(!this.frameElement)return{left:0,top:0,width:0,height:0};const e=(i=(t=this.frameElement).getBoundingClientRect)==null?void 0:i.call(t);return e&&Number.isFinite(e.width)&&Number.isFinite(e.height)?{left:e.left,top:e.top,width:e.width,height:e.height}:{left:Rs(this.frameElement.style.left),top:Rs(this.frameElement.style.top),width:this.frameElement.clientWidth,height:this.frameElement.clientHeight}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}setGlobalCursor(e){var i;const t=(i=this.getDocument())==null?void 0:i.body;t&&(t.style.cursor=e||"")}}function Jd(s,e){var u;const t=s.activeClips.filter(p=>p.trackType!=="text"),i=s.nextClips.filter(p=>p.trackType!=="text"),r=s.interactionMode??"steady",n=new Map(t.map(p=>[p.trackId,p])),a=new Map(i.map(p=>[p.trackId,p])),o=new Map,l=t.filter(p=>p.trackType==="video"&&p.hasVisual).sort((p,f)=>p.trackOrder-f.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(p,f)=>!a.has(p)||r!=="steady"&&c?!1:c?s.playState==="playing"&&f==="video"&&p===h:s.playState!=="playing"||t.length<=1;return e.forEach(p=>{o.set(p.trackId,{kind:p.kind,order:p.order})}),t.forEach(p=>{o.set(p.trackId,{kind:p.trackType,order:p.trackOrder})}),i.forEach(p=>{o.set(p.trackId,{kind:p.trackType,order:p.trackOrder})}),Array.from(o.entries()).map(([p,f])=>{const m=n.get(p)||null,S=d(p,f.kind)&&a.get(p)||null;return{trackId:p,kind:f.kind,order:f.order,current:{role:"current",entry:m,playState:s.requestedPlayState??s.playState,speed:s.speed,visible:!!(m!=null&&m.hasVisual),zIndex:m?1e3-m.trackOrder:0,syncRequestId:s.syncRequestId},preload:{role:"preload",entry:S,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:s.syncRequestId}}}).sort((p,f)=>p.order-f.order)}function on(s,e){return s.entry?e?s.entry.clip.id===e:!0:!1}function Qd(s,e){return e?!on(s.current,e.clip.id)&&on(s.preload,e.clip.id):!1}function eu(s){return s.current.role="preload",s.preload.role="current",{current:s.preload,preload:s.current}}function tu(s){return`${s.trackId}:${s.role}`}function iu(s,e){return s.role!=="preload"||!on(s)?null:{role:"preload",entry:s.entry,playState:s.requestedPlayState,speed:1,visible:!1,zIndex:0,syncRequestId:e}}function ru(s,e){const t=e.lastIndexOf(":");if(t<=0)return null;const i=e.slice(0,t),r=e.slice(t+1);if(r!=="current"&&r!=="preload")return null;const n=s.get(i);return n?r==="current"?n.current:n.preload:null}function nu(s,e,t,i){const r=e||s.clip.src||"";switch(t){case"abort":case"emptied":return`${s.clip.id}:${r}:${t}`;case"error":case"reconcile":case"stalled":return`${s.clip.id}:${r}:${Math.floor(s.mediaTime/i)}`;default:return`${s.clip.id}:${r}`}}function su(s){if(!s.desiredSource||!s.stableSourceUrl||!s.currentSourceKey||s.currentSourceKey!==s.nextSourceKey)return null;const e=s.objectUrl??(s.desiredSource.startsWith("blob:")?s.desiredSource:null);return{stableSourceUrl:s.stableSourceUrl,url:s.desiredSource,objectUrl:e}}function au(s,e,t){return t?s===t||e===t:!1}function ou(s){const e=s.configuredSource||null,t=e||s.assignedSource||null;let i=!1,r=null;return s.forceRecover?(i=!0,r="force-recover"):e?t!==s.desiredSource?(i=!0,r="source-mismatch"):s.networkState===s.networkEmptyState&&((s.readyState??0)>=s.haveCurrentDataState?(i=!1,r="network-empty-but-current-data-ready"):(i=!(s.isLoading||s.phase==="binding"||s.phase==="recovering"),r=i?"network-empty":"network-empty-binding-in-flight")):(i=!0,r="missing-src-attribute"),{needsRecovery:i,recoveryReason:r,actualSource:t,configuredSource:e,shouldWarn:i&&(r==="source-mismatch"||s.isActive&&s.phase!=="idle"&&s.phase!=="binding")}}function lu(s,e){const t=s==="current"?Math.abs(e):1;return Math.max(.1,t*.15)}function cu(s,e,t){return!!s||e!=="reconcile"||t>1}function hu(s){return{role:s.role,entry:s.entry,playState:s.requestedPlayState,speed:s.isActive&&s.playbackRate||1,visible:s.isActive&&!!s.entry.hasVisual,zIndex:1e3-s.entry.trackOrder,syncRequestId:s.syncRequestId}}function du(s){const e=nu(s.entry,s.desiredSource,s.reason,s.recoveryTimeBucketMs);return s.previousRecoveryKey===e?s.previousRetryCount>=s.maxImmediateRecoveryRetries?s.isBackgroundPreload?{status:"park",message:"媒体恢复失败,请等待下一次重建",parkReason:"retries-exhausted"}:{status:"fail",message:"媒体恢复失败,请刷新重试"}:{status:"continue",recoveryKey:e,retryCount:s.previousRetryCount+1}:{status:"continue",recoveryKey:e,retryCount:1}}function fo(s,e){s.phase="idle",s.errorMessage=null,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,gr(s,e)}function uu(s){s.phase==="failed"&&(s.phase="binding",s.errorMessage=null,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,gr(s))}function gr(s,e=!1){s.forceRecover=e,s.retryCount=0,s.recoveryKey=null,s.expectedEmptiedEvents=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}function pu(s){fo(s,!1)}function gu(s){fo(s,!0)}function fu(s){s.phase==="binding"&&(s.phase=s.isActive?"active":"primed"),s.isResolvingSource=!1,s.isLoading=!1,s.isBuffering=!1,(s.phase!=="failed"||!s.errorMessage)&&(s.errorMessage=null)}function mu(s){s.isLoading||s.isSeeking||s.phase==="failed"&&s.errorMessage||(s.phase=s.isActive?"active":"primed")}function yu(s,e){s.forceRecover=!0,s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=null,e||(s.phase="idle")}function Su(s,e){const t=!!s.isSeeking&&!e.withinSeekThreshold,i=s.isResolvingSource,r=!i&&e.hasDesiredSource&&e.sourceMatched&&!t&&e.readyState>=e.haveCurrentDataState,n=s.phase==="failed"&&!r,a=!r&&!n&&(!e.hasDesiredSource||!e.sourceMatched||s.phase==="binding"||s.phase==="recovering"||e.readyState<e.haveCurrentDataState);return s.isSeeking=t,r?(gr(s),s.isLoading=!1,s.isBuffering=!1,s.errorMessage=null,s.phase=s.isActive?"active":"primed"):!n&&s.phase!=="recovering"&&s.phase!=="binding"&&(s.phase=s.isActive?"active":"primed"),{failed:n,resolving:i,seeking:t,mediaUnready:a,ready:r}}function Ms(s,e){s.phase="failed",s.isLoading=!1,s.isResolvingSource=!1,s.isSeeking=!1,s.isBuffering=!1,s.errorMessage=e,s.forceRecover=!1,s.expectedEmptiedEvents=0}function vu(s){s.isActive=!1,s.isBuffering=!1,s.isSeeking=!1}function Cu(s,e){s.phase="recovering",s.errorMessage=null,s.forceRecover=!1,s.isLoading=!0,s.isResolvingSource=!1,s.isBuffering=s.isActive&&e==="playing",s.isSeeking=!1,s.consecutiveStalledCount=0,s.recoverableEventCount=0,s.loadStartedSinceRecover=!1}const Tu=0,at=2,Ir=3,bu=2,ku=250,wu=250,Pu=100,xu=500,_u=700,Ds=.03,Ls=8e3,Au=.5,Iu=750,Bs="Arial, sans-serif",Wt="媒体丢失";function Eu(s,e){const t=Math.max(0,Math.round(s));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let n=-t;n<=t;n+=1)n===0&&r===0||i.push(`${n}px ${r}px 0 ${e}`);return i.join(", ")}function mo(s){return s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Er(s){return`"${mo(s)}"`}function Ru(s){return un(s,hn)}function Mu(s,e){return!_t(s.mode)||!e?s:{mode:Be.mode,width:e.width,height:e.height}}function _e(s){return s.getAttribute("src")||s.currentSrc||s.src||""}function sr(s){return s.getAttribute("src")||""}function Fe(s,e){const t=sr(s),i=s.currentSrc||"",r=s.src||"",n=_e(s);return{desiredSource:e||null,srcAttribute:t||null,currentSrc:i||null,elementSrc:r||null,assignedSrc:n||null,hasSrcAttribute:!!t,matchesDesiredByAttribute:!!e&&t===e,matchesDesiredByAssigned:!!e&&n===e}}function ar(s){return typeof HTMLVideoElement<"u"?s instanceof HTMLVideoElement:s.tagName==="VIDEO"}function Ye(s){try{s.load()}catch{}}function Ne(s){try{s.pause()}catch{}}function Rr(s){var e;try{const t=s.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function Os(s,e){try{s.currentTime=Math.max(0,e)}catch{}}function Oi(s,e){var i;const t=(i=s==null?void 0:s.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function Fs(s){if(!s)return 0;const e=Number.parseFloat(s);return Number.isFinite(e)?e:0}function Yi(){return typeof performance<"u"&&typeof performance.now=="function"?Math.round(performance.now()):Date.now()}function Du(s){const e=s.buffered;if(!e||typeof e.length!="number"||e.length<=0)return null;try{return Number(e.end(e.length-1).toFixed(3))}catch{return null}}function ee(s){return{tsMs:Yi(),currentTime:Number.isFinite(s.currentTime)?Number(s.currentTime.toFixed(3)):null,duration:Number.isFinite(s.duration)?Number(s.duration.toFixed(3)):null,currentSrc:_e(s)||null,srcAttribute:sr(s)||null,elementSrc:s.src||null,rawCurrentSrc:s.currentSrc||null,readyState:typeof s.readyState=="number"?s.readyState:null,networkState:typeof s.networkState=="number"?s.networkState:null,paused:typeof s.paused=="boolean"?s.paused:null,ended:typeof s.ended=="boolean"?s.ended:null,playbackRate:typeof s.playbackRate=="number"?Number(s.playbackRate.toFixed(3)):null,bufferedEnd:Du(s),videoWidth:ar(s)?s.videoWidth:null,videoHeight:ar(s)?s.videoHeight:null,error:s.error?{code:typeof s.error.code=="number"?s.error.code:null,message:s.error.message??null}:null}}function Ge(s){return typeof(s==null?void 0:s.then)=="function"}class Lu{constructor(e={},t={}){g(this,"container",null);g(this,"rootElement",null);g(this,"frameElement",null);g(this,"textOverlayRoot",null);g(this,"pendingOverlayElement",null);g(this,"pendingOverlayRenderer");g(this,"resizeObserver",null);g(this,"trackSlots",new Map);g(this,"textPreviewEntries",new Map);g(this,"audioContext",null);g(this,"masterGainNode",null);g(this,"loadingProbeTimeoutId",null);g(this,"clockProbeTimeoutId",null);g(this,"playbackGroupSuspended",!1);g(this,"lastRuntimeSignature",null);g(this,"lastRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});g(this,"lastSettledSyncRequestId",null);g(this,"primarySelectedClipId",null);g(this,"transientVisualTransform",null);g(this,"transientFontSize",null);g(this,"transientRotation",null);g(this,"textPreviewDragState",null);g(this,"textPreviewFontStyleElement",null);g(this,"textPreviewFontSignature",null);g(this,"textPreviewFontLoadState","idle");g(this,"textPreviewFontLoadToken",0);g(this,"callbacks");g(this,"dependencies");g(this,"transformOverlay");g(this,"boundTextPreviewPointerMove",e=>{this.handleTextPreviewPointerMove(e)});g(this,"boundTextPreviewPointerUp",()=>{this.finishTextPreviewDrag(!0)});g(this,"boundTextPreviewVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishTextPreviewDrag(!1)});g(this,"boundTextPreviewWindowBlur",()=>{this.finishTextPreviewDrag(!1)});g(this,"requestedAspectRatio",{...Be});g(this,"resolvedAutoAspectRatio",null);g(this,"aspectRatioProbe",null);g(this,"aspectRatioProbeSrc",null);g(this,"aspectRatioProbeResolveToken",0);g(this,"pendingState",null);g(this,"activeSyncRequestId");g(this,"isSyncProjecting",!1);g(this,"deferredPreloadSlotKeys",new Set);g(this,"deferredPreloadFlushScheduled",!1);g(this,"lastSyncedPlayState","paused");g(this,"pendingClockAlignmentTargetTime",null);this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new Yd(()=>{var i,r;(r=(i=this.callbacks).onPendingPreviewRetry)==null||r.call(i)}),this.transformOverlay=new Zd({onPreviewTransformChange:this.handlePreviewTransformChange.bind(this),onPreviewTransformCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onVisualTransformCommit)==null||a.call(n,i,r)},onFontSizeChange:(i,r)=>{var a;if(r===null){if(((a=this.transientFontSize)==null?void 0:a.clipId)===i){this.transientFontSize=null;const o=this.textPreviewEntries.get(i);o&&(o.element.style.fontSize=`${De(o.entry.clip.textStyle).fontSize}px`),this.refreshVisualLayout()}return}this.transientFontSize={clipId:i,fontSize:r};const n=this.textPreviewEntries.get(i);n&&(n.element.style.fontSize=`${r}px`),this.refreshVisualLayout()},onFontSizeCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onTextFontSizeCommit)==null||a.call(n,i,r)},onRotationChange:(i,r)=>{var n;if(r===null){((n=this.transientRotation)==null?void 0:n.clipId)===i&&(this.transientRotation=null,this.refreshVisualLayout());return}this.transientRotation={clipId:i,rotation:r},this.refreshVisualLayout()},onRotationCommit:(i,r)=>{var n,a;(a=(n=this.callbacks).onTextRotationCommit)==null||a.call(n,i,r)},onTextTransformInteractionStart:()=>{this.requestPauseIfPlaying()}})}requestPauseIfPlaying(){var e,t;this.lastSyncedPlayState==="playing"&&((t=(e=this.callbacks).onPauseIfPlaying)==null||t.call(e))}emitDiagnostic(e,t,i,r={}){var o,l;const n=this.dependencies.diagnostics;if(!n)return;const a=((l=(o=this.dependencies).getDiagnosticsContext)==null?void 0:l.call(o))??{};n.emit({...a,...r,severity:e,category:t,eventName:i,runtimeState:ja(a.runtimeState,r.runtimeState)})}buildSlotTraceData(e,t={}){var i;return{...t,trackId:e.trackId,clipId:((i=e.entry)==null?void 0:i.clip.id)??null,slotKey:`${e.trackId}:${e.role}`,desiredSourceUrl:e.desiredSource,actualSourceUrl:_e(e.element)||null,extra:{role:e.role,kind:e.kind,phase:e.phase,retryCount:e.retryCount,sourceState:Fe(e.element,e.desiredSource),...t.extra??{}}}}hasPreview(){return!!this.container}attach(e){if(this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e;const t=document.createElement("div");t.className=this.dependencies.rootClassName??"timeline-preview-root",t.style.position="relative",t.style.width="100%",t.style.height="100%",t.style.overflow="hidden";const i=document.createElement("div");i.className=this.dependencies.frameClassName??"timeline-preview-frame",i.style.position="absolute",i.style.left="0",i.style.top="0",i.style.overflow="hidden",i.style.background=_.black,t.appendChild(i);const r=document.createElement("div");r.className="timeline-preview-text-layer",r.style.position="absolute",r.style.inset="0",r.style.pointerEvents="none",r.style.zIndex="2000",i.appendChild(r);const n=document.createElement("div");t.appendChild(n),this.pendingOverlayRenderer.mount(n),e.appendChild(t),this.rootElement=t,this.frameElement=i,this.textOverlayRoot=r,this.pendingOverlayElement=n,this.transformOverlay.attach(i),this.ensureTextPreviewFontReady(),this.emitDiagnostic("info","session","preview.attach",{message:"Preview attached",extra:{containerWidth:e.clientWidth,containerHeight:e.clientHeight}}),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(e)),this.updateFrameLayout(),this.refreshPendingOverlay(),this.refreshRuntimeState()}detach(){var e,t,i,r,n,a;this.emitDiagnostic("info","session","preview.detach",{message:"Preview detached",extra:{slotCount:this.trackSlots.size}}),(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,this.transformOverlay.detach(),this.finishTextPreviewDrag(!1),this.pendingOverlayRenderer.destroy();for(const o of this.trackSlots.values())this.destroySlot(o.current),this.destroySlot(o.preload);this.trackSlots.clear(),this.clearTextPreviewEntries(),this.resetTextPreviewFontState(),this.aspectRatioProbe&&(Ne(this.aspectRatioProbe),this.aspectRatioProbe.src="",Ye(this.aspectRatioProbe),this.aspectRatioProbe=null),this.aspectRatioProbeSrc=null,this.aspectRatioProbeResolveToken+=1,this.audioContext&&((n=(i=(t=this.audioContext).close)==null?void 0:(r=i.call(t)).catch)==null||n.call(r,()=>{}),this.audioContext=null,this.masterGainNode=null),(a=this.rootElement)==null||a.remove(),this.rootElement=null,this.frameElement=null,this.textOverlayRoot=null,this.pendingOverlayElement=null,this.container=null,this.primarySelectedClipId=null,this.transientVisualTransform=null,this.transientFontSize=null,this.transientRotation=null,this.pendingState=null,this.activeSyncRequestId=void 0,this.isSyncProjecting=!1,this.clearLoadingProbe(),this.clearClockProbe(),this.playbackGroupSuspended=!1,this.lastRuntimeSignature=null,this.lastSettledSyncRequestId=null,this.pendingClockAlignmentTargetTime=null,this.lastRuntimeState={phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]},this.refreshPendingOverlay(),this.refreshRuntimeState()}setPendingState(e){this.pendingState=e,this.refreshPendingOverlay()}sync(e){var a;if(!this.rootElement||!this.frameElement)return;this.lastSyncedPlayState=e.playState,this.updatePendingClockAlignmentTarget(e),this.primarySelectedClipId=e.primarySelectedClipId??null,this.activeSyncRequestId=e.syncRequestId,this.emitDiagnostic("info","playback","preview.sync.requested",{message:"Preview sync requested",syncRequestId:e.syncRequestId??null,runtimeState:{currentTimeMs:e.currentTime,playState:e.playState,speed:e.speed,activeClipIds:e.activeClips.map(o=>o.clip.id)},extra:{activeClipCount:e.activeClips.length,nextClipCount:e.nextClips.length,autoAspectRatioClipId:((a=e.autoAspectRatioClip)==null?void 0:a.clip.id)??null}}),this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.transientFontSize&&this.transientFontSize.clipId!==this.primarySelectedClipId&&(this.transientFontSize=null),this.transientRotation&&this.transientRotation.clipId!==this.primarySelectedClipId&&(this.transientRotation=null),this.textPreviewDragState&&this.textPreviewDragState.clipId!==this.primarySelectedClipId&&this.finishTextPreviewDrag(!1),this.maybeResolveAutoAspectRatio(e.autoAspectRatioClip),this.syncTextPreviewEntries(e.activeClips.filter(o=>o.trackType==="text"));const t=Array.from(this.trackSlots.entries()).map(([o,l],c)=>{var h,d;return{trackId:o,kind:l.current.kind,order:((h=l.current.entry)==null?void 0:h.trackOrder)??((d=l.preload.entry)==null?void 0:d.trackOrder)??1e4+c}}),n=Jd(e,t).map(o=>this.applyTrackPlan(o)).filter(o=>Ge(o));if(this.isSyncProjecting=n.length>0,this.refreshVisualLayout(),this.refreshRuntimeState(),n.length===0){this.refreshVisualLayout(),this.refreshRuntimeState();return}Promise.all(n).then(()=>{this.activeSyncRequestId===e.syncRequestId&&(this.isSyncProjecting=!1,this.refreshVisualLayout(),this.refreshRuntimeState())}).catch(o=>{this.emitDiagnostic("error","playback","preview.sync.failed",{message:"Preview sync failed",syncRequestId:e.syncRequestId??null,error:o}),O.warn("TimelinePreviewSession","preview sync failed",{error:o,syncRequestId:e.syncRequestId}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.requestedAspectRatio=je(e),this.updateFrameLayout()}getAspectRatio(){return Mu(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}createMediaElement(e,t){const i=this.dependencies.createMediaElement,r=i?i(e,t):document.createElement(e==="video"?"video":"audio");return r.preload=t==="preload"?"auto":"metadata",r.crossOrigin="anonymous",r.loop=!1,r.controls=!1,ar(r)?(Nr(r),r.playsInline=!0,r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.objectFit="fill",r.style.background=_.black,r.style.pointerEvents="none"):r.style.display="none",r}createSlot(e,t,i){var x,D;const r=this.createMediaElement(t,i),n=t==="video"?document.createElement("div"):null,a=t==="video"?document.createElement("div"):null,o=t==="video"?document.createElement("div"):null;if(n){const w=this.dependencies.slotClassNamePrefix??"timeline-preview-slot";n.className=`${w} timeline-preview-slot--${e} timeline-preview-slot--${i}`,n.style.position="absolute",n.style.overflow="hidden",n.style.background=_.black,n.style.pointerEvents="none",n.style.display="none",n.appendChild(r),a&&o&&(a.className="timeline-preview-slot__failure",a.style.position="absolute",a.style.inset="0",a.style.display="none",a.style.alignItems="center",a.style.justifyContent="center",a.style.padding="12px",a.style.boxSizing="border-box",a.style.background=_.mediaClipFailedBackground,a.style.color=_.white,a.style.pointerEvents="none",o.className="timeline-preview-slot__failure-label",o.style.fontSize="18px",o.style.fontWeight="600",o.style.lineHeight="1.2",o.style.textAlign="center",o.textContent=Wt,a.appendChild(o),n.appendChild(a)),(x=this.frameElement)==null||x.appendChild(n)}const l={role:i,trackId:e,kind:t,wrapper:n,failureOverlay:a,failureLabel:o,element:r,entry:null,stableSourceUrl:null,desiredSource:null,objectUrl:null,pendingRuntimeSourceUrl:null,pendingRuntimeSourcePromise:null,requestedPlayState:"paused",isActive:!1,isLoading:!1,isResolvingSource:!1,isBuffering:!1,isSeeking:!1,phase:"idle",errorMessage:null,retryCount:0,recoveryKey:null,sourceNode:null,gainNode:null,audioRoutingFailed:!1,consecutiveStalledCount:0,forceRecover:!1,expectedEmptiedEvents:0,recoverableEventCount:0,loadStartedSinceRecover:!1,hasReadyEventSinceSourceChange:!1,hasBufferingSignalSinceSourceChange:!1,pendingClockAlignmentMediaTime:null,lastPlaybackResumeAttemptAtMs:-1,lastPlaybackProgressCheckAtMs:-1,lastPlaybackProgressMediaTimeSeconds:Number.NaN,playbackProgressStalled:!1,mediaPendingSinceMs:-1,mediaPendingFailureKey:null,resolveToken:0,applyToken:0,cleanup:[]},c=w=>{var A;if(!this.shouldIgnoreClearedSlotRecoverableEvent(l)){if(w==="abort"&&this.shouldIgnoreExpectedAbort(l)){this.emitDiagnostic("debug","playback","media.abort.ignored",this.buildSlotTraceData(l,{message:"Ignored expected media abort during source reset",mediaState:ee(l.element)}));return}if(w==="emptied"&&this.shouldIgnoreExpectedEmptied(l)){this.emitDiagnostic("debug","playback","media.emptied.ignored",this.buildSlotTraceData(l,{message:"Ignored expected media emptied during source reset",mediaState:ee(l.element)}));return}if(this.emitDiagnostic(w==="error"?"error":"warn","playback",`media.${w}`,this.buildSlotTraceData(l,{message:`Media event: ${w}`,mediaState:ee(l.element),error:l.element.error})),w==="error"&&O.error("TimelinePreviewSession",`media event: ${w}`,{trackId:l.trackId,role:l.role,clipId:((A=l.entry)==null?void 0:A.clip.id)??null,phase:l.phase,mediaState:ee(l.element)}),l.forceRecover=!0,l.expectedEmptiedEvents=0,l.isLoading=!1,l.isResolvingSource=!1,l.isSeeking=!1,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),l.recoverableEventCount+=1,this.shouldSkipImmediatePreloadRecovery(l)){l.phase="idle",this.emitDiagnostic("info","recovery","preload.recovery.skipped",this.buildSlotTraceData(l,{message:"Skipped immediate preload recovery after recoverable media event",mediaState:ee(l.element),extra:{reason:w,recoverableEventCount:l.recoverableEventCount,loadStartedSinceRecover:l.loadStartedSinceRecover}})),this.refreshRuntimeState();return}if(this.refreshRuntimeState(),this.shouldDeferPreloadRecovery(l)){this.deferPreloadRecovery(l,w);return}this.recoverSlot(l,w)}},h=()=>c("abort"),d=()=>c("emptied"),u=()=>c("error"),p=()=>{l.loadStartedSinceRecover=!0,l.isLoading=!0,l.hasReadyEventSinceSourceChange=!1,l.hasBufferingSignalSinceSourceChange=!1,l.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.emitDiagnostic("debug","playback","media.loadstart",this.buildSlotTraceData(l,{message:"Media event: loadstart",mediaState:ee(l.element)})),this.refreshRuntimeState()},f=()=>{l.hasReadyEventSinceSourceChange=!0,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.maybeResumeRequestedPlayback(l,"canplay"),this.emitDiagnostic("debug","playback","media.canplay",this.buildSlotTraceData(l,{message:"Media event: canplay",mediaState:ee(l.element)})),this.refreshRuntimeState()},m=()=>{l.hasReadyEventSinceSourceChange=!0,l.isBuffering=!1,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.emitDiagnostic("debug","playback","media.playing",this.buildSlotTraceData(l,{message:"Media event: playing",mediaState:ee(l.element)})),this.refreshRuntimeState()},S=()=>{this.refreshRuntimeState()},T=()=>{this.emitDiagnostic("debug","playback","media.pause",this.buildSlotTraceData(l,{message:"Media event: pause",mediaState:ee(l.element)})),this.refreshRuntimeState()},v=()=>{l.isBuffering=l.role==="current"&&l.isActive&&l.requestedPlayState==="playing",l.hasBufferingSignalSinceSourceChange=l.isBuffering,l.lastPlaybackResumeAttemptAtMs=-1,this.emitDiagnostic("warn","playback","media.stalled",this.buildSlotTraceData(l,{message:"Media event: stalled",mediaState:ee(l.element)})),this.refreshRuntimeState()},C=()=>{l.isBuffering=l.role==="current"&&l.isActive&&l.requestedPlayState==="playing",l.hasBufferingSignalSinceSourceChange=l.isBuffering,l.lastPlaybackResumeAttemptAtMs=-1,this.emitDiagnostic("warn","playback","media.waiting",this.buildSlotTraceData(l,{message:"Media event: waiting",mediaState:ee(l.element)})),this.refreshRuntimeState()},k=()=>{l.isSeeking=!0,this.refreshRuntimeState()},P=()=>{l.isSeeking=!1,l.hasReadyEventSinceSourceChange=!0,l.hasBufferingSignalSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(l),this.resetSlotMediaPendingProbe(l),this.maybeResumeRequestedPlayback(l,"seeked"),this.refreshRuntimeState()};return r.addEventListener("loadstart",p),r.addEventListener("canplay",f),r.addEventListener("playing",m),r.addEventListener("progress",S),r.addEventListener("pause",T),r.addEventListener("stalled",v),r.addEventListener("waiting",C),r.addEventListener("seeking",k),r.addEventListener("seeked",P),r.addEventListener("abort",h),r.addEventListener("emptied",d),r.addEventListener("error",u),l.cleanup.push(()=>r.removeEventListener("loadstart",p),()=>r.removeEventListener("canplay",f),()=>r.removeEventListener("playing",m),()=>r.removeEventListener("progress",S),()=>r.removeEventListener("pause",T),()=>r.removeEventListener("stalled",v),()=>r.removeEventListener("waiting",C),()=>r.removeEventListener("seeking",k),()=>r.removeEventListener("seeked",P),()=>r.removeEventListener("abort",h),()=>r.removeEventListener("emptied",d),()=>r.removeEventListener("error",u)),t==="audio"&&((D=this.rootElement)==null||D.appendChild(r)),l}resetSlotRecoveryTracking(e,t=!1){gr(e,t)}destroySlot(e){var t,i,r,n,a;this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.resolveToken+=1,e.applyToken+=1,e.cleanup.forEach(o=>o()),Ne(e.element),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.stableSourceUrl=null,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),e.element.removeAttribute("src"),Ye(e.element),(i=(t=e.gainNode)==null?void 0:t.disconnect)==null||i.call(t),(n=(r=e.sourceNode)==null?void 0:r.disconnect)==null||n.call(r),e.gainNode=null,e.sourceNode=null,(a=e.wrapper)==null||a.remove(),e.element.remove()}releaseSlotObjectUrl(e){var t;e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl),e.objectUrl=null)}clearPendingRuntimeSource(e){e.pendingRuntimeSourceUrl=null,e.pendingRuntimeSourcePromise=null,e.isResolvingSource=!1}rememberSlotObjectUrl(e,t){e.objectUrl&&e.objectUrl!==t&&this.releaseSlotObjectUrl(e),e.objectUrl=t??null}revokeResolvedObjectUrl(e){var t;e!=null&&e.objectUrl&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e.objectUrl))}getTrackSlots(e,t){const i=this.trackSlots.get(e);if(i&&i.current.kind===t&&i.preload.kind===t)return i;i&&(this.destroySlot(i.current),this.destroySlot(i.preload),this.trackSlots.delete(e));const r={current:this.createSlot(e,t,"current"),preload:this.createSlot(e,t,"preload")};return this.trackSlots.set(e,r),r}swapTrackSlots(e){const t=this.trackSlots.get(e);t&&this.trackSlots.set(e,eu(t))}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);Qd(t,e.current.entry)&&(this.swapTrackSlots(e.trackId),t=this.getTrackSlots(e.trackId,e.kind));const i=this.applySlotTarget(t.current,e.current),r=this.applySlotTarget(t.preload,e.preload);if(Ge(i)||Ge(r))return Promise.all([Promise.resolve(i),Promise.resolve(r)]).then(()=>{})}applySlotTarget(e,t){const i=++e.applyToken,r=e.entry,n=_e(e.element)||null,a=r?this.buildPreviewSourceCacheKey(r.clip):null,o=t.entry?this.buildPreviewSourceCacheKey(t.entry.clip):null,l=!!r&&!!t.entry&&r.clip.id!==t.entry.clip.id;if(l&&(uu(e),e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e),this.resetSlotMediaPendingProbe(e)),e.entry=t.entry,e.requestedPlayState=t.playState,e.isActive=t.role==="current"&&!!t.entry,e.errorMessage=t.entry?e.errorMessage:null,e.isBuffering=t.entry?e.isBuffering:!1,e.isSeeking=t.entry?e.isSeeking:!1,e.consecutiveStalledCount=t.entry?e.consecutiveStalledCount:0,this.syncSlotClockAlignmentTarget(e,t,l),!t.entry){this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),(r||n)&&this.emitDiagnostic("info","playback","slot.cleared",this.buildSlotTraceData(e,{message:"Preview slot cleared",extra:{previousClipId:(r==null?void 0:r.clip.id)??null,previousSource:n}})),Ne(e.element),e.stableSourceUrl=null,e.desiredSource=null,e.pendingClockAlignmentMediaTime=null,e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e),pu(e),this.releaseSlotObjectUrl(e),this.clearPendingRuntimeSource(e),e.element.removeAttribute("src"),Ye(e.element),this.setSlotVisible(e,!1,0),this.refreshVisualLayout(),this.refreshRuntimeState();return}a&&o&&a!==o&&(this.releaseSlotObjectUrl(e),e.hasReadyEventSinceSourceChange=!1,e.hasBufferingSignalSinceSourceChange=!1,e.lastPlaybackResumeAttemptAtMs=-1,this.resetSlotPlaybackProgressProbe(e));const c=this.resolveDesiredSource(e,t.entry,i,a);if(Ge(c))return c.then(h=>{if(!h||!this.isCurrentSourceTarget(e,t.entry,h.stableSourceUrl)){this.revokeResolvedObjectUrl(h);return}const d=this.buildCurrentTargetForSlot(e)??t;if(!d.entry){this.revokeResolvedObjectUrl(h);return}if(e.stableSourceUrl=h.stableSourceUrl,e.desiredSource=h.url,this.configureAudioRouting(e,d.entry),this.slotNeedsRecovery(e,h.url)){if(this.shouldDeferPreloadTarget(e,d,h.url)){this.deferPreloadTarget(e,d,h,"current-loading");return}return Promise.resolve(this.recoverSlot(e,"reconcile",d,void 0,h)).then(()=>{})}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,h.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,d)});if(!c||!this.isCurrentRequest(e,i,t.entry)){this.revokeResolvedObjectUrl(c);return}if(e.stableSourceUrl=c.stableSourceUrl,e.desiredSource=c.url,this.configureAudioRouting(e,t.entry),this.slotNeedsRecovery(e,c.url)){if(this.shouldDeferPreloadTarget(e,t,c.url)){this.deferPreloadTarget(e,t,c,"current-loading");return}return this.recoverSlot(e,"reconcile",t,i,c)}this.deferredPreloadSlotKeys.delete(this.getSlotKey(e)),e.recoverableEventCount=0,e.loadStartedSinceRecover=!1,this.rememberSlotObjectUrl(e,c.objectUrl),this.settleResolvedSourceWithoutRecovery(e),this.applyResolvedSlotState(e,t)}settleResolvedSourceWithoutRecovery(e){fu(e)}resolveDesiredSource(e,t,i,r){const n=this.getReusableBoundSlotSource(e,t,r);if(n)return n;const a=this.dependencies.previewSourceResolver??Wd,o=this.dependencies.sourceMediaRegistry;let l=null;const c=()=>(l!==null||(e.resolveToken+=1,l=e.resolveToken,e.phase="binding",e.isResolvingSource=!0,e.isLoading=!0,this.emitDiagnostic("info","resource","source.resolve.pending",this.buildSlotTraceData(e,{message:"Preview source resolving",sourceUrl:t.clip.src,extra:{requestToken:i,resolveToken:l}})),this.refreshRuntimeState()),l);if(!a){const h={url:t.clip.src};return this.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),l)}try{const h=o?o.getPreviewSource(this.buildPreviewSourceCacheKey(t.clip),()=>a(t.clip)):a(t.clip);if(Ge(h)){const d=c();return h.then(u=>d!==e.resolveToken||!this.isCurrentRequest(e,i,t)?null:u?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:u.url,extra:{mimeType:u.mimeType,mediaKind:u.kind}})),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,u),d)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)).catch(u=>(this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:u})),O.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:u}),this.failSlot(e,t,"预览源解析失败"),null))}return h?(this.emitDiagnostic("info","resource","source.resolve.resolved",this.buildSlotTraceData(e,{message:"Preview source resolved",sourceUrl:t.clip.src,desiredSourceUrl:h.url,extra:{mimeType:h.mimeType,mediaKind:h.kind}})),this.dependencies.resourceCacheManager&&c(),this.finalizeSourceResolutionResult(e,this.resolvePlayableSlotSource(e,t,h),l)):(this.emitDiagnostic("warn","resource","source.resolve.missing",this.buildSlotTraceData(e,{message:"Preview source missing",sourceUrl:t.clip.src})),this.failSlot(e,t,"未找到可用预览源"),null)}catch(h){return this.emitDiagnostic("error","resource","source.resolve.failed",this.buildSlotTraceData(e,{message:"Preview source resolve failed",sourceUrl:t.clip.src,error:h})),O.warn("TimelinePreviewSession","preview source resolver failed",{clipId:t.clip.id,error:h}),this.failSlot(e,t,"预览源解析失败"),null}}decorateSlotSourceUrl(e,t){return t}resolvePlayableSlotSource(e,t,i){const r=this.dependencies.resourceCacheManager,n=this.getReusableResolvedSlotSource(e,i);if(n)return this.emitRuntimeSourceDiagnostic(e,i.url,n,"source.runtime.reused","Reused existing runtime preview source"),n;if(e.pendingRuntimeSourceUrl===i.url&&e.pendingRuntimeSourcePromise)return this.emitRuntimeSourceDiagnostic(e,i.url,null,"source.runtime.pending-reused","Reused pending runtime preview source resolution"),e.pendingRuntimeSourcePromise;if(!r)return{stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null,sizeBytes:null};const a=()=>!this.isCurrentSourceTarget(e,t,i.url),o={url:i.url,mimeType:i.mimeType,kind:i.kind,sourceKey:this.buildPreviewSourceCacheKey(t.clip)},l=()=>({stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,i.url),objectUrl:null,sizeBytes:null});try{const c=r.resolvePlayableUrl(o),h=d=>{if(!(d!=null&&d.url))return a()?null:l();const u={stableSourceUrl:i.url,url:this.decorateSlotSourceUrl(e,d.url),objectUrl:d.objectUrl??null,sizeBytes:d.sizeBytes??null};return a()?(this.revokeResolvedObjectUrl(u),null):(this.emitRuntimeSourceDiagnostic(e,i.url,u,"source.runtime.resolved","Resolved runtime playable source",{cacheStatus:d.cacheStatus}),u)};if(Ge(c)){e.isResolvingSource=!0,e.isLoading=!0,e.phase="binding",this.refreshRuntimeState();const d=c.then(h).catch(()=>a()?null:l());return d.finally(()=>{e.pendingRuntimeSourcePromise===d&&(this.clearPendingRuntimeSource(e),this.refreshRuntimeState())}).catch(()=>{}),e.pendingRuntimeSourceUrl=i.url,e.pendingRuntimeSourcePromise=d,d}return h(c)}catch{return a()?null:l()}}emitRuntimeSourceDiagnostic(e,t,i,r,n,a={}){const o=(i==null?void 0:i.url)??t;this.emitDiagnostic("debug","resource",r,this.buildSlotTraceData(e,{message:n,desiredSourceUrl:o,actualSourceUrl:_e(e.element)||null,mediaState:ee(e.element),extra:{stableSourceUrl:t,runtimeSourceUrl:(i==null?void 0:i.url)??null,objectUrl:(i==null?void 0:i.objectUrl)??null,sourceState:Fe(e.element,o),...a}}))}getReusableResolvedSlotSource(e,t){if(!e.desiredSource||e.stableSourceUrl!==t.url)return null;const i=e.objectUrl??(e.desiredSource.startsWith("blob:")?e.desiredSource:null);return{stableSourceUrl:t.url,url:e.desiredSource,objectUrl:i,sizeBytes:null}}getReusableBoundSlotSource(e,t,i){const r=i??(e.entry?this.buildPreviewSourceCacheKey(e.entry.clip):null);if(!r)return null;const n=su({currentSourceKey:r,nextSourceKey:this.buildPreviewSourceCacheKey(t.clip),desiredSource:e.desiredSource,stableSourceUrl:e.stableSourceUrl,objectUrl:e.objectUrl});return n?{...n,sizeBytes:null}:null}slotNeedsRecovery(e,t){const i=ou({desiredSource:t,configuredSource:sr(e.element)||null,assignedSource:_e(e.element)||null,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,phase:e.phase,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,networkEmptyState:Tu,haveCurrentDataState:at});return this.emitDiagnostic(i.shouldWarn?"warn":"debug","recovery","slot.recovery-check",this.buildSlotTraceData(e,{message:i.needsRecovery?"Preview slot needs recovery":"Preview slot source is reusable",desiredSourceUrl:t,actualSourceUrl:i.actualSource,mediaState:ee(e.element),extra:{needsRecovery:i.needsRecovery,recoveryReason:i.recoveryReason,configuredSource:i.configuredSource,actualSource:i.actualSource,forceRecover:e.forceRecover,isActive:e.isActive,isLoading:e.isLoading,isSeeking:e.isSeeking,isBuffering:e.isBuffering,networkState:typeof e.element.networkState=="number"?e.element.networkState:null,readyState:typeof e.element.readyState=="number"?e.element.readyState:null,sourceState:Fe(e.element,t)}})),i.needsRecovery}recoverSlot(e,t,i,r,n){const a=i??(e.entry?{...hu({role:e.role,entry:e.entry,requestedPlayState:e.requestedPlayState,isActive:e.isActive,playbackRate:e.element.playbackRate||1,syncRequestId:this.activeSyncRequestId})}:null);if(!e.entry||!a||r!==void 0&&!this.isCurrentRequest(e,r,e.entry))return;const o=n??(e.desiredSource?{stableSourceUrl:e.stableSourceUrl??e.desiredSource,url:e.desiredSource,objectUrl:e.objectUrl,sizeBytes:null}:this.resolveDesiredSource(e,e.entry,e.applyToken));if(Ge(o))return o.then(l=>{l&&this.finishSlotRecovery(e,t,a,l,r)});o&&this.finishSlotRecovery(e,t,a,o,r)}finishSlotRecovery(e,t,i,r,n){if(!e.entry)return;const a=typeof r=="string"?{stableSourceUrl:e.stableSourceUrl??r,url:r,objectUrl:e.objectUrl}:r,o=a.url,l=du({entry:e.entry,desiredSource:o,reason:t,previousRecoveryKey:e.recoveryKey,previousRetryCount:e.retryCount,maxImmediateRecoveryRetries:bu,recoveryTimeBucketMs:ku,isBackgroundPreload:this.isBackgroundPreloadSlot(e)});if(l.status==="park"){this.parkPreloadSlot(e,l.message,l.parkReason);return}if(l.status==="fail"){this.failSlot(e,e.entry,l.message);return}e.recoveryKey=l.recoveryKey,e.retryCount=l.retryCount,Cu(e,i.playState),this.refreshRuntimeState(),this.emitDiagnostic(t==="reconcile"?"info":"warn","recovery","slot.recover",this.buildSlotTraceData(e,{message:"Recovering preview slot",desiredSourceUrl:o,mediaState:ee(e.element),extra:{reason:t,mediaTime:e.entry.mediaTime,requestedPlayState:i.playState}})),e.retryCount>1&&O.warn("TimelinePreviewSession","recover media slot",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,reason:t,retryCount:e.retryCount,desiredSource:o,mediaState:ee(e.element)});const c=_e(e.element),h=Fe(e.element,o),d=cu(c||null,t,e.retryCount);Ne(e.element),e.expectedEmptiedEvents=d?2:1,e.stableSourceUrl=a.stableSourceUrl,e.hasReadyEventSinceSourceChange=!1,this.resetSlotPlaybackProgressProbe(e),this.resetSlotMediaPendingProbe(e),this.rememberSlotObjectUrl(e,a.objectUrl),d&&(e.element.removeAttribute("src"),Ye(e.element)),e.element.setAttribute("src",o),Ye(e.element),this.emitDiagnostic("info","resource","source.assigned",this.buildSlotTraceData(e,{message:"Preview source assigned",desiredSourceUrl:o,actualSourceUrl:o,extra:{reason:t,hardReset:d,previousSourceState:h,nextSourceState:Fe(e.element,o),objectUrl:a.objectUrl,stableSourceUrl:a.stableSourceUrl}})),!(n!==void 0&&!this.isCurrentRequest(e,n,e.entry))&&this.applyResolvedSlotState(e,i)}getSlotKey(e){return tu(e)}isActiveCurrentSlot(e){return e.role==="current"&&e.isActive&&!!e.entry}isTrackedActiveCurrentVideoSlot(e){return this.isActiveCurrentSlot(e)&&e.kind==="video"}hasBlockingActiveCurrentSlot(e){for(const{current:t}of this.trackSlots.values()){if(e&&this.getSlotKey(t)===e||!this.isTrackedActiveCurrentVideoSlot(t))continue;const i=this.evaluateTrackedCurrentVideoSlot(t);if(!i.ready&&!i.failed)return!0}return!1}shouldDeferPreloadTarget(e,t,i){return t.role!=="preload"||!t.entry||!this.slotNeedsRecovery(e,i)?!1:this.hasBlockingActiveCurrentSlot()}shouldDeferPreloadRecovery(e){return e.role!=="preload"||e.isActive||!e.entry?!1:this.hasBlockingActiveCurrentSlot()}buildDeferredPreloadTarget(e){return iu(e,this.activeSyncRequestId)}deferPreloadTarget(e,t,i,r){const n=i.url;e.desiredSource=n,this.rememberSlotObjectUrl(e,i.objectUrl),e.element.getAttribute("src")&&e.element.getAttribute("src")!==n&&(Ne(e.element),e.element.removeAttribute("src"),Ye(e.element)),_e(e.element)||(e.hasReadyEventSinceSourceChange=!1),yu(e,!!_e(e.element)),this.deferredPreloadSlotKeys.add(this.getSlotKey(e)),this.emitDiagnostic("info","recovery","preload.recovery.deferred",this.buildSlotTraceData(e,{message:"Deferred preload recovery until active current media settles",desiredSourceUrl:n,extra:{reason:r,currentLoading:!0,requestedPlayState:t.playState}})),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState()}deferPreloadRecovery(e,t){this.deferredPreloadSlotKeys.add(this.getSlotKey(e)),this.emitDiagnostic("info","recovery","preload.recovery.deferred",this.buildSlotTraceData(e,{message:"Deferred preload recovery until active current media settles",extra:{reason:t,currentLoading:!0,requestedPlayState:e.requestedPlayState}})),this.scheduleDeferredPreloadFlush()}scheduleDeferredPreloadFlush(){this.deferredPreloadFlushScheduled||this.deferredPreloadSlotKeys.size===0||(this.deferredPreloadFlushScheduled=!0,queueMicrotask(()=>{this.deferredPreloadFlushScheduled=!1,this.flushDeferredPreloads()}))}flushDeferredPreloads(){if(this.deferredPreloadSlotKeys.size===0||this.hasBlockingActiveCurrentSlot())return;const e=Array.from(this.deferredPreloadSlotKeys);this.deferredPreloadSlotKeys.clear();for(const t of e){const i=ru(this.trackSlots,t);if(!i||i.role!=="preload"||!i.entry)continue;const r=this.buildDeferredPreloadTarget(i);if(r){if(this.emitDiagnostic("info","recovery","preload.recovery.resumed",this.buildSlotTraceData(i,{message:"Resumed deferred preload recovery",desiredSourceUrl:i.desiredSource,extra:{requestedPlayState:i.requestedPlayState}})),i.desiredSource&&this.slotNeedsRecovery(i,i.desiredSource)){this.recoverSlot(i,"reconcile",r);continue}this.resetSlotRecoveryTracking(i),this.applyResolvedSlotState(i,r)}}}applyResolvedSlotState(e,t){if(!t.entry)return;e.phase==="failed"&&!!e.errorMessage||(e.errorMessage=null),e.element.playbackRate=t.role==="current"?t.speed:1,t.role==="current"?this.syncCurrentSlot(e,t.entry,t.speed,t.playState):this.preparePreloadSlot(e,t.entry),mu(e),this.setSlotVisible(e,t.visible,t.zIndex),this.refreshVisualLayout(),this.refreshRuntimeState()}buildCurrentTargetForSlot(e){return e.entry?{role:e.role,entry:e.entry,playState:e.requestedPlayState,speed:e.isActive&&e.element.playbackRate||1,visible:e.isActive&&!!e.entry.hasVisual,zIndex:e.isActive?1e3-e.entry.trackOrder:0,syncRequestId:this.activeSyncRequestId}:null}isCurrentRequest(e,t,i){var r;return e.applyToken===t&&((r=e.entry)==null?void 0:r.clip.id)===i.clip.id}isCurrentSourceTarget(e,t,i){return!e.entry||e.entry.clip.id!==t.clip.id?!1:this.buildPreviewSourceCacheKey(e.entry.clip)===this.buildPreviewSourceCacheKey(t.clip)||e.stableSourceUrl===i||e.desiredSource===i}shouldIgnoreExpectedEmptied(e){return e.phase==="recovering"&&!e.loadStartedSinceRecover?!0:e.expectedEmptiedEvents<=0?!1:e.phase!=="recovering"&&!e.isLoading?(e.expectedEmptiedEvents=0,!1):(e.expectedEmptiedEvents-=1,!0)}shouldIgnoreExpectedAbort(e){return e.phase==="recovering"&&!e.loadStartedSinceRecover}shouldIgnoreClearedSlotRecoverableEvent(e){return!e.entry&&e.phase==="idle"}shouldSkipImmediatePreloadRecovery(e){return this.isBackgroundPreloadSlot(e)?!e.loadStartedSinceRecover&&e.recoverableEventCount<2:!1}isBackgroundPreloadSlot(e){return e.role==="preload"&&!e.isActive&&!!e.entry}parkPreloadSlot(e,t,i){Ne(e.element),this.releaseSlotObjectUrl(e),e.element.removeAttribute("src"),Ye(e.element),e.hasReadyEventSinceSourceChange=!1,gu(e),this.emitDiagnostic("warn","recovery","preload.recovery.parked",this.buildSlotTraceData(e,{message:"Background preload parked until next steady sync",mediaState:ee(e.element),extra:{reason:i,errorMessage:t}})),this.refreshVisualLayout(),this.refreshRuntimeState()}failSlot(e,t,i){if(this.isBackgroundPreloadSlot(e)){this.parkPreloadSlot(e,i,"failed");return}Ms(e,i),this.emitDiagnostic("error","recovery","slot.failed",this.buildSlotTraceData(e,{message:"Preview slot failed",mediaState:ee(e.element),extra:{errorMessage:i}})),O.error("TimelinePreviewSession","preview slot failed",{trackId:e.trackId,role:e.role,clipId:t.clip.id,errorMessage:i,mediaState:ee(e.element)}),this.refreshVisualLayout(),this.refreshRuntimeState()}configureAudioRouting(e,t){const i=Math.max(0,Math.min(1,t.clip.volume??1)),r=t.muted?0:i;if(!t.hasAudio){e.element.muted=!0,e.element.volume=0;return}const n=this.getAudioContext();if(!n||e.audioRoutingFailed){e.element.muted=t.muted,e.element.volume=r;return}if(!e.sourceNode||!e.gainNode)try{e.sourceNode=n.createMediaElementSource(e.element),e.gainNode=n.createGain(),e.sourceNode.connect(e.gainNode),e.gainNode.connect(this.getMasterGainNode(n))}catch{e.audioRoutingFailed=!0,e.element.muted=t.muted,e.element.volume=r;return}e.element.muted=!1,e.element.volume=1,e.gainNode.gain.value=r}syncCurrentSlot(e,t,i,r){e.isActive=!0,e.entry=t,e.element.playbackRate=i;const n=t.mediaTime/1e3,a=Math.max(r==="playing"?Au:.1,i*.15),o=r==="playing"&&!e.element.ended,l=this.doesSlotSourceMatchDesired(e,e.desiredSource),c=typeof e.element.readyState=="number"?e.element.readyState:0;if(this.updateSlotPlaybackProgressState(e,{shouldBePlaying:o,sourceMatched:l,readyState:c,speed:i}),!e.playbackProgressStalled&&Math.abs(e.element.currentTime-n)>a&&(this.emitDiagnostic("debug","playback","media.current-slot.seek",this.buildSlotTraceData(e,{message:"Current slot seek applied",mediaState:ee(e.element),extra:{playState:r,speed:i,fromSeconds:Number(e.element.currentTime.toFixed(3)),toSeconds:Number(n.toFixed(3)),deltaSeconds:Number(Math.abs(e.element.currentTime-n).toFixed(3)),thresholdSeconds:Number(a.toFixed(3))}})),e.isSeeking=!0,Os(e.element,n)),r==="playing"){this.resumeAudioContext();const d=Fe(e.element,e.desiredSource);e.element.paused&&(this.emitDiagnostic(d.hasSrcAttribute?"debug":"warn","playback","media.play.requested",this.buildSlotTraceData(e,{message:d.hasSrcAttribute?"Media play requested":"Media play requested without configured src attribute",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:d}})),Rr(e.element))}else this.emitDiagnostic("debug","playback","media.pause.requested",this.buildSlotTraceData(e,{message:"Media pause requested",mediaState:ee(e.element),extra:{playState:r,speed:i,sourceState:Fe(e.element,e.desiredSource)}})),Ne(e.element);this.setSlotVisible(e,t.hasVisual,1e3-t.trackOrder)}resetSlotPlaybackProgressProbe(e){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN,e.playbackProgressStalled=!1}updateSlotPlaybackProgressState(e,t){const i=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN;if(!(t.shouldBePlaying&&e.role==="current"&&e.isActive&&t.sourceMatched&&t.readyState>=at&&!e.element.paused&&!e.element.ended&&!e.isSeeking&&Number.isFinite(i))){e.lastPlaybackProgressCheckAtMs=-1,e.lastPlaybackProgressMediaTimeSeconds=Number.NaN;return}const n=Yi(),a=e.lastPlaybackProgressMediaTimeSeconds,o=e.lastPlaybackProgressCheckAtMs;if(o<0||!Number.isFinite(a)){e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}const l=i-a;if(l>Ds||l<-Ds){e.playbackProgressStalled&&this.emitDiagnostic("info","playback","media.progress.recovered",this.buildSlotTraceData(e,{message:"Media playback progress recovered",mediaState:ee(e.element),extra:{previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3)),advancedSeconds:Number(l.toFixed(3))}})),e.playbackProgressStalled=!1,e.hasBufferingSignalSinceSourceChange||(e.isBuffering=!1),e.lastPlaybackProgressCheckAtMs=n,e.lastPlaybackProgressMediaTimeSeconds=i;return}n-o<_u||(e.playbackProgressStalled||this.emitDiagnostic("warn","playback","media.progress.stalled",this.buildSlotTraceData(e,{message:"Media playback progress stalled without waiting event",mediaState:ee(e.element),extra:{stalledForMs:n-o,speed:t.speed,previousTimeSeconds:Number(a.toFixed(3)),currentTimeSeconds:Number(i.toFixed(3))}})),e.playbackProgressStalled=!0,e.isBuffering=!0)}maybeResumeRequestedPlayback(e,t){if(e.role!=="current"||!e.isActive||!e.entry||e.requestedPlayState!=="playing"||e.element.paused!==!0||this.playbackGroupSuspended)return;const i=Fe(e.element,e.desiredSource);if(!i.hasSrcAttribute)return;const r=Yi();t==="runtime-check"&&(!this.canRuntimeCheckRetryBufferedPlayback(e)||e.lastPlaybackResumeAttemptAtMs>=0&&r-e.lastPlaybackResumeAttemptAtMs<xu)||(e.lastPlaybackResumeAttemptAtMs=r,this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.play.retried",this.buildSlotTraceData(e,{message:"Retried media play after ready event",mediaState:ee(e.element),extra:{reason:t,playState:e.requestedPlayState,speed:e.element.playbackRate||1,sourceState:i}})),Rr(e.element))}canRuntimeCheckRetryBufferedPlayback(e){return e.hasBufferingSignalSinceSourceChange?(typeof e.element.readyState=="number"?e.element.readyState:0)>=Ir&&!e.isSeeking&&!e.playbackProgressStalled:!0}shouldClearRecoveredBufferingSignal(e,t){return t.shouldBePlaying&&e.hasBufferingSignalSinceSourceChange&&e.lastPlaybackResumeAttemptAtMs>=0&&!e.playbackProgressStalled&&!e.isSeeking&&t.readyState>=Ir&&!t.pausedWhilePlaying}preparePreloadSlot(e,t){vu(e),e.entry=t,e.element.playbackRate=1,e.hasReadyEventSinceSourceChange=!1,this.emitDiagnostic("debug","playback","media.preload-slot.seek",this.buildSlotTraceData(e,{message:"Preload slot primed",mediaState:ee(e.element),extra:{toSeconds:Number((t.clip.startTimeAtSource/1e3).toFixed(3))}})),Os(e.element,t.clip.startTimeAtSource/1e3),Ne(e.element),this.setSlotVisible(e,!1,0)}setSlotVisible(e,t,i){if(e.kind!=="video"||!e.wrapper){e.element.style.display="none";return}e.wrapper.style.display=t?"block":"none",e.wrapper.style.zIndex=String(i),e.wrapper.style.pointerEvents="none",e.element.style.display=t?"block":"none",e.element.style.zIndex=String(i),this.syncSlotFailureVisualState(e)}getAudioContext(){if(this.audioContext)return this.audioContext;const e=this.dependencies.createAudioContext;if(e)return this.audioContext=e(),this.audioContext;if(typeof window>"u")return null;const t=window.AudioContext||window.webkitAudioContext;return t?(this.audioContext=new t,this.audioContext):null}getMasterGainNode(e){if(this.masterGainNode)return this.masterGainNode;const t=e.createGain();return t.gain.value=1,t.connect(e.destination),this.masterGainNode=t,t}resumeAudioContext(){var e,t,i,r;!this.audioContext||this.audioContext.state!=="suspended"||(r=(t=(e=this.audioContext).resume)==null?void 0:(i=t.call(e)).catch)==null||r.call(i,()=>{})}updateFrameLayout(){if(!this.container||!this.frameElement)return;const{width:e,height:t}=this.getAspectRatio(),i=this.container.clientWidth,r=this.container.clientHeight;if(i<=0||r<=0||e<=0||t<=0)return;const n=e/t,a=i/r;let o=i,l=r;n>a?l=i/n:o=r*n,this.frameElement.style.width=`${o}px`,this.frameElement.style.height=`${l}px`,this.frameElement.style.left=`${(i-o)/2}px`,this.frameElement.style.top=`${(r-l)/2}px`,this.refreshVisualLayout()}maybeResolveAutoAspectRatio(e){if(!_t(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||!e||!e.hasVisual)return;const t=Oi(e,"sys_width"),i=Oi(e,"sys_height");if(t&&i){this.handleResolvedAutoAspectRatio(t,i);return}if(this.aspectRatioProbeSrc===e.clip.id)return;const r=++this.aspectRatioProbeResolveToken;(async()=>{const a=await this.resolveAspectRatioProbeSource(e,r);if(!a||r!==this.aspectRatioProbeResolveToken)return;const o=this.getAspectRatioProbe();this.aspectRatioProbeSrc=e.clip.id,this.emitDiagnostic("info","resource","aspect-ratio.probe.start",{message:"Aspect ratio probe started",clipId:e.clip.id,sourceUrl:a}),this.refreshRuntimeState(),o.crossOrigin="anonymous",o.preload="metadata",o.muted=!0,o.src=a,Ye(o)})().catch(()=>{})}async resolveAspectRatioProbeSource(e,t){const i=this.dependencies.previewSourceResolver,r=this.dependencies.sourceMediaRegistry;if(!i)return e.clip.src;const n=r?r.getPreviewSource(this.buildPreviewSourceCacheKey(e.clip),()=>i(e.clip)):i(e.clip);if(!Ge(n))return(n==null?void 0:n.url)??null;const a=await n;return t!==this.aspectRatioProbeResolveToken?null:(a==null?void 0:a.url)??null}buildPreviewSourceCacheKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src}getAspectRatioProbe(){var r,n;if(this.aspectRatioProbe)return this.aspectRatioProbe;const e=((n=(r=this.dependencies).createAspectRatioProbe)==null?void 0:n.call(r))||document.createElement("video");Nr(e);const t=()=>{this.emitDiagnostic("info","resource","aspect-ratio.probe.loadedmetadata",{message:"Aspect ratio probe resolved",clipId:this.aspectRatioProbeSrc,extra:{videoWidth:e.videoWidth,videoHeight:e.videoHeight}}),this.refreshRuntimeState(),e.videoWidth>0&&e.videoHeight>0&&this.handleResolvedAutoAspectRatio(e.videoWidth,e.videoHeight)},i=()=>{this.emitDiagnostic("warn","resource","aspect-ratio.probe.error",{message:"Aspect ratio probe failed",clipId:this.aspectRatioProbeSrc,actualSourceUrl:e.currentSrc||e.src||null}),this.refreshRuntimeState()};return e.addEventListener("loadedmetadata",t),e.addEventListener("error",i),this.aspectRatioProbe=e,e}tryResolveAutoAspectRatioFromSlot(e){if(!_t(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const t=e.element;t.videoWidth>0&&t.videoHeight>0&&this.handleResolvedAutoAspectRatio(t.videoWidth,t.videoHeight)}handleResolvedAutoAspectRatio(e,t){var i,r;e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),_t(this.requestedAspectRatio.mode)&&((r=(i=this.callbacks).onAspectRatioChange)==null||r.call(i,this.getAspectRatio())))}refreshRuntimeState(){var m,S,T,v,C,k,P,x;const e=[];let t=null,i=!1,r=0,n=0,a=!1,o=!1,l=!1,c=!1;for(const{current:D,preload:w}of this.trackSlots.values())for(const A of[D,w]){const B=this.isTrackedActiveCurrentVideoSlot(A),z=B?this.evaluateTrackedCurrentVideoSlot(A):null,F=_e(A.element)||null;e.push({trackId:A.trackId,role:A.role,kind:A.kind,clipId:((m=A.entry)==null?void 0:m.clip.id)??null,desiredSource:A.desiredSource,actualSource:F,phase:A.phase,retryCount:A.retryCount,errorMessage:A.errorMessage}),A.phase!=="idle"&&(i=!0),B&&(r+=1,z!=null&&z.failed&&(n+=1,a=!0,t||(t=A.errorMessage||"资源加载异常,请刷新重试")),z!=null&&z.resolving&&(o=!0),z!=null&&z.seeking&&(l=!0),z!=null&&z.mediaUnready&&(c=!0))}const h=this.buildPreviewLoadingState({trackedActiveCurrentVideoSlotCount:r,failedTrackedCurrentVideoSlotCount:n,hasFailedTrackedVideoSlot:a,hasResolvingTrackedVideoSlot:o,hasSeekingTrackedVideoSlot:l,hasMediaUnreadyTrackedVideoSlot:c});this.syncActivePlaybackGroupSuspension(h,r);let d="idle";h.status==="failed"?d="failed":h.status==="loading"&&h.reason==="syncing"?d="awaiting-sync":h.status==="loading"?d="awaiting-media":(r>0&&h.status==="ready"||i)&&(d="ready"),h.status!=="failed"&&(t=null);const u={...this.activeSyncRequestId!==void 0?{syncRequestId:this.activeSyncRequestId}:{},phase:d,loading:h,clock:this.buildPreviewClockState(h),errorMessage:t,slots:e},p=this.lastRuntimeState,f=JSON.stringify(u);f!==this.lastRuntimeSignature&&(this.lastRuntimeSignature=f,this.lastRuntimeState=u,(p.phase!==u.phase||p.loading.status!==u.loading.status||p.loading.reason!==u.loading.reason||p.loading.isLoading!==u.loading.isLoading||p.errorMessage!==u.errorMessage)&&this.emitDiagnostic(u.phase==="failed"?"error":"info","runtime","runtime.state",{message:"Preview runtime state updated",syncRequestId:u.syncRequestId??null,runtimeState:{runtimePhase:u.phase,loadingStatus:u.loading.status,loadingReason:u.loading.reason,isLoading:u.loading.isLoading,clockStatus:((S=u.clock)==null?void 0:S.status)??"unavailable",clockReason:((T=u.clock)==null?void 0:T.reason)??null,clockTimelineTime:((v=u.clock)==null?void 0:v.timelineTime)??null},extra:{previousPhase:p.phase,phase:u.phase,errorMessage:u.errorMessage,loading:u.loading,slots:u.slots.map(D=>({trackId:D.trackId,role:D.role,clipId:D.clipId,phase:D.phase,retryCount:D.retryCount,desiredSource:D.desiredSource,actualSource:D.actualSource}))}}),(k=(C=this.callbacks).onRuntimeStateChange)==null||k.call(C,u)),(h.status==="ready"||h.status==="failed"||h.status==="idle")&&u.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==u.syncRequestId&&(this.lastSettledSyncRequestId=u.syncRequestId,(x=(P=this.callbacks).onSyncProcessed)==null||x.call(P,u.syncRequestId)),h.status!=="loading"&&this.deferredPreloadSlotKeys.size>0&&this.scheduleDeferredPreloadFlush(),this.syncLoadingProbe(h),this.syncClockProbe(u.clock),this.refreshPendingOverlay()}buildPreviewClockState(e){const t=this.getPreviewClockSourceSlot();if(!(t!=null&&t.entry))return this.buildPreviewClockStateFromSlot(null,"unavailable","no-video-clock");const i=this.doesSlotSourceMatchDesired(t,t.desiredSource),r=this.getSlotMediaTimeMs(t),n=this.getSlotTimelineTime(t,r),a=t.requestedPlayState==="playing"&&!t.element.ended;return e.status==="failed"||t.phase==="failed"?this.buildPreviewClockStateFromSlot(t,"failed","failed",n,r):a?!i||t.isResolvingSource||t.phase==="binding"?this.buildPreviewClockStateFromSlot(t,"priming","resolving-source",n,r):t.isSeeking||e.reason==="seeking"?this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):this.isSlotClockAlignedToPendingMediaTarget(t,r)?t.isBuffering||t.playbackProgressStalled?this.buildPreviewClockStateFromSlot(t,"blocked","media-stalled",n,r):this.isPreviewClockSlotAlignedToPendingTarget(t,n)?e.status==="loading"?this.buildPreviewClockStateFromSlot(t,"blocked",this.resolveClockBlockedReason(e.reason),n,r):t.element.paused?this.buildPreviewClockStateFromSlot(t,"blocked","media-paused",n,r):n===null||r===null?this.buildPreviewClockStateFromSlot(t,"priming","media-pending",n,r):(this.pendingClockAlignmentTargetTime=null,this.buildPreviewClockStateFromSlot(t,"running",null,n,r)):this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):this.buildPreviewClockStateFromSlot(t,"blocked","seeking",n,r):this.buildPreviewClockStateFromSlot(t,"unavailable",null,n,r)}syncSlotClockAlignmentTarget(e,t,i){if(t.role!=="current"||!t.entry){e.pendingClockAlignmentMediaTime=null;return}(i||e.pendingClockAlignmentMediaTime!==null)&&(e.pendingClockAlignmentMediaTime=t.entry.mediaTime)}isSlotClockAlignedToPendingMediaTarget(e,t){const i=e.pendingClockAlignmentMediaTime;if(i===null)return!0;if(t===null)return!1;const r=this.getPreviewClockTargetAlignmentThresholdMs(e);return Math.abs(t-i)>r?!1:(e.pendingClockAlignmentMediaTime=null,!0)}buildPreviewClockStateFromSlot(e,t,i,r=null,n=null){var a;return{status:t,timelineTime:r,mediaTime:n,clipId:((a=e==null?void 0:e.entry)==null?void 0:a.clip.id)??null,trackId:(e==null?void 0:e.trackId)??null,reason:i}}resolveClockBlockedReason(e){return e==="syncing"||e==="resolving-source"||e==="seeking"||e==="media-pending"||e==="failed"?e:"media-pending"}getPreviewClockSourceSlot(){var t,i;const e=[];for(const{current:r}of this.trackSlots.values())this.isTrackedActiveCurrentVideoSlot(r)&&((t=r.entry)!=null&&t.hasVisual)&&e.push(this.buildPreviewClockSourceCandidate(r));return e.length===0?(this.pendingClockAlignmentTargetTime=null,null):(e.sort((r,n)=>this.comparePreviewClockSourceCandidates(r,n)),((i=e[0])==null?void 0:i.slot)??null)}buildPreviewClockSourceCandidate(e){const t=this.getSlotMediaTimeMs(e),i=this.getSlotTimelineTime(e,t),r=this.doesSlotSourceMatchDesired(e,e.desiredSource),n=typeof e.element.readyState=="number"?e.element.readyState:0,a=this.pendingClockAlignmentTargetTime===null||i===null?Number.POSITIVE_INFINITY:Math.abs(i-this.pendingClockAlignmentTargetTime),o=e.requestedPlayState==="playing"&&!e.element.ended,l=n>=at||e.hasReadyEventSinceSourceChange,c=!!e.entry&&r&&l&&!e.isResolvingSource&&e.phase!=="binding"&&e.phase!=="failed"&&!e.isSeeking&&!e.isBuffering&&!e.playbackProgressStalled&&(!o||!e.element.paused)&&t!==null&&i!==null;return{slot:e,timelineTime:i,targetDistance:a,sourceMatched:r,readyState:n,usable:c}}comparePreviewClockSourceCandidates(e,t){var n,a;const i=this.isPreviewClockCandidateAlignedToTarget(e),r=this.isPreviewClockCandidateAlignedToTarget(t);return i!==r?i?-1:1:this.pendingClockAlignmentTargetTime!==null&&e.targetDistance!==t.targetDistance?e.targetDistance-t.targetDistance:e.usable!==t.usable?e.usable?-1:1:e.sourceMatched!==t.sourceMatched?e.sourceMatched?-1:1:e.readyState!==t.readyState?t.readyState-e.readyState:(((n=e.slot.entry)==null?void 0:n.trackOrder)??0)-(((a=t.slot.entry)==null?void 0:a.trackOrder)??0)}isPreviewClockCandidateAlignedToTarget(e){return this.pendingClockAlignmentTargetTime!==null&&e.usable&&e.targetDistance<=this.getPreviewClockTargetAlignmentThresholdMs(e.slot)}getPreviewClockTargetAlignmentThresholdMs(e){return Math.max(Iu,this.getSlotSeekThresholdSeconds(e)*1e3)}isPreviewClockSlotAlignedToPendingTarget(e,t){return this.pendingClockAlignmentTargetTime===null||t===null?!0:Math.abs(t-this.pendingClockAlignmentTargetTime)<=this.getPreviewClockTargetAlignmentThresholdMs(e)}updatePendingClockAlignmentTarget(e){if(!e.activeClips.some(i=>i.trackType==="video"&&i.hasVisual)){this.pendingClockAlignmentTargetTime=null;return}(e.interactionMode==="seek"||e.interactionMode==="scrub")&&(this.pendingClockAlignmentTargetTime=e.currentTime)}syncActivePlaybackGroupSuspension(e,t){var n;const i=((n=this.pendingState)==null?void 0:n.mode)==="seek";if(t>1&&!i&&(e.status==="loading"||e.status==="failed")){this.playbackGroupSuspended=!0;for(const{current:a}of this.trackSlots.values())!this.isActiveCurrentSlot(a)||a.requestedPlayState!=="playing"||a.isBuffering||a.playbackProgressStalled||a.isSeeking||a.isResolvingSource||a.phase==="binding"||a.phase==="recovering"||a.element.paused||(this.emitDiagnostic("debug","playback","media.group-pause.requested",this.buildSlotTraceData(a,{message:"Paused active media while preview playback group is blocked",mediaState:ee(a.element),extra:{loadingStatus:e.status,loadingReason:e.reason}})),Ne(a.element));return}if(this.playbackGroupSuspended){this.playbackGroupSuspended=!1;for(const{current:a}of this.trackSlots.values()){if(!this.isActiveCurrentSlot(a)||a.requestedPlayState!=="playing"||!a.element.paused||a.element.ended)continue;const o=Fe(a.element,a.desiredSource);o.hasSrcAttribute&&(this.resumeAudioContext(),this.emitDiagnostic("debug","playback","media.group-play.requested",this.buildSlotTraceData(a,{message:"Resumed active media after preview playback group became ready",mediaState:ee(a.element),extra:{loadingStatus:e.status,loadingReason:e.reason,sourceState:o}})),Rr(a.element))}}}getSlotMediaTimeMs(e){return Number.isFinite(e.element.currentTime)?Math.max(0,e.element.currentTime*1e3):null}getSlotTimelineTime(e,t=this.getSlotMediaTimeMs(e)){if(!e.entry||t===null)return null;const i=e.entry.clip,r=i.startTime+(t-i.startTimeAtSource);return Math.max(i.startTime,Math.min(i.endTime,r))}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.lastRuntimeState})}buildPreviewLoadingState(e){return e.trackedActiveCurrentVideoSlotCount<=0?{status:"idle",isLoading:!1,reason:null}:e.hasFailedTrackedVideoSlot&&e.failedTrackedCurrentVideoSlotCount>=e.trackedActiveCurrentVideoSlotCount?{status:"failed",isLoading:!1,reason:"failed"}:this.activeSyncRequestId!==void 0&&this.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:e.hasResolvingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"resolving-source"}:e.hasSeekingTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"seeking"}:e.hasMediaUnreadyTrackedVideoSlot?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}evaluateTrackedCurrentVideoSlot(e){if(!this.isTrackedActiveCurrentVideoSlot(e)||!e.entry)return{failed:!1,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1};const t=e.desiredSource,i=this.doesSlotSourceMatchDesired(e,t),r=typeof e.element.readyState=="number"?e.element.readyState:0,n=e.entry.mediaTime/1e3,a=Number.isFinite(e.element.currentTime)?e.element.currentTime:Number.NaN,o=this.getSlotSeekThresholdSeconds(e),l=Number.isFinite(a)&&Math.abs(a-n)<=o,c=e.requestedPlayState==="playing"&&!e.element.ended,h=r>=at;let d=c&&e.element.paused&&!this.playbackGroupSuspended;d&&(this.maybeResumeRequestedPlayback(e,"runtime-check"),d=c&&e.element.paused&&!this.playbackGroupSuspended),this.shouldClearRecoveredBufferingSignal(e,{shouldBePlaying:c,readyState:r,pausedWhilePlaying:d})&&(e.hasBufferingSignalSinceSourceChange=!1,e.isBuffering=!1),this.playbackGroupSuspended&&e.playbackProgressStalled&&!e.hasBufferingSignalSinceSourceChange&&r>=Ir&&(e.playbackProgressStalled=!1,e.isBuffering=!1),this.updateSlotPlaybackProgressState(e,{shouldBePlaying:c,sourceMatched:i,readyState:r,speed:e.element.playbackRate||1}),c&&e.isBuffering&&!e.hasBufferingSignalSinceSourceChange&&!e.playbackProgressStalled&&h&&!d&&(e.isBuffering=!1);const u=e.hasReadyEventSinceSourceChange&&!e.isBuffering,f=!(c&&(e.isBuffering||e.playbackProgressStalled))&&!d&&(h||!c&&e.hasReadyEventSinceSourceChange||c&&u),m=Su(e,{hasDesiredSource:!!t,sourceMatched:i,withinSeekThreshold:l,readyState:f?at:Math.min(r,at-1),haveCurrentDataState:at});return this.failStalledMediaPendingSlotIfNeeded(e,m,i)?{failed:!0,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1}:(m.ready?(this.resetSlotMediaPendingProbe(e),this.tryResolveAutoAspectRatioFromSlot(e)):m.mediaUnready||this.resetSlotMediaPendingProbe(e),m)}failStalledMediaPendingSlotIfNeeded(e,t,i){if(!t.mediaUnready||t.failed||t.resolving||t.seeking||!e.entry||e.role!=="current"||!e.isActive||!e.desiredSource||!i)return this.resetSlotMediaPendingProbe(e),!1;const r=`${e.entry.clip.id}:${e.desiredSource}`,n=Yi();if(e.mediaPendingFailureKey!==r)return e.mediaPendingFailureKey=r,e.mediaPendingSinceMs=n,!1;if(e.mediaPendingSinceMs<0||n-e.mediaPendingSinceMs<Ls)return!1;const a=n-e.mediaPendingSinceMs;return Ms(e,Wt),this.resetSlotMediaPendingProbe(e),this.emitDiagnostic("error","recovery","slot.failed",this.buildSlotTraceData(e,{message:"Preview slot failed after media pending timeout",mediaState:ee(e.element),extra:{errorMessage:Wt,pendingForMs:a,timeoutMs:Ls}})),O.error("TimelinePreviewSession","preview slot failed after media pending timeout",{trackId:e.trackId,role:e.role,clipId:e.entry.clip.id,errorMessage:Wt,mediaState:ee(e.element)}),this.refreshVisualLayout(),!0}resetSlotMediaPendingProbe(e){e.mediaPendingSinceMs=-1,e.mediaPendingFailureKey=null}doesSlotSourceMatchDesired(e,t){return au(sr(e.element)||null,_e(e.element)||null,t)}getSlotSeekThresholdSeconds(e){return lu(e.role,e.element.playbackRate||1)}finalizeSourceResolutionResult(e,t,i){return i===null?(e.isResolvingSource=!1,t):Ge(t)?t.finally(()=>{e.resolveToken===i&&(e.isResolvingSource=!1,this.refreshRuntimeState())}):(e.resolveToken===i&&(e.isResolvingSource=!1),t)}syncLoadingProbe(e){if(e.status!=="loading"){this.clearLoadingProbe();return}this.loadingProbeTimeoutId||(this.loadingProbeTimeoutId=setTimeout(()=>{this.loadingProbeTimeoutId=null,this.refreshRuntimeState()},wu))}syncClockProbe(e){if(!((e==null?void 0:e.status)==="running"||(e==null?void 0:e.status)==="blocked"||(e==null?void 0:e.status)==="priming")){this.clearClockProbe();return}this.clockProbeTimeoutId||(this.clockProbeTimeoutId=setTimeout(()=>{this.clockProbeTimeoutId=null,this.refreshRuntimeState()},Pu))}clearLoadingProbe(){this.loadingProbeTimeoutId&&(clearTimeout(this.loadingProbeTimeoutId),this.loadingProbeTimeoutId=null)}clearClockProbe(){this.clockProbeTimeoutId&&(clearTimeout(this.clockProbeTimeoutId),this.clockProbeTimeoutId=null)}handlePreviewTransformChange(e,t){var i;if(!t){((i=this.transientVisualTransform)==null?void 0:i.clipId)===e&&(this.transientVisualTransform=null,this.refreshVisualLayout());return}this.transientVisualTransform={clipId:e,transform:t},this.refreshVisualLayout()}refreshVisualLayout(){for(const{current:e,preload:t}of this.trackSlots.values())this.refreshSlotVisualLayout(e),this.refreshSlotVisualLayout(t);this.refreshTextPreviewLayout(),this.transformOverlay.sync(this.buildSelectedOverlayState())}syncTextPreviewEntries(e){this.ensureTextPreviewFontReady();const t=e.filter(r=>!r.muted&&r.hasVisual).sort((r,n)=>r.trackOrder-n.trackOrder),i=new Set(t.map(r=>r.clip.id));for(const[r]of this.textPreviewEntries)i.has(r)||this.removeTextPreviewEntry(r);t.forEach(r=>{var c;const n=this.textPreviewEntries.get(r.clip.id);if(n){n.entry=r,this.applyTextPreviewEntry(n);return}const a=document.createElement("div");a.className="timeline-preview-text-entry",a.style.position="absolute",a.style.left="0",a.style.top="0",a.style.transformOrigin="center center",a.style.whiteSpace="pre",a.style.wordBreak="normal",a.style.overflowWrap="normal",a.style.pointerEvents="none",a.style.userSelect="none",a.style.boxSizing="border-box",a.style.border="1px solid transparent";const o=this.createTextPreviewPointerDownHandler(r.clip.id);a.addEventListener("pointerdown",o),(c=this.textOverlayRoot)==null||c.appendChild(a);const l={entry:r,element:a,handlePointerDown:o};this.textPreviewEntries.set(r.clip.id,l),this.applyTextPreviewEntry(l)}),this.refreshTextPreviewInteractionState()}clearTextPreviewEntries(){for(const e of Array.from(this.textPreviewEntries.keys()))this.removeTextPreviewEntry(e)}removeTextPreviewEntry(e){var i;const t=this.textPreviewEntries.get(e);t&&(((i=this.textPreviewDragState)==null?void 0:i.clipId)===e&&this.finishTextPreviewDrag(!1),t.element.removeEventListener("pointerdown",t.handlePointerDown),t.element.remove(),this.textPreviewEntries.delete(e))}applyTextPreviewEntry(e){const t=De(e.entry.clip.textStyle),i=e.entry.clip.textContent||e.entry.clip.name||"";e.element.textContent=i,e.element.style.color=t.color,e.element.style.fontFamily=this.getTextPreviewFontFamily(),e.element.style.fontSize=`${t.fontSize}px`,e.element.style.textShadow=Eu(t.strokeWidth,t.strokeColor),e.element.style.padding=`0 ${t.paddingX}px`,e.element.style.textAlign="left",e.element.style.zIndex=String(2e3-e.entry.trackOrder)}refreshTextPreviewLayout(){var i;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return;const t=this.getTextPreviewBaselineMetrics(e);for(const r of this.textPreviewEntries.values()){const n=this.getEffectiveVisualTransform(r.entry),a=r.entry.clip.id,o=De(r.entry.clip.textStyle).rotation,l=((i=this.transientRotation)==null?void 0:i.clipId)===a?this.transientRotation.rotation:o;r.element.style.left=`${e.width*n.x}px`,r.element.style.top=`${e.height*n.y}px`,r.element.style.transform=["translate(-50%, -50%)",`scale(${t.scale*n.scale})`,`rotate(${l}deg)`].join(" ")}}refreshTextPreviewEntries(){for(const e of this.textPreviewEntries.values())this.applyTextPreviewEntry(e);this.refreshTextPreviewLayout(),this.refreshTextPreviewInteractionState()}createTextPreviewPointerDownHandler(e){return t=>{var a,o,l,c;const i=t;if((i.button??0)!==0)return;if((a=i.preventDefault)==null||a.call(i),(o=i.stopPropagation)==null||o.call(i),this.requestPauseIfPlaying(),this.primarySelectedClipId!==e){(c=(l=this.callbacks).onPreviewClipSelect)==null||c.call(l,e);return}this.textPreviewDragState&&this.finishTextPreviewDrag(!1);const r=this.textPreviewEntries.get(e);if(!r)return;const n=this.getEffectiveVisualTransform(r.entry);this.textPreviewDragState={clipId:e,pointerStart:this.toFrameLocalPoint(i),startTransform:n,nextTransform:n,changed:!1},this.bindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}}bindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.addEventListener("pointermove",this.boundTextPreviewPointerMove),e.addEventListener("pointerup",this.boundTextPreviewPointerUp),e.addEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.addEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}unbindTextPreviewDocumentListeners(){var t,i;const e=this.getDocument();e&&(e.removeEventListener("pointermove",this.boundTextPreviewPointerMove),e.removeEventListener("pointerup",this.boundTextPreviewPointerUp),e.removeEventListener("visibilitychange",this.boundTextPreviewVisibilityChange),(i=(t=globalThis.window)==null?void 0:t.removeEventListener)==null||i.call(t,"blur",this.boundTextPreviewWindowBlur))}handleTextPreviewPointerMove(e){var o;const t=this.textPreviewDragState;if(!t)return;if(!this.textPreviewEntries.get(t.clipId)){this.finishTextPreviewDrag(!1);return}const r=e;(o=r.preventDefault)==null||o.call(r);const n=this.toFrameLocalPoint(r),a=go(t.startTransform,n.x-t.pointerStart.x,n.y-t.pointerStart.y,this.getFrameSize());t.nextTransform=a,t.changed=!wn(t.startTransform,a),this.handlePreviewTransformChange(t.clipId,a),this.refreshTextPreviewInteractionState()}finishTextPreviewDrag(e){var i,r;const t=this.textPreviewDragState;if(!t){this.unbindTextPreviewDocumentListeners();return}e&&t.changed&&((r=(i=this.callbacks).onVisualTransformCommit)==null||r.call(i,t.clipId,t.nextTransform)),this.handlePreviewTransformChange(t.clipId,null),this.textPreviewDragState=null,this.unbindTextPreviewDocumentListeners(),this.refreshTextPreviewInteractionState()}refreshTextPreviewInteractionState(){var e;for(const t of this.textPreviewEntries.values()){const i=t.entry.clip.id===this.primarySelectedClipId,r=t.entry.clip.id===((e=this.textPreviewDragState)==null?void 0:e.clipId);t.element.style.pointerEvents="auto",t.element.style.cursor=i?r?"grabbing":"grab":"pointer",t.element.style.border=i?`1px solid ${ot.border}`:"1px solid transparent"}}getTextPreviewFontConfig(){const e=this.dependencies.textPreviewFont;return!(e!=null&&e.fontName)||!e.fontSourceUrl?null:e}getTextPreviewFontFamily(){const e=this.getTextPreviewFontConfig();return!e||this.textPreviewFontLoadState==="failed"?Bs:`${Er(e.fontName)}, ${Bs}`}ensureTextPreviewFontReady(){const e=this.getTextPreviewFontConfig();if(!e||!this.rootElement||typeof document>"u")return;const t=`${e.fontName}::${e.fontSourceUrl}`;if(this.textPreviewFontSignature!==t){this.resetTextPreviewFontState();const n=document.createElement("style");n.textContent=["@font-face {",`font-family: ${Er(e.fontName)};`,`src: url("${mo(e.fontSourceUrl)}");`,"font-display: swap;","}"].join(""),this.rootElement.appendChild(n),this.textPreviewFontStyleElement=n,this.textPreviewFontSignature=t,this.textPreviewFontLoadState="idle"}const i=document.fonts;if(typeof(i==null?void 0:i.load)!="function"||this.textPreviewFontLoadState==="loading"||this.textPreviewFontLoadState==="loaded")return;const r=++this.textPreviewFontLoadToken;this.textPreviewFontLoadState="loading",Promise.resolve(i.load(`1em ${Er(e.fontName)}`)).then(()=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="loaded",this.refreshTextPreviewEntries())}).catch(n=>{this.textPreviewFontLoadToken===r&&(this.textPreviewFontLoadState="failed",O.warn("TimelinePreviewSession","Failed to load text preview font",{fontName:e.fontName,fontSourceUrl:e.fontSourceUrl,error:n}),this.refreshTextPreviewEntries())})}resetTextPreviewFontState(){var e;this.textPreviewFontLoadToken+=1,this.textPreviewFontLoadState="idle",this.textPreviewFontSignature=null,(e=this.textPreviewFontStyleElement)==null||e.remove(),this.textPreviewFontStyleElement=null}refreshSlotVisualLayout(e){if(e.kind!=="video"||!e.wrapper||!e.entry||!this.frameElement)return;const t=this.getFrameSize();if(t.width<=0||t.height<=0)return;const i=this.getMediaSize(e,e.entry,t),r=this.getEffectiveVisualTransform(e.entry),n=Es(t,i,r);e.wrapper.style.left=`${n.left}px`,e.wrapper.style.top=`${n.top}px`,e.wrapper.style.width=`${n.width}px`,e.wrapper.style.height=`${n.height}px`,this.syncSlotFailureVisualState(e)}syncSlotFailureVisualState(e){if(e.kind!=="video"||!e.wrapper||!e.failureOverlay||!e.failureLabel)return;const t=e.phase==="failed"&&!!e.entry;e.wrapper.style.background=t?_.mediaClipFailedBackground:_.black,e.failureOverlay.style.display=t?"flex":"none",e.failureLabel.textContent=Wt,e.element.style.visibility=t?"hidden":"visible"}buildSelectedOverlayState(){var t,i;if(!this.primarySelectedClipId)return null;const e=this.getFrameSize();if(e.width<=0||e.height<=0)return null;for(const{current:r}of this.trackSlots.values()){if(r.kind!=="video"||!r.isActive||!r.entry||r.entry.clip.id!==this.primarySelectedClipId)continue;const n=this.getMediaSize(r,r.entry,e),a=this.getEffectiveVisualTransform(r.entry);return{clipId:r.entry.clip.id,transform:a,frameSize:e,baseRect:po(e,n),displayRect:Es(e,n,a),clipType:"video"}}if(this.frameElement)for(const[r,n]of this.textPreviewEntries){if(r!==this.primarySelectedClipId)continue;const a=this.getEffectiveVisualTransform(n.entry),o=De(n.entry.clip.textStyle),l=((t=this.transientFontSize)==null?void 0:t.clipId)===r?this.transientFontSize.fontSize:o.fontSize,c=((i=this.transientRotation)==null?void 0:i.clipId)===r?this.transientRotation.rotation:o.rotation,d=this.getTextPreviewBaselineMetrics(e).scale*a.scale,u=(n.element.offsetWidth||0)*d,p=(n.element.offsetHeight||0)*d,f=e.width*a.x,m=e.height*a.y;return{clipId:r,transform:a,frameSize:e,baseRect:{left:0,top:0,width:e.width,height:e.height,centerX:e.width/2,centerY:e.height/2},displayRect:{left:f-u/2,top:m-p/2,width:u,height:p,centerX:f,centerY:m},clipType:"text",currentFontSize:l,currentRotation:c}}return null}getFrameSize(){var i,r,n,a;const e=((i=this.frameElement)==null?void 0:i.clientWidth)??0,t=((r=this.frameElement)==null?void 0:r.clientHeight)??0;return{width:e>0?e:Fs((n=this.frameElement)==null?void 0:n.style.width),height:t>0?t:Fs((a=this.frameElement)==null?void 0:a.style.height)}}getDocument(){var e;return(e=this.frameElement)!=null&&e.ownerDocument?this.frameElement.ownerDocument:typeof document<"u"?document:null}toFrameLocalPoint(e){var i;const t=(i=this.frameElement)==null?void 0:i.getBoundingClientRect();return{x:(e.clientX??0)-((t==null?void 0:t.left)??0),y:(e.clientY??0)-((t==null?void 0:t.top)??0)}}getTextPreviewBaselineMetrics(e){const t=Ru(this.getAspectRatio());return t.width<=0||t.height<=0||e.width<=0||e.height<=0?{width:t.width,height:t.height,scale:1}:{width:t.width,height:t.height,scale:Math.min(e.width/t.width,e.height/t.height)}}getMediaSize(e,t,i){if(ar(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=Oi(t,"sys_width"),n=Oi(t,"sys_height");return r&&n?{width:r,height:n}:{width:i.width,height:i.height}}getEffectiveVisualTransform(e){var t;return((t=this.transientVisualTransform)==null?void 0:t.clipId)===e.clip.id?this.transientVisualTransform.transform:Pe(e.clip.visualTransform)}}class Bu extends Lu{constructor(e={}){super(e.callbacks,{diagnostics:e.diagnostics,getDiagnosticsContext:e.getDiagnosticsContext,previewSourceResolver:e.previewSourceResolver,textPreviewFont:e.textPreviewFont,sourceMediaRegistry:e.sourceMediaRegistry,resourceCacheManager:e.resourceCacheManager,rootClassName:e.rootClassName,frameClassName:e.frameClassName,slotClassNamePrefix:e.slotClassNamePrefix})}destroy(){this.detach()}}function Ou(s){return"dom"}const Fu=36e5,Nu=3e5;function ln(s){return s.length===0?0:s.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function Ns(s){return ln(s)}function Gs(s){return Math.max(s+Nu,Fu)}class Hs{constructor(e={}){g(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(r){O.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function Gu(s){return[...s].sort((e,t)=>e.order-t.order)}function Hu(s){return[...s].sort((e,t)=>e.startTime-t.startTime)}function Mr(s,e,t){const i=s.type==="video"||s.type==="text",r=s.type!=="text";return{trackId:s.id,trackType:s.type,trackOrder:s.order,clip:e,mediaTime:t,muted:(s.isMuted??!1)||(e.isMuted??!1),kind:s.type,hasVisual:i,hasAudio:r}}class zu{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t,i={}){const r=Gu(e),n=[],a=[];let o=null;for(const l of r){const c=Hu(l.clips),h=c.find(u=>t>=u.startTime&&t<u.endTime?!0:!!i.includeEndedClipsAtTime&&t>=u.startTime&&t===u.endTime);if(h){const u=h.startTimeAtSource+(t-h.startTime);n.push(Mr(l,h,u))}const d=c.find(u=>u.startTime>t);if(d&&a.push(Mr(l,d,d.startTimeAtSource)),!o&&l.type==="video"){const u=c[0];u&&(o=Mr(l,u,u.startTimeAtSource))}}return{activeClips:n,nextClips:a,firstVideoClip:o}}}class $u{constructor(e){g(this,"options");g(this,"_previewSession");g(this,"_previewMountContainer",null);g(this,"_resolvedPreviewBackend","dom");g(this,"_runtimePreviewBackendOverride",null);g(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const Vu=1e3;class Uu{constructor(e){g(this,"callbacks");g(this,"failedOverlayDelayMs");g(this,"_previewLoadingState",{status:"idle",isLoading:!1,reason:null});g(this,"_pendingPreviewState",null);g(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.failedOverlayDelayMs=e.failedOverlayDelayMs??Vu}get previewLoadingState(){return this._previewLoadingState}get pendingPreviewState(){return this._pendingPreviewState}set pendingPreviewState(e){this._pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this._nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this._nextPendingPreviewSyncRequestId=Math.max(0,e)}handleRuntimeStateChange(e){const t=this._previewLoadingState;this._previewLoadingState=e.loading;const i=this._pendingPreviewState;i&&(e.syncRequestId===i.syncRequestId||e.syncRequestId===void 0)&&(e.loading.reason!=="syncing"&&(i.awaitingSync=!1),e.loading.status==="failed"?this.scheduleFailedOverlay(e.errorMessage||"资源加载异常,请刷新重试"):(this.clearFailedOverlayTimeout(),i.pendingFailedMessage=null,i.errorMessage=null)),zs(t,e.loading)||this.callbacks.emitLoadingStateChange(e.loading),this.updatePendingPreviewState()}markSyncProcessed(e){this._pendingPreviewState&&e===this._pendingPreviewState.syncRequestId&&(this._pendingPreviewState.awaitingSync=!1),this.updatePendingPreviewState()}beginPendingPreview(e,t,i){this.clearPendingPreviewTimeout(),this._pendingPreviewState={mode:t,targetTime:e,resumePlayOnReady:i,errorMessage:null,timeoutId:null,failedTimeoutId:null,pendingFailedMessage:null,awaitingSync:!0,syncRequestId:++this._nextPendingPreviewSyncRequestId}}buildPreviewPendingState(){return this._pendingPreviewState?this._pendingPreviewState.mode==="scrub"?null:{mode:this._pendingPreviewState.mode,targetTime:this._pendingPreviewState.targetTime,loading:this.resolvePendingLoadingState(),errorMessage:this._pendingPreviewState.errorMessage}:this.buildPlaybackLoadingOverlayState()}updatePendingPreviewState(){if(!this._pendingPreviewState){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const t=this.resolvePendingLoadingState().status==="loading";if(this._pendingPreviewState.errorMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.pendingFailedMessage){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(this._pendingPreviewState.awaitingSync){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}if(t){this.callbacks.applyPendingState(this.buildPreviewPendingState());return}const i=this._pendingPreviewState.resumePlayOnReady;this.clearPendingPreviewState(),i&&this.callbacks.resumePlayback()}retryPendingPreview(){this._pendingPreviewState&&(this._pendingPreviewState.errorMessage=null,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.awaitingSync=!0,this._pendingPreviewState.syncRequestId=++this._nextPendingPreviewSyncRequestId,this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this.callbacks.requestPreviewSync())}clearPendingPreviewState(){this.clearPendingPreviewTimeout(),this.clearFailedOverlayTimeout(),this._pendingPreviewState=null,this.callbacks.applyPendingState(null)}resetPreviewRuntimeState(){const e={status:"idle",isLoading:!1,reason:null};zs(this._previewLoadingState,e)||(this._previewLoadingState=e,this.callbacks.emitLoadingStateChange(e))}resolvePendingLoadingState(){var e;return(e=this._pendingPreviewState)!=null&&e.awaitingSync?{status:"loading",isLoading:!0,reason:"syncing"}:this._previewLoadingState}buildPlaybackLoadingOverlayState(){return this._previewLoadingState.status!=="loading"||this._previewLoadingState.reason!=="media-pending"?null:{mode:"playback",targetTime:0,loading:this._previewLoadingState,errorMessage:null}}clearPendingPreviewTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.timeoutId&&(clearTimeout(this._pendingPreviewState.timeoutId),this._pendingPreviewState.timeoutId=null)}scheduleFailedOverlay(e){if(!this._pendingPreviewState||this._pendingPreviewState.errorMessage===e||this._pendingPreviewState.pendingFailedMessage===e&&this._pendingPreviewState.failedTimeoutId)return;this.clearFailedOverlayTimeout(),this._pendingPreviewState.pendingFailedMessage=e;const t=this._pendingPreviewState.syncRequestId;this._pendingPreviewState.failedTimeoutId=setTimeout(()=>{!this._pendingPreviewState||this._pendingPreviewState.syncRequestId!==t||(this._pendingPreviewState.errorMessage=e,this._pendingPreviewState.pendingFailedMessage=null,this._pendingPreviewState.failedTimeoutId=null,this.callbacks.applyPendingState(this.buildPreviewPendingState()))},this.failedOverlayDelayMs)}clearFailedOverlayTimeout(){var e;(e=this._pendingPreviewState)!=null&&e.failedTimeoutId&&(clearTimeout(this._pendingPreviewState.failedTimeoutId),this._pendingPreviewState.failedTimeoutId=null)}}function zs(s,e){return s.status===e.status&&s.isLoading===e.isLoading&&s.reason===e.reason}const Wu=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Yu={togglePlay:["Space"],deleteSelectedClips:["Delete","Backspace"],copySelectedClips:["Mod+C"],cutSelectedClips:["Mod+X"],pasteClipboardClips:["Mod+V"],toggleSelectedClipsAudio:["Mod+Alt+A"],splitCurrentClip:["Mod+B"],undo:["Mod+Z"],redo:["Mod+Shift+Z","Ctrl+Y"]};function Xu(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function qu(s){const e=s.trim();if(!e)return null;const t=e.toLowerCase();return t==="space"||t==="spacebar"?"Space":t==="delete"?"Delete":t==="backspace"?"Backspace":/^[a-z]$/i.test(e)?`Key${e.toUpperCase()}`:/^key[a-z]$/i.test(e)?`Key${e.slice(-1).toUpperCase()}`:/^[0-9]$/.test(e)?`Digit${e}`:/^digit[0-9]$/i.test(e)?`Digit${e.slice(-1)}`:null}function ju(s,e,t){const i=e.split("+").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return null;let r=null,n=!1,a=!1,o=!1,l=!1;for(const c of i)switch(c.toLowerCase()){case"mod":t?o=!0:a=!0;break;case"alt":case"option":n=!0;break;case"ctrl":case"control":a=!0;break;case"cmd":case"command":case"meta":o=!0;break;case"shift":l=!0;break;default:{const h=qu(c);if(!h||r)return null;r=h}}return r?{action:s,code:r,altKey:n,ctrlKey:a,metaKey:o,shiftKey:l}:null}function Ku(s){if(!(s instanceof HTMLElement))return!1;if(s.isContentEditable)return!0;const e=s.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:!!s.closest('[contenteditable=""], [contenteditable="true"], input, textarea, select')}function Zu(s,e){return s.code===e.code&&s.altKey===e.altKey&&s.ctrlKey===e.ctrlKey&&s.metaKey===e.metaKey&&s.shiftKey===e.shiftKey}function Ju(s,e){return s===!1||(s==null?void 0:s.enabled)===!1?[]:Wu.flatMap(t=>{var n;const i=(n=s==null?void 0:s.bindings)==null?void 0:n[t];return(i===void 0?Yu[t]:Array.isArray(i)?i:[i]).map(a=>ju(t,a,e)).filter(a=>a!==null)})}class Qu{constructor(e){g(this,"callbacks");g(this,"bindings");g(this,"enabled");g(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??Xu();e.root,this.callbacks=e.callbacks,this.bindings=Ju(e.config,t),this.enabled=e.config!==!1&&((i=e.config)==null?void 0:i.enabled)!==!1&&this.bindings.length>0}init(){var e,t;this.enabled&&((t=(e=globalThis.window)==null?void 0:e.addEventListener)==null||t.call(e,"keydown",this.keydownListener))}destroy(){var e,t;(t=(e=globalThis.window)==null?void 0:e.removeEventListener)==null||t.call(e,"keydown",this.keydownListener)}handleKeydown(e){if(Ku(e.target))return;const t=this.bindings.find(i=>Zu(e,i));t&&(e.preventDefault(),e.stopPropagation(),this.dispatchAction(t.action))}dispatchAction(e){switch(e){case"togglePlay":this.callbacks.togglePlay();return;case"deleteSelectedClips":this.callbacks.canDeleteSelectedClips()&&this.callbacks.deleteSelectedClips();return;case"copySelectedClips":this.callbacks.canCopySelectedClips()&&this.callbacks.copySelectedClips();return;case"cutSelectedClips":this.callbacks.canCutSelectedClips()&&this.callbacks.cutSelectedClips();return;case"pasteClipboardClips":this.callbacks.canPasteClipboardClips()&&this.callbacks.pasteClipboardClips();return;case"toggleSelectedClipsAudio":this.callbacks.canToggleSelectedClipsAudio()&&this.callbacks.toggleSelectedClipsAudio();return;case"splitCurrentClip":this.callbacks.canSplitSelectedClip()&&this.callbacks.splitCurrentClip();return;case"undo":this.callbacks.undo();return;case"redo":this.callbacks.redo();return}}}function yo(s){var t;const e=s.getPrimarySelectedClip()||((t=s.findFallbackSelectedClip)==null?void 0:t.call(s))||null;return{clip:e,hasSelectedClip:!!e}}function ep(s){const e=yo(s),t=s.getSelectedClipIds(),i=s.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:s.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function tp(s){var i;const e=s.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===s.lastSelectedClipId?s.lastSelectedClipId:(s.emitSelectedClipChange(e),t)}class ip{constructor(e){g(this,"cleanupEmptyTracks",!1);g(this,"durationDirty",!1);g(this,"canPlayDirty",!1);g(this,"selectionDirty",!1);g(this,"trackLayoutDirty",!1);g(this,"trackInfoDirty",!1);g(this,"stageDirty",!1);g(this,"previewDirty",!1);g(this,"committed",!1);g(this,"events",[]);this.options=e}addClipToTrack(e,t){const i=this.options.addClipToTrack?this.options.addClipToTrack(e,t):this.options.trackCollection.addClipToTrack(e,t);return i&&this.markStructureMutation(),i}removeClip(e){this.options.removeClip?this.options.removeClip(e):this.options.trackCollection.removeClip(e),this.markStructureMutation()}removeClipFromTrack(e,t){const i=this.options.removeClipFromTrack?this.options.removeClipFromTrack(e,t):this.options.trackCollection.removeClipFromTrack(e,t);return i&&this.markStructureMutation(),i}updateClip(e,t){this.options.updateClip?this.options.updateClip(e,t):this.options.trackCollection.updateClip(e,t),this.markClipStateMutation()}moveClipToTrack(e,t){const i=this.findTrackByClipId(e),r=this.getClips().find(o=>o.id===e)??null,n=i?this.resolveTrackId(i):null;if(!r||!n)return!1;const a=this.options.moveClipToTrack?this.options.moveClipToTrack(r,n,t):this.options.trackCollection.moveClipToTrack(r,n,t);return a&&this.markStructureMutation(),a}ensureTrackFromHistorySnapshot(e,t){const i=this.options.ensureTrackFromHistorySnapshot(e,t);return i&&this.markTrackLayoutMutation(),i}removeClipGaps(){this.options.removeClipGaps(),this.markStructureMutation()}getClips(){return this.options.getClips?this.options.getClips():this.options.trackCollection.getAllClips()}findTrackByClipId(e){return this.options.findTrackByClipId?this.options.findTrackByClipId(e):this.options.trackCollection.findTrackByClipId(e)}getDefaultTrack(){return this.options.getDefaultTrack?this.options.getDefaultTrack():this.options.trackCollection.getDefaultTrack()}queueEvent(e,t){this.events.push({type:e,payload:t})}markStructureMutation(){this.cleanupEmptyTracks=!0,this.durationDirty=!0,this.canPlayDirty=!0,this.selectionDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}markClipStateMutation(){this.durationDirty=!0,this.canPlayDirty=!0,this.selectionDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}markTrackLayoutMutation(){this.trackLayoutDirty=!0,this.trackInfoDirty=!0,this.stageDirty=!0,this.previewDirty=!0}commit(){this.committed||(this.committed=!0,this.options.onCommit({cleanupEmptyTracks:this.cleanupEmptyTracks,durationDirty:this.durationDirty,canPlayDirty:this.canPlayDirty,selectionDirty:this.selectionDirty,trackLayoutDirty:this.trackLayoutDirty,trackInfoDirty:this.trackInfoDirty,stageDirty:this.stageDirty,previewDirty:this.previewDirty,events:[...this.events]}))}createHistoryExecutionTarget(){return{removeClip:e=>{this.removeClip(e)},addClipToTrack:(e,t)=>this.addClipToTrack(e,t),updateClip:(e,t)=>{this.updateClip(e,t)},moveClipToTrack:(e,t)=>this.moveClipToTrack(e,t),setPrimaryTrackMagnetEnabled:e=>{this.options.setPrimaryTrackMagnetEnabled(e)},ensureTrackFromHistorySnapshot:(e,t)=>this.ensureTrackFromHistorySnapshot(e,t),removeClipGaps:()=>{this.removeClipGaps()},getClips:()=>this.getClips(),findTrackByClipId:e=>{const t=this.findTrackByClipId(e);return t!=null&&t.addClip?t:null},getDefaultTrack:()=>{const e=this.getDefaultTrack();return e!=null&&e.addClip?e:null},loadClipThumbnails:this.options.loadClipThumbnails,withClipRemovalBatch:e=>e()}}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}function rp(s,e){var t,i,r,n;return((i=(t=s.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((n=(r=s.getLastTrack())==null?void 0:r.getId)==null?void 0:n.call(r))||e}function np(s){if(s.placement.status==="use_existing_track")return s.trackCollection.addClipToTrack(s.placement.trackId,s.clip);const e=s.createTrack(s.placement.trackType,s.placement.suggestedTrackName,s.placement.insertionPlacement),t=rp(s.trackCollection,e);return t?s.trackCollection.addClipToTrack(t,s.clip):!1}function $s(s,e,t){return e.trackId?s.removeClipFromTrack(e.trackId,t):!1}function sp(s){return s.trackCollection.moveClipToTrack(s.command.clip,s.command.sourceTrackId,s.command.targetTrackId)}function Fi(s){var e,t,i,r,n;(e=s.checkTrackDurationChange)==null||e.call(s),(t=s.updateCanPlayState)==null||t.call(s),(i=s.updateTrackInfoPanel)==null||i.call(s),(r=s.handleClipChange)==null||r.call(s),(n=s.cleanupEmptyTracks)==null||n.call(s)}class So{constructor(){g(this,"panel",null);g(this,"config",null);g(this,"currentSelectionState",this.buildSelectionState(null,[]));g(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new uo({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,this.resolveUpdateTargets(i,r).forEach(a=>{e.updateClip(a.id,r)}),setTimeout(()=>{this.isInternalUpdate=!1},0)},onGenerateVoice:e.onGenerateVoice})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip(),t=this.config.getSelectedClips();this.currentSelectionState=this.buildSelectionState(e,t),this.panel.setSelectionState(this.currentSelectionState)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}setPreferredTab(e){var t;(t=this.panel)==null||t.setPreferredTab(e)}showVoiceGenerationLoading(){var e;(e=this.panel)==null||e.showVoiceGenerationLoading()}hideVoiceGenerationLoading(){var e;(e=this.panel)==null||e.hideVoiceGenerationLoading()}setVoiceGenerationBusy(e){var t;(t=this.panel)==null||t.setVoiceGenerationBusy(e)}buildSelectionState(e,t){const i=t.length>0?t:e?[e]:[],r=e??i[0]??null;if(!r||i.length===0)return{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1};const a=new Set(i.map(c=>c.type)).size>1?"mixed":r.type,o=i.length>1,l=a==="audio"&&i.every(c=>Le(c));return{primaryClip:r,selectedClips:i,selectionCount:i.length,groupKind:a,supportsVoiceBatch:a==="text"||l,supportsTextContentBatch:a==="text"&&!o,supportsVisualBatch:a==="video",supportsVolumeBatch:a==="video"||a==="audio"}}resolveUpdateTargets(e,t){const{primaryClip:i,selectedClips:r,groupKind:n,supportsVoiceBatch:a}=this.currentSelectionState,o=r.find(l=>l.id===e)??i;return o?Object.prototype.hasOwnProperty.call(t,"textContent")?[o]:Object.prototype.hasOwnProperty.call(t,"ttsFollowTextUpdates")?a&&n==="audio"?r.filter(l=>Le(l)):[o]:Object.prototype.hasOwnProperty.call(t,"textStyle")?n==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"visualTransform")?n==="video"||n==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"volume")?n==="video"||n==="audio"?r:[o]:[o]:[]}convertTheme(e){return{backgroundColor:ye.backgroundColor,borderColor:e.border||ye.borderColor,textColor:e.clipName||ye.textColor,labelColor:e.timeText||ye.labelColor,inputBackground:e.trackBackground||ye.inputBackground,inputBorder:e.trackBorder||ye.inputBorder,inputFocusBorder:ye.inputFocusBorder,buttonBackground:e.clipBackground||ye.buttonBackground,buttonBorder:e.clipBorder||ye.buttonBorder,buttonActiveBackground:ye.buttonActiveBackground,buttonActiveBorder:e.clipSelectedBorder||ye.buttonActiveBorder,buttonActiveText:ye.buttonActiveText}}}class ap{constructor(){g(this,"panel",null)}init(e){var i,r,n,a;const t=((i=e.theme)==null?void 0:i.background)||ke.background;this.panel=new ho({container:e.container,theme:{background:t,border:((r=e.theme)==null?void 0:r.border)||ke.border,text:((n=e.theme)==null?void 0:n.clipName)||ke.text,buttonBackground:((a=e.theme)==null?void 0:a.clipBackground)||ke.buttonBackground,buttonHover:ke.buttonHover,buttonDanger:ke.buttonDanger},width:vi,timeScaleHeight:e.timeScaleHeight||40,includeTimeScaleSpacer:e.includeTimeScaleSpacer},e.onRenameTrack,e.onRemoveTrack,e.onMuteTrack)}hasPanel(){return!!this.panel}update(e){var t;(t=this.panel)==null||t.setTracks(e)}setScrollTop(e){var t;(t=this.panel)==null||t.setScrollTop(e)}destroy(){var e;(e=this.panel)==null||e.destroy(),this.panel=null}}class Vs{syncCurrentTime(e,t,i,r){e==null||e.setCurrentTime(r),t==null||t.setCurrentTime(r)}syncZoom(e,t,i,r){e==null||e.setZoom(r),t==null||t.setZoom(r),i.syncZoom(r)}syncScrollLeft(e,t,i){e==null||e.setScrollLeft(i),t.syncScrollLeft(i)}syncScrollTop(e,t,i){e==null||e.setScrollTop(i),t==null||t.setScrollTop(i)}syncSelection(e,t){e.syncSelection(t,t[0]??null)}findSelectedClip(e){return e.findPrimarySelectedClip()}}const op=100*1024*1024,lp=10*1024*1024*1024,cp=30*24*60*60*1e3,hp=["video/mp4","audio/aac","audio/mpeg","audio/mp4","audio/mp3","audio/ogg","audio/wav","audio/x-wav"],li={enabled:!1,maxEntryBytes:op,maxTotalBytes:lp,ttlMs:cp,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:hp},dp="timeline-preview-resource-cache",up=1,Se="metadata";function pp(){return new Promise((s,e)=>{const t=indexedDB.open(dp,up);t.onupgradeneeded=()=>{const i=t.result,r=i.objectStoreNames.contains(Se)?t.transaction.objectStore(Se):i.createObjectStore(Se,{keyPath:"cacheKey"});r.indexNames.contains("sourceUrl")||r.createIndex("sourceUrl","sourceUrl"),r.indexNames.contains("expiresAt")||r.createIndex("expiresAt","expiresAt"),r.indexNames.contains("lastAccessedAt")||r.createIndex("lastAccessedAt","lastAccessedAt"),r.indexNames.contains("storageKind")||r.createIndex("storageKind","storageKind")},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function Dr(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class gp{constructor(){g(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=pp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async get(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(Se,"readonly").objectStore(Se).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async put(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).put(e),await Dr(i)}async delete(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).delete(e),await Dr(i)}async clear(){const t=(await this.getDb()).transaction(Se,"readwrite");t.objectStore(Se).clear(),await Dr(t)}async list(){const e=await this.getDb();return new Promise((t,i)=>{const r=e.transaction(Se,"readonly").objectStore(Se).getAll();r.onerror=()=>i(r.error),r.onsuccess=()=>t(r.result)})}}const fp="timeline-preview-resource-cache",mp="timeline-preview-resource-cache-blobs",yp=1,Re="blobs";function Sp(){return new Promise((s,e)=>{const t=indexedDB.open(mp,yp);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Re)||i.createObjectStore(Re)},t.onerror=()=>e(t.error),t.onsuccess=()=>s(t.result)})}function Lr(s){return new Promise((e,t)=>{s.oncomplete=()=>e(),s.onerror=()=>t(s.error),s.onabort=()=>t(s.error)})}class vp{constructor(){g(this,"kind","indexeddb");g(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=Sp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async read(e){const t=await this.getDb();return new Promise((i,r)=>{const n=t.transaction(Re,"readonly").objectStore(Re).get(e);n.onerror=()=>r(n.error),n.onsuccess=()=>i(n.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Re,"readwrite");r.objectStore(Re).put(t,e),await Lr(r)}async delete(e){const i=(await this.getDb()).transaction(Re,"readwrite");i.objectStore(Re).delete(e),await Lr(i)}async clear(){const t=(await this.getDb()).transaction(Re,"readwrite");t.objectStore(Re).clear(),await Lr(t)}}class Cp{constructor(){g(this,"kind","opfs");g(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(fp,{create:!0})).catch(e=>{throw this.directoryPromise=null,e})),this.directoryPromise}async ensureReady(){try{return await this.getDirectory(),!0}catch{return!1}}async read(e){try{return await(await(await this.getDirectory()).getFileHandle(e)).getFile()}catch{return null}}async write(e,t){const n=await(await(await this.getDirectory()).getFileHandle(e,{create:!0})).createWritable();try{await n.write(t),await n.close()}catch(a){try{typeof n.abort=="function"&&await n.abort()}catch{}throw a}}async delete(e){const t=await this.getDirectory();try{await t.removeEntry(e)}catch{}}async clear(){const e=await this.getDirectory();for await(const[t]of e)await e.removeEntry(t)}}async function Tp(s){var e;if(s.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new Cp;if(await t.ensureReady())return t}return new vp}function bp(s){return Array.from(s).map(e=>e.toString(16).padStart(2,"0")).join("")}function Us(s){return s.split(";",1)[0].trim().toLowerCase()}async function kp(s){const e=globalThis.crypto;if(!(e!=null&&e.subtle))throw new Error("Resource cache key generation requires Web Crypto SHA-256 support.");const t=await e.subtle.digest("SHA-256",new TextEncoder().encode(s));return bp(new Uint8Array(t))}function Br(s){return s?[...s]:[...li.allowedMimeTypes]}function wp(s){return s?s===!0?{...li,enabled:!0,allowedMimeTypes:Br(void 0)}:{...li,...s,enabled:s.enabled??!0,allowedMimeTypes:Br(s.allowedMimeTypes)}:{...li,allowedMimeTypes:Br(void 0)}}function Pp(s){try{const e=new URL(s);return e.hash="",e.toString()}catch{return s.trim()}}async function xp(s){var t;const e=((t=s.sourceKey)==null?void 0:t.trim())||Pp(s.url);return kp(e)}function Ws(s,e=li.allowedMimeTypes){if(!s.url)return!0;let t;try{t=new URL(s.url)}catch{return!0}if(t.protocol!=="http:"&&t.protocol!=="https:"||s.kind==="hls-fmp4"||/\.m3u8(?:$|\?|#)/i.test(t.pathname))return!0;if(!s.mimeType)return!1;const i=Us(s.mimeType);return!e.some(r=>Us(r)===i)}function _p(s){return s&&s.split(";",1)[0].trim().toLowerCase()||null}function Ys(s){if(!s)return null;const e=Number(s);return Number.isSafeInteger(e)&&e>=0?e:null}function Ap(s){if(!s)return null;const e=s.match(/^bytes\s+(?:\d+-\d+|\*)\/(\d+|\*)$/i);if(!e||e[1]==="*")return null;const t=Number(e[1]);return Number.isSafeInteger(t)&&t>=0?t:null}function Xs(s,e,t){return{url:e,ok:s.ok,status:s.status,mimeType:_p(s.headers.get("content-type")),sizeBytes:t,etag:s.headers.get("etag"),lastModified:s.headers.get("last-modified"),acceptRanges:s.headers.get("accept-ranges")}}class Ip{async probe(e){var r;try{const n=await fetch(e,{method:"HEAD"}),a=Ys(n.headers.get("content-length"));if(n.ok&&a!==null)return Xs(n,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=Ap(t.headers.get("content-range"))??Ys(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return Xs(t,e,i)}async download(e){const t=await fetch(e);if(!t.ok)throw new Error(`Resource cache download failed with HTTP ${t.status}.`);return t.blob()}}const Ep={createObjectURL(s){return URL.createObjectURL(s)},revokeObjectURL(s){URL.revokeObjectURL(s)}};function Tt(s,e){return{url:s.url,cacheStatus:e,sourceUrl:s.url}}function Rp(s,e){return s.etag||e.etag?s.etag===e.etag&&s.sizeBytes===e.contentLength:s.sizeBytes===e.contentLength&&s.lastModified===e.lastModified}class Mp{constructor(e={}){g(this,"options");g(this,"metadataStore");g(this,"storagePromise");g(this,"http");g(this,"objectUrl");g(this,"now");g(this,"cacheKeyBuilder");g(this,"onEvent");g(this,"objectUrls",new Set);g(this,"inflightDownloads",new Map);this.options=wp(e.options),this.metadataStore=e.metadataStore??new gp,this.storagePromise=e.storage?Promise.resolve(e.storage):Tp({preferStorage:this.options.preferStorage}),this.http=e.http??new Ip,this.objectUrl=e.objectUrl??Ep,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??xp,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Ws(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),Tt(e,"bypass");try{const t=await this.cacheKeyBuilder(e),i=await this.storagePromise,r=await this.metadataStore.get(t);if(r){const l=await i.read(t);if(l){if(r.expiresAt>this.now()){const c={...r,lastAccessedAt:this.now()};return await this.metadataStore.put(c),this.emitEvent("resource-cache.hit",{sourceUrl:e.url,sizeBytes:c.sizeBytes}),this.blobResult(e.url,l,c,"hit")}return await this.resolveExpired(e,t,r,l,i)}await this.metadataStore.delete(t)}if(this.options.resolveMode==="prefer-fast-start")return this.probeAndDownload(t,e,i).catch(()=>{}),this.emitEvent("resource-cache.miss",{sourceUrl:e.url}),Tt(e,"miss");const n=await this.probeCacheable(e);if(n.cacheStatus!=="miss")return n.result;const{blob:a,metadata:o}=await this.getOrCreateDownload(t,e,n.probe,i);return this.emitEvent("resource-cache.miss",{sourceUrl:e.url,sizeBytes:o.sizeBytes}),this.blobResult(e.url,a,o,"miss")}catch{return this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),Tt(e,"fallback")}}revokeObjectUrl(e){this.objectUrls.delete(e)&&this.objectUrl.revokeObjectURL(e)}async cleanupExpired(){const e=await this.storagePromise,t=this.now(),i=await this.metadataStore.list();await Promise.all(i.filter(r=>r.expiresAt<=t).map(r=>this.deleteEntry(r.cacheKey,e)))}async clear(){const e=await this.storagePromise;await Promise.all([e.clear(),this.metadataStore.clear()]);for(const t of[...this.objectUrls])this.revokeObjectUrl(t)}async getStats(){const e=await this.metadataStore.list();return{entryCount:e.length,totalBytes:e.reduce((t,i)=>t+i.sizeBytes,0),maxTotalBytes:this.options.maxTotalBytes}}async resolveExpired(e,t,i,r,n){const a=await this.probeCacheable(e);if(a.cacheStatus!=="miss")return a.result;if(Rp(a.probe,i)){const c=this.now(),h={...i,updatedAt:c,lastAccessedAt:c,expiresAt:c+this.options.ttlMs};return await this.metadataStore.put(h),this.emitEvent("resource-cache.revalidate.success",{sourceUrl:e.url,sizeBytes:h.sizeBytes}),this.blobResult(e.url,r,h,"stale-revalidated")}this.emitEvent("resource-cache.revalidate.stale",{sourceUrl:e.url}),await this.deleteEntry(t,n);const{blob:o,metadata:l}=await this.getOrCreateDownload(t,e,a.probe,n);return this.blobResult(e.url,o,l,"miss")}async probeCacheable(e){const t=await this.http.probe(e.url);return t.ok?t.sizeBytes===null?(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:Tt(e,"fallback")}):Ws({...e,mimeType:e.mimeType??t.mimeType},this.options.allowedMimeTypes)||t.sizeBytes>this.options.maxEntryBytes||t.sizeBytes>this.options.maxTotalBytes?(this.emitEvent("resource-cache.bypass",{sourceUrl:e.url,sizeBytes:t.sizeBytes,mimeType:t.mimeType}),{cacheStatus:"bypass",result:Tt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:Tt(e,"fallback")})}async probeAndDownload(e,t,i){const r=await this.probeCacheable(t);r.cacheStatus==="miss"&&await this.getOrCreateDownload(e,t,r.probe,i)}getOrCreateDownload(e,t,i,r){const n=this.inflightDownloads.get(e);if(n)return n;const a=this.downloadAndStore(e,t,i,r).finally(()=>{this.inflightDownloads.delete(e)});return this.inflightDownloads.set(e,a),a}async downloadAndStore(e,t,i,r){this.emitEvent("resource-cache.download.start",{sourceUrl:t.url});try{const n=await this.http.download(t.url),a=n.size;if(a>this.options.maxEntryBytes||a>this.options.maxTotalBytes)throw new Error("Resource exceeds cache capacity.");await this.evictForWrite(e,a,r),await r.write(e,n);const o=this.now(),l={cacheKey:e,sourceUrl:t.url,mimeType:i.mimeType??t.mimeType??null,sizeBytes:a,etag:i.etag,lastModified:i.lastModified,contentLength:a,storageKind:r.kind,createdAt:o,updatedAt:o,lastAccessedAt:o,expiresAt:o+this.options.ttlMs};return await this.metadataStore.put(l),this.emitEvent("resource-cache.download.success",{sourceUrl:t.url,sizeBytes:a}),{blob:n,metadata:l}}catch(n){throw this.emitEvent("resource-cache.download.failed",{sourceUrl:t.url,error:n instanceof Error?n.message:String(n)}),n}}async evictForWrite(e,t,i){const r=(await this.metadataStore.list()).filter(a=>a.cacheKey!==e);let n=r.reduce((a,o)=>a+o.sizeBytes,0);for(const a of r.sort((o,l)=>o.lastAccessedAt-l.lastAccessedAt)){if(n+t<=this.options.maxTotalBytes)return;await this.deleteEntry(a.cacheKey,i),n-=a.sizeBytes}}async deleteEntry(e,t){await Promise.all([t.delete(e),this.metadataStore.delete(e)]),this.emitEvent("resource-cache.cleanup.deleted",{cacheKey:e})}blobResult(e,t,i,r){const n=this.objectUrl.createObjectURL(t);return this.objectUrls.add(n),{url:n,cacheStatus:r,sourceUrl:e,sizeBytes:i.sizeBytes,objectUrl:n}}emitEvent(e,t){var i;(i=this.onEvent)==null||i.call(this,e,t)}}function Dp(s){return!!s&&typeof s.then=="function"}class Or{constructor(){g(this,"durationCache",new Map);g(this,"thumbnailCache",new Map);g(this,"previewSourceCache",new Map)}static buildSourceKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src||""}static buildThumbnailKey(e){return[this.buildSourceKey(e),e.type,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}getDuration(e,t,i={}){const r=this.durationCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(typeof(r==null?void 0:r.value)=="number")return Promise.resolve(r.value)}const n=t().then(a=>(this.durationCache.set(e,{value:a,promise:null}),a)).catch(a=>{throw this.durationCache.delete(e),a});return this.durationCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeDuration(e,t){this.durationCache.set(e,{value:t,promise:null})}getThumbnails(e,t,i={}){const r=this.thumbnailCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.value)return Promise.resolve(r.value)}const n=t().then(a=>(this.thumbnailCache.set(e,{value:a,promise:null}),a)).catch(a=>{throw this.thumbnailCache.delete(e),a});return this.thumbnailCache.set(e,{value:(r==null?void 0:r.value)??null,promise:n}),n}primeThumbnails(e,t){this.thumbnailCache.set(e,{value:t,promise:null})}clearThumbnailCache(){this.thumbnailCache.clear()}getPreviewSource(e,t,i={}){const r=this.previewSourceCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(r!=null&&r.resolved)return r.value}const n=t();if(!Dp(n))return this.previewSourceCache.set(e,{value:n,promise:null,resolved:!0}),n;const a=n.then(o=>(this.previewSourceCache.set(e,{value:o,promise:null,resolved:!0}),o)).catch(o=>{throw this.previewSourceCache.delete(e),o});return this.previewSourceCache.set(e,{value:(r==null?void 0:r.value)??null,promise:a,resolved:!1}),a}primePreviewSource(e,t){this.previewSourceCache.set(e,{value:t,promise:null,resolved:!0})}}class qs{constructor(e,t=ir){this.handlers=e,this.TrackCtor=t}createTrack(e){return new this.TrackCtor(e.layer,e.config,e.trackType,e.zoom,e.trackY,e.trackHeight,e.theme,this.handlers.onClipUpdate,this.handlers.onClipAdd,this.handlers.onClipRemove,this.handlers.onClipSplit,this.handlers.onClipSelect,this.handlers.onTimeJump,this.handlers.onHorizontalDragAutoScroll,this.handlers.onClipOverlap,this.handlers.onPrimaryTrackMagnetMove,this.handlers.onClipCrossTrackPreview,this.handlers.onClipCrossTrack,this.handlers.onClearDropPreview,this.handlers.onClearSelection,this.handlers.onSnapGuideChange,this.handlers.onClipToggleSelection,this.handlers.onSetSingleSelection,this.handlers.getMultiDragClipIds,this.handlers.onMultiDragMove,this.handlers.onMultiDragInteractionEnd,e.dragActivationThreshold,e.enableClipSnap,e.clipSnapThreshold)}}class Lp{constructor(e){this.tracks=e}getAll(){return this.tracks}getDefaultTrack(){return this.tracks[0]||null}getPrimaryTrack(){return this.tracks.find(e=>{var t;return((t=e.getRole)==null?void 0:t.call(e))==="primary"})||this.getDefaultTrack()}getLastTrack(){return this.tracks.length>0?this.tracks[this.tracks.length-1]:null}add(e){this.tracks.push(e)}findById(e){return this.tracks.find(t=>this.resolveTrackId(t)===e)||null}removeById(e){const t=this.findIndexById(e);if(t===-1)return null;const[i]=this.tracks.splice(t,1);return i||null}removeEmptyNonPrimaryTracks(){var t;const e=[];for(let i=this.tracks.length-1;i>=0;i-=1){const r=this.tracks[i];if(((t=r.getRole)==null?void 0:t.call(r))==="primary"||(typeof r.getClips=="function"?r.getClips():[]).length>0)continue;const[a]=this.tracks.splice(i,1);a&&e.push(a)}return e.reverse()}findTrackByClipId(e){return this.tracks.find(t=>t.getClips().some(i=>i.id===e))||null}getAllClips(){return this.tracks.flatMap(e=>e.getClips())}syncCurrentTime(e){this.tracks.forEach(t=>{var i;return(i=t.setCurrentTime)==null?void 0:i.call(t,e)})}syncZoom(e){this.tracks.forEach(t=>{var i;return(i=t.setZoom)==null?void 0:i.call(t,e)})}syncScrollLeft(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollLeft)==null?void 0:i.call(t,e)})}syncScrollTop(e){this.tracks.forEach(t=>{var i;return(i=t.setScrollTop)==null?void 0:i.call(t,e)})}updateClip(e,t){this.tracks.forEach(i=>{var r;return(r=i.updateClip)==null?void 0:r.call(i,e,t)})}removeClip(e){this.tracks.forEach(t=>{var i;return(i=t.removeClip)==null?void 0:i.call(t,e)})}addClipToTrack(e,t){const i=this.findById(e);return i!=null&&i.addClip?(i.addClip(t),!0):!1}removeClipFromTrack(e,t){const i=this.findById(e);return i!=null&&i.removeClip?(i.removeClip(t),!0):!1}moveClipToTrack(e,t,i){if(t===i)return!0;const r=this.findById(t),n=this.findById(i);return!(r!=null&&r.removeClip)||!(n!=null&&n.addClip)?!1:(r.removeClip(e.id),n.addClip(e),!0)}removeClipGaps(){this.tracks.forEach(e=>{var t;return(t=e.removeClipGaps)==null?void 0:t.call(e)})}clearSelection(){this.tracks.forEach(e=>{var t;return(t=e.clearSelection)==null?void 0:t.call(e)})}syncSelection(e,t=e[0]??null){this.tracks.forEach(i=>{var r;(r=i.setSelection)==null||r.call(i,e,t)})}findPrimarySelectedClip(){var e;for(const t of this.tracks){const i=(e=t.getPrimarySelectedClip)==null?void 0:e.call(t);if(i)return i}return null}forEach(e){this.tracks.forEach(e)}findIndexById(e){return this.tracks.findIndex(t=>this.resolveTrackId(t)===e)}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}}function Bp(s){return s==="text"?"文本":s==="video"?"视频":"音频"}function Ni(s){return s==="text"?0:s==="video"?1:2}class vo{constructor(e=[]){g(this,"tracks",[]);g(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,r,n,a){this.trackCounter++;const o=t||`${Bp(e)}轨道 ${this.trackCounter}`,l=n??(this.tracks.length===0?"primary":"normal");l==="primary"&&this.tracks.forEach(h=>{h.role==="primary"&&(h.role="normal")});const c={id:a||`track_${Date.now()}_${this.trackCounter}`,type:e,name:o,order:this.tracks.length,role:l,clips:[]};return this.insertTrack(c,i,r),O.debugLazy("TrackManager",()=>`创建轨道: ${o}`,()=>({trackId:c.id,type:e,order:c.order})),c}removeTrack(e){var i;const t=this.tracks.findIndex(r=>r.id===e);return t===-1?(O.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(O.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),O.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,O.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(O.warn("TrackManager",`轨道不存在: ${e}`),!1)}getTracks(){return[...this.tracks]}getTrack(e){return this.tracks.find(t=>t.id===e)}getTracksByType(e){return this.tracks.filter(t=>t.type===e)}updateTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(Object.assign(i,t),O.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(O.warn("TrackManager",`轨道不存在: ${e}`),!1)}recalculateOrder(){this.tracks.forEach((e,t)=>{e.order=t})}insertTrack(e,t,i){const r=this.tracks.findIndex(a=>a.role==="primary"),n=t??(e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary");if(r===-1||e.role==="primary"){this.tracks.push(e),this.recalculateOrder();return}if((n==="before_track"||n==="after_track")&&i){const a=this.tracks.findIndex(o=>o.id===i);if(a!==-1){this.tracks.splice(a+(n==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(n==="top_of_type_region"){const a=this.tracks.findIndex(l=>l.type===e.type);if(a!==-1){this.tracks.splice(a,0,e),this.recalculateOrder();return}const o=this.tracks.findIndex(l=>Ni(l.type)>Ni(e.type));if(o!==-1){this.tracks.splice(o,0,e),this.recalculateOrder();return}}if(n==="bottom_of_type_region"){const a=this.tracks.reduce((l,c,h)=>c.type===e.type?h:l,-1);if(a!==-1){this.tracks.splice(a+1,0,e),this.recalculateOrder();return}const o=this.tracks.reduce((l,c,h)=>Ni(c.type)<=Ni(e.type)?h:l,-1);if(o!==-1){this.tracks.splice(o+1,0,e),this.recalculateOrder();return}}n==="before_primary"?this.tracks.splice(r,0,e):this.tracks.splice(r+1,0,e),this.recalculateOrder()}muteTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.isMuted=t,O.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(O.warn("TrackManager",`轨道不存在:${e}`),!1)}isTrackMuted(e){const t=this.tracks.find(i=>i.id===e);return(t==null?void 0:t.isMuted)??!1}clearAllTracks(){this.tracks=[],this.trackCounter=0,O.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}class Op{constructor(e){g(this,"currentTime");g(this,"playState");g(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class Co{constructor(){g(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class Fp{constructor(e){g(this,"zoom");g(this,"duration");g(this,"scrollLeft");g(this,"scrollTop");g(this,"viewportWidth");g(this,"viewportHeight");g(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class js{constructor(e){g(this,"selectionStore");g(this,"playbackStore");g(this,"viewportStore");this.selectionStore=new Co,this.playbackStore=new Op({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new Fp({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 Np{constructor(e,t,i,r,n){g(this,"stage");g(this,"layer");g(this,"onTimeChange");g(this,"onScrollChange");g(this,"config");g(this,"theme");g(this,"scrollLeft",0);g(this,"timeScaleHeight",40);g(this,"isDragging",!1);g(this,"dragStartX",0);g(this,"isPointerInsideTimeline",!1);g(this,"lastPointerXInTimeline",null);g(this,"hasBoundGlobalPointerListenersForDrag",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=r,this.onScrollChange=n,this.config={duration:i.duration||Qt,zoom:i.zoom||Me.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:qi(i.theme),timeScaleHeight:i.timeScaleHeight},this.theme=this.config.theme,this.timeScaleHeight=i.timeScaleHeight||40,this.initEventListeners(),this.render()}setCurrentTime(e){}setZoom(e){this.config.zoom=e,this.render()}setDuration(e){this.config.duration=e,this.render()}setScrollLeft(e){this.scrollLeft=this.clampScrollLeft(e),this.render()}getScrollLeft(){return this.scrollLeft}scrollToTime(e){const t=U.timeToPixels(e,this.config.zoom),i=this.stage.width();this.setScrollLeft(Math.max(0,t-i/2))}scrollToClip(e){const t=U.timeToPixels(e.startTime,this.config.zoom),r=U.timeToPixels(e.startTime+e.duration,this.config.zoom)-t,n=this.stage.width(),a=r<=n?Math.max(0,t-(n-r)/2):Math.max(0,t);this.setScrollLeft(a)}resize(e){this.stage.width(e),this.render()}hasPointerInTimeline(){return this.isPointerInsideTimeline}getPointerXInTimeline(){return this.lastPointerXInTimeline}destroy(){this.unbindGlobalPointerListenersForDrag(),this.stage.destroy()}initEventListeners(){this.stage.on("click",e=>{e.target.getLayer()===this.layer&&this.onTimeChange(this.pixelToTime(e.evt.offsetX),"seek")}),this.stage.on("mousedown",e=>{e.target.getLayer()===this.layer&&(this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging=!0,this.dragStartX=e.evt.clientX,this.bindGlobalPointerListenersForDrag())}),this.stage.on("mousemove",e=>{this.updatePointerPosition(e.evt.offsetX),this.isPointerInsideTimeline=!0,this.isDragging&&!this.hasBoundGlobalPointerListenersForDrag&&this.handlePointerMove(e.evt)}),this.stage.on("mouseup",()=>{this.handleGlobalPointerEnd()}),this.stage.on("mouseleave",()=>{this.isPointerInsideTimeline=!1})}updatePointerPosition(e){if(!Number.isFinite(e))return;const t=this.stage.width();this.lastPointerXInTimeline=Math.max(0,Math.min(t,e))}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListenersForDrag=!1)}handlePointerMove(e){const t=e.clientX-this.dragStartX,i=this.clampScrollLeft(this.scrollLeft-t),r=this.scrollLeft;this.dragStartX=e.clientX,this.scrollLeft=i,this.render(),r!==this.scrollLeft&&this.onScrollChange(this.scrollLeft)}pixelToTime(e){return U.pixelsToTime(e-pe+this.scrollLeft,this.config.zoom)}timeToPixel(e){return U.timeToPixels(e,this.config.zoom)-this.scrollLeft+pe}render(){const e=this.stage.width(),t=this.stage.height(),i=this.layer.findOne(".timeline-header-background");if(i)i.width(e),i.height(t),i.fill(this.theme.background),i.stroke(this.theme.border);else{const r=de.createRect(0,0,e,t,this.theme.background,this.theme.border,1);r.name("timeline-header-background"),this.layer.add(r)}this.layer.find(".time-tick-line").forEach(r=>r.remove()),this.layer.find(".time-tick-text").forEach(r=>r.remove()),this.renderTimeTicks(),this.layer.batchDraw()}renderTimeTicks(){const e=this.stage.width(),t=this.scrollLeft,i=this.scrollLeft+e,r=U.pixelsToTime(t,this.config.zoom),n=U.pixelsToTime(i,this.config.zoom),a=U.msToSeconds(r),o=U.msToSeconds(n),{majorStep:l,minorStep:c}=U.getTickConfig(this.config.zoom),h=U.generateVisibleTicks(a-10,o+10,l,c);for(const d of h){const u=this.timeToPixel(d.time);u>=-20&&u<=e+20&&de.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,U.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const q=class q{constructor(e,t,i,r,n,a,o){g(this,"container");g(this,"visualElement");g(this,"lineHitAreaElement");g(this,"theme");g(this,"onTimeChange");g(this,"onHorizontalAutoScroll");g(this,"currentTime");g(this,"zoom");g(this,"scrollLeft",0);g(this,"height");g(this,"isDragging",!1);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"edgeAutoScrollAnimationFrameId",null);g(this,"lastPointerClientX",null);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});g(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});g(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const r=this.scrollLeft,n=this.onHorizontalAutoScroll(this.scrollLeft+i),a=typeof n=="number"?n:this.scrollLeft;if(this.scrollLeft=Math.max(0,a),this.updateTimeFromClientX(this.lastPointerClientX),Math.abs(this.scrollLeft-r)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.container=e,this.currentTime=t,this.zoom=i,this.height=r,this.theme=n,this.onTimeChange=a,this.onHorizontalAutoScroll=o,this.container.innerHTML="",this.container.style.position="absolute",this.container.style.pointerEvents="none",this.container.style.overflow="visible",this.visualElement=document.createElementNS(q.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${q.VISUAL_WIDTH}`),this.visualElement.style.position="absolute",this.visualElement.style.top="0",this.visualElement.style.marginLeft=`${-14/2}px`,this.visualElement.style.pointerEvents="none",this.visualElement.style.overflow="visible",this.lineHitAreaElement=document.createElement("div"),this.lineHitAreaElement.className="timeline-manager-playhead-hit-area",this.lineHitAreaElement.style.position="absolute",this.lineHitAreaElement.style.top="0",this.lineHitAreaElement.style.width=`${q.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,r=U.pixelsToTime(i-pe+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,r),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(q.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=q.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const n=(i-e)/i;return-Math.max(1,Math.round(n*r))}if(e>t-i){const n=(e-(t-i))/i;return Math.max(1,Math.round(n*r))}return 0}startEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null||typeof requestAnimationFrame!="function"||(this.edgeAutoScrollAnimationFrameId=requestAnimationFrame(this.handleEdgeAutoScrollFrame))}stopEdgeAutoScroll(){this.edgeAutoScrollAnimationFrameId!==null&&(typeof cancelAnimationFrame=="function"&&cancelAnimationFrame(this.edgeAutoScrollAnimationFrameId),this.edgeAutoScrollAnimationFrameId=null)}render(){const e=U.timeToPixels(this.currentTime,this.zoom)-this.scrollLeft+pe,t=e>=0&&e<=this.container.clientWidth,i=Math.max(q.HANDLE_HEIGHT+q.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${q.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=Pn.grip,i=Math.max(q.HANDLE_HEIGHT,e-q.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i))}createHandleShadowPath(){const e=document.createElementNS(q.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill",Pn.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(q.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(q.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(q.VISUAL_WIDTH-q.LINE_WIDTH)/2}`),t.setAttribute("y",`${q.HANDLE_LINE_START}`),t.setAttribute("width",`${q.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-q.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e){const t=document.createElementNS(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-end-cap"),t.setAttribute("x","3"),t.setAttribute("y",`${e}`),t.setAttribute("width",`${q.END_CAP_WIDTH}`),t.setAttribute("height",`${q.END_CAP_HEIGHT}`),t.setAttribute("rx","1.5"),t.setAttribute("fill","#ffffff"),t}};g(q,"SVG_NS","http://www.w3.org/2000/svg"),g(q,"VISUAL_WIDTH",14),g(q,"HANDLE_HEIGHT",16),g(q,"HANDLE_LINE_START",13),g(q,"LINE_WIDTH",1),g(q,"LINE_HIT_WIDTH",12),g(q,"END_CAP_WIDTH",8),g(q,"END_CAP_HEIGHT",1),g(q,"AUTO_SCROLL_EDGE_THRESHOLD",48),g(q,"AUTO_SCROLL_MAX_SPEED",18);let cn=q;class Ks{constructor(e){g(this,"container");g(this,"orientation");g(this,"theme");g(this,"onScrollChange");g(this,"leadingInset");g(this,"trailingInset");g(this,"stage");g(this,"layer");g(this,"hitAreaRect");g(this,"thumbRect");g(this,"viewportSize",0);g(this,"contentSize",0);g(this,"scrollOffset",0);g(this,"isDragging",!1);g(this,"dragStartClient",0);g(this,"dragStartOffset",0);g(this,"hasBoundGlobalPointerListeners",!1);g(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});g(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});g(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});g(this,"handleStageMouseDown",e=>{var r;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((r=e.target)==null?void 0:r.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});g(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});g(this,"handleStageMouseEnter",()=>{this.updateCursor()});g(this,"handleStageMouseMove",()=>{this.updateCursor()});g(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new Z.Stage({container:this.container,width:this.container.clientWidth,height:this.container.clientHeight}),this.layer=new Z.Layer,this.layer.name("scrollbar-layer"),this.stage.add(this.layer),this.hitAreaRect=de.createRect(0,0,0,0,Lt.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||Lt.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Lt.border,1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}handleDragMove(e){const i=(this.orientation==="horizontal"?e.clientX:e.clientY)-this.dragStartClient,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),a=Math.max(1,r-n),o=this.getMaxScrollOffset(),l=this.dragStartOffset+i/a*o;this.emitScrollChange(l)}jumpToPointer(e){const t=this.stage.container().getBoundingClientRect(),i=this.orientation==="horizontal"?e-t.left:e-t.top,r=this.getAvailableTrackSize(),n=this.getThumbSize(r),a=Math.max(1,r-n),o=Math.max(0,Math.min(r,i-this.leadingInset)),l=Math.max(0,Math.min(a,o-n/2)),c=this.getMaxScrollOffset(),h=a<=0?0:l/a*c;this.emitScrollChange(h)}emitScrollChange(e){const t=this.clampScrollOffset(e);this.scrollOffset=t,this.render(),this.onScrollChange(t)}render(){const e=Math.max(0,this.container.clientWidth),t=Math.max(0,this.container.clientHeight),i=this.shouldHideScrollbar();this.stage.width(e),this.stage.height(t),this.container.style.display=i?"none":"block",this.hitAreaRect.x(0),this.hitAreaRect.y(0),this.hitAreaRect.width(e),this.hitAreaRect.height(t),this.thumbRect.fill(this.theme.scrollbarThumb||Lt.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Lt.border);const r=this.getAvailableTrackSize();if(r<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const n=this.getThumbSize(r),a=this.leadingInset+this.getThumbPosition(r,n);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(a),this.thumbRect.y(0),this.thumbRect.width(n),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(a),this.thumbRect.width(e),this.thumbRect.height(n)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const r=Math.max(1,e-t);return this.scrollOffset/i*r}}const Gp=48;function Hp(s,e,t){return U.timeToPixels(s,e)-t+pe}function zp(s,e,t){const i=Math.max(0,t-e);return Math.max(0,Math.min(i,s))}function $p(s){const{time:e,zoom:t,scrollLeft:i,viewportWidth:r,contentWidth:n,margin:a=Gp}=s;if(r<=0||Math.max(0,n-r)<=0)return null;const l=Hp(e,t,i),c=r-a;if(l>=a&&l<=c)return null;const h=U.timeToPixels(e,t),d=l<a?h+pe-a:h+pe-c,u=zp(d,r,n);return Math.abs(u-i)<=.5?null:u}class Zs{constructor(){g(this,"entries",new Map)}register(e,t){const i=this.entries.get(e);i&&i.destroy(),this.entries.set(e,{id:e,destroy:t})}unregister(e){this.entries.delete(e)}destroyAll(){for(const e of this.entries.values())e.destroy();this.entries.clear()}}const Vp="@linker-design-plus/timeline-track",Up="2.1.5",Yt={name:Vp,version:Up},Wp=1,Yp=2,Xp=250,qp=750,jp=1500;function Js(s){return s==null?s:JSON.parse(JSON.stringify(s))}function Kp(s,e){return s.length!==e.length?!1:s.every((t,i)=>t===e[i])}function Zp(s){return s==="text"?"文本":s==="video"?"视频":"音频"}class Jp{constructor(e={}){g(this,"timeline",null);g(this,"tracks",[]);g(this,"trackManager");g(this,"trackInfoPanelController");g(this,"playhead",null);g(this,"history");g(this,"config");g(this,"eventDispatcher");g(this,"animationFrameId",null);g(this,"lastUpdateTime",0);g(this,"isInitialized",!1);g(this,"stage",null);g(this,"headerStage",null);g(this,"headerLayer",null);g(this,"backgroundLayer",null);g(this,"trackLayer",null);g(this,"dragOverlayLayer",null);g(this,"snapGuideLayer",null);g(this,"selectionBoxLayer",null);g(this,"selectionBoxRect",null);g(this,"isBoxSelecting",!1);g(this,"boxSelectStartX",0);g(this,"boxSelectStartY",0);g(this,"resizeObserver",null);g(this,"rootContainer",null);g(this,"layout",null);g(this,"bodyBackgroundRect",null);g(this,"snapGuideLine",null);g(this,"trackInsertionPreviewLine",null);g(this,"trackInsertionPreviewY",null);g(this,"snapGuideTime",null);g(this,"horizontalScrollbar",null);g(this,"verticalScrollbar",null);g(this,"isExecutingHistoryAction",!1);g(this,"lastTrackDuration",0);g(this,"lastReportedTrackDuration",0);g(this,"thumbnailProvider",null);g(this,"thumbnailProviderVersion",0);g(this,"clipThumbnailLoadStates",new Map);g(this,"sourceMediaRegistry",new Or);g(this,"canPlay",!1);g(this,"sourceLoadingCount",0);g(this,"timelineStore");g(this,"timelineCommands");g(this,"timelineHistoryRecorder");g(this,"timelinePresentationAdapter");g(this,"timelineTrackBridge");g(this,"timelinePlaybackResolver");g(this,"previewRuntimeController");g(this,"previewStateController");g(this,"previewPlaybackSuspendedByBuffering",!1);g(this,"previewPlaybackAutoResume",!1);g(this,"lastSelectedClipId",null);g(this,"previewAspectRatio",{...Be});g(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});g(this,"stageMouseDownListener",null);g(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});g(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});g(this,"keyboardShortcutsController",null);g(this,"clipClipboard",null);g(this,"mountManager",new Zs);g(this,"pendingDraftData",null);g(this,"selectionStore",new Co);g(this,"multiDragSession",null);g(this,"clipRemovalBatchDepth",0);g(this,"splitOperationDepth",0);g(this,"diagnostics");g(this,"previewRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});g(this,"failedPreviewClipIds");g(this,"previewActiveClipIds",[]);g(this,"previewClockSeekAlignmentTargetTime",null);g(this,"previewClockSeekAlignmentDeadlineMs",0);g(this,"playbackAttemptId",this.createPlaybackAttemptId("initial"));g(this,"lastPreviewSyncedPlayState",null);g(this,"lastPreviewSyncSignature",null);g(this,"lastSteadyPlaybackPreviewSyncAt",0);g(this,"previewSyncInteractionMode",null);g(this,"resourceCacheManager");g(this,"voiceLinkedTextRegenerationTimer",null);g(this,"pendingVoiceLinkedTextRegeneration",null);g(this,"historyRecordingSuppressionDepth",0);g(this,"activeStructureSession",null);g(this,"structureSessionDepth",0);g(this,"preserveEmptyTracksDepth",0);g(this,"playbackViewportFollowSuspended",!1);g(this,"isProgrammaticScrollChange",!1);this.config={duration:e.duration||Qt,zoom:e.zoom||Me.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:qi(e.theme),timeScaleHeight:e.timeScaleHeight,diagnostics:e.diagnostics,speed:e.speed||1,dragActivationThreshold:e.dragActivationThreshold??4,enableClipSnap:e.enableClipSnap??!1,enablePrimaryTrackMagnet:e.enablePrimaryTrackMagnet??!0,clipSnapThreshold:e.clipSnapThreshold??8,thumbnailProvider:e.thumbnailProvider,previewBackend:e.previewBackend??"dom",previewSourceResolver:e.previewSourceResolver,resourceCache:e.resourceCache,textPreviewFont:e.textPreviewFont??null,keyboardShortcuts:e.keyboardShortcuts,playbackViewportFollow:e.playbackViewportFollow??!0},this.diagnostics=new qa(this.config.diagnostics),this.resourceCacheManager=this.config.resourceCache?new Mp({options:this.config.resourceCache,onEvent:(t,i)=>{this.emitDiagnostic({...this.buildPreviewDiagnosticsContext(),severity:t.endsWith(".failed")||t.endsWith(".fallback")?"warn":"info",category:"resource",eventName:t,message:t,extra:i})}}):null,this.diagnostics.startSession({packageName:Yt.name,packageVersion:Yt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.config.previewBackend}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new ap,this.eventDispatcher=new Hs({can_play_change:()=>({canPlay:this.canPlay}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})}),this.history=new an(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new Is(this.history),this.trackManager=new vo,this.timelineStore=new js({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new _s(this.timelineStore),this.timelinePresentationAdapter=new Vs,this.timelineTrackBridge=new qs({onClipUpdate:(t,i,r)=>this.handleClipUpdate(t,i,r),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.handleTimeChange.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onPrimaryTrackMagnetMove:this.handlePrimaryTrackMagnetMove.bind(this),onClipCrossTrackPreview:this.handleClipCrossTrackPreview.bind(this),onClipCrossTrack:this.handleClipCrossTrack.bind(this),onClearDropPreview:this.clearAllTrackDropPreviews.bind(this),onClearSelection:this.clearSelection.bind(this),onSnapGuideChange:this.updateSnapGuideLine.bind(this),onClipToggleSelection:this.handleClipToggleSelection.bind(this),onSetSingleSelection:this.handleSetSingleSelection.bind(this),getMultiDragClipIds:this.getMultiDragClipIds.bind(this),onMultiDragMove:this.handleMultiDragMove.bind(this),onMultiDragInteractionEnd:this.handleMultiDragInteractionEnd.bind(this)}),e.draftData&&(this.pendingDraftData=e.draftData),this.config.container&&this.init(this.config.container)}createPlaybackAttemptId(e){return`playback-${e}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}refreshPlaybackAttempt(e){this.playbackAttemptId=this.createPlaybackAttemptId(e)}emitDiagnostic(e){var t;(t=this.diagnostics)==null||t.emit(e)}buildDiagnosticsRuntimeState(){var e,t;return{currentTimeMs:this.getCurrentTimeState(),playState:this.getPlayStateState(),speed:this.getSpeedState(),pendingMode:((e=this.pendingPreviewState)==null?void 0:e.mode)??null,sourceLoadingPending:this.getSourceLoadingState().pending,loadingStatus:this.getPreviewLoadingState().status,loadingReason:this.getPreviewLoadingState().reason,isLoading:this.getPreviewLoadingState().isLoading,runtimePhase:((t=this.previewRuntimeState)==null?void 0:t.phase)??"idle",selectedClipId:this.getPrimarySelectedClipId(),activeClipIds:Array.isArray(this.previewActiveClipIds)?[...this.previewActiveClipIds]:[],previewAspectRatio:this.getPreviewAspectRatio()}}buildPreviewDiagnosticsContext(){return{playbackAttemptId:this.playbackAttemptId,previewBackend:this.getPreviewBackendType(),runtimeState:this.buildDiagnosticsRuntimeState()}}getTimelineStore(){var e,t,i,r,n;if(!this.timelineStore){const a=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,c=((r=this.config)==null?void 0:r.zoom)||Me.MEDIUM,h=((n=this.config)==null?void 0:n.duration)||Qt;this.timelineStore=new js({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new _s(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Lp(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new Vs),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new qs({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.handleTimeChange.bind(this),onHorizontalDragAutoScroll:this.handleHorizontalDragAutoScroll.bind(this),onClipOverlap:this.handleClipOverlap.bind(this),onPrimaryTrackMagnetMove:this.handlePrimaryTrackMagnetMove.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 zu),this.timelinePlaybackResolver}get previewSession(){return this.getPreviewRuntimeController().previewSession}set previewSession(e){this.getPreviewRuntimeController().previewSession=e}get previewMountContainer(){return this.getPreviewRuntimeController().previewMountContainer}set previewMountContainer(e){this.getPreviewRuntimeController().previewMountContainer=e}get resolvedPreviewBackend(){return this.getPreviewRuntimeController().resolvedPreviewBackend}set resolvedPreviewBackend(e){this.getPreviewRuntimeController().resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this.getPreviewRuntimeController().runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this.getPreviewRuntimeController().runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this.getPreviewRuntimeController().activePreviewCallbackToken}set activePreviewCallbackToken(e){this.getPreviewRuntimeController().activePreviewCallbackToken=e}getPreviewLoadingState(){return this.getPreviewStateController().previewLoadingState}get pendingPreviewState(){return this.getPreviewStateController().pendingPreviewState}set pendingPreviewState(e){this.getPreviewStateController().pendingPreviewState=e}get nextPendingPreviewSyncRequestId(){return this.getPreviewStateController().nextPendingPreviewSyncRequestId}set nextPendingPreviewSyncRequestId(e){this.getPreviewStateController().nextPendingPreviewSyncRequestId=e}getPreviewStateController(){return this.previewStateController||(this.previewStateController=new Uu({callbacks:{applyPendingState:e=>{var t,i;(i=(t=this.previewSession)==null?void 0:t.setPendingState)==null||i.call(t,e)},emitLoadingStateChange:e=>{this.syncPlaybackClockToPreviewLoadingState(e),this.emitEvent("loading_state_change",e)},resumePlayback:()=>{this.play()},requestPreviewSync:()=>{this.syncPreviewSession()}}})),this.previewStateController}getPreviewRuntimeController(){return this.previewRuntimeController||(this.previewRuntimeController=new $u({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new Bu({callbacks:t,diagnostics:this.diagnostics,getDiagnosticsContext:()=>this.buildPreviewDiagnosticsContext(),previewSourceResolver:this.config.previewSourceResolver,resourceCacheManager:this.resourceCacheManager,textPreviewFont:this.config.textPreviewFont,sourceMediaRegistry:this.sourceMediaRegistry}),resolveConfiguredBackend:e=>e||Ou(this.config.previewBackend)})),this.previewRuntimeController}resolveConfiguredPreviewBackend(){return this.getPreviewRuntimeController().resolveConfiguredPreviewBackend()}createPreviewBackendCallbacks(e=this.activePreviewCallbackToken){return{onRuntimeStateChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewRuntimeState=t,this.syncTimelineClipMediaStateFromPreview(t),this.getPreviewStateController().handleRuntimeStateChange(t),this.handlePreviewClockStateChange(t.clock))},onSyncProcessed:t=>{this.isActivePreviewCallbackToken(e)&&this.getPreviewStateController().markSyncProcessed(t)},onAspectRatioChange:t=>{this.isActivePreviewCallbackToken(e)&&(this.previewAspectRatio=je(t),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))},onPreviewClipSelect:t=>{this.isActivePreviewCallbackToken(e)&&this.selectClip(t)},onVisualTransformCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewVisualTransform(t,i)},onTextFontSizeCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextFontSize(t,i)},onTextRotationCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextRotation(t,i)},onPendingPreviewRetry:()=>{this.isActivePreviewCallbackToken(e)&&this.retryPendingPreview()},onPauseIfPlaying:()=>{this.isActivePreviewCallbackToken(e)&&this.getPlayStateState()==="playing"&&this.pause()},onRuntimeError:()=>{this.isActivePreviewCallbackToken(e)&&this.handlePreviewBackendRuntimeError()}}}isActivePreviewCallbackToken(e){return this.getPreviewRuntimeController().isActiveCallbackToken(e)}getEventDispatcher(){return this.eventDispatcher||(this.eventDispatcher=new Hs({can_play_change:()=>({canPlay:this.canPlay??!1}),selection_change:()=>this.resolveSelectionChangeData(),selected_clip_change:()=>this.resolveSelectedClipSnapshot(),loading_state_change:()=>this.getPreviewLoadingState(),preview_aspect_ratio_change:()=>({aspectRatio:this.getPreviewAspectRatio()})})),this.eventDispatcher}getDefaultTrackForHistory(){return this.getTrackCollection().getDefaultTrack()}getTimelineHistoryRecorder(){return this.timelineHistoryRecorder||(this.history||(this.history=new an(()=>{},()=>{})),this.timelineHistoryRecorder=new Is(this.history)),this.timelineHistoryRecorder}withStructureSession(e){const t=this.activeStructureSession;if(t)return e(t);const i=new ip({trackCollection:this.getTrackCollection(),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),setPrimaryTrackMagnetEnabled:this.setPrimaryTrackMagnetEnabledFromHistory.bind(this),loadClipThumbnails:this.loadClipThumbnails.bind(this),addClipToTrack:(n,a)=>this.getTrackCollection().addClipToTrack(n,a),removeClip:n=>{const a=this.getTrackCollection();if(typeof a.removeClip=="function"){a.removeClip(n);return}this.tracks.forEach(o=>{var l;return(l=o.removeClip)==null?void 0:l.call(o,n)})},removeClipFromTrack:(n,a)=>this.getTrackCollection().removeClipFromTrack(n,a),updateClip:(n,a)=>{const o=this.getTrackCollection();if(typeof o.updateClip=="function"){o.updateClip(n,a);return}this.tracks.forEach(l=>{var c;return(c=l.updateClip)==null?void 0:c.call(l,n,a)})},moveClipToTrack:(n,a,o)=>{const l=this.getTrackCollection();if(typeof l.moveClipToTrack=="function")return l.moveClipToTrack(n,a,o);const c=l.findById(a),h=l.findById(o);return!(c!=null&&c.removeClip)||!(h!=null&&h.addClip)?!1:(c.removeClip(n.id),h.addClip(n),!0)},getClips:this.getClips.bind(this),findTrackByClipId:this.findTrackByClipId.bind(this),getDefaultTrack:()=>this.getDefaultTrackForHistory(),onCommit:this.applyStructureSessionSummary.bind(this)});this.activeStructureSession=i,this.structureSessionDepth=(this.structureSessionDepth??0)+1;const r=()=>{this.structureSessionDepth=Math.max(0,(this.structureSessionDepth??1)-1),this.activeStructureSession=null,i.commit()};try{const n=e(i);return n instanceof Promise?n.finally(r):(r(),n)}catch(n){throw r(),n}}getActiveStructureSession(){return this.activeStructureSession??null}withPreservedEmptyTracks(e){this.preserveEmptyTracksDepth+=1;const t=()=>{this.preserveEmptyTracksDepth=Math.max(0,this.preserveEmptyTracksDepth-1)};try{const i=e();return i instanceof Promise?i.finally(t):(t(),i)}catch(i){throw t(),i}}applyStructureSessionSummary(e){var i;((e.cleanupEmptyTracks&&this.preserveEmptyTracksDepth===0?this.removeEmptyTracksFromStructure():!1)||e.trackLayoutDirty)&&this.updateAllTrackPositions(),e.durationDirty&&this.checkTrackDurationChange(),e.canPlayDirty&&this.updateCanPlayState(),e.events.forEach(r=>{this.emitEvent(r.type,r.payload)}),e.selectionDirty&&(this.notifySelectionChange(),this.emitSelectionChangeEvent(),this.emitSelectedClipChangeIfNeeded()),e.trackInfoDirty&&this.updateTrackInfoPanel(),e.stageDirty&&((i=this.stage)==null||i.batchDraw()),e.previewDirty&&this.syncPreviewSession()}withHistoryBoundary(e,t,i){if(e==="transaction"){const a=t,o=i;if(!o)throw new Error("transaction history boundary requires a callback");return this.getTimelineHistoryRecorder().withTransaction(a,o)}const r=typeof t=="function"?t:i;if(!r)throw new Error(`history boundary "${e}" requires a callback`);if(e==="record")return r();if(e==="suppressed"||e==="reset"){this.historyRecordingSuppressionDepth=(this.historyRecordingSuppressionDepth??0)+1;try{const a=r();return a instanceof Promise?a.then(o=>(this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),o),o=>{throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),o}):(this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),a)}catch(a){throw this.historyRecordingSuppressionDepth=Math.max(0,(this.historyRecordingSuppressionDepth??1)-1),a}}const n=this.isExecutingHistoryAction??!1;this.isExecutingHistoryAction=!0;try{const a=r();return a instanceof Promise?a.then(o=>(this.isExecutingHistoryAction=n,o),o=>{throw this.isExecutingHistoryAction=n,o}):(this.isExecutingHistoryAction=n,a)}catch(a){throw this.isExecutingHistoryAction=n,a}}shouldSkipHistoryRecording(){return this.isExecutingHistoryAction||this.historyRecordingSuppressionDepth>0}withHistoryTransaction(e,t){return this.withHistoryBoundary("transaction",e,t)}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:Qt,zoom:Me.MEDIUM,currentTime:0,playState:"paused",theme:qi(),speed:1,dragActivationThreshold:4,enableClipSnap:!1,enablePrimaryTrackMagnet:!0,clipSnapThreshold:8,previewBackend:"dom",textPreviewFont:null,playbackViewportFollow:!0}),this.config}isPlaybackViewportFollowEnabled(){return this.ensureConfigState().playbackViewportFollow!==!1}suspendPlaybackViewportFollowIfUserScrolling(){this.getPlayStateState()==="playing"&&!this.isProgrammaticScrollChange&&(this.playbackViewportFollowSuspended=!0)}runProgrammaticScrollChange(e){this.isProgrammaticScrollChange=!0;try{e()}finally{this.isProgrammaticScrollChange=!1}}followPlaybackViewportIfNeeded(e){if(!this.isPlaybackViewportFollowEnabled()||this.getPlayStateState()!=="playing"||this.playbackViewportFollowSuspended)return;const t=this.getViewportWidth(),i=this.getZoomState(),r=this.getScrollLeftState(),n=this.getHorizontalContentWidth(),a=$p({time:e,zoom:i,scrollLeft:r,viewportWidth:t,contentWidth:n});if(a!==null){this.isProgrammaticScrollChange=!0;try{this.syncScrollLeft(a)}finally{this.isProgrammaticScrollChange=!1}}}getCurrentTimeState(){return this.getTimelineStore().getCurrentTime()}getPlayStateState(){return this.getTimelineStore().getPlayState()}setPlayStateState(e){this.getTimelineStore().setPlayState(e),this.ensureConfigState().playState=e}getSpeedState(){return this.getTimelineStore().getSpeed()}getZoomState(){return this.getTimelineStore().getZoom()}getDurationState(){return this.getTimelineStore().getDuration()}setDurationState(e){this.getTimelineStore().setDuration(e),this.ensureConfigState().duration=e}getScrollLeftState(){return this.getTimelineStore().getScrollLeft()}setScrollLeftState(e){this.getTimelineStore().setScrollLeft(e)}getScrollTopState(){return this.getTimelineStore().getScrollTop()}setScrollTopState(e){this.getTimelineStore().setScrollTop(e)}setViewportMetrics(e,t,i){const r=this.getTimelineStore();r.setViewportWidth(e),r.setViewportHeight(t),r.setContentHeight(i)}syncCurrentTimeToScene(e){this.getTimelinePresentationAdapter().syncCurrentTime(this.timeline?{setCurrentTime:this.timeline.setCurrentTime.bind(this.timeline)}:null,this.playhead?{setCurrentTime:this.playhead.setTime.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncZoomToScene(e){this.getTimelinePresentationAdapter().syncZoom(this.timeline,this.playhead?{setZoom:this.playhead.setZoom.bind(this.playhead)}:null,this.getTrackCollection(),e)}syncScrollTopPresentation(e){this.getTimelinePresentationAdapter().syncScrollTop({setScrollTop:this.trackInfoPanelController.setScrollTop.bind(this.trackInfoPanelController)},this.verticalScrollbar?{setScrollTop:this.verticalScrollbar.setScrollTop.bind(this.verticalScrollbar)}:null,e)}refreshScrollbarMetrics(){var i,r,n,a;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(r=this.verticalScrollbar)==null||r.resize(),(n=this.horizontalScrollbar)==null||n.setViewportMetrics(e,this.getHorizontalContentWidth()),(a=this.verticalScrollbar)==null||a.setViewportMetrics(t,this.getVerticalContentHeight())}getTimeScaleHeight(){return this.config.timeScaleHeight||40}getTrackContentTopOffset(){return 0}getViewportWidth(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientWidth)||0}getViewportHeight(){var e;return((e=this.layout)==null?void 0:e.bodyViewport.clientHeight)||0}getHorizontalContentWidth(){return U.timeToPixels(this.getDurationState(),this.getZoomState())}getVerticalContentHeight(){return Math.max(this.calculateTotalHeight(),this.getViewportHeight())}clampScrollLeft(e){const t=Math.max(0,this.getHorizontalContentWidth()-this.getViewportWidth());return Math.max(0,Math.min(t,e))}clampScrollTop(e){const t=Math.max(0,this.getVerticalContentHeight()-this.getViewportHeight());return Math.max(0,Math.min(t,e))}syncScrollLeft(e){var i,r;const t=this.clampScrollLeft(e);this.setScrollLeftState(t),(i=this.timeline)==null||i.setScrollLeft(t),(r=this.horizontalScrollbar)==null||r.setScrollLeft(t),this.getTimelinePresentationAdapter().syncScrollLeft(this.playhead?{setScrollLeft:this.playhead.setScrollLeft.bind(this.playhead)}:null,this.getTrackCollection(),t),this.refreshSnapGuideLine()}syncScrollTop(e){var i;const t=this.clampScrollTop(e);this.setScrollTopState(t),(i=this.layout)!=null&&i.bodyViewport&&Math.abs(this.layout.bodyViewport.scrollTop-t)>.5&&(this.layout.bodyViewport.scrollTop=t),this.syncScrollTopPresentation(t)}getResolvedTracksSnapshot(){const e=this.getTrackCollection();return this.trackManager.getTracks().map(t=>{const i=e.findById(t.id);return{...t,clips:i?i.getClips():[...t.clips]}})}getTracksSortedByOrder(){const e=this.getTrackCollection();return this.trackManager.getTracks().slice().sort((t,i)=>t.order-i.order).map(t=>e.findById(t.id)).filter(t=>t!==null)}getPlaybackTracksSnapshot(){return this.getResolvedTracksSnapshot().map(e=>({id:e.id,type:e.type,order:e.order,isMuted:e.isMuted??!1,clips:e.clips}))}buildPlaybackPlan(e=this.getCurrentTimeState()){return this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),e)}buildPreviewPlaybackPlan(e,t=this.getCurrentTimeState()){const i=this.buildPlaybackPlan(t);if(e!=="paused"||i.activeClips.length>0)return i;let r;try{r=this.getClips()}catch{return i}if(r.length===0)return i;const n=kt(r);return n<=0||t!==n?i:this.getTimelinePlaybackResolver().resolvePlaybackPlan(this.getPlaybackTracksSnapshot(),t,{includeEndedClipsAtTime:!0})}playbackPlanHasActiveVideoClip(e){return e.activeClips.some(t=>t.trackType==="video")}hasActiveTimelineVideoClip(e=this.getCurrentTimeState()){return this.playbackPlanHasActiveVideoClip(this.buildPlaybackPlan(e))}getPreviewAutoAspectRatioClipOrderMap(){const e=this;return e.previewAutoAspectRatioVideoClipOrder instanceof Map||(e.previewAutoAspectRatioVideoClipOrder=new Map),e.previewAutoAspectRatioVideoClipOrder}getNextPreviewAutoAspectRatioOrder(){const e=this;return Number.isFinite(e.nextPreviewAutoAspectRatioVideoClipOrder)||(e.nextPreviewAutoAspectRatioVideoClipOrder=0),e.nextPreviewAutoAspectRatioVideoClipOrder}getAutoAspectRatioClip(){const e=this.getPreviewAutoAspectRatioClipOrderMap(),t=this.getPlaybackTracksSnapshot().slice().sort((a,o)=>a.order-o.order);let i=null,r=null,n=Number.POSITIVE_INFINITY;for(const a of t){if(a.type!=="video")continue;const o=[...a.clips].sort((l,c)=>l.startTime-c.startTime);for(const l of o){const c={trackId:a.id,trackType:a.type,trackOrder:a.order,clip:l,mediaTime:l.startTimeAtSource,muted:(a.isMuted??!1)||(l.isMuted??!1),kind:a.type,hasVisual:!0,hasAudio:!0};i||(i=c);const h=e.get(l.id);h===void 0||h>=n||(r=c,n=h)}}return r||i}registerPreviewAutoAspectRatioClip(e){const t=this,i=this.getPreviewAutoAspectRatioClipOrderMap();e.type!=="video"||i.has(e.id)||(i.set(e.id,this.getNextPreviewAutoAspectRatioOrder()),t.nextPreviewAutoAspectRatioVideoClipOrder=this.getNextPreviewAutoAspectRatioOrder()+1)}buildPreviewSyncSignature(e){var i,r;const t=n=>[n.trackId,n.clip.id,n.trackType,n.trackOrder,n.clip.startTime,n.clip.endTime,n.clip.startTimeAtSource,n.muted?1:0,n.clip.volume??""].join(":");return JSON.stringify({active:e.playbackPlan.activeClips.map(t),next:e.playbackPlan.nextClips.map(t),firstVideoClipId:((i=e.playbackPlan.firstVideoClip)==null?void 0:i.clip.id)??null,autoAspectRatioClipId:((r=e.autoAspectRatioClip)==null?void 0:r.clip.id)??null,previewAspectRatio:e.previewAspectRatio,playState:e.targetPlayState,requestedPlayState:e.requestedPlayState,speed:e.speed,interactionMode:e.interactionMode,primarySelectedClipId:e.primarySelectedClipId})}shouldSkipSteadyPlaybackPreviewSync(e,t,i){return t!=="playing"||i!=="steady"||this.pendingPreviewState||this.getPreviewLoadingState().isLoading||this.lastPreviewSyncedPlayState!=="playing"||this.lastPreviewSyncSignature!==e?!1:Date.now()-this.lastSteadyPlaybackPreviewSyncAt<Xp}syncPreviewSession(e){var d,u,p,f;if(!((d=this.previewSession)!=null&&d.hasPreview())){this.previewSyncInteractionMode=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0;return}const t=this.resolvePreviewSyncPlayState(e),i=this.resolvePreviewRequestedPlayState(t),r=this.buildPreviewPlaybackPlan(t);this.previewActiveClipIds=r.activeClips.map(m=>m.clip.id);const n=this.getAutoAspectRatioClip(),a=je(this.previewAspectRatio),o=this.getSpeedState(),l=this.previewSyncInteractionMode??((u=this.pendingPreviewState)==null?void 0:u.mode)??"steady",c=this.getPrimarySelectedClipId(),h=this.buildPreviewSyncSignature({playbackPlan:r,autoAspectRatioClip:n,previewAspectRatio:a,targetPlayState:t,requestedPlayState:i,speed:o,interactionMode:l,primarySelectedClipId:c});if(this.shouldSkipSteadyPlaybackPreviewSync(h,t,l)){this.previewSyncInteractionMode=null;return}this.previewAspectRatio=a,this.previewSession.applyAspectRatio(a),(f=(p=this.previewSession).setPendingState)==null||f.call(p,this.buildPreviewPendingState()),this.previewSession.sync({...r,autoAspectRatioClip:n,currentTime:this.getCurrentTimeState(),playState:t,...i!==t?{requestedPlayState:i}:{},speed:o,interactionMode:l,primarySelectedClipId:c,...this.pendingPreviewState?{syncRequestId:this.pendingPreviewState.syncRequestId}:{}}),this.previewSyncInteractionMode=null,this.lastPreviewSyncedPlayState=t,this.lastPreviewSyncSignature=h,this.lastSteadyPlaybackPreviewSyncAt=t==="playing"&&l==="steady"?Date.now():0}resolvePreviewSyncPlayState(e){return e||this.getPlayStateState()}resolvePreviewRequestedPlayState(e){var t;return((t=this.pendingPreviewState)==null?void 0:t.mode)==="seek"&&this.pendingPreviewState.resumePlayOnReady&&e==="paused"?"playing":e}syncPreviewPlaybackStateIfNeeded(e){this.lastPreviewSyncedPlayState!==e&&this.syncPreviewSession(e)}shouldUsePreviewClockPlayback(){var e;try{return!!((e=this.previewSession)!=null&&e.hasPreview())&&this.hasActiveTimelineVideoClip()&&!this.pendingPreviewState}catch{return!1}}handlePreviewClockStateChange(e){if(!(!e||this.getPlayStateState()!=="playing")){if(!this.shouldUsePreviewClockPlayback()){this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState());return}if(this.isPreviewClockForCurrentActiveClip(e)&&!this.shouldIgnorePreviewClockUntilSeekTargetAligned(e)){if(e.status!=="running"||e.timelineTime===null){this.cancelPlaybackAnimationFrame(),this.shouldCommitUnavailablePreviewClock(e)&&this.commitPlaybackTimeFromPreviewClock(e);return}this.commitPlaybackTimeFromPreviewClock(e)}}}isPreviewClockForCurrentActiveClip(e){return!e.clipId||!Array.isArray(this.previewActiveClipIds)?!0:this.previewActiveClipIds.includes(e.clipId)}shouldCommitUnavailablePreviewClock(e){return e.status!=="unavailable"||e.timelineTime===null?!1:this.isPreviewClockForCurrentActiveClip(e)}shouldIgnorePreviewClockUntilSeekTargetAligned(e){return this.previewClockSeekAlignmentTargetTime==null||e.timelineTime===null?!1:Date.now()>this.previewClockSeekAlignmentDeadlineMs?(this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,!1):Math.abs(e.timelineTime-this.previewClockSeekAlignmentTargetTime)<=qp?(this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,!1):!0}commitPlaybackTimeFromPreviewClock(e){if(e.timelineTime===null)return;const t=this.clampPlaybackSeekTime(e.timelineTime),i=this.getTimelineCommands().setCurrentTime(t);if(!i.changed){this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(i.nextValue,e);return}const r=i.nextValue;this.ensureConfigState().currentTime=r,this.syncCurrentTimeToScene(r),this.followPlaybackViewportIfNeeded(r),this.emitEvent("time_change",{time:r}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewAfterPreviewClockCommitIfNeeded(r,e)}syncPreviewAfterPreviewClockCommitIfNeeded(e,t){if(this.getPlayStateState()!=="playing"||this.pendingPreviewState)return;const i=this.buildPlaybackPlan(e),r=i.activeClips.map(n=>n.clip.id);if(!Kp(r,this.previewActiveClipIds)){this.syncPreviewSession(),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i);return}t.clipId&&(r.includes(t.clipId)||this.syncPreviewSession()),this.resumeWallClockPlaybackIfPreviewClockUnavailable(e,i)}resumeWallClockPlaybackIfPreviewClockUnavailable(e,t=this.buildPlaybackPlan(e)){this.getPlayStateState()!=="playing"||this.pendingPreviewState||this.animationFrameId||this.playbackPlanHasActiveVideoClip(t)||!this.canPlay||(this.lastUpdateTime=Date.now(),this.animate())}beginPendingPreview(e,t="seek"){var r,n,a,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;if(!this.hasActiveTimelineVideoClip(e)){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();return}(t!=="scrub"||((n=this.pendingPreviewState)==null?void 0:n.mode)!=="scrub")&&this.refreshPlaybackAttempt(t);const i=((a=this.pendingPreviewState)==null?void 0:a.resumePlayOnReady)??this.getPlayStateState()==="playing";this.getPreviewStateController().beginPendingPreview(e,t,i),this.getPlayStateState()==="playing"&&this.pause(),t!=="scrub"&&this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"pending-preview.begin",message:"Pending preview started",playbackAttemptId:this.playbackAttemptId,syncRequestId:((o=this.pendingPreviewState)==null?void 0:o.syncRequestId)??null,runtimeState:{...this.buildDiagnosticsRuntimeState(),pendingMode:t},extra:{targetTime:e,resumePlayOnReady:i}})}updatePendingPreviewState(){this.getPreviewStateController().updatePendingPreviewState()}buildPreviewPendingState(){return this.getPreviewStateController().buildPreviewPendingState()}clearPendingPreviewState(){this.getPreviewStateController().clearPendingPreviewState()}resetPreviewRuntimeState(){this.getPreviewStateController().resetPreviewRuntimeState(),this.previewActiveClipIds=[],this.previewClockSeekAlignmentTargetTime=null,this.previewClockSeekAlignmentDeadlineMs=0,this.lastPreviewSyncedPlayState=null,this.lastPreviewSyncSignature=null,this.lastSteadyPlaybackPreviewSyncAt=0,this.previewSyncInteractionMode=null,this.previewRuntimeState={phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},errorMessage:null,slots:[]}}destroyPreviewSession(e=!1){this.getPreviewRuntimeController().destroyPreviewSession(e),this.lastPreviewSyncedPlayState=null,this.resetPreviewRuntimeState()}retryPendingPreview(){var e;this.refreshPlaybackAttempt("retry"),this.getPreviewStateController().retryPendingPreview(),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"pending-preview.retry",message:"Pending preview retried",playbackAttemptId:this.playbackAttemptId,syncRequestId:((e=this.pendingPreviewState)==null?void 0:e.syncRequestId)??null,runtimeState:this.buildDiagnosticsRuntimeState()})}handlePreviewBackendRuntimeError(){this.emitDiagnostic({severity:"error",category:"runtime",eventName:"preview.runtime.error",message:"Preview backend runtime error",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState(),extra:{resolvedBackend:this.getPreviewBackendType()}}),this.clearPendingPreviewState(),this.resetPreviewRuntimeState();const e=this.getPreviewRuntimeController().fallbackToDom(je(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,r,n,a,o,l,c;if(this.isInitialized){O.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=kd(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:vi,scrollbarSize:rn}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(r=(i=this.layout.bodyCanvasHost).addEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(a=(n=this.rootContainer)==null?void 0:n.addEventListener)==null||a.call(n,"wheel",this.rootWheelListener,{passive:!1}),this.initKeyboardShortcuts(),this.headerStage=new Z.Stage({container:this.layout.headerCanvasHost,width:this.layout.headerViewport.clientWidth,height:this.getTimeScaleHeight()}),this.headerLayer=new Z.Layer({name:"timelineHeaderLayer"}),this.headerStage.add(this.headerLayer),this.stage=new Z.Stage({container:this.layout.bodyCanvasHost,width:this.layout.bodyViewport.clientWidth,height:0}),this.backgroundLayer=new Z.Layer({name:"trackBackgroundLayer"}),this.trackLayer=new Z.Layer({name:"trackLayer"}),this.dragOverlayLayer=new Z.Layer({name:"trackDragOverlayLayer",listening:!1}),this.snapGuideLayer=new Z.Layer({name:"trackSnapGuideLayer",listening:!1}),this.selectionBoxLayer=new Z.Layer({name:"selectionBoxLayer",listening:!1}),this.stage.add(this.backgroundLayer),this.stage.add(this.trackLayer),this.stage.add(this.dragOverlayLayer),this.stage.add(this.snapGuideLayer),this.stage.add(this.selectionBoxLayer);const t=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);if(t&&(this.stageMouseDownListener||(this.stageMouseDownListener=h=>{this.handleStageMouseDown(h)}),t.addEventListener("mousedown",this.stageMouseDownListener)),this.timeline=new Np(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new cn(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 Ks({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:pe,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Ks({container:this.layout.verticalScrollbarCanvasHost,orientation:"vertical",theme:this.config.theme,onScrollChange:h=>{this.syncScrollTop(h)}}),this.trackInfoPanelController.init({container:this.layout.trackInfoViewport,theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),includeTimeScaleSpacer:!1,onRenameTrack:this.renameTrack.bind(this),onRemoveTrack:this.removeTrack.bind(this),onMuteTrack:this.muteTrack.bind(this)}),this.resizeObserver=new ResizeObserver(()=>{this.updateViewportLayout()}),this.resizeObserver.observe(e),this.createTrack("video","视频轨道 1"),this.isInitialized=!0,this.updateViewportLayout(),this.syncScrollLeft(this.getScrollLeftState()),this.syncScrollTop(this.getScrollTopState()),(c=this.stage)==null||c.batchDraw(),this.pendingDraftData){const h=this.pendingDraftData;this.pendingDraftData=null,queueMicrotask(()=>{this.importTimeline(h).catch(d=>{O.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,n,a){var u,p,f,m;if(!this.trackLayer)return O.error("TimelineManager","Track layer not initialized"),"";const o=this.trackManager.createTrack(e,t,i,r,n,a),l=o.id,c=Ae(e),h=this.calculateTrackY(l),d=this.getTimelineTrackBridge().createTrack({layer:this.trackLayer,config:{id:l,clips:[],role:o.role},trackType:e,zoom:this.getZoomState(),trackY:h,trackHeight:c,theme:this.config.theme,dragActivationThreshold:this.config.dragActivationThreshold,enableClipSnap:this.config.enableClipSnap,clipSnapThreshold:this.config.clipSnapThreshold});return(u=d.setSnapTargetResolver)==null||u.call(d,()=>this.getClips()),(p=d.setDragOverlayLayer)==null||p.call(d,this.dragOverlayLayer),this.getTrackCollection().add(d),this.getActiveStructureSession()?(f=this.getActiveStructureSession())==null||f.markTrackLayoutMutation():(this.updateAllTrackPositions(),(m=this.stage)==null||m.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession()),l}removeTrack(e){var r,n,a,o,l;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return O.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return O.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((a=(n=t.getTrackGroup)==null?void 0:n.call(t))==null||a.destroy(),this.getTrackCollection().removeById(e),this.getActiveStructureSession()?(o=this.getActiveStructureSession())==null||o.markTrackLayoutMutation():(this.updateAllTrackPositions(),(l=this.stage)==null||l.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession())),i}renameTrack(e,t){var r,n;if(!((r=this.trackManager)!=null&&r.renameTrack))return!1;const i=this.trackManager.renameTrack(e,t);return i&&(this.getActiveStructureSession()?(n=this.getActiveStructureSession())==null||n.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}getTracks(){return this.getResolvedTracksSnapshot()}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){var r,n;if(!((r=this.trackManager)!=null&&r.muteTrack))return!1;const i=this.trackManager.muteTrack(e,t);return i&&(this.getActiveStructureSession()?(n=this.getActiveStructureSession())==null||n.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return Ut(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return Ps(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=_d(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const r of e){const n=this.getTrackCollection().findById(r.trackId);n&&((t=n.setTrackY)==null||t.call(n,r.y),(i=n.setTrackHeight)==null||i.call(n,r.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}removeEmptyTracksFromStructure(){var i,r,n;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return!1;const e=this.getTrackCollection();if(typeof e.removeEmptyNonPrimaryTracks!="function")return!1;const t=e.removeEmptyNonPrimaryTracks();if(t.length===0)return!1;for(const a of t){const o=(i=a.getId)==null?void 0:i.call(a);o&&(typeof this.trackManager.removeTrack=="function"&&this.trackManager.removeTrack(o),(n=(r=a.getTrackGroup)==null?void 0:r.call(a))==null||n.destroy(),this.getTrackCollection().removeById(o))}return!0}cleanupEmptyTracks(){var e;this.clipRemovalBatchDepth>0||this.getActiveStructureSession()||this.removeEmptyTracksFromStructure()&&(this.updateAllTrackPositions(),(e=this.stage)==null||e.batchDraw(),this.updateTrackInfoPanel(),this.syncPreviewSession())}clearAllTrackDropPreviews(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDropPreview)==null?void 0:t.call(e)}),this.hideTrackInsertionPreview(),this.normalizeTrackGroupStackOrder()}showClipDropPreview(e,t){this.showClipDropPreviews(new Map([[t,[e]]]))}showClipDropPreviews(e){this.hideTrackInsertionPreview(),this.getTrackCollection().forEach(t=>{var n,a,o,l;const i=(n=t.getId)==null?void 0:n.call(t),r=i?e.get(i)??[]:[];if(r.length>0){r.length===1?(a=t.showClipDropPreview)==null||a.call(t,r[0]):(o=t.showClipDropPreviews)==null||o.call(t,r);return}(l=t.clearClipDropPreview)==null||l.call(t)})}ensureTrackInsertionPreviewLine(){if(!this.snapGuideLayer)return null;if(!this.trackInsertionPreviewLine){const e=de.createLine([0,0,0,0],this.getSnapGuideAccentColor(),2);e.name("timeline-track-insertion-preview-line"),e.dash([8,4]),e.visible(!1),e.listening(!1),this.snapGuideLayer.add(e),this.trackInsertionPreviewLine=e}return this.trackInsertionPreviewLine}refreshTrackInsertionPreview(e=!0){var i,r,n;if(!this.trackInsertionPreviewLine)return;if(this.trackInsertionPreviewY===null){this.trackInsertionPreviewLine.visible(!1),e&&((i=this.snapGuideLayer)==null||i.batchDraw());return}const t=((r=this.stage)==null?void 0:r.width())??0;this.trackInsertionPreviewLine.stroke(this.getSnapGuideAccentColor()),this.trackInsertionPreviewLine.strokeWidth(2),this.trackInsertionPreviewLine.points([0,this.trackInsertionPreviewY,t,this.trackInsertionPreviewY]),this.trackInsertionPreviewLine.visible(t>0),this.trackInsertionPreviewLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(n=>{var a;return(a=n.clearClipDropPreview)==null?void 0:a.call(n)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const r=this.trackManager.getTracks(),n=r.find(c=>c.role==="primary"),a=r.find(c=>c.type===e),o=[...r].reverse().find(c=>c.type===e);if((t==="before_track"||t==="after_track")&&i){const c=r.find(h=>h.id===i);if(c){const h=Ut(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+Ae(c.type)}}if(t==="top_of_type_region"&&a)return Ut(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Ut(r,o.id,this.getTrackContentTopOffset())+Ae(o.type);if(!n)return e!=="audio"?this.getTrackContentTopOffset():Ps(r,this.getTrackContentTopOffset());const l=Ut(r,n.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+Ae(n.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),r=Math.max(i,t),n=this.clampScrollLeft(this.getScrollLeftState()),a=this.clampScrollTop(this.getScrollTopState());this.setViewportMetrics(e,t,r),this.headerStage.width(e),this.timeline.resize(e),this.stage.width(e),this.stage.height(Math.max(1,i)),this.layout.bodyCanvasHost.style.height=`${r}px`,this.renderBodyBackground(e,i,!1),this.tracks.forEach(l=>l.render(!1)),this.refreshSnapGuideLine(!1),this.refreshTrackInsertionPreview(!1),(o=this.playhead)==null||o.setHeight(this.getTimeScaleHeight()+t),this.refreshScrollbarMetrics(),this.syncScrollLeft(n),this.syncScrollTop(a),this.stage.batchDraw()}renderBodyBackground(e,t,i=!0){if(!this.backgroundLayer)return;if(this.bodyBackgroundRect){this.bodyBackgroundRect.width(e),this.bodyBackgroundRect.height(t),this.bodyBackgroundRect.fill(this.config.theme.background),this.bodyBackgroundRect.stroke(this.config.theme.border),i&&this.backgroundLayer.batchDraw();return}const r=new Z.Rect({x:0,y:0,width:e,height:t,fill:this.config.theme.background,stroke:this.config.theme.border,strokeWidth:1,listening:!0,name:"timeline-body-background"});r.on("click",n=>{this.handleBodyBackgroundClick(n.evt.offsetX)}),this.bodyBackgroundRect=r,this.backgroundLayer.add(r),i&&this.backgroundLayer.batchDraw()}handleBodyBackgroundClick(e){const t=U.pixelsToTime(e-pe+this.getScrollLeftState(),this.getZoomState());this.handleTimeChange(Math.max(0,t))}handleBodyCanvasHostClick(e){if(!this.layout||e.target!==this.layout.bodyCanvasHost)return;const t=this.layout.bodyCanvasHost.getBoundingClientRect(),i=e.clientX-t.left;this.handleBodyBackgroundClick(i)}getSnapGuideAccentColor(){return this.config.theme.snapGuideLineColor||te.snapGuideLineColor}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=de.createLine([0,0,0,this.calculateTotalHeight()],this.getSnapGuideAccentColor(),e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var r,n;if(!this.snapGuideLine)return;const t=this.config.theme;if(this.snapGuideLine.stroke(this.getSnapGuideAccentColor()),this.snapGuideLine.strokeWidth(t.snapGuideLineWidth??1),this.snapGuideTime===null||!this.getEnableClipSnap()){this.snapGuideLine.visible(!1),e&&((r=this.snapGuideLayer)==null||r.batchDraw());return}const i=fe(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((n=this.snapGuideLayer)==null||n.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const n=this.getPrimaryWheelDelta(t,i);if(n===0)return;e.preventDefault(),this.handleWheelZoom(n,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const n=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(n===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+n);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===Wp)return e*16;if(t===Yp){const r=i==="x"?this.getViewportWidth():this.getViewportHeight();return e*(r||1)}return e}getPrimaryWheelDelta(e,t){return Math.abs(t)>=Math.abs(e)?t:e}isHorizontalWheelGesture(e,t){const i=Math.abs(e);if(i<.5)return!1;const r=Math.abs(t);return r<.5?!0:i>r*1.2}getHorizontalScrollDelta(e,t,i){return i&&Math.abs(t)>=Math.abs(e)?t:e}handleWheelZoom(e,t){const i=this.getZoomState(),r=Math.exp(-e*Fr.SENSITIVITY_FACTOR),n=Math.max(Me.MIN,Math.min(Me.MAX,i*r));Math.abs(n-i)<Fr.CONVERGENCE_THRESHOLD||this.setZoomCenteredOnTimelinePointer(n,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var n;const t=(n=this.layout)==null?void 0:n.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const r=e-t.left;return Math.max(0,Math.min(i,r))}play(){if(this.getPlayStateState()==="playing")return;if(this.pendingPreviewState){this.emitDiagnostic({severity:"warn",category:"ui-trigger",eventName:"play.blocked.pending-preview",message:"Play blocked by pending preview state",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()});return}if(!this.canPlay){const t=this.getClips();if(t.length>0&&this.getCurrentTime()>=kt(t)){if(this.setCurrentTime(0),!this.canPlay)return}else{O.warn("TimelineManager","Cannot play: no clips or playhead is after all clips");return}}this.refreshPlaybackAttempt("play"),this.playbackViewportFollowSuspended=!1,this.setPlayStateState("playing"),this.followPlaybackViewportIfNeeded(this.getCurrentTimeState()),this.lastUpdateTime=Date.now();const e=this.shouldUsePreviewClockPlayback();e?(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame()):this.getPreviewLoadingState().isLoading?(this.previewPlaybackSuspendedByBuffering=!0,this.previewPlaybackAutoResume=!0):this.animate(),this.emitPlayStateChangeEvent(),this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"play.started",message:"Playback started",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}),this.syncPreviewSession(!e&&this.getPreviewLoadingState().isLoading?"paused":void 0)}pause(){if(this.getPlayStateState()==="paused"){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused");return}this.setPlayStateState("paused"),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.cancelPlaybackAnimationFrame(),this.emitPlayStateChangeEvent(),this.syncPreviewSession()}togglePlay(){this.getPlayStateState()==="playing"?this.pause():this.play()}animate(){if(this.getPlayStateState()==="paused"){this.animationFrameId=null;return}if(this.shouldUsePreviewClockPlayback()){this.animationFrameId=null;return}if(this.getPreviewLoadingState().status==="loading"){!this.previewPlaybackSuspendedByBuffering&&this.getPlayStateState()==="playing"&&this.suspendPlaybackForMediaPending(),this.animationFrameId=null;return}if(this.previewPlaybackSuspendedByBuffering){this.animationFrameId=null;return}const e=Date.now(),t=e-this.lastUpdateTime;this.lastUpdateTime=e;const i=this.getCurrentTimeState()+t*this.getSpeedState();if(this.setCurrentTime(i),this.getPlayStateState()==="paused"){this.animationFrameId=null;return}this.animationFrameId=requestAnimationFrame(this.animate.bind(this))}cancelPlaybackAnimationFrame(){this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null)}emitPlayStateChangeEvent(){this.emitEvent("play_state_change",{playState:this.getPlayStateState()})}suspendPlaybackForMediaPending(){this.previewPlaybackAutoResume=!0,this.previewPlaybackSuspendedByBuffering=!0,this.cancelPlaybackAnimationFrame(),this.syncPreviewPlaybackStateIfNeeded("paused")}resumePlaybackAfterMediaPending(){this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.syncPreviewPlaybackStateIfNeeded("playing"),this.lastUpdateTime=Date.now(),this.animationFrameId||this.animate()}shouldSuspendPreviewPlaybackForLoadingState(e){return e.status==="loading"}syncPlaybackClockToPreviewLoadingState(e){if(this.shouldUsePreviewClockPlayback()){this.cancelPlaybackAnimationFrame(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,e.status==="failed"&&this.getPlayStateState()!=="paused"&&(this.setPlayStateState("paused"),this.emitPlayStateChangeEvent());return}if(this.shouldSuspendPreviewPlaybackForLoadingState(e)){if(this.previewPlaybackSuspendedByBuffering){this.syncPreviewPlaybackStateIfNeeded("paused");return}if(this.getPlayStateState()!=="playing"){this.syncPreviewPlaybackStateIfNeeded("paused");return}this.suspendPlaybackForMediaPending();return}if(!this.previewPlaybackSuspendedByBuffering)return;const t=this.previewPlaybackAutoResume&&(e.status==="ready"||e.status==="idle")&&!this.pendingPreviewState,i=this.previewPlaybackAutoResume&&e.status==="failed"&&this.getPlayStateState()!=="paused";if(this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,i){this.setPlayStateState("paused"),this.emitPlayStateChangeEvent();return}!t||this.animationFrameId||this.resumePlaybackAfterMediaPending()}clampPlaybackSeekTime(e){const t=Math.max(0,e);let i;try{const n=this.getClips();i=Array.isArray(n)?n:[]}catch{return t}if(i.length===0)return t;const r=kt(i);return!Number.isFinite(r)||r<=0?t:Math.min(t,r)}setCurrentTime(e){const t=this.clampPlaybackSeekTime(e),i=this.getTimelineCommands().setCurrentTime(t);if(!i.changed){this.updateCanPlayState(),this.pendingPreviewState&&this.pendingPreviewState.targetTime===i.nextValue&&this.syncPreviewSession();return}const r=i.nextValue;this.ensureConfigState().currentTime=r,this.syncCurrentTimeToScene(r),this.followPlaybackViewportIfNeeded(r),this.emitEvent("time_change",{time:r}),this.emitSelectionChangeEvent(),this.updateCanPlayState(),this.syncPreviewSession()}getCurrentTime(){return this.getCurrentTimeState()}setEnableClipSnap(e){this.ensureConfigState().enableClipSnap=e,e||this.updateSnapGuideLine(null),this.tracks.forEach(t=>{t.setClipSnapEnabled(e)})}getEnableClipSnap(){return!!this.ensureConfigState().enableClipSnap}setEnablePrimaryTrackMagnet(e){const t=this.getEnablePrimaryTrackMagnet();t!==e&&this.withHistoryTransaction("set_primary_track_magnet",()=>{this.setPrimaryTrackMagnetEnabledState(e),this.shouldSkipHistoryRecording()||this.getTimelineHistoryRecorder().recordSetPrimaryTrackMagnet(t,e),e&&this.withStructureSession(i=>{this.normalizePrimaryTrackInSession(i)})})}getEnablePrimaryTrackMagnet(){return this.ensureConfigState().enablePrimaryTrackMagnet!==!1}setPrimaryTrackMagnetEnabledFromHistory(e){this.setPrimaryTrackMagnetEnabledState(e)}setPrimaryTrackMagnetEnabledState(e){this.ensureConfigState().enablePrimaryTrackMagnet=e}getPrimaryTrackId(){var i,r;const e=this.getTrackCollection();if(typeof e.getPrimaryTrack=="function"){const n=e.getPrimaryTrack();return((i=n==null?void 0:n.getId)==null?void 0:i.call(n))??null}const t=Array.isArray(this.tracks)?this.tracks.find(n=>{var a;return((a=n.getRole)==null?void 0:a.call(n))==="primary"}):null;return((r=t==null?void 0:t.getId)==null?void 0:r.call(t))??null}isPrimaryTrackId(e){var r,n,a,o;if(!e)return!1;const t=this.getTrackCollection(),i=typeof t.findById=="function"?t.findById(e):null;return((r=i==null?void 0:i.getRole)==null?void 0:r.call(i))==="primary"?!0:((o=(a=(n=this.trackManager)==null?void 0:n.getTrack)==null?void 0:a.call(n,e))==null?void 0:o.role)==="primary"}shouldNormalizePrimaryTrackForTrackIds(e){return this.getEnablePrimaryTrackMagnet()&&e.some(t=>this.isPrimaryTrackId(t))}getStableStartOrderedClips(e){return e.map((t,i)=>({clip:t,index:i})).sort((t,i)=>t.clip.startTime===i.clip.startTime?t.index-i.index:t.clip.startTime-i.clip.startTime).map(t=>t.clip)}buildPrimaryTrackContinuousClips(e){if(e.length===0)return[];let t=e[0].startTime;return e.map(i=>{const r={...i,startTime:t,endTime:t+i.duration};return t+=i.duration,r})}buildPrimaryTrackMultiDragOrderedClips(e,t){return e.map((i,r)=>({clip:t.get(i.id)??i,index:r,isMoved:t.has(i.id)})).sort((i,r)=>i.clip.startTime!==r.clip.startTime?i.clip.startTime-r.clip.startTime:i.isMoved!==r.isMoved?i.isMoved?-1:1:i.index-r.index).map(i=>i.clip)}normalizePrimaryTrackInSession(e,t={}){var c;if(!this.getEnablePrimaryTrackMagnet())return[];const i=this.getPrimaryTrackId();if(!this.isPrimaryTrackId(i))return[];const r=i?this.getTrackCollection().findById(i):null,n=t.orderedClips?[...t.orderedClips]:this.getStableStartOrderedClips(((c=r==null?void 0:r.getClips)==null?void 0:c.call(r))??[]);if(n.length===0)return[];const a=this.buildPrimaryTrackContinuousClips(n),o=new Set(t.forceClipIds??[]),l=[];return a.forEach((h,d)=>{const u=n[d];if(!u)return;const p=u.startTime!==h.startTime||u.endTime!==h.endTime;p&&l.push({clipId:u.id,previousState:u,newState:h}),(p||o.has(u.id))&&e.updateClip(u.id,{startTime:h.startTime,endTime:h.endTime})}),l.length>0&&!this.shouldSkipHistoryRecording()&&this.getTimelineHistoryRecorder().recordClipUpdate(l[0].newState,void 0,l),l}setZoom(e){const t=this.getTimelineCommands().setZoom(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().zoom=i,this.syncZoomToScene(i),this.refreshScrollbarMetrics(),this.syncScrollLeft(this.getScrollLeftState()),this.emitEvent("zoom_change",{zoom:i})}setZoomCenteredOnPlayhead(e){const t=this.getZoomState(),i=this.getCurrentTimeState(),r=this.getTimelineCommands().setZoom(e);if(!r.changed)return;const n=r.nextValue;if(this.ensureConfigState().zoom=n,this.syncZoomToScene(n),this.refreshScrollbarMetrics(),this.timeline){const a=this.timeline.getScrollLeft(),o=U.timeToPixels(i,t),c=U.timeToPixels(i,n)-o+a;this.timeline.setScrollLeft(c),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())})}this.emitEvent("zoom_change",{zoom:n})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),r=this.timeline.getScrollLeft(),n=U.pixelsToTime(t-pe+r,i),a=this.getTimelineCommands().setZoom(e);if(!a.changed)return;const o=a.nextValue;this.ensureConfigState().zoom=o,this.syncZoomToScene(o),this.refreshScrollbarMetrics();const c=U.timeToPixels(n,o)-(t-pe);this.timeline.setScrollLeft(c),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),this.emitEvent("zoom_change",{zoom:o})}getZoom(){return this.getZoomState()}setSpeed(e){const t=this.getTimelineCommands().setSpeed(e);if(!t.changed)return;const i=t.nextValue;this.ensureConfigState().speed=i,this.emitEvent("speed_change",{speed:i}),this.syncPreviewSession()}getSpeed(){return this.getSpeedState()}getCanPlay(){return this.canPlay}isSourceLoading(){return this.sourceLoadingCount>0}getSourceLoadingState(){const e=this.sourceLoadingCount;return{isLoading:e>0,pending:e}}setThumbnailProvider(e){this.thumbnailProvider=e,this.thumbnailProviderVersion+=1,this.config.thumbnailProvider=e,this.clipThumbnailLoadStates.clear(),this.sourceMediaRegistry.clearThumbnailCache(),this.getClips().forEach(i=>{this.primeOrLoadClipThumbnails(i,{allowPrimeExisting:!1,force:!0})})}async loadClipThumbnails(e,t={}){if(!this.thumbnailProvider||e.type!=="video")return!1;const i=this.thumbnailProvider,r=this.buildClipThumbnailLoadSignature(e,this.thumbnailProviderVersion),n=this.clipThumbnailLoadStates.get(e.id);if((n==null?void 0:n.signature)===r){if(n.promise)return n.promise;if(n.completed&&!t.force)return!0}let a=!1;const o=this.sourceMediaRegistry.getThumbnails(this.buildClipThumbnailResourceKey(e),async()=>{const l=await Promise.resolve(i.getThumbnails(e));return Array.isArray(l)?l:[]},{force:t.force}).then(l=>{try{if(!Array.isArray(l))return!1;a=!0;const c=this.findClipById(e.id)??e;return this.isClipThumbnailLoadCurrent(e.id,r)?(this.areThumbnailArraysEqual(c.thumbnails,l)||this.updateClip(e.id,{thumbnails:l}),O.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return O.warn("TimelineManager","Error loading clip thumbnails:",{error:c,clipId:e.id}),!1}}).finally(()=>{const l=this.clipThumbnailLoadStates.get(e.id);(l==null?void 0:l.signature)===r&&(l.promise=null,l.completed=a,a||this.clipThumbnailLoadStates.delete(e.id))});this.clipThumbnailLoadStates.set(e.id,{signature:r,promise:o,completed:!1});try{return await o}catch{return!1}}async refreshClipThumbnails(e){const t=this.getClips().find(i=>i.id===e);return t?this.loadClipThumbnails(t,{force:!0}):!1}async refreshAllClipThumbnails(){const e=this.getClips();return await Promise.all(e.map(i=>this.loadClipThumbnails(i,{force:!0})))}async addClip(e){this.beginSourceLoading();try{return await this.addClipInternal(e)}finally{this.endSourceLoading()}}async addClips(e){if(e.length===0)return[];this.beginSourceLoading();try{return await this.withHistoryTransaction("add_clips",async()=>{const t=[],i=new Map,r=new Map,n=!!this.trackManager;for(const a of e){const o=n?this.resolveBatchClipConfig(a,i,r):a,l=await this.addClipInternal(o);if(t.push(l),!n||a.startTime!==void 0||a.trackId)continue;const c=this.getClips().find(d=>d.id===l),h=this.resolveTrackIdByClipId(l);!c||!h||(i.set(c.type,h),r.set(h,c.endTime))}return t})}finally{this.endSourceLoading()}}resolveBatchClipConfig(e,t,i){if(e.startTime!==void 0||e.trackId)return e;const r=e.type||"video",n=t.get(r)||this.resolveBatchAppendTrackId(r);if(!n)return e;const a=i.get(n)??this.getTrackTimelineExtentById(n);return{...e,trackId:n,startTime:a}}resolveBatchAppendTrackId(e){const t=this.getTracksSortedByOrder(),i=t.find(a=>{var o,l;return((o=a.getRole)==null?void 0:o.call(a))==="primary"&&((l=a.getTrackType)==null?void 0:l.call(a))===e});if(i)return i.getId();const r=t.find(a=>{var o;return((o=a.getTrackType)==null?void 0:o.call(a))===e});return r?r.getId():this.createTrack(e)||null}getTrackTimelineExtentById(e){const t=this.getTrackCollection().findById(e);return t?ln(t.getClips()):0}async addClipInternal(e){return this.withStructureSession(async()=>{let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.type||"video",r=i==="text",n=e.src??"",a=e.duration??(r?ra:0),o=e.name??(r?"文本":`${i}_${Date.now()}`);if(!r&&(!e.name||a<=0))throw new Error(`addClip requires name and duration for ${i} clips`);const l=r?0:e.startTimeAtSource||0,c=r?a:e.endTimeAtSource||l+a;let h=r?a:e.sourceDuration;if(!h)try{h=await U.getVideoDuration(n,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(S){O.error("TimelineManager","Failed to get video duration:",{error:S}),h=c}!r&&h>0&&this.sourceMediaRegistry.primeDuration(this.buildSourceMediaKey(e),h);let d=e.thumbnails;const u=e.id||`clip_${o}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=pn({id:u,type:i,externalId:e.externalId,src:n,name:o,isMuted:e.isMuted??!1,startTime:t,duration:a,startTimeAtSource:l,endTimeAtSource:c,sourceDuration:h,endTime:t+a,thumbnails:d,style:e.style,visualTransform:r||i==="video"?Pe(e.visualTransform):e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1,textContent:e.textContent??(r?"默认文本":void 0),textStyle:r?De(e.textStyle):void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});O.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:p.id,type:p.type,startTime:p.startTime,duration:p.duration}));const f=()=>{var k;if(e.trackId){const P=this.getTrackCollection().findById(e.trackId);if(P){if(this.registerPreviewAutoAspectRatioClip(p),(k=P.addClip)==null||k.call(P,p),Wi({applied:!0,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const x=e.trackId;this.getTimelineHistoryRecorder().recordAddClip(p,x,this.cloneTrackSnapshot(x),this.getTrackRestoreAnchor(x))},applyEffects:()=>{}}),this.shouldNormalizePrimaryTrackForTrackIds([e.trackId])){const x=this.getActiveStructureSession();x&&this.normalizePrimaryTrackInSession(x)}return this.primeOrLoadClipThumbnails(p),p.id}}const S=this.getTimelineCommands().planTrackPlacement(p,this.getTracksSortedByOrder()),T=this.getTrackCollection(),v=np({clip:p,placement:S,trackCollection:T,createTrack:this.createTrack.bind(this)});Wi({applied:v,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const P=this.resolveTrackIdByClipId(p.id);this.getTimelineHistoryRecorder().recordAddClip(p,P,P?this.cloneTrackSnapshot(P):null,P?this.getTrackRestoreAnchor(P):null)},applyEffects:()=>{}});const C=this.resolveTrackIdByClipId(p.id);if(this.shouldNormalizePrimaryTrackForTrackIds([C])){const P=this.getActiveStructureSession();P&&this.normalizePrimaryTrackInSession(P)}return this.primeOrLoadClipThumbnails(p),p.id},m=e.trackId?[e.trackId]:[this.getPrimaryTrackId()];return this.shouldNormalizePrimaryTrackForTrackIds(m)?this.withHistoryTransaction("add_primary_track_clip",f):f()})}removeClip(e){const t=this.getTimelineCommands().prepareRemoveClip(e,this.tracks);if(!t.exists)return;t.shouldClearSelection&&this.clearSelection();const i=()=>this.withStructureSession(r=>{Wi({applied:$s(this.getTrackCollection(),t,e),isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{this.getTimelineHistoryRecorder().recordRemoveClip(t.clip,t.trackId,t.trackId?this.cloneTrackSnapshot(t.trackId):null,t.trackId?this.getTrackRestoreAnchor(t.trackId):null)},applyEffects:()=>{}}),this.shouldNormalizePrimaryTrackForTrackIds([t.trackId])&&this.normalizePrimaryTrackInSession(r)});if(this.shouldNormalizePrimaryTrackForTrackIds([t.trackId])){this.withHistoryTransaction("remove_primary_track_clip",i);return}i()}removeClipsByExternalId(e){if(!e)return!1;const t=this.resolveClipIdsForExternalIdRemoval(e);if(t.length===0)return!1;const i=new Set(t);this.resetMultiDragSession(),this.shouldClearSelectionForClipIds(i)&&this.clearSelection();let r=!1;return this.withHistoryBoundary("suppressed",()=>{this.withClipRemovalBatch(()=>{for(const n of t){const a=this.getTimelineCommands().prepareRemoveClip(n,this.tracks);a.exists&&(r=$s(this.getTrackCollection(),a,n)||r)}})}),r?(Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){if(this.getTimelineCommands().findClipById(this.tracks,e)){if(this.getTrackCollection().updateClip(e,t),Object.prototype.hasOwnProperty.call(t,"thumbnails")){const i=this.findClipById(e);i&&this.markClipThumbnailLoadCompleted(i)}Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);if((i==null?void 0:i.clip.type)==="text")return;const r=i==null?void 0:i.track.splitSelectedClip;if(r){const n=()=>{this.withSplitOperation(()=>{r.call(i.track,t)})};this.shouldNormalizePrimaryTrackForTrackIds([i.trackId])?this.withHistoryTransaction("split_primary_track_clip",n):n(),Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e);if((t==null?void 0:t.clip.type)==="text")return;const i=t==null?void 0:t.track.splitSelectedClip;if(i){const r=()=>{this.withSplitOperation(()=>{i.call(t.track,e)})};this.shouldNormalizePrimaryTrackForTrackIds([t.trackId])?this.withHistoryTransaction("split_primary_track_clip",r):r(),Fi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}getClips(){return this.getTrackCollection().getAllClips()}syncTimelineClipMediaStateFromPreview(e){const t=this.getFailedPreviewClipIds(),i=new Set;e.slots.forEach(r=>{const n=r.clipId;if(!n)return;const a=this.findClipById(n);if(!a||a.type!=="video"&&a.type!=="audio")return;if(i.add(n),r.phase==="failed"&&r.role==="current"){this.applyTimelineClipMediaStatus(n,"failed","媒体丢失");return}(r.phase==="active"||r.phase==="primed")&&!!r.actualSource&&this.clearTimelineClipMediaStatus(n)}),Array.from(t).forEach(r=>{if(i.has(r))return;this.findClipById(r)||t.delete(r)})}applyTimelineClipMediaStatus(e,t,i){const r=this.getFailedPreviewClipIds(),n=this.findClipById(e);if(!n){r.delete(e);return}if(n.mediaStatus===t&&n.mediaStatusMessage===i){r.add(e);return}r.add(e),this.updateClip(e,{mediaStatus:t,mediaStatusMessage:i})}clearTimelineClipMediaStatus(e){const t=this.getFailedPreviewClipIds();if(!t.has(e))return;t.delete(e);const i=this.findClipById(e);!i||i.mediaStatus!=="failed"&&i.mediaStatusMessage==null||this.updateClip(e,{mediaStatus:"ready",mediaStatusMessage:null})}getFailedPreviewClipIds(){return this.failedPreviewClipIds||(this.failedPreviewClipIds=new Set),this.failedPreviewClipIds}getExportComposition(){var n,a,o;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(_t(e.mode)&&t===Be.width&&i===Be.height){const l=(n=this.getAutoAspectRatioClip())==null?void 0:n.clip,c=(a=l==null?void 0:l.style)==null?void 0:a.sys_width,h=(o=l==null?void 0:l.style)==null?void 0:o.sys_height;typeof c=="number"&&c>0&&typeof h=="number"&&h>0&&(t=c,i=h)}const r=un({width:t,height:i});return{width:r.width,height:r.height,aspectRatio:`${r.width}:${r.height}`,mode:e.mode}}getExportCoverUrl(e){var r;let t=null,i=null;for(const n of e)for(const a of n.clips)if(a.type==="video"){if(!t||!i){t=n,i=a;continue}if(a.startTime<i.startTime){t=n,i=a;continue}a.startTime===i.startTime&&n.order<t.order&&(t=n,i=a)}return((r=i==null?void 0:i.thumbnails)==null?void 0:r[0])||""}exportTimeline(){const e=this.getResolvedTracksSnapshot().slice().sort((i,r)=>i.order-r.order).map(i=>{const r=i.clips.map(n=>({id:n.id,type:n.type,externalId:n.externalId,src:n.src,name:n.name,isMuted:n.isMuted??!1,startTime:Math.round(n.startTime),duration:Math.round(n.duration),endTime:Math.round(n.endTime),startTimeAtSource:Math.round(n.startTimeAtSource),endTimeAtSource:Math.round(n.endTimeAtSource),sourceDuration:Math.round(n.sourceDuration),thumbnails:n.thumbnails,visualTransform:n.type==="video"||n.type==="text"?Pe(n.visualTransform):void 0,separatedAudioClipId:n.separatedAudioClipId,separatedFromVideoClipId:n.separatedFromVideoClipId,volume:n.volume??1,textContent:n.textContent,textStyle:n.textStyle,ttsSourceTextClipId:n.ttsSourceTextClipId,ttsVoiceId:n.ttsVoiceId,ttsVoiceName:n.ttsVoiceName,ttsFollowTextUpdates:n.ttsFollowTextUpdates})).sort((n,a)=>n.startTime-a.startTime);return{id:i.id,type:i.type,name:i.name||"未命名轨道",order:i.order,role:i.role??"normal",isMuted:i.isMuted??!1,clips:r}}),t=this.getExportCoverUrl(e);return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){O.error("TimelineManager","importTimeline: invalid data — composition or tracks missing");return}const t=[];await this.withHistoryBoundary("reset",async()=>{await this.withPreservedEmptyTracks(async()=>{this.stopPlaybackForImport(),this.clearAllTracksAndClips(),e.composition.mode==="manual"?this.setPreviewAspectRatio({width:e.composition.width,height:e.composition.height}):this.resetPreviewAspectRatioToAuto();const r=new Map,n=[...e.tracks].sort((c,h)=>c.order-h.order),a=this.resolveImportedTrackRoles(n);let o;for(const c of n){const h=this.createTrack(c.type,c.name,o?"after_track":void 0,o,a.get(c.id));h&&(this.muteTrack(h,c.isMuted),r.set(c.id,h),o=h)}const l=new Map;for(const c of n){const h=r.get(c.id);if(h)for(const d of c.clips)try{let u=d.separatedAudioClipId;u&&l.has(u)&&(u=l.get(u));let p=d.separatedFromVideoClipId;p&&l.has(p)&&(p=l.get(p));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:p,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,ttsSourceTextClipId:d.ttsSourceTextClipId,ttsVoiceId:d.ttsVoiceId,ttsVoiceName:d.ttsVoiceName,ttsFollowTextUpdates:d.ttsFollowTextUpdates,trackId:h},m=await this.addClip(f);l.set(d.id,m)}catch(u){t.push({clipId:d.id,error:u}),O.error("TimelineManager",`Failed to import clip ${d.id}:`,{error:u})}}})}),this.clearHistory();const i={errors:t};this.emitEvent("draft_loaded",i)}resolveImportedTrackRoles(e){const t=new Map;let i=!1;for(const n of e){const a=n.role==="primary"&&!i?"primary":"normal";a==="primary"&&(i=!0),t.set(n.id,a)}if(i)return t;const r=this.inferImportedPrimaryTrackIndex(e);return r>=0&&t.set(e[r].id,"primary"),t}inferImportedPrimaryTrackIndex(e){var t;for(let i=e.length-1;i>=0;i-=1)if(((t=e[i])==null?void 0:t.type)==="video")return i;return e.length>0?0:-1}stopPlaybackForImport(){var i;const e=this.getPlayStateState()==="playing",t=(i=this.previewSession)!=null&&i.hasPreview()?this.previewMountContainer:null;this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.previewPlaybackSuspendedByBuffering=!1,this.previewPlaybackAutoResume=!1,this.animationFrameId&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),e?this.pause():this.setPlayStateState("paused"),this.destroyPreviewSession(!0),t&&(this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t,this.previewAspectRatio)),this.syncPreviewSession()}getClipsData(){return this.getClips()}getVersion(){return Yt.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(c=>c.startTime)),r=(Math.max(...e.map(c=>c.endTime))-t)/1e3,n=((l=this.stage)==null?void 0:l.width())||0,a=n-pe*2;O.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:n,availableWidth:a}));const o=Math.min(a/r,Me.MAX);if(this.setZoom(o),this.timeline){const c=e.reduce((h,d)=>d.startTime<h.startTime?d:h);this.scrollToClip(c.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){var i;this.previewSyncInteractionMode=t,this.previewClockSeekAlignmentTargetTime=t==="seek"?this.clampPlaybackSeekTime(e):null,this.previewClockSeekAlignmentDeadlineMs=t==="seek"?Date.now()+jp:0,this.beginPendingPreview(e,t),this.setCurrentTime(e),this.getPlayStateState()==="playing"&&this.resumeWallClockPlaybackIfPreviewClockUnavailable(this.getCurrentTimeState()),t!=="scrub"&&this.emitDiagnostic({severity:"info",category:"ui-trigger",eventName:"timeline.seek",message:"Timeline seek requested",playbackAttemptId:this.playbackAttemptId,syncRequestId:((i=this.pendingPreviewState)==null?void 0:i.syncRequestId)??null,runtimeState:this.buildDiagnosticsRuntimeState(),extra:{targetTime:e}})}handleScrollChange(e){this.suspendPlaybackViewportFollowIfUserScrolling(),this.syncScrollLeft(e)}handleClipUpdate(e,t,i){this.shouldSkipHistoryRecording()||this.getTimelineHistoryRecorder().recordClipUpdate(e,t,i);const r=this.getActiveStructureSession();if(r){r.queueEvent("clip_updated",{clip:e}),r.markClipStateMutation();return}this.emitEvent("clip_updated",{clip:e});const n=this.selectedClipId===e.id;Od({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),n&&this.emitEvent("selected_clip_change",this.resolveSelectedClipSnapshot())}handleClipAdd(e){if(this.splitOperationDepth>0)return;const t=this.getActiveStructureSession();if(this.registerPreviewAutoAspectRatioClip(e),t){t.queueEvent("clip_added",{clip:e}),t.markStructureMutation();return}this.emitEvent("clip_added",{clip:e}),Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}handleClipRemove(e){if(this.clipThumbnailLoadStates.delete(e),this.splitOperationDepth>0)return;const t=this.getActiveStructureSession();if(t){t.queueEvent("clip_removed",{clipId:e}),t.markStructureMutation();return}this.emitEvent("clip_removed",{clipId:e}),!(this.clipRemovalBatchDepth>0)&&Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){Fd(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{O.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){const e=this.getClips(),t=this.getCurrentTime(),i=Nd(e,t),r=this.canPlay;this.canPlay=Gd({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:kt(e)||1,setCanPlay:n=>{this.canPlay=n},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:n=>{this.emitEvent("can_play_change",{canPlay:n})}}),r!==this.canPlay&&O.debugLazy("TimelineManager",()=>"Can play state changed",()=>({oldState:r,newState:this.canPlay}))}findClipById(e){return this.getClips().find(t=>t.id===e)}buildGeneratedAudioClipName(e){return`配音 · ${e}`}normalizeGeneratedAudioDuration(e){return!Number.isFinite(e)||e<=0?1:Math.max(1,Math.round(e))}resolveVoiceTextContent(e){return e.textContent??e.name??""}findSourceTextClipForTtsAudio(e){if(!e.ttsSourceTextClipId)return null;const t=this.findClipById(e.ttsSourceTextClipId);return(t==null?void 0:t.type)!=="text"?null:t}resolveTtsAudioVoiceGenerationSource(e){const t=this.findSourceTextClipForTtsAudio(e),i=t?this.resolveVoiceTextContent(t):"",r=typeof e.textContent=="string"?e.textContent:"",n=i.trim().length>0?i:r.trim().length>0?r:"";if(n.length===0)throw new Error("替换音色失败:缺少可用的配音文本");return{requestSourceTextClipId:(t==null?void 0:t.id)??e.ttsSourceTextClipId??e.id,persistedSourceTextClipId:t==null?void 0:t.id,text:n}}getVoiceLinkedAudioClips(e){return this.getClips().filter(t=>t.type==="audio"&&t.ttsSourceTextClipId===e)}hasVoiceLinkedAudioClipsToRegenerate(e){return this.getVoiceLinkedAudioClips(e).some(t=>t.ttsFollowTextUpdates===!0&&!!t.ttsVoiceId)}scheduleVoiceLinkedTextRegeneration(e,t,i,r){var n;this.pendingVoiceLinkedTextRegeneration&&this.pendingVoiceLinkedTextRegeneration.clipId!==e&&(this.voiceLinkedTextRegenerationTimer!==null&&(clearTimeout(this.voiceLinkedTextRegenerationTimer),this.voiceLinkedTextRegenerationTimer=null),this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{O.error("TimelineManager","Failed to flush pending linked voice regeneration",{error:a,clipId:e})})),this.voiceLinkedTextRegenerationTimer!==null&&clearTimeout(this.voiceLinkedTextRegenerationTimer),this.pendingVoiceLinkedTextRegeneration={clipId:e,originalClip:((n=this.pendingVoiceLinkedTextRegeneration)==null?void 0:n.clipId)===e?this.pendingVoiceLinkedTextRegeneration.originalClip:{...t},nextText:i,generateVoiceBatch:r},this.voiceLinkedTextRegenerationTimer=setTimeout(()=>{this.voiceLinkedTextRegenerationTimer=null,this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{O.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:a,clipId:e})})},na)}async flushPendingVoiceLinkedTextRegeneration(){const e=this.pendingVoiceLinkedTextRegeneration;if(this.pendingVoiceLinkedTextRegeneration=null,!e)return;const t=this.findClipById(e.clipId),i=(t==null?void 0:t.type)==="text"?{...t,textContent:e.nextText}:null,r=e.nextText,n=i?this.getTimelineHistoryRecorder().createClipUpdateAction(i,e.originalClip):null;await this.withHistoryTransaction("update_text_with_voice_regeneration",async()=>{n&&this.getTimelineHistoryRecorder().recordAction(n),await this.regenerateVoiceLinkedAudioClips(e.clipId,r,e.generateVoiceBatch)})}applyGeneratedAudioClipResult(e,t,i,r,n){const a=this.normalizeGeneratedAudioDuration(r.duration);this.updateClip(e,{src:r.audioSrc,name:this.buildGeneratedAudioClipName(r.voiceName),textContent:i,duration:a,startTimeAtSource:0,endTimeAtSource:a,sourceDuration:a,ttsSourceTextClipId:t,ttsVoiceId:r.voiceId,ttsVoiceName:r.voiceName,ttsFollowTextUpdates:n})}syncTextClipDurationToAudio(e,t){const i=this.normalizeGeneratedAudioDuration(t),r=this.findClipById(e);!r||r.type!=="text"||r.duration===i&&r.endTimeAtSource===i&&r.sourceDuration===i||(this.updateClip(e,{duration:i,endTimeAtSource:i,sourceDuration:i}),this.relocateClipIfNeeded(e))}doesClipOverlapOnTrack(e,t){const i=this.getTrackCollection().findById(e);if(!i)return!1;const r=t.startTime+t.duration;return i.getClips().some(n=>n.id!==t.id&&t.startTime<n.endTime&&r>n.startTime)}doesClipGroupOverlapOnTrack(e,t,i=new Set){const r=this.getTrackCollection().findById(e);if(!r)return!1;const n=r.getClips().filter(a=>!i.has(a.id));return t.some(a=>{const o=a.startTime+a.duration;return n.some(l=>l.id!==a.id&&a.startTime<l.endTime&&o>l.startTime)})}findNearestAvailableTrackForClip(e,t){const i=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),r=i.findIndex(o=>o.id===t);if(r===-1)return null;const a=i.map((o,l)=>({track:o,index:l,distance:Math.abs(l-r)})).filter(({track:o})=>o.id!==t&&o.type===e.type).sort((o,l)=>{if(o.distance!==l.distance)return o.distance-l.distance;const c=o.index>r?0:1,h=l.index>r?0:1;return c-h}).find(({track:o})=>!this.doesClipOverlapOnTrack(o.id,e));return(a==null?void 0:a.track.id)??null}resolveOverlapRelocationTargetTrackId(e,t){const i=this.findNearestAvailableTrackForClip(e,t);if(i)return i;const r=e.type==="audio"?"bottom_of_type_region":"top_of_type_region";return this.createTrack(e.type,void 0,"after_track",t)||this.createTrack(e.type,void 0,r)||null}relocateClipToAvoidOverlap(e){const t=this.findClipById(e);if(!t)return!1;const i=this.resolveTrackIdByClipId(e);if(!i||!this.doesClipOverlapOnTrack(i,t))return!1;const r=this.resolveOverlapRelocationTargetTrackId(t,i);return!r||r===i?!1:this.moveClipToTrack(e,r)}buildClipboardPasteGroups(e,t){const i=new Map,r=new Map;e.trackReferences.slice().sort((o,l)=>{var c,h;return(((c=o.trackSnapshot)==null?void 0:c.order)??Number.MAX_SAFE_INTEGER)-(((h=l.trackSnapshot)==null?void 0:h.order)??Number.MAX_SAFE_INTEGER)}).forEach((o,l)=>{var c;i.set(o.sourceTrackId,l),r.set(o.sourceTrackId,((c=o.trackSnapshot)==null?void 0:c.order)??Number.MAX_SAFE_INTEGER)});let n=i.size;const a=new Map;return e.items.forEach(o=>{const l=o.sourceTrackId??`clipboard-orphan:${o.sourceClipId}`,c=t.get(o.sourceClipId);if(!c)return;let h=a.get(l);if(!h){const d=i.get(l);h={key:l,type:o.clip.type,sourceTrackId:o.sourceTrackId,sourceTrackOrder:r.get(l)??Number.MAX_SAFE_INTEGER,sourceOrder:d??n++,sourceClipIds:[],clipIds:[]},a.set(l,h)}h.sourceClipIds.push(o.sourceClipId),h.clipIds.push(c)}),Array.from(a.values()).sort((o,l)=>o.sourceOrder-l.sourceOrder)}createTracksForTypeBoundary(e,t,i){for(let r=0;r<t;r+=1)i==="before"?this.createTrack(e,void 0,"top_of_type_region"):this.createTrack(e,void 0,"bottom_of_type_region")}selectBestClipboardPasteStartIndex(e,t){var r;if(t.length===0)return null;const i=t.filter(n=>n.newTrackCount===0).sort((n,a)=>n.score-a.score)[0];if(i)return i.startIndex;if(e==="text"){const n=t.filter(a=>a.startIndex<0).sort((a,o)=>a.newTrackCount!==o.newTrackCount?a.newTrackCount-o.newTrackCount:a.score-o.score)[0];if(n)return n.startIndex}return((r=t.slice().sort((n,a)=>n.score-a.score)[0])==null?void 0:r.startIndex)??null}buildClipboardPasteGroupPlacementClips(e,t,i,r){const n=new Map(t.items.map(a=>[a.sourceClipId,a]));return e.sourceClipIds.map(a=>{const o=n.get(a),l=i.get(a);return!o||!l?null:{id:l,startTime:r+(o.clip.startTime-t.minStartTime),duration:o.clip.duration}}).filter(a=>a!==null)}ensureClipboardPasteSourceTracks(e,t){const i=e.trackReferences.filter(r=>{var n;return((n=r.trackSnapshot)==null?void 0:n.type)===t}).sort((r,n)=>{var a,o;return(((a=r.trackSnapshot)==null?void 0:a.order)??Number.MAX_SAFE_INTEGER)-(((o=n.trackSnapshot)==null?void 0:o.order)??Number.MAX_SAFE_INTEGER)});for(const r of i)!r.trackSnapshot||r.trackSnapshot.role==="primary"||this.getTrackCollection().findById(r.sourceTrackId)||this.ensureTrackFromHistorySnapshot(r.trackSnapshot,r.trackRestoreAnchor)}resolveClipboardPasteTypeGroupAssignments(e,t,i,r){const n=new Map;if(e.length===0)return n;this.ensureClipboardPasteSourceTracks(t,e[0].type);const a=[...this.getResolvedTracksSnapshot()].filter(C=>{var k;return C.type===((k=e[0])==null?void 0:k.type)}).sort((C,k)=>C.order-k.order);if(a.length===0){const C=this.createTrack(e[0].type);C&&n.set(e[0].key,C);for(let k=1;k<e.length;k+=1){const P=this.createTrack(e[k].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");P&&n.set(e[k].key,P)}return n}const o=new Set(e.flatMap(C=>C.clipIds)),l=e.map(C=>{const k=this.buildClipboardPasteGroupPlacementClips(C,t,i,r);if(k.length===0)return null;const P=this.resolvePreferredTrackIndexForPasteGroup(C,a,Math.min(C.sourceOrder,Math.max(a.length-1,0)));return{...C,preferredTrackIndex:P,clips:k}}).filter(C=>C!==null);if(l.length===0)return n;const c=l.map(C=>C.preferredTrackIndex),h=Math.min(...c),d=a.length,u=-l.length,p=[];for(let C=u;C<=d;C+=1){let k=!0,P=0,x=0;for(let D=0;D<l.length;D+=1){const w=l[D];if(!w)continue;const A=C+D;if(P+=Math.abs(A-w.preferredTrackIndex),A<0||A>=a.length){x+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[A].id,w.clips,o)){k=!1;break}}k&&(P+=x*.1,P+=Math.abs(C-h)*sa.ANCHOR_INDEX_WEIGHT,p.push({startIndex:C,score:P,newTrackCount:x}))}const f=this.selectBestClipboardPasteStartIndex(l[0].type,p);if(f===null)return n;const m=Math.max(0,-f),S=Math.max(0,f+l.length-a.length);m>0&&this.createTracksForTypeBoundary(l[0].type,m,"before"),S>0&&this.createTracksForTypeBoundary(l[0].type,S,"after");const T=[...this.getResolvedTracksSnapshot()].filter(C=>{var k;return C.type===((k=l[0])==null?void 0:k.type)}).sort((C,k)=>C.order-k.order),v=f+m;return l.forEach((C,k)=>{const P=T[v+k];P&&n.set(C.key,P.id)}),n}resolvePreferredTrackIndexForPasteGroup(e,t,i){if(e.sourceTrackId){const r=t.findIndex(n=>n.id===e.sourceTrackId);if(r!==-1)return r}if(Number.isFinite(e.sourceTrackOrder)){const r=t.findIndex(n=>n.order>=e.sourceTrackOrder);return r!==-1?r:t.length}return i}resolveClipboardPasteTrackAssignments(e,t,i){const r=this.buildClipboardPasteGroups(e,t),n=new Map;r.forEach(o=>{const l=n.get(o.type)??[];l.push(o),n.set(o.type,l)});const a=new Map;return n.forEach(o=>{this.resolveClipboardPasteTypeGroupAssignments(o,e,t,i).forEach((c,h)=>{a.set(h,c)})}),a}relocateClipIfNeeded(e){this.relocateClipToAvoidOverlap(e)}async regenerateVoiceLinkedAudioClips(e,t,i){const r=this.getVoiceLinkedAudioClips(e).filter(c=>c.ttsFollowTextUpdates===!0&&!!c.ttsVoiceId);if(r.length===0)return;const n=r.map((c,h)=>({requestId:`regen:${c.id}:${Date.now()}:${h}`,sourceTextClipId:e,targetAudioClipId:c.id,text:t,voiceId:c.ttsVoiceId,followTextUpdates:!0,mode:"replace"})),a=await i(n),o=new Map(a.map(c=>[c.requestId,c]));let l=0;n.forEach(c=>{const h=o.get(c.requestId);!h||!c.targetAudioClipId||(this.applyGeneratedAudioClipResult(c.targetAudioClipId,e,t,h,c.followTextUpdates),this.relocateClipIfNeeded(c.targetAudioClipId),l=Math.max(l,this.normalizeGeneratedAudioDuration(h.duration)))}),l>0&&this.syncTextClipDurationToAudio(e,l),this.handleClipChange()}getSelectedTextClipsForVoiceGeneration(e){if(e.type!=="text")return[e];const t=this.getSelectedClips().filter(i=>i.type==="text");return t.length===0?[e]:t.some(i=>i.id===e.id)?t:[e]}getSelectedTtsAudioClipsForVoiceGeneration(e){if(e.type!=="audio"||!Le(e))return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(n=>Le(n))))return[e];const r=t.filter(n=>Le(n));return r.some(n=>n.id===e.id)?r:[e]}async handleVoiceGenerateAction(e,t,i,r,n){if(t.type==="text"){const c=this.getSelectedTextClipsForVoiceGeneration(t),h=Date.now(),d=c.map((f,m)=>({requestId:`create:${f.id}:${i.id}:${h}:${m}`,sourceTextClipId:f.id,text:f.textContent??f.name??"",voiceId:i.id,followTextUpdates:r,mode:"create"}));e.setPreferredTab("voice");const u=[];if(await this.withHistoryTransaction("generate_voice_from_text_clips",async()=>{const f=await n(d),m=new Map(f.map(S=>[S.requestId,S]));for(const S of d){const T=m.get(S.requestId);if(!T)continue;const v=c.find(x=>x.id===S.sourceTextClipId);if(!v)continue;const C=this.normalizeGeneratedAudioDuration(T.duration),k=v.textContent??v.name??"";this.syncTextClipDurationToAudio(v.id,C);const P=await this.addClip({type:"audio",src:T.audioSrc,name:this.buildGeneratedAudioClipName(T.voiceName),textContent:k,startTime:v.startTime,duration:C,startTimeAtSource:0,endTimeAtSource:C,sourceDuration:C,ttsSourceTextClipId:v.id,ttsVoiceId:T.voiceId,ttsVoiceName:T.voiceName,ttsFollowTextUpdates:r});u.push(P)}if(u.length===0)throw new Error("生成音频失败:未返回音频结果")}),u.length===1){this.scrollToClip(u[0],{selectClip:!0,setCurrentTime:!0});return}const p=u[0]??null;this.scrollToClip(p,{setCurrentTime:!0}),this.setSelection(u,{preferredPrimaryClipId:p});return}if(t.type!=="audio"||!Le(t))return;const a=this.getSelectedTtsAudioClipsForVoiceGeneration(t),o=Date.now(),l=a.map((c,h)=>{const d=this.resolveTtsAudioVoiceGenerationSource(c);return{requestId:`replace:${c.id}:${i.id}:${o}:${h}`,sourceTextClipId:d.requestSourceTextClipId,targetAudioClipId:c.id,text:d.text,voiceId:i.id,followTextUpdates:r,mode:"replace"}});e.setPreferredTab("voice"),await this.withHistoryTransaction("replace_voice_for_tts_audio_clips",async()=>{const c=await n(l),h=new Map(c.map(u=>[u.requestId,u])),d=new Map;if(l.some(u=>!h.has(u.requestId)))throw new Error("替换音色失败:未返回音频结果");for(const u of l){const p=h.get(u.requestId);if(!p||!u.targetAudioClipId)continue;const f=a.find(S=>S.id===u.targetAudioClipId);if(!f)continue;const m=this.resolveTtsAudioVoiceGenerationSource(f);if(this.applyGeneratedAudioClipResult(u.targetAudioClipId,m.persistedSourceTextClipId,m.text,p,r),this.relocateClipIfNeeded(u.targetAudioClipId),m.persistedSourceTextClipId){const S=d.get(m.persistedSourceTextClipId)??0;d.set(m.persistedSourceTextClipId,Math.max(S,p.duration))}}d.forEach((u,p)=>{this.syncTextClipDurationToAudio(p,u)}),this.handleClipChange()})}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{O.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){O.warn("TimelineManager","Error loading clip thumbnails:",{error:i,clipId:e.id})}}markClipThumbnailLoadCompleted(e){return Array.isArray(e.thumbnails)?(this.sourceMediaRegistry.primeThumbnails(this.buildClipThumbnailResourceKey(e),e.thumbnails),this.clipThumbnailLoadStates.set(e.id,{signature:this.buildClipThumbnailLoadSignature(e),promise:null,completed:!0}),!0):!1}buildClipThumbnailLoadSignature(e,t=this.thumbnailProviderVersion){return[t,e.type,e.src,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}buildSourceMediaKey(e){return Or.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return Or.buildThumbnailKey({...e,externalId:e.externalId})}isClipThumbnailLoadCurrent(e,t){var i;return((i=this.clipThumbnailLoadStates.get(e))==null?void 0:i.signature)===t}areThumbnailArraysEqual(e,t){return!e||e.length!==t.length?!1:e.every((i,r)=>i===t[r])}handleClipSplit(e,t){const i=this.resolveTrackIdByClipId(e.id),r=i?this.cloneTrackSnapshot(i):null,n=i?this.getTrackRestoreAnchor(i):null;this.withStructureSession(a=>{$d({clip1:e,clip2:t,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordSplitClip:(o,l)=>{this.getTimelineHistoryRecorder().recordSplitClip(o,l,i,r,n)},emitClipUpdated:o=>{this.emitEvent("clip_updated",{clip:o})},emitClipAdded:o=>{this.emitEvent("clip_added",{clip:o})},applyEffects:()=>Bi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}),this.shouldNormalizePrimaryTrackForTrackIds([i])&&this.normalizePrimaryTrackInSession(a)})}handleClipSelect(e){const t=Hd(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),O.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){O.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new As(t.createHistoryExecutionTarget()).executeUndo(e)})})}handleActionRedo(e){O.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new As(t.createHistoryExecutionTarget()).executeRedo(e)})})}on(e,t){this.getEventDispatcher().on(e,t)}off(e,t){this.getEventDispatcher().off(e,t)}emitEvent(e,t){this.getEventDispatcher().emit(e,t)}emitSelectedClipChangeIfNeeded(){this.lastSelectedClipId=tp({lastSelectedClipId:this.lastSelectedClipId,resolveSelectedClip:()=>this.resolveSelectedClipSnapshot(),emitSelectedClipChange:e=>this.emitEvent("selected_clip_change",e)})}beginSourceLoading(){this.sourceLoadingCount+=1}endSourceLoading(){this.sourceLoadingCount=Math.max(0,this.sourceLoadingCount-1)}handlePrimaryTrackMagnetMove(e,t,i,r){if(!this.getEnablePrimaryTrackMagnet()||!this.isPrimaryTrackId(r))return!1;const n=this.getStableStartOrderedClips(i),a=n.findIndex(l=>l.startTime>=e.startTime),o=[...n];return o.splice(a===-1?o.length:a,0,e),this.withHistoryTransaction("move_primary_track_clips",()=>{this.withStructureSession(l=>{this.normalizePrimaryTrackInSession(l,{orderedClips:o,forceClipIds:[e.id]})})}),!0}handleClipOverlap(e,t,i){var h,d,u,p;O.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const r=this.getTrackCollection();if(!r.findById(t))return;const n=e.type,a=this.trackManager.getTracksByType(n).length+1,o=`${Zp(n)}轨道 ${a}`,l=this.createTrack(n,o);if(!l)return;const c=((d=(h=r.findById(l))==null?void 0:h.getId)==null?void 0:d.call(h))||((p=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:p.call(u))||l;this.moveClipToTrackWithHistorySnapshot(e.id,c,i??null,e),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const r=this.resolveCrossTrackPreviewDestination(e,t,i);return r.status==="existing_track"?(this.showClipDropPreview(e,r.targetTrackId),r.targetTrackId===i?"self":"external"):r.status==="new_track_insertion"?(this.showTrackInsertionPreview(r.trackType,r.insertionPlacement,r.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,r){O.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:r}));const n=this.resolveCrossTrackMoveDestination(e,i,r);return n.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):n.status==="same_track"?(O.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(O.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:n.targetTrackId})),this.showClipDropPreview(e,n.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,n.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}getRenderedHeight(){return this.getTimeScaleHeight()+this.calculateTotalHeight()+rn}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.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),t&&this.setCurrentTime(e))}notifySelectionChange(){const e=this.getSelectedClipIds();this.getTimelinePresentationAdapter().syncSelection(this.getTrackCollection(),e)}syncPrimarySelectionFromSelectionStore(){var t,i,r,n;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((n=(r=this.selectionStore)==null?void 0:r.getSelectedClipId)==null?void 0:n.call(r))??null;this.selectedClipId=e}getOrderedSelectionClipIds(e,t){const i=Array.from(new Set(e));if(i.length<=1)return i;const r=t&&i.includes(t)&&t||this.selectedClipId&&i.includes(this.selectedClipId)&&this.selectedClipId||i[0]||null;return r?[r,...i.filter(n=>n!==r)]:i}setSelection(e,t={}){this.resetMultiDragSession();const i=this.getOrderedSelectionClipIds(e,t.preferredPrimaryClipId);this.selectionStore.setSelection(i),this.syncPrimarySelectionFromSelectionStore(),this.notifySelectionChange(),this.emitSelectionChangeEvent(),t.selectedClipEventClip&&this.emitEvent("clip_selected",{clip:t.selectedClipEventClip}),this.emitSelectedClipChangeIfNeeded(),this.syncPreviewSession()}selectClip(e,t){var r;const i=t||((r=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:r.clip);this.setSelection([e],{preferredPrimaryClipId:e,selectedClipEventClip:i??null})}clearSelection(){this.setSelection([])}getSelectedClipIds(){var e,t;return((t=(e=this.selectionStore)==null?void 0:e.getSelectedClipIds)==null?void 0:t.call(e))??(this.selectedClipId?[this.selectedClipId]:[])}getPrimarySelectedClipId(){return this.getSelectedClipIds()[0]??null}addToSelection(e){this.setSelection([...this.selectionStore.getSelectedClipIds(),e],{preferredPrimaryClipId:this.selectedClipId??e})}removeFromSelection(e){this.setSelection(this.selectionStore.getSelectedClipIds().filter(t=>t!==e))}toggleSelection(e){const t=this.selectionStore.getSelectedClipIds(),i=t.includes(e);this.setSelection(i?t.filter(r=>r!==e):[...t,e],{preferredPrimaryClipId:i?void 0:e})}isClipSelected(e){return this.selectionStore.isSelected(e)}deleteSelectedClips(){this.deleteSelectedClipsWithHistoryLabel("delete_selected_clips")}copySelectedClips(){const e=this.captureSelectedClipsToClipboard();return e?(this.clipClipboard=e,!0):!1}cutSelectedClips(){return this.copySelectedClips()?this.deleteSelectedClipsWithHistoryLabel("cut_selected_clips"):!1}async pasteClipboardClips(){if(!this.clipClipboard||this.clipClipboard.items.length===0)return!1;const e=this.clipClipboard,t=new Map;for(const o of e.items)t.set(o.sourceClipId,this.generateClipId(o.clip.name));const i=this.resolveClipboardPasteTrackAssignments(e,t,this.getCurrentTime()),r=[],n=this.getCurrentTime();if(await this.withHistoryTransaction("paste_clipboard_clips",async()=>{for(const o of e.items){const l=this.buildClipboardPasteClipConfig(o,n,t),c=o.sourceTrackId??`clipboard-orphan:${o.sourceClipId}`,h=i.get(c)??this.resolveClipboardPasteTrackId(o,l,i),d=t.get(o.sourceClipId);if(!d)continue;const u=await this.addClipInternal({...l,id:d,...h?{trackId:h}:{}});(this.getClips().find(f=>f.id===u)??null)&&r.push(u)}}),r.length===0)return!1;const a=e.primaryClipId?t.get(e.primaryClipId)??r[0]??null:r[0]??null;return this.setSelection(r,{preferredPrimaryClipId:a}),!0}deleteSelectedClipsWithHistoryLabel(e){this.resetMultiDragSession();const t=this.selectionStore.getSelectedClipIds();return t.length===0?!1:(this.clearSelection(),this.withHistoryTransaction(e,()=>{for(const i of t)this.removeClip(i)}),this.emitSelectionChangeEvent(),!0)}captureSelectedClipsToClipboard(){const e=this.getSelectedClipIds();if(e.length===0)return null;const t=new Map,i=e.map(r=>{const n=this.getTimelineCommands().prepareRemoveClip(r,this.tracks);return!n.exists||!n.clip?null:(n.trackId&&!t.has(n.trackId)&&t.set(n.trackId,{sourceTrackId:n.trackId,trackSnapshot:this.cloneTrackSnapshot(n.trackId),trackRestoreAnchor:this.getTrackRestoreAnchor(n.trackId)}),{sourceClipId:r,sourceTrackId:n.trackId,clip:this.cloneClipForClipboard(n.clip)})}).filter(r=>r!==null);return i.length===0?null:{items:i,trackReferences:Array.from(t.values()),minStartTime:Math.min(...i.map(r=>r.clip.startTime)),primaryClipId:this.getPrimarySelectedClipId()}}cloneClipForClipboard(e){return{...e,thumbnails:e.thumbnails?[...e.thumbnails]:void 0,style:Js(e.style),visualTransform:e.visualTransform?{...e.visualTransform}:void 0,textStyle:e.textStyle?{...e.textStyle}:void 0}}buildClipboardPasteClipConfig(e,t,i){const r=e.clip,n=r.separatedAudioClipId?i.get(r.separatedAudioClipId)??void 0:void 0,a=r.separatedFromVideoClipId?i.get(r.separatedFromVideoClipId)??void 0:void 0,o=r.ttsSourceTextClipId?i.get(r.ttsSourceTextClipId)??void 0:void 0,l=t+(r.startTime-this.clipClipboard.minStartTime);return{type:r.type,externalId:r.externalId,src:r.src,name:r.name,isMuted:r.isMuted,startTime:l,duration:r.duration,startTimeAtSource:r.startTimeAtSource,endTimeAtSource:r.endTimeAtSource,sourceDuration:r.sourceDuration,thumbnails:r.thumbnails?[...r.thumbnails]:void 0,style:Js(r.style),visualTransform:r.visualTransform?{...r.visualTransform}:void 0,separatedAudioClipId:n,separatedFromVideoClipId:a,volume:r.volume,textContent:r.textContent,textStyle:r.textStyle?{...r.textStyle}:void 0,ttsSourceTextClipId:o,ttsVoiceId:r.ttsVoiceId,ttsVoiceName:r.ttsVoiceName,ttsFollowTextUpdates:r.ttsFollowTextUpdates}}resolveClipboardPasteTrackId(e,t,i){var l,c;const r=e.sourceTrackId??`clipboard-orphan:${e.sourceClipId}`,n=i.get(r);if(n)return n;if(e.sourceTrackId){const h=this.getTrackCollection().findById(e.sourceTrackId);if(h&&((l=h.getTrackType)==null?void 0:l.call(h))===t.type)return i.set(r,e.sourceTrackId),e.sourceTrackId;const d=((c=this.clipClipboard)==null?void 0:c.trackReferences.find(u=>u.sourceTrackId===e.sourceTrackId))??null;if(d!=null&&d.trackSnapshot&&d.trackSnapshot.role!=="primary"){const u=this.ensureTrackFromHistorySnapshot(d.trackSnapshot,d.trackRestoreAnchor);if(u)return i.set(r,u),u}}const a=this.getTimelineCommands().planTrackPlacement({type:t.type||"video",startTime:t.startTime??this.getCurrentTime(),duration:t.duration??0},this.getTracksSortedByOrder()),o=a.status==="use_existing_track"?a.trackId:this.createTrack(a.trackType,void 0,a.insertionPlacement);return o?(i.set(r,o),o):null}generateClipId(e){return`clip_${e}_${Date.now()}_${Math.random().toString(36).slice(2,11)}`}separateSelectedClipsAudio(){this.applySelectedClipAudioAction("separate")}selectAllClips(){this.setSelection(this.tracks.flatMap(e=>e.getClips().map(t=>t.id)),{preferredPrimaryClipId:this.selectedClipId})}emitSelectionChangeEvent(){this.emitEvent("selection_change",this.resolveSelectionChangeData())}scrollToClip(e,t={}){const{selectClip:i=!1,setCurrentTime:r=!1}=t,n=this.getClips().find(a=>a.id===e);!n||!this.timeline||(this.timeline.scrollToClip(n),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),r&&this.setCurrentTime(n.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}canCopySelectedClips(){return this.getSelectedClipIds().length>0}canCutSelectedClips(){return this.canCopySelectedClips()}canPasteClipboardClips(){var e;return(((e=this.clipClipboard)==null?void 0:e.items.length)??0)>0}canDeleteSelectedClips(){return this.getSelectedClipIds().length>0}canSplitSelectedClip(){const e=this.resolveSelectedClipAtTime(this.getCurrentTime());return!!e&&e.clip.type!=="text"}getSelectedClipAudioAction(){const e=this.getSelectedClips().filter(r=>r.type==="video");return e.length===0?null:e.some(r=>this.canSeparateClipAudio(r.id))?"separate":e.some(r=>this.canRestoreClipAudio(r.id))?"restore":null}canToggleSelectedClipsAudio(){return this.getSelectedClipAudioAction()!==null}async toggleSelectedClipsAudio(){const e=this.getSelectedClipAudioAction();return e?this.applySelectedClipAudioAction(e):!1}getCurrentActiveClips(){return this.buildPlaybackPlan().activeClips}getCurrentPlaybackPlan(){return this.buildPlaybackPlan()}getPlaybackPlanAtTime(e){return this.buildPlaybackPlan(e)}getActiveClipsAtTime(e){return this.buildPlaybackPlan(e).activeClips}attachPreview(e){const t=e instanceof HTMLElement?{container:e}:e;t.aspectRatio&&(this.previewAspectRatio=je({mode:t.aspectRatio.mode??(t.aspectRatio.width&&t.aspectRatio.height?"manual":this.previewAspectRatio.mode),width:t.aspectRatio.width??this.previewAspectRatio.width,height:t.aspectRatio.height??this.previewAspectRatio.height})),this.previewAspectRatio=this.getPreviewRuntimeController().attachPreview(t.container,this.previewAspectRatio),this.emitDiagnostic({severity:"info",category:"session",eventName:"preview.mount.attached",message:"Preview mount attached",playbackAttemptId:this.playbackAttemptId,previewBackend:this.getPreviewBackendType(),runtimeState:this.buildDiagnosticsRuntimeState(),extra:{hasAspectRatioOverride:!!t.aspectRatio}}),this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}detachPreview(){this.getPreviewRuntimeController().detachPreviewSession()&&(this.clearPendingPreviewState(),this.resetPreviewRuntimeState(),this.emitDiagnostic({severity:"info",category:"session",eventName:"preview.mount.detached",message:"Preview mount detached",playbackAttemptId:this.playbackAttemptId,runtimeState:this.buildDiagnosticsRuntimeState()}))}attachClipConfig(e,t={}){const i=new So,r=t.generateVoiceBatch,n=r,a=r?async c=>{i.setVoiceGenerationBusy(!0);try{return await r(c)}finally{i.setVoiceGenerationBusy(!1)}}:void 0;i.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),getSelectedClips:()=>this.getSelectedClips(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c),u=d?{...d}:null,p=typeof h.textContent=="string"?h.textContent:null;if(n&&(u==null?void 0:u.type)==="text"&&p!==null&&p!==u.textContent&&this.hasVoiceLinkedAudioClipsToRegenerate(c)&&(u==null?void 0:u.type)==="text"){this.withHistoryBoundary("suppressed",()=>{this.updateClip(c,h)}),this.handleClipChange(),this.scheduleVoiceLinkedTextRegeneration(c,u,p,n);return}this.updateClip(c,h),this.handleClipChange()},onGenerateVoice:async(c,h,d)=>{if(!a)throw new Error("未配置音色生成回调");await this.handleVoiceGenerateAction(i,c,h,d,a)}});const o=()=>i.updateFromExternal(),l=(c,h)=>{var p;const d=new Set(this.getSelectedClipIds()),u=this.getPrimarySelectedClip();d.size===0&&(u!=null&&u.id)&&d.add(u.id),(p=h==null?void 0:h.clip)!=null&&p.id&&d.has(h.clip.id)&&i.updateFromExternal()};return this.on("selected_clip_change",o),this.on("clip_updated",l),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",o),this.off("clip_updated",l),i.destroy()}),i.update(),i}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return je(this.previewAspectRatio)}getDiagnosticsSnapshot(){return this.diagnostics.getSnapshot()}subscribeDiagnostics(e){return this.diagnostics.subscribe(e)}getDiagnosticsLiveSnapshot(e){return this.diagnostics.getLiveSnapshot(void 0,e)}subscribeDiagnosticsLive(e,t){return this.diagnostics.subscribeLive(e,t)}exportDiagnosticsPackage(){return this.diagnostics.exportPackage()}clearDiagnostics(e=!0){this.diagnostics.clear(e),e&&this.diagnostics.startSession({packageName:Yt.name,packageVersion:Yt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=je({mode:"manual",width:Math.max(1,e.width),height:Math.max(1,e.height)}),(t=this.previewSession)==null||t.applyAspectRatio(this.previewAspectRatio),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}resetPreviewAspectRatioToAuto(){var e,t;this.previewAspectRatio={...Be},(e=this.previewSession)==null||e.applyAspectRatio(this.previewAspectRatio),this.previewAspectRatio=((t=this.previewSession)==null?void 0:t.getAspectRatio())||this.previewAspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()})}removeSelectedClip(){return this.removeSelectedClips()}removeSelectedClips(){return this.canDeleteSelectedClips()?(this.deleteSelectedClips(),!0):!1}canSeparateClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!t.separatedAudioClipId}canRestoreClipAudio(e){const t=this.getClips().find(i=>i.id===e);return!!t&&t.type==="video"&&!!t.separatedAudioClipId}pausePlaybackForAudioSeparation(){var t,i,r;(((i=(t=this.timelineStore)==null?void 0:t.getPlayState)==null?void 0:i.call(t))??((r=this.config)==null?void 0:r.playState))==="playing"&&this.pause()}resolvePreferredSeparatedAudioTrackId(e,t){var l;if(!this.trackManager||typeof this.trackManager.getTracks!="function")return null;const i=this.resolveTrackIdByClipId(e);if(!i)return null;const r=[...this.getResolvedTracksSnapshot()].sort((c,h)=>c.order-h.order),n=r.findIndex(c=>c.id===i);if(n===-1)return null;const a=t.startTime+t.duration,o=r.map((c,h)=>({track:c,index:h})).filter(({track:c})=>c.type==="audio").filter(({track:c})=>!c.clips.some(h=>t.startTime<h.endTime&&a>h.startTime));return o.length===0?null:(o.sort((c,h)=>{const d=Math.abs(c.index-n)-Math.abs(h.index-n);return d!==0?d:c.index-h.index}),((l=o[0])==null?void 0:l.track.id)??null)}async separateClipAudio(e){if(!this.canSeparateClipAudio(e))return null;this.pausePlaybackForAudioSeparation();const t=this.getClips().find(c=>c.id===e);if(!t||t.type!=="video")return null;const i=this.resolvePreferredSeparatedAudioTrackId(t.id,{startTime:t.startTime,duration:t.duration});let r=null;const n=!this.shouldSkipHistoryRecording();if(await this.withHistoryBoundary("suppressed",async()=>{if(r=await this.addClip({type:"audio",src:t.src,name:t.name,startTime:t.startTime,duration:t.duration,startTimeAtSource:t.startTimeAtSource,endTimeAtSource:t.endTimeAtSource,sourceDuration:t.sourceDuration,separatedFromVideoClipId:t.id,isMuted:!1,volume:t.volume??1,trackId:i??void 0}),!r)return null;this.updateClip(e,{isMuted:!0,separatedAudioClipId:r})}),!r)return null;const a=this.getClips().find(c=>c.id===e),o=this.getClips().find(c=>c.id===r)??null,l=this.resolveTrackIdByClipId(r);return a?(n&&this.getTimelineHistoryRecorder().recordSeparateClipAudio(t,a,o,l),r):null}restoreClipAudio(e){if(!this.canRestoreClipAudio(e))return!1;const t=this.getClips().find(l=>l.id===e);if(!t||t.type!=="video")return!1;const i=t.separatedAudioClipId??null,r=i?this.getClips().find(l=>l.id===i)??null:null,n=i?this.resolveTrackIdByClipId(i):null,a=!this.shouldSkipHistoryRecording();this.withHistoryBoundary("suppressed",()=>{this.updateClip(e,{isMuted:!1,separatedAudioClipId:void 0})});const o=this.getClips().find(l=>l.id===e);return o?(a&&this.getTimelineHistoryRecorder().recordRestoreClipAudio(t,o,r,n),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(n=>n.type==="video"),i=e==="separate"?t.filter(n=>this.canSeparateClipAudio(n.id)):t.filter(n=>this.canRestoreClipAudio(n.id));if(i.length===0)return!1;if(i.length===1){const[n]=i;return e==="separate"?!!await this.separateClipAudio(n.id):this.restoreClipAudio(n.id)}let r=0;return await this.withHistoryTransaction(`selected_clips_audio_${e}`,async()=>{if(e==="restore"){for(const n of i)this.restoreClipAudio(n.id)&&(r+=1);return}for(const n of i)await this.separateClipAudio(n.id)&&(r+=1)}),r>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,r=null){const n=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(n.status==="missing_source_track")return O.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(n.status==="noop")return O.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(n.status==="missing_target_track")return O.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>{var l,c,h;return{targetTrackType:(c=(l=this.getTrackCollection().findById(t))==null?void 0:l.getTrackType)==null?void 0:c.call(l),clipType:(h=this.getTimelineCommands().findClipById(this.tracks,e))==null?void 0:h.clip.type}}),!1;if(n.status!=="ready")return!1;const a=this.shouldNormalizePrimaryTrackForTrackIds([n.sourceTrackId,n.targetTrackId]),o=()=>this.withStructureSession(l=>{const{sourceTrackId:c,targetTrackId:h}=n,d=i?{...i}:{...n.clip},u=r?{...r}:{...n.clip},p=this.cloneTrackSnapshot(c),f=this.cloneTrackSnapshot(h),m=this.getTrackRestoreAnchor(c),S=this.getTrackRestoreAnchor(h),T=sp({command:{...n,clip:u},trackCollection:this.getTrackCollection()}),v=this.getClips().find(C=>C.id===e)??null;return zd({applied:T,clipId:e,sourceTrackId:c,targetTrackId:h,clipBefore:d,clipAfter:v??d,sourceTrackSnapshot:p,targetTrackSnapshot:f,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordMoveClipBetweenTracks:(C,k,P,x,D,w,A)=>{this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks(C,k,P,x,D,w,A,m,S)},applyEffects:()=>{}})?(a&&this.normalizePrimaryTrackInSession(l),this.clearAllTrackDropPreviews(),!0):!1});return a?this.withHistoryTransaction("move_primary_track_clip_between_tracks",o):o()}getTrackTotalDuration(){return Ns(this.getClips())}async getResourceCacheStats(){return this.resourceCacheManager?{enabled:!0,...await this.resourceCacheManager.getStats()}:{enabled:!1,entryCount:0,totalBytes:0,maxTotalBytes:0}}async cleanupResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.cleanupExpired())}async clearResourceCache(){var e;await((e=this.resourceCacheManager)==null?void 0:e.clear())}destroy(){var t,i,r,n,a,o,l,c,h,d,u,p,f,m,S;this.mountManager.destroyAll(),this.animationFrameId&&cancelAnimationFrame(this.animationFrameId),this.clearPendingPreviewState(),(t=this.resourceCacheManager)==null||t.cleanupExpired().catch(()=>{}),this.previewSession&&(this.previewSession.hasPreview()?(this.detachPreview(),this.previewSession=void 0):this.destroyPreviewSession(!0)),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.trackInfoPanelController.destroy(),(i=this.layout)==null||i.bodyViewport.removeEventListener("scroll",this.bodyViewportScrollListener),(a=(r=this.layout)==null?void 0:(n=r.bodyCanvasHost).removeEventListener)==null||a.call(n,"click",this.bodyCanvasHostClickListener);const e=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);e&&this.stageMouseDownListener&&((c=e.removeEventListener)==null||c.call(e,"mousedown",this.stageMouseDownListener)),(d=(h=this.rootContainer)==null?void 0:h.removeEventListener)==null||d.call(h,"wheel",this.rootWheelListener),(u=this.horizontalScrollbar)==null||u.destroy(),(p=this.verticalScrollbar)==null||p.destroy(),(f=this.playhead)==null||f.destroy(),(m=this.timeline)==null||m.destroy(),(S=this.stage)==null||S.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new Zs),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new Qu({root:this.rootContainer,config:this.config.keyboardShortcuts,callbacks:{togglePlay:()=>this.togglePlay(),deleteSelectedClips:()=>{this.removeSelectedClips()},copySelectedClips:()=>{this.copySelectedClips()},cutSelectedClips:()=>{this.cutSelectedClips()},pasteClipboardClips:()=>this.pasteClipboardClips(),toggleSelectedClipsAudio:()=>this.toggleSelectedClipsAudio(),splitCurrentClip:()=>this.splitCurrentClip(),undo:()=>this.undo(),redo:()=>this.redo(),canDeleteSelectedClips:()=>this.canDeleteSelectedClips(),canCopySelectedClips:()=>this.canCopySelectedClips(),canCutSelectedClips:()=>this.canCutSelectedClips(),canPasteClipboardClips:()=>this.canPasteClipboardClips(),canSplitSelectedClip:()=>this.canSplitSelectedClip(),canToggleSelectedClipsAudio:()=>this.canToggleSelectedClipsAudio()}}),this.keyboardShortcutsController.init(),this.mountManager.register("keyboardShortcuts",()=>{var t;(t=this.keyboardShortcutsController)==null||t.destroy(),this.keyboardShortcutsController=null}))}clearHistory(){this.history.clear()}handleClipChange(){this.syncPreviewSession()}withClipRemovalBatch(e){this.clipRemovalBatchDepth=(this.clipRemovalBatchDepth??0)+1;try{return e()}finally{this.clipRemovalBatchDepth=Math.max(0,(this.clipRemovalBatchDepth??1)-1)}}withSplitOperation(e){this.splitOperationDepth=(this.splitOperationDepth??0)+1;try{return e()}finally{this.splitOperationDepth=Math.max(0,(this.splitOperationDepth??1)-1)}}resolveClipIdsForExternalIdRemoval(e){const t=this.getClips(),i=new Map(t.map(a=>[a.id,a])),r=new Set,n=t.filter(a=>a.externalId===e).map(a=>a.id);for(let a=0;a<n.length;a+=1){const o=n[a];if(r.has(o))continue;r.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!r.has(l.separatedAudioClipId)&&n.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!r.has(l.separatedFromVideoClipId)&&n.push(l.separatedFromVideoClipId))}return t.filter(a=>r.has(a.id)).map(a=>a.id)}shouldClearSelectionForClipIds(e){return this.selectedClipId&&e.has(this.selectedClipId)?!0:this.selectionStore.getSelectedClipIds().some(t=>e.has(t))}resolveSelectedClipAtTime(e){var i;const t=((i=this.selectionStore)==null?void 0:i.getSelectedClipIds())??[];for(const r of t){const n=this.getTimelineCommands().findClipById(this.tracks,r),a=n==null?void 0:n.clip;if(a&&e>=a.startTime&&e<a.endTime)return n}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{return e.isFinal?this.withHistoryTransaction("move_selected_clips",()=>this.finalizeMultiDragCrossTrack(t,e)?!0:this.finalizeMultiDragSameTrack(t,e)):(this.syncMultiDragOverlayState(t,e.crossTrackOffsetY!==0),this.syncMultiDragPeerClips(t,e,!1),e.crossTrackOffsetY!==0?this.elevateMultiDragTrackGroups(t,e.currentTrackId):this.normalizeTrackGroupStackOrder(),this.previewMultiDragCrossTrack(t,e))}finally{e.isFinal&&(this.syncMultiDragOverlayState(t,!1),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession())}}normalizeTrackGroupStackOrder(){this.tracks.forEach((e,t)=>{var i;(i=e.setTrackStackOrder)==null||i.call(e,t)})}elevateMultiDragTrackGroups(e,t){var o,l,c;const i=this.resolveMultiDragSessionTrackIds(e);if(i.length<=1)return;const r=i.indexOf(t);r>=0&&(i.splice(r,1),i.push(t));const n=new Set(i);let a=0;for(const h of this.tracks){const d=(o=h.getId)==null?void 0:o.call(h);!d||n.has(d)||(l=h.setTrackStackOrder)==null||l.call(h,a++)}for(const h of i){const d=this.getTrackCollection().findById(h);(c=d==null?void 0:d.setTrackStackOrder)==null||c.call(d,a++)}}resolveMultiDragSessionTrackIds(e){var i;const t=new Set;for(const r of this.tracks){const n=(i=r.getId)==null?void 0:i.call(r);if(!n)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===n})&&t.add(n)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const r of e.selectedClipIds){const n=e.clips.get(r);if(!n)continue;const a=i.get(n.trackId);a?a.push(r):i.set(n.trackId,[r])}i.forEach((r,n)=>{var o;const a=this.getTrackCollection().findById(n);(o=a==null?void 0:a.setClipsDragOverlayActive)==null||o.call(a,r,t)})}clearMultiDragOverlayState(){this.getTrackCollection().forEach(e=>{var t;return(t=e.clearClipDragOverlay)==null?void 0:t.call(e)})}ensureMultiDragSession(e){var r;const t=this.selectionStore.getSelectedClipIds();if(t.length<=1)return this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null;if(this.multiDragSession&&this.multiDragSession.draggedClipId===e.draggedClipId&&this.haveSameClipIds(this.multiDragSession.selectedClipIds,t))return this.multiDragSession;const i=new Map;for(const n of t){const a=this.findTrackByClipId(n),o=((r=a==null?void 0:a.getId)==null?void 0:r.call(a))??this.resolveTrackIdByClipId(n),l=a==null?void 0:a.getClips().find(h=>h.id===n);if(!o||!l)continue;const c=n===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(n,{clipId:n,trackId:o,clip:c})}return i.size<=1?(this.clearMultiDragOverlayState(),this.resetMultiDragSession(),null):(this.multiDragSession={draggedClipId:e.draggedClipId,selectedClipIds:t.slice(),clips:i},this.multiDragSession)}haveSameClipIds(e,t){if(e.length!==t.length)return!1;const i=new Set(t);return e.every(r=>i.has(r))}restoreDraggedClipSnapshot(e,t){const i=Math.max(0,e.startTime-t);return{...e,startTime:i,endTime:i+e.duration}}syncMultiDragPeerClips(e,t,i){for(const r of e.selectedClipIds){if(r===t.draggedClipId)continue;const n=e.clips.get(r);if(!n||n.trackId===t.currentTrackId)continue;const a=this.getTrackCollection().findById(n.trackId);if(!(a!=null&&a.updateClipPosition))continue;const o=Math.max(0,n.clip.startTime+t.deltaTime);a.updateClipPosition(r,o,i,i?0:t.crossTrackOffsetY)}}createMultiDragPlacementContext(e){const t=new Map,i=new Map,r=[...this.getResolvedTracksSnapshot()].sort((n,a)=>(n.order??0)-(a.order??0));for(const n of r){const a=i.get(n.type)??[];a.push(n.id),i.set(n.type,a),t.set(n.id,n.clips.filter(o=>!e.has(o.id)).map(o=>({id:o.id,startTime:o.startTime,duration:o.duration})))}return{occupancyByTrackId:t,orderedTrackIdsByType:i}}doesMultiDragPlacementOverlap(e,t,i){const r=e.occupancyByTrackId.get(t)??[],n=i.startTime+i.duration;return r.some(a=>a.id!==i.id&&i.startTime<a.startTime+a.duration&&n>a.startTime)}reserveMultiDragPlacement(e,t,i){const r=e.occupancyByTrackId.get(t)??[];r.push({id:i.id,startTime:i.startTime,duration:i.duration}),e.occupancyByTrackId.set(t,r)}registerMultiDragPlacementTrack(e,t,i,r,n){const a=e.orderedTrackIdsByType.get(i)??[];if(!a.includes(t)){if(r==="before_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o,0,t):a.unshift(t)}else if(r==="after_track"&&n){const o=a.indexOf(n);o>=0?a.splice(o+1,0,t):a.push(t)}else r==="top_of_type_region"?a.unshift(t):a.push(t);e.orderedTrackIdsByType.set(i,a)}e.occupancyByTrackId.has(t)||e.occupancyByTrackId.set(t,[])}findNearestAvailableTrackForMultiDragPlacement(e,t,i){const r=e.orderedTrackIdsByType.get(t.type)??[],n=r.indexOf(i);if(n===-1)return null;const o=r.map((l,c)=>({trackId:l,index:c,distance:Math.abs(c-n)})).filter(({trackId:l})=>l!==i).sort((l,c)=>{if(l.distance!==c.distance)return l.distance-c.distance;const h=l.index>n?0:1,d=c.index>n?0:1;return h-d}).find(({trackId:l})=>!this.doesMultiDragPlacementOverlap(e,l,t));return(o==null?void 0:o.trackId)??null}resolveMultiDragOverlapTargetTrackId(e,t,i){const r=this.findNearestAvailableTrackForMultiDragPlacement(e,t,i);if(r)return r;const n=this.createTrack(t.type,void 0,"after_track",i);if(n)return this.registerMultiDragPlacementTrack(e,n,t.type,"after_track",i),n;const a=t.type==="audio"?"bottom_of_type_region":"top_of_type_region",o=this.createTrack(t.type,void 0,a);return o?(this.registerMultiDragPlacementTrack(e,o,t.type,a),o):null}commitMultiDragPlacements(e,t,i,r={}){const n=[],a=this.createMultiDragPlacementContext(new Set(e.selectedClipIds)),o=new Map,l=new Map;let c=null;for(const h of e.selectedClipIds){const d=e.clips.get(h);if(!d)continue;const u=this.buildMovedClipSnapshot(d.clip,t.deltaTime),p=i(d,u);if(!p)continue;if(r.compactSameTrackPrimary&&this.getEnablePrimaryTrackMagnet()&&p===d.trackId&&this.isPrimaryTrackId(d.trackId)){c=d.trackId,l.set(d.clipId,d.clip),o.set(d.clipId,u);continue}let f=p;if(!(this.doesMultiDragPlacementOverlap(a,p,u)&&(f=this.resolveMultiDragOverlapTargetTrackId(a,u,p),!f))){if(this.reserveMultiDragPlacement(a,f,u),f===d.trackId){if(u.startTime===d.clip.startTime&&u.endTime===d.clip.endTime)continue;this.updateClipPositionSilently(d.trackId,d.clipId,u.startTime),n.push({clipId:d.clipId,previousState:d.clip,newState:u});continue}this.updateClipPositionSilently(d.trackId,d.clipId,u.startTime),this.moveClipToTrackWithHistorySnapshot(d.clipId,f,d.clip,u)}}return c&&o.size>0&&n.push(...this.compactPrimaryTrackAfterMultiDrag(c,o,l)),n.length>0&&this.getTimelineHistoryRecorder().recordClipUpdate(n[0].newState,void 0,n),!0}finalizeMultiDragSameTrack(e,t){return this.commitMultiDragPlacements(e,t,i=>i.trackId,{compactSameTrackPrimary:!0})}compactPrimaryTrackAfterMultiDrag(e,t,i){var d;if(!this.getEnablePrimaryTrackMagnet()||!this.isPrimaryTrackId(e))return[];const r=this.getTrackCollection().findById(e),n=this.getStableStartOrderedClips(((d=r==null?void 0:r.getClips)==null?void 0:d.call(r))??[]);if(n.length===0)return[];const a=new Map(n.map(u=>[u.id,u])),o=new Map(a);i.forEach((u,p)=>{o.set(p,u)});const l=this.buildPrimaryTrackMultiDragOrderedClips(n,t),c=this.buildPrimaryTrackContinuousClips(l),h=[];return c.forEach(u=>{const p=a.get(u.id),f=o.get(u.id);!p||!f||((p.startTime!==u.startTime||p.endTime!==u.endTime)&&this.updateClipPositionSilently(e,u.id,u.startTime),(f.startTime!==u.startTime||f.endTime!==u.endTime)&&h.push({clipId:u.id,previousState:f,newState:u}))}),h}previewMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackPreviewDestination(r,t.targetTrackY,i.trackId);if(n.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(n.trackType,n.insertionPlacement,n.referenceTrackId),!0;if(n.status!=="existing_track"||n.targetTrackId===i.trackId)return!1;const a=this.resolveTrackIndexDelta(i.trackId,n.targetTrackId,i.clip.type);if(a===null)return!1;const o=new Map;this.appendPreviewClip(o,n.targetTrackId,r);for(const l of e.selectedClipIds){if(l===t.draggedClipId)continue;const c=e.clips.get(l);if(!c)continue;const h=this.buildMovedClipSnapshot(c.clip,t.deltaTime),d=this.resolveMultiDragPreviewTargetTrackId(c,a,h);!d||d===c.trackId||this.appendPreviewClip(o,d,h)}return o.size===0?!1:(this.showClipDropPreviews(o),!0)}finalizeMultiDragCrossTrack(e,t){const i=e.clips.get(t.draggedClipId);if(!i)return!1;const r=this.buildMovedClipSnapshot(i.clip,t.deltaTime),n=this.resolveCrossTrackMoveDestination(r,t.targetTrackY,i.trackId);if(n.status==="blocked"||n.status==="same_track")return!1;const a=n.targetTrackId;if(!a)return!1;const o=this.resolveTrackIndexDelta(i.trackId,a,i.clip.type);return o===null?!1:this.commitMultiDragPlacements(e,t,(l,c)=>l.clipId===t.draggedClipId?a:this.resolveMultiDragTargetTrackId(l,o,c))}resolveTrackIndexDelta(e,t,i){const r=this.getTrackIdsByType(i),n=r.indexOf(e),a=r.indexOf(t);return n===-1||a===-1?null:a-n}resolveMultiDragTargetTrackId(e,t,i){const r=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return e.trackId;const n=this.calculateTrackY(r)+1,a=this.resolveCrossTrackMoveDestination(i,n,e.trackId);return a.status==="blocked"?r:a.targetTrackId}resolveMultiDragPreviewTargetTrackId(e,t,i){const r=this.findTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return null;const n=this.calculateTrackY(r)+1,a=this.resolveCrossTrackPreviewDestination(i,n,e.trackId);return a.status==="existing_track"?a.targetTrackId:null}buildMovedClipSnapshot(e,t,i=!1){let r=e.startTime+t;if(i){const n=this.getDurationState();r=Math.max(0,Math.min(r,n-e.duration))}else r=Math.max(0,r);return{...e,startTime:r,endTime:r+e.duration}}appendPreviewClip(e,t,i){const r=e.get(t);if(r){r.push(i);return}e.set(t,[i])}resolveCrossTrackMoveDestination(e,t,i){if(!this.trackManager||!this.getTimelineCommands)return{status:"blocked"};const r=this.trackManager.getTracks(),n=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);if(n.status==="missing_target_track_by_position")return O.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(n.status==="same_track")return{status:"same_track",targetTrackId:n.targetTrackId};if(n.status==="missing_target_track_view")return O.warn("TimelineManager","目标轨道不存在",{targetTrackId:n.targetTrackId}),{status:"blocked"};if(n.status==="track_type_mismatch")return O.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:n.targetTrackType,clipType:e.type})),{status:"blocked"};if(n.status==="move_to_track")return{status:"move_to_track",targetTrackId:n.targetTrackId};O.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const a=this.createTrack(n.trackType,void 0,n.insertionPlacement,n.referenceTrackId);return a?{status:"move_to_track",targetTrackId:a}:{status:"blocked"}}resolveCrossTrackPreviewDestination(e,t,i){if(!this.trackManager||typeof this.trackManager.getTracks!="function")return{status:"existing_track",targetTrackId:i};const r=this.trackManager.getTracks();if(!Array.isArray(r)||r.length===0)return{status:"clear"};const n=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);return n.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:n.targetTrackId}:n.status==="new_track_insertion"?{status:"new_track_insertion",trackType:n.trackType,insertionPlacement:n.insertionPlacement,referenceTrackId:n.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(e,t,i){let r=this.getTrackIdsByType(t);const n=r.indexOf(e);if(n===-1)return null;let a=n+i;for(;a<0;){if(!this.createTrack(t,void 0,"top_of_type_region"))return null;r=this.getTrackIdsByType(t),a+=1}for(;a>=r.length;){if(!this.createTrack(t,void 0,"bottom_of_type_region"))return null;r=this.getTrackIdsByType(t)}return r[a]??null}findTrackIdByRelativeIndex(e,t,i){const r=this.getTrackIdsByType(t),n=r.indexOf(e);if(n===-1)return null;const a=n+i;return a<0||a>=r.length?null:r[a]??null}getTrackIdsByType(e){if(!this.trackManager)return[];const t=this.trackManager.getTracks();return t?t.filter(i=>i.type===e).map(i=>i.id):[]}updateClipPositionSilently(e,t,i){const r=this.getTrackCollection().findById(e),n=r==null?void 0:r.updateClipPosition;n&&this.withHistoryBoundary("suppressed",()=>{n.call(r,t,i,!0)})}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new Z.Rect({fill:xn.fill,stroke:xn.stroke,strokeWidth:1,dash:[4,4],listening:!1,visible:!1});return(t=this.selectionBoxLayer)==null||t.add(e),this.selectionBoxRect=e,e}showSelectionBoxRect(e,t,i,r){var a;const n=this.ensureSelectionBoxRect();n.x(e),n.y(t),n.width(Math.max(i,1)),n.height(Math.max(r,1)),n.visible(!0),(a=this.selectionBoxLayer)==null||a.batchDraw()}hideSelectionBoxRect(){var e;this.selectionBoxRect&&(this.selectionBoxRect.visible(!1),(e=this.selectionBoxLayer)==null||e.batchDraw())}handleStageMouseDown(e){if(e.button!==0)return;const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,a=e.clientY-r.top;if(this.isPointOnClip(n,a))return;this.isBoxSelecting=!1,this.boxSelectStartX=n,this.boxSelectStartY=a;const l=h=>{this.handleBoxSelectMove(h)},c=()=>{this.handleBoxSelectEnd(),window.removeEventListener("mousemove",l),window.removeEventListener("mouseup",c)};window.addEventListener("mousemove",l),window.addEventListener("mouseup",c)}handleBoxSelectMove(e){const t=this.stage;if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),n=e.clientX-r.left,a=e.clientY-r.top,o=Math.abs(n-this.boxSelectStartX),l=Math.abs(a-this.boxSelectStartY);if(!this.isBoxSelecting&&(o>4||l>4)&&(this.isBoxSelecting=!0),!this.isBoxSelecting)return;const c=Math.min(this.boxSelectStartX,n),h=Math.min(this.boxSelectStartY,a),d=Math.abs(n-this.boxSelectStartX),u=Math.abs(a-this.boxSelectStartY);this.showSelectionBoxRect(c,h,d,u)}handleBoxSelectEnd(){if(!this.isBoxSelecting)return;const e=this.selectionBoxRect;if(e){const t={x:e.x(),y:e.y(),width:e.width(),height:e.height()},i=this.getClipsIntersectingBox(t);this.setSelection(i,{preferredPrimaryClipId:this.selectedClipId})}this.hideSelectionBoxRect(),this.isBoxSelecting=!1}isPointOnClip(e,t){for(const i of this.tracks){const n=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);if(!(t<n||t>n+a))for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ve(o.duration,this.getZoomState());if(e>=l&&e<=l+c&&t>=n+2&&t<=n+a-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const n=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=ve(o.duration,this.getZoomState()),h=n+2,d=a-4,u=l+c,p=h+d,f=e.x+e.width,m=e.y+e.height;l<f&&u>e.x&&h<m&&p>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return Ae(e.getTrackType())}cloneTrackSnapshot(e){var i;if(!((i=this.trackManager)!=null&&i.getTracks))return null;const t=this.getResolvedTracksSnapshot().find(r=>r.id===e);return t?{...t,clips:t.clips.map(r=>({...r}))}:null}ensureTrackFromHistorySnapshot(e,t=null){var d;if(this.getTrackCollection().findById(e.id))return this.renameTrack(e.id,e.name),this.muteTrack(e.id,e.isMuted??!1),e.id;if(e.role==="primary")return((d=this.getTracks()[0])==null?void 0:d.id)??null;const r=this.resolveTrackInsertionFromRestoreAnchor(t);if(r){const u=this.createTrack(e.type,e.name,r.insertionPlacement,r.referenceTrackId,void 0,e.id);return this.muteTrack(u,e.isMuted??!1),u}const n=[...this.getTracks()].sort((u,p)=>u.order-p.order),a=n.find(u=>u.order>=e.order),o=a?n[n.findIndex(u=>u.id===a.id)-1]??null:n[n.length-1]??null;let l,c;a?(l="before_track",c=a.id):o&&(l="after_track",c=o.id);const h=this.createTrack(e.type,e.name,l,c,void 0,e.id);return this.muteTrack(h,e.isMuted??!1),h}getTrackRestoreAnchor(e){var r,n,a;if(!((r=this.trackManager)!=null&&r.getTracks))return null;const t=[...this.getResolvedTracksSnapshot()].sort((o,l)=>o.order-l.order),i=t.findIndex(o=>o.id===e);return i===-1?null:{previousTrackId:((n=t[i-1])==null?void 0:n.id)??null,nextTrackId:((a=t[i+1])==null?void 0:a.id)??null}}resolveTrackInsertionFromRestoreAnchor(e){return e?e.previousTrackId&&this.getTrackCollection().findById(e.previousTrackId)?{insertionPlacement:"after_track",referenceTrackId:e.previousTrackId}:e.nextTrackId&&this.getTrackCollection().findById(e.nextTrackId)?{insertionPlacement:"before_track",referenceTrackId:e.nextTrackId}:null:null}resolveTrackIdByClipId(e){var a;const t=this.getTimelineCommands();if(typeof t.findClipById=="function")return((a=t.findClipById(this.tracks,e))==null?void 0:a.trackId)??null;const i=this.getTrackCollection();if(typeof i.findTrackByClipId=="function"){const o=i.findTrackByClipId(e);if(o)return o.getId()}const n=(Array.isArray(this.tracks)?this.tracks:[]).find(o=>o.getClips().some(l=>l.id===e));return(n==null?void 0:n.getId())??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var a;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=ln(e),n=Ns(e);if(r!==t){this.lastTrackDuration=r;const o=Gs(r);this.setDurationState(o),(a=this.timeline)==null||a.setDuration(o),this.updateViewportLayout()}if(n!==i&&(this.lastReportedTrackDuration=n,this.emitEvent("track_duration_change",{duration:n})),e.length===0&&this.getCurrentTimeState()!==0&&this.setCurrentTime(0),e.length>0){const o=kt(e);o>0&&this.getCurrentTimeState()>o&&this.setCurrentTime(o)}r===t&&n===i||O.debugLazy("TimelineManager",()=>`Track duration changed: total=${n}ms, extent=${r}ms, timeline=${Gs(r)}ms`)}resolveSelectedClipSnapshot(){return yo({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}}})}resolveSelectionChangeData(){return ep({getPrimarySelectedClip:()=>{var e;try{return((e=this.getPrimarySelectedClip)==null?void 0:e.call(this))||null}catch{return null}},findFallbackSelectedClip:()=>{var e,t;if(!this.tracks)return null;try{const i=(e=this.getTimelinePresentationAdapter)==null?void 0:e.call(this),r=(t=this.getTrackCollection)==null?void 0:t.call(this);return!i||!r||typeof i.findSelectedClip!="function"?null:i.findSelectedClip(r)}catch{return null}},getSelectedClipIds:()=>{try{return this.getSelectedClipIds()}catch{return[]}},canSplitSelectedClip:()=>{try{return this.canSplitSelectedClip()}catch{return!1}},getSelectedClipAudioAction:()=>{try{return this.getSelectedClipAudioAction()}catch{return null}}})}commitPreviewVisualTransform(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="video"&&i.type!=="text")return;const r=Pe(i.visualTransform),n=Pe(t);wn(r,n)||this.updateClip(e,{visualTransform:n})}commitPreviewTextFontSize(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=De(i.textStyle),n=Math.max(ci.MIN,Math.min(ci.MAX,Math.round(t)));r.fontSize!==n&&this.updateClip(e,{textStyle:{...r,fontSize:n}})}commitPreviewTextRotation(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=De(i.textStyle),n=Math.round(t);r.rotation!==n&&this.updateClip(e,{textStyle:{...r,rotation:n}})}clearAllTracksAndClips(){this.withHistoryBoundary("reset",()=>{var t,i,r,n;const e=this.getTracks();for(const a of e){const o=this.getTrackCollection().findById(a.id);if(o){const l=[...o.getClips()];for(const c of l)(t=o.removeClip)==null||t.call(o,c.id)}}for(const a of e){const o=a.id,l=this.getTrackCollection().findById(o);(r=(i=l==null?void 0:l.getTrackGroup)==null?void 0:i.call(l))==null||r.destroy(),this.getTrackCollection().removeById(o)}this.trackManager.clearAllTracks(),this.updateAllTrackPositions(),(n=this.stage)==null||n.batchDraw(),this.clearHistory()})}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=hn;exports.CLIP_LAYER=wo;exports.Clip=$i;exports.ClipConfigPanel=uo;exports.DEFAULT_CLIP_VIEW_STATE=ia;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Be;exports.DEFAULT_TEXT_CLIP_DURATION_MS=ra;exports.DEFAULT_TEXT_CLIP_STYLE=ea;exports.DEFAULT_TIMELINE_DURATION_MS=Qt;exports.DiagnosticsCenter=qa;exports.HistoryManager=an;exports.MIN_CLIP_LINE_WIDTH=hi;exports.PREVIEW_ASPECT_RATIO_PRESETS=ko;exports.SNAP_SCORING=sa;exports.TEXT_CLIP_FONT_SIZE_LIMITS=ci;exports.TIMELINE_LEFT_PADDING=pe;exports.TIME_SCALE=xo;exports.TRACK_HEIGHT=Gi;exports.TimeUtils=U;exports.TimelineClipConfigController=So;exports.TimelineManager=Jp;exports.Track=ir;exports.TrackInfoPanel=ho;exports.TrackManager=vo;exports.VOICE_LINKED_TEXT_REGEN_DEBOUNCE_MS=na;exports.ZOOM_ANIMATION=Po;exports.ZOOM_GESTURE=Fr;exports.ZOOM_PRESETS=Me;exports.createClipViewState=aa;exports.createClipWithViewState=pn;exports.defaultDarkTheme=Xi;exports.devConsole=O;exports.isAudioOnlyTtsClipCandidate=ta;exports.isAutoPreviewAspectRatioMode=_t;exports.isTtsAudioClip=Le;exports.mergeDiagnosticRuntimeState=ja;exports.normalizePreviewAspectRatio=je;exports.normalizePreviewAspectRatioMode=dn;exports.resolveAspectRatioBaselineDimensions=un;exports.resolveTextClipStyle=De;exports.resolveTheme=qi;