@linker-design-plus/timeline-track 2.2.2 → 2.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -731,4 +731,4 @@ js: import "konva/skia-backend";
731
731
  ${this.renderNumberInput(e.theme,{min:a,max:o,step:s,value:String(i),onChange:r})}
732
732
  </label>
733
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:${P.sliderFillStart}`,`--clip-slider-fill-end:${P.sliderFillEnd}`,`--clip-slider-road:${P.sliderRoad}`,`--clip-slider-thumb-border:${P.sliderThumbBorder}`,`--clip-slider-thumb-shadow:${Pe.sliderThumbShadow}`].join(";")}getSliderStyle(e,t,i){const r=Number(e||0),s=Number(t||100),a=Number(i||0),o=s-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 s=this.getTransform(e).scale/2,a={left:s,center:.5,right:1-s},o={top:s,center:.5,bottom:1-s};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(Tt.colorRafId),Tt.colorRafId=requestAnimationFrame(()=>{e.callbacks.onTextStyleChange("color",i)})}}};p(Tt,"colorRafId",0);let es=Tt;const Xd={...ye};function _n(n){return n?{primaryClip:n,selectedClips:[n],selectionCount:1,groupKind:n.type,supportsVoiceBatch:n.type==="text"||Me(n),supportsTextContentBatch:n.type==="text",supportsVisualBatch:n.type==="video",supportsVolumeBatch:n.type==="video"||n.type==="audio"}:{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1}}function jd(n,e){return n.groupKind!==e.groupKind||n.selectionCount!==e.selectionCount||n.supportsVoiceBatch!==e.supportsVoiceBatch||n.supportsTextContentBatch!==e.supportsTextContentBatch||n.supportsVisualBatch!==e.supportsVisualBatch||n.supportsVolumeBatch!==e.supportsVolumeBatch||n.selectedClips.length!==e.selectedClips.length?!1:n.selectedClips.every((t,i)=>{var r;return t.id===((r=e.selectedClips[i])==null?void 0:r.id)})}class mo{constructor(e){p(this,"container");p(this,"theme");p(this,"renderer",new es);p(this,"onClipUpdate");p(this,"onGenerateVoice");p(this,"voiceCatalog");p(this,"currentClip",null);p(this,"selectionState",_n(null));p(this,"activeTab","visual");p(this,"iconCache",new Map);p(this,"pendingPreferredTab",null);p(this,"selectedVoiceId",null);p(this,"activeVoiceFilterTag","男");p(this,"textDraftContent","");p(this,"followTextUpdates",!0);p(this,"voiceLoadingBusyCount",0);p(this,"isVoiceLoadingOverlayRendered",!1);p(this,"isVoiceLoadingOverlayExiting",!1);p(this,"voiceLoadingOverlayHideTimer",null);p(this,"voiceErrorMessage",null);p(this,"voicePreviewAudio",null);p(this,"previewingVoiceId",null);p(this,"handleVoicePreviewEnded",()=>{this.stopVoicePreview()});this.container=e.container,this.theme=e.theme??Xd,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(_n(e))}setSelectionState(e){var l,c,h,d,u,g;const t=e,i=this.selectionState,r=((l=this.currentClip)==null?void 0:l.id)??null,s=((c=t.primaryClip)==null?void 0:c.id)??null,a=r!==s,o=!jd(i,t);a&&this.stopVoicePreview(!1),this.selectionState=t,this.currentClip=t.primaryClip,a||o?(this.voiceErrorMessage=null,this.textDraftContent=((h=this.currentClip)==null?void 0:h.textContent)??((d=this.currentClip)==null?void 0:d.name)??"",this.syncVoiceStateForSelection(t)):((u=this.currentClip)==null?void 0:u.type)==="text"?this.textDraftContent=this.currentClip.textContent??this.currentClip.name??"":((g=this.currentClip)==null?void 0:g.type)==="audio"&&t.supportsVoiceBatch?(this.followTextUpdates=this.currentClip.ttsFollowTextUpdates??!1,this.ensureVoiceFilters()):this.currentClip||this.resetVoiceState(),this.syncActiveTab(t),this.render()}setPreferredTab(e){this.pendingPreferredTab=e}showVoiceGenerationLoading(){this.setVoiceGenerationBusy(!0)}hideVoiceGenerationLoading(){this.setVoiceGenerationBusy(!1)}setVoiceGenerationBusy(e){if(this.voiceLoadingBusyCount=Math.max(0,this.voiceLoadingBusyCount+(e?1:-1)),this.voiceLoadingBusyCount>0){this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.isVoiceLoadingOverlayRendered=!0,this.isVoiceLoadingOverlayExiting=!1,this.render();return}if(!this.isVoiceLoadingOverlayRendered){this.render();return}this.isVoiceLoadingOverlayExiting=!0,this.voiceLoadingOverlayHideTimer!==null&&window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=window.setTimeout(()=>{this.isVoiceLoadingOverlayRendered=!1,this.isVoiceLoadingOverlayExiting=!1,this.voiceLoadingOverlayHideTimer=null,this.render()},180),this.render()}destroy(){this.stopVoicePreview(!1),this.voiceLoadingOverlayHideTimer!==null&&(window.clearTimeout(this.voiceLoadingOverlayHideTimer),this.voiceLoadingOverlayHideTimer=null),this.renderer.destroy()}render(){const e=this.getAvailableTabs(this.selectionState);this.renderer.update({clip:this.currentClip,selectionState:this.selectionState,activeTab:this.activeTab,availableTabs:e,theme:this.theme,emptyStateMessage:this.getEmptyStateMessage(this.selectionState),isTextContentEditable:this.selectionState.supportsTextContentBatch,loadingIconSvg:this.iconCache.get("OmAi-loading")??"",selectedIconSvg:this.iconCache.get("OmAi-accept")??"",textDraftContent:this.textDraftContent,voiceCatalog:this.voiceCatalog,selectedVoiceId:this.selectedVoiceId,previewingVoiceId:this.previewingVoiceId,activeVoiceFilterTag:this.activeVoiceFilterTag,followTextUpdates:this.followTextUpdates,isVoiceLoadingOverlayVisible:this.isVoiceLoadingOverlayRendered,isVoiceLoadingOverlayExiting:this.isVoiceLoadingOverlayExiting,voiceErrorMessage:this.voiceErrorMessage,callbacks:{onTabChange:t=>{this.activeTab=t,this.render()},onTransformChange:(t,i)=>{this.handleTransformChange(t,i)},onPresetSelect:(t,i)=>{this.handleTransformChanges({x:t,y:i})},onVolumeChange:t=>{this.handleVolumeChange(t)},onTextContentInput:t=>{this.handleTextContentInput(t)},onTextContentCommit:()=>{this.handleTextContentCommit()},onTextStyleChange:(t,i)=>{this.handleTextStyleChange(t,i)},onVoiceFilterChange:t=>{this.handleVoiceFilterChange(t)},onVoiceSelect:t=>{this.handleVoiceSelect(t)},onVoiceFollowTextUpdatesChange:t=>{this.handleVoiceFollowTextUpdatesChange(t)},onGenerateVoice:async()=>{await this.handleGenerateVoice()}}})}getAvailableTabs(e=this.selectionState){return e.groupKind==="text"?["text","voice"]:e.groupKind==="audio"?e.supportsVoiceBatch?["voice","audio"]:["audio"]:e.groupKind==="video"?["visual","audio"]:[]}getEmptyStateMessage(e=this.selectionState){return e.groupKind==="empty"?"请选择一个片段":e.groupKind==="mixed"?"暂不支持跨类型批量配置":null}resetVoiceState(){this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=!1,this.stopVoicePreview(!1)}syncVoiceStateForSelection(e){if(!this.supportsVoicePanel(e)||!e.primaryClip){this.resetVoiceState();return}this.selectedVoiceId=null,this.activeVoiceFilterTag="男",this.followTextUpdates=e.primaryClip.type==="audio"?e.primaryClip.ttsFollowTextUpdates??!1:!0,this.ensureVoiceFilters()}syncActiveTab(e){const t=this.getAvailableTabs(e);if(t.length===0){this.activeTab="visual",this.pendingPreferredTab=null;return}if(this.pendingPreferredTab&&t.includes(this.pendingPreferredTab)){this.activeTab=this.pendingPreferredTab,this.pendingPreferredTab=null;return}t.includes(this.activeTab)||(this.activeTab=t[0],this.pendingPreferredTab=null)}supportsVoicePanel(e=this.selectionState){return e.groupKind==="text"||e.groupKind==="audio"&&e.supportsVoiceBatch}ensureVoiceFilters(){if(this.voiceCatalog.length===0){this.selectedVoiceId=null,this.stopVoicePreview(!1);return}this.selectedVoiceId&&!this.voiceCatalog.some(e=>e.id===this.selectedVoiceId)&&(this.selectedVoiceId=null,this.stopVoicePreview(!1))}handleVoiceFilterChange(e){const t=e==="男"||e==="女"||e==="普通话"||e==="粤语"?e:null;this.activeVoiceFilterTag=this.activeVoiceFilterTag===t?null:t,this.render()}async handleVoiceSelect(e){const t=this.voiceCatalog.find(r=>r.id===e)??null,i=this.previewingVoiceId===e;if(this.selectedVoiceId=e,this.voiceErrorMessage=null,this.render(),!(t!=null&&t.audiofile)){this.stopVoicePreview();return}if(i){this.stopVoicePreview();return}await this.playVoicePreview(t)}handleVoiceFollowTextUpdatesChange(e){var t;this.followTextUpdates=e,((t=this.currentClip)==null?void 0:t.type)==="audio"&&this.selectionState.supportsVoiceBatch&&this.onClipUpdate&&(this.currentClip={...this.currentClip,ttsFollowTextUpdates:e},this.onClipUpdate(this.currentClip.id,{ttsFollowTextUpdates:e})),this.render()}async handleGenerateVoice(){if(!this.currentClip||!this.onGenerateVoice)return;const e=this.voiceCatalog.find(t=>t.id===this.selectedVoiceId);if(!e){this.voiceErrorMessage="请选择一个音色",this.render();return}this.voiceErrorMessage=null,this.render();try{await this.onGenerateVoice(this.currentClip,e,this.followTextUpdates)}catch(t){this.voiceErrorMessage=t instanceof Error?t.message:"音色生成失败"}this.render()}handleVolumeChange(e){if(!this.currentClip||!this.onClipUpdate)return;const t=Math.max(0,Math.min(1,e));this.currentClip={...this.currentClip,volume:t},this.render(),this.onClipUpdate(this.currentClip.id,{volume:t})}clampValue(e,t){return e==="scale"?Math.max(.1,Math.min(8,t)):t}handleTransformChange(e,t){if(!this.currentClip||!this.onClipUpdate)return;const i=this.clampValue(e,t),s={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:i};this.currentClip={...this.currentClip,visualTransform:s},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:s})}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 s=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(s))return;const o={...this.currentClip.visualTransform??{x:.5,y:.5,scale:1},[e]:Math.max(0,Math.min(1,s))};this.currentClip={...this.currentClip,visualTransform:o},this.render(),this.onClipUpdate(this.currentClip.id,{visualTransform:o});return}const r={...ce(this.currentClip.textStyle)};if(e==="fontSize"){const s=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(s))return;r.fontSize=Math.max(ci.MIN,Math.min(ci.MAX,s))}else if(e==="rotation"){const s=typeof t=="number"?t:Number.parseFloat(String(t));if(!Number.isFinite(s))return;r.rotation=s}else r.color=String(t);this.currentClip={...this.currentClip,textStyle:r},this.render(),this.onClipUpdate(this.currentClip.id,{textStyle:r})}}function qd(n){return n==="text"?"文本":n==="video"?"视频":"音频"}class An{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(s=>s.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(s=>t>=s.startTime&&t<s.startTime+s.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:s,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!==s.type?{status:"track_type_mismatch",clipId:e,targetTrackId:t,sourceTrackId:o}:{status:"ready",clip:s,sourceTrack:a,sourceTrackId:o,targetTrack:l,targetTrackId:t}}planTrackPlacement(e,t){var s;const i=e.startTime+e.duration;for(const a of t){if(((s=a.getTrackType)==null?void 0:s.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:`${qd(e.type)}轨道 ${r}`,insertionPlacement:e.type==="text"||e.type==="video"?"top_of_type_region":"bottom_of_type_region"}}planCrossTrackMove(e,t,i,r,s,a){var f;const o=this.resolveTrackTargetByY(t,r,s,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=s.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,s);if(d)return{status:"create_track",trackType:e.type,insertionPlacement:d.insertionPlacement,referenceTrackId:d.referenceTrackId};const u=s.filter(m=>m.type===e.type).map(m=>m.id),g=u.indexOf(l);for(let m=1;m<=u.length;m+=1){const C=g-m;if(C>=0){const S=u[C],T=a.find(k=>this.resolveTrackId(k)===S);if(T&&!this.hasOverlapOnTrack(e,T))return{status:"move_to_track",targetTrackId:S}}const v=g+m;if(v<u.length){const S=u[v],T=a.find(k=>this.resolveTrackId(k)===S);if(T&&!this.hasOverlapOnTrack(e,T))return{status:"move_to_track",targetTrackId:S}}}return{status:"create_track",trackType:e.type,insertionPlacement:e.type==="text"?"top_of_type_region":e.type==="video"?"before_primary":"after_primary"}}planCrossTrackPreview(e,t,i,r,s,a){const o=this.planCrossTrackMove(e,t,i,r,s,a);return o.status==="same_track"||o.status==="move_to_track"?{status:"existing_track_placeholder",targetTrackId:o.targetTrackId}:o.status==="create_track"?{status:"new_track_insertion",trackType:o.trackType,insertionPlacement:o.insertionPlacement,referenceTrackId:o.referenceTrackId}:{status:"clear"}}setCurrentTime(e){const t=Math.max(0,e);return this.updateCurrentTime(t)}setZoom(e){const t=Math.max(Re.MIN,Math.min(Re.MAX,e));return this.updateZoom(t)}setSpeed(e){const t=Math.max(.1,Math.min(10,e));return this.updateSpeed(t)}updateSelection(e){const t=this.timelineStore.getPrimarySelectedClipId();return t===e?{previousClipId:t,nextClipId:e,changed:!1}:(e===null?this.timelineStore.clearSelection():this.timelineStore.setPrimarySelectedClipId(e),{previousClipId:t,nextClipId:e,changed:!0})}updateCurrentTime(e){const t=this.timelineStore.getCurrentTime();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setCurrentTime(e),{previousValue:t,nextValue:e,changed:!0})}updateZoom(e){const t=this.timelineStore.getZoom();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setZoom(e),{previousValue:t,nextValue:e,changed:!0})}updateSpeed(e){const t=this.timelineStore.getSpeed();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setSpeed(e),{previousValue:t,nextValue:e,changed:!0})}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}resolveTrackType(e){return typeof e.getTrackType=="function"?e.getTrackType():e.type??null}resolveTrackTargetByY(e,t,i,r){let s=t,a=null,o=null;for(const l of i){const c=_e(l.type),h=s+c;if(l.type===r&&(a===null&&(a=s),o=h),e>=s&&e<h)return{status:"existing_track",targetTrackId:l.id};s=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,s){let a=r;const o=s.map(d=>{const u=a,g=_e(d.type),f=u+g;return a=f,{id:d.id,type:d.type,role:d.role,startY:u,endY:f,height:g}}).filter(d=>d.type===e),l=o.findIndex(d=>d.id===t);if(l===-1)return null;const c=o[l],h=Math.min(12,Math.max(6,Math.floor(c.height/4)));return c.role==="primary"?{insertionPlacement:e==="text"||e==="video"?"before_track":"after_track",referenceTrackId:t}:l<o.length-1&&i>=c.endY-h?{insertionPlacement:"after_track",referenceTrackId:t}:{insertionPlacement:"before_track",referenceTrackId:t}}hasOverlapOnTrack(e,t){const i=e.startTime+e.duration;return t.getClips().some(r=>r.id===e.id?!1:e.startTime<r.endTime&&i>r.startTime)}}class ts{constructor(e,t,i,r=100){p(this,"state");p(this,"maxHistorySize",100);p(this,"onActionUndo");p(this,"onActionRedo");p(this,"onHistoryChange");this.state={past:[],future:[]},this.maxHistorySize=r,this.onActionUndo=e,this.onActionRedo=t,this.onHistoryChange=i}addAction(e){this.state.past.length>=this.maxHistorySize&&this.state.past.shift(),this.state.past.push({...e,timestamp:Date.now()}),this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}undo(){if(this.state.past.length===0)return!1;const e=this.state.past.pop();return this.state.future.push(e),this.onActionUndo(e),this.onHistoryChange&&this.onHistoryChange(),!0}redo(){if(this.state.future.length===0)return!1;const e=this.state.future.pop();return this.state.past.push(e),this.onActionRedo(e),this.onHistoryChange&&this.onHistoryChange(),!0}clear(){this.state.past=[],this.state.future=[],this.onHistoryChange&&this.onHistoryChange()}canUndo(){return this.state.past.length>0}canRedo(){return this.state.future.length>0}getState(){return{...this.state}}createAddClipAction(e,t=null,i=null,r=null){return{type:"add_clip",data:{clip:e,targetTrackId:t,targetTrackSnapshot:i,targetTrackRestoreAnchor:r},timestamp:Date.now()}}createRemoveClipAction(e){return{type:"remove_clip",data:{clip:e,sourceTrackId:null,sourceTrackSnapshot:null,sourceTrackRestoreAnchor:null},timestamp:Date.now()}}createRemoveClipActionWithTrackSnapshot(e,t,i,r=null){return{type:"remove_clip",data:{clip:e,sourceTrackId:t,sourceTrackSnapshot:i,sourceTrackRestoreAnchor:r},timestamp:Date.now()}}createUpdateClipAction(e,t,i){return{type:"update_clip",data:{clipId:e,updates:t,previousState:i},timestamp:Date.now()}}createSplitClipAction(e,t,i,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,s){return{type:"resize_clip",data:{clipId:e,newDuration:t,newStartTime:i,previousDuration:r,previousStartTime:s},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,s,a,o,l=null,c=null){return{type:"move_clip_between_tracks",data:{clipId:e,sourceTrackId:t,targetTrackId:i,clipBefore:r,clipAfter:s,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 In{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,s,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=(s=this.target).setPrimaryTrackMagnetEnabled)==null||a.call(s,e.data.previousEnabled);break;case"compound":[...e.data.actions].reverse().forEach(o=>{this.executeUndoInternal(o,t)});break;default:N.warn("TimelineHistoryExecutor","Unknown action type for undo:",{type:e.type})}}executeRedoInternal(e,t){var i,r,s,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=(s=this.target).setPrimaryTrackMagnetEnabled)==null||a.call(s,e.data.nextEnabled);break;case"compound":e.data.actions.forEach(o=>{this.executeRedoInternal(o,t)});break;default:N.warn("TimelineHistoryExecutor","Unknown action type for redo:",{type:e.type})}}restoreMovedClip(e,t,i,r,s,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,s)}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 s=(e==null?void 0:e.id)??t??null;if(s){const o=i.get(s);if(o)return o}if(!e)return t;const a=this.target.ensureTrackFromHistorySnapshot(e,this.resolveRestoreAnchor(r,i))??t;return s&&a&&i.set(s,a),a}resolveRestoreAnchor(e,t){return e?{previousTrackId:e.previousTrackId?t.get(e.previousTrackId)??e.previousTrackId:null,nextTrackId:e.nextTrackId?t.get(e.nextTrackId)??e.nextTrackId:null}:null}}const Kd=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],Zd=new Set(["thumbnails"]);function Jd(n,e){return Object.is(n,e)?!0:n===void 0||e===void 0?!1:typeof n=="object"&&typeof e=="object"?JSON.stringify(n)===JSON.stringify(e):!1}class En{constructor(e){p(this,"transactionStack",[]);this.history=e}createAddClipAction(e,t=null,i=null,r=null){return this.history.createAddClipAction(e,t,i,r)}recordAddClip(e,t=null,i=null,r=null){const s=this.history.createAddClipAction(e,t,i,r);return this.recordAction(s),s}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 s=this.createRemoveClipAction(e,t,i,r);return this.recordAction(s),s}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,s=null){const a={...e,duration:e.duration+t.duration,endTime:t.endTime,endTimeAtSource:t.endTimeAtSource},o={trackId:i,trackSnapshot:r,trackRestoreAnchor:s},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,s,a,o,l=null,c=null){const h=this.history.createMoveClipBetweenTracksAction(e,t,i,r,s,a,o,l,c);return this.recordAction(h),h}recordSeparateClipAudio(e,t,i,r){const s=this.history.createSeparateClipAudioAction(e,t,i,r);return this.recordAction(s),s}recordRestoreClipAudio(e,t,i,r){const s=this.history.createRestoreClipAudioAction(e,t,i,r);return this.recordAction(s),s}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={},s={};if(Kd.forEach(d=>{Jd(e[d],t[d])||(r[d]=e[d],s[d]=t[d])}),Object.keys(r).length===0)return null;const a=Object.keys(r);if(a.every(d=>Zd.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,s)}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 Oi(n){var e;n.notifySelectionChange(),(e=n.emitSelectionChangeEvent)==null||e.call(n),n.emitSelectedClipChangeIfNeeded(),n.handleClipChange()}function Qd(n){var e,t,i;n.notifySelectionChange(),(e=n.emitSelectionChangeEvent)==null||e.call(n),(t=n.reloadClipThumbnailsIfNeeded)==null||t.call(n),(i=n.checkTrackDurationChange)==null||i.call(n),n.emitSelectedClipChangeIfNeeded(),n.handleClipChange()}function eu(n,e,t=!1){if(!e||!t||n.type==="audio")return!1;const i=e.duration!==n.duration,r=e.startTimeAtSource!==n.startTimeAtSource||e.endTimeAtSource!==n.endTimeAtSource;return i||r}function St(n){return n.length===0?0:Math.max(...n.map(e=>e.endTime))}function tu(n,e){return e<St(n)}function iu(n){return n.currentCanPlay===n.nextCanPlay?n.currentCanPlay:(n.setCanPlay(n.nextCanPlay),n.currentCanPlay&&!n.nextCanPlay&&n.playState==="playing"&&(n.pauseTimeline(),n.setCurrentTime(n.clipEndTime||1)),n.emitCanPlayChange(n.nextCanPlay),n.nextCanPlay)}function ru(n){const e=!n.id&&n.startTime>0;return{shouldJumpToTime:e,jumpTime:e?n.startTime:null,shouldSelectClip:!!n.id}}function Ui(n){var e;return n.applied?(n.isExecutingHistoryAction||(e=n.recordHistory)==null||e.call(n),n.applyEffects(),!0):!1}function su(n){return Ui({applied:n.applied,isExecutingHistoryAction:n.isExecutingHistoryAction,recordHistory:()=>{var e;(e=n.recordMoveClipBetweenTracks)==null||e.call(n,n.clipId,n.sourceTrackId,n.targetTrackId,n.clipBefore,n.clipAfter,n.sourceTrackSnapshot,n.targetTrackSnapshot)},applyEffects:n.applyEffects})}function nu(n){var e;n.isExecutingHistoryAction||(e=n.recordSplitClip)==null||e.call(n,n.clip1,n.clip2),n.emitClipUpdated(n.clip1),n.emitClipAdded(n.clip2),n.applyEffects()}const Pr={x:.5,y:.5,scale:1},Ts=.06,Rn={x:.5,y:1-Ts-48/720/2},au=.1,ou=8;function ai(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function lu(n){return Math.min(ou,Math.max(au,n))}function xe(n){return{x:ai(n==null?void 0:n.x,Pr.x),y:ai(n==null?void 0:n.y,Pr.y),scale:lu(ai(n==null?void 0:n.scale,Pr.scale))}}function qe(n){return{x:ai(n==null?void 0:n.x,Rn.x),y:ai(n==null?void 0:n.y,Rn.y),scale:1}}function bs(n,e,t=1e-4){const i=xe(n),r=xe(e);return Math.abs(i.x-r.x)<=t&&Math.abs(i.y-r.y)<=t&&Math.abs(i.scale-r.scale)<=t}function yo(n,e){if(n.width<=0||n.height<=0)return{left:0,top:0,width:0,height:0,centerX:0,centerY:0};const t=e.width>0?e.width:n.width,i=e.height>0?e.height:n.height,r=t/i,s=n.width/n.height;let a=n.width,o=n.height;r>s?o=a/r:a=o*r;const l=(n.width-a)/2,c=(n.height-o)/2;return{left:l,top:c,width:a,height:o,centerX:l+a/2,centerY:c+o/2}}function Mn(n,e,t){const i=yo(n,e),r=xe(t),s=i.width*r.scale,a=i.height*r.scale,o=n.width*r.x,l=n.height*r.y;return{left:o-s/2,top:l-a/2,width:s,height:a,centerX:o,centerY:l}}function So(n,e,t,i){const r=xe(n),s=i.width>0?i.width:1,a=i.height>0?i.height:1;return xe({x:r.x+e/s,y:r.y+t/a,scale:r.scale})}function cu(n,e,t,i,r,s){const a=xe(s),o=Math.max(r.width/2,1),l=Math.max(r.height/2,1),c=Math.abs(t-n)/o,h=Math.abs(i-e)/l;return xe({x:a.x,y:a.y,scale:Math.max(c,h)})}const Co=1,hu=48,du=48,vo=16,uu=4e3,pu=4e3,gu=1.35,fu=.55,mu=1;function yu(n){return/[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff]/.test(n)}function ks(n){return n>0?n:1}function To(n,e,t,i){const r=ks(i);return{fontSize:n*r,paddingX:e*r,strokeWidth:t*r}}function Su(n,e,t,i=.5){if(n<=0||e<=0)return 0;const r=Math.max(0,n/e-t*2),s=Math.min(1,Math.max(0,i)),a=n*s,o=Math.min(a,n-a),l=Math.max(0,o*2/e-t*2);return Math.min(r,l)}function Cu(n,e,t,i){const r=Math.max(1,n),s=e.split(`
734
- `),a=Math.max(1,t-i*2),o=yu(e)?mu:fu,l=Math.max(1,Math.floor(a/(r*o)));let c=0;for(const h of s){const d=h.length>0?h:" ";c+=Math.max(1,Math.ceil(d.length/l))}return Math.max(vo,Math.round(r*gu*c))}function vu(n,e=hu){const t=n>0?n:720;return{x:.5,y:1-Ts-e/t/2,scale:1}}function bo(n,e){return n.anchorVersion!==Co?!0:e>=1-Ts-.008}function ko(n,e,t,i){return n.height<=0?0:bo(t,e.y)?n.height*e.y-i/2:n.height*e.y}function Tu(n,e,t){const i=e.height>0?e.height:1,r=t/i/2;return{x:n.x,y:n.y-r,scale:1}}function wo(n,e,t,i){const r={x:typeof(n==null?void 0:n.x)=="number"&&Number.isFinite(n.x)?n.x:.5,y:typeof(n==null?void 0:n.y)=="number"&&Number.isFinite(n.y)?n.y:.5,scale:1};return bo(e,r.y)?Tu(r,t,i):r}function xo(n){return Math.min(uu,Math.max(du,n))}function Po(n){return Math.min(pu,Math.max(vo,n))}function _o(n){return n.layoutHeight!==void 0}function bu(n){return _o(ce(n))?"manual":"auto"}function ws(n){var o,l,c;const e=n.textStyle,t=((o=n.styleOverride)==null?void 0:o.fontSize)??e.fontSize,i=n.frameSize,r=ks(n.baselineScale),s=xo(((l=n.styleOverride)==null?void 0:l.layoutWidth)??e.layoutWidth??Su(i.width,r,e.paddingX,n.visualTransform.x)),a=Po(((c=n.styleOverride)==null?void 0:c.layoutHeight)??e.layoutHeight??Cu(t,n.contentText,s,e.paddingX));return{layoutWidth:s,layoutHeight:a}}function Ao(n){const{layoutWidth:e,layoutHeight:t}=ws(n),i=e*n.baselineScale,r=t*n.baselineScale,s=n.frameSize.width*n.visualTransform.x,a=ko(n.frameSize,n.visualTransform,n.textStyle,r),o={left:s-i/2,top:a-r/2,width:i,height:r,centerX:s,centerY:a};return{layoutWidth:e,layoutHeight:t,frameRect:o,visualTransform:n.visualTransform}}function ku(n,e,t,i,r){const s=ks(r),a=Math.abs(n-t),o=Math.abs(e-i);return{layoutWidth:xo(Math.round(a*2/s)),layoutHeight:Po(Math.round(o*2/s))}}function Io(n,e,t,i){const r=ce(n.clip.textStyle),s=n.clip.textContent||n.clip.name||"",{layoutHeight:a}=ws({frameSize:e,baselineScale:t,visualTransform:{x:.5,y:.5,scale:1},textStyle:r,contentText:s,styleOverride:i}),o=a*t,l=wo(n.clip.visualTransform,r,e,o);return Ao({frameSize:e,baselineScale:t,visualTransform:l,textStyle:r,contentText:s,styleOverride:i})}function Eo(n){const{layout:e,frameSize:t,baselineScale:i,visualTransform:r,textStyle:s,measuredHeightPx:a}=n,o=t.width*r.x,l=ko(t,r,s,a);return{...e,layoutHeight:Math.ceil(a/i),visualTransform:r,frameRect:{...e.frameRect,width:e.frameRect.width,height:a,centerX:o,centerY:l,left:o-e.frameRect.width/2,top:l-a/2}}}function Ro(n){const{frameSize:e,composition:t,lastLayout:i,layoutMode:r}=n,s=e.width>0?e.width:t.width,a=e.height>0?e.height:t.height,{layoutWidth:o,layoutHeight:l}=i;return{compositionWidth:t.width,compositionHeight:t.height,layoutWidth:o,layoutHeight:l,layoutWidthRatio:t.width>0?o/t.width:0,layoutHeightRatio:t.height>0?l/t.height:0,centerX:s>0?i.frameRect.centerX/s:0,centerY:a>0?i.frameRect.centerY/a:0,layoutMode:r,anchorVersion:Co}}function wu(n,e,t=1e-4){return!n&&!e?!0:!n||!e?!1:n.compositionWidth===e.compositionWidth&&n.compositionHeight===e.compositionHeight&&n.layoutWidth===e.layoutWidth&&n.layoutHeight===e.layoutHeight&&n.layoutMode===e.layoutMode&&n.anchorVersion===e.anchorVersion&&Math.abs(n.centerX-e.centerX)<=t&&Math.abs(n.centerY-e.centerY)<=t}function xu(n){if(!n||typeof n!="object")return!1;const e=n;if(typeof e.closest=="function")return!!e.closest(".timeline-preview-transform-handle");const t=e.className;return typeof t=="string"&&t.includes("timeline-preview-transform-handle")}function Ln(n){if(!n)return 0;const e=Number.parseFloat(n);return Number.isFinite(e)?e:0}class Pu{constructor(e={}){p(this,"frameElement",null);p(this,"overlayElement",null);p(this,"boxElement",null);p(this,"rotateHandleElement",null);p(this,"rotateHandlePointerDownHandler",null);p(this,"handleElements",new Map);p(this,"handlePointerDownHandlers",new Map);p(this,"state",null);p(this,"interaction",null);p(this,"textHostElement",null);p(this,"callbacks");p(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});p(this,"boundPointerUp",()=>{this.finishInteraction(!0)});p(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});p(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});p(this,"handleMovePointerDown",e=>{var i,r,s,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=(s=this.callbacks).onTextTransformInteractionStart)==null||a.call(s)),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,startLayoutWidth:void 0,startLayoutHeight:void 0,nextLayoutWidth:void 0,nextLayoutHeight: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 ${ze.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),this.setTextHost(null),(e=this.boxElement)==null||e.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,r)=>{const s=this.handlePointerDownHandlers.get(r);s&&i.removeEventListener("pointerdown",s)}),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.setTextHost(null),this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==e.clipId&&this.finishInteraction(!1),this.setTextHost(e.clipType==="text"?e.textHostElement??null:null),this.state=e,this.render()}handleTextHostPointerDown(e){xu(e.target)||this.handleMovePointerDown(e)}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 ${ze.border}`,e.style.background=ze.handleBackground,e.style.pointerEvents="auto",e.style.cursor="grab",e.style.boxSizing="border-box",e.style.transform="translate(-50%, -50%)",e.style.alignItems="center",e.style.justifyContent="center",e.style.fontSize="12px",e.style.color=ze.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,s=this.toLocalPoint(t),a=Math.atan2(s.y-r,s.x-i)*(180/Math.PI);this.interaction={clipId:this.state.clipId,mode:"rotate",pointerStart:s,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,startLayoutWidth:void 0,startLayoutHeight:void 0,nextLayoutWidth:void 0,nextLayoutHeight: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 ${ze.border}`,i.style.background=ze.handleBackground,i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=t,i.style.boxSizing="border-box",i.style.zIndex="10",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 s=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:s,clipType:this.state.clipType??"video",startFontSize:void 0,nextFontSize:void 0,startLayoutWidth:r?this.state.currentLayoutWidth:void 0,startLayoutHeight:r?this.state.currentLayoutHeight:void 0,nextLayoutWidth:r?this.state.currentLayoutWidth:void 0,nextLayoutHeight:r?this.state.currentLayoutHeight:void 0,centerX:a,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor(s),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,r,s,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=(s=globalThis.window)==null?void 0:s.addEventListener)==null||a.call(s,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,r,s,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=(s=globalThis.window)==null?void 0:s.removeEventListener)==null||a.call(s,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var s,a,o,l,c,h,d,u;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const t=e;(s=t.preventDefault)==null||s.call(t);const i=this.toLocalPoint(t);if(this.interaction.mode==="rotate"&&this.interaction.startRotation!==void 0){const g=i.x-this.interaction.centerX,f=i.y-this.interaction.centerY,C=Math.atan2(f,g)*(180/Math.PI)-this.interaction.startAngle,v=Math.round(this.interaction.startRotation+C);this.interaction.nextRotation=v,this.interaction.changed=v!==this.interaction.startRotation,(o=(a=this.callbacks).onRotationChange)==null||o.call(a,this.interaction.clipId,v);return}if(this.interaction.clipType==="text"&&this.interaction.startLayoutWidth!==void 0&&this.interaction.startLayoutHeight!==void 0){const g=ku(i.x,i.y,this.interaction.centerX,this.interaction.centerY,((l=this.state)==null?void 0:l.baselineScale)??1);this.interaction.nextLayoutWidth=g.layoutWidth,this.interaction.nextLayoutHeight=g.layoutHeight,this.interaction.changed=g.layoutWidth!==this.interaction.startLayoutWidth||g.layoutHeight!==this.interaction.startLayoutHeight,(h=(c=this.callbacks).onTextLayoutChange)==null||h.call(c,this.interaction.clipId,g);return}let r=this.interaction.startTransform;if(this.interaction.mode==="move")r=So(this.interaction.startTransform,i.x-this.interaction.pointerStart.x,i.y-this.interaction.pointerStart.y,this.interaction.frameSize);else{const g=this.interaction.startTransform.x*this.interaction.frameSize.width,f=this.interaction.startTransform.y*this.interaction.frameSize.height;r=cu(g,f,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!bs(this.interaction.startTransform,r),(u=(d=this.callbacks).onPreviewTransformChange)==null||u.call(d,this.interaction.clipId,r)}finishInteraction(e){var i,r,s,a,o,l,c,h,d,u,g,f,m,C,v,S;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=(s=this.callbacks).onRotationChange)==null||a.call(s,t.clipId,null)):t.clipType==="text"?t.mode==="move"?(e&&t.changed&&((l=(o=this.callbacks).onPreviewTransformCommit)==null||l.call(o,t.clipId,t.nextTransform)),(h=(c=this.callbacks).onPreviewTransformChange)==null||h.call(c,t.clipId,null)):t.mode==="scale"&&(e&&t.changed&&t.nextLayoutWidth!==void 0&&t.nextLayoutHeight!==void 0&&((u=(d=this.callbacks).onTextLayoutCommit)==null||u.call(d,t.clipId,{layoutWidth:t.nextLayoutWidth,layoutHeight:t.nextLayoutHeight})),(f=(g=this.callbacks).onTextLayoutChange)==null||f.call(g,t.clipId,null)):(e&&t.changed&&((C=(m=this.callbacks).onPreviewTransformCommit)==null||C.call(m,t.clipId,t.nextTransform)),(S=(v=this.callbacks).onPreviewTransformChange)==null||S.call(v,t.clipId,null)),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners(),this.render()}render(){if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none"),this.rotateHandleElement&&(this.rotateHandleElement.style.display="none");return}const{displayRect:e}=this.state,t=this.state.clipType==="text",i=t?this.textHostElement:null;t&&i?this.renderTextHostHandles(i,e):this.boxElement&&this.renderOverlayBox(this.boxElement,e,t?this.state.currentRotation??0:0),this.renderRotateHandle(e,t)}renderTextHostHandles(e,t){this.boxElement&&(this.boxElement.style.display="none",this.boxElement.style.pointerEvents="none");const i=e.offsetWidth>0?e.offsetWidth:t.width,r=e.offsetHeight>0?e.offsetHeight:t.height;this.mountHandlesOn(e),this.positionHandle("top-left",0,0),this.positionHandle("top-right",i,0),this.positionHandle("bottom-right",i,r),this.positionHandle("bottom-left",0,r)}renderOverlayBox(e,t,i){this.mountHandlesOn(e),e.style.display="block",e.style.pointerEvents="auto",e.style.cursor="grab",e.style.border=`1px solid ${ze.border}`,e.style.left=`${t.left}px`,e.style.top=`${t.top}px`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`,e.style.transformOrigin="center",e.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)}renderRotateHandle(e,t){var i,r;if(this.rotateHandleElement){if(!t){this.rotateHandleElement.style.display="none";return}if(((i=this.interaction)==null?void 0:i.mode)!=="rotate"){const s=e.left+e.width/2,a=e.top+e.height/2,o=e.height/2+20,c=(((r=this.state)==null?void 0:r.currentRotation)??0)*(Math.PI/180);this.rotateHandleElement.style.left=`${s-o*Math.sin(c)}px`,this.rotateHandleElement.style.top=`${a+o*Math.cos(c)}px`}this.rotateHandleElement.style.display="flex"}}setTextHost(e){this.textHostElement!==e&&(this.textHostElement=e,!e&&this.boxElement&&this.mountHandlesOn(this.boxElement))}mountHandlesOn(e){for(const t of this.handleElements.values())t.parentElement!==e&&e.appendChild(t)}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:Ln(this.frameElement.style.left),top:Ln(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||"")}}class _u{constructor(e){p(this,"container",null);p(this,"statusElement",null);p(this,"actionElement",null);p(this,"onRetry");this.onRetry=e}mount(e){this.container=e,this.container.className="timeline-preview-pending-overlay",this.container.style.position="absolute",this.container.style.top="12px",this.container.style.left="12px",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="flex-start",this.container.style.flexDirection="row",this.container.style.gap="8px",this.container.style.background=Ge.background,this.container.style.color=Ge.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=Ge.actionBackground,i.style.color=Ge.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,s=!!(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=s?Ge.failedBackground:Ge.background,this.container.style.color=s?Ge.failedText:Ge.text,s){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}}function Au(n,e){var u;const t=n.activeClips.filter(g=>g.trackType!=="text"),i=n.nextClips.filter(g=>g.trackType!=="text"),r=n.interactionMode??"steady",s=new Map(t.map(g=>[g.trackId,g])),a=new Map(i.map(g=>[g.trackId,g])),o=new Map,l=t.filter(g=>g.trackType==="video"&&g.hasVisual).sort((g,f)=>g.trackOrder-f.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(g,f)=>!a.has(g)||r!=="steady"&&c?!1:c?n.playState==="playing"&&f==="video"&&g===h:n.playState!=="playing"||t.length<=1;return e.forEach(g=>{o.set(g.trackId,{kind:g.kind,order:g.order})}),t.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),i.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),Array.from(o.entries()).map(([g,f])=>{const m=s.get(g)||null,C=d(g,f.kind)&&a.get(g)||null;return{trackId:g,kind:f.kind,order:f.order,current:{role:"current",entry:m,playState:n.requestedPlayState??n.playState,speed:n.speed,visible:!!(m!=null&&m.hasVisual),zIndex:m?1e3-m.trackOrder:0,syncRequestId:n.syncRequestId},preload:{role:"preload",entry:C,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:n.syncRequestId}}}).sort((g,f)=>g.order-f.order)}function Dn(n,e){return n.entry?e?n.entry.clip.id===e:!0:!1}function Iu(n,e){return e?!Dn(n.current,e.clip.id)&&Dn(n.preload,e.clip.id):!1}function Eu(n){return n.current.role="preload",n.preload.role="current",{current:n.preload,preload:n.current}}const Ru=2,Mu=.5,Lu=750,Du="媒体丢失";function Wi(n){return!!n&&typeof n.then=="function"}function is(n){return n.getAttribute("src")||n.currentSrc||n.src||""}function oi(n){return n.getAttribute("src")||""}function At(n){return typeof HTMLVideoElement<"u"?n instanceof HTMLVideoElement:n.tagName==="VIDEO"}function jt(n){try{n.load()}catch{}}function qt(n){try{n.pause()}catch{}}function rs(n){var e;try{const t=n.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function On(n,e){try{n.currentTime=Math.max(0,e)}catch{}}function nr(n,e){var i;const t=(i=n==null?void 0:n.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function Bn(n){if(!n)return 0;const e=Number.parseFloat(n);return Number.isFinite(e)?e:0}function Ou(n){const e=n.buffered;return!e||typeof e.length!="number"||e.length<=0?null:e.end(e.length-1)}function Bu(n){return{tsMs:Date.now(),currentTime:n.currentTime,duration:n.duration,currentSrc:n.currentSrc||n.src||null,readyState:n.readyState,networkState:n.networkState,paused:n.paused,ended:n.ended,playbackRate:n.playbackRate,bufferedEnd:Ou(n),videoWidth:At(n)?n.videoWidth:0,videoHeight:At(n)?n.videoHeight:0,error:n.error?{code:n.error.code,message:n.error.message}:null}}function Fn(n,e,t){return t?n===t||e===t:!1}function ar(n,e){const t=n==="current"?Math.abs(e||1):1;return Math.max(.1,t*.15)}function nt(n){var e;return((e=n.externalId)==null?void 0:e.trim())||n.src}function Fu(n){const e=n==null?void 0:n.trim();return e?`clip:${e}`:null}function ss(n){return typeof n=="string"&&n.startsWith("blob:")}function Hu(n,e){return n||(ss(e)?e:null)}class Gu{constructor(){p(this,"pendingClockAlignmentTargetTime",null)}updateAlignmentTarget(e,t,i){if(!e){this.pendingClockAlignmentTargetTime=null;return}(t==="seek"||t==="scrub")&&(this.pendingClockAlignmentTargetTime=i)}buildClockState(e,t,i){const r=this.getClockSourceSlot(t);if(!(r!=null&&r.entry))return this.buildFromSlot(null,"unavailable","no-video-clock");const s=r.sourceMatchesDesired(),a=this.getMediaTimeMs(r),o=this.getTimelineTime(r,a),l=r.requestedPlayState==="playing"&&!r.element.ended;return e.status==="failed"||r.phase==="failed"?this.buildFromSlot(r,"failed","failed",o,a):l?!s||r.isResolvingSource||r.phase==="binding"?this.buildFromSlot(r,"priming","resolving-source",o,a):r.isSeeking||e.reason==="seeking"?this.buildFromSlot(r,"blocked","seeking",o,a):this.isMediaTimeAligned(r,a)?r.isBuffering||i?this.buildFromSlot(r,"blocked","media-stalled",o,a):this.isTimelineAligned(r,o)?e.status==="loading"?this.buildFromSlot(r,"blocked",this.resolveBlockedReason(e.reason),o,a):r.element.paused?this.buildFromSlot(r,"blocked","media-paused",o,a):o===null||a===null?this.buildFromSlot(r,"priming","media-pending",o,a):(this.pendingClockAlignmentTargetTime=null,this.buildFromSlot(r,"running",null,o,a)):this.buildFromSlot(r,"blocked","seeking",o,a):this.buildFromSlot(r,"blocked","seeking",o,a):this.buildFromSlot(r,"unavailable",null,o,a)}getClockSourceSlot(e){var i,r;const t=[];for(const s of e)s.role!=="current"||!s.isActive||s.kind!=="video"||!((i=s.entry)!=null&&i.hasVisual)||t.push(this.buildCandidate(s));return t.length===0?(this.pendingClockAlignmentTargetTime=null,null):(t.sort((s,a)=>this.compareCandidates(s,a)),((r=t[0])==null?void 0:r.slot)??null)}buildCandidate(e){const t=this.getMediaTimeMs(e),i=this.getTimelineTime(e,t),r=e.sourceMatchesDesired(),s=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=s>=Ru||e.hasReadyEventSinceSourceChange,c=!!e.entry&&r&&l&&!e.isResolvingSource&&e.phase!=="binding"&&e.phase!=="failed"&&!e.isSeeking&&!e.isBuffering&&(!o||!e.element.paused)&&t!==null&&i!==null;return{slot:e,timelineTime:i,targetDistance:a,sourceMatched:r,readyState:s,usable:c}}compareCandidates(e,t){var s,a;const i=this.isCandidateAligned(e),r=this.isCandidateAligned(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:(((s=e.slot.entry)==null?void 0:s.trackOrder)??0)-(((a=t.slot.entry)==null?void 0:a.trackOrder)??0)}isCandidateAligned(e){return this.pendingClockAlignmentTargetTime!==null&&e.usable&&e.targetDistance<=this.getAlignmentThresholdMs(e.slot)}getAlignmentThresholdMs(e){return Math.max(Lu,ar("current",e.element.playbackRate||1)*1e3)}isMediaTimeAligned(e,t){const i=e.pendingClockAlignmentMediaTime;return i===null?!0:t===null||Math.abs(t-i)>this.getAlignmentThresholdMs(e)?!1:(e.pendingClockAlignmentMediaTime=null,!0)}isTimelineAligned(e,t){return this.pendingClockAlignmentTargetTime===null||t===null?!0:Math.abs(t-this.pendingClockAlignmentTargetTime)<=this.getAlignmentThresholdMs(e)}getMediaTimeMs(e){return Number.isFinite(e.element.currentTime)?Math.max(0,e.element.currentTime*1e3):null}getTimelineTime(e,t){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))}buildFromSlot(e,t,i,r=null,s=null){var a;return{status:t,timelineTime:r,mediaTime:s,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}}resolveBlockedReason(e){return e==="syncing"||e==="resolving-source"||e==="seeking"||e==="media-pending"||e==="failed"?e:"media-pending"}}function Nu(n,e){return!kt(n.mode)||!e?n:{mode:Le.mode,width:e.width,height:e.height}}class zu{constructor(e){p(this,"container",null);p(this,"rootElement",null);p(this,"frameElement",null);p(this,"resizeObserver",null);p(this,"onFrameLayoutChange",null);p(this,"requestedAspectRatio",{...Le});p(this,"resolvedAutoAspectRatio",null);p(this,"transformOverlay");this.transformOverlay=e}attach(e,t){if(this.onFrameLayoutChange=t.onFrameLayoutChange??null,this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e,this.onFrameLayoutChange=t.onFrameLayoutChange??null;const i=document.createElement("div");i.className=t.rootClassName??"timeline-preview-root",i.style.position="relative",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden";const r=document.createElement("div");r.className=t.frameClassName??"timeline-preview-frame",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.overflow="hidden",r.style.background=P.black,i.appendChild(r),e.appendChild(i),this.rootElement=i,this.frameElement=r,this.transformOverlay.attach(r),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(e)),this.updateFrameLayout()}detach(){var e,t;(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,this.onFrameLayoutChange=null,this.transformOverlay.detach(),(t=this.rootElement)==null||t.remove(),this.rootElement=null,this.frameElement=null,this.container=null,this.resolvedAutoAspectRatio=null}getFrameElement(){return this.frameElement}getRootElement(){return this.rootElement}applyAspectRatio(e){this.requestedAspectRatio=Ue(e),this.updateFrameLayout()}getAspectRatio(){return Nu(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}resolveAutoAspectRatio(e,t,i){e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),i&&kt(this.requestedAspectRatio.mode)&&i(this.getAspectRatio()))}tryResolveAutoAspectRatioFromSlot(e,t){if(!kt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const i=e.element;At(i)&&i.videoWidth>0&&i.videoHeight>0&&this.resolveAutoAspectRatio(i.videoWidth,i.videoHeight,t)}refreshSlotVisual(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=xe(e.entry.clip.visualTransform),s=Mn(t,i,r);e.wrapper.style.left=`${s.left}px`,e.wrapper.style.top=`${s.top}px`,e.wrapper.style.width=`${s.width}px`,e.wrapper.style.height=`${s.height}px`,this.syncFailureVisual(e)}buildSelectedOverlayState(e,t,i,r){var m,C;if(!e)return null;const s=this.getFrameSize();if(s.width<=0||s.height<=0)return null;for(const v of t){if(v.kind!=="video"||!v.isActive||!v.entry||v.entry.clip.id!==e)continue;const S=this.getMediaSize(v,v.entry,s),T=r(v.entry);return{clipId:v.entry.clip.id,transform:T,frameSize:s,baseRect:yo(s,S),displayRect:Mn(s,S,T),clipType:"video"}}const a=i.getEntry(e);if(!a||!this.frameElement)return null;const o=this.getTextBaselineMetrics(s),l=((m=i.getTextLayoutOverride)==null?void 0:m.call(i,e))??null,h=((C=i.getLayout)==null?void 0:C.call(i,e))??null??Io(a.entry,s,o.scale,l),d=ce(a.entry.clip.textStyle),u=h.visualTransform,g=i.getTransientFontSize(e)??d.fontSize,f=i.getTransientRotation(e)??d.rotation;return{clipId:e,transform:u,frameSize:s,baseRect:{left:0,top:0,width:s.width,height:s.height,centerX:s.width/2,centerY:s.height/2},displayRect:h.frameRect,clipType:"text",currentFontSize:g,currentRotation:f,currentLayoutWidth:h.layoutWidth,currentLayoutHeight:h.layoutHeight,textHostElement:a.element,baselineScale:o.scale}}getFrameSize(){var i,r,s,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:Bn((s=this.frameElement)==null?void 0:s.style.width),height:t>0?t:Bn((a=this.frameElement)==null?void 0:a.style.height)}}getTextBaselineMetrics(e){const t=ji(this.getAspectRatio(),os);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)}}moveTransform(e,t,i){return So(e,t,i,this.getFrameSize())}transformsEqual(e,t){return bs(e,t)}updateFrameLayout(){var h;if(!this.container||!this.frameElement)return;const e=this.getAspectRatio(),t=this.container.clientWidth,i=this.container.clientHeight;if(t<=0||i<=0||e.width<=0||e.height<=0)return;const r=t/i,s=e.width/e.height;let a=t,o=i,l=0,c=0;r>s?(a=i*s,l=(t-a)/2):(o=t/s,c=(i-o)/2),this.frameElement.style.width=`${a}px`,this.frameElement.style.height=`${o}px`,this.frameElement.style.left=`${l}px`,this.frameElement.style.top=`${c}px`,(h=this.onFrameLayoutChange)==null||h.call(this)}getMediaSize(e,t,i){if(At(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=nr(t,"sys_width"),s=nr(t,"sys_height");return r&&s?{width:r,height:s}:{width:i.width,height:i.height}}syncFailureVisual(e){if(!e.wrapper||!e.failureOverlay||!e.failureLabel)return;const t=e.phase==="failed"&&!!e.entry;e.wrapper.style.background=t?P.mediaClipFailedBackground:P.black,e.failureOverlay.style.display=t?"flex":"none",e.failureLabel.textContent=Du,e.element.style.visibility=t?"hidden":"visible"}}const $u=500;class Hn{constructor(e,t,i,r={}){p(this,"trackId");p(this,"kind");p(this,"role");p(this,"element");p(this,"wrapper");p(this,"failureOverlay");p(this,"failureLabel");p(this,"entry",null);p(this,"stableSourceUrl",null);p(this,"boundStableKey",null);p(this,"desiredSource",null);p(this,"objectUrl",null);p(this,"objectUrlHolderId",null);p(this,"requestedPlayState","paused");p(this,"isActive",!1);p(this,"isLoading",!1);p(this,"isResolvingSource",!1);p(this,"isBuffering",!1);p(this,"isSeeking",!1);p(this,"phase","idle");p(this,"errorMessage",null);p(this,"hasReadyEventSinceSourceChange",!1);p(this,"pendingClockAlignmentMediaTime",null);p(this,"sourceGen",0);p(this,"loadSourceGen",0);p(this,"sourceNode",null);p(this,"gainNode",null);p(this,"audioRoutingFailed",!1);p(this,"cleanup",[]);p(this,"lastPlaybackResumeAttemptAtMs",-1);p(this,"options");this.trackId=e,this.kind=t,this.role=i,this.options=r,this.element=this.createMediaElement(t,i),this.wrapper=t==="video"?document.createElement("div"):null,this.failureOverlay=t==="video"?document.createElement("div"):null,this.failureLabel=t==="video"?document.createElement("div"):null,this.setupWrapper(),this.bindMediaEvents()}takeTrackedObjectUrl(){const e={url:this.objectUrl,holderId:this.objectUrlHolderId};return this.objectUrl=null,this.objectUrlHolderId=null,e}mountVideoTo(e){this.wrapper&&e.appendChild(this.wrapper)}mountAudioTo(e){this.kind==="audio"&&e.appendChild(this.element)}clear(){this.sourceGen+=1,qt(this.element),this.entry=null,this.desiredSource=null,this.stableSourceUrl=null,this.boundStableKey=null,this.pendingClockAlignmentMediaTime=null,this.hasReadyEventSinceSourceChange=!1,this.isActive=!1,this.isLoading=!1,this.isResolvingSource=!1,this.isBuffering=!1,this.isSeeking=!1,this.errorMessage=null,this.phase="idle",this.element.removeAttribute("src"),jt(this.element),this.setVisible(!1,0)}fail(e){var t,i;if(this.role==="preload"){this.clear();return}this.phase="failed",this.errorMessage=e,this.isLoading=!1,this.isResolvingSource=!1,this.isSeeking=!1,this.isBuffering=!1,(i=(t=this.options).onStateChange)==null||i.call(t)}clearFailureIfClipChanged(){this.phase==="failed"&&(this.phase="binding",this.errorMessage=null)}assignSource(e,t){var o,l;const i=oi(this.element),r=is(this.element),s=!i&&!!e.url,a=this.boundStableKey!==t||s||!Fn(i,r,e.url);return a?(this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url,this.loadSourceGen=this.sourceGen,this.hasReadyEventSinceSourceChange=!1,this.element.setAttribute("src",e.url),jt(this.element),(l=(o=this.options).onDiagnostic)==null||l.call(o,"source.assigned",this,{playbackUrl:e.url,stableKey:t})):!i&&e.url?(this.element.setAttribute("src",e.url),jt(this.element),this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url,this.loadSourceGen=this.sourceGen):(this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url),a}applyPlayback(e,t,i,r,s){var a,o;this.entry=e,this.requestedPlayState=t,this.isActive=this.role==="current",this.element.playbackRate=this.role==="current"?i:1,this.role==="current"?this.syncCurrentPlayback(e,t,i):this.preparePreload(e),!this.isLoading&&!this.isSeeking&&this.phase!=="failed"&&((this.element.readyState??0)>=2&&this.sourceMatchesDesired()?(this.phase=this.isActive?"active":"primed",this.isLoading=!1):this.isLoading||(this.phase=this.isActive?"active":"primed")),this.setVisible(r,s),(o=(a=this.options).onStateChange)==null||o.call(a)}sourceMatchesDesired(){return Fn(oi(this.element),is(this.element),this.desiredSource)}maybeResumePlayback(e){if(this.role!=="current"||!this.isActive||!this.entry||this.requestedPlayState!=="playing"||this.element.paused!==!0||this.phase==="failed"||!oi(this.element))return;const t=Date.now();e==="runtime-check"&&(this.lastPlaybackResumeAttemptAtMs>=0&&t-this.lastPlaybackResumeAttemptAtMs<$u||this.isBuffering||this.isSeeking)||(this.lastPlaybackResumeAttemptAtMs=t,rs(this.element))}destroy(e){var r,s,a,o,l;this.sourceGen+=1,this.cleanup.forEach(c=>c()),this.cleanup=[],qt(this.element);const{url:t,holderId:i}=this.takeTrackedObjectUrl();this.desiredSource=null,this.element.removeAttribute("src"),jt(this.element),e(t,i),(s=(r=this.gainNode)==null?void 0:r.disconnect)==null||s.call(r),(o=(a=this.sourceNode)==null?void 0:a.disconnect)==null||o.call(a),(l=this.wrapper)==null||l.remove(),this.element.remove()}syncCurrentPlayback(e,t,i){const r=e.mediaTime/1e3,s=t==="playing"?Math.max(Mu,i*.15):ar("current",i),a=t==="playing"&&!this.element.ended;Math.abs(this.element.currentTime-r)>s&&(this.isSeeking=!0,On(this.element,r)),a?this.element.paused&&rs(this.element):qt(this.element)}preparePreload(e){const t=e.mediaTime/1e3;qt(this.element),Math.abs(this.element.currentTime-t)>ar("preload",1)&&On(this.element,t)}setVisible(e,t){this.wrapper&&(this.wrapper.style.display=e?"block":"none",this.wrapper.style.zIndex=String(t),At(this.element)&&(this.element.style.display=e?"block":"none",this.element.style.zIndex=String(t)))}createMediaElement(e,t){const i=this.options.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,At(r)?(hs(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=P.black,r.style.pointerEvents="none"):r.style.display="none",r}setupWrapper(){if(!this.wrapper||!this.failureOverlay||!this.failureLabel)return;const e=this.options.slotClassNamePrefix??"timeline-preview-slot";this.wrapper.className=`${e} timeline-preview-slot--${this.trackId} timeline-preview-slot--${this.role}`,this.wrapper.style.position="absolute",this.wrapper.style.overflow="hidden",this.wrapper.style.background=P.black,this.wrapper.style.display="none",this.failureOverlay.className="timeline-preview-slot__failure",this.failureOverlay.style.inset="0",this.failureOverlay.style.display="none",this.failureOverlay.style.alignItems="center",this.failureOverlay.style.justifyContent="center",this.failureOverlay.style.background="rgba(80, 0, 0, 0.72)",this.failureLabel.className="timeline-preview-slot__failure-label",this.failureOverlay.style.position="absolute",this.failureLabel.style.fontSize="14px",this.failureOverlay.appendChild(this.failureLabel),this.wrapper.appendChild(this.failureOverlay),this.wrapper.appendChild(this.element)}bindMediaEvents(){const e=d=>()=>{this.entry&&d()},t=e(()=>{var d,u,g,f;this.isLoading=!0,this.phase!=="failed"&&(this.phase="binding"),(u=(d=this.options).onDiagnostic)==null||u.call(d,"media.loadstart",this),(f=(g=this.options).onStateChange)==null||f.call(g)}),i=e(()=>{var d,u;this.hasReadyEventSinceSourceChange=!0,this.isBuffering=!1,this.isLoading=!1,this.isResolvingSource=!1,this.maybeResumePlayback("canplay"),(u=(d=this.options).onStateChange)==null||u.call(d)}),r=e(()=>{var d,u;this.hasReadyEventSinceSourceChange=!0,this.isBuffering=!1,this.isLoading=!1,(u=(d=this.options).onStateChange)==null||u.call(d)}),s=e(()=>{var d,u,g,f;this.isBuffering=this.role==="current"&&this.isActive&&this.requestedPlayState==="playing",(u=(d=this.options).onDiagnostic)==null||u.call(d,"media.stalled",this),(f=(g=this.options).onStateChange)==null||f.call(g)}),a=e(()=>{var d,u,g,f;this.isBuffering=this.role==="current"&&this.isActive&&this.requestedPlayState==="playing",(u=(d=this.options).onDiagnostic)==null||u.call(d,"media.waiting",this),(f=(g=this.options).onStateChange)==null||f.call(g)}),o=e(()=>{var d,u;this.isSeeking=!0,(u=(d=this.options).onStateChange)==null||u.call(d)}),l=e(()=>{var d,u;this.isSeeking=!1,this.hasReadyEventSinceSourceChange=!0,this.maybeResumePlayback("seeked"),(u=(d=this.options).onStateChange)==null||u.call(d)}),c=e(()=>{var u,g,f,m,C;if(!this.desiredSource||!this.sourceMatchesDesired()||this.loadSourceGen!==this.sourceGen)return;const d=((u=this.element.error)==null?void 0:u.message)||"媒体播放失败";(f=(g=this.options).onMediaError)==null||f.call(g,this,d),(C=(m=this.options).onDiagnostic)==null||C.call(m,"media.error",this,{mediaState:Bu(this.element)})});[["loadstart",t],["canplay",i],["playing",r],["stalled",s],["waiting",a],["seeking",o],["seeked",l],["error",c]].forEach(([d,u])=>{this.element.addEventListener(d,u),this.cleanup.push(()=>this.element.removeEventListener(d,u))})}}function Vu(n,e){if(!e||!n.entry)return{failed:!1,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1};const t=n.sourceMatchesDesired(),i=n.element.readyState??0,r=n.entry.mediaTime/1e3,s=Number.isFinite(n.element.currentTime)?n.element.currentTime:Number.NaN,a=ar("current",n.element.playbackRate||1),o=Number.isFinite(s)&&Math.abs(s-r)<=a,l=!!n.isSeeking&&!o,c=n.isResolvingSource,h=n.phase==="failed",d=!h&&!c&&!!n.desiredSource&&t&&!l&&i>=2&&(n.hasReadyEventSinceSourceChange||i>=2),u=n.requestedPlayState==="playing"&&!n.element.ended,g=d&&(!u||!n.element.paused),f=!g&&!h&&(!n.desiredSource||!t||n.phase==="binding"||i<2||n.isBuffering);return n.isSeeking=l,g&&(n.isLoading=!1,n.isBuffering=!1,n.phase!=="failed"&&(n.phase="active")),{failed:h,resolving:c,seeking:l,mediaUnready:f,ready:g}}class Uu{constructor(){p(this,"lastSignature",null);p(this,"lastState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});p(this,"lastSettledSyncRequestId",null)}getLastState(){return this.lastState}publish(e,t,i){var v;const r=[];let s=null,a=!1,o=0,l=0,c=!1,h=!1,d=!1,u=!1;for(const S of e.slots){const T=e.isTrackedVideo(S),k=T?e.evaluateTracked(S):null;r.push({trackId:S.trackId,role:S.role,kind:S.kind,clipId:((v=S.entry)==null?void 0:v.clip.id)??null,desiredSource:S.desiredSource,actualSource:is(S.element)||null,phase:S.phase,retryCount:0,errorMessage:S.errorMessage}),S.phase!=="idle"&&(a=!0),T&&(o+=1,k!=null&&k.failed&&(l+=1,c=!0,s||(s=S.errorMessage||"资源加载异常,请刷新重试")),k!=null&&k.resolving&&(h=!0),k!=null&&k.seeking&&(d=!0),k!=null&&k.mediaUnready&&(u=!0))}const g=this.buildLoadingState({trackedCount:o,failedTrackedCount:l,hasFailed:c,hasResolving:h,hasSeeking:d,hasMediaUnready:u,isSyncProjecting:e.isSyncProjecting,activeSyncRequestId:e.activeSyncRequestId});let f="idle";g.status==="failed"?f="failed":g.status==="loading"&&g.reason==="syncing"?f="awaiting-sync":g.status==="loading"?f="awaiting-media":(o>0&&g.status==="ready"||a)&&(f="ready"),g.status!=="failed"&&(s=null);const m={...e.activeSyncRequestId!==void 0?{syncRequestId:e.activeSyncRequestId}:{},phase:f,loading:g,clock:e.clock,errorMessage:s,slots:r},C=JSON.stringify(m);return C!==this.lastSignature&&(this.lastSignature=C,this.lastState=m,t(m)),(g.status==="ready"||g.status==="failed"||g.status==="idle")&&m.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==m.syncRequestId&&(this.lastSettledSyncRequestId=m.syncRequestId,i==null||i(m.syncRequestId)),m}reset(){this.lastSignature=null,this.lastSettledSyncRequestId=null,this.lastState={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:[]}}buildLoadingState(e){return e.trackedCount<=0?{status:"idle",isLoading:!1,reason:null}:e.hasFailed&&e.failedTrackedCount>=e.trackedCount?{status:"failed",isLoading:!1,reason:"failed"}:e.activeSyncRequestId!==void 0&&e.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:e.hasResolving?{status:"loading",isLoading:!0,reason:"resolving-source"}:e.hasSeeking?{status:"loading",isLoading:!0,reason:"seeking"}:e.hasMediaUnready?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}}class Wu{constructor(e){p(this,"syncGen",0);p(this,"pendingAsyncCount",0);p(this,"options");this.options=e}get isProjecting(){return this.pendingAsyncCount>0}applyTrackPlan(e){const t=this.options.getTrackSlots(e.trackId,e.kind),i=this.applySlotTarget(t.current,e.current),r=this.applySlotTarget(t.preload,e.preload);if(Wi(i)||Wi(r))return this.beginAsyncWork(),Promise.all([Promise.resolve(i),Promise.resolve(r)]).finally(()=>{this.endAsyncWork()}).then(()=>{})}bumpSyncGeneration(){return this.syncGen+=1,this.syncGen}applySlotTarget(e,t){const i=e.entry,r=i?nt(i.clip):null,s=!!i&&!!t.entry&&i.clip.id!==t.entry.clip.id;if(s&&e.clearFailureIfClipChanged(),e.entry=t.entry,e.requestedPlayState=t.playState,e.isActive=t.role==="current"&&!!t.entry,this.options.syncClockAlignment(e,t,s),!t.entry){const{url:d,holderId:u}=e.takeTrackedObjectUrl();e.clear(),this.options.releaseObjectUrl(d,u),this.options.onStateChange();return}const a=nt(t.entry.clip),o=this.options.sourceService.getReusableSource(e.boundStableKey,e.stableSourceUrl,e.desiredSource,e.objectUrl,t.entry);e.desiredSource&&!oi(e.element)&&(e.element.setAttribute("src",e.desiredSource),jt(e.element)),(r&&r!==a||!o&&s)&&(e.sourceGen+=1);const l=e.sourceGen,c=this.options.sourceService.resolve(t.entry,{sourceGen:l,getCurrentSourceGen:()=>e.sourceGen,reuse:o}),h=d=>{const u=e.sourceGen!==l,g=!this.options.isCurrentTarget(e,t.entry,a);if(!(!d||u||g)){if(e.isResolvingSource=!1,!oi(e.element)&&!d.url){e.fail("未找到可用预览源");return}if(e.phase==="failed"&&e.errorMessage){this.options.onStateChange();return}e.assignSource(d,a),this.options.rememberObjectUrl(e,Hu(d.objectUrl,d.url)),e.phase==="binding"&&e.sourceMatchesDesired()&&(e.phase=e.isActive?"active":"primed",e.isLoading=!1,e.isBuffering=!1),this.options.configureAudio(e,t.entry),e.applyPlayback(t.entry,t.playState,t.speed,t.visible,t.zIndex),this.options.onStateChange()}};if(Wi(c))return o||(e.isResolvingSource=!0,e.phase="binding",e.isLoading=!0,this.options.onStateChange()),c.then(d=>{if(!d){if(e.sourceGen!==l||!this.options.isCurrentTarget(e,t.entry,a))return;e.role==="current"?e.fail("未找到可用预览源"):e.clear(),this.options.onStateChange();return}h(d)});if(!c){e.role==="current"&&e.fail("未找到可用预览源"),this.options.onStateChange();return}h(c)}beginAsyncWork(){this.pendingAsyncCount+=1,this.options.onAsyncWorkStarted()}endAsyncWork(){this.pendingAsyncCount=Math.max(0,this.pendingAsyncCount-1),this.pendingAsyncCount===0&&this.options.onAsyncWorkFinished()}}function Kt(n){return n.role==="current"&&n.isActive&&n.kind==="video"&&!!n.entry}function Gn(n){const e=Kt(n),t=Vu(n,e);return e&&n.requestedPlayState==="playing"&&n.maybeResumePlayback("runtime-check"),t}const Yu={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function Xu(n){var e,t;try{const i=typeof location<"u"?location.href:"http://localhost/";return((e=new URL(n,i).pathname.split(".").pop())==null?void 0:e.toLowerCase())??""}catch{return((t=(n.split(/[?#]/,1)[0]??"").split(".").pop())==null?void 0:t.toLowerCase())??""}}function ju(n){const e=Xu(n.src);if(e==="mp4")return{url:n.src,mimeType:"video/mp4",kind:"mp4"};if(e==="m3u8")return{url:n.src,mimeType:"application/vnd.apple.mpegurl",kind:"hls-fmp4"};const t=Yu[e];return t?{url:n.src,mimeType:t,kind:"audio"}:null}class qu{constructor(e={}){p(this,"dependencies");p(this,"pendingCacheRuntime",new Map);this.dependencies=e}resolve(e,t){if(t.reuse)return t.reuse;const i=this.dependencies.previewSourceResolver??ju,r=this.dependencies.sourceMediaRegistry,s=nt(e.clip);try{const a=r?r.getPreviewSource(s,()=>i(e.clip)):i(e.clip);return Wi(a)?a.then(o=>t.getCurrentSourceGen()!==t.sourceGen?null:o?(this.emit("source.resolve.resolved",{clipId:e.clip.id,sourceUrl:e.clip.src,desiredSourceUrl:o.url}),this.resolvePlayable(e,o,t.getCurrentSourceGen,t.sourceGen)):(this.emit("source.resolve.missing",{clipId:e.clip.id,sourceUrl:e.clip.src}),null)).catch(o=>(this.emit("source.resolve.failed",{clipId:e.clip.id,sourceUrl:e.clip.src,error:o}),N.warn("PreviewSourceService","preview source resolver failed",{clipId:e.clip.id,error:o}),null)):a?(this.emit("source.resolve.resolved",{clipId:e.clip.id,sourceUrl:e.clip.src,desiredSourceUrl:a.url}),this.resolvePlayable(e,a,t.getCurrentSourceGen,t.sourceGen)):(this.emit("source.resolve.missing",{clipId:e.clip.id,sourceUrl:e.clip.src}),null)}catch(a){return this.emit("source.resolve.failed",{clipId:e.clip.id,sourceUrl:e.clip.src,error:a}),null}}getReusableSource(e,t,i,r,s){const a=nt(s.clip);if(!e||e!==a||!t||!i)return null;const o=r??(i.startsWith("blob:")?i:null);return{stableSourceUrl:t,url:i,objectUrl:o,sizeBytes:null}}resolvePlayable(e,t,i,r){const s={url:t.url,mimeType:t.mimeType,kind:t.kind},a=this.dependencies.resourceCacheManager;if(!a)return{stableSourceUrl:s.url,url:s.url,objectUrl:null,sizeBytes:null};const o=nt(e.clip),l=`${o}:${s.url}:${e.clip.id}`;let c=this.pendingCacheRuntime.get(l);return c||(c=a.resolvePlayableUrl({url:s.url,mimeType:s.mimeType,kind:s.kind,sourceKey:o}),this.pendingCacheRuntime.set(l,c),c.finally(()=>{this.pendingCacheRuntime.get(l)===c&&this.pendingCacheRuntime.delete(l)})),c.then(h=>this.normalizeCachedResult(s.url,h,i,r)).catch(()=>i()!==r?null:{stableSourceUrl:s.url,url:s.url,objectUrl:null,sizeBytes:null})}normalizeCachedResult(e,t,i,r){return i()!==r?null:t!=null&&t.url?{stableSourceUrl:e,url:t.url,objectUrl:t.url.startsWith("blob:")?t.url:null,sizeBytes:null}:{stableSourceUrl:e,url:e,objectUrl:null,sizeBytes:null}}emit(e,t){var i,r;(r=(i=this.dependencies).onDiagnostic)==null||r.call(i,e,t)}}const Ku=1.35;function Zu(n,e){const t=Math.max(0,Math.round(n));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let s=-t;s<=t;s+=1)s===0&&r===0||i.push(`${s}px ${r}px 0 ${e}`);return i.join(", ")}function Mo(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _r(n){return`"${Mo(n)}"`}function Nn(n){return n.clip.textContent||n.clip.name||""}function Ju(){const n=document.createElement("div");n.className="timeline-preview-text-box",n.style.position="absolute",n.style.boxSizing="border-box",n.style.overflow="visible",n.style.pointerEvents="auto",n.style.userSelect="none";const e=document.createElement("div");return e.className="timeline-preview-text-content",e.style.position="relative",e.style.zIndex="0",e.style.display="block",e.style.width="100%",e.style.height="auto",e.style.minHeight="0",e.style.textAlign="center",e.style.whiteSpace="pre-wrap",e.style.overflowWrap="break-word",e.style.overflow="visible",e.style.boxSizing="border-box",n.appendChild(e),{boxElement:n,contentElement:e}}const Ar="Arial, sans-serif";class Qu{constructor(e,t){p(this,"overlayRoot",null);p(this,"entries",new Map);p(this,"fontStyleElement",null);p(this,"fontSignature",null);p(this,"fontLoadState","idle");p(this,"fontLoadToken",0);p(this,"primarySelectedClipId",null);p(this,"textPreviewFont",null);p(this,"compositor");p(this,"callbacks");p(this,"autoRemeasureScheduled",!1);this.compositor=e,this.callbacks=t}mount(e){const t=document.createElement("div");return t.className="timeline-preview-text-layer",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="2000",e.appendChild(t),this.overlayRoot=t,t}destroy(){this.clearEntries(),this.resetFontState(),this.overlayRoot=null}setPrimarySelectedClipId(e){this.primarySelectedClipId=e,this.refreshInteractionState()}setTextPreviewFont(e){this.textPreviewFont=e,this.ensureFontReady()}syncEntries(e,t,i){var a;this.ensureFontReady();const r=e.filter(o=>!o.muted&&o.hasVisual).sort((o,l)=>o.trackOrder-l.trackOrder),s=new Set(r.map(o=>o.clip.id));for(const o of this.entries.keys())s.has(o)||this.removeEntry(o);for(const o of r){const l=this.entries.get(o.clip.id);if(l){l.entry=o;continue}const{boxElement:c,contentElement:h}=Ju(),d=this.createPointerDownHandler(o.clip.id);c.addEventListener("pointerdown",d),(a=this.overlayRoot)==null||a.appendChild(c),this.entries.set(o.clip.id,{entry:o,boxElement:c,contentElement:h,handlePointerDown:d,lastLayout:null})}this.refreshLayout(t,i),this.refreshInteractionState()}refreshLayout(e,t){var a;const i=this.compositor.getFrameSize();if(i.width<=0||i.height<=0)return;const r=this.resolveBaselineScale(),s=(t==null?void 0:t.resolveVisualTransform)??e;for(const o of this.entries.values()){const l=((a=t==null?void 0:t.getStyleOverride)==null?void 0:a.call(t,o.entry))??null,c=Ao({frameSize:i,baselineScale:r,visualTransform:s(o.entry),textStyle:ce(o.entry.clip.textStyle),contentText:Nn(o.entry),styleOverride:l});o.lastLayout=c,this.applyBoxLayout(o,c,l),this.applyContent(o,r,l),o.lastLayout=this.finalizeTextBoxLayout(o,o.lastLayout,r,l),this.usesManualTextLayout(o,l)&&this.emitResolvedLayout(o,l)}this.scheduleAutoRemeasure(t)}getEntry(e){const t=this.entries.get(e);if(t)return{entry:t.entry,element:t.boxElement,layout:t.lastLayout}}getLayout(e){var t;return((t=this.entries.get(e))==null?void 0:t.lastLayout)??null}resolveBaselineScale(){const e=this.compositor.getFrameSize();return e.width<=0||e.height<=0?1:this.compositor.getTextBaselineMetrics(e).scale}reapplyAllContent(){const e=this.resolveBaselineScale();for(const t of this.entries.values())this.applyContent(t,e,null),t.lastLayout&&(t.lastLayout=this.finalizeTextBoxLayout(t,t.lastLayout,e,null))}applyBoxLayout(e,t,i){const r=ce(e.entry.clip.textStyle),s=(i==null?void 0:i.rotation)??r.rotation,{frameRect:a}=t,o=!this.usesManualTextLayout(e,i);e.boxElement.style.left=`${a.centerX}px`,e.boxElement.style.top=`${a.centerY}px`,e.boxElement.style.width=`${a.width}px`,e.boxElement.style.height=o?"auto":`${a.height}px`,e.boxElement.style.transformOrigin="center center",e.boxElement.style.transform=["translate(-50%, -50%)",`rotate(${s}deg)`].join(" ")}applyContent(e,t,i){const r=ce(e.entry.clip.textStyle),s=(i==null?void 0:i.fontSize)??r.fontSize,a=To(s,r.paddingX,r.strokeWidth,t);e.contentElement.textContent=Nn(e.entry),e.contentElement.style.color=r.color,e.contentElement.style.fontFamily=this.getFontFamily(),e.contentElement.style.fontSize=`${a.fontSize}px`,e.contentElement.style.lineHeight=String(Ku),e.contentElement.style.padding=`0 ${a.paddingX}px`,e.contentElement.style.textShadow=Zu(a.strokeWidth,r.strokeColor),e.boxElement.style.zIndex=String(2e3-e.entry.trackOrder)}usesManualTextLayout(e,t){return(t==null?void 0:t.layoutHeight)!==void 0?!0:_o(ce(e.entry.clip.textStyle))}emitResolvedLayout(e,t){var s,a;if(!e.lastLayout)return;const i=this.compositor.getFrameSize();if(i.width<=0||i.height<=0)return;const r=this.compositor.getTextBaselineMetrics(i);(a=(s=this.callbacks).onTextLayoutResolved)==null||a.call(s,e.entry.clip.id,Ro({frameSize:i,composition:{width:r.width,height:r.height},lastLayout:e.lastLayout,layoutMode:this.usesManualTextLayout(e,t)?"manual":"auto"}))}finalizeTextBoxLayout(e,t,i,r){return this.usesManualTextLayout(e,r)?this.applyManualTextBoxLayout(e,t):this.applyAutoTextBoxLayout(e,t,i)}applyManualTextBoxLayout(e,t){return e.boxElement.style.height=`${t.frameRect.height}px`,e.boxElement.style.overflow="hidden",e.contentElement.style.overflow="hidden",t}applyAutoTextBoxLayout(e,t,i){const r=this.compositor.getFrameSize(),s=ce(e.entry.clip.textStyle),a=qe(e.entry.clip.visualTransform);e.boxElement.style.width=`${t.frameRect.width}px`,e.boxElement.style.height="auto",e.boxElement.style.overflow="visible",e.contentElement.style.overflow="visible",e.contentElement.style.textOverflow="clip";const o=Math.max(e.boxElement.offsetHeight,e.contentElement.offsetHeight,e.contentElement.scrollHeight,1),l=Eo({layout:t,frameSize:r,baselineScale:i,visualTransform:a,textStyle:s,measuredHeightPx:o});return e.boxElement.style.left=`${l.frameRect.centerX}px`,e.boxElement.style.top=`${l.frameRect.centerY}px`,l}scheduleAutoRemeasure(e){if(this.autoRemeasureScheduled||!Array.from(this.entries.values()).some(r=>{var a;const s=((a=e==null?void 0:e.getStyleOverride)==null?void 0:a.call(e,r.entry))??null;return!this.usesManualTextLayout(r,s)}))return;this.autoRemeasureScheduled=!0;const i=()=>{var a,o,l;this.autoRemeasureScheduled=!1;const r=this.compositor.getFrameSize();if(r.width<=0||r.height<=0)return;const s=this.resolveBaselineScale();for(const c of this.entries.values()){const h=((a=e==null?void 0:e.getStyleOverride)==null?void 0:a.call(e,c.entry))??null;this.usesManualTextLayout(c,h)||!c.lastLayout||(c.lastLayout=this.applyAutoTextBoxLayout(c,c.lastLayout,s),this.emitResolvedLayout(c,h))}(l=(o=this.callbacks).onAutoLayoutUpdated)==null||l.call(o)};typeof requestAnimationFrame=="function"?requestAnimationFrame(i):i()}getFontFamily(){const e=this.textPreviewFont;return e!=null&&e.fontName&&this.fontLoadState==="loaded"?`${_r(e.fontName)}, ${Ar}`:Ar}ensureFontReady(){var a,o,l;const e=this.textPreviewFont;if(!(e!=null&&e.fontSourceUrl)||!e.fontName)return;const t=`${e.fontName}:${e.fontSourceUrl}`;if(this.fontSignature===t&&this.fontLoadState==="loaded"||this.fontLoadState==="loading"&&this.fontSignature===t)return;this.fontSignature=t,this.fontLoadState="loading";const i=++this.fontLoadToken,r=document.createElement("style");r.textContent=`@font-face { font-family: ${_r(e.fontName)}; src: url("${Mo(e.fontSourceUrl)}"); }`,document.head.appendChild(r),(a=this.fontStyleElement)==null||a.remove(),this.fontStyleElement=r;const s=this.compositor.getRootElement();s&&s.appendChild(r),(l=(o=document.fonts)==null?void 0:o.load)==null||l.call(o,`1em ${_r(e.fontName)}`).then(()=>{i===this.fontLoadToken&&(this.fontLoadState="loaded",this.reapplyAllContent())}).catch(c=>{i===this.fontLoadToken&&(this.fontLoadState="failed",N.warn("PreviewTextLayer","Failed to load text preview font",{error:c}),this.reapplyAllContent())})}resetFontState(){var e;this.fontLoadToken+=1,this.fontLoadState="idle",this.fontSignature=null,(e=this.fontStyleElement)==null||e.remove(),this.fontStyleElement=null}clearEntries(){for(const e of Array.from(this.entries.keys()))this.removeEntry(e)}removeEntry(e){const t=this.entries.get(e);t&&(t.boxElement.removeEventListener("pointerdown",t.handlePointerDown),t.boxElement.remove(),this.entries.delete(e))}createPointerDownHandler(e){return t=>{var r,s,a,o,l,c,h,d,u;const i=t;if((i.button??0)===0){if(this.primarySelectedClipId===e){(r=i.preventDefault)==null||r.call(i),(a=(s=this.callbacks).onSelectedTextPointerDown)==null||a.call(s,e,t);return}(o=i.preventDefault)==null||o.call(i),(l=i.stopPropagation)==null||l.call(i),this.callbacks.lastSyncedPlayState()==="playing"&&((h=(c=this.callbacks).onPauseIfPlaying)==null||h.call(c)),(u=(d=this.callbacks).onPreviewClipSelect)==null||u.call(d,e)}}}refreshInteractionState(){for(const e of this.entries.values()){const t=e.entry.clip.id===this.primarySelectedClipId;e.boxElement.style.cursor=t?"grab":"pointer",e.boxElement.style.border=t?`1px solid ${ze.border}`:"1px solid transparent"}}}const ep=250,tp=100;class ip{constructor(e={},t={}){p(this,"container",null);p(this,"pendingOverlayElement",null);p(this,"pendingOverlayRenderer");p(this,"compositor");p(this,"textLayer");p(this,"sourceService");p(this,"syncCoordinator");p(this,"clockAggregator",new Gu);p(this,"runtimePublisher",new Uu);p(this,"trackSlots",new Map);p(this,"callbacks");p(this,"dependencies");p(this,"audioContext",null);p(this,"masterGainNode",null);p(this,"loadingProbeTimeoutId",null);p(this,"clockProbeTimeoutId",null);p(this,"playbackGroupSuspended",!1);p(this,"primarySelectedClipId",null);p(this,"transientVisualTransform",null);p(this,"transientFontSize",null);p(this,"transientTextLayout",null);p(this,"transientRotation",null);p(this,"pendingState",null);p(this,"activeSyncRequestId");p(this,"isSyncProjecting",!1);p(this,"lastSyncedPlayState","paused");p(this,"aspectRatioProbe",null);p(this,"aspectRatioProbeSrc",null);p(this,"releaseTrackedObjectUrl",(e,t)=>{const i=this.dependencies.resourceCacheManager;!i||!ss(e)||!t||i.releaseObjectUrl(e,t)});this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new _u(()=>{var r,s;(s=(r=this.callbacks).onPendingPreviewRetry)==null||s.call(r)});const i=new Pu({onPreviewTransformChange:(r,s)=>this.handlePreviewTransformChange(r,s),onPreviewTransformCommit:(r,s)=>{var a,o;(o=(a=this.callbacks).onVisualTransformCommit)==null||o.call(a,r,s)},onFontSizeChange:(r,s)=>{s===null?this.transientFontSize=null:this.transientFontSize={clipId:r,fontSize:s},this.refreshVisualLayout()},onFontSizeCommit:(r,s)=>{var a,o;(o=(a=this.callbacks).onTextFontSizeCommit)==null||o.call(a,r,s)},onRotationChange:(r,s)=>{s===null?this.transientRotation=null:this.transientRotation={clipId:r,rotation:s},this.refreshVisualLayout()},onRotationCommit:(r,s)=>{var a,o;(o=(a=this.callbacks).onTextRotationCommit)==null||o.call(a,r,s)},onTextLayoutChange:(r,s)=>{s===null?this.transientTextLayout=null:this.transientTextLayout={clipId:r,...s},this.refreshVisualLayout()},onTextLayoutCommit:(r,s)=>{var a,o;this.transientTextLayout=null,(o=(a=this.callbacks).onTextLayoutCommit)==null||o.call(a,r,s)},onTextTransformInteractionStart:()=>{var r,s;this.lastSyncedPlayState==="playing"&&((s=(r=this.callbacks).onPauseIfPlaying)==null||s.call(r))}});this.compositor=new zu(i),this.textLayer=new Qu(this.compositor,{onPreviewClipSelect:r=>{var s,a;return(a=(s=this.callbacks).onPreviewClipSelect)==null?void 0:a.call(s,r)},onSelectedTextPointerDown:(r,s)=>{this.primarySelectedClipId===r&&this.compositor.transformOverlay.handleTextHostPointerDown(s)},onPauseIfPlaying:()=>{var r,s;return(s=(r=this.callbacks).onPauseIfPlaying)==null?void 0:s.call(r)},onAutoLayoutUpdated:()=>this.refreshTextSelectionOverlay(),onTextLayoutResolved:(r,s)=>{var a,o;return(o=(a=this.callbacks).onTextLayoutResolved)==null?void 0:o.call(a,r,s)},lastSyncedPlayState:()=>this.lastSyncedPlayState}),this.textLayer.setTextPreviewFont(t.textPreviewFont??null),this.sourceService=new qu({previewSourceResolver:t.previewSourceResolver,sourceMediaRegistry:t.sourceMediaRegistry,resourceCacheManager:t.resourceCacheManager,onDiagnostic:(r,s)=>this.emitDiagnostic("info","resource",r,{extra:s})}),this.syncCoordinator=new Wu({sourceService:this.sourceService,getTrackSlots:(r,s)=>this.getTrackSlots(r,s),onAsyncWorkStarted:()=>{this.isSyncProjecting=!0,this.refreshRuntimeState()},onAsyncWorkFinished:()=>{this.isSyncProjecting=!1,this.refreshVisualLayout(),this.refreshRuntimeState()},onStateChange:()=>this.refreshRuntimeState(),releaseObjectUrl:this.releaseTrackedObjectUrl,rememberObjectUrl:(r,s)=>this.rememberSlotObjectUrl(r,s),configureAudio:(r,s)=>this.configureAudioRouting(r,s),syncClockAlignment:(r,s,a)=>{if(s.role!=="current"||!s.entry){r.pendingClockAlignmentMediaTime=null;return}(a||r.pendingClockAlignmentMediaTime!==null)&&(r.pendingClockAlignmentMediaTime=s.entry.mediaTime)},isCurrentTarget:(r,s,a)=>!!r.entry&&r.entry.clip.id===s.clip.id&&(r.boundStableKey===a||nt(r.entry.clip)===a)})}hasPreview(){return!!this.container}attach(e){this.compositor.attach(e,{rootClassName:this.dependencies.rootClassName,frameClassName:this.dependencies.frameClassName,onFrameLayoutChange:()=>this.refreshVisualLayout()}),this.container=e;const t=this.compositor.getRootElement(),i=this.compositor.getFrameElement();if(!t||!i)return;this.textLayer.mount(i);for(const{current:s,preload:a}of this.trackSlots.values())s.mountVideoTo(i),a.mountVideoTo(i),s.mountAudioTo(t),a.mountAudioTo(t);const r=document.createElement("div");t.appendChild(r),this.pendingOverlayElement=r,this.pendingOverlayRenderer.mount(r),this.emitDiagnostic("info","session","preview.attach",{message:"Preview attached"}),this.refreshPendingOverlay(),this.refreshRuntimeState()}detach(){var e,t,i,r;this.emitDiagnostic("info","session","preview.detach",{message:"Preview detached"}),this.clearProbes(),this.textLayer.destroy();for(const{current:s,preload:a}of this.trackSlots.values())s.destroy(this.releaseTrackedObjectUrl),a.destroy(this.releaseTrackedObjectUrl);this.trackSlots.clear(),this.pendingOverlayRenderer.destroy(),this.compositor.detach(),this.container=null,this.pendingOverlayElement=null,this.audioContext&&((r=(t=(e=this.audioContext).close)==null?void 0:(i=t.call(e)).catch)==null||r.call(i,()=>{}),this.audioContext=null,this.masterGainNode=null),this.runtimePublisher.reset(),this.refreshRuntimeState()}sync(e){if(!this.compositor.getFrameElement())return;this.lastSyncedPlayState=e.playState,this.primarySelectedClipId=e.primarySelectedClipId??null,this.textLayer.setPrimarySelectedClipId(this.primarySelectedClipId),this.activeSyncRequestId=e.syncRequestId,this.syncCoordinator.bumpSyncGeneration();const i=e.activeClips.some(l=>l.trackType==="video"&&l.hasVisual);this.clockAggregator.updateAlignmentTarget(i,e.interactionMode,e.currentTime),this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.transientTextLayout&&this.transientTextLayout.clipId!==this.primarySelectedClipId&&(this.transientTextLayout=null),this.maybeResolveAutoAspectRatio(e.autoAspectRatioClip),this.bootstrapLayoutAspectRatioFromClipStyle(e.autoAspectRatioClip),this.textLayer.syncEntries(e.activeClips.filter(l=>l.trackType==="text"),l=>this.getEffectiveVisualTransform(l),this.getTextLayoutOptions());const r=Array.from(this.trackSlots.entries()).map(([l,c],h)=>{var d,u;return{trackId:l,kind:c.current.kind,order:((d=c.current.entry)==null?void 0:d.trackOrder)??((u=c.preload.entry)==null?void 0:u.trackOrder)??1e4+h}}),o=Au(e,r).map(l=>this.applyTrackPlan(l)).filter(l=>l!==void 0);this.refreshVisualLayout(),this.refreshRuntimeState(),o.length!==0&&Promise.all(o).catch(l=>{N.warn("PreviewEngine","preview sync failed",{error:l}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.compositor.applyAspectRatio(e),this.refreshVisualLayout()}getAspectRatio(){return this.compositor.getAspectRatio()}setPendingState(e){this.pendingState=e,this.refreshPendingOverlay()}failSlot(e,t,i){e.fail(i),this.refreshVisualLayout(),this.refreshRuntimeState()}get lastRuntimeState(){return this.runtimePublisher.getLastState()}refreshRuntimeState(){const e=this.collectSlots(),t=o=>Gn(o),i=this.buildTrackedSummary(e),r=this.buildLoadingState(e,t);this.syncPlaybackGroupSuspension(i,r);const s=this.clockAggregator.buildClockState(r,e.filter(o=>o.role==="current"),this.playbackGroupSuspended),a=this.runtimePublisher.publish({activeSyncRequestId:this.activeSyncRequestId,isSyncProjecting:this.isSyncProjecting,slots:e,evaluateTracked:t,isTrackedVideo:o=>Kt(o),clock:s},o=>{var l,c;return(c=(l=this.callbacks).onRuntimeStateChange)==null?void 0:c.call(l,o)},o=>{var l,c;return(c=(l=this.callbacks).onSyncProcessed)==null?void 0:c.call(l,o)});for(const o of e)Kt(o)&&this.compositor.tryResolveAutoAspectRatioFromSlot(o,l=>{var c,h;(h=(c=this.callbacks).onAspectRatioChange)==null||h.call(c,l)});this.syncLoadingProbe(a.loading),this.syncClockProbe(a.clock),this.refreshPendingOverlay()}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);if(Iu(t,e.current.entry)){const i=Eu(t);this.trackSlots.set(e.trackId,i),t=i}return this.syncCoordinator.applyTrackPlan(e)}rememberSlotObjectUrl(e,t){var o;const i=this.dependencies.resourceCacheManager,r=e.objectUrl,s=e.objectUrlHolderId,a=Fu((o=e.entry)==null?void 0:o.clip.id);e.objectUrl=t,e.objectUrlHolderId=a,i&&(r&&r!==t&&s&&i.releaseObjectUrl(r,s),ss(t)&&a&&i.retainObjectUrl(t,a))}getTrackSlots(e,t){const i=this.trackSlots.get(e);if(i&&i.current.kind===t&&i.preload.kind===t)return i;i&&(i.current.destroy(this.releaseTrackedObjectUrl),i.preload.destroy(this.releaseTrackedObjectUrl),this.trackSlots.delete(e));const r={createMediaElement:this.dependencies.createMediaElement,slotClassNamePrefix:this.dependencies.slotClassNamePrefix,onStateChange:()=>this.refreshRuntimeState(),onMediaError:(l,c)=>l.fail(c),onDiagnostic:(l,c,h)=>{var g;const d=l==="media.error"?"error":l==="media.stalled"||l==="media.waiting"?"warn":"debug",u=l.startsWith("source")?"resource":"playback";this.emitDiagnostic(d,u,l,{trackId:c.trackId,clipId:((g=c.entry)==null?void 0:g.clip.id)??null,slotKey:`${c.trackId}:${c.role}`,desiredSourceUrl:c.desiredSource,actualSourceUrl:c.element.getAttribute("src"),extra:{role:c.role,kind:c.kind,...h??{}}})}},s={current:new Hn(e,t,"current",r),preload:new Hn(e,t,"preload",r)},a=this.compositor.getFrameElement(),o=this.compositor.getRootElement();return a&&(s.current.mountVideoTo(a),s.preload.mountVideoTo(a)),o&&(s.current.mountAudioTo(o),s.preload.mountAudioTo(o)),this.trackSlots.set(e,s),s}collectSlots(){const e=[];for(const t of this.trackSlots.values())e.push(t.current,t.preload);return e}buildLoadingState(e,t){let i=0,r=0,s=!1,a=!1,o=!1,l=!1;for(const c of e){if(!Kt(c))continue;i+=1;const h=t(c);h.failed&&(r+=1,s=!0),h.resolving&&(a=!0),h.seeking&&(o=!0),h.mediaUnready&&(l=!0)}return i<=0?{status:"idle",isLoading:!1,reason:null}:s&&r>=i?{status:"failed",isLoading:!1,reason:"failed"}:this.activeSyncRequestId!==void 0&&this.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:a?{status:"loading",isLoading:!0,reason:"resolving-source"}:o?{status:"loading",isLoading:!0,reason:"seeking"}:l?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}buildTrackedSummary(e){let t=0,i=0,r=!1,s=!1,a=!1,o=!1;for(const l of e){if(!Kt(l))continue;t+=1;const c=Gn(l);c.failed&&(i+=1,r=!0),c.resolving&&(s=!0),c.seeking&&(a=!0),c.mediaUnready&&(o=!0)}return{trackedCount:t,failedTrackedCount:i,hasFailed:r,hasResolving:s,hasSeeking:a,hasMediaUnready:o}}syncPlaybackGroupSuspension(e,t){var r;if(((r=this.pendingState)==null?void 0:r.mode)==="seek")return;if(e.trackedCount>1&&(t.status==="loading"||t.status==="failed")){this.playbackGroupSuspended=!0;for(const s of this.collectSlots())s.role!=="current"||!s.isActive||s.requestedPlayState!=="playing"||s.isBuffering||s.isSeeking||s.isResolvingSource||s.phase==="binding"||s.element.paused||qt(s.element);return}if(this.playbackGroupSuspended){this.playbackGroupSuspended=!1;for(const s of this.collectSlots())s.role!=="current"||!s.isActive||s.requestedPlayState!=="playing"||!s.element.paused||rs(s.element)}}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 s=this.getAudioContext();if(!s||e.audioRoutingFailed){e.element.muted=t.muted,e.element.volume=r;return}if(!e.sourceNode||!e.gainNode)try{e.sourceNode=s.createMediaElementSource(e.element),e.gainNode=s.createGain(),e.sourceNode.connect(e.gainNode),e.gainNode.connect(this.getMasterGainNode(s))}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}getAudioContext(){if(this.audioContext)return this.audioContext;const e=this.dependencies.createAudioContext;return this.audioContext=e?e():null,this.audioContext}getMasterGainNode(e){return this.masterGainNode||(this.masterGainNode=e.createGain(),this.masterGainNode.connect(e.destination)),this.masterGainNode}bootstrapLayoutAspectRatioFromClipStyle(e){if(!e||!kt(this.compositor.getAspectRatio().mode))return;const t=nr(e,"sys_width"),i=nr(e,"sys_height");!t||!i||(this.compositor.resolveAutoAspectRatio(t,i),this.refreshVisualLayout())}maybeResolveAutoAspectRatio(e){if(!e)return;const t=nt(e.clip);if(this.aspectRatioProbeSrc===t)return;this.aspectRatioProbeSrc=t;const i=this.getAspectRatioProbe(),r=l=>{i.src=l;try{i.load()}catch{}},s=this.dependencies.previewSourceResolver;if(!s){r(e.clip.src);return}const a=this.dependencies.sourceMediaRegistry,o=a?a.getPreviewSource(t,()=>s(e.clip)):s(e.clip);if(o&&typeof o.then=="function"){o.then(l=>{r((l==null?void 0:l.url)??e.clip.src)});return}r((o==null?void 0:o.url)??e.clip.src)}getAspectRatioProbe(){var t,i;if(this.aspectRatioProbe)return this.aspectRatioProbe;const e=((i=(t=this.dependencies).createAspectRatioProbe)==null?void 0:i.call(t))||document.createElement("video");return hs(e),e.addEventListener("loadedmetadata",()=>{e.videoWidth>0&&e.videoHeight>0&&this.compositor.resolveAutoAspectRatio(e.videoWidth,e.videoHeight,r=>{var s,a;(a=(s=this.callbacks).onAspectRatioChange)==null||a.call(s,r)})}),this.aspectRatioProbe=e,e}getEffectiveVisualTransform(e){var o;const t=((o=this.transientVisualTransform)==null?void 0:o.clipId)===e.clip.id?this.transientVisualTransform.transform:e.clip.type==="text"?qe(e.clip.visualTransform):xe(e.clip.visualTransform);if(e.clip.type!=="text")return t;const i=this.compositor.getFrameSize(),r=this.compositor.getTextBaselineMetrics(i).scale,s=ce(e.clip.textStyle),{layoutHeight:a}=ws({frameSize:i,baselineScale:r,visualTransform:t,textStyle:s,contentText:e.clip.textContent||e.clip.name||"",styleOverride:this.getTextLayoutOverride(e)});return wo(t,s,i,a*r)}getTextLayoutOverride(e){var i,r,s;if(e.clip.type!=="text")return null;const t={};return((i=this.transientFontSize)==null?void 0:i.clipId)===e.clip.id&&(t.fontSize=this.transientFontSize.fontSize),((r=this.transientRotation)==null?void 0:r.clipId)===e.clip.id&&(t.rotation=this.transientRotation.rotation),((s=this.transientTextLayout)==null?void 0:s.clipId)===e.clip.id&&(t.layoutWidth=this.transientTextLayout.layoutWidth,t.layoutHeight=this.transientTextLayout.layoutHeight),Object.keys(t).length>0?t:null}getTextLayoutOptions(){return{getStyleOverride:e=>this.getTextLayoutOverride(e),resolveVisualTransform:e=>qe(e.clip.visualTransform)}}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 e of this.collectSlots())this.compositor.refreshSlotVisual(e);this.textLayer.refreshLayout(e=>qe(e.clip.visualTransform),this.getTextLayoutOptions()),this.refreshTextSelectionOverlay()}refreshTextSelectionOverlay(){this.compositor.transformOverlay.sync(this.compositor.buildSelectedOverlayState(this.primarySelectedClipId,this.collectSlots().filter(e=>e.role==="current"),{getEntry:e=>{const t=this.textLayer.getEntry(e);return t?{entry:t.entry,element:t.element}:void 0},getLayout:e=>this.textLayer.getLayout(e),getTransientFontSize:e=>{var t;return((t=this.transientFontSize)==null?void 0:t.clipId)===e?this.transientFontSize.fontSize:null},getTransientRotation:e=>{var t;return((t=this.transientRotation)==null?void 0:t.clipId)===e?this.transientRotation.rotation:null},getTextLayoutOverride:e=>{const t=this.textLayer.getEntry(e);return t?this.getTextLayoutOverride(t.entry):null}},e=>this.getEffectiveVisualTransform(e)))}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.runtimePublisher.getLastState()})}syncLoadingProbe(e){if(e.status!=="loading"){this.clearLoadingProbe();return}this.loadingProbeTimeoutId||(this.loadingProbeTimeoutId=setTimeout(()=>{this.loadingProbeTimeoutId=null,this.refreshRuntimeState()},ep))}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()},tp))}clearProbes(){this.clearLoadingProbe(),this.clearClockProbe()}clearLoadingProbe(){this.loadingProbeTimeoutId&&(clearTimeout(this.loadingProbeTimeoutId),this.loadingProbeTimeoutId=null)}clearClockProbe(){this.clockProbeTimeoutId&&(clearTimeout(this.clockProbeTimeoutId),this.clockProbeTimeoutId=null)}emitDiagnostic(e,t,i,r={}){var o,l;const s=this.dependencies.diagnostics;if(!s)return;const a=((l=(o=this.dependencies).getDiagnosticsContext)==null?void 0:l.call(o))??{};s.emit({severity:e,category:t,eventName:i,...a,...r})}}class rp extends ip{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 sp(n){return"dom"}const np=36e5,ap=3e5;function ns(n){return n.length===0?0:n.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function zn(n){return ns(n)}function $n(n){return Math.max(n+ap,np)}class Vn{constructor(e={}){p(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(r){N.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function op(n){return[...n].sort((e,t)=>e.order-t.order)}function lp(n){return[...n].sort((e,t)=>e.startTime-t.startTime)}function Ir(n,e,t){const i=n.type==="video"||n.type==="text",r=n.type!=="text";return{trackId:n.id,trackType:n.type,trackOrder:n.order,clip:e,mediaTime:t,muted:(n.isMuted??!1)||(e.isMuted??!1),kind:n.type,hasVisual:i,hasAudio:r}}class cp{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t,i={}){const r=op(e),s=[],a=[];let o=null;for(const l of r){const c=lp(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);s.push(Ir(l,h,u))}const d=c.find(u=>u.startTime>t);if(d&&a.push(Ir(l,d,d.startTimeAtSource)),!o&&l.type==="video"){const u=c[0];u&&(o=Ir(l,u,u.startTimeAtSource))}}return{activeClips:s,nextClips:a,firstVideoClip:o}}}class hp{constructor(e){p(this,"options");p(this,"_previewSession");p(this,"_previewMountContainer",null);p(this,"_resolvedPreviewBackend","dom");p(this,"_runtimePreviewBackendOverride",null);p(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const dp=1e3;class up{constructor(e){p(this,"callbacks");p(this,"failedOverlayDelayMs");p(this,"_previewLoadingState",{status:"idle",isLoading:!1,reason:null});p(this,"_pendingPreviewState",null);p(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.failedOverlayDelayMs=e.failedOverlayDelayMs??dp}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)),Un(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};Un(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 Un(n,e){return n.status===e.status&&n.isLoading===e.isLoading&&n.reason===e.reason}const pp=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],gp={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 fp(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function mp(n){const e=n.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 yp(n,e,t){const i=e.split("+").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return null;let r=null,s=!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":s=!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=mp(c);if(!h||r)return null;r=h}}return r?{action:n,code:r,altKey:s,ctrlKey:a,metaKey:o,shiftKey:l}:null}function Sp(n){if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:!!n.closest('[contenteditable=""], [contenteditable="true"], input, textarea, select')}function Cp(n,e){return n.code===e.code&&n.altKey===e.altKey&&n.ctrlKey===e.ctrlKey&&n.metaKey===e.metaKey&&n.shiftKey===e.shiftKey}function vp(n,e){return n===!1||(n==null?void 0:n.enabled)===!1?[]:pp.flatMap(t=>{var s;const i=(s=n==null?void 0:n.bindings)==null?void 0:s[t];return(i===void 0?gp[t]:Array.isArray(i)?i:[i]).map(a=>yp(t,a,e)).filter(a=>a!==null)})}class Tp{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??fp();e.root,this.callbacks=e.callbacks,this.bindings=vp(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(Sp(e.target))return;const t=this.bindings.find(i=>Cp(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 Lo(n){var t;const e=n.getPrimarySelectedClip()||((t=n.findFallbackSelectedClip)==null?void 0:t.call(n))||null;return{clip:e,hasSelectedClip:!!e}}function bp(n){const e=Lo(n),t=n.getSelectedClipIds(),i=n.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:n.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function kp(n){var i;const e=n.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===n.lastSelectedClipId?n.lastSelectedClipId:(n.emitSelectedClipChange(e),t)}class wp{constructor(e){p(this,"cleanupEmptyTracks",!1);p(this,"durationDirty",!1);p(this,"canPlayDirty",!1);p(this,"selectionDirty",!1);p(this,"trackLayoutDirty",!1);p(this,"trackInfoDirty",!1);p(this,"stageDirty",!1);p(this,"previewDirty",!1);p(this,"committed",!1);p(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,s=i?this.resolveTrackId(i):null;if(!r||!s)return!1;const a=this.options.moveClipToTrack?this.options.moveClipToTrack(r,s,t):this.options.trackCollection.moveClipToTrack(r,s,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 xp(n,e){var t,i,r,s;return((i=(t=n.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((s=(r=n.getLastTrack())==null?void 0:r.getId)==null?void 0:s.call(r))||e}function Pp(n){if(n.placement.status==="use_existing_track")return n.trackCollection.addClipToTrack(n.placement.trackId,n.clip);const e=n.createTrack(n.placement.trackType,n.placement.suggestedTrackName,n.placement.insertionPlacement),t=xp(n.trackCollection,e);return t?n.trackCollection.addClipToTrack(t,n.clip):!1}function Wn(n,e,t){return e.trackId?n.removeClipFromTrack(e.trackId,t):!1}function _p(n){return n.trackCollection.moveClipToTrack(n.command.clip,n.command.sourceTrackId,n.command.targetTrackId)}function Bi(n){var e,t,i,r,s;(e=n.checkTrackDurationChange)==null||e.call(n),(t=n.updateCanPlayState)==null||t.call(n),(i=n.updateTrackInfoPanel)==null||i.call(n),(r=n.handleClipChange)==null||r.call(n),(s=n.cleanupEmptyTracks)==null||s.call(n)}class Do{constructor(){p(this,"panel",null);p(this,"config",null);p(this,"currentSelectionState",this.buildSelectionState(null,[]));p(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new mo({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=>Me(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:s,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&&s==="audio"?r.filter(l=>Me(l)):[o]:Object.prototype.hasOwnProperty.call(t,"textStyle")?s==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"visualTransform")?s==="video"||s==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"volume")?s==="video"||s==="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(){p(this,"panel",null)}init(e){var i,r,s,a;const t=((i=e.theme)==null?void 0:i.background)||ke.background;this.panel=new fo({container:e.container,theme:{background:t,border:((r=e.theme)==null?void 0:r.border)||ke.border,text:((s=e.theme)==null?void 0:s.clipName)||ke.text,buttonBackground:((a=e.theme)==null?void 0:a.clipBackground)||ke.buttonBackground,buttonHover:ke.buttonHover,buttonDanger:ke.buttonDanger},width:Ci,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}}const Ip=1.35,Yn="Arial, sans-serif";function Ep(n,e){const t=Math.max(0,Math.round(n));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let s=-t;s<=t;s+=1)s===0&&r===0||i.push(`${s}px ${r}px 0 ${e}`);return i.join(", ")}function Rp(n){return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Mp(n){return n!=null&&n.fontName?`${Rp(n.fontName)}, ${Yn}`:Yn}function Lp(n,e,t,i){if(typeof document>"u")return 0;const r=ce(n.textStyle),s=To(r.fontSize,r.paddingX,r.strokeWidth,e),a=document.createElement("div");a.style.position="absolute",a.style.visibility="hidden",a.style.pointerEvents="none",a.style.boxSizing="border-box",a.style.overflow="visible",a.style.width=`${t}px`,a.style.height="auto";const o=document.createElement("div");o.style.display="block",o.style.width="100%",o.style.height="auto",o.style.textAlign="center",o.style.whiteSpace="pre-wrap",o.style.overflowWrap="break-word",o.style.overflow="visible",o.style.boxSizing="border-box",o.style.color=r.color,o.style.fontFamily=Mp(i),o.style.fontSize=`${s.fontSize}px`,o.style.lineHeight=String(Ip),o.style.padding=`0 ${s.paddingX}px`,o.style.textShadow=Ep(s.strokeWidth,r.strokeColor),o.textContent=n.textContent||n.name||"",a.appendChild(o),document.body.appendChild(a);const l=Math.max(a.offsetHeight,o.offsetHeight,o.scrollHeight,1);return a.remove(),Math.ceil(l/e)}function Xn(n,e,t,i,r){const s={width:e.width,height:e.height},a=ce(n.textStyle),o=qe(n.visualTransform),l=r===void 0?i:Eo({layout:i,frameSize:s,baselineScale:1,visualTransform:o,textStyle:a,measuredHeightPx:r});return Ro({frameSize:s,composition:e,lastLayout:l,layoutMode:t})}function Dp(n,e,t){if(e.width<=0||e.height<=0)return null;const i={width:e.width,height:e.height},r=bu(n.textStyle),s=Io({clip:n},i,1);if(r==="manual")return Xn(n,e,r,s);const a=Lp(n,1,s.frameRect.width,t)||s.layoutHeight;return Xn(n,e,r,s,a)}class jn{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,Bp=10*1024*1024*1024,Fp=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:Bp,ttlMs:Fp,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:Hp},Gp="timeline-preview-resource-cache",Np=1,Se="metadata";function zp(){return new Promise((n,e)=>{const t=indexedDB.open(Gp,Np);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=()=>n(t.result)})}function Er(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onerror=()=>t(n.error),n.onabort=()=>t(n.error)})}class $p{constructor(){p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=zp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async get(e){const t=await this.getDb();return new Promise((i,r)=>{const s=t.transaction(Se,"readonly").objectStore(Se).get(e);s.onerror=()=>r(s.error),s.onsuccess=()=>i(s.result??null)})}async put(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).put(e),await Er(i)}async delete(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).delete(e),await Er(i)}async clear(){const t=(await this.getDb()).transaction(Se,"readwrite");t.objectStore(Se).clear(),await Er(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 Vp="timeline-preview-resource-cache",Up="timeline-preview-resource-cache-blobs",Wp=1,Ee="blobs";function Yp(){return new Promise((n,e)=>{const t=indexedDB.open(Up,Wp);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result)})}function Rr(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onerror=()=>t(n.error),n.onabort=()=>t(n.error)})}class Xp{constructor(){p(this,"kind","indexeddb");p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=Yp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async read(e){const t=await this.getDb();return new Promise((i,r)=>{const s=t.transaction(Ee,"readonly").objectStore(Ee).get(e);s.onerror=()=>r(s.error),s.onsuccess=()=>i(s.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Ee,"readwrite");r.objectStore(Ee).put(t,e),await Rr(r)}async delete(e){const i=(await this.getDb()).transaction(Ee,"readwrite");i.objectStore(Ee).delete(e),await Rr(i)}async clear(){const t=(await this.getDb()).transaction(Ee,"readwrite");t.objectStore(Ee).clear(),await Rr(t)}}class jp{constructor(){p(this,"kind","opfs");p(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(Vp,{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 s=await(await(await this.getDirectory()).getFileHandle(e,{create:!0})).createWritable();try{await s.write(t),await s.close()}catch(a){try{typeof s.abort=="function"&&await s.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 qp(n){var e;if(n.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new jp;if(await t.ensureReady())return t}return new Xp}function Kp(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function qn(n){return n.split(";",1)[0].trim().toLowerCase()}async function Zp(n){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(n));return Kp(new Uint8Array(t))}function Mr(n){return n?[...n]:[...li.allowedMimeTypes]}function Jp(n){return n?n===!0?{...li,enabled:!0,allowedMimeTypes:Mr(void 0)}:{...li,...n,enabled:n.enabled??!0,allowedMimeTypes:Mr(n.allowedMimeTypes)}:{...li,allowedMimeTypes:Mr(void 0)}}function Qp(n){try{const e=new URL(n);return e.hash="",e.toString()}catch{return n.trim()}}async function eg(n){var t;const e=((t=n.sourceKey)==null?void 0:t.trim())||Qp(n.url);return Zp(e)}function Kn(n,e=li.allowedMimeTypes){if(!n.url)return!0;let t;try{t=new URL(n.url)}catch{return!0}if(t.protocol!=="http:"&&t.protocol!=="https:"||n.kind==="hls-fmp4"||/\.m3u8(?:$|\?|#)/i.test(t.pathname))return!0;if(!n.mimeType)return!1;const i=qn(n.mimeType);return!e.some(r=>qn(r)===i)}function tg(n){return n&&n.split(";",1)[0].trim().toLowerCase()||null}function Zn(n){if(!n)return null;const e=Number(n);return Number.isSafeInteger(e)&&e>=0?e:null}function ig(n){if(!n)return null;const e=n.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 Jn(n,e,t){return{url:e,ok:n.ok,status:n.status,mimeType:tg(n.headers.get("content-type")),sizeBytes:t,etag:n.headers.get("etag"),lastModified:n.headers.get("last-modified"),acceptRanges:n.headers.get("accept-ranges")}}class rg{async probe(e){var r;try{const s=await fetch(e,{method:"HEAD"}),a=Zn(s.headers.get("content-length"));if(s.ok&&a!==null)return Jn(s,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=ig(t.headers.get("content-range"))??Zn(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return Jn(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 sg={createObjectURL(n){return URL.createObjectURL(n)},revokeObjectURL(n){URL.revokeObjectURL(n)}};function mt(n,e){return{url:n.url,cacheStatus:e,sourceUrl:n.url}}function ng(n,e){return n.etag||e.etag?n.etag===e.etag&&n.sizeBytes===e.contentLength:n.sizeBytes===e.contentLength&&n.lastModified===e.lastModified}class ag{constructor(e={}){p(this,"options");p(this,"metadataStore");p(this,"storagePromise");p(this,"http");p(this,"objectUrl");p(this,"now");p(this,"cacheKeyBuilder");p(this,"onEvent");p(this,"objectUrls",new Set);p(this,"objectUrlByCacheKey",new Map);p(this,"cacheKeyByObjectUrl",new Map);p(this,"objectUrlHolders",new Map);p(this,"inflightDownloads",new Map);this.options=Jp(e.options),this.metadataStore=e.metadataStore??new $p,this.storagePromise=e.storage?Promise.resolve(e.storage):qp({preferStorage:this.options.preferStorage}),this.http=e.http??new rg,this.objectUrl=e.objectUrl??sg,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??eg,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Kn(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),mt(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(t,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}),mt(e,"miss");const s=await this.probeCacheable(e);if(s.cacheStatus!=="miss")return s.result;const{blob:a,metadata:o}=await this.getOrCreateDownload(t,e,s.probe,i);return this.emitEvent("resource-cache.miss",{sourceUrl:e.url,sizeBytes:o.sizeBytes}),this.blobResult(t,e.url,a,o,"miss")}catch{return this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),mt(e,"fallback")}}retainObjectUrl(e,t){if(!t||!this.objectUrls.has(e))return;let i=this.objectUrlHolders.get(e);i||(i=new Set,this.objectUrlHolders.set(e,i)),i.add(t)}releaseObjectUrl(e,t){if(!e||!t||!this.objectUrls.has(e))return;const i=this.objectUrlHolders.get(e);!(i!=null&&i.delete(t))||i.size>0||(this.objectUrlHolders.delete(e),this.revokeTrackedObjectUrl(e))}revokeObjectUrl(e){this.forceRevokeObjectUrl(e)}forceRevokeObjectUrl(e){!e||!this.objectUrls.has(e)||(this.objectUrlHolders.delete(e),this.revokeTrackedObjectUrl(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.forceRevokeObjectUrl(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,s){const a=await this.probeCacheable(e);if(a.cacheStatus!=="miss")return a.result;if(ng(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(t,e.url,r,h,"stale-revalidated")}this.emitEvent("resource-cache.revalidate.stale",{sourceUrl:e.url}),await this.deleteEntry(t,s);const{blob:o,metadata:l}=await this.getOrCreateDownload(t,e,a.probe,s);return this.blobResult(t,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:mt(e,"fallback")}):Kn({...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:mt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:mt(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 s=this.inflightDownloads.get(e);if(s)return s;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 s=await this.http.download(t.url),a=s.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,s);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:s,metadata:l}}catch(s){throw this.emitEvent("resource-cache.download.failed",{sourceUrl:t.url,error:s instanceof Error?s.message:String(s)}),s}}async evictForWrite(e,t,i){const r=(await this.metadataStore.list()).filter(a=>a.cacheKey!==e);let s=r.reduce((a,o)=>a+o.sizeBytes,0);for(const a of r.sort((o,l)=>o.lastAccessedAt-l.lastAccessedAt)){if(s+t<=this.options.maxTotalBytes)return;await this.deleteEntry(a.cacheKey,i),s-=a.sizeBytes}}async deleteEntry(e,t){const i=this.objectUrlByCacheKey.get(e);i&&(this.objectUrlByCacheKey.delete(e),this.forceRevokeObjectUrl(i)),await Promise.all([t.delete(e),this.metadataStore.delete(e)]),this.emitEvent("resource-cache.cleanup.deleted",{cacheKey:e})}registerObjectUrl(e,t){this.objectUrls.add(t),this.objectUrlByCacheKey.set(e,t),this.cacheKeyByObjectUrl.set(t,e)}revokeTrackedObjectUrl(e){if(!this.objectUrls.delete(e))return;const t=this.cacheKeyByObjectUrl.get(e);t&&(this.objectUrlByCacheKey.delete(t),this.cacheKeyByObjectUrl.delete(e)),this.objectUrl.revokeObjectURL(e)}blobResult(e,t,i,r,s){const a=this.objectUrlByCacheKey.get(e);if(a&&this.objectUrls.has(a))return this.toResolvedBlob(a,t,r,s);const o=this.objectUrl.createObjectURL(i);return this.registerObjectUrl(e,o),this.toResolvedBlob(o,t,r,s)}toResolvedBlob(e,t,i,r){return{url:e,cacheStatus:r,sourceUrl:t,sizeBytes:i.sizeBytes,objectUrl:e}}emitEvent(e,t){var i;(i=this.onEvent)==null||i.call(this,e,t)}}function og(n){return!!n&&typeof n.then=="function"}class Lr{constructor(){p(this,"durationCache",new Map);p(this,"thumbnailCache",new Map);p(this,"previewSourceCache",new Map)}static buildSourceKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src||""}static buildThumbnailKey(e){return[this.buildSourceKey(e),e.type,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}getDuration(e,t,i={}){const r=this.durationCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(typeof(r==null?void 0:r.value)=="number")return Promise.resolve(r.value)}const s=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:s}),s}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 s=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:s}),s}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 s=t();if(!og(s))return this.previewSourceCache.set(e,{value:s,promise:null,resolved:!0}),s;const a=s.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 Qn{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 lg{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),s=this.findById(i);return!(r!=null&&r.removeClip)||!(s!=null&&s.addClip)?!1:(r.removeClip(e.id),s.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 cg(n){return n==="text"?"文本":n==="video"?"视频":"音频"}function Fi(n){return n==="text"?0:n==="video"?1:2}class Oo{constructor(e=[]){p(this,"tracks",[]);p(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,r,s,a){this.trackCounter++;const o=t||`${cg(e)}轨道 ${this.trackCounter}`,l=s??(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),N.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?(N.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(N.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),N.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,N.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(N.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),N.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(N.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"),s=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((s==="before_track"||s==="after_track")&&i){const a=this.tracks.findIndex(o=>o.id===i);if(a!==-1){this.tracks.splice(a+(s==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(s==="top_of_type_region"){const a=this.tracks.findIndex(l=>l.type===e.type);if(a!==-1){this.tracks.splice(a,0,e),this.recalculateOrder();return}const o=this.tracks.findIndex(l=>Fi(l.type)>Fi(e.type));if(o!==-1){this.tracks.splice(o,0,e),this.recalculateOrder();return}}if(s==="bottom_of_type_region"){const a=this.tracks.reduce((l,c,h)=>c.type===e.type?h:l,-1);if(a!==-1){this.tracks.splice(a+1,0,e),this.recalculateOrder();return}const o=this.tracks.reduce((l,c,h)=>Fi(c.type)<=Fi(e.type)?h:l,-1);if(o!==-1){this.tracks.splice(o+1,0,e),this.recalculateOrder();return}}s==="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,N.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(N.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,N.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}class hg{constructor(e){p(this,"currentTime");p(this,"playState");p(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class Bo{constructor(){p(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class dg{constructor(e){p(this,"zoom");p(this,"duration");p(this,"scrollLeft");p(this,"scrollTop");p(this,"viewportWidth");p(this,"viewportHeight");p(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class ea{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new Bo,this.playbackStore=new hg({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new dg({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 ug{constructor(e,t,i,r,s){p(this,"stage");p(this,"layer");p(this,"onTimeChange");p(this,"onScrollChange");p(this,"config");p(this,"theme");p(this,"scrollLeft",0);p(this,"timeScaleHeight",40);p(this,"isDragging",!1);p(this,"dragStartX",0);p(this,"isPointerInsideTimeline",!1);p(this,"lastPointerXInTimeline",null);p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=r,this.onScrollChange=s,this.config={duration:i.duration||Zt,zoom:i.zoom||Re.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Xi(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,s=this.stage.width(),a=r<=s?Math.max(0,t-(s-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),s=U.pixelsToTime(i,this.config.zoom),a=U.msToSeconds(r),o=U.msToSeconds(s),{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 j=class j{constructor(e,t,i,r,s,a,o){p(this,"container");p(this,"visualElement");p(this,"lineHitAreaElement");p(this,"theme");p(this,"onTimeChange");p(this,"onHorizontalAutoScroll");p(this,"currentTime");p(this,"zoom");p(this,"scrollLeft",0);p(this,"height");p(this,"isDragging",!1);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"lastPointerClientX",null);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});p(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});p(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const r=this.scrollLeft,s=this.onHorizontalAutoScroll(this.scrollLeft+i),a=typeof s=="number"?s: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=s,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(j.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${j.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=`${j.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(j.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=j.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const s=(i-e)/i;return-Math.max(1,Math.round(s*r))}if(e>t-i){const s=(e-(t-i))/i;return Math.max(1,Math.round(s*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(j.HANDLE_HEIGHT+j.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 ${j.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=xs.grip,i=Math.max(j.HANDLE_HEIGHT,e-j.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(j.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",xs.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(j.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(j.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(j.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(j.VISUAL_WIDTH-j.LINE_WIDTH)/2}`),t.setAttribute("y",`${j.HANDLE_LINE_START}`),t.setAttribute("width",`${j.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-j.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e){const t=document.createElementNS(j.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-end-cap"),t.setAttribute("x","3"),t.setAttribute("y",`${e}`),t.setAttribute("width",`${j.END_CAP_WIDTH}`),t.setAttribute("height",`${j.END_CAP_HEIGHT}`),t.setAttribute("rx","1.5"),t.setAttribute("fill","#ffffff"),t}};p(j,"SVG_NS","http://www.w3.org/2000/svg"),p(j,"VISUAL_WIDTH",14),p(j,"HANDLE_HEIGHT",16),p(j,"HANDLE_LINE_START",13),p(j,"LINE_WIDTH",1),p(j,"LINE_HIT_WIDTH",12),p(j,"END_CAP_WIDTH",8),p(j,"END_CAP_HEIGHT",1),p(j,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(j,"AUTO_SCROLL_MAX_SPEED",18);let as=j;class ta{constructor(e){p(this,"container");p(this,"orientation");p(this,"theme");p(this,"onScrollChange");p(this,"leadingInset");p(this,"trailingInset");p(this,"stage");p(this,"layer");p(this,"hitAreaRect");p(this,"thumbRect");p(this,"viewportSize",0);p(this,"contentSize",0);p(this,"scrollOffset",0);p(this,"isDragging",!1);p(this,"dragStartClient",0);p(this,"dragStartOffset",0);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleStageMouseDown",e=>{var r;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((r=e.target)==null?void 0:r.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});p(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});p(this,"handleStageMouseEnter",()=>{this.updateCursor()});p(this,"handleStageMouseMove",()=>{this.updateCursor()});p(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new 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,Et.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||Et.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Et.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(),s=this.getThumbSize(r),a=Math.max(1,r-s),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(),s=this.getThumbSize(r),a=Math.max(1,r-s),o=Math.max(0,Math.min(r,i-this.leadingInset)),l=Math.max(0,Math.min(a,o-s/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||Et.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Et.border);const r=this.getAvailableTrackSize();if(r<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const s=this.getThumbSize(r),a=this.leadingInset+this.getThumbPosition(r,s);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(a),this.thumbRect.y(0),this.thumbRect.width(s),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(a),this.thumbRect.width(e),this.thumbRect.height(s)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const r=Math.max(1,e-t);return this.scrollOffset/i*r}}const pg=48;function gg(n,e,t){return U.timeToPixels(n,e)-t+pe}function fg(n,e,t){const i=Math.max(0,t-e);return Math.max(0,Math.min(i,n))}function mg(n){const{time:e,zoom:t,scrollLeft:i,viewportWidth:r,contentWidth:s,margin:a=pg}=n;if(r<=0||Math.max(0,s-r)<=0)return null;const l=gg(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=fg(d,r,s);return Math.abs(u-i)<=.5?null:u}class ia{constructor(){p(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 yg="@linker-design-plus/timeline-track",Sg="2.2.2",zt={name:yg,version:Sg},Cg=1,vg=2,Tg=250,bg=750,kg=1500;function ra(n){return n==null?n:JSON.parse(JSON.stringify(n))}function wg(n,e){return n.length!==e.length?!1:n.every((t,i)=>t===e[i])}function xg(n){return n==="text"?"文本":n==="video"?"视频":"音频"}class Pg{constructor(e={}){p(this,"timeline",null);p(this,"tracks",[]);p(this,"trackManager");p(this,"trackInfoPanelController");p(this,"playhead",null);p(this,"history");p(this,"config");p(this,"eventDispatcher");p(this,"animationFrameId",null);p(this,"lastUpdateTime",0);p(this,"isInitialized",!1);p(this,"stage",null);p(this,"headerStage",null);p(this,"headerLayer",null);p(this,"backgroundLayer",null);p(this,"trackLayer",null);p(this,"dragOverlayLayer",null);p(this,"snapGuideLayer",null);p(this,"selectionBoxLayer",null);p(this,"selectionBoxRect",null);p(this,"isBoxSelecting",!1);p(this,"boxSelectStartX",0);p(this,"boxSelectStartY",0);p(this,"resizeObserver",null);p(this,"rootContainer",null);p(this,"layout",null);p(this,"bodyBackgroundRect",null);p(this,"snapGuideLine",null);p(this,"trackInsertionPreviewLine",null);p(this,"trackInsertionPreviewY",null);p(this,"snapGuideTime",null);p(this,"horizontalScrollbar",null);p(this,"verticalScrollbar",null);p(this,"isExecutingHistoryAction",!1);p(this,"lastTrackDuration",0);p(this,"lastReportedTrackDuration",0);p(this,"thumbnailProvider",null);p(this,"thumbnailProviderVersion",0);p(this,"clipThumbnailLoadStates",new Map);p(this,"sourceMediaRegistry",new Lr);p(this,"canPlay",!1);p(this,"sourceLoadingCount",0);p(this,"timelineStore");p(this,"timelineCommands");p(this,"timelineHistoryRecorder");p(this,"timelinePresentationAdapter");p(this,"timelineTrackBridge");p(this,"timelinePlaybackResolver");p(this,"previewRuntimeController");p(this,"previewStateController");p(this,"previewPlaybackSuspendedByBuffering",!1);p(this,"previewPlaybackAutoResume",!1);p(this,"lastSelectedClipId",null);p(this,"previewAspectRatio",{...Le});p(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});p(this,"stageMouseDownListener",null);p(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});p(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});p(this,"keyboardShortcutsController",null);p(this,"clipClipboard",null);p(this,"mountManager",new ia);p(this,"pendingDraftData",null);p(this,"selectionStore",new Bo);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);p(this,"splitOperationDepth",0);p(this,"diagnostics");p(this,"previewRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});p(this,"failedPreviewClipIds");p(this,"previewActiveClipIds",[]);p(this,"previewClockSeekAlignmentTargetTime",null);p(this,"previewClockSeekAlignmentDeadlineMs",0);p(this,"playbackAttemptId",this.createPlaybackAttemptId("initial"));p(this,"lastPreviewSyncedPlayState",null);p(this,"lastPreviewSyncSignature",null);p(this,"lastSteadyPlaybackPreviewSyncAt",0);p(this,"previewSyncInteractionMode",null);p(this,"resourceCacheManager");p(this,"voiceLinkedTextRegenerationTimer",null);p(this,"pendingVoiceLinkedTextRegeneration",null);p(this,"historyRecordingSuppressionDepth",0);p(this,"activeStructureSession",null);p(this,"structureSessionDepth",0);p(this,"preserveEmptyTracksDepth",0);p(this,"playbackViewportFollowSuspended",!1);p(this,"isProgrammaticScrollChange",!1);this.config={duration:e.duration||Zt,zoom:e.zoom||Re.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:Xi(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 ag({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:zt.name,packageVersion:zt.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 Vn({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 ts(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new En(this.history),this.trackManager=new Oo,this.timelineStore=new ea({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new An(this.timelineStore),this.timelinePresentationAdapter=new jn,this.timelineTrackBridge=new Qn({onClipUpdate:(t,i,r)=>this.handleClipUpdate(t,i,r),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.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,s;if(!this.timelineStore){const a=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,c=((r=this.config)==null?void 0:r.zoom)||Re.MEDIUM,h=((s=this.config)==null?void 0:s.duration)||Zt;this.timelineStore=new ea({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new An(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new lg(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new jn),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Qn({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.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 cp),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 up({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 hp({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new rp({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||sp(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=Ue(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)},onTextLayoutCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextLayout(t,i)},onTextLayoutResolved:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextResolvedLayout(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 Vn({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 ts(()=>{},()=>{})),this.timelineHistoryRecorder=new En(this.history)),this.timelineHistoryRecorder}withStructureSession(e){const t=this.activeStructureSession;if(t)return e(t);const i=new wp({trackCollection:this.getTrackCollection(),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),setPrimaryTrackMagnetEnabled:this.setPrimaryTrackMagnetEnabledFromHistory.bind(this),loadClipThumbnails:this.loadClipThumbnails.bind(this),addClipToTrack:(s,a)=>this.getTrackCollection().addClipToTrack(s,a),removeClip:s=>{const a=this.getTrackCollection();if(typeof a.removeClip=="function"){a.removeClip(s);return}this.tracks.forEach(o=>{var l;return(l=o.removeClip)==null?void 0:l.call(o,s)})},removeClipFromTrack:(s,a)=>this.getTrackCollection().removeClipFromTrack(s,a),updateClip:(s,a)=>{const o=this.getTrackCollection();if(typeof o.updateClip=="function"){o.updateClip(s,a);return}this.tracks.forEach(l=>{var c;return(c=l.updateClip)==null?void 0:c.call(l,s,a)})},moveClipToTrack:(s,a,o)=>{const l=this.getTrackCollection();if(typeof l.moveClipToTrack=="function")return l.moveClipToTrack(s,a,o);const c=l.findById(a),h=l.findById(o);return!(c!=null&&c.removeClip)||!(h!=null&&h.addClip)?!1:(c.removeClip(s.id),h.addClip(s),!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 s=e(i);return s instanceof Promise?s.finally(r):(r(),s)}catch(s){throw r(),s}}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 s=this.isExecutingHistoryAction??!1;this.isExecutingHistoryAction=!0;try{const a=r();return a instanceof Promise?a.then(o=>(this.isExecutingHistoryAction=s,o),o=>{throw this.isExecutingHistoryAction=s,o}):(this.isExecutingHistoryAction=s,a)}catch(a){throw this.isExecutingHistoryAction=s,a}}shouldSkipHistoryRecording(){return this.isExecutingHistoryAction||this.historyRecordingSuppressionDepth>0}withHistoryTransaction(e,t){return this.withHistoryBoundary("transaction",e,t)}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:Zt,zoom:Re.MEDIUM,currentTime:0,playState:"paused",theme:Xi(),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(),s=this.getHorizontalContentWidth(),a=mg({time:e,zoom:i,scrollLeft:r,viewportWidth:t,contentWidth:s});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,s,a;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(r=this.verticalScrollbar)==null||r.resize(),(s=this.horizontalScrollbar)==null||s.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 s=St(r);return s<=0||t!==s?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,s=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>=s||(r=c,s=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=s=>[s.trackId,s.clip.id,s.trackType,s.trackOrder,s.clip.startTime,s.clip.endTime,s.clip.startTimeAtSource,s.muted?1:0,s.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<Tg}syncPreviewSession(e){var d,u,g,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 s=this.getAutoAspectRatioClip(),a=Ue(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:s,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=(g=this.previewSession).setPendingState)==null||f.call(g,this.buildPreviewPendingState()),this.previewSession.sync({...r,autoAspectRatioClip:s,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)<=bg?(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(s=>s.clip.id);if(!wg(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,s,a,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;if(!this.hasActiveTimelineVideoClip(e)){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();return}(t!=="scrub"||((s=this.pendingPreviewState)==null?void 0:s.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(Ue(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,r,s,a,o,l,c;if(this.isInitialized){N.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=Nd(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Ci,scrollbarSize:Jr}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(r=(i=this.layout.bodyCanvasHost).addEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(a=(s=this.rootContainer)==null?void 0:s.addEventListener)==null||a.call(s,"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 ug(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new as(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 ta({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:pe,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new ta({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=>{N.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,s,a){var u,g,f,m;if(!this.trackLayer)return N.error("TimelineManager","Track layer not initialized"),"";const o=this.trackManager.createTrack(e,t,i,r,s,a),l=o.id,c=_e(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()),(g=d.setDragOverlayLayer)==null||g.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,s,a,o,l;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return N.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return N.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((a=(s=t.getTrackGroup)==null?void 0:s.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,s;if(!((r=this.trackManager)!=null&&r.renameTrack))return!1;const i=this.trackManager.renameTrack(e,t);return i&&(this.getActiveStructureSession()?(s=this.getActiveStructureSession())==null||s.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}getTracks(){return this.getResolvedTracksSnapshot()}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){var r,s;if(!((r=this.trackManager)!=null&&r.muteTrack))return!1;const i=this.trackManager.muteTrack(e,t);return i&&(this.getActiveStructureSession()?(s=this.getActiveStructureSession())==null||s.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return Nt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return Pn(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=Ud(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const r of e){const s=this.getTrackCollection().findById(r.trackId);s&&((t=s.setTrackY)==null||t.call(s,r.y),(i=s.setTrackHeight)==null||i.call(s,r.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}removeEmptyTracksFromStructure(){var i,r,s;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),(s=(r=a.getTrackGroup)==null?void 0:r.call(a))==null||s.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 s,a,o,l;const i=(s=t.getId)==null?void 0:s.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,s;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&&((s=this.snapGuideLayer)==null||s.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(s=>{var a;return(a=s.clearClipDropPreview)==null?void 0:a.call(s)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const r=this.trackManager.getTracks(),s=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=Nt(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+_e(c.type)}}if(t==="top_of_type_region"&&a)return Nt(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Nt(r,o.id,this.getTrackContentTopOffset())+_e(o.type);if(!s)return e!=="audio"?this.getTrackContentTopOffset():Pn(r,this.getTrackContentTopOffset());const l=Nt(r,s.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+_e(s.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),r=Math.max(i,t),s=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(s),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",s=>{this.handleBodyBackgroundClick(s.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||ee.snapGuideLineColor}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=de.createLine([0,0,0,this.calculateTotalHeight()],this.getSnapGuideAccentColor(),e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var r,s;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&&((s=this.snapGuideLayer)==null||s.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const s=this.getPrimaryWheelDelta(t,i);if(s===0)return;e.preventDefault(),this.handleWheelZoom(s,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const s=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(s===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+s);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===Cg)return e*16;if(t===vg){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*Dr.SENSITIVITY_FACTOR),s=Math.max(Re.MIN,Math.min(Re.MAX,i*r));Math.abs(s-i)<Dr.CONVERGENCE_THRESHOLD||this.setZoomCenteredOnTimelinePointer(s,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var s;const t=(s=this.layout)==null?void 0:s.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const 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()>=St(t)){if(this.setCurrentTime(0),!this.canPlay)return}else{N.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 s=this.getClips();i=Array.isArray(s)?s:[]}catch{return t}if(i.length===0)return t;const r=St(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 s=e.getPrimaryTrack();return((i=s==null?void 0:s.getId)==null?void 0:i.call(s))??null}const t=Array.isArray(this.tracks)?this.tracks.find(s=>{var a;return((a=s.getRole)==null?void 0:a.call(s))==="primary"}):null;return((r=t==null?void 0:t.getId)==null?void 0:r.call(t))??null}isPrimaryTrackId(e){var r,s,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=(s=this.trackManager)==null?void 0:s.getTrack)==null?void 0:a.call(s,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,s=t.orderedClips?[...t.orderedClips]:this.getStableStartOrderedClips(((c=r==null?void 0:r.getClips)==null?void 0:c.call(r))??[]);if(s.length===0)return[];const a=this.buildPrimaryTrackContinuousClips(s),o=new Set(t.forceClipIds??[]),l=[];return a.forEach((h,d)=>{const u=s[d];if(!u)return;const g=u.startTime!==h.startTime||u.endTime!==h.endTime;g&&l.push({clipId:u.id,previousState:u,newState:h}),(g||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 s=r.nextValue;if(this.ensureConfigState().zoom=s,this.syncZoomToScene(s),this.refreshScrollbarMetrics(),this.timeline){const a=this.timeline.getScrollLeft(),o=U.timeToPixels(i,t),c=U.timeToPixels(i,s)-o+a;this.timeline.setScrollLeft(c),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())})}this.emitEvent("zoom_change",{zoom:s})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),r=this.timeline.getScrollLeft(),s=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(s,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),s=this.clipThumbnailLoadStates.get(e.id);if((s==null?void 0:s.signature)===r){if(s.promise)return s.promise;if(s.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}),N.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return N.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,s=!!this.trackManager;for(const a of e){const o=s?this.resolveBatchClipConfig(a,i,r):a,l=await this.addClipInternal(o);if(t.push(l),!s||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",s=t.get(r)||this.resolveBatchAppendTrackId(r);if(!s)return e;const a=i.get(s)??this.getTrackTimelineExtentById(s);return{...e,trackId:s,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?ns(t.getClips()):0}async addClipInternal(e){return this.withStructureSession(async()=>{var C;let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.type||"video",r=i==="text",s=e.src??"",a=e.duration??(r?la: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(s,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(v){N.error("TimelineManager","Failed to get video duration:",{error:v}),h=c}!r&&h>0&&this.sourceMediaRegistry.primeDuration(this.buildSourceMediaKey(e),h);let d=e.thumbnails;const u=e.id||`clip_${o}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=cs({id:u,type:i,externalId:e.externalId,src:s,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?qe(e.visualTransform??vu(ji(this.getPreviewAspectRatio()).height)):i==="video"?xe(e.visualTransform):e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1,textContent:e.textContent??(r?"默认文本":void 0),textStyle:r?{...ce(e.textStyle),anchorVersion:((C=e.textStyle)==null?void 0:C.anchorVersion)??1}:void 0,textResolvedLayout:r?e.textResolvedLayout:void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});N.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:g.id,type:g.type,startTime:g.startTime,duration:g.duration}));const f=()=>{var _;if(e.trackId){const w=this.getTrackCollection().findById(e.trackId);if(w){if(this.registerPreviewAutoAspectRatioClip(g),(_=w.addClip)==null||_.call(w,g),Ui({applied:!0,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const D=e.trackId;this.getTimelineHistoryRecorder().recordAddClip(g,D,this.cloneTrackSnapshot(D),this.getTrackRestoreAnchor(D))},applyEffects:()=>{}}),this.shouldNormalizePrimaryTrackForTrackIds([e.trackId])){const D=this.getActiveStructureSession();D&&this.normalizePrimaryTrackInSession(D)}return this.primeOrLoadClipThumbnails(g),g.id}}const v=this.getTimelineCommands().planTrackPlacement(g,this.getTracksSortedByOrder()),S=this.getTrackCollection(),T=Pp({clip:g,placement:v,trackCollection:S,createTrack:this.createTrack.bind(this)});Ui({applied:T,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const w=this.resolveTrackIdByClipId(g.id);this.getTimelineHistoryRecorder().recordAddClip(g,w,w?this.cloneTrackSnapshot(w):null,w?this.getTrackRestoreAnchor(w):null)},applyEffects:()=>{}});const k=this.resolveTrackIdByClipId(g.id);if(this.shouldNormalizePrimaryTrackForTrackIds([k])){const w=this.getActiveStructureSession();w&&this.normalizePrimaryTrackInSession(w)}return this.primeOrLoadClipThumbnails(g),g.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=>{Ui({applied:Wn(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 s of t){const a=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);a.exists&&(r=Wn(this.getTrackCollection(),a,s)||r)}})}),r?(Oi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Bi({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)}Bi({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 s=()=>{this.withSplitOperation(()=>{r.call(i.track,t)})};this.shouldNormalizePrimaryTrackForTrackIds([i.trackId])?this.withHistoryTransaction("split_primary_track_clip",s):s(),Bi({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(),Bi({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 s=r.clipId;if(!s)return;const a=this.findClipById(s);if(!a||a.type!=="video"&&a.type!=="audio")return;if(i.add(s),r.phase==="failed"&&r.role==="current"){this.applyTimelineClipMediaStatus(s,"failed","媒体丢失");return}(r.phase==="active"||r.phase==="primed")&&!!r.actualSource&&this.clearTimelineClipMediaStatus(s)}),Array.from(t).forEach(r=>{if(i.has(r))return;this.findClipById(r)||t.delete(r)})}applyTimelineClipMediaStatus(e,t,i){const r=this.getFailedPreviewClipIds(),s=this.findClipById(e);if(!s){r.delete(e);return}if(s.mediaStatus===t&&s.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 s,a,o,l;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(kt(e.mode)&&t===Le.width&&i===Le.height){const c=(s=this.getAutoAspectRatioClip())==null?void 0:s.clip,h=(a=c==null?void 0:c.style)==null?void 0:a.sys_width,d=(o=c==null?void 0:c.style)==null?void 0:o.sys_height;typeof h=="number"&&h>0&&typeof d=="number"&&d>0&&(t=h,i=d)}const r=ji({width:t,height:i});return{width:r.width,height:r.height,aspectRatio:`${r.width}:${r.height}`,mode:e.mode,textPreviewFont:((l=this.config)==null?void 0:l.textPreviewFont)??void 0}}resolveTextClipExportLayout(e,t){var i;return e.textResolvedLayout?e.textResolvedLayout:Dp(e,t,((i=this.config)==null?void 0:i.textPreviewFont)??null)??void 0}getExportCoverUrl(e){var r;let t=null,i=null;for(const s of e)for(const a of s.clips)if(a.type==="video"){if(!t||!i){t=s,i=a;continue}if(a.startTime<i.startTime){t=s,i=a;continue}a.startTime===i.startTime&&s.order<t.order&&(t=s,i=a)}return((r=i==null?void 0:i.thumbnails)==null?void 0:r[0])||""}exportTimeline(){const e=this.getExportComposition(),t=this.getResolvedTracksSnapshot().slice().sort((r,s)=>r.order-s.order).map(r=>{const s=r.clips.map(a=>({id:a.id,type:a.type,externalId:a.externalId,src:a.src,name:a.name,isMuted:a.isMuted??!1,startTime:Math.round(a.startTime),duration:Math.round(a.duration),endTime:Math.round(a.endTime),startTimeAtSource:Math.round(a.startTimeAtSource),endTimeAtSource:Math.round(a.endTimeAtSource),sourceDuration:Math.round(a.sourceDuration),thumbnails:a.thumbnails,visualTransform:a.type==="text"?qe(a.visualTransform):a.type==="video"?xe(a.visualTransform):void 0,separatedAudioClipId:a.separatedAudioClipId,separatedFromVideoClipId:a.separatedFromVideoClipId,volume:a.volume??1,textContent:a.textContent,textStyle:a.textStyle,textResolvedLayout:a.type==="text"?this.resolveTextClipExportLayout(a,e):void 0,ttsSourceTextClipId:a.ttsSourceTextClipId,ttsVoiceId:a.ttsVoiceId,ttsVoiceName:a.ttsVoiceName,ttsFollowTextUpdates:a.ttsFollowTextUpdates})).sort((a,o)=>a.startTime-o.startTime);return{id:r.id,type:r.type,name:r.name||"未命名轨道",order:r.order,role:r.role??"normal",isMuted:r.isMuted??!1,clips:s}}),i=this.getExportCoverUrl(t);return{version:this.getVersion(),exportTime:Date.now(),coverUrl:i,composition:e,tracks:t}}async importTimeline(e){if(!e||!e.composition||!e.tracks){N.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,s=[...e.tracks].sort((c,h)=>c.order-h.order),a=this.resolveImportedTrackRoles(s);let o;for(const c of s){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 s){const h=r.get(c.id);if(h)for(const d of c.clips)try{let u=d.separatedAudioClipId;u&&l.has(u)&&(u=l.get(u));let g=d.separatedFromVideoClipId;g&&l.has(g)&&(g=l.get(g));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:g,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,textResolvedLayout:d.textResolvedLayout,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}),N.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 s of e){const a=s.role==="primary"&&!i?"primary":"normal";a==="primary"&&(i=!0),t.set(s.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 zt.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,s=((l=this.stage)==null?void 0:l.width())||0,a=s-pe*2;N.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:s,availableWidth:a}));const o=Math.min(a/r,Re.MAX);if(this.setZoom(o),this.timeline){const c=e.reduce((h,d)=>d.startTime<h.startTime?d:h);this.scrollToClip(c.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){var i;this.previewSyncInteractionMode=t,this.previewClockSeekAlignmentTargetTime=t==="seek"?this.clampPlaybackSeekTime(e):null,this.previewClockSeekAlignmentDeadlineMs=t==="seek"?Date.now()+kg: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 s=this.selectedClipId===e.id;Qd({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)}),s&&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}),Oi({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)&&Oi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){eu(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{N.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){const e=this.getClips(),t=this.getCurrentTime(),i=tu(e,t),r=this.canPlay;this.canPlay=iu({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:St(e)||1,setCanPlay:s=>{this.canPlay=s},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:s=>{this.emitEvent("can_play_change",{canPlay:s})}}),r!==this.canPlay&&N.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:"",s=i.trim().length>0?i:r.trim().length>0?r:"";if(s.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:s}}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 s;this.pendingVoiceLinkedTextRegeneration&&this.pendingVoiceLinkedTextRegeneration.clipId!==e&&(this.voiceLinkedTextRegenerationTimer!==null&&(clearTimeout(this.voiceLinkedTextRegenerationTimer),this.voiceLinkedTextRegenerationTimer=null),this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{N.error("TimelineManager","Failed to flush pending linked voice regeneration",{error:a,clipId:e})})),this.voiceLinkedTextRegenerationTimer!==null&&clearTimeout(this.voiceLinkedTextRegenerationTimer),this.pendingVoiceLinkedTextRegeneration={clipId:e,originalClip:((s=this.pendingVoiceLinkedTextRegeneration)==null?void 0:s.clipId)===e?this.pendingVoiceLinkedTextRegeneration.originalClip:{...t},nextText:i,generateVoiceBatch:r},this.voiceLinkedTextRegenerationTimer=setTimeout(()=>{this.voiceLinkedTextRegenerationTimer=null,this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{N.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:a,clipId:e})})},ca)}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,s=i?this.getTimelineHistoryRecorder().createClipUpdateAction(i,e.originalClip):null;await this.withHistoryTransaction("update_text_with_voice_regeneration",async()=>{s&&this.getTimelineHistoryRecorder().recordAction(s),await this.regenerateVoiceLinkedAudioClips(e.clipId,r,e.generateVoiceBatch)})}applyGeneratedAudioClipResult(e,t,i,r,s){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:s})}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(s=>s.id!==t.id&&t.startTime<s.endTime&&r>s.startTime)}doesClipGroupOverlapOnTrack(e,t,i=new Set){const r=this.getTrackCollection().findById(e);if(!r)return!1;const s=r.getClips().filter(a=>!i.has(a.id));return t.some(a=>{const o=a.startTime+a.duration;return s.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 s=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??s++,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(s=>s.newTrackCount===0).sort((s,a)=>s.score-a.score)[0];if(i)return i.startIndex;if(e==="text"){const s=t.filter(a=>a.startIndex<0).sort((a,o)=>a.newTrackCount!==o.newTrackCount?a.newTrackCount-o.newTrackCount:a.score-o.score)[0];if(s)return s.startIndex}return((r=t.slice().sort((s,a)=>s.score-a.score)[0])==null?void 0:r.startIndex)??null}buildClipboardPasteGroupPlacementClips(e,t,i,r){const s=new Map(t.items.map(a=>[a.sourceClipId,a]));return e.sourceClipIds.map(a=>{const o=s.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 s;return((s=r.trackSnapshot)==null?void 0:s.type)===t}).sort((r,s)=>{var a,o;return(((a=r.trackSnapshot)==null?void 0:a.order)??Number.MAX_SAFE_INTEGER)-(((o=s.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 s=new Map;if(e.length===0)return s;this.ensureClipboardPasteSourceTracks(t,e[0].type);const a=[...this.getResolvedTracksSnapshot()].filter(T=>{var k;return T.type===((k=e[0])==null?void 0:k.type)}).sort((T,k)=>T.order-k.order);if(a.length===0){const T=this.createTrack(e[0].type);T&&s.set(e[0].key,T);for(let k=1;k<e.length;k+=1){const _=this.createTrack(e[k].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");_&&s.set(e[k].key,_)}return s}const o=new Set(e.flatMap(T=>T.clipIds)),l=e.map(T=>{const k=this.buildClipboardPasteGroupPlacementClips(T,t,i,r);if(k.length===0)return null;const _=this.resolvePreferredTrackIndexForPasteGroup(T,a,Math.min(T.sourceOrder,Math.max(a.length-1,0)));return{...T,preferredTrackIndex:_,clips:k}}).filter(T=>T!==null);if(l.length===0)return s;const c=l.map(T=>T.preferredTrackIndex),h=Math.min(...c),d=a.length,u=-l.length,g=[];for(let T=u;T<=d;T+=1){let k=!0,_=0,w=0;for(let D=0;D<l.length;D+=1){const x=l[D];if(!x)continue;const R=T+D;if(_+=Math.abs(R-x.preferredTrackIndex),R<0||R>=a.length){w+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[R].id,x.clips,o)){k=!1;break}}k&&(_+=w*.1,_+=Math.abs(T-h)*ha.ANCHOR_INDEX_WEIGHT,g.push({startIndex:T,score:_,newTrackCount:w}))}const f=this.selectBestClipboardPasteStartIndex(l[0].type,g);if(f===null)return s;const m=Math.max(0,-f),C=Math.max(0,f+l.length-a.length);m>0&&this.createTracksForTypeBoundary(l[0].type,m,"before"),C>0&&this.createTracksForTypeBoundary(l[0].type,C,"after");const v=[...this.getResolvedTracksSnapshot()].filter(T=>{var k;return T.type===((k=l[0])==null?void 0:k.type)}).sort((T,k)=>T.order-k.order),S=f+m;return l.forEach((T,k)=>{const _=v[S+k];_&&s.set(T.key,_.id)}),s}resolvePreferredTrackIndexForPasteGroup(e,t,i){if(e.sourceTrackId){const r=t.findIndex(s=>s.id===e.sourceTrackId);if(r!==-1)return r}if(Number.isFinite(e.sourceTrackOrder)){const r=t.findIndex(s=>s.order>=e.sourceTrackOrder);return r!==-1?r:t.length}return i}resolveClipboardPasteTrackAssignments(e,t,i){const r=this.buildClipboardPasteGroups(e,t),s=new Map;r.forEach(o=>{const l=s.get(o.type)??[];l.push(o),s.set(o.type,l)});const a=new Map;return s.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 s=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(s),o=new Map(a.map(c=>[c.requestId,c]));let l=0;s.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"||!Me(e))return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(s=>Me(s))))return[e];const r=t.filter(s=>Me(s));return r.some(s=>s.id===e.id)?r:[e]}async handleVoiceGenerateAction(e,t,i,r,s){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 s(d),m=new Map(f.map(C=>[C.requestId,C]));for(const C of d){const v=m.get(C.requestId);if(!v)continue;const S=c.find(w=>w.id===C.sourceTextClipId);if(!S)continue;const T=this.normalizeGeneratedAudioDuration(v.duration),k=S.textContent??S.name??"";this.syncTextClipDurationToAudio(S.id,T);const _=await this.addClip({type:"audio",src:v.audioSrc,name:this.buildGeneratedAudioClipName(v.voiceName),textContent:k,startTime:S.startTime,duration:T,startTimeAtSource:0,endTimeAtSource:T,sourceDuration:T,ttsSourceTextClipId:S.id,ttsVoiceId:v.voiceId,ttsVoiceName:v.voiceName,ttsFollowTextUpdates:r});u.push(_)}if(u.length===0)throw new Error("生成音频失败:未返回音频结果")}),u.length===1){this.scrollToClip(u[0],{selectClip:!0,setCurrentTime:!0});return}const g=u[0]??null;this.scrollToClip(g,{setCurrentTime:!0}),this.setSelection(u,{preferredPrimaryClipId:g});return}if(t.type!=="audio"||!Me(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 s(l),h=new Map(c.map(u=>[u.requestId,u])),d=new Map;if(l.some(u=>!h.has(u.requestId)))throw new Error("替换音色失败:未返回音频结果");for(const u of l){const g=h.get(u.requestId);if(!g||!u.targetAudioClipId)continue;const f=a.find(C=>C.id===u.targetAudioClipId);if(!f)continue;const m=this.resolveTtsAudioVoiceGenerationSource(f);if(this.applyGeneratedAudioClipResult(u.targetAudioClipId,m.persistedSourceTextClipId,m.text,g,r),this.relocateClipIfNeeded(u.targetAudioClipId),m.persistedSourceTextClipId){const C=d.get(m.persistedSourceTextClipId)??0;d.set(m.persistedSourceTextClipId,Math.max(C,g.duration))}}d.forEach((u,g)=>{this.syncTextClipDurationToAudio(g,u)}),this.handleClipChange()})}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{N.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){N.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 Lr.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return Lr.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,s=i?this.getTrackRestoreAnchor(i):null;this.withStructureSession(a=>{nu({clip1:e,clip2:t,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordSplitClip:(o,l)=>{this.getTimelineHistoryRecorder().recordSplitClip(o,l,i,r,s)},emitClipUpdated:o=>{this.emitEvent("clip_updated",{clip:o})},emitClipAdded:o=>{this.emitEvent("clip_added",{clip:o})},applyEffects:()=>Oi({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=ru(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),N.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){N.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new In(t.createHistoryExecutionTarget()).executeUndo(e)})})}handleActionRedo(e){N.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new In(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=kp({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 s=this.getStableStartOrderedClips(i),a=s.findIndex(l=>l.startTime>=e.startTime),o=[...s];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,g;N.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const r=this.getTrackCollection();if(!r.findById(t))return;const s=e.type,a=this.trackManager.getTracksByType(s).length+1,o=`${xg(s)}轨道 ${a}`,l=this.createTrack(s,o);if(!l)return;const c=((d=(h=r.findById(l))==null?void 0:h.getId)==null?void 0:d.call(h))||((g=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:g.call(u))||l;this.moveClipToTrackWithHistorySnapshot(e.id,c,i??null,e),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const r=this.resolveCrossTrackPreviewDestination(e,t,i);return r.status==="existing_track"?(this.showClipDropPreview(e,r.targetTrackId),r.targetTrackId===i?"self":"external"):r.status==="new_track_insertion"?(this.showTrackInsertionPreview(r.trackType,r.insertionPlacement,r.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,r){N.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:r}));const s=this.resolveCrossTrackMoveDestination(e,i,r);return s.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):s.status==="same_track"?(N.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(N.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:s.targetTrackId})),this.showClipDropPreview(e,s.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,s.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}getRenderedHeight(){return this.getTimeScaleHeight()+this.calculateTotalHeight()+Jr}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,s;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((s=(r=this.selectionStore)==null?void 0:r.getSelectedClipId)==null?void 0:s.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(s=>s!==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=[],s=this.getCurrentTime();if(await this.withHistoryTransaction("paste_clipboard_clips",async()=>{for(const o of e.items){const l=this.buildClipboardPasteClipConfig(o,s,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 s=this.getTimelineCommands().prepareRemoveClip(r,this.tracks);return!s.exists||!s.clip?null:(s.trackId&&!t.has(s.trackId)&&t.set(s.trackId,{sourceTrackId:s.trackId,trackSnapshot:this.cloneTrackSnapshot(s.trackId),trackRestoreAnchor:this.getTrackRestoreAnchor(s.trackId)}),{sourceClipId:r,sourceTrackId:s.trackId,clip:this.cloneClipForClipboard(s.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:ra(e.style),visualTransform:e.visualTransform?{...e.visualTransform}:void 0,textStyle:e.textStyle?{...e.textStyle}:void 0}}buildClipboardPasteClipConfig(e,t,i){const r=e.clip,s=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:ra(r.style),visualTransform:r.visualTransform?{...r.visualTransform}:void 0,separatedAudioClipId:s,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}`,s=i.get(r);if(s)return s;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,s=this.getClips().find(a=>a.id===e);!s||!this.timeline||(this.timeline.scrollToClip(s),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),r&&this.setCurrentTime(s.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}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=Ue({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 Do,r=t.generateVoiceBatch,s=r,a=r?async c=>{i.setVoiceGenerationBusy(!0);try{return await r(c)}finally{i.setVoiceGenerationBusy(!1)}}:void 0;i.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),getSelectedClips:()=>this.getSelectedClips(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c),u=d?{...d}:null,g=typeof h.textContent=="string"?h.textContent:null;if(s&&(u==null?void 0:u.type)==="text"&&g!==null&&g!==u.textContent&&this.hasVoiceLinkedAudioClipsToRegenerate(c)&&(u==null?void 0:u.type)==="text"){this.withHistoryBoundary("suppressed",()=>{this.updateClip(c,h)}),this.handleClipChange(),this.scheduleVoiceLinkedTextRegeneration(c,u,g,s);return}this.updateClip(c,h),this.handleClipChange()},onGenerateVoice:async(c,h,d)=>{if(!a)throw new Error("未配置音色生成回调");await this.handleVoiceGenerateAction(i,c,h,d,a)}});const o=()=>i.updateFromExternal(),l=(c,h)=>{var g;const d=new Set(this.getSelectedClipIds()),u=this.getPrimarySelectedClip();d.size===0&&(u!=null&&u.id)&&d.add(u.id),(g=h==null?void 0:h.clip)!=null&&g.id&&d.has(h.clip.id)&&i.updateFromExternal()};return this.on("selected_clip_change",o),this.on("clip_updated",l),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",o),this.off("clip_updated",l),i.destroy()}),i.update(),i}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return Ue(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:zt.name,packageVersion:zt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=Ue({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={...Le},(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),s=r.findIndex(c=>c.id===i);if(s===-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-s)-Math.abs(h.index-s);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 s=!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?(s&&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,s=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,s),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(s=>s.type==="video"),i=e==="separate"?t.filter(s=>this.canSeparateClipAudio(s.id)):t.filter(s=>this.canRestoreClipAudio(s.id));if(i.length===0)return!1;if(i.length===1){const[s]=i;return e==="separate"?!!await this.separateClipAudio(s.id):this.restoreClipAudio(s.id)}let r=0;return await this.withHistoryTransaction(`selected_clips_audio_${e}`,async()=>{if(e==="restore"){for(const s of i)this.restoreClipAudio(s.id)&&(r+=1);return}for(const s of i)await this.separateClipAudio(s.id)&&(r+=1)}),r>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,r=null){const s=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(s.status==="missing_source_track")return N.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(s.status==="noop")return N.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(s.status==="missing_target_track")return N.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(s.status==="track_type_mismatch")return N.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(s.status!=="ready")return!1;const a=this.shouldNormalizePrimaryTrackForTrackIds([s.sourceTrackId,s.targetTrackId]),o=()=>this.withStructureSession(l=>{const{sourceTrackId:c,targetTrackId:h}=s,d=i?{...i}:{...s.clip},u=r?{...r}:{...s.clip},g=this.cloneTrackSnapshot(c),f=this.cloneTrackSnapshot(h),m=this.getTrackRestoreAnchor(c),C=this.getTrackRestoreAnchor(h),v=_p({command:{...s,clip:u},trackCollection:this.getTrackCollection()}),S=this.getClips().find(T=>T.id===e)??null;return su({applied:v,clipId:e,sourceTrackId:c,targetTrackId:h,clipBefore:d,clipAfter:S??d,sourceTrackSnapshot:g,targetTrackSnapshot:f,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordMoveClipBetweenTracks:(T,k,_,w,D,x,R)=>{this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks(T,k,_,w,D,x,R,m,C)},applyEffects:()=>{}})?(a&&this.normalizePrimaryTrackInSession(l),this.clearAllTrackDropPreviews(),!0):!1});return a?this.withHistoryTransaction("move_primary_track_clip_between_tracks",o):o()}getTrackTotalDuration(){return zn(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,s,a,o,l,c,h,d,u,g,f,m,C;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:(s=r.bodyCanvasHost).removeEventListener)==null||a.call(s,"click",this.bodyCanvasHostClickListener);const e=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);e&&this.stageMouseDownListener&&((c=e.removeEventListener)==null||c.call(e,"mousedown",this.stageMouseDownListener)),(d=(h=this.rootContainer)==null?void 0:h.removeEventListener)==null||d.call(h,"wheel",this.rootWheelListener),(u=this.horizontalScrollbar)==null||u.destroy(),(g=this.verticalScrollbar)==null||g.destroy(),(f=this.playhead)==null||f.destroy(),(m=this.timeline)==null||m.destroy(),(C=this.stage)==null||C.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new ia),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new Tp({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,s=t.filter(a=>a.externalId===e).map(a=>a.id);for(let a=0;a<s.length;a+=1){const o=s[a];if(r.has(o))continue;r.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!r.has(l.separatedAudioClipId)&&s.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!r.has(l.separatedFromVideoClipId)&&s.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 s=this.getTimelineCommands().findClipById(this.tracks,r),a=s==null?void 0:s.clip;if(a&&e>=a.startTime&&e<a.endTime)return s}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{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 s=new Set(i);let a=0;for(const h of this.tracks){const d=(o=h.getId)==null?void 0:o.call(h);!d||s.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 s=(i=r.getId)==null?void 0:i.call(r);if(!s)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===s})&&t.add(s)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const r of e.selectedClipIds){const s=e.clips.get(r);if(!s)continue;const a=i.get(s.trackId);a?a.push(r):i.set(s.trackId,[r])}i.forEach((r,s)=>{var o;const a=this.getTrackCollection().findById(s);(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 s of t){const a=this.findTrackByClipId(s),o=((r=a==null?void 0:a.getId)==null?void 0:r.call(a))??this.resolveTrackIdByClipId(s),l=a==null?void 0:a.getClips().find(h=>h.id===s);if(!o||!l)continue;const c=s===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(s,{clipId:s,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 s=e.clips.get(r);if(!s||s.trackId===t.currentTrackId)continue;const a=this.getTrackCollection().findById(s.trackId);if(!(a!=null&&a.updateClipPosition))continue;const o=Math.max(0,s.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((s,a)=>(s.order??0)-(a.order??0));for(const s of r){const a=i.get(s.type)??[];a.push(s.id),i.set(s.type,a),t.set(s.id,s.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)??[],s=i.startTime+i.duration;return r.some(a=>a.id!==i.id&&i.startTime<a.startTime+a.duration&&s>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,s){const a=e.orderedTrackIdsByType.get(i)??[];if(!a.includes(t)){if(r==="before_track"&&s){const o=a.indexOf(s);o>=0?a.splice(o,0,t):a.unshift(t)}else if(r==="after_track"&&s){const o=a.indexOf(s);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)??[],s=r.indexOf(i);if(s===-1)return null;const o=r.map((l,c)=>({trackId:l,index:c,distance:Math.abs(c-s)})).filter(({trackId:l})=>l!==i).sort((l,c)=>{if(l.distance!==c.distance)return l.distance-c.distance;const h=l.index>s?0:1,d=c.index>s?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 s=this.createTrack(t.type,void 0,"after_track",i);if(s)return this.registerMultiDragPlacementTrack(e,s,t.type,"after_track",i),s;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 s=[],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),g=i(d,u);if(!g)continue;if(r.compactSameTrackPrimary&&this.getEnablePrimaryTrackMagnet()&&g===d.trackId&&this.isPrimaryTrackId(d.trackId)){c=d.trackId,l.set(d.clipId,d.clip),o.set(d.clipId,u);continue}let f=g;if(!(this.doesMultiDragPlacementOverlap(a,g,u)&&(f=this.resolveMultiDragOverlapTargetTrackId(a,u,g),!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),s.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&&s.push(...this.compactPrimaryTrackAfterMultiDrag(c,o,l)),s.length>0&&this.getTimelineHistoryRecorder().recordClipUpdate(s[0].newState,void 0,s),!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),s=this.getStableStartOrderedClips(((d=r==null?void 0:r.getClips)==null?void 0:d.call(r))??[]);if(s.length===0)return[];const a=new Map(s.map(u=>[u.id,u])),o=new Map(a);i.forEach((u,g)=>{o.set(g,u)});const l=this.buildPrimaryTrackMultiDragOrderedClips(s,t),c=this.buildPrimaryTrackContinuousClips(l),h=[];return c.forEach(u=>{const g=a.get(u.id),f=o.get(u.id);!g||!f||((g.startTime!==u.startTime||g.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),s=this.resolveCrossTrackPreviewDestination(r,t.targetTrackY,i.trackId);if(s.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(s.trackType,s.insertionPlacement,s.referenceTrackId),!0;if(s.status!=="existing_track"||s.targetTrackId===i.trackId)return!1;const a=this.resolveTrackIndexDelta(i.trackId,s.targetTrackId,i.clip.type);if(a===null)return!1;const o=new Map;this.appendPreviewClip(o,s.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),s=this.resolveCrossTrackMoveDestination(r,t.targetTrackY,i.trackId);if(s.status==="blocked"||s.status==="same_track")return!1;const a=s.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),s=r.indexOf(e),a=r.indexOf(t);return s===-1||a===-1?null:a-s}resolveMultiDragTargetTrackId(e,t,i){const r=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return e.trackId;const s=this.calculateTrackY(r)+1,a=this.resolveCrossTrackMoveDestination(i,s,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 s=this.calculateTrackY(r)+1,a=this.resolveCrossTrackPreviewDestination(i,s,e.trackId);return a.status==="existing_track"?a.targetTrackId:null}buildMovedClipSnapshot(e,t,i=!1){let r=e.startTime+t;if(i){const s=this.getDurationState();r=Math.max(0,Math.min(r,s-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(),s=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);if(s.status==="missing_target_track_by_position")return N.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(s.status==="same_track")return{status:"same_track",targetTrackId:s.targetTrackId};if(s.status==="missing_target_track_view")return N.warn("TimelineManager","目标轨道不存在",{targetTrackId:s.targetTrackId}),{status:"blocked"};if(s.status==="track_type_mismatch")return N.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:s.targetTrackType,clipType:e.type})),{status:"blocked"};if(s.status==="move_to_track")return{status:"move_to_track",targetTrackId:s.targetTrackId};N.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const a=this.createTrack(s.trackType,void 0,s.insertionPlacement,s.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 s=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);return s.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:s.targetTrackId}:s.status==="new_track_insertion"?{status:"new_track_insertion",trackType:s.trackType,insertionPlacement:s.insertionPlacement,referenceTrackId:s.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(e,t,i){let r=this.getTrackIdsByType(t);const s=r.indexOf(e);if(s===-1)return null;let a=s+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),s=r.indexOf(e);if(s===-1)return null;const a=s+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),s=r==null?void 0:r.updateClipPosition;s&&this.withHistoryBoundary("suppressed",()=>{s.call(r,t,i,!0)})}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new Z.Rect({fill:Ps.fill,stroke:Ps.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 s=this.ensureSelectionBoxRect();s.x(e),s.y(t),s.width(Math.max(i,1)),s.height(Math.max(r,1)),s.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(),s=e.clientX-r.left,a=e.clientY-r.top;if(this.isPointOnClip(s,a))return;this.isBoxSelecting=!1,this.boxSelectStartX=s,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(),s=e.clientX-r.left,a=e.clientY-r.top,o=Math.abs(s-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,s),h=Math.min(this.boxSelectStartY,a),d=Math.abs(s-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 s=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);if(!(t<s||t>s+a))for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Ce(o.duration,this.getZoomState());if(e>=l&&e<=l+c&&t>=s+2&&t<=s+a-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const s=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Ce(o.duration,this.getZoomState()),h=s+2,d=a-4,u=l+c,g=h+d,f=e.x+e.width,m=e.y+e.height;l<f&&u>e.x&&h<m&&g>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return _e(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 s=[...this.getTracks()].sort((u,g)=>u.order-g.order),a=s.find(u=>u.order>=e.order),o=a?s[s.findIndex(u=>u.id===a.id)-1]??null:s[s.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,s,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:((s=t[i-1])==null?void 0:s.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 s=(Array.isArray(this.tracks)?this.tracks:[]).find(o=>o.getClips().some(l=>l.id===e));return(s==null?void 0:s.getId())??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var a;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=ns(e),s=zn(e);if(r!==t){this.lastTrackDuration=r;const o=$n(r);this.setDurationState(o),(a=this.timeline)==null||a.setDuration(o),this.updateViewportLayout()}if(s!==i&&(this.lastReportedTrackDuration=s,this.emitEvent("track_duration_change",{duration:s})),e.length===0&&this.getCurrentTimeState()!==0&&this.setCurrentTime(0),e.length>0){const o=St(e);o>0&&this.getCurrentTimeState()>o&&this.setCurrentTime(o)}r===t&&s===i||N.debugLazy("TimelineManager",()=>`Track duration changed: total=${s}ms, extent=${r}ms, timeline=${$n(r)}ms`)}resolveSelectedClipSnapshot(){return Lo({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 bp({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(l=>l.id===e);if(!i||i.type!=="video"&&i.type!=="text")return;const r=i.type==="text"?qe:xe,s=r(i.visualTransform),a=r(t);if(bs(s,a))return;const o={visualTransform:a};if(i.type==="text"){const l=ce(i.textStyle);l.anchorVersion!==1&&(o.textStyle={...l,anchorVersion:1})}this.updateClip(e,o)}commitPreviewTextLayout(e,t){const i=this.getClips().find(s=>s.id===e);if(!i||i.type!=="text")return;const r=ce(i.textStyle);r.layoutWidth===t.layoutWidth&&r.layoutHeight===t.layoutHeight||this.updateClip(e,{textStyle:{...r,layoutWidth:t.layoutWidth,layoutHeight:t.layoutHeight,anchorVersion:1}})}commitPreviewTextResolvedLayout(e,t){const i=this.getClips().find(r=>r.id===e);!i||i.type!=="text"||wu(i.textResolvedLayout,t)||this.updateClip(e,{textResolvedLayout:t})}commitPreviewTextFontSize(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=ce(i.textStyle),s=Math.max(ci.MIN,Math.min(ci.MAX,Math.round(t)));r.fontSize!==s&&this.updateClip(e,{textStyle:{...r,fontSize:s}})}commitPreviewTextRotation(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=ce(i.textStyle),s=Math.round(t);r.rotation!==s&&this.updateClip(e,{textStyle:{...r,rotation:s}})}clearAllTracksAndClips(){this.withHistoryBoundary("reset",()=>{var t,i,r,s;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(),(s=this.stage)==null||s.batchDraw(),this.clearHistory()})}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=os;exports.CLIP_LAYER=No;exports.Clip=zi;exports.ClipConfigPanel=mo;exports.DEFAULT_CLIP_VIEW_STATE=oa;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Le;exports.DEFAULT_TEXT_CLIP_DURATION_MS=la;exports.DEFAULT_TEXT_CLIP_STYLE=na;exports.DEFAULT_TIMELINE_DURATION_MS=Zt;exports.DiagnosticsCenter=Qa;exports.HistoryManager=ts;exports.MIN_CLIP_LINE_WIDTH=hi;exports.PREVIEW_ASPECT_RATIO_PRESETS=Go;exports.SNAP_SCORING=ha;exports.TEXT_CLIP_FONT_SIZE_LIMITS=ci;exports.TIMELINE_LEFT_PADDING=pe;exports.TIME_SCALE=$o;exports.TRACK_HEIGHT=Hi;exports.TimeUtils=U;exports.TimelineClipConfigController=Do;exports.TimelineManager=Pg;exports.Track=ir;exports.TrackInfoPanel=fo;exports.TrackManager=Oo;exports.VOICE_LINKED_TEXT_REGEN_DEBOUNCE_MS=ca;exports.ZOOM_ANIMATION=zo;exports.ZOOM_GESTURE=Dr;exports.ZOOM_PRESETS=Re;exports.createClipViewState=da;exports.createClipWithViewState=cs;exports.defaultDarkTheme=Yi;exports.devConsole=N;exports.isAudioOnlyTtsClipCandidate=aa;exports.isAutoPreviewAspectRatioMode=kt;exports.isTtsAudioClip=Me;exports.mergeDiagnosticRuntimeState=Mh;exports.normalizePreviewAspectRatio=Ue;exports.normalizePreviewAspectRatioMode=ls;exports.resolveAspectRatioBaselineDimensions=ji;exports.resolveTextClipStyle=ce;exports.resolveTheme=Xi;
734
+ `),a=Math.max(1,t-i*2),o=yu(e)?mu:fu,l=Math.max(1,Math.floor(a/(r*o)));let c=0;for(const h of s){const d=h.length>0?h:" ";c+=Math.max(1,Math.ceil(d.length/l))}return Math.max(vo,Math.round(r*gu*c))}function vu(n,e=hu){const t=n>0?n:720;return{x:.5,y:1-Ts-e/t/2,scale:1}}function bo(n,e){return n.anchorVersion!==Co?!0:e>=1-Ts-.008}function ko(n,e,t,i){return n.height<=0?0:bo(t,e.y)?n.height*e.y-i/2:n.height*e.y}function Tu(n,e,t){const i=e.height>0?e.height:1,r=t/i/2;return{x:n.x,y:n.y-r,scale:1}}function wo(n,e,t,i){const r={x:typeof(n==null?void 0:n.x)=="number"&&Number.isFinite(n.x)?n.x:.5,y:typeof(n==null?void 0:n.y)=="number"&&Number.isFinite(n.y)?n.y:.5,scale:1};return bo(e,r.y)?Tu(r,t,i):r}function xo(n){return Math.min(uu,Math.max(du,n))}function Po(n){return Math.min(pu,Math.max(vo,n))}function _o(n){return n.layoutHeight!==void 0}function bu(n){return _o(ce(n))?"manual":"auto"}function ws(n){var o,l,c;const e=n.textStyle,t=((o=n.styleOverride)==null?void 0:o.fontSize)??e.fontSize,i=n.frameSize,r=ks(n.baselineScale),s=xo(((l=n.styleOverride)==null?void 0:l.layoutWidth)??e.layoutWidth??Su(i.width,r,e.paddingX,n.visualTransform.x)),a=Po(((c=n.styleOverride)==null?void 0:c.layoutHeight)??e.layoutHeight??Cu(t,n.contentText,s,e.paddingX));return{layoutWidth:s,layoutHeight:a}}function Ao(n){const{layoutWidth:e,layoutHeight:t}=ws(n),i=e*n.baselineScale,r=t*n.baselineScale,s=n.frameSize.width*n.visualTransform.x,a=ko(n.frameSize,n.visualTransform,n.textStyle,r),o={left:s-i/2,top:a-r/2,width:i,height:r,centerX:s,centerY:a};return{layoutWidth:e,layoutHeight:t,frameRect:o,visualTransform:n.visualTransform}}function ku(n,e,t,i,r){const s=ks(r),a=Math.abs(n-t),o=Math.abs(e-i);return{layoutWidth:xo(Math.round(a*2/s)),layoutHeight:Po(Math.round(o*2/s))}}function Io(n,e,t,i){const r=ce(n.clip.textStyle),s=n.clip.textContent||n.clip.name||"",{layoutHeight:a}=ws({frameSize:e,baselineScale:t,visualTransform:{x:.5,y:.5,scale:1},textStyle:r,contentText:s,styleOverride:i}),o=a*t,l=wo(n.clip.visualTransform,r,e,o);return Ao({frameSize:e,baselineScale:t,visualTransform:l,textStyle:r,contentText:s,styleOverride:i})}function Eo(n){const{layout:e,frameSize:t,baselineScale:i,visualTransform:r,textStyle:s,measuredHeightPx:a}=n,o=t.width*r.x,l=ko(t,r,s,a);return{...e,layoutHeight:Math.ceil(a/i),visualTransform:r,frameRect:{...e.frameRect,width:e.frameRect.width,height:a,centerX:o,centerY:l,left:o-e.frameRect.width/2,top:l-a/2}}}function Ro(n){const{frameSize:e,composition:t,lastLayout:i,layoutMode:r}=n,s=e.width>0?e.width:t.width,a=e.height>0?e.height:t.height,{layoutWidth:o,layoutHeight:l}=i;return{compositionWidth:t.width,compositionHeight:t.height,layoutWidth:o,layoutHeight:l,layoutWidthRatio:t.width>0?o/t.width:0,layoutHeightRatio:t.height>0?l/t.height:0,centerX:s>0?i.frameRect.centerX/s:0,centerY:a>0?i.frameRect.centerY/a:0,layoutMode:r,anchorVersion:Co}}function wu(n,e,t=1e-4){return!n&&!e?!0:!n||!e?!1:n.compositionWidth===e.compositionWidth&&n.compositionHeight===e.compositionHeight&&n.layoutWidth===e.layoutWidth&&n.layoutHeight===e.layoutHeight&&n.layoutMode===e.layoutMode&&n.anchorVersion===e.anchorVersion&&Math.abs(n.centerX-e.centerX)<=t&&Math.abs(n.centerY-e.centerY)<=t}function xu(n){if(!n||typeof n!="object")return!1;const e=n;if(typeof e.closest=="function")return!!e.closest(".timeline-preview-transform-handle");const t=e.className;return typeof t=="string"&&t.includes("timeline-preview-transform-handle")}function Ln(n){if(!n)return 0;const e=Number.parseFloat(n);return Number.isFinite(e)?e:0}class Pu{constructor(e={}){p(this,"frameElement",null);p(this,"overlayElement",null);p(this,"boxElement",null);p(this,"rotateHandleElement",null);p(this,"rotateHandlePointerDownHandler",null);p(this,"handleElements",new Map);p(this,"handlePointerDownHandlers",new Map);p(this,"state",null);p(this,"interaction",null);p(this,"textHostElement",null);p(this,"callbacks");p(this,"boundPointerMove",e=>{this.handleDocumentPointerMove(e)});p(this,"boundPointerUp",()=>{this.finishInteraction(!0)});p(this,"boundVisibilityChange",()=>{var e;(e=this.getDocument())!=null&&e.hidden&&this.finishInteraction(!1)});p(this,"boundWindowBlur",()=>{this.finishInteraction(!1)});p(this,"handleMovePointerDown",e=>{var i,r,s,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=(s=this.callbacks).onTextTransformInteractionStart)==null||a.call(s)),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,startLayoutWidth:void 0,startLayoutHeight:void 0,nextLayoutWidth:void 0,nextLayoutHeight: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 ${ze.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),this.setTextHost(null),(e=this.boxElement)==null||e.removeEventListener("pointerdown",this.handleMovePointerDown),this.handleElements.forEach((i,r)=>{const s=this.handlePointerDownHandlers.get(r);s&&i.removeEventListener("pointerdown",s)}),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.setTextHost(null),this.state=null,this.finishInteraction(!1),this.render();return}this.interaction&&this.interaction.clipId!==e.clipId&&this.finishInteraction(!1),this.setTextHost(e.clipType==="text"?e.textHostElement??null:null),this.state=e,this.render()}handleTextHostPointerDown(e){xu(e.target)||this.handleMovePointerDown(e)}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 ${ze.border}`,e.style.background=ze.handleBackground,e.style.pointerEvents="auto",e.style.cursor="grab",e.style.boxSizing="border-box",e.style.transform="translate(-50%, -50%)",e.style.alignItems="center",e.style.justifyContent="center",e.style.fontSize="12px",e.style.color=ze.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,s=this.toLocalPoint(t),a=Math.atan2(s.y-r,s.x-i)*(180/Math.PI);this.interaction={clipId:this.state.clipId,mode:"rotate",pointerStart:s,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,startLayoutWidth:void 0,startLayoutHeight:void 0,nextLayoutWidth:void 0,nextLayoutHeight: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 ${ze.border}`,i.style.background=ze.handleBackground,i.style.borderRadius="999px",i.style.pointerEvents="auto",i.style.cursor=t,i.style.boxSizing="border-box",i.style.zIndex="10",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 s=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:s,clipType:this.state.clipType??"video",startFontSize:void 0,nextFontSize:void 0,startLayoutWidth:r?this.state.currentLayoutWidth:void 0,startLayoutHeight:r?this.state.currentLayoutHeight:void 0,nextLayoutWidth:r?this.state.currentLayoutWidth:void 0,nextLayoutHeight:r?this.state.currentLayoutHeight:void 0,centerX:a,centerY:o,startCenterDistance:l,startRotation:void 0,nextRotation:void 0,startAngle:void 0},this.setGlobalCursor(s),this.bindDocumentListeners()}}bindDocumentListeners(){var t,i,r,s,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=(s=globalThis.window)==null?void 0:s.addEventListener)==null||a.call(s,"blur",this.boundWindowBlur))}unbindDocumentListeners(){var t,i,r,s,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=(s=globalThis.window)==null?void 0:s.removeEventListener)==null||a.call(s,"blur",this.boundWindowBlur))}handleDocumentPointerMove(e){var s,a,o,l,c,h,d,u;if(!this.interaction||!this.state||this.state.clipId!==this.interaction.clipId)return;const t=e;(s=t.preventDefault)==null||s.call(t);const i=this.toLocalPoint(t);if(this.interaction.mode==="rotate"&&this.interaction.startRotation!==void 0){const g=i.x-this.interaction.centerX,f=i.y-this.interaction.centerY,C=Math.atan2(f,g)*(180/Math.PI)-this.interaction.startAngle,v=Math.round(this.interaction.startRotation+C);this.interaction.nextRotation=v,this.interaction.changed=v!==this.interaction.startRotation,(o=(a=this.callbacks).onRotationChange)==null||o.call(a,this.interaction.clipId,v);return}if(this.interaction.clipType==="text"&&this.interaction.startLayoutWidth!==void 0&&this.interaction.startLayoutHeight!==void 0){const g=ku(i.x,i.y,this.interaction.centerX,this.interaction.centerY,((l=this.state)==null?void 0:l.baselineScale)??1);this.interaction.nextLayoutWidth=g.layoutWidth,this.interaction.nextLayoutHeight=g.layoutHeight,this.interaction.changed=g.layoutWidth!==this.interaction.startLayoutWidth||g.layoutHeight!==this.interaction.startLayoutHeight,(h=(c=this.callbacks).onTextLayoutChange)==null||h.call(c,this.interaction.clipId,g);return}let r=this.interaction.startTransform;if(this.interaction.mode==="move")r=So(this.interaction.startTransform,i.x-this.interaction.pointerStart.x,i.y-this.interaction.pointerStart.y,this.interaction.frameSize);else{const g=this.interaction.startTransform.x*this.interaction.frameSize.width,f=this.interaction.startTransform.y*this.interaction.frameSize.height;r=cu(g,f,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!bs(this.interaction.startTransform,r),(u=(d=this.callbacks).onPreviewTransformChange)==null||u.call(d,this.interaction.clipId,r)}finishInteraction(e){var i,r,s,a,o,l,c,h,d,u,g,f,m,C,v,S;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=(s=this.callbacks).onRotationChange)==null||a.call(s,t.clipId,null)):t.clipType==="text"?t.mode==="move"?(e&&t.changed&&((l=(o=this.callbacks).onPreviewTransformCommit)==null||l.call(o,t.clipId,t.nextTransform)),(h=(c=this.callbacks).onPreviewTransformChange)==null||h.call(c,t.clipId,null)):t.mode==="scale"&&(e&&t.changed&&t.nextLayoutWidth!==void 0&&t.nextLayoutHeight!==void 0&&((u=(d=this.callbacks).onTextLayoutCommit)==null||u.call(d,t.clipId,{layoutWidth:t.nextLayoutWidth,layoutHeight:t.nextLayoutHeight})),(f=(g=this.callbacks).onTextLayoutChange)==null||f.call(g,t.clipId,null)):(e&&t.changed&&((C=(m=this.callbacks).onPreviewTransformCommit)==null||C.call(m,t.clipId,t.nextTransform)),(S=(v=this.callbacks).onPreviewTransformChange)==null||S.call(v,t.clipId,null)),this.interaction=null,this.setGlobalCursor(null),this.unbindDocumentListeners(),this.render()}render(){if(!this.boxElement||!this.state){this.boxElement&&(this.boxElement.style.display="none"),this.rotateHandleElement&&(this.rotateHandleElement.style.display="none");return}const{displayRect:e}=this.state,t=this.state.clipType==="text",i=t?this.textHostElement:null;t&&i?this.renderTextHostHandles(i,e):this.boxElement&&this.renderOverlayBox(this.boxElement,e,t?this.state.currentRotation??0:0),this.renderRotateHandle(e,t)}renderTextHostHandles(e,t){this.boxElement&&(this.boxElement.style.display="none",this.boxElement.style.pointerEvents="none");const i=e.offsetWidth>0?e.offsetWidth:t.width,r=e.offsetHeight>0?e.offsetHeight:t.height;this.mountHandlesOn(e),this.positionHandle("top-left",0,0),this.positionHandle("top-right",i,0),this.positionHandle("bottom-right",i,r),this.positionHandle("bottom-left",0,r)}renderOverlayBox(e,t,i){this.mountHandlesOn(e),e.style.display="block",e.style.pointerEvents="auto",e.style.cursor="grab",e.style.border=`1px solid ${ze.border}`,e.style.left=`${t.left}px`,e.style.top=`${t.top}px`,e.style.width=`${t.width}px`,e.style.height=`${t.height}px`,e.style.transformOrigin="center",e.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)}renderRotateHandle(e,t){var i,r;if(this.rotateHandleElement){if(!t){this.rotateHandleElement.style.display="none";return}if(((i=this.interaction)==null?void 0:i.mode)!=="rotate"){const s=e.left+e.width/2,a=e.top+e.height/2,o=e.height/2+20,c=(((r=this.state)==null?void 0:r.currentRotation)??0)*(Math.PI/180);this.rotateHandleElement.style.left=`${s-o*Math.sin(c)}px`,this.rotateHandleElement.style.top=`${a+o*Math.cos(c)}px`}this.rotateHandleElement.style.display="flex"}}setTextHost(e){this.textHostElement!==e&&(this.textHostElement=e,!e&&this.boxElement&&this.mountHandlesOn(this.boxElement))}mountHandlesOn(e){for(const t of this.handleElements.values())t.parentElement!==e&&e.appendChild(t)}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:Ln(this.frameElement.style.left),top:Ln(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||"")}}class _u{constructor(e){p(this,"container",null);p(this,"statusElement",null);p(this,"actionElement",null);p(this,"onRetry");this.onRetry=e}mount(e){this.container=e,this.container.className="timeline-preview-pending-overlay",this.container.style.position="absolute",this.container.style.top="12px",this.container.style.left="12px",this.container.style.display="none",this.container.style.alignItems="center",this.container.style.justifyContent="flex-start",this.container.style.flexDirection="row",this.container.style.gap="8px",this.container.style.background=Ge.background,this.container.style.color=Ge.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=Ge.actionBackground,i.style.color=Ge.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,s=!!(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=s?Ge.failedBackground:Ge.background,this.container.style.color=s?Ge.failedText:Ge.text,s){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}}function Au(n,e){var u;const t=n.activeClips.filter(g=>g.trackType!=="text"),i=n.nextClips.filter(g=>g.trackType!=="text"),r=n.interactionMode??"steady",s=new Map(t.map(g=>[g.trackId,g])),a=new Map(i.map(g=>[g.trackId,g])),o=new Map,l=t.filter(g=>g.trackType==="video"&&g.hasVisual).sort((g,f)=>g.trackOrder-f.trackOrder),c=l.length>1,h=((u=l[0])==null?void 0:u.trackId)??null,d=(g,f)=>!a.has(g)||r!=="steady"&&c?!1:c?n.playState==="playing"&&f==="video"&&g===h:n.playState!=="playing"||t.length<=1;return e.forEach(g=>{o.set(g.trackId,{kind:g.kind,order:g.order})}),t.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),i.forEach(g=>{o.set(g.trackId,{kind:g.trackType,order:g.trackOrder})}),Array.from(o.entries()).map(([g,f])=>{const m=s.get(g)||null,C=d(g,f.kind)&&a.get(g)||null;return{trackId:g,kind:f.kind,order:f.order,current:{role:"current",entry:m,playState:n.requestedPlayState??n.playState,speed:n.speed,visible:!!(m!=null&&m.hasVisual),zIndex:m?1e3-m.trackOrder:0,syncRequestId:n.syncRequestId},preload:{role:"preload",entry:C,playState:"paused",speed:1,visible:!1,zIndex:0,syncRequestId:n.syncRequestId}}}).sort((g,f)=>g.order-f.order)}function Dn(n,e){return n.entry?e?n.entry.clip.id===e:!0:!1}function Iu(n,e){return e?!Dn(n.current,e.clip.id)&&Dn(n.preload,e.clip.id):!1}function Eu(n){return n.current.role="preload",n.preload.role="current",{current:n.preload,preload:n.current}}const Ru=2,Mu=.5,Lu=750,Du="媒体丢失";function Wi(n){return!!n&&typeof n.then=="function"}function is(n){return n.getAttribute("src")||n.currentSrc||n.src||""}function oi(n){return n.getAttribute("src")||""}function At(n){return typeof HTMLVideoElement<"u"?n instanceof HTMLVideoElement:n.tagName==="VIDEO"}function jt(n){try{n.load()}catch{}}function qt(n){try{n.pause()}catch{}}function rs(n){var e;try{const t=n.play();(e=t==null?void 0:t.catch)==null||e.call(t,()=>{})}catch{}}function On(n,e){try{n.currentTime=Math.max(0,e)}catch{}}function nr(n,e){var i;const t=(i=n==null?void 0:n.clip.style)==null?void 0:i[e];return typeof t=="number"&&t>0?t:null}function Bn(n){if(!n)return 0;const e=Number.parseFloat(n);return Number.isFinite(e)?e:0}function Ou(n){const e=n.buffered;return!e||typeof e.length!="number"||e.length<=0?null:e.end(e.length-1)}function Bu(n){return{tsMs:Date.now(),currentTime:n.currentTime,duration:n.duration,currentSrc:n.currentSrc||n.src||null,readyState:n.readyState,networkState:n.networkState,paused:n.paused,ended:n.ended,playbackRate:n.playbackRate,bufferedEnd:Ou(n),videoWidth:At(n)?n.videoWidth:0,videoHeight:At(n)?n.videoHeight:0,error:n.error?{code:n.error.code,message:n.error.message}:null}}function Fn(n,e,t){return t?n===t||e===t:!1}function ar(n,e){const t=n==="current"?Math.abs(e||1):1;return Math.max(.1,t*.15)}function nt(n){var e;return((e=n.externalId)==null?void 0:e.trim())||n.src}function Fu(n){const e=n==null?void 0:n.trim();return e?`clip:${e}`:null}function ss(n){return typeof n=="string"&&n.startsWith("blob:")}function Hu(n,e){return n||(ss(e)?e:null)}class Gu{constructor(){p(this,"pendingClockAlignmentTargetTime",null)}updateAlignmentTarget(e,t,i){if(!e){this.pendingClockAlignmentTargetTime=null;return}(t==="seek"||t==="scrub")&&(this.pendingClockAlignmentTargetTime=i)}buildClockState(e,t,i){const r=this.getClockSourceSlot(t);if(!(r!=null&&r.entry))return this.buildFromSlot(null,"unavailable","no-video-clock");const s=r.sourceMatchesDesired(),a=this.getMediaTimeMs(r),o=this.getTimelineTime(r,a),l=r.requestedPlayState==="playing"&&!r.element.ended;return e.status==="failed"||r.phase==="failed"?this.buildFromSlot(r,"failed","failed",o,a):l?!s||r.isResolvingSource||r.phase==="binding"?this.buildFromSlot(r,"priming","resolving-source",o,a):r.isSeeking||e.reason==="seeking"?this.buildFromSlot(r,"blocked","seeking",o,a):this.isMediaTimeAligned(r,a)?r.isBuffering||i?this.buildFromSlot(r,"blocked","media-stalled",o,a):this.isTimelineAligned(r,o)?e.status==="loading"?this.buildFromSlot(r,"blocked",this.resolveBlockedReason(e.reason),o,a):r.element.paused?this.buildFromSlot(r,"blocked","media-paused",o,a):o===null||a===null?this.buildFromSlot(r,"priming","media-pending",o,a):(this.pendingClockAlignmentTargetTime=null,this.buildFromSlot(r,"running",null,o,a)):this.buildFromSlot(r,"blocked","seeking",o,a):this.buildFromSlot(r,"blocked","seeking",o,a):this.buildFromSlot(r,"unavailable",null,o,a)}getClockSourceSlot(e){var i,r;const t=[];for(const s of e)s.role!=="current"||!s.isActive||s.kind!=="video"||!((i=s.entry)!=null&&i.hasVisual)||t.push(this.buildCandidate(s));return t.length===0?(this.pendingClockAlignmentTargetTime=null,null):(t.sort((s,a)=>this.compareCandidates(s,a)),((r=t[0])==null?void 0:r.slot)??null)}buildCandidate(e){const t=this.getMediaTimeMs(e),i=this.getTimelineTime(e,t),r=e.sourceMatchesDesired(),s=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=s>=Ru||e.hasReadyEventSinceSourceChange,c=!!e.entry&&r&&l&&!e.isResolvingSource&&e.phase!=="binding"&&e.phase!=="failed"&&!e.isSeeking&&!e.isBuffering&&(!o||!e.element.paused)&&t!==null&&i!==null;return{slot:e,timelineTime:i,targetDistance:a,sourceMatched:r,readyState:s,usable:c}}compareCandidates(e,t){var s,a;const i=this.isCandidateAligned(e),r=this.isCandidateAligned(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:(((s=e.slot.entry)==null?void 0:s.trackOrder)??0)-(((a=t.slot.entry)==null?void 0:a.trackOrder)??0)}isCandidateAligned(e){return this.pendingClockAlignmentTargetTime!==null&&e.usable&&e.targetDistance<=this.getAlignmentThresholdMs(e.slot)}getAlignmentThresholdMs(e){return Math.max(Lu,ar("current",e.element.playbackRate||1)*1e3)}isMediaTimeAligned(e,t){const i=e.pendingClockAlignmentMediaTime;return i===null?!0:t===null||Math.abs(t-i)>this.getAlignmentThresholdMs(e)?!1:(e.pendingClockAlignmentMediaTime=null,!0)}isTimelineAligned(e,t){return this.pendingClockAlignmentTargetTime===null||t===null?!0:Math.abs(t-this.pendingClockAlignmentTargetTime)<=this.getAlignmentThresholdMs(e)}getMediaTimeMs(e){return Number.isFinite(e.element.currentTime)?Math.max(0,e.element.currentTime*1e3):null}getTimelineTime(e,t){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))}buildFromSlot(e,t,i,r=null,s=null){var a;return{status:t,timelineTime:r,mediaTime:s,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}}resolveBlockedReason(e){return e==="syncing"||e==="resolving-source"||e==="seeking"||e==="media-pending"||e==="failed"?e:"media-pending"}}function Nu(n,e){return!kt(n.mode)||!e?n:{mode:Le.mode,width:e.width,height:e.height}}class zu{constructor(e){p(this,"container",null);p(this,"rootElement",null);p(this,"frameElement",null);p(this,"resizeObserver",null);p(this,"onFrameLayoutChange",null);p(this,"requestedAspectRatio",{...Le});p(this,"resolvedAutoAspectRatio",null);p(this,"transformOverlay");this.transformOverlay=e}attach(e,t){if(this.onFrameLayoutChange=t.onFrameLayoutChange??null,this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e,this.onFrameLayoutChange=t.onFrameLayoutChange??null;const i=document.createElement("div");i.className=t.rootClassName??"timeline-preview-root",i.style.position="relative",i.style.width="100%",i.style.height="100%",i.style.overflow="hidden";const r=document.createElement("div");r.className=t.frameClassName??"timeline-preview-frame",r.style.position="absolute",r.style.left="0",r.style.top="0",r.style.overflow="hidden",r.style.background=P.black,i.appendChild(r),e.appendChild(i),this.rootElement=i,this.frameElement=r,this.transformOverlay.attach(r),typeof ResizeObserver<"u"&&(this.resizeObserver=new ResizeObserver(()=>this.updateFrameLayout()),this.resizeObserver.observe(e)),this.updateFrameLayout()}detach(){var e,t;(e=this.resizeObserver)==null||e.disconnect(),this.resizeObserver=null,this.onFrameLayoutChange=null,this.transformOverlay.detach(),(t=this.rootElement)==null||t.remove(),this.rootElement=null,this.frameElement=null,this.container=null,this.resolvedAutoAspectRatio=null}getFrameElement(){return this.frameElement}getRootElement(){return this.rootElement}applyAspectRatio(e){this.requestedAspectRatio=Ue(e),this.updateFrameLayout()}getAspectRatio(){return Nu(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}resolveAutoAspectRatio(e,t,i){e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),i&&kt(this.requestedAspectRatio.mode)&&i(this.getAspectRatio()))}tryResolveAutoAspectRatioFromSlot(e,t){if(!kt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const i=e.element;At(i)&&i.videoWidth>0&&i.videoHeight>0&&this.resolveAutoAspectRatio(i.videoWidth,i.videoHeight,t)}refreshSlotVisual(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=xe(e.entry.clip.visualTransform),s=Mn(t,i,r);e.wrapper.style.left=`${s.left}px`,e.wrapper.style.top=`${s.top}px`,e.wrapper.style.width=`${s.width}px`,e.wrapper.style.height=`${s.height}px`,this.syncFailureVisual(e)}buildSelectedOverlayState(e,t,i,r){var m,C;if(!e)return null;const s=this.getFrameSize();if(s.width<=0||s.height<=0)return null;for(const v of t){if(v.kind!=="video"||!v.isActive||!v.entry||v.entry.clip.id!==e)continue;const S=this.getMediaSize(v,v.entry,s),T=r(v.entry);return{clipId:v.entry.clip.id,transform:T,frameSize:s,baseRect:yo(s,S),displayRect:Mn(s,S,T),clipType:"video"}}const a=i.getEntry(e);if(!a||!this.frameElement)return null;const o=this.getTextBaselineMetrics(s),l=((m=i.getTextLayoutOverride)==null?void 0:m.call(i,e))??null,h=((C=i.getLayout)==null?void 0:C.call(i,e))??null??Io(a.entry,s,o.scale,l),d=ce(a.entry.clip.textStyle),u=h.visualTransform,g=i.getTransientFontSize(e)??d.fontSize,f=i.getTransientRotation(e)??d.rotation;return{clipId:e,transform:u,frameSize:s,baseRect:{left:0,top:0,width:s.width,height:s.height,centerX:s.width/2,centerY:s.height/2},displayRect:h.frameRect,clipType:"text",currentFontSize:g,currentRotation:f,currentLayoutWidth:h.layoutWidth,currentLayoutHeight:h.layoutHeight,textHostElement:a.element,baselineScale:o.scale}}getFrameSize(){var i,r,s,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:Bn((s=this.frameElement)==null?void 0:s.style.width),height:t>0?t:Bn((a=this.frameElement)==null?void 0:a.style.height)}}getTextBaselineMetrics(e){const t=ji(this.getAspectRatio(),os);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)}}moveTransform(e,t,i){return So(e,t,i,this.getFrameSize())}transformsEqual(e,t){return bs(e,t)}updateFrameLayout(){var h;if(!this.container||!this.frameElement)return;const e=this.getAspectRatio(),t=this.container.clientWidth,i=this.container.clientHeight;if(t<=0||i<=0||e.width<=0||e.height<=0)return;const r=t/i,s=e.width/e.height;let a=t,o=i,l=0,c=0;r>s?(a=i*s,l=(t-a)/2):(o=t/s,c=(i-o)/2),this.frameElement.style.width=`${a}px`,this.frameElement.style.height=`${o}px`,this.frameElement.style.left=`${l}px`,this.frameElement.style.top=`${c}px`,(h=this.onFrameLayoutChange)==null||h.call(this)}getMediaSize(e,t,i){if(At(e.element)&&e.element.videoWidth>0&&e.element.videoHeight>0)return{width:e.element.videoWidth,height:e.element.videoHeight};const r=nr(t,"sys_width"),s=nr(t,"sys_height");return r&&s?{width:r,height:s}:{width:i.width,height:i.height}}syncFailureVisual(e){if(!e.wrapper||!e.failureOverlay||!e.failureLabel)return;const t=e.phase==="failed"&&!!e.entry;e.wrapper.style.background=t?P.mediaClipFailedBackground:P.black,e.failureOverlay.style.display=t?"flex":"none",e.failureLabel.textContent=Du,e.element.style.visibility=t?"hidden":"visible"}}const $u=500;class Hn{constructor(e,t,i,r={}){p(this,"trackId");p(this,"kind");p(this,"role");p(this,"element");p(this,"wrapper");p(this,"failureOverlay");p(this,"failureLabel");p(this,"entry",null);p(this,"stableSourceUrl",null);p(this,"boundStableKey",null);p(this,"desiredSource",null);p(this,"objectUrl",null);p(this,"objectUrlHolderId",null);p(this,"requestedPlayState","paused");p(this,"isActive",!1);p(this,"isLoading",!1);p(this,"isResolvingSource",!1);p(this,"isBuffering",!1);p(this,"isSeeking",!1);p(this,"phase","idle");p(this,"errorMessage",null);p(this,"hasReadyEventSinceSourceChange",!1);p(this,"pendingClockAlignmentMediaTime",null);p(this,"sourceGen",0);p(this,"loadSourceGen",0);p(this,"sourceNode",null);p(this,"gainNode",null);p(this,"audioRoutingFailed",!1);p(this,"cleanup",[]);p(this,"lastPlaybackResumeAttemptAtMs",-1);p(this,"options");this.trackId=e,this.kind=t,this.role=i,this.options=r,this.element=this.createMediaElement(t,i),this.wrapper=t==="video"?document.createElement("div"):null,this.failureOverlay=t==="video"?document.createElement("div"):null,this.failureLabel=t==="video"?document.createElement("div"):null,this.setupWrapper(),this.bindMediaEvents()}takeTrackedObjectUrl(){const e={url:this.objectUrl,holderId:this.objectUrlHolderId};return this.objectUrl=null,this.objectUrlHolderId=null,e}mountVideoTo(e){this.wrapper&&e.appendChild(this.wrapper)}mountAudioTo(e){this.kind==="audio"&&e.appendChild(this.element)}clear(){this.sourceGen+=1,qt(this.element),this.entry=null,this.desiredSource=null,this.stableSourceUrl=null,this.boundStableKey=null,this.pendingClockAlignmentMediaTime=null,this.hasReadyEventSinceSourceChange=!1,this.isActive=!1,this.isLoading=!1,this.isResolvingSource=!1,this.isBuffering=!1,this.isSeeking=!1,this.errorMessage=null,this.phase="idle",this.element.removeAttribute("src"),jt(this.element),this.setVisible(!1,0)}fail(e){var t,i;if(this.role==="preload"){this.clear();return}this.phase="failed",this.errorMessage=e,this.isLoading=!1,this.isResolvingSource=!1,this.isSeeking=!1,this.isBuffering=!1,(i=(t=this.options).onStateChange)==null||i.call(t)}clearFailureIfClipChanged(){this.phase==="failed"&&(this.phase="binding",this.errorMessage=null)}assignSource(e,t){var o,l;const i=oi(this.element),r=is(this.element),s=!i&&!!e.url,a=this.boundStableKey!==t||s||!Fn(i,r,e.url);return a?(this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url,this.loadSourceGen=this.sourceGen,this.hasReadyEventSinceSourceChange=!1,this.element.setAttribute("src",e.url),jt(this.element),(l=(o=this.options).onDiagnostic)==null||l.call(o,"source.assigned",this,{playbackUrl:e.url,stableKey:t})):!i&&e.url?(this.element.setAttribute("src",e.url),jt(this.element),this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url,this.loadSourceGen=this.sourceGen):(this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url),a}applyPlayback(e,t,i,r,s){var a,o;this.entry=e,this.requestedPlayState=t,this.isActive=this.role==="current",this.element.playbackRate=this.role==="current"?i:1,this.role==="current"?this.syncCurrentPlayback(e,t,i):this.preparePreload(e),!this.isLoading&&!this.isSeeking&&this.phase!=="failed"&&((this.element.readyState??0)>=2&&this.sourceMatchesDesired()?(this.phase=this.isActive?"active":"primed",this.isLoading=!1):this.isLoading||(this.phase=this.isActive?"active":"primed")),this.setVisible(r,s),(o=(a=this.options).onStateChange)==null||o.call(a)}sourceMatchesDesired(){return Fn(oi(this.element),is(this.element),this.desiredSource)}maybeResumePlayback(e){if(this.role!=="current"||!this.isActive||!this.entry||this.requestedPlayState!=="playing"||this.element.paused!==!0||this.phase==="failed"||!oi(this.element))return;const t=Date.now();e==="runtime-check"&&(this.lastPlaybackResumeAttemptAtMs>=0&&t-this.lastPlaybackResumeAttemptAtMs<$u||this.isBuffering||this.isSeeking)||(this.lastPlaybackResumeAttemptAtMs=t,rs(this.element))}destroy(e){var r,s,a,o,l;this.sourceGen+=1,this.cleanup.forEach(c=>c()),this.cleanup=[],qt(this.element);const{url:t,holderId:i}=this.takeTrackedObjectUrl();this.desiredSource=null,this.element.removeAttribute("src"),jt(this.element),e(t,i),(s=(r=this.gainNode)==null?void 0:r.disconnect)==null||s.call(r),(o=(a=this.sourceNode)==null?void 0:a.disconnect)==null||o.call(a),(l=this.wrapper)==null||l.remove(),this.element.remove()}syncCurrentPlayback(e,t,i){const r=e.mediaTime/1e3,s=t==="playing"?Math.max(Mu,i*.15):ar("current",i),a=t==="playing"&&!this.element.ended;Math.abs(this.element.currentTime-r)>s&&(this.isSeeking=!0,On(this.element,r)),a?this.element.paused&&rs(this.element):qt(this.element)}preparePreload(e){const t=e.mediaTime/1e3;qt(this.element),Math.abs(this.element.currentTime-t)>ar("preload",1)&&On(this.element,t)}setVisible(e,t){this.wrapper&&(this.wrapper.style.display=e?"block":"none",this.wrapper.style.zIndex=String(t),At(this.element)&&(this.element.style.display=e?"block":"none",this.element.style.zIndex=String(t)))}createMediaElement(e,t){const i=this.options.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,At(r)?(hs(r),r.playsInline=!0,r.style.position="absolute",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.objectFit="contain",r.style.background=P.black,r.style.pointerEvents="none"):r.style.display="none",r}setupWrapper(){if(!this.wrapper||!this.failureOverlay||!this.failureLabel)return;const e=this.options.slotClassNamePrefix??"timeline-preview-slot";this.wrapper.className=`${e} timeline-preview-slot--${this.trackId} timeline-preview-slot--${this.role}`,this.wrapper.style.position="absolute",this.wrapper.style.overflow="hidden",this.wrapper.style.background=P.black,this.wrapper.style.display="none",this.failureOverlay.className="timeline-preview-slot__failure",this.failureOverlay.style.inset="0",this.failureOverlay.style.display="none",this.failureOverlay.style.alignItems="center",this.failureOverlay.style.justifyContent="center",this.failureOverlay.style.background="rgba(80, 0, 0, 0.72)",this.failureLabel.className="timeline-preview-slot__failure-label",this.failureOverlay.style.position="absolute",this.failureLabel.style.fontSize="14px",this.failureOverlay.appendChild(this.failureLabel),this.wrapper.appendChild(this.failureOverlay),this.wrapper.appendChild(this.element)}bindMediaEvents(){const e=d=>()=>{this.entry&&d()},t=e(()=>{var d,u,g,f;this.isLoading=!0,this.phase!=="failed"&&(this.phase="binding"),(u=(d=this.options).onDiagnostic)==null||u.call(d,"media.loadstart",this),(f=(g=this.options).onStateChange)==null||f.call(g)}),i=e(()=>{var d,u;this.hasReadyEventSinceSourceChange=!0,this.isBuffering=!1,this.isLoading=!1,this.isResolvingSource=!1,this.maybeResumePlayback("canplay"),(u=(d=this.options).onStateChange)==null||u.call(d)}),r=e(()=>{var d,u;this.hasReadyEventSinceSourceChange=!0,this.isBuffering=!1,this.isLoading=!1,(u=(d=this.options).onStateChange)==null||u.call(d)}),s=e(()=>{var d,u,g,f;this.isBuffering=this.role==="current"&&this.isActive&&this.requestedPlayState==="playing",(u=(d=this.options).onDiagnostic)==null||u.call(d,"media.stalled",this),(f=(g=this.options).onStateChange)==null||f.call(g)}),a=e(()=>{var d,u,g,f;this.isBuffering=this.role==="current"&&this.isActive&&this.requestedPlayState==="playing",(u=(d=this.options).onDiagnostic)==null||u.call(d,"media.waiting",this),(f=(g=this.options).onStateChange)==null||f.call(g)}),o=e(()=>{var d,u;this.isSeeking=!0,(u=(d=this.options).onStateChange)==null||u.call(d)}),l=e(()=>{var d,u;this.isSeeking=!1,this.hasReadyEventSinceSourceChange=!0,this.maybeResumePlayback("seeked"),(u=(d=this.options).onStateChange)==null||u.call(d)}),c=e(()=>{var u,g,f,m,C;if(!this.desiredSource||!this.sourceMatchesDesired()||this.loadSourceGen!==this.sourceGen)return;const d=((u=this.element.error)==null?void 0:u.message)||"媒体播放失败";(f=(g=this.options).onMediaError)==null||f.call(g,this,d),(C=(m=this.options).onDiagnostic)==null||C.call(m,"media.error",this,{mediaState:Bu(this.element)})});[["loadstart",t],["canplay",i],["playing",r],["stalled",s],["waiting",a],["seeking",o],["seeked",l],["error",c]].forEach(([d,u])=>{this.element.addEventListener(d,u),this.cleanup.push(()=>this.element.removeEventListener(d,u))})}}function Vu(n,e){if(!e||!n.entry)return{failed:!1,resolving:!1,seeking:!1,mediaUnready:!1,ready:!1};const t=n.sourceMatchesDesired(),i=n.element.readyState??0,r=n.entry.mediaTime/1e3,s=Number.isFinite(n.element.currentTime)?n.element.currentTime:Number.NaN,a=ar("current",n.element.playbackRate||1),o=Number.isFinite(s)&&Math.abs(s-r)<=a,l=!!n.isSeeking&&!o,c=n.isResolvingSource,h=n.phase==="failed",d=!h&&!c&&!!n.desiredSource&&t&&!l&&i>=2&&(n.hasReadyEventSinceSourceChange||i>=2),u=n.requestedPlayState==="playing"&&!n.element.ended,g=d&&(!u||!n.element.paused),f=!g&&!h&&(!n.desiredSource||!t||n.phase==="binding"||i<2||n.isBuffering);return n.isSeeking=l,g&&(n.isLoading=!1,n.isBuffering=!1,n.phase!=="failed"&&(n.phase="active")),{failed:h,resolving:c,seeking:l,mediaUnready:f,ready:g}}class Uu{constructor(){p(this,"lastSignature",null);p(this,"lastState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});p(this,"lastSettledSyncRequestId",null)}getLastState(){return this.lastState}publish(e,t,i){var v;const r=[];let s=null,a=!1,o=0,l=0,c=!1,h=!1,d=!1,u=!1;for(const S of e.slots){const T=e.isTrackedVideo(S),k=T?e.evaluateTracked(S):null;r.push({trackId:S.trackId,role:S.role,kind:S.kind,clipId:((v=S.entry)==null?void 0:v.clip.id)??null,desiredSource:S.desiredSource,actualSource:is(S.element)||null,phase:S.phase,retryCount:0,errorMessage:S.errorMessage}),S.phase!=="idle"&&(a=!0),T&&(o+=1,k!=null&&k.failed&&(l+=1,c=!0,s||(s=S.errorMessage||"资源加载异常,请刷新重试")),k!=null&&k.resolving&&(h=!0),k!=null&&k.seeking&&(d=!0),k!=null&&k.mediaUnready&&(u=!0))}const g=this.buildLoadingState({trackedCount:o,failedTrackedCount:l,hasFailed:c,hasResolving:h,hasSeeking:d,hasMediaUnready:u,isSyncProjecting:e.isSyncProjecting,activeSyncRequestId:e.activeSyncRequestId});let f="idle";g.status==="failed"?f="failed":g.status==="loading"&&g.reason==="syncing"?f="awaiting-sync":g.status==="loading"?f="awaiting-media":(o>0&&g.status==="ready"||a)&&(f="ready"),g.status!=="failed"&&(s=null);const m={...e.activeSyncRequestId!==void 0?{syncRequestId:e.activeSyncRequestId}:{},phase:f,loading:g,clock:e.clock,errorMessage:s,slots:r},C=JSON.stringify(m);return C!==this.lastSignature&&(this.lastSignature=C,this.lastState=m,t(m)),(g.status==="ready"||g.status==="failed"||g.status==="idle")&&m.syncRequestId!==void 0&&this.lastSettledSyncRequestId!==m.syncRequestId&&(this.lastSettledSyncRequestId=m.syncRequestId,i==null||i(m.syncRequestId)),m}reset(){this.lastSignature=null,this.lastSettledSyncRequestId=null,this.lastState={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:[]}}buildLoadingState(e){return e.trackedCount<=0?{status:"idle",isLoading:!1,reason:null}:e.hasFailed&&e.failedTrackedCount>=e.trackedCount?{status:"failed",isLoading:!1,reason:"failed"}:e.activeSyncRequestId!==void 0&&e.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:e.hasResolving?{status:"loading",isLoading:!0,reason:"resolving-source"}:e.hasSeeking?{status:"loading",isLoading:!0,reason:"seeking"}:e.hasMediaUnready?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}}class Wu{constructor(e){p(this,"syncGen",0);p(this,"pendingAsyncCount",0);p(this,"options");this.options=e}get isProjecting(){return this.pendingAsyncCount>0}applyTrackPlan(e){const t=this.options.getTrackSlots(e.trackId,e.kind),i=this.applySlotTarget(t.current,e.current),r=this.applySlotTarget(t.preload,e.preload);if(Wi(i)||Wi(r))return this.beginAsyncWork(),Promise.all([Promise.resolve(i),Promise.resolve(r)]).finally(()=>{this.endAsyncWork()}).then(()=>{})}bumpSyncGeneration(){return this.syncGen+=1,this.syncGen}applySlotTarget(e,t){const i=e.entry,r=i?nt(i.clip):null,s=!!i&&!!t.entry&&i.clip.id!==t.entry.clip.id;if(s&&e.clearFailureIfClipChanged(),e.entry=t.entry,e.requestedPlayState=t.playState,e.isActive=t.role==="current"&&!!t.entry,this.options.syncClockAlignment(e,t,s),!t.entry){const{url:d,holderId:u}=e.takeTrackedObjectUrl();e.clear(),this.options.releaseObjectUrl(d,u),this.options.onStateChange();return}const a=nt(t.entry.clip),o=this.options.sourceService.getReusableSource(e.boundStableKey,e.stableSourceUrl,e.desiredSource,e.objectUrl,t.entry);e.desiredSource&&!oi(e.element)&&(e.element.setAttribute("src",e.desiredSource),jt(e.element)),(r&&r!==a||!o&&s)&&(e.sourceGen+=1);const l=e.sourceGen,c=this.options.sourceService.resolve(t.entry,{sourceGen:l,getCurrentSourceGen:()=>e.sourceGen,reuse:o}),h=d=>{const u=e.sourceGen!==l,g=!this.options.isCurrentTarget(e,t.entry,a);if(!(!d||u||g)){if(e.isResolvingSource=!1,!oi(e.element)&&!d.url){e.fail("未找到可用预览源");return}if(e.phase==="failed"&&e.errorMessage){this.options.onStateChange();return}e.assignSource(d,a),this.options.rememberObjectUrl(e,Hu(d.objectUrl,d.url)),e.phase==="binding"&&e.sourceMatchesDesired()&&(e.phase=e.isActive?"active":"primed",e.isLoading=!1,e.isBuffering=!1),this.options.configureAudio(e,t.entry),e.applyPlayback(t.entry,t.playState,t.speed,t.visible,t.zIndex),this.options.onStateChange()}};if(Wi(c))return o||(e.isResolvingSource=!0,e.phase="binding",e.isLoading=!0,this.options.onStateChange()),c.then(d=>{if(!d){if(e.sourceGen!==l||!this.options.isCurrentTarget(e,t.entry,a))return;e.role==="current"?e.fail("未找到可用预览源"):e.clear(),this.options.onStateChange();return}h(d)});if(!c){e.role==="current"&&e.fail("未找到可用预览源"),this.options.onStateChange();return}h(c)}beginAsyncWork(){this.pendingAsyncCount+=1,this.options.onAsyncWorkStarted()}endAsyncWork(){this.pendingAsyncCount=Math.max(0,this.pendingAsyncCount-1),this.pendingAsyncCount===0&&this.options.onAsyncWorkFinished()}}function Kt(n){return n.role==="current"&&n.isActive&&n.kind==="video"&&!!n.entry}function Gn(n){const e=Kt(n),t=Vu(n,e);return e&&n.requestedPlayState==="playing"&&n.maybeResumePlayback("runtime-check"),t}const Yu={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function Xu(n){var e,t;try{const i=typeof location<"u"?location.href:"http://localhost/";return((e=new URL(n,i).pathname.split(".").pop())==null?void 0:e.toLowerCase())??""}catch{return((t=(n.split(/[?#]/,1)[0]??"").split(".").pop())==null?void 0:t.toLowerCase())??""}}function ju(n){const e=Xu(n.src);if(e==="mp4")return{url:n.src,mimeType:"video/mp4",kind:"mp4"};if(e==="m3u8")return{url:n.src,mimeType:"application/vnd.apple.mpegurl",kind:"hls-fmp4"};const t=Yu[e];return t?{url:n.src,mimeType:t,kind:"audio"}:null}class qu{constructor(e={}){p(this,"dependencies");p(this,"pendingCacheRuntime",new Map);this.dependencies=e}resolve(e,t){if(t.reuse)return t.reuse;const i=this.dependencies.previewSourceResolver??ju,r=this.dependencies.sourceMediaRegistry,s=nt(e.clip);try{const a=r?r.getPreviewSource(s,()=>i(e.clip)):i(e.clip);return Wi(a)?a.then(o=>t.getCurrentSourceGen()!==t.sourceGen?null:o?(this.emit("source.resolve.resolved",{clipId:e.clip.id,sourceUrl:e.clip.src,desiredSourceUrl:o.url}),this.resolvePlayable(e,o,t.getCurrentSourceGen,t.sourceGen)):(this.emit("source.resolve.missing",{clipId:e.clip.id,sourceUrl:e.clip.src}),null)).catch(o=>(this.emit("source.resolve.failed",{clipId:e.clip.id,sourceUrl:e.clip.src,error:o}),N.warn("PreviewSourceService","preview source resolver failed",{clipId:e.clip.id,error:o}),null)):a?(this.emit("source.resolve.resolved",{clipId:e.clip.id,sourceUrl:e.clip.src,desiredSourceUrl:a.url}),this.resolvePlayable(e,a,t.getCurrentSourceGen,t.sourceGen)):(this.emit("source.resolve.missing",{clipId:e.clip.id,sourceUrl:e.clip.src}),null)}catch(a){return this.emit("source.resolve.failed",{clipId:e.clip.id,sourceUrl:e.clip.src,error:a}),null}}getReusableSource(e,t,i,r,s){const a=nt(s.clip);if(!e||e!==a||!t||!i)return null;const o=r??(i.startsWith("blob:")?i:null);return{stableSourceUrl:t,url:i,objectUrl:o,sizeBytes:null}}resolvePlayable(e,t,i,r){const s={url:t.url,mimeType:t.mimeType,kind:t.kind},a=this.dependencies.resourceCacheManager;if(!a)return{stableSourceUrl:s.url,url:s.url,objectUrl:null,sizeBytes:null};const o=nt(e.clip),l=`${o}:${s.url}:${e.clip.id}`;let c=this.pendingCacheRuntime.get(l);return c||(c=a.resolvePlayableUrl({url:s.url,mimeType:s.mimeType,kind:s.kind,sourceKey:o}),this.pendingCacheRuntime.set(l,c),c.finally(()=>{this.pendingCacheRuntime.get(l)===c&&this.pendingCacheRuntime.delete(l)})),c.then(h=>this.normalizeCachedResult(s.url,h,i,r)).catch(()=>i()!==r?null:{stableSourceUrl:s.url,url:s.url,objectUrl:null,sizeBytes:null})}normalizeCachedResult(e,t,i,r){return i()!==r?null:t!=null&&t.url?{stableSourceUrl:e,url:t.url,objectUrl:t.url.startsWith("blob:")?t.url:null,sizeBytes:null}:{stableSourceUrl:e,url:e,objectUrl:null,sizeBytes:null}}emit(e,t){var i,r;(r=(i=this.dependencies).onDiagnostic)==null||r.call(i,e,t)}}const Ku=1.35;function Zu(n,e){const t=Math.max(0,Math.round(n));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let s=-t;s<=t;s+=1)s===0&&r===0||i.push(`${s}px ${r}px 0 ${e}`);return i.join(", ")}function Mo(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _r(n){return`"${Mo(n)}"`}function Nn(n){return n.clip.textContent||n.clip.name||""}function Ju(){const n=document.createElement("div");n.className="timeline-preview-text-box",n.style.position="absolute",n.style.boxSizing="border-box",n.style.overflow="visible",n.style.pointerEvents="auto",n.style.userSelect="none";const e=document.createElement("div");return e.className="timeline-preview-text-content",e.style.position="relative",e.style.zIndex="0",e.style.display="block",e.style.width="100%",e.style.height="auto",e.style.minHeight="0",e.style.textAlign="center",e.style.whiteSpace="pre-wrap",e.style.overflowWrap="break-word",e.style.overflow="visible",e.style.boxSizing="border-box",n.appendChild(e),{boxElement:n,contentElement:e}}const Ar="Arial, sans-serif";class Qu{constructor(e,t){p(this,"overlayRoot",null);p(this,"entries",new Map);p(this,"fontStyleElement",null);p(this,"fontSignature",null);p(this,"fontLoadState","idle");p(this,"fontLoadToken",0);p(this,"primarySelectedClipId",null);p(this,"textPreviewFont",null);p(this,"compositor");p(this,"callbacks");p(this,"autoRemeasureScheduled",!1);this.compositor=e,this.callbacks=t}mount(e){const t=document.createElement("div");return t.className="timeline-preview-text-layer",t.style.position="absolute",t.style.inset="0",t.style.pointerEvents="none",t.style.zIndex="2000",e.appendChild(t),this.overlayRoot=t,t}destroy(){this.clearEntries(),this.resetFontState(),this.overlayRoot=null}setPrimarySelectedClipId(e){this.primarySelectedClipId=e,this.refreshInteractionState()}setTextPreviewFont(e){this.textPreviewFont=e,this.ensureFontReady()}syncEntries(e,t,i){var a;this.ensureFontReady();const r=e.filter(o=>!o.muted&&o.hasVisual).sort((o,l)=>o.trackOrder-l.trackOrder),s=new Set(r.map(o=>o.clip.id));for(const o of this.entries.keys())s.has(o)||this.removeEntry(o);for(const o of r){const l=this.entries.get(o.clip.id);if(l){l.entry=o;continue}const{boxElement:c,contentElement:h}=Ju(),d=this.createPointerDownHandler(o.clip.id);c.addEventListener("pointerdown",d),(a=this.overlayRoot)==null||a.appendChild(c),this.entries.set(o.clip.id,{entry:o,boxElement:c,contentElement:h,handlePointerDown:d,lastLayout:null})}this.refreshLayout(t,i),this.refreshInteractionState()}refreshLayout(e,t){var a;const i=this.compositor.getFrameSize();if(i.width<=0||i.height<=0)return;const r=this.resolveBaselineScale(),s=(t==null?void 0:t.resolveVisualTransform)??e;for(const o of this.entries.values()){const l=((a=t==null?void 0:t.getStyleOverride)==null?void 0:a.call(t,o.entry))??null,c=Ao({frameSize:i,baselineScale:r,visualTransform:s(o.entry),textStyle:ce(o.entry.clip.textStyle),contentText:Nn(o.entry),styleOverride:l});o.lastLayout=c,this.applyBoxLayout(o,c,l),this.applyContent(o,r,l),o.lastLayout=this.finalizeTextBoxLayout(o,o.lastLayout,r,l),this.usesManualTextLayout(o,l)&&this.emitResolvedLayout(o,l)}this.scheduleAutoRemeasure(t)}getEntry(e){const t=this.entries.get(e);if(t)return{entry:t.entry,element:t.boxElement,layout:t.lastLayout}}getLayout(e){var t;return((t=this.entries.get(e))==null?void 0:t.lastLayout)??null}resolveBaselineScale(){const e=this.compositor.getFrameSize();return e.width<=0||e.height<=0?1:this.compositor.getTextBaselineMetrics(e).scale}reapplyAllContent(){const e=this.resolveBaselineScale();for(const t of this.entries.values())this.applyContent(t,e,null),t.lastLayout&&(t.lastLayout=this.finalizeTextBoxLayout(t,t.lastLayout,e,null))}applyBoxLayout(e,t,i){const r=ce(e.entry.clip.textStyle),s=(i==null?void 0:i.rotation)??r.rotation,{frameRect:a}=t,o=!this.usesManualTextLayout(e,i);e.boxElement.style.left=`${a.centerX}px`,e.boxElement.style.top=`${a.centerY}px`,e.boxElement.style.width=`${a.width}px`,e.boxElement.style.height=o?"auto":`${a.height}px`,e.boxElement.style.transformOrigin="center center",e.boxElement.style.transform=["translate(-50%, -50%)",`rotate(${s}deg)`].join(" ")}applyContent(e,t,i){const r=ce(e.entry.clip.textStyle),s=(i==null?void 0:i.fontSize)??r.fontSize,a=To(s,r.paddingX,r.strokeWidth,t);e.contentElement.textContent=Nn(e.entry),e.contentElement.style.color=r.color,e.contentElement.style.fontFamily=this.getFontFamily(),e.contentElement.style.fontSize=`${a.fontSize}px`,e.contentElement.style.lineHeight=String(Ku),e.contentElement.style.padding=`0 ${a.paddingX}px`,e.contentElement.style.textShadow=Zu(a.strokeWidth,r.strokeColor),e.boxElement.style.zIndex=String(2e3-e.entry.trackOrder)}usesManualTextLayout(e,t){return(t==null?void 0:t.layoutHeight)!==void 0?!0:_o(ce(e.entry.clip.textStyle))}emitResolvedLayout(e,t){var s,a;if(!e.lastLayout)return;const i=this.compositor.getFrameSize();if(i.width<=0||i.height<=0)return;const r=this.compositor.getTextBaselineMetrics(i);(a=(s=this.callbacks).onTextLayoutResolved)==null||a.call(s,e.entry.clip.id,Ro({frameSize:i,composition:{width:r.width,height:r.height},lastLayout:e.lastLayout,layoutMode:this.usesManualTextLayout(e,t)?"manual":"auto"}))}finalizeTextBoxLayout(e,t,i,r){return this.usesManualTextLayout(e,r)?this.applyManualTextBoxLayout(e,t):this.applyAutoTextBoxLayout(e,t,i)}applyManualTextBoxLayout(e,t){return e.boxElement.style.height=`${t.frameRect.height}px`,e.boxElement.style.overflow="hidden",e.contentElement.style.overflow="hidden",t}applyAutoTextBoxLayout(e,t,i){const r=this.compositor.getFrameSize(),s=ce(e.entry.clip.textStyle),a=qe(e.entry.clip.visualTransform);e.boxElement.style.width=`${t.frameRect.width}px`,e.boxElement.style.height="auto",e.boxElement.style.overflow="visible",e.contentElement.style.overflow="visible",e.contentElement.style.textOverflow="clip";const o=Math.max(e.boxElement.offsetHeight,e.contentElement.offsetHeight,e.contentElement.scrollHeight,1),l=Eo({layout:t,frameSize:r,baselineScale:i,visualTransform:a,textStyle:s,measuredHeightPx:o});return e.boxElement.style.left=`${l.frameRect.centerX}px`,e.boxElement.style.top=`${l.frameRect.centerY}px`,l}scheduleAutoRemeasure(e){if(this.autoRemeasureScheduled||!Array.from(this.entries.values()).some(r=>{var a;const s=((a=e==null?void 0:e.getStyleOverride)==null?void 0:a.call(e,r.entry))??null;return!this.usesManualTextLayout(r,s)}))return;this.autoRemeasureScheduled=!0;const i=()=>{var a,o,l;this.autoRemeasureScheduled=!1;const r=this.compositor.getFrameSize();if(r.width<=0||r.height<=0)return;const s=this.resolveBaselineScale();for(const c of this.entries.values()){const h=((a=e==null?void 0:e.getStyleOverride)==null?void 0:a.call(e,c.entry))??null;this.usesManualTextLayout(c,h)||!c.lastLayout||(c.lastLayout=this.applyAutoTextBoxLayout(c,c.lastLayout,s),this.emitResolvedLayout(c,h))}(l=(o=this.callbacks).onAutoLayoutUpdated)==null||l.call(o)};typeof requestAnimationFrame=="function"?requestAnimationFrame(i):i()}getFontFamily(){const e=this.textPreviewFont;return e!=null&&e.fontName&&this.fontLoadState==="loaded"?`${_r(e.fontName)}, ${Ar}`:Ar}ensureFontReady(){var a,o,l;const e=this.textPreviewFont;if(!(e!=null&&e.fontSourceUrl)||!e.fontName)return;const t=`${e.fontName}:${e.fontSourceUrl}`;if(this.fontSignature===t&&this.fontLoadState==="loaded"||this.fontLoadState==="loading"&&this.fontSignature===t)return;this.fontSignature=t,this.fontLoadState="loading";const i=++this.fontLoadToken,r=document.createElement("style");r.textContent=`@font-face { font-family: ${_r(e.fontName)}; src: url("${Mo(e.fontSourceUrl)}"); }`,document.head.appendChild(r),(a=this.fontStyleElement)==null||a.remove(),this.fontStyleElement=r;const s=this.compositor.getRootElement();s&&s.appendChild(r),(l=(o=document.fonts)==null?void 0:o.load)==null||l.call(o,`1em ${_r(e.fontName)}`).then(()=>{i===this.fontLoadToken&&(this.fontLoadState="loaded",this.reapplyAllContent())}).catch(c=>{i===this.fontLoadToken&&(this.fontLoadState="failed",N.warn("PreviewTextLayer","Failed to load text preview font",{error:c}),this.reapplyAllContent())})}resetFontState(){var e;this.fontLoadToken+=1,this.fontLoadState="idle",this.fontSignature=null,(e=this.fontStyleElement)==null||e.remove(),this.fontStyleElement=null}clearEntries(){for(const e of Array.from(this.entries.keys()))this.removeEntry(e)}removeEntry(e){const t=this.entries.get(e);t&&(t.boxElement.removeEventListener("pointerdown",t.handlePointerDown),t.boxElement.remove(),this.entries.delete(e))}createPointerDownHandler(e){return t=>{var r,s,a,o,l,c,h,d,u;const i=t;if((i.button??0)===0){if(this.primarySelectedClipId===e){(r=i.preventDefault)==null||r.call(i),(a=(s=this.callbacks).onSelectedTextPointerDown)==null||a.call(s,e,t);return}(o=i.preventDefault)==null||o.call(i),(l=i.stopPropagation)==null||l.call(i),this.callbacks.lastSyncedPlayState()==="playing"&&((h=(c=this.callbacks).onPauseIfPlaying)==null||h.call(c)),(u=(d=this.callbacks).onPreviewClipSelect)==null||u.call(d,e)}}}refreshInteractionState(){for(const e of this.entries.values()){const t=e.entry.clip.id===this.primarySelectedClipId;e.boxElement.style.cursor=t?"grab":"pointer",e.boxElement.style.border=t?`1px solid ${ze.border}`:"1px solid transparent"}}}const ep=250,tp=100;class ip{constructor(e={},t={}){p(this,"container",null);p(this,"pendingOverlayElement",null);p(this,"pendingOverlayRenderer");p(this,"compositor");p(this,"textLayer");p(this,"sourceService");p(this,"syncCoordinator");p(this,"clockAggregator",new Gu);p(this,"runtimePublisher",new Uu);p(this,"trackSlots",new Map);p(this,"callbacks");p(this,"dependencies");p(this,"audioContext",null);p(this,"masterGainNode",null);p(this,"loadingProbeTimeoutId",null);p(this,"clockProbeTimeoutId",null);p(this,"playbackGroupSuspended",!1);p(this,"primarySelectedClipId",null);p(this,"transientVisualTransform",null);p(this,"transientFontSize",null);p(this,"transientTextLayout",null);p(this,"transientRotation",null);p(this,"pendingState",null);p(this,"activeSyncRequestId");p(this,"isSyncProjecting",!1);p(this,"lastSyncedPlayState","paused");p(this,"aspectRatioProbe",null);p(this,"aspectRatioProbeSrc",null);p(this,"releaseTrackedObjectUrl",(e,t)=>{const i=this.dependencies.resourceCacheManager;!i||!ss(e)||!t||i.releaseObjectUrl(e,t)});this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new _u(()=>{var r,s;(s=(r=this.callbacks).onPendingPreviewRetry)==null||s.call(r)});const i=new Pu({onPreviewTransformChange:(r,s)=>this.handlePreviewTransformChange(r,s),onPreviewTransformCommit:(r,s)=>{var a,o;(o=(a=this.callbacks).onVisualTransformCommit)==null||o.call(a,r,s)},onFontSizeChange:(r,s)=>{s===null?this.transientFontSize=null:this.transientFontSize={clipId:r,fontSize:s},this.refreshVisualLayout()},onFontSizeCommit:(r,s)=>{var a,o;(o=(a=this.callbacks).onTextFontSizeCommit)==null||o.call(a,r,s)},onRotationChange:(r,s)=>{s===null?this.transientRotation=null:this.transientRotation={clipId:r,rotation:s},this.refreshVisualLayout()},onRotationCommit:(r,s)=>{var a,o;(o=(a=this.callbacks).onTextRotationCommit)==null||o.call(a,r,s)},onTextLayoutChange:(r,s)=>{s===null?this.transientTextLayout=null:this.transientTextLayout={clipId:r,...s},this.refreshVisualLayout()},onTextLayoutCommit:(r,s)=>{var a,o;this.transientTextLayout=null,(o=(a=this.callbacks).onTextLayoutCommit)==null||o.call(a,r,s)},onTextTransformInteractionStart:()=>{var r,s;this.lastSyncedPlayState==="playing"&&((s=(r=this.callbacks).onPauseIfPlaying)==null||s.call(r))}});this.compositor=new zu(i),this.textLayer=new Qu(this.compositor,{onPreviewClipSelect:r=>{var s,a;return(a=(s=this.callbacks).onPreviewClipSelect)==null?void 0:a.call(s,r)},onSelectedTextPointerDown:(r,s)=>{this.primarySelectedClipId===r&&this.compositor.transformOverlay.handleTextHostPointerDown(s)},onPauseIfPlaying:()=>{var r,s;return(s=(r=this.callbacks).onPauseIfPlaying)==null?void 0:s.call(r)},onAutoLayoutUpdated:()=>this.refreshTextSelectionOverlay(),onTextLayoutResolved:(r,s)=>{var a,o;return(o=(a=this.callbacks).onTextLayoutResolved)==null?void 0:o.call(a,r,s)},lastSyncedPlayState:()=>this.lastSyncedPlayState}),this.textLayer.setTextPreviewFont(t.textPreviewFont??null),this.sourceService=new qu({previewSourceResolver:t.previewSourceResolver,sourceMediaRegistry:t.sourceMediaRegistry,resourceCacheManager:t.resourceCacheManager,onDiagnostic:(r,s)=>this.emitDiagnostic("info","resource",r,{extra:s})}),this.syncCoordinator=new Wu({sourceService:this.sourceService,getTrackSlots:(r,s)=>this.getTrackSlots(r,s),onAsyncWorkStarted:()=>{this.isSyncProjecting=!0,this.refreshRuntimeState()},onAsyncWorkFinished:()=>{this.isSyncProjecting=!1,this.refreshVisualLayout(),this.refreshRuntimeState()},onStateChange:()=>this.refreshRuntimeState(),releaseObjectUrl:this.releaseTrackedObjectUrl,rememberObjectUrl:(r,s)=>this.rememberSlotObjectUrl(r,s),configureAudio:(r,s)=>this.configureAudioRouting(r,s),syncClockAlignment:(r,s,a)=>{if(s.role!=="current"||!s.entry){r.pendingClockAlignmentMediaTime=null;return}(a||r.pendingClockAlignmentMediaTime!==null)&&(r.pendingClockAlignmentMediaTime=s.entry.mediaTime)},isCurrentTarget:(r,s,a)=>!!r.entry&&r.entry.clip.id===s.clip.id&&(r.boundStableKey===a||nt(r.entry.clip)===a)})}hasPreview(){return!!this.container}attach(e){this.compositor.attach(e,{rootClassName:this.dependencies.rootClassName,frameClassName:this.dependencies.frameClassName,onFrameLayoutChange:()=>this.refreshVisualLayout()}),this.container=e;const t=this.compositor.getRootElement(),i=this.compositor.getFrameElement();if(!t||!i)return;this.textLayer.mount(i);for(const{current:s,preload:a}of this.trackSlots.values())s.mountVideoTo(i),a.mountVideoTo(i),s.mountAudioTo(t),a.mountAudioTo(t);const r=document.createElement("div");t.appendChild(r),this.pendingOverlayElement=r,this.pendingOverlayRenderer.mount(r),this.emitDiagnostic("info","session","preview.attach",{message:"Preview attached"}),this.refreshPendingOverlay(),this.refreshRuntimeState()}detach(){var e,t,i,r;this.emitDiagnostic("info","session","preview.detach",{message:"Preview detached"}),this.clearProbes(),this.textLayer.destroy();for(const{current:s,preload:a}of this.trackSlots.values())s.destroy(this.releaseTrackedObjectUrl),a.destroy(this.releaseTrackedObjectUrl);this.trackSlots.clear(),this.pendingOverlayRenderer.destroy(),this.compositor.detach(),this.container=null,this.pendingOverlayElement=null,this.audioContext&&((r=(t=(e=this.audioContext).close)==null?void 0:(i=t.call(e)).catch)==null||r.call(i,()=>{}),this.audioContext=null,this.masterGainNode=null),this.runtimePublisher.reset(),this.refreshRuntimeState()}sync(e){if(!this.compositor.getFrameElement())return;this.lastSyncedPlayState=e.playState,this.primarySelectedClipId=e.primarySelectedClipId??null,this.textLayer.setPrimarySelectedClipId(this.primarySelectedClipId),this.activeSyncRequestId=e.syncRequestId,this.syncCoordinator.bumpSyncGeneration();const i=e.activeClips.some(l=>l.trackType==="video"&&l.hasVisual);this.clockAggregator.updateAlignmentTarget(i,e.interactionMode,e.currentTime),this.transientVisualTransform&&this.transientVisualTransform.clipId!==this.primarySelectedClipId&&(this.transientVisualTransform=null),this.transientTextLayout&&this.transientTextLayout.clipId!==this.primarySelectedClipId&&(this.transientTextLayout=null),this.maybeResolveAutoAspectRatio(e.autoAspectRatioClip),this.bootstrapLayoutAspectRatioFromClipStyle(e.autoAspectRatioClip),this.textLayer.syncEntries(e.activeClips.filter(l=>l.trackType==="text"),l=>this.getEffectiveVisualTransform(l),this.getTextLayoutOptions());const r=Array.from(this.trackSlots.entries()).map(([l,c],h)=>{var d,u;return{trackId:l,kind:c.current.kind,order:((d=c.current.entry)==null?void 0:d.trackOrder)??((u=c.preload.entry)==null?void 0:u.trackOrder)??1e4+h}}),o=Au(e,r).map(l=>this.applyTrackPlan(l)).filter(l=>l!==void 0);this.refreshVisualLayout(),this.refreshRuntimeState(),o.length!==0&&Promise.all(o).catch(l=>{N.warn("PreviewEngine","preview sync failed",{error:l}),this.isSyncProjecting=!1,this.refreshRuntimeState()})}applyAspectRatio(e){this.compositor.applyAspectRatio(e),this.refreshVisualLayout()}getAspectRatio(){return this.compositor.getAspectRatio()}setPendingState(e){this.pendingState=e,this.refreshPendingOverlay()}failSlot(e,t,i){e.fail(i),this.refreshVisualLayout(),this.refreshRuntimeState()}get lastRuntimeState(){return this.runtimePublisher.getLastState()}refreshRuntimeState(){const e=this.collectSlots(),t=o=>Gn(o),i=this.buildTrackedSummary(e),r=this.buildLoadingState(e,t);this.syncPlaybackGroupSuspension(i,r);const s=this.clockAggregator.buildClockState(r,e.filter(o=>o.role==="current"),this.playbackGroupSuspended),a=this.runtimePublisher.publish({activeSyncRequestId:this.activeSyncRequestId,isSyncProjecting:this.isSyncProjecting,slots:e,evaluateTracked:t,isTrackedVideo:o=>Kt(o),clock:s},o=>{var l,c;return(c=(l=this.callbacks).onRuntimeStateChange)==null?void 0:c.call(l,o)},o=>{var l,c;return(c=(l=this.callbacks).onSyncProcessed)==null?void 0:c.call(l,o)});for(const o of e)Kt(o)&&this.compositor.tryResolveAutoAspectRatioFromSlot(o,l=>{var c,h;(h=(c=this.callbacks).onAspectRatioChange)==null||h.call(c,l)});this.syncLoadingProbe(a.loading),this.syncClockProbe(a.clock),this.refreshPendingOverlay()}applyTrackPlan(e){let t=this.getTrackSlots(e.trackId,e.kind);if(Iu(t,e.current.entry)){const i=Eu(t);this.trackSlots.set(e.trackId,i),t=i}return this.syncCoordinator.applyTrackPlan(e)}rememberSlotObjectUrl(e,t){var o;const i=this.dependencies.resourceCacheManager,r=e.objectUrl,s=e.objectUrlHolderId,a=Fu((o=e.entry)==null?void 0:o.clip.id);e.objectUrl=t,e.objectUrlHolderId=a,i&&(r&&r!==t&&s&&i.releaseObjectUrl(r,s),ss(t)&&a&&i.retainObjectUrl(t,a))}getTrackSlots(e,t){const i=this.trackSlots.get(e);if(i&&i.current.kind===t&&i.preload.kind===t)return i;i&&(i.current.destroy(this.releaseTrackedObjectUrl),i.preload.destroy(this.releaseTrackedObjectUrl),this.trackSlots.delete(e));const r={createMediaElement:this.dependencies.createMediaElement,slotClassNamePrefix:this.dependencies.slotClassNamePrefix,onStateChange:()=>this.refreshRuntimeState(),onMediaError:(l,c)=>l.fail(c),onDiagnostic:(l,c,h)=>{var g;const d=l==="media.error"?"error":l==="media.stalled"||l==="media.waiting"?"warn":"debug",u=l.startsWith("source")?"resource":"playback";this.emitDiagnostic(d,u,l,{trackId:c.trackId,clipId:((g=c.entry)==null?void 0:g.clip.id)??null,slotKey:`${c.trackId}:${c.role}`,desiredSourceUrl:c.desiredSource,actualSourceUrl:c.element.getAttribute("src"),extra:{role:c.role,kind:c.kind,...h??{}}})}},s={current:new Hn(e,t,"current",r),preload:new Hn(e,t,"preload",r)},a=this.compositor.getFrameElement(),o=this.compositor.getRootElement();return a&&(s.current.mountVideoTo(a),s.preload.mountVideoTo(a)),o&&(s.current.mountAudioTo(o),s.preload.mountAudioTo(o)),this.trackSlots.set(e,s),s}collectSlots(){const e=[];for(const t of this.trackSlots.values())e.push(t.current,t.preload);return e}buildLoadingState(e,t){let i=0,r=0,s=!1,a=!1,o=!1,l=!1;for(const c of e){if(!Kt(c))continue;i+=1;const h=t(c);h.failed&&(r+=1,s=!0),h.resolving&&(a=!0),h.seeking&&(o=!0),h.mediaUnready&&(l=!0)}return i<=0?{status:"idle",isLoading:!1,reason:null}:s&&r>=i?{status:"failed",isLoading:!1,reason:"failed"}:this.activeSyncRequestId!==void 0&&this.isSyncProjecting?{status:"loading",isLoading:!0,reason:"syncing"}:a?{status:"loading",isLoading:!0,reason:"resolving-source"}:o?{status:"loading",isLoading:!0,reason:"seeking"}:l?{status:"loading",isLoading:!0,reason:"media-pending"}:{status:"ready",isLoading:!1,reason:null}}buildTrackedSummary(e){let t=0,i=0,r=!1,s=!1,a=!1,o=!1;for(const l of e){if(!Kt(l))continue;t+=1;const c=Gn(l);c.failed&&(i+=1,r=!0),c.resolving&&(s=!0),c.seeking&&(a=!0),c.mediaUnready&&(o=!0)}return{trackedCount:t,failedTrackedCount:i,hasFailed:r,hasResolving:s,hasSeeking:a,hasMediaUnready:o}}syncPlaybackGroupSuspension(e,t){var r;if(((r=this.pendingState)==null?void 0:r.mode)==="seek")return;if(e.trackedCount>1&&(t.status==="loading"||t.status==="failed")){this.playbackGroupSuspended=!0;for(const s of this.collectSlots())s.role!=="current"||!s.isActive||s.requestedPlayState!=="playing"||s.isBuffering||s.isSeeking||s.isResolvingSource||s.phase==="binding"||s.element.paused||qt(s.element);return}if(this.playbackGroupSuspended){this.playbackGroupSuspended=!1;for(const s of this.collectSlots())s.role!=="current"||!s.isActive||s.requestedPlayState!=="playing"||!s.element.paused||rs(s.element)}}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 s=this.getAudioContext();if(!s||e.audioRoutingFailed){e.element.muted=t.muted,e.element.volume=r;return}if(!e.sourceNode||!e.gainNode)try{e.sourceNode=s.createMediaElementSource(e.element),e.gainNode=s.createGain(),e.sourceNode.connect(e.gainNode),e.gainNode.connect(this.getMasterGainNode(s))}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}getAudioContext(){if(this.audioContext)return this.audioContext;const e=this.dependencies.createAudioContext;return this.audioContext=e?e():null,this.audioContext}getMasterGainNode(e){return this.masterGainNode||(this.masterGainNode=e.createGain(),this.masterGainNode.connect(e.destination)),this.masterGainNode}bootstrapLayoutAspectRatioFromClipStyle(e){if(!e||!kt(this.compositor.getAspectRatio().mode))return;const t=nr(e,"sys_width"),i=nr(e,"sys_height");!t||!i||(this.compositor.resolveAutoAspectRatio(t,i),this.refreshVisualLayout())}maybeResolveAutoAspectRatio(e){if(!e)return;const t=nt(e.clip);if(this.aspectRatioProbeSrc===t)return;this.aspectRatioProbeSrc=t;const i=this.getAspectRatioProbe(),r=l=>{i.src=l;try{i.load()}catch{}},s=this.dependencies.previewSourceResolver;if(!s){r(e.clip.src);return}const a=this.dependencies.sourceMediaRegistry,o=a?a.getPreviewSource(t,()=>s(e.clip)):s(e.clip);if(o&&typeof o.then=="function"){o.then(l=>{r((l==null?void 0:l.url)??e.clip.src)});return}r((o==null?void 0:o.url)??e.clip.src)}getAspectRatioProbe(){var t,i;if(this.aspectRatioProbe)return this.aspectRatioProbe;const e=((i=(t=this.dependencies).createAspectRatioProbe)==null?void 0:i.call(t))||document.createElement("video");return hs(e),e.addEventListener("loadedmetadata",()=>{e.videoWidth>0&&e.videoHeight>0&&this.compositor.resolveAutoAspectRatio(e.videoWidth,e.videoHeight,r=>{var s,a;(a=(s=this.callbacks).onAspectRatioChange)==null||a.call(s,r)})}),this.aspectRatioProbe=e,e}getEffectiveVisualTransform(e){var o;const t=((o=this.transientVisualTransform)==null?void 0:o.clipId)===e.clip.id?this.transientVisualTransform.transform:e.clip.type==="text"?qe(e.clip.visualTransform):xe(e.clip.visualTransform);if(e.clip.type!=="text")return t;const i=this.compositor.getFrameSize(),r=this.compositor.getTextBaselineMetrics(i).scale,s=ce(e.clip.textStyle),{layoutHeight:a}=ws({frameSize:i,baselineScale:r,visualTransform:t,textStyle:s,contentText:e.clip.textContent||e.clip.name||"",styleOverride:this.getTextLayoutOverride(e)});return wo(t,s,i,a*r)}getTextLayoutOverride(e){var i,r,s;if(e.clip.type!=="text")return null;const t={};return((i=this.transientFontSize)==null?void 0:i.clipId)===e.clip.id&&(t.fontSize=this.transientFontSize.fontSize),((r=this.transientRotation)==null?void 0:r.clipId)===e.clip.id&&(t.rotation=this.transientRotation.rotation),((s=this.transientTextLayout)==null?void 0:s.clipId)===e.clip.id&&(t.layoutWidth=this.transientTextLayout.layoutWidth,t.layoutHeight=this.transientTextLayout.layoutHeight),Object.keys(t).length>0?t:null}getTextLayoutOptions(){return{getStyleOverride:e=>this.getTextLayoutOverride(e),resolveVisualTransform:e=>qe(e.clip.visualTransform)}}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 e of this.collectSlots())this.compositor.refreshSlotVisual(e);this.textLayer.refreshLayout(e=>qe(e.clip.visualTransform),this.getTextLayoutOptions()),this.refreshTextSelectionOverlay()}refreshTextSelectionOverlay(){this.compositor.transformOverlay.sync(this.compositor.buildSelectedOverlayState(this.primarySelectedClipId,this.collectSlots().filter(e=>e.role==="current"),{getEntry:e=>{const t=this.textLayer.getEntry(e);return t?{entry:t.entry,element:t.element}:void 0},getLayout:e=>this.textLayer.getLayout(e),getTransientFontSize:e=>{var t;return((t=this.transientFontSize)==null?void 0:t.clipId)===e?this.transientFontSize.fontSize:null},getTransientRotation:e=>{var t;return((t=this.transientRotation)==null?void 0:t.clipId)===e?this.transientRotation.rotation:null},getTextLayoutOverride:e=>{const t=this.textLayer.getEntry(e);return t?this.getTextLayoutOverride(t.entry):null}},e=>this.getEffectiveVisualTransform(e)))}refreshPendingOverlay(){this.pendingOverlayElement&&this.pendingOverlayRenderer.update({pendingState:this.pendingState,runtimeState:this.runtimePublisher.getLastState()})}syncLoadingProbe(e){if(e.status!=="loading"){this.clearLoadingProbe();return}this.loadingProbeTimeoutId||(this.loadingProbeTimeoutId=setTimeout(()=>{this.loadingProbeTimeoutId=null,this.refreshRuntimeState()},ep))}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()},tp))}clearProbes(){this.clearLoadingProbe(),this.clearClockProbe()}clearLoadingProbe(){this.loadingProbeTimeoutId&&(clearTimeout(this.loadingProbeTimeoutId),this.loadingProbeTimeoutId=null)}clearClockProbe(){this.clockProbeTimeoutId&&(clearTimeout(this.clockProbeTimeoutId),this.clockProbeTimeoutId=null)}emitDiagnostic(e,t,i,r={}){var o,l;const s=this.dependencies.diagnostics;if(!s)return;const a=((l=(o=this.dependencies).getDiagnosticsContext)==null?void 0:l.call(o))??{};s.emit({severity:e,category:t,eventName:i,...a,...r})}}class rp extends ip{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 sp(n){return"dom"}const np=36e5,ap=3e5;function ns(n){return n.length===0?0:n.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function zn(n){return ns(n)}function $n(n){return Math.max(n+ap,np)}class Vn{constructor(e={}){p(this,"listeners",new Map);this.initialPayloadProviders=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t);const i=this.initialPayloadProviders[e];i&&t(e,i())}off(e,t){this.listeners.has(e)&&this.listeners.set(e,this.listeners.get(e).filter(i=>i!==t))}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(i=>{try{i(e,t)}catch(r){N.error("TimelineEventDispatcher",`Error in event listener for ${e}:`,{error:r})}})}clear(){this.listeners.clear()}}function op(n){return[...n].sort((e,t)=>e.order-t.order)}function lp(n){return[...n].sort((e,t)=>e.startTime-t.startTime)}function Ir(n,e,t){const i=n.type==="video"||n.type==="text",r=n.type!=="text";return{trackId:n.id,trackType:n.type,trackOrder:n.order,clip:e,mediaTime:t,muted:(n.isMuted??!1)||(e.isMuted??!1),kind:n.type,hasVisual:i,hasAudio:r}}class cp{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t,i={}){const r=op(e),s=[],a=[];let o=null;for(const l of r){const c=lp(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);s.push(Ir(l,h,u))}const d=c.find(u=>u.startTime>t);if(d&&a.push(Ir(l,d,d.startTimeAtSource)),!o&&l.type==="video"){const u=c[0];u&&(o=Ir(l,u,u.startTimeAtSource))}}return{activeClips:s,nextClips:a,firstVideoClip:o}}}class hp{constructor(e){p(this,"options");p(this,"_previewSession");p(this,"_previewMountContainer",null);p(this,"_resolvedPreviewBackend","dom");p(this,"_runtimePreviewBackendOverride",null);p(this,"_activePreviewCallbackToken",0);this.options=e}get previewSession(){return this._previewSession}set previewSession(e){this._previewSession=e}get previewMountContainer(){return this._previewMountContainer}set previewMountContainer(e){this._previewMountContainer=e}get resolvedPreviewBackend(){return this._resolvedPreviewBackend}set resolvedPreviewBackend(e){this._resolvedPreviewBackend=e}get runtimePreviewBackendOverride(){return this._runtimePreviewBackendOverride}set runtimePreviewBackendOverride(e){this._runtimePreviewBackendOverride=e}get activePreviewCallbackToken(){return this._activePreviewCallbackToken}set activePreviewCallbackToken(e){this._activePreviewCallbackToken=e}isActiveCallbackToken(e){return e===this._activePreviewCallbackToken}resolveConfiguredPreviewBackend(){return this._resolvedPreviewBackend=this.options.resolveConfiguredBackend(this._runtimePreviewBackendOverride),this._resolvedPreviewBackend}createPreviewBackend(e=this.resolveConfiguredPreviewBackend()){const t=++this._activePreviewCallbackToken,i=this.options.createBackendCallbacks(t);return this.options.createBackend(e,i)}getPreviewSession(){return this._previewSession||(this._previewSession=this.createPreviewBackend()),this._previewSession}hasAttachedPreview(){var e;return!!((e=this._previewSession)!=null&&e.hasPreview())}attachPreview(e,t){this._previewMountContainer=e,this._runtimePreviewBackendOverride=null;const i=this.getPreviewSession();return i.attach(e),i.applyAspectRatio(t),i.getAspectRatio()}detachPreviewSession(){var e;return(e=this._previewSession)!=null&&e.hasPreview()?(this.destroyPreviewSession(),this.recreateDetachedPreviewSession(),this._previewMountContainer=null,!0):!1}destroyPreviewSession(e=!1){var t;this._activePreviewCallbackToken+=1,(t=this._previewSession)==null||t.destroy(),e&&(this._previewSession=void 0)}recreateDetachedPreviewSession(){this._previewSession&&(this._previewSession=this.createPreviewBackend(this._resolvedPreviewBackend))}fallbackToDom(e){if(this._resolvedPreviewBackend==="dom"||!this._previewSession)return{handled:!1,aspectRatio:e};const t=this._previewMountContainer;if(this.destroyPreviewSession(!0),this._runtimePreviewBackendOverride="dom",this._resolvedPreviewBackend="dom",!t)return{handled:!0,aspectRatio:e};const i=this.createPreviewBackend("dom");return this._previewSession=i,i.attach(t),i.applyAspectRatio(e),{handled:!0,aspectRatio:i.getAspectRatio()}}}const dp=1e3;class up{constructor(e){p(this,"callbacks");p(this,"failedOverlayDelayMs");p(this,"_previewLoadingState",{status:"idle",isLoading:!1,reason:null});p(this,"_pendingPreviewState",null);p(this,"_nextPendingPreviewSyncRequestId",0);this.callbacks=e.callbacks,this.failedOverlayDelayMs=e.failedOverlayDelayMs??dp}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)),Un(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};Un(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 Un(n,e){return n.status===e.status&&n.isLoading===e.isLoading&&n.reason===e.reason}const pp=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],gp={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 fp(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function mp(n){const e=n.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 yp(n,e,t){const i=e.split("+").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return null;let r=null,s=!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":s=!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=mp(c);if(!h||r)return null;r=h}}return r?{action:n,code:r,altKey:s,ctrlKey:a,metaKey:o,shiftKey:l}:null}function Sp(n){if(!(n instanceof HTMLElement))return!1;if(n.isContentEditable)return!0;const e=n.tagName;return e==="INPUT"||e==="TEXTAREA"||e==="SELECT"?!0:!!n.closest('[contenteditable=""], [contenteditable="true"], input, textarea, select')}function Cp(n,e){return n.code===e.code&&n.altKey===e.altKey&&n.ctrlKey===e.ctrlKey&&n.metaKey===e.metaKey&&n.shiftKey===e.shiftKey}function vp(n,e){return n===!1||(n==null?void 0:n.enabled)===!1?[]:pp.flatMap(t=>{var s;const i=(s=n==null?void 0:n.bindings)==null?void 0:s[t];return(i===void 0?gp[t]:Array.isArray(i)?i:[i]).map(a=>yp(t,a,e)).filter(a=>a!==null)})}class Tp{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??fp();e.root,this.callbacks=e.callbacks,this.bindings=vp(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(Sp(e.target))return;const t=this.bindings.find(i=>Cp(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 Lo(n){var t;const e=n.getPrimarySelectedClip()||((t=n.findFallbackSelectedClip)==null?void 0:t.call(n))||null;return{clip:e,hasSelectedClip:!!e}}function bp(n){const e=Lo(n),t=n.getSelectedClipIds(),i=n.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:n.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function kp(n){var i;const e=n.resolveSelectedClip(),t=((i=e.clip)==null?void 0:i.id)||null;return t===n.lastSelectedClipId?n.lastSelectedClipId:(n.emitSelectedClipChange(e),t)}class wp{constructor(e){p(this,"cleanupEmptyTracks",!1);p(this,"durationDirty",!1);p(this,"canPlayDirty",!1);p(this,"selectionDirty",!1);p(this,"trackLayoutDirty",!1);p(this,"trackInfoDirty",!1);p(this,"stageDirty",!1);p(this,"previewDirty",!1);p(this,"committed",!1);p(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,s=i?this.resolveTrackId(i):null;if(!r||!s)return!1;const a=this.options.moveClipToTrack?this.options.moveClipToTrack(r,s,t):this.options.trackCollection.moveClipToTrack(r,s,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 xp(n,e){var t,i,r,s;return((i=(t=n.findById(e))==null?void 0:t.getId)==null?void 0:i.call(t))||((s=(r=n.getLastTrack())==null?void 0:r.getId)==null?void 0:s.call(r))||e}function Pp(n){if(n.placement.status==="use_existing_track")return n.trackCollection.addClipToTrack(n.placement.trackId,n.clip);const e=n.createTrack(n.placement.trackType,n.placement.suggestedTrackName,n.placement.insertionPlacement),t=xp(n.trackCollection,e);return t?n.trackCollection.addClipToTrack(t,n.clip):!1}function Wn(n,e,t){return e.trackId?n.removeClipFromTrack(e.trackId,t):!1}function _p(n){return n.trackCollection.moveClipToTrack(n.command.clip,n.command.sourceTrackId,n.command.targetTrackId)}function Bi(n){var e,t,i,r,s;(e=n.checkTrackDurationChange)==null||e.call(n),(t=n.updateCanPlayState)==null||t.call(n),(i=n.updateTrackInfoPanel)==null||i.call(n),(r=n.handleClipChange)==null||r.call(n),(s=n.cleanupEmptyTracks)==null||s.call(n)}class Do{constructor(){p(this,"panel",null);p(this,"config",null);p(this,"currentSelectionState",this.buildSelectionState(null,[]));p(this,"isInternalUpdate",!1)}init(e){this.config=e;const t=this.convertTheme(e.theme);this.panel=new mo({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=>Me(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:s,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&&s==="audio"?r.filter(l=>Me(l)):[o]:Object.prototype.hasOwnProperty.call(t,"textStyle")?s==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"visualTransform")?s==="video"||s==="text"?r:[o]:Object.prototype.hasOwnProperty.call(t,"volume")?s==="video"||s==="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(){p(this,"panel",null)}init(e){var i,r,s,a;const t=((i=e.theme)==null?void 0:i.background)||ke.background;this.panel=new fo({container:e.container,theme:{background:t,border:((r=e.theme)==null?void 0:r.border)||ke.border,text:((s=e.theme)==null?void 0:s.clipName)||ke.text,buttonBackground:((a=e.theme)==null?void 0:a.clipBackground)||ke.buttonBackground,buttonHover:ke.buttonHover,buttonDanger:ke.buttonDanger},width:Ci,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}}const Ip=1.35,Yn="Arial, sans-serif";function Ep(n,e){const t=Math.max(0,Math.round(n));if(t<=0)return"none";const i=[];for(let r=-t;r<=t;r+=1)for(let s=-t;s<=t;s+=1)s===0&&r===0||i.push(`${s}px ${r}px 0 ${e}`);return i.join(", ")}function Rp(n){return`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Mp(n){return n!=null&&n.fontName?`${Rp(n.fontName)}, ${Yn}`:Yn}function Lp(n,e,t,i){if(typeof document>"u")return 0;const r=ce(n.textStyle),s=To(r.fontSize,r.paddingX,r.strokeWidth,e),a=document.createElement("div");a.style.position="absolute",a.style.visibility="hidden",a.style.pointerEvents="none",a.style.boxSizing="border-box",a.style.overflow="visible",a.style.width=`${t}px`,a.style.height="auto";const o=document.createElement("div");o.style.display="block",o.style.width="100%",o.style.height="auto",o.style.textAlign="center",o.style.whiteSpace="pre-wrap",o.style.overflowWrap="break-word",o.style.overflow="visible",o.style.boxSizing="border-box",o.style.color=r.color,o.style.fontFamily=Mp(i),o.style.fontSize=`${s.fontSize}px`,o.style.lineHeight=String(Ip),o.style.padding=`0 ${s.paddingX}px`,o.style.textShadow=Ep(s.strokeWidth,r.strokeColor),o.textContent=n.textContent||n.name||"",a.appendChild(o),document.body.appendChild(a);const l=Math.max(a.offsetHeight,o.offsetHeight,o.scrollHeight,1);return a.remove(),Math.ceil(l/e)}function Xn(n,e,t,i,r){const s={width:e.width,height:e.height},a=ce(n.textStyle),o=qe(n.visualTransform),l=r===void 0?i:Eo({layout:i,frameSize:s,baselineScale:1,visualTransform:o,textStyle:a,measuredHeightPx:r});return Ro({frameSize:s,composition:e,lastLayout:l,layoutMode:t})}function Dp(n,e,t){if(e.width<=0||e.height<=0)return null;const i={width:e.width,height:e.height},r=bu(n.textStyle),s=Io({clip:n},i,1);if(r==="manual")return Xn(n,e,r,s);const a=Lp(n,1,s.frameRect.width,t)||s.layoutHeight;return Xn(n,e,r,s,a)}class jn{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,Bp=10*1024*1024*1024,Fp=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:Bp,ttlMs:Fp,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:Hp},Gp="timeline-preview-resource-cache",Np=1,Se="metadata";function zp(){return new Promise((n,e)=>{const t=indexedDB.open(Gp,Np);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=()=>n(t.result)})}function Er(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onerror=()=>t(n.error),n.onabort=()=>t(n.error)})}class $p{constructor(){p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=zp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async get(e){const t=await this.getDb();return new Promise((i,r)=>{const s=t.transaction(Se,"readonly").objectStore(Se).get(e);s.onerror=()=>r(s.error),s.onsuccess=()=>i(s.result??null)})}async put(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).put(e),await Er(i)}async delete(e){const i=(await this.getDb()).transaction(Se,"readwrite");i.objectStore(Se).delete(e),await Er(i)}async clear(){const t=(await this.getDb()).transaction(Se,"readwrite");t.objectStore(Se).clear(),await Er(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 Vp="timeline-preview-resource-cache",Up="timeline-preview-resource-cache-blobs",Wp=1,Ee="blobs";function Yp(){return new Promise((n,e)=>{const t=indexedDB.open(Up,Wp);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result)})}function Rr(n){return new Promise((e,t)=>{n.oncomplete=()=>e(),n.onerror=()=>t(n.error),n.onabort=()=>t(n.error)})}class Xp{constructor(){p(this,"kind","indexeddb");p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=Yp().catch(e=>{throw this.dbPromise=null,e})),this.dbPromise}async read(e){const t=await this.getDb();return new Promise((i,r)=>{const s=t.transaction(Ee,"readonly").objectStore(Ee).get(e);s.onerror=()=>r(s.error),s.onsuccess=()=>i(s.result??null)})}async write(e,t){const r=(await this.getDb()).transaction(Ee,"readwrite");r.objectStore(Ee).put(t,e),await Rr(r)}async delete(e){const i=(await this.getDb()).transaction(Ee,"readwrite");i.objectStore(Ee).delete(e),await Rr(i)}async clear(){const t=(await this.getDb()).transaction(Ee,"readwrite");t.objectStore(Ee).clear(),await Rr(t)}}class jp{constructor(){p(this,"kind","opfs");p(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(Vp,{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 s=await(await(await this.getDirectory()).getFileHandle(e,{create:!0})).createWritable();try{await s.write(t),await s.close()}catch(a){try{typeof s.abort=="function"&&await s.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 qp(n){var e;if(n.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new jp;if(await t.ensureReady())return t}return new Xp}function Kp(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function qn(n){return n.split(";",1)[0].trim().toLowerCase()}async function Zp(n){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(n));return Kp(new Uint8Array(t))}function Mr(n){return n?[...n]:[...li.allowedMimeTypes]}function Jp(n){return n?n===!0?{...li,enabled:!0,allowedMimeTypes:Mr(void 0)}:{...li,...n,enabled:n.enabled??!0,allowedMimeTypes:Mr(n.allowedMimeTypes)}:{...li,allowedMimeTypes:Mr(void 0)}}function Qp(n){try{const e=new URL(n);return e.hash="",e.toString()}catch{return n.trim()}}async function eg(n){var t;const e=((t=n.sourceKey)==null?void 0:t.trim())||Qp(n.url);return Zp(e)}function Kn(n,e=li.allowedMimeTypes){if(!n.url)return!0;let t;try{t=new URL(n.url)}catch{return!0}if(t.protocol!=="http:"&&t.protocol!=="https:"||n.kind==="hls-fmp4"||/\.m3u8(?:$|\?|#)/i.test(t.pathname))return!0;if(!n.mimeType)return!1;const i=qn(n.mimeType);return!e.some(r=>qn(r)===i)}function tg(n){return n&&n.split(";",1)[0].trim().toLowerCase()||null}function Zn(n){if(!n)return null;const e=Number(n);return Number.isSafeInteger(e)&&e>=0?e:null}function ig(n){if(!n)return null;const e=n.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 Jn(n,e,t){return{url:e,ok:n.ok,status:n.status,mimeType:tg(n.headers.get("content-type")),sizeBytes:t,etag:n.headers.get("etag"),lastModified:n.headers.get("last-modified"),acceptRanges:n.headers.get("accept-ranges")}}class rg{async probe(e){var r;try{const s=await fetch(e,{method:"HEAD"}),a=Zn(s.headers.get("content-length"));if(s.ok&&a!==null)return Jn(s,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=ig(t.headers.get("content-range"))??Zn(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return Jn(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 sg={createObjectURL(n){return URL.createObjectURL(n)},revokeObjectURL(n){URL.revokeObjectURL(n)}};function mt(n,e){return{url:n.url,cacheStatus:e,sourceUrl:n.url}}function ng(n,e){return n.etag||e.etag?n.etag===e.etag&&n.sizeBytes===e.contentLength:n.sizeBytes===e.contentLength&&n.lastModified===e.lastModified}class ag{constructor(e={}){p(this,"options");p(this,"metadataStore");p(this,"storagePromise");p(this,"http");p(this,"objectUrl");p(this,"now");p(this,"cacheKeyBuilder");p(this,"onEvent");p(this,"objectUrls",new Set);p(this,"objectUrlByCacheKey",new Map);p(this,"cacheKeyByObjectUrl",new Map);p(this,"objectUrlHolders",new Map);p(this,"inflightDownloads",new Map);this.options=Jp(e.options),this.metadataStore=e.metadataStore??new $p,this.storagePromise=e.storage?Promise.resolve(e.storage):qp({preferStorage:this.options.preferStorage}),this.http=e.http??new rg,this.objectUrl=e.objectUrl??sg,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??eg,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Kn(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),mt(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(t,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}),mt(e,"miss");const s=await this.probeCacheable(e);if(s.cacheStatus!=="miss")return s.result;const{blob:a,metadata:o}=await this.getOrCreateDownload(t,e,s.probe,i);return this.emitEvent("resource-cache.miss",{sourceUrl:e.url,sizeBytes:o.sizeBytes}),this.blobResult(t,e.url,a,o,"miss")}catch{return this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),mt(e,"fallback")}}retainObjectUrl(e,t){if(!t||!this.objectUrls.has(e))return;let i=this.objectUrlHolders.get(e);i||(i=new Set,this.objectUrlHolders.set(e,i)),i.add(t)}releaseObjectUrl(e,t){if(!e||!t||!this.objectUrls.has(e))return;const i=this.objectUrlHolders.get(e);!(i!=null&&i.delete(t))||i.size>0||(this.objectUrlHolders.delete(e),this.revokeTrackedObjectUrl(e))}revokeObjectUrl(e){this.forceRevokeObjectUrl(e)}forceRevokeObjectUrl(e){!e||!this.objectUrls.has(e)||(this.objectUrlHolders.delete(e),this.revokeTrackedObjectUrl(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.forceRevokeObjectUrl(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,s){const a=await this.probeCacheable(e);if(a.cacheStatus!=="miss")return a.result;if(ng(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(t,e.url,r,h,"stale-revalidated")}this.emitEvent("resource-cache.revalidate.stale",{sourceUrl:e.url}),await this.deleteEntry(t,s);const{blob:o,metadata:l}=await this.getOrCreateDownload(t,e,a.probe,s);return this.blobResult(t,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:mt(e,"fallback")}):Kn({...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:mt(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:mt(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 s=this.inflightDownloads.get(e);if(s)return s;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 s=await this.http.download(t.url),a=s.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,s);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:s,metadata:l}}catch(s){throw this.emitEvent("resource-cache.download.failed",{sourceUrl:t.url,error:s instanceof Error?s.message:String(s)}),s}}async evictForWrite(e,t,i){const r=(await this.metadataStore.list()).filter(a=>a.cacheKey!==e);let s=r.reduce((a,o)=>a+o.sizeBytes,0);for(const a of r.sort((o,l)=>o.lastAccessedAt-l.lastAccessedAt)){if(s+t<=this.options.maxTotalBytes)return;await this.deleteEntry(a.cacheKey,i),s-=a.sizeBytes}}async deleteEntry(e,t){const i=this.objectUrlByCacheKey.get(e);i&&(this.objectUrlByCacheKey.delete(e),this.forceRevokeObjectUrl(i)),await Promise.all([t.delete(e),this.metadataStore.delete(e)]),this.emitEvent("resource-cache.cleanup.deleted",{cacheKey:e})}registerObjectUrl(e,t){this.objectUrls.add(t),this.objectUrlByCacheKey.set(e,t),this.cacheKeyByObjectUrl.set(t,e)}revokeTrackedObjectUrl(e){if(!this.objectUrls.delete(e))return;const t=this.cacheKeyByObjectUrl.get(e);t&&(this.objectUrlByCacheKey.delete(t),this.cacheKeyByObjectUrl.delete(e)),this.objectUrl.revokeObjectURL(e)}blobResult(e,t,i,r,s){const a=this.objectUrlByCacheKey.get(e);if(a&&this.objectUrls.has(a))return this.toResolvedBlob(a,t,r,s);const o=this.objectUrl.createObjectURL(i);return this.registerObjectUrl(e,o),this.toResolvedBlob(o,t,r,s)}toResolvedBlob(e,t,i,r){return{url:e,cacheStatus:r,sourceUrl:t,sizeBytes:i.sizeBytes,objectUrl:e}}emitEvent(e,t){var i;(i=this.onEvent)==null||i.call(this,e,t)}}function og(n){return!!n&&typeof n.then=="function"}class Lr{constructor(){p(this,"durationCache",new Map);p(this,"thumbnailCache",new Map);p(this,"previewSourceCache",new Map)}static buildSourceKey(e){var t;return((t=e.externalId)==null?void 0:t.trim())||e.src||""}static buildThumbnailKey(e){return[this.buildSourceKey(e),e.type,e.startTimeAtSource,e.endTimeAtSource,e.duration].join("|")}getDuration(e,t,i={}){const r=this.durationCache.get(e);if(!i.force){if(r!=null&&r.promise)return r.promise;if(typeof(r==null?void 0:r.value)=="number")return Promise.resolve(r.value)}const s=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:s}),s}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 s=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:s}),s}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 s=t();if(!og(s))return this.previewSourceCache.set(e,{value:s,promise:null,resolved:!0}),s;const a=s.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 Qn{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 lg{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),s=this.findById(i);return!(r!=null&&r.removeClip)||!(s!=null&&s.addClip)?!1:(r.removeClip(e.id),s.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 cg(n){return n==="text"?"文本":n==="video"?"视频":"音频"}function Fi(n){return n==="text"?0:n==="video"?1:2}class Oo{constructor(e=[]){p(this,"tracks",[]);p(this,"trackCounter",0);this.tracks=[...e],this.trackCounter=this.tracks.length}createTrack(e,t,i,r,s,a){this.trackCounter++;const o=t||`${cg(e)}轨道 ${this.trackCounter}`,l=s??(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),N.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?(N.warn("TrackManager",`轨道不存在: ${e}`),!1):((i=this.tracks[t])==null?void 0:i.role)==="primary"?(N.warn("TrackManager",`主轨不可删除: ${e}`),!1):(this.tracks.splice(t,1),this.recalculateOrder(),N.debugLazy("TrackManager",()=>`删除轨道: ${e}`),!0)}renameTrack(e,t){const i=this.tracks.find(r=>r.id===e);return i?(i.name=t,N.debugLazy("TrackManager",()=>`重命名轨道: ${e} -> ${t}`),!0):(N.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),N.debugLazy("TrackManager",()=>`更新轨道: ${e}`,()=>t),!0):(N.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"),s=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((s==="before_track"||s==="after_track")&&i){const a=this.tracks.findIndex(o=>o.id===i);if(a!==-1){this.tracks.splice(a+(s==="after_track"?1:0),0,e),this.recalculateOrder();return}}if(s==="top_of_type_region"){const a=this.tracks.findIndex(l=>l.type===e.type);if(a!==-1){this.tracks.splice(a,0,e),this.recalculateOrder();return}const o=this.tracks.findIndex(l=>Fi(l.type)>Fi(e.type));if(o!==-1){this.tracks.splice(o,0,e),this.recalculateOrder();return}}if(s==="bottom_of_type_region"){const a=this.tracks.reduce((l,c,h)=>c.type===e.type?h:l,-1);if(a!==-1){this.tracks.splice(a+1,0,e),this.recalculateOrder();return}const o=this.tracks.reduce((l,c,h)=>Fi(c.type)<=Fi(e.type)?h:l,-1);if(o!==-1){this.tracks.splice(o+1,0,e),this.recalculateOrder();return}}s==="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,N.debugLazy("TrackManager",()=>`${t?"静音":"取消静音"}轨道:${e}`),!0):(N.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,N.debug("TrackManager","清空所有轨道(包括主轨)")}getTrackCount(){return this.tracks.length}getTrackCountByType(e){return this.tracks.filter(t=>t.type===e).length}}class hg{constructor(e){p(this,"currentTime");p(this,"playState");p(this,"speed");this.currentTime=e.currentTime,this.playState=e.playState,this.speed=e.speed}getCurrentTime(){return this.currentTime}setCurrentTime(e){this.currentTime=e}getPlayState(){return this.playState}setPlayState(e){this.playState=e}getSpeed(){return this.speed}setSpeed(e){this.speed=e}}class Bo{constructor(){p(this,"selectedClipIds",new Set)}getPrimarySelectedClipId(){return this.selectedClipIds.values().next().value??null}getSelectedClipId(){return this.getPrimarySelectedClipId()}getSelectedClipIds(){return Array.from(this.selectedClipIds)}addToSelection(e){this.selectedClipIds.add(e)}removeFromSelection(e){this.selectedClipIds.delete(e)}toggleSelection(e){this.selectedClipIds.has(e)?this.selectedClipIds.delete(e):this.selectedClipIds.add(e)}setSelection(e){this.selectedClipIds=new Set(e)}setPrimarySelection(e){this.setSelection(e===null?[]:[e])}setSelectedClipId(e){this.setPrimarySelection(e)}clear(){this.selectedClipIds.clear()}hasSelection(){return this.selectedClipIds.size>0}isSelected(e){return this.selectedClipIds.has(e)}getSelectionCount(){return this.selectedClipIds.size}}class dg{constructor(e){p(this,"zoom");p(this,"duration");p(this,"scrollLeft");p(this,"scrollTop");p(this,"viewportWidth");p(this,"viewportHeight");p(this,"contentHeight");this.zoom=e.zoom,this.duration=e.duration,this.scrollLeft=e.scrollLeft||0,this.scrollTop=e.scrollTop||0,this.viewportWidth=e.viewportWidth||0,this.viewportHeight=e.viewportHeight||0,this.contentHeight=e.contentHeight||0}getZoom(){return this.zoom}setZoom(e){this.zoom=e}getDuration(){return this.duration}setDuration(e){this.duration=e}getScrollLeft(){return this.scrollLeft}setScrollLeft(e){this.scrollLeft=e}getScrollTop(){return this.scrollTop}setScrollTop(e){this.scrollTop=e}getViewportWidth(){return this.viewportWidth}setViewportWidth(e){this.viewportWidth=e}getViewportHeight(){return this.viewportHeight}setViewportHeight(e){this.viewportHeight=e}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}}class ea{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new Bo,this.playbackStore=new hg({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new dg({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 ug{constructor(e,t,i,r,s){p(this,"stage");p(this,"layer");p(this,"onTimeChange");p(this,"onScrollChange");p(this,"config");p(this,"theme");p(this,"scrollLeft",0);p(this,"timeScaleHeight",40);p(this,"isDragging",!1);p(this,"dragStartX",0);p(this,"isPointerInsideTimeline",!1);p(this,"lastPointerXInTimeline",null);p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handlePointerMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.unbindGlobalPointerListenersForDrag()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});this.stage=e,this.layer=t,this.onTimeChange=r,this.onScrollChange=s,this.config={duration:i.duration||Zt,zoom:i.zoom||Re.MEDIUM,currentTime:i.currentTime||0,playState:i.playState||"paused",container:i.container,theme:Xi(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,s=this.stage.width(),a=r<=s?Math.max(0,t-(s-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),s=U.pixelsToTime(i,this.config.zoom),a=U.msToSeconds(r),o=U.msToSeconds(s),{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 j=class j{constructor(e,t,i,r,s,a,o){p(this,"container");p(this,"visualElement");p(this,"lineHitAreaElement");p(this,"theme");p(this,"onTimeChange");p(this,"onHorizontalAutoScroll");p(this,"currentTime");p(this,"zoom");p(this,"scrollLeft",0);p(this,"height");p(this,"isDragging",!1);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"lastPointerClientX",null);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&(this.lastPointerClientX=e.clientX,this.updateTimeFromClientX(e.clientX),this.updateEdgeAutoScrollState(e.clientX))});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.lastPointerClientX=null,this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleMouseDown",e=>{e.preventDefault(),e.stopPropagation(),this.isDragging=!0,this.lastPointerClientX=e.clientX,this.bindGlobalPointerListeners()});p(this,"handleHandleClick",e=>{e.preventDefault(),e.stopPropagation()});p(this,"handleEdgeAutoScrollFrame",()=>{if(this.edgeAutoScrollAnimationFrameId=null,!this.isDragging||!this.onHorizontalAutoScroll||this.lastPointerClientX===null)return;const e=this.container.getBoundingClientRect(),t=this.lastPointerClientX-e.left,i=this.calculateHorizontalAutoScrollVelocity(t,e.width);if(i===0){this.stopEdgeAutoScroll();return}const r=this.scrollLeft,s=this.onHorizontalAutoScroll(this.scrollLeft+i),a=typeof s=="number"?s: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=s,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(j.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${j.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=`${j.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(j.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=j.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const s=(i-e)/i;return-Math.max(1,Math.round(s*r))}if(e>t-i){const s=(e-(t-i))/i;return Math.max(1,Math.round(s*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(j.HANDLE_HEIGHT+j.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 ${j.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=xs.grip,i=Math.max(j.HANDLE_HEIGHT,e-j.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(j.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",xs.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(j.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(j.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(j.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(j.VISUAL_WIDTH-j.LINE_WIDTH)/2}`),t.setAttribute("y",`${j.HANDLE_LINE_START}`),t.setAttribute("width",`${j.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-j.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e){const t=document.createElementNS(j.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-end-cap"),t.setAttribute("x","3"),t.setAttribute("y",`${e}`),t.setAttribute("width",`${j.END_CAP_WIDTH}`),t.setAttribute("height",`${j.END_CAP_HEIGHT}`),t.setAttribute("rx","1.5"),t.setAttribute("fill","#ffffff"),t}};p(j,"SVG_NS","http://www.w3.org/2000/svg"),p(j,"VISUAL_WIDTH",14),p(j,"HANDLE_HEIGHT",16),p(j,"HANDLE_LINE_START",13),p(j,"LINE_WIDTH",1),p(j,"LINE_HIT_WIDTH",12),p(j,"END_CAP_WIDTH",8),p(j,"END_CAP_HEIGHT",1),p(j,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(j,"AUTO_SCROLL_MAX_SPEED",18);let as=j;class ta{constructor(e){p(this,"container");p(this,"orientation");p(this,"theme");p(this,"onScrollChange");p(this,"leadingInset");p(this,"trailingInset");p(this,"stage");p(this,"layer");p(this,"hitAreaRect");p(this,"thumbRect");p(this,"viewportSize",0);p(this,"contentSize",0);p(this,"scrollOffset",0);p(this,"isDragging",!1);p(this,"dragStartClient",0);p(this,"dragStartOffset",0);p(this,"hasBoundGlobalPointerListeners",!1);p(this,"handleGlobalPointerMove",e=>{this.isDragging&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.isDragging=!1,this.updateCursor(),this.unbindGlobalPointerListeners()});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.handleGlobalPointerEnd()});p(this,"handleStageMouseDown",e=>{var r;e.evt.preventDefault();const t=e.target===this.thumbRect||typeof((r=e.target)==null?void 0:r.name)=="function"&&e.target.name()==="scrollbar-thumb",i=this.orientation==="horizontal"?e.evt.clientX:e.evt.clientY;t||this.jumpToPointer(i),this.isDragging=!0,this.dragStartClient=i,this.dragStartOffset=this.scrollOffset,this.updateCursor(),this.bindGlobalPointerListeners()});p(this,"handleStageMouseUp",()=>{this.handleGlobalPointerEnd()});p(this,"handleStageMouseEnter",()=>{this.updateCursor()});p(this,"handleStageMouseMove",()=>{this.updateCursor()});p(this,"handleStageMouseLeave",()=>{this.isDragging||(this.container.style.cursor="default")});this.container=e.container,this.orientation=e.orientation,this.theme=e.theme,this.onScrollChange=e.onScrollChange,this.leadingInset=Math.max(0,e.leadingInset||0),this.trailingInset=Math.max(0,e.trailingInset||0),this.container.innerHTML="",this.container.style.userSelect="none",this.container.style.background="transparent",this.stage=new 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,Et.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=de.createRect(0,0,0,0,this.theme.scrollbarThumb||Et.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Et.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(),s=this.getThumbSize(r),a=Math.max(1,r-s),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(),s=this.getThumbSize(r),a=Math.max(1,r-s),o=Math.max(0,Math.min(r,i-this.leadingInset)),l=Math.max(0,Math.min(a,o-s/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||Et.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||Et.border);const r=this.getAvailableTrackSize();if(r<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const s=this.getThumbSize(r),a=this.leadingInset+this.getThumbPosition(r,s);this.thumbRect.visible(!0),this.orientation==="horizontal"?(this.thumbRect.x(a),this.thumbRect.y(0),this.thumbRect.width(s),this.thumbRect.height(t)):(this.thumbRect.x(0),this.thumbRect.y(a),this.thumbRect.width(e),this.thumbRect.height(s)),this.stage.batchDraw()}getTrackSize(){return this.orientation==="horizontal"?this.stage.width():this.stage.height()}getAvailableTrackSize(){return Math.max(0,this.getTrackSize()-this.leadingInset-this.trailingInset)}getMaxScrollOffset(){return Math.max(0,this.contentSize-this.viewportSize)}clampScrollOffset(e){return Math.max(0,Math.min(this.getMaxScrollOffset(),e))}shouldHideScrollbar(){return this.orientation==="vertical"&&this.getMaxScrollOffset()<=0}updateCursor(){if(this.shouldHideScrollbar()){this.container.style.cursor="default";return}this.container.style.cursor=this.orientation==="horizontal"?"ew-resize":"ns-resize"}getThumbSize(e){return e<=0||this.contentSize<=0?e:this.contentSize<=this.viewportSize?Math.min(e,this.orientation==="horizontal"?48:32):Math.max(40,this.viewportSize/this.contentSize*e)}getThumbPosition(e,t){const i=this.getMaxScrollOffset();if(i<=0||t>=e)return 0;const r=Math.max(1,e-t);return this.scrollOffset/i*r}}const pg=48;function gg(n,e,t){return U.timeToPixels(n,e)-t+pe}function fg(n,e,t){const i=Math.max(0,t-e);return Math.max(0,Math.min(i,n))}function mg(n){const{time:e,zoom:t,scrollLeft:i,viewportWidth:r,contentWidth:s,margin:a=pg}=n;if(r<=0||Math.max(0,s-r)<=0)return null;const l=gg(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=fg(d,r,s);return Math.abs(u-i)<=.5?null:u}class ia{constructor(){p(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 yg="@linker-design-plus/timeline-track",Sg="2.2.3",zt={name:yg,version:Sg},Cg=1,vg=2,Tg=250,bg=750,kg=1500;function ra(n){return n==null?n:JSON.parse(JSON.stringify(n))}function wg(n,e){return n.length!==e.length?!1:n.every((t,i)=>t===e[i])}function xg(n){return n==="text"?"文本":n==="video"?"视频":"音频"}class Pg{constructor(e={}){p(this,"timeline",null);p(this,"tracks",[]);p(this,"trackManager");p(this,"trackInfoPanelController");p(this,"playhead",null);p(this,"history");p(this,"config");p(this,"eventDispatcher");p(this,"animationFrameId",null);p(this,"lastUpdateTime",0);p(this,"isInitialized",!1);p(this,"stage",null);p(this,"headerStage",null);p(this,"headerLayer",null);p(this,"backgroundLayer",null);p(this,"trackLayer",null);p(this,"dragOverlayLayer",null);p(this,"snapGuideLayer",null);p(this,"selectionBoxLayer",null);p(this,"selectionBoxRect",null);p(this,"isBoxSelecting",!1);p(this,"boxSelectStartX",0);p(this,"boxSelectStartY",0);p(this,"resizeObserver",null);p(this,"rootContainer",null);p(this,"layout",null);p(this,"bodyBackgroundRect",null);p(this,"snapGuideLine",null);p(this,"trackInsertionPreviewLine",null);p(this,"trackInsertionPreviewY",null);p(this,"snapGuideTime",null);p(this,"horizontalScrollbar",null);p(this,"verticalScrollbar",null);p(this,"isExecutingHistoryAction",!1);p(this,"lastTrackDuration",0);p(this,"lastReportedTrackDuration",0);p(this,"thumbnailProvider",null);p(this,"thumbnailProviderVersion",0);p(this,"clipThumbnailLoadStates",new Map);p(this,"sourceMediaRegistry",new Lr);p(this,"canPlay",!1);p(this,"sourceLoadingCount",0);p(this,"timelineStore");p(this,"timelineCommands");p(this,"timelineHistoryRecorder");p(this,"timelinePresentationAdapter");p(this,"timelineTrackBridge");p(this,"timelinePlaybackResolver");p(this,"previewRuntimeController");p(this,"previewStateController");p(this,"previewPlaybackSuspendedByBuffering",!1);p(this,"previewPlaybackAutoResume",!1);p(this,"lastSelectedClipId",null);p(this,"previewAspectRatio",{...Le});p(this,"bodyViewportScrollListener",()=>{this.handleBodyViewportScroll()});p(this,"stageMouseDownListener",null);p(this,"bodyCanvasHostClickListener",e=>{this.handleBodyCanvasHostClick(e)});p(this,"rootWheelListener",e=>{this.handleUnifiedWheel(e)});p(this,"keyboardShortcutsController",null);p(this,"clipClipboard",null);p(this,"mountManager",new ia);p(this,"pendingDraftData",null);p(this,"selectionStore",new Bo);p(this,"multiDragSession",null);p(this,"clipRemovalBatchDepth",0);p(this,"splitOperationDepth",0);p(this,"diagnostics");p(this,"previewRuntimeState",{phase:"idle",loading:{status:"idle",isLoading:!1,reason:null},clock:{status:"unavailable",timelineTime:null,mediaTime:null,clipId:null,trackId:null,reason:"no-video-clock"},errorMessage:null,slots:[]});p(this,"failedPreviewClipIds");p(this,"previewActiveClipIds",[]);p(this,"previewClockSeekAlignmentTargetTime",null);p(this,"previewClockSeekAlignmentDeadlineMs",0);p(this,"playbackAttemptId",this.createPlaybackAttemptId("initial"));p(this,"lastPreviewSyncedPlayState",null);p(this,"lastPreviewSyncSignature",null);p(this,"lastSteadyPlaybackPreviewSyncAt",0);p(this,"previewSyncInteractionMode",null);p(this,"resourceCacheManager");p(this,"voiceLinkedTextRegenerationTimer",null);p(this,"pendingVoiceLinkedTextRegeneration",null);p(this,"historyRecordingSuppressionDepth",0);p(this,"activeStructureSession",null);p(this,"structureSessionDepth",0);p(this,"preserveEmptyTracksDepth",0);p(this,"playbackViewportFollowSuspended",!1);p(this,"isProgrammaticScrollChange",!1);this.config={duration:e.duration||Zt,zoom:e.zoom||Re.MEDIUM,currentTime:e.currentTime||0,playState:e.playState||"paused",container:e.container,theme:Xi(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 ag({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:zt.name,packageVersion:zt.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 Vn({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 ts(this.handleActionUndo.bind(this),this.handleActionRedo.bind(this),()=>{this.emitEvent("history_change",{canUndo:this.history.canUndo(),canRedo:this.history.canRedo()})}),this.timelineHistoryRecorder=new En(this.history),this.trackManager=new Oo,this.timelineStore=new ea({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new An(this.timelineStore),this.timelinePresentationAdapter=new jn,this.timelineTrackBridge=new Qn({onClipUpdate:(t,i,r)=>this.handleClipUpdate(t,i,r),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.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,s;if(!this.timelineStore){const a=((e=this.config)==null?void 0:e.currentTime)??0,o=((t=this.config)==null?void 0:t.playState)??"paused",l=((i=this.config)==null?void 0:i.speed)||1,c=((r=this.config)==null?void 0:r.zoom)||Re.MEDIUM,h=((s=this.config)==null?void 0:s.duration)||Zt;this.timelineStore=new ea({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new An(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new lg(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new jn),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new Qn({onClipUpdate:(e,t,i)=>this.handleClipUpdate(e,t,i),onClipAdd:this.handleClipAdd.bind(this),onClipRemove:this.handleClipRemove.bind(this),onClipSplit:this.handleClipSplit.bind(this),onClipSelect:this.handleClipSelect.bind(this),onTimeJump:this.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 cp),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 up({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 hp({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new rp({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||sp(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=Ue(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)},onTextLayoutCommit:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextLayout(t,i)},onTextLayoutResolved:(t,i)=>{this.isActivePreviewCallbackToken(e)&&this.commitPreviewTextResolvedLayout(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 Vn({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 ts(()=>{},()=>{})),this.timelineHistoryRecorder=new En(this.history)),this.timelineHistoryRecorder}withStructureSession(e){const t=this.activeStructureSession;if(t)return e(t);const i=new wp({trackCollection:this.getTrackCollection(),ensureTrackFromHistorySnapshot:this.ensureTrackFromHistorySnapshot.bind(this),removeClipGaps:this.removeClipGaps.bind(this),setPrimaryTrackMagnetEnabled:this.setPrimaryTrackMagnetEnabledFromHistory.bind(this),loadClipThumbnails:this.loadClipThumbnails.bind(this),addClipToTrack:(s,a)=>this.getTrackCollection().addClipToTrack(s,a),removeClip:s=>{const a=this.getTrackCollection();if(typeof a.removeClip=="function"){a.removeClip(s);return}this.tracks.forEach(o=>{var l;return(l=o.removeClip)==null?void 0:l.call(o,s)})},removeClipFromTrack:(s,a)=>this.getTrackCollection().removeClipFromTrack(s,a),updateClip:(s,a)=>{const o=this.getTrackCollection();if(typeof o.updateClip=="function"){o.updateClip(s,a);return}this.tracks.forEach(l=>{var c;return(c=l.updateClip)==null?void 0:c.call(l,s,a)})},moveClipToTrack:(s,a,o)=>{const l=this.getTrackCollection();if(typeof l.moveClipToTrack=="function")return l.moveClipToTrack(s,a,o);const c=l.findById(a),h=l.findById(o);return!(c!=null&&c.removeClip)||!(h!=null&&h.addClip)?!1:(c.removeClip(s.id),h.addClip(s),!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 s=e(i);return s instanceof Promise?s.finally(r):(r(),s)}catch(s){throw r(),s}}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 s=this.isExecutingHistoryAction??!1;this.isExecutingHistoryAction=!0;try{const a=r();return a instanceof Promise?a.then(o=>(this.isExecutingHistoryAction=s,o),o=>{throw this.isExecutingHistoryAction=s,o}):(this.isExecutingHistoryAction=s,a)}catch(a){throw this.isExecutingHistoryAction=s,a}}shouldSkipHistoryRecording(){return this.isExecutingHistoryAction||this.historyRecordingSuppressionDepth>0}withHistoryTransaction(e,t){return this.withHistoryBoundary("transaction",e,t)}get selectedClipId(){var t,i;const e=this.getTimelineStore();return((t=e.getPrimarySelectedClipId)==null?void 0:t.call(e))??((i=e.getSelectedClipId)==null?void 0:i.call(e))??null}set selectedClipId(e){var i;const t=this.getTimelineStore();if(typeof t.setPrimarySelectedClipId=="function"){t.setPrimarySelectedClipId(e);return}(i=t.setSelectedClipId)==null||i.call(t,e)}ensureConfigState(){return this.config||(this.config={duration:Zt,zoom:Re.MEDIUM,currentTime:0,playState:"paused",theme:Xi(),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(),s=this.getHorizontalContentWidth(),a=mg({time:e,zoom:i,scrollLeft:r,viewportWidth:t,contentWidth:s});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,s,a;const e=this.getViewportWidth(),t=this.getViewportHeight();(i=this.horizontalScrollbar)==null||i.resize(),(r=this.verticalScrollbar)==null||r.resize(),(s=this.horizontalScrollbar)==null||s.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 s=St(r);return s<=0||t!==s?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,s=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>=s||(r=c,s=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=s=>[s.trackId,s.clip.id,s.trackType,s.trackOrder,s.clip.startTime,s.clip.endTime,s.clip.startTimeAtSource,s.muted?1:0,s.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<Tg}syncPreviewSession(e){var d,u,g,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 s=this.getAutoAspectRatioClip(),a=Ue(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:s,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=(g=this.previewSession).setPendingState)==null||f.call(g,this.buildPreviewPendingState()),this.previewSession.sync({...r,autoAspectRatioClip:s,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)<=bg?(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(s=>s.clip.id);if(!wg(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,s,a,o;if(!((r=this.previewSession)!=null&&r.hasPreview()))return;if(!this.hasActiveTimelineVideoClip(e)){this.clearPendingPreviewState(),this.resetPreviewRuntimeState();return}(t!=="scrub"||((s=this.pendingPreviewState)==null?void 0:s.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(Ue(this.previewAspectRatio));e.handled&&(this.previewAspectRatio=e.aspectRatio,this.syncPreviewSession(),this.emitEvent("preview_aspect_ratio_change",{aspectRatio:this.getPreviewAspectRatio()}))}init(e){var i,r,s,a,o,l,c;if(this.isInitialized){N.warn("TimelineManager","TimelineManager has already been initialized");return}this.rootContainer=e,this.layout=Nd(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Ci,scrollbarSize:Jr}),this.layout.bodyViewport.addEventListener("scroll",this.bodyViewportScrollListener),(r=(i=this.layout.bodyCanvasHost).addEventListener)==null||r.call(i,"click",this.bodyCanvasHostClickListener),(a=(s=this.rootContainer)==null?void 0:s.addEventListener)==null||a.call(s,"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 ug(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new as(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 ta({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:pe,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new ta({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=>{N.error("TimelineManager","Failed to import draft data:",{error:d})})})}}createTrack(e,t,i,r,s,a){var u,g,f,m;if(!this.trackLayer)return N.error("TimelineManager","Track layer not initialized"),"";const o=this.trackManager.createTrack(e,t,i,r,s,a),l=o.id,c=_e(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()),(g=d.setDragOverlayLayer)==null||g.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,s,a,o,l;const t=this.getTrackCollection().findById(e);if(!t)return!1;if(t.getClips().length>0)return N.warn("TimelineManager","Cannot remove track with clips"),!1;if(((r=t.getRole)==null?void 0:r.call(t))==="primary")return N.warn("TimelineManager","Cannot remove primary track"),!1;const i=this.trackManager.removeTrack(e);return i&&((a=(s=t.getTrackGroup)==null?void 0:s.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,s;if(!((r=this.trackManager)!=null&&r.renameTrack))return!1;const i=this.trackManager.renameTrack(e,t);return i&&(this.getActiveStructureSession()?(s=this.getActiveStructureSession())==null||s.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}getTracks(){return this.getResolvedTracksSnapshot()}updateTrackInfoPanel(){this.trackInfoPanelController.update(this.getResolvedTracksSnapshot())}muteTrack(e,t){var r,s;if(!((r=this.trackManager)!=null&&r.muteTrack))return!1;const i=this.trackManager.muteTrack(e,t);return i&&(this.getActiveStructureSession()?(s=this.getActiveStructureSession())==null||s.markTrackLayoutMutation():(this.updateTrackInfoPanel(),this.syncPreviewSession())),i}isTrackMuted(e){return this.trackManager.isTrackMuted(e)}calculateTrackY(e){return Nt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return Pn(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=Ud(this.trackManager.getTracks(),this.getTrackContentTopOffset());for(const r of e){const s=this.getTrackCollection().findById(r.trackId);s&&((t=s.setTrackY)==null||t.call(s,r.y),(i=s.setTrackHeight)==null||i.call(s,r.height))}this.normalizeTrackGroupStackOrder(),this.updateViewportLayout()}removeEmptyTracksFromStructure(){var i,r,s;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),(s=(r=a.getTrackGroup)==null?void 0:r.call(a))==null||s.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 s,a,o,l;const i=(s=t.getId)==null?void 0:s.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,s;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&&((s=this.snapGuideLayer)==null||s.batchDraw())}showTrackInsertionPreview(e,t,i){this.getTrackCollection().forEach(s=>{var a;return(a=s.clearClipDropPreview)==null?void 0:a.call(s)}),this.ensureTrackInsertionPreviewLine()&&(this.trackInsertionPreviewY=this.resolveTrackInsertionPreviewY(e,t,i),this.refreshTrackInsertionPreview())}hideTrackInsertionPreview(){var e;this.trackInsertionPreviewY=null,this.trackInsertionPreviewLine&&(this.trackInsertionPreviewLine.visible(!1),(e=this.snapGuideLayer)==null||e.batchDraw())}resolveTrackInsertionPreviewY(e,t,i){const r=this.trackManager.getTracks(),s=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=Nt(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+_e(c.type)}}if(t==="top_of_type_region"&&a)return Nt(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Nt(r,o.id,this.getTrackContentTopOffset())+_e(o.type);if(!s)return e!=="audio"?this.getTrackContentTopOffset():Pn(r,this.getTrackContentTopOffset());const l=Nt(r,s.id,this.getTrackContentTopOffset());return e==="text"?this.getTrackContentTopOffset():e==="video"?l:l+_e(s.type)}updateViewportLayout(){var o;if(!this.layout||!this.stage||!this.timeline||!this.headerStage)return;const e=this.layout.bodyViewport.clientWidth,t=this.layout.bodyViewport.clientHeight,i=this.calculateTotalHeight(),r=Math.max(i,t),s=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(s),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",s=>{this.handleBodyBackgroundClick(s.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||ee.snapGuideLineColor}ensureSnapGuideLine(){if(!this.snapGuideLayer)return null;if(!this.snapGuideLine){const e=this.config.theme;this.snapGuideLine=de.createLine([0,0,0,this.calculateTotalHeight()],this.getSnapGuideAccentColor(),e.snapGuideLineWidth??1),this.snapGuideLine.name("timeline-snap-guide-line"),this.snapGuideLine.visible(!1),this.snapGuideLine.listening(!1),this.snapGuideLayer.add(this.snapGuideLine)}return this.snapGuideLine}refreshSnapGuideLine(e=!0){var r,s;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&&((s=this.snapGuideLayer)==null||s.batchDraw())}updateSnapGuideLine(e){var t;if(this.snapGuideTime=e,e===null||!this.getEnableClipSnap()){this.snapGuideLine&&(this.snapGuideLine.visible(!1),(t=this.snapGuideLayer)==null||t.batchDraw());return}this.ensureSnapGuideLine(),this.refreshSnapGuideLine()}handleBodyViewportScroll(){var t;const e=(t=this.layout)==null?void 0:t.bodyViewport;e&&this.syncScrollTop(e.scrollTop)}handleHorizontalDragAutoScroll(e){return this.syncScrollLeft(e),this.getScrollLeftState()}handleUnifiedWheel(e){const t=this.normalizeWheelDelta(e.deltaX,e.deltaMode,"x"),i=this.normalizeWheelDelta(e.deltaY,e.deltaMode,"y");if(e.metaKey||e.ctrlKey){const s=this.getPrimaryWheelDelta(t,i);if(s===0)return;e.preventDefault(),this.handleWheelZoom(s,e.clientX);return}if(e.shiftKey||this.isHorizontalWheelGesture(t,i)){const s=this.getHorizontalScrollDelta(t,i,e.shiftKey);if(s===0)return;e.preventDefault(),this.handleScrollChange(this.getScrollLeftState()+s);return}i!==0&&(e.preventDefault(),this.syncScrollTop(this.getScrollTopState()+i))}normalizeWheelDelta(e,t,i){if(!Number.isFinite(e)||e===0)return 0;if(t===Cg)return e*16;if(t===vg){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*Dr.SENSITIVITY_FACTOR),s=Math.max(Re.MIN,Math.min(Re.MAX,i*r));Math.abs(s-i)<Dr.CONVERGENCE_THRESHOLD||this.setZoomCenteredOnTimelinePointer(s,this.getWheelAnchorPointerX(t))}getWheelAnchorPointerX(e){var s;const t=(s=this.layout)==null?void 0:s.bodyViewport.getBoundingClientRect(),i=this.getViewportWidth();if(!t||i<=0)return 0;const 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()>=St(t)){if(this.setCurrentTime(0),!this.canPlay)return}else{N.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 s=this.getClips();i=Array.isArray(s)?s:[]}catch{return t}if(i.length===0)return t;const r=St(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 s=e.getPrimaryTrack();return((i=s==null?void 0:s.getId)==null?void 0:i.call(s))??null}const t=Array.isArray(this.tracks)?this.tracks.find(s=>{var a;return((a=s.getRole)==null?void 0:a.call(s))==="primary"}):null;return((r=t==null?void 0:t.getId)==null?void 0:r.call(t))??null}isPrimaryTrackId(e){var r,s,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=(s=this.trackManager)==null?void 0:s.getTrack)==null?void 0:a.call(s,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,s=t.orderedClips?[...t.orderedClips]:this.getStableStartOrderedClips(((c=r==null?void 0:r.getClips)==null?void 0:c.call(r))??[]);if(s.length===0)return[];const a=this.buildPrimaryTrackContinuousClips(s),o=new Set(t.forceClipIds??[]),l=[];return a.forEach((h,d)=>{const u=s[d];if(!u)return;const g=u.startTime!==h.startTime||u.endTime!==h.endTime;g&&l.push({clipId:u.id,previousState:u,newState:h}),(g||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 s=r.nextValue;if(this.ensureConfigState().zoom=s,this.syncZoomToScene(s),this.refreshScrollbarMetrics(),this.timeline){const a=this.timeline.getScrollLeft(),o=U.timeToPixels(i,t),c=U.timeToPixels(i,s)-o+a;this.timeline.setScrollLeft(c),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())})}this.emitEvent("zoom_change",{zoom:s})}setZoomByInteraction(e){const t=this.timeline;if(!t){this.setZoomCenteredOnPlayhead(e);return}const i=t.getPointerXInTimeline();if(t.hasPointerInTimeline()&&i!==null){this.setZoomCenteredOnTimelinePointer(e,i);return}this.setZoomCenteredOnPlayhead(e)}setZoomCenteredOnTimelinePointer(e,t){if(!this.timeline){this.setZoom(e);return}const i=this.getZoomState(),r=this.timeline.getScrollLeft(),s=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(s,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),s=this.clipThumbnailLoadStates.get(e.id);if((s==null?void 0:s.signature)===r){if(s.promise)return s.promise;if(s.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}),N.debugLazy("TimelineManager",()=>"关键帧加载完成",()=>({clipId:e.id,count:l.length})),!0):!1}catch(c){return N.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,s=!!this.trackManager;for(const a of e){const o=s?this.resolveBatchClipConfig(a,i,r):a,l=await this.addClipInternal(o);if(t.push(l),!s||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",s=t.get(r)||this.resolveBatchAppendTrackId(r);if(!s)return e;const a=i.get(s)??this.getTrackTimelineExtentById(s);return{...e,trackId:s,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?ns(t.getClips()):0}async addClipInternal(e){return this.withStructureSession(async()=>{var C;let t=e.startTime;t===void 0&&(t=this.getCurrentTime());const i=e.type||"video",r=i==="text",s=e.src??"",a=e.duration??(r?la: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(s,{registry:this.sourceMediaRegistry,cacheKey:this.buildSourceMediaKey(e)}),h<=0&&(h=c)}catch(v){N.error("TimelineManager","Failed to get video duration:",{error:v}),h=c}!r&&h>0&&this.sourceMediaRegistry.primeDuration(this.buildSourceMediaKey(e),h);let d=e.thumbnails;const u=e.id||`clip_${o}_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=cs({id:u,type:i,externalId:e.externalId,src:s,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?qe(e.visualTransform??vu(ji(this.getPreviewAspectRatio()).height)):i==="video"?xe(e.visualTransform):e.visualTransform,separatedAudioClipId:e.separatedAudioClipId,separatedFromVideoClipId:e.separatedFromVideoClipId,volume:e.volume??1,textContent:e.textContent??(r?"默认文本":void 0),textStyle:r?{...ce(e.textStyle),anchorVersion:((C=e.textStyle)==null?void 0:C.anchorVersion)??1}:void 0,textResolvedLayout:r?e.textResolvedLayout:void 0,ttsSourceTextClipId:e.ttsSourceTextClipId,ttsVoiceId:e.ttsVoiceId,ttsVoiceName:e.ttsVoiceName,ttsFollowTextUpdates:e.ttsFollowTextUpdates});N.debugLazy("TimelineManager",()=>"添加的片段",()=>({clipId:g.id,type:g.type,startTime:g.startTime,duration:g.duration}));const f=()=>{var _;if(e.trackId){const w=this.getTrackCollection().findById(e.trackId);if(w){if(this.registerPreviewAutoAspectRatioClip(g),(_=w.addClip)==null||_.call(w,g),Ui({applied:!0,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const D=e.trackId;this.getTimelineHistoryRecorder().recordAddClip(g,D,this.cloneTrackSnapshot(D),this.getTrackRestoreAnchor(D))},applyEffects:()=>{}}),this.shouldNormalizePrimaryTrackForTrackIds([e.trackId])){const D=this.getActiveStructureSession();D&&this.normalizePrimaryTrackInSession(D)}return this.primeOrLoadClipThumbnails(g),g.id}}const v=this.getTimelineCommands().planTrackPlacement(g,this.getTracksSortedByOrder()),S=this.getTrackCollection(),T=Pp({clip:g,placement:v,trackCollection:S,createTrack:this.createTrack.bind(this)});Ui({applied:T,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordHistory:()=>{const w=this.resolveTrackIdByClipId(g.id);this.getTimelineHistoryRecorder().recordAddClip(g,w,w?this.cloneTrackSnapshot(w):null,w?this.getTrackRestoreAnchor(w):null)},applyEffects:()=>{}});const k=this.resolveTrackIdByClipId(g.id);if(this.shouldNormalizePrimaryTrackForTrackIds([k])){const w=this.getActiveStructureSession();w&&this.normalizePrimaryTrackInSession(w)}return this.primeOrLoadClipThumbnails(g),g.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=>{Ui({applied:Wn(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 s of t){const a=this.getTimelineCommands().prepareRemoveClip(s,this.tracks);a.exists&&(r=Wn(this.getTrackCollection(),a,s)||r)}})}),r?(Oi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Bi({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)}Bi({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 s=()=>{this.withSplitOperation(()=>{r.call(i.track,t)})};this.shouldNormalizePrimaryTrackForTrackIds([i.trackId])?this.withHistoryTransaction("split_primary_track_clip",s):s(),Bi({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(),Bi({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 s=r.clipId;if(!s)return;const a=this.findClipById(s);if(!a||a.type!=="video"&&a.type!=="audio")return;if(i.add(s),r.phase==="failed"&&r.role==="current"){this.applyTimelineClipMediaStatus(s,"failed","媒体丢失");return}(r.phase==="active"||r.phase==="primed")&&!!r.actualSource&&this.clearTimelineClipMediaStatus(s)}),Array.from(t).forEach(r=>{if(i.has(r))return;this.findClipById(r)||t.delete(r)})}applyTimelineClipMediaStatus(e,t,i){const r=this.getFailedPreviewClipIds(),s=this.findClipById(e);if(!s){r.delete(e);return}if(s.mediaStatus===t&&s.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 s,a,o,l;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(kt(e.mode)&&t===Le.width&&i===Le.height){const c=(s=this.getAutoAspectRatioClip())==null?void 0:s.clip,h=(a=c==null?void 0:c.style)==null?void 0:a.sys_width,d=(o=c==null?void 0:c.style)==null?void 0:o.sys_height;typeof h=="number"&&h>0&&typeof d=="number"&&d>0&&(t=h,i=d)}const r=ji({width:t,height:i});return{width:r.width,height:r.height,aspectRatio:`${r.width}:${r.height}`,mode:e.mode,textPreviewFont:((l=this.config)==null?void 0:l.textPreviewFont)??void 0}}resolveTextClipExportLayout(e,t){var i;return e.textResolvedLayout?e.textResolvedLayout:Dp(e,t,((i=this.config)==null?void 0:i.textPreviewFont)??null)??void 0}getExportCoverUrl(e){var r;let t=null,i=null;for(const s of e)for(const a of s.clips)if(a.type==="video"){if(!t||!i){t=s,i=a;continue}if(a.startTime<i.startTime){t=s,i=a;continue}a.startTime===i.startTime&&s.order<t.order&&(t=s,i=a)}return((r=i==null?void 0:i.thumbnails)==null?void 0:r[0])||""}exportTimeline(){const e=this.getExportComposition(),t=this.getResolvedTracksSnapshot().slice().sort((r,s)=>r.order-s.order).map(r=>{const s=r.clips.map(a=>({id:a.id,type:a.type,externalId:a.externalId,src:a.src,name:a.name,isMuted:a.isMuted??!1,startTime:Math.round(a.startTime),duration:Math.round(a.duration),endTime:Math.round(a.endTime),startTimeAtSource:Math.round(a.startTimeAtSource),endTimeAtSource:Math.round(a.endTimeAtSource),sourceDuration:Math.round(a.sourceDuration),thumbnails:a.thumbnails,visualTransform:a.type==="text"?qe(a.visualTransform):a.type==="video"?xe(a.visualTransform):void 0,separatedAudioClipId:a.separatedAudioClipId,separatedFromVideoClipId:a.separatedFromVideoClipId,volume:a.volume??1,textContent:a.textContent,textStyle:a.textStyle,textResolvedLayout:a.type==="text"?this.resolveTextClipExportLayout(a,e):void 0,ttsSourceTextClipId:a.ttsSourceTextClipId,ttsVoiceId:a.ttsVoiceId,ttsVoiceName:a.ttsVoiceName,ttsFollowTextUpdates:a.ttsFollowTextUpdates})).sort((a,o)=>a.startTime-o.startTime);return{id:r.id,type:r.type,name:r.name||"未命名轨道",order:r.order,role:r.role??"normal",isMuted:r.isMuted??!1,clips:s}}),i=this.getExportCoverUrl(t);return{version:this.getVersion(),exportTime:Date.now(),coverUrl:i,composition:e,tracks:t}}async importTimeline(e){if(!e||!e.composition||!e.tracks){N.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,s=[...e.tracks].sort((c,h)=>c.order-h.order),a=this.resolveImportedTrackRoles(s);let o;for(const c of s){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 s){const h=r.get(c.id);if(h)for(const d of c.clips)try{let u=d.separatedAudioClipId;u&&l.has(u)&&(u=l.get(u));let g=d.separatedFromVideoClipId;g&&l.has(g)&&(g=l.get(g));const f={id:d.id,type:d.type,externalId:d.externalId,src:d.src,name:d.name,isMuted:d.isMuted,startTime:d.startTime,duration:d.duration,startTimeAtSource:d.startTimeAtSource,endTimeAtSource:d.endTimeAtSource,sourceDuration:d.sourceDuration,thumbnails:d.thumbnails,visualTransform:d.visualTransform,separatedAudioClipId:u,separatedFromVideoClipId:g,volume:d.volume,textContent:d.textContent,textStyle:d.textStyle,textResolvedLayout:d.textResolvedLayout,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}),N.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 s of e){const a=s.role==="primary"&&!i?"primary":"normal";a==="primary"&&(i=!0),t.set(s.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 zt.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,s=((l=this.stage)==null?void 0:l.width())||0,a=s-pe*2;N.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:s,availableWidth:a}));const o=Math.min(a/r,Re.MAX);if(this.setZoom(o),this.timeline){const c=e.reduce((h,d)=>d.startTime<h.startTime?d:h);this.scrollToClip(c.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){var i;this.previewSyncInteractionMode=t,this.previewClockSeekAlignmentTargetTime=t==="seek"?this.clampPlaybackSeekTime(e):null,this.previewClockSeekAlignmentDeadlineMs=t==="seek"?Date.now()+kg: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 s=this.selectedClipId===e.id;Qd({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)}),s&&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}),Oi({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)&&Oi({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){eu(e,t,!!this.thumbnailProvider)&&this.loadClipThumbnails(e).catch(i=>{N.warn("TimelineManager","Error reloading clip thumbnails during update:",{error:i,clipId:e.id})})}updateCanPlayState(){const e=this.getClips(),t=this.getCurrentTime(),i=tu(e,t),r=this.canPlay;this.canPlay=iu({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:St(e)||1,setCanPlay:s=>{this.canPlay=s},pauseTimeline:this.pause.bind(this),setCurrentTime:this.setCurrentTime.bind(this),emitCanPlayChange:s=>{this.emitEvent("can_play_change",{canPlay:s})}}),r!==this.canPlay&&N.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:"",s=i.trim().length>0?i:r.trim().length>0?r:"";if(s.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:s}}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 s;this.pendingVoiceLinkedTextRegeneration&&this.pendingVoiceLinkedTextRegeneration.clipId!==e&&(this.voiceLinkedTextRegenerationTimer!==null&&(clearTimeout(this.voiceLinkedTextRegenerationTimer),this.voiceLinkedTextRegenerationTimer=null),this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{N.error("TimelineManager","Failed to flush pending linked voice regeneration",{error:a,clipId:e})})),this.voiceLinkedTextRegenerationTimer!==null&&clearTimeout(this.voiceLinkedTextRegenerationTimer),this.pendingVoiceLinkedTextRegeneration={clipId:e,originalClip:((s=this.pendingVoiceLinkedTextRegeneration)==null?void 0:s.clipId)===e?this.pendingVoiceLinkedTextRegeneration.originalClip:{...t},nextText:i,generateVoiceBatch:r},this.voiceLinkedTextRegenerationTimer=setTimeout(()=>{this.voiceLinkedTextRegenerationTimer=null,this.flushPendingVoiceLinkedTextRegeneration().catch(a=>{N.error("TimelineManager","Failed to regenerate linked voice audio clips",{error:a,clipId:e})})},ca)}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,s=i?this.getTimelineHistoryRecorder().createClipUpdateAction(i,e.originalClip):null;await this.withHistoryTransaction("update_text_with_voice_regeneration",async()=>{s&&this.getTimelineHistoryRecorder().recordAction(s),await this.regenerateVoiceLinkedAudioClips(e.clipId,r,e.generateVoiceBatch)})}applyGeneratedAudioClipResult(e,t,i,r,s){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:s})}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(s=>s.id!==t.id&&t.startTime<s.endTime&&r>s.startTime)}doesClipGroupOverlapOnTrack(e,t,i=new Set){const r=this.getTrackCollection().findById(e);if(!r)return!1;const s=r.getClips().filter(a=>!i.has(a.id));return t.some(a=>{const o=a.startTime+a.duration;return s.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 s=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??s++,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(s=>s.newTrackCount===0).sort((s,a)=>s.score-a.score)[0];if(i)return i.startIndex;if(e==="text"){const s=t.filter(a=>a.startIndex<0).sort((a,o)=>a.newTrackCount!==o.newTrackCount?a.newTrackCount-o.newTrackCount:a.score-o.score)[0];if(s)return s.startIndex}return((r=t.slice().sort((s,a)=>s.score-a.score)[0])==null?void 0:r.startIndex)??null}buildClipboardPasteGroupPlacementClips(e,t,i,r){const s=new Map(t.items.map(a=>[a.sourceClipId,a]));return e.sourceClipIds.map(a=>{const o=s.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 s;return((s=r.trackSnapshot)==null?void 0:s.type)===t}).sort((r,s)=>{var a,o;return(((a=r.trackSnapshot)==null?void 0:a.order)??Number.MAX_SAFE_INTEGER)-(((o=s.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 s=new Map;if(e.length===0)return s;this.ensureClipboardPasteSourceTracks(t,e[0].type);const a=[...this.getResolvedTracksSnapshot()].filter(T=>{var k;return T.type===((k=e[0])==null?void 0:k.type)}).sort((T,k)=>T.order-k.order);if(a.length===0){const T=this.createTrack(e[0].type);T&&s.set(e[0].key,T);for(let k=1;k<e.length;k+=1){const _=this.createTrack(e[k].type,void 0,e[0].type==="audio"?"bottom_of_type_region":"top_of_type_region");_&&s.set(e[k].key,_)}return s}const o=new Set(e.flatMap(T=>T.clipIds)),l=e.map(T=>{const k=this.buildClipboardPasteGroupPlacementClips(T,t,i,r);if(k.length===0)return null;const _=this.resolvePreferredTrackIndexForPasteGroup(T,a,Math.min(T.sourceOrder,Math.max(a.length-1,0)));return{...T,preferredTrackIndex:_,clips:k}}).filter(T=>T!==null);if(l.length===0)return s;const c=l.map(T=>T.preferredTrackIndex),h=Math.min(...c),d=a.length,u=-l.length,g=[];for(let T=u;T<=d;T+=1){let k=!0,_=0,w=0;for(let D=0;D<l.length;D+=1){const x=l[D];if(!x)continue;const R=T+D;if(_+=Math.abs(R-x.preferredTrackIndex),R<0||R>=a.length){w+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[R].id,x.clips,o)){k=!1;break}}k&&(_+=w*.1,_+=Math.abs(T-h)*ha.ANCHOR_INDEX_WEIGHT,g.push({startIndex:T,score:_,newTrackCount:w}))}const f=this.selectBestClipboardPasteStartIndex(l[0].type,g);if(f===null)return s;const m=Math.max(0,-f),C=Math.max(0,f+l.length-a.length);m>0&&this.createTracksForTypeBoundary(l[0].type,m,"before"),C>0&&this.createTracksForTypeBoundary(l[0].type,C,"after");const v=[...this.getResolvedTracksSnapshot()].filter(T=>{var k;return T.type===((k=l[0])==null?void 0:k.type)}).sort((T,k)=>T.order-k.order),S=f+m;return l.forEach((T,k)=>{const _=v[S+k];_&&s.set(T.key,_.id)}),s}resolvePreferredTrackIndexForPasteGroup(e,t,i){if(e.sourceTrackId){const r=t.findIndex(s=>s.id===e.sourceTrackId);if(r!==-1)return r}if(Number.isFinite(e.sourceTrackOrder)){const r=t.findIndex(s=>s.order>=e.sourceTrackOrder);return r!==-1?r:t.length}return i}resolveClipboardPasteTrackAssignments(e,t,i){const r=this.buildClipboardPasteGroups(e,t),s=new Map;r.forEach(o=>{const l=s.get(o.type)??[];l.push(o),s.set(o.type,l)});const a=new Map;return s.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 s=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(s),o=new Map(a.map(c=>[c.requestId,c]));let l=0;s.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"||!Me(e))return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(s=>Me(s))))return[e];const r=t.filter(s=>Me(s));return r.some(s=>s.id===e.id)?r:[e]}async handleVoiceGenerateAction(e,t,i,r,s){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 s(d),m=new Map(f.map(C=>[C.requestId,C]));for(const C of d){const v=m.get(C.requestId);if(!v)continue;const S=c.find(w=>w.id===C.sourceTextClipId);if(!S)continue;const T=this.normalizeGeneratedAudioDuration(v.duration),k=S.textContent??S.name??"";this.syncTextClipDurationToAudio(S.id,T);const _=await this.addClip({type:"audio",src:v.audioSrc,name:this.buildGeneratedAudioClipName(v.voiceName),textContent:k,startTime:S.startTime,duration:T,startTimeAtSource:0,endTimeAtSource:T,sourceDuration:T,ttsSourceTextClipId:S.id,ttsVoiceId:v.voiceId,ttsVoiceName:v.voiceName,ttsFollowTextUpdates:r});u.push(_)}if(u.length===0)throw new Error("生成音频失败:未返回音频结果")}),u.length===1){this.scrollToClip(u[0],{selectClip:!0,setCurrentTime:!0});return}const g=u[0]??null;this.scrollToClip(g,{setCurrentTime:!0}),this.setSelection(u,{preferredPrimaryClipId:g});return}if(t.type!=="audio"||!Me(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 s(l),h=new Map(c.map(u=>[u.requestId,u])),d=new Map;if(l.some(u=>!h.has(u.requestId)))throw new Error("替换音色失败:未返回音频结果");for(const u of l){const g=h.get(u.requestId);if(!g||!u.targetAudioClipId)continue;const f=a.find(C=>C.id===u.targetAudioClipId);if(!f)continue;const m=this.resolveTtsAudioVoiceGenerationSource(f);if(this.applyGeneratedAudioClipResult(u.targetAudioClipId,m.persistedSourceTextClipId,m.text,g,r),this.relocateClipIfNeeded(u.targetAudioClipId),m.persistedSourceTextClipId){const C=d.get(m.persistedSourceTextClipId)??0;d.set(m.persistedSourceTextClipId,Math.max(C,g.duration))}}d.forEach((u,g)=>{this.syncTextClipDurationToAudio(g,u)}),this.handleClipChange()})}primeOrLoadClipThumbnails(e,t={}){if(!(!this.thumbnailProvider||e.type!=="video")&&!((t.allowPrimeExisting??!0)&&this.markClipThumbnailLoadCompleted(e)))try{N.debugLazy("TimelineManager",()=>"开始加载片段封面",()=>({clipId:e.id})),this.loadClipThumbnails(e,{force:t.force})}catch(i){N.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 Lr.buildSourceKey(e)}buildClipThumbnailResourceKey(e){return Lr.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,s=i?this.getTrackRestoreAnchor(i):null;this.withStructureSession(a=>{nu({clip1:e,clip2:t,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordSplitClip:(o,l)=>{this.getTimelineHistoryRecorder().recordSplitClip(o,l,i,r,s)},emitClipUpdated:o=>{this.emitEvent("clip_updated",{clip:o})},emitClipAdded:o=>{this.emitEvent("clip_added",{clip:o})},applyEffects:()=>Oi({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=ru(e);t.shouldJumpToTime&&t.jumpTime!==null?(this.setCurrentTime(t.jumpTime),this.emitEvent("clip_selected",{clip:e}),N.debugLazy("TimelineManager",()=>"Empty track clicked, jumping to time",()=>({time:e.startTime}))):t.shouldSelectClip&&this.selectClip(e.id,e)}handleActionUndo(e){N.debugLazy("TimelineManager",()=>"Undo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new In(t.createHistoryExecutionTarget()).executeUndo(e)})})}handleActionRedo(e){N.debugLazy("TimelineManager",()=>"Redo action",()=>({type:e==null?void 0:e.type})),this.withHistoryBoundary("replay",()=>{this.withStructureSession(t=>{new In(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=kp({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 s=this.getStableStartOrderedClips(i),a=s.findIndex(l=>l.startTime>=e.startTime),o=[...s];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,g;N.debugLazy("TimelineManager",()=>"检测到 clip 重叠,需要创建新轨道",()=>({clipId:e.id,currentTrackId:t}));const r=this.getTrackCollection();if(!r.findById(t))return;const s=e.type,a=this.trackManager.getTracksByType(s).length+1,o=`${xg(s)}轨道 ${a}`,l=this.createTrack(s,o);if(!l)return;const c=((d=(h=r.findById(l))==null?void 0:h.getId)==null?void 0:d.call(h))||((g=(u=r.getLastTrack())==null?void 0:u.getId)==null?void 0:g.call(u))||l;this.moveClipToTrackWithHistorySnapshot(e.id,c,i??null,e),this.cleanupEmptyTracks()}handleClipCrossTrackPreview(e,t,i){const r=this.resolveCrossTrackPreviewDestination(e,t,i);return r.status==="existing_track"?(this.showClipDropPreview(e,r.targetTrackId),r.targetTrackId===i?"self":"external"):r.status==="new_track_insertion"?(this.showTrackInsertionPreview(r.trackType,r.insertionPlacement,r.referenceTrackId),"external"):(this.clearAllTrackDropPreviews(),"clear")}handleClipCrossTrack(e,t,i,r){N.debugLazy("TimelineManager",()=>"处理跨轨道拖拽",()=>({clipId:e.id,targetTrackY:i,currentTrackId:r}));const s=this.resolveCrossTrackMoveDestination(e,i,r);return s.status==="blocked"?(this.clearAllTrackDropPreviews(),!1):s.status==="same_track"?(N.debugLazy("TimelineManager",()=>"目标轨道与源轨道相同,无需移动"),this.showClipDropPreview(e,r),!1):(N.debugLazy("TimelineManager",()=>"跨轨拖拽命中可用轨道",()=>({clipId:e.id,targetTrackId:s.targetTrackId})),this.showClipDropPreview(e,s.targetTrackId),this.moveClipToTrackWithHistorySnapshot(e.id,s.targetTrackId,t,e))}getPlayState(){return this.getPlayStateState()}setDuration(e){this.setDurationState(e),this.timeline&&this.timeline.setDuration(e),this.updateViewportLayout()}getDuration(){return this.getDurationState()}getRenderedHeight(){return this.getTimeScaleHeight()+this.calculateTotalHeight()+Jr}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,s;const e=((i=(t=this.selectionStore)==null?void 0:t.getPrimarySelectedClipId)==null?void 0:i.call(t))??((s=(r=this.selectionStore)==null?void 0:r.getSelectedClipId)==null?void 0:s.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(s=>s!==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=[],s=this.getCurrentTime();if(await this.withHistoryTransaction("paste_clipboard_clips",async()=>{for(const o of e.items){const l=this.buildClipboardPasteClipConfig(o,s,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 s=this.getTimelineCommands().prepareRemoveClip(r,this.tracks);return!s.exists||!s.clip?null:(s.trackId&&!t.has(s.trackId)&&t.set(s.trackId,{sourceTrackId:s.trackId,trackSnapshot:this.cloneTrackSnapshot(s.trackId),trackRestoreAnchor:this.getTrackRestoreAnchor(s.trackId)}),{sourceClipId:r,sourceTrackId:s.trackId,clip:this.cloneClipForClipboard(s.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:ra(e.style),visualTransform:e.visualTransform?{...e.visualTransform}:void 0,textStyle:e.textStyle?{...e.textStyle}:void 0}}buildClipboardPasteClipConfig(e,t,i){const r=e.clip,s=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:ra(r.style),visualTransform:r.visualTransform?{...r.visualTransform}:void 0,separatedAudioClipId:s,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}`,s=i.get(r);if(s)return s;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,s=this.getClips().find(a=>a.id===e);!s||!this.timeline||(this.timeline.scrollToClip(s),this.runProgrammaticScrollChange(()=>{this.handleScrollChange(this.timeline.getScrollLeft())}),r&&this.setCurrentTime(s.startTime),i&&this.selectClip(e))}getSelectedClip(){return this.getPrimarySelectedClip()}getPrimarySelectedClip(){return this.getSelectedClips()[0]??null}getSelectedClips(){const e=this.getSelectedClipIds();if(e.length===0)return[];const t=new Map(this.getClips().map(i=>[i.id,i]));return e.map(i=>t.get(i)||null).filter(i=>i!==null)}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=Ue({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 Do,r=t.generateVoiceBatch,s=r,a=r?async c=>{i.setVoiceGenerationBusy(!0);try{return await r(c)}finally{i.setVoiceGenerationBusy(!1)}}:void 0;i.init({container:e,theme:this.config.theme,getPrimarySelectedClip:()=>this.getPrimarySelectedClip(),getSelectedClips:()=>this.getSelectedClips(),voiceCatalog:t.voiceCatalog??[],updateClip:(c,h)=>{const d=this.findClipById(c),u=d?{...d}:null,g=typeof h.textContent=="string"?h.textContent:null;if(s&&(u==null?void 0:u.type)==="text"&&g!==null&&g!==u.textContent&&this.hasVoiceLinkedAudioClipsToRegenerate(c)&&(u==null?void 0:u.type)==="text"){this.withHistoryBoundary("suppressed",()=>{this.updateClip(c,h)}),this.handleClipChange(),this.scheduleVoiceLinkedTextRegeneration(c,u,g,s);return}this.updateClip(c,h),this.handleClipChange()},onGenerateVoice:async(c,h,d)=>{if(!a)throw new Error("未配置音色生成回调");await this.handleVoiceGenerateAction(i,c,h,d,a)}});const o=()=>i.updateFromExternal(),l=(c,h)=>{var g;const d=new Set(this.getSelectedClipIds()),u=this.getPrimarySelectedClip();d.size===0&&(u!=null&&u.id)&&d.add(u.id),(g=h==null?void 0:h.clip)!=null&&g.id&&d.has(h.clip.id)&&i.updateFromExternal()};return this.on("selected_clip_change",o),this.on("clip_updated",l),this.mountManager.register("clipConfig",()=>{this.off("selected_clip_change",o),this.off("clip_updated",l),i.destroy()}),i.update(),i}getPreviewBackendType(){return this.previewSession?this.resolvedPreviewBackend:this.resolveConfiguredPreviewBackend()}hasAttachedPreview(){return this.getPreviewRuntimeController().hasAttachedPreview()}getPreviewAspectRatio(){return Ue(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:zt.name,packageVersion:zt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=Ue({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={...Le},(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),s=r.findIndex(c=>c.id===i);if(s===-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-s)-Math.abs(h.index-s);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 s=!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?(s&&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,s=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,s),!0):!1}async applySelectedClipAudioAction(e){const t=this.getSelectedClips().filter(s=>s.type==="video"),i=e==="separate"?t.filter(s=>this.canSeparateClipAudio(s.id)):t.filter(s=>this.canRestoreClipAudio(s.id));if(i.length===0)return!1;if(i.length===1){const[s]=i;return e==="separate"?!!await this.separateClipAudio(s.id):this.restoreClipAudio(s.id)}let r=0;return await this.withHistoryTransaction(`selected_clips_audio_${e}`,async()=>{if(e==="restore"){for(const s of i)this.restoreClipAudio(s.id)&&(r+=1);return}for(const s of i)await this.separateClipAudio(s.id)&&(r+=1)}),r>0}moveClipToTrack(e,t){return this.moveClipToTrackWithHistorySnapshot(e,t,null)}moveClipToTrackWithHistorySnapshot(e,t,i,r=null){const s=this.getTimelineCommands().prepareMoveClipToTrack(e,t,this.tracks);if(s.status==="missing_source_track")return N.warn("TimelineManager",`片段不在任何轨道中: ${e}`),!1;if(s.status==="noop")return N.debugLazy("TimelineManager",()=>`源轨道和目标轨道相同,无需移动: ${e}`),!0;if(s.status==="missing_target_track")return N.warn("TimelineManager",`目标轨道不存在: ${t}`),!1;if(s.status==="track_type_mismatch")return N.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(s.status!=="ready")return!1;const a=this.shouldNormalizePrimaryTrackForTrackIds([s.sourceTrackId,s.targetTrackId]),o=()=>this.withStructureSession(l=>{const{sourceTrackId:c,targetTrackId:h}=s,d=i?{...i}:{...s.clip},u=r?{...r}:{...s.clip},g=this.cloneTrackSnapshot(c),f=this.cloneTrackSnapshot(h),m=this.getTrackRestoreAnchor(c),C=this.getTrackRestoreAnchor(h),v=_p({command:{...s,clip:u},trackCollection:this.getTrackCollection()}),S=this.getClips().find(T=>T.id===e)??null;return su({applied:v,clipId:e,sourceTrackId:c,targetTrackId:h,clipBefore:d,clipAfter:S??d,sourceTrackSnapshot:g,targetTrackSnapshot:f,isExecutingHistoryAction:this.shouldSkipHistoryRecording(),recordMoveClipBetweenTracks:(T,k,_,w,D,x,R)=>{this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks(T,k,_,w,D,x,R,m,C)},applyEffects:()=>{}})?(a&&this.normalizePrimaryTrackInSession(l),this.clearAllTrackDropPreviews(),!0):!1});return a?this.withHistoryTransaction("move_primary_track_clip_between_tracks",o):o()}getTrackTotalDuration(){return zn(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,s,a,o,l,c,h,d,u,g,f,m,C;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:(s=r.bodyCanvasHost).removeEventListener)==null||a.call(s,"click",this.bodyCanvasHostClickListener);const e=(l=(o=this.stage)==null?void 0:o.container)==null?void 0:l.call(o);e&&this.stageMouseDownListener&&((c=e.removeEventListener)==null||c.call(e,"mousedown",this.stageMouseDownListener)),(d=(h=this.rootContainer)==null?void 0:h.removeEventListener)==null||d.call(h,"wheel",this.rootWheelListener),(u=this.horizontalScrollbar)==null||u.destroy(),(g=this.verticalScrollbar)==null||g.destroy(),(f=this.playhead)==null||f.destroy(),(m=this.timeline)==null||m.destroy(),(C=this.stage)==null||C.destroy(),this.rootContainer&&(this.rootContainer.innerHTML=""),this.getEventDispatcher().clear()}initKeyboardShortcuts(){var e;this.rootContainer&&(this.mountManager||(this.mountManager=new ia),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new Tp({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,s=t.filter(a=>a.externalId===e).map(a=>a.id);for(let a=0;a<s.length;a+=1){const o=s[a];if(r.has(o))continue;r.add(o);const l=i.get(o);l&&(l.separatedAudioClipId&&!r.has(l.separatedAudioClipId)&&s.push(l.separatedAudioClipId),l.separatedFromVideoClipId&&!r.has(l.separatedFromVideoClipId)&&s.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 s=this.getTimelineCommands().findClipById(this.tracks,r),a=s==null?void 0:s.clip;if(a&&e>=a.startTime&&e<a.endTime)return s}return null}handleClipToggleSelection(e){this.toggleSelection(e)}handleSetSingleSelection(e){this.setSelection([e],{preferredPrimaryClipId:e})}getMultiDragClipIds(e){return this.selectionStore.isSelected(e)&&this.selectionStore.getSelectionCount()>1?this.selectionStore.getSelectedClipIds():null}handleMultiDragMove(e){const t=this.ensureMultiDragSession(e);if(!t)return!1;try{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 s=new Set(i);let a=0;for(const h of this.tracks){const d=(o=h.getId)==null?void 0:o.call(h);!d||s.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 s=(i=r.getId)==null?void 0:i.call(r);if(!s)continue;e.selectedClipIds.some(o=>{var l;return((l=e.clips.get(o))==null?void 0:l.trackId)===s})&&t.add(s)}return[...t]}resetMultiDragSession(){this.multiDragSession=null}handleMultiDragInteractionEnd(){this.clearMultiDragOverlayState(),this.normalizeTrackGroupStackOrder(),this.resetMultiDragSession()}syncMultiDragOverlayState(e,t){const i=new Map;for(const r of e.selectedClipIds){const s=e.clips.get(r);if(!s)continue;const a=i.get(s.trackId);a?a.push(r):i.set(s.trackId,[r])}i.forEach((r,s)=>{var o;const a=this.getTrackCollection().findById(s);(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 s of t){const a=this.findTrackByClipId(s),o=((r=a==null?void 0:a.getId)==null?void 0:r.call(a))??this.resolveTrackIdByClipId(s),l=a==null?void 0:a.getClips().find(h=>h.id===s);if(!o||!l)continue;const c=s===e.draggedClipId?this.restoreDraggedClipSnapshot(l,e.deltaTime):{...l};i.set(s,{clipId:s,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 s=e.clips.get(r);if(!s||s.trackId===t.currentTrackId)continue;const a=this.getTrackCollection().findById(s.trackId);if(!(a!=null&&a.updateClipPosition))continue;const o=Math.max(0,s.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((s,a)=>(s.order??0)-(a.order??0));for(const s of r){const a=i.get(s.type)??[];a.push(s.id),i.set(s.type,a),t.set(s.id,s.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)??[],s=i.startTime+i.duration;return r.some(a=>a.id!==i.id&&i.startTime<a.startTime+a.duration&&s>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,s){const a=e.orderedTrackIdsByType.get(i)??[];if(!a.includes(t)){if(r==="before_track"&&s){const o=a.indexOf(s);o>=0?a.splice(o,0,t):a.unshift(t)}else if(r==="after_track"&&s){const o=a.indexOf(s);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)??[],s=r.indexOf(i);if(s===-1)return null;const o=r.map((l,c)=>({trackId:l,index:c,distance:Math.abs(c-s)})).filter(({trackId:l})=>l!==i).sort((l,c)=>{if(l.distance!==c.distance)return l.distance-c.distance;const h=l.index>s?0:1,d=c.index>s?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 s=this.createTrack(t.type,void 0,"after_track",i);if(s)return this.registerMultiDragPlacementTrack(e,s,t.type,"after_track",i),s;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 s=[],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),g=i(d,u);if(!g)continue;if(r.compactSameTrackPrimary&&this.getEnablePrimaryTrackMagnet()&&g===d.trackId&&this.isPrimaryTrackId(d.trackId)){c=d.trackId,l.set(d.clipId,d.clip),o.set(d.clipId,u);continue}let f=g;if(!(this.doesMultiDragPlacementOverlap(a,g,u)&&(f=this.resolveMultiDragOverlapTargetTrackId(a,u,g),!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),s.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&&s.push(...this.compactPrimaryTrackAfterMultiDrag(c,o,l)),s.length>0&&this.getTimelineHistoryRecorder().recordClipUpdate(s[0].newState,void 0,s),!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),s=this.getStableStartOrderedClips(((d=r==null?void 0:r.getClips)==null?void 0:d.call(r))??[]);if(s.length===0)return[];const a=new Map(s.map(u=>[u.id,u])),o=new Map(a);i.forEach((u,g)=>{o.set(g,u)});const l=this.buildPrimaryTrackMultiDragOrderedClips(s,t),c=this.buildPrimaryTrackContinuousClips(l),h=[];return c.forEach(u=>{const g=a.get(u.id),f=o.get(u.id);!g||!f||((g.startTime!==u.startTime||g.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),s=this.resolveCrossTrackPreviewDestination(r,t.targetTrackY,i.trackId);if(s.status==="new_track_insertion")return this.clearAllTrackDropPreviews(),this.showTrackInsertionPreview(s.trackType,s.insertionPlacement,s.referenceTrackId),!0;if(s.status!=="existing_track"||s.targetTrackId===i.trackId)return!1;const a=this.resolveTrackIndexDelta(i.trackId,s.targetTrackId,i.clip.type);if(a===null)return!1;const o=new Map;this.appendPreviewClip(o,s.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),s=this.resolveCrossTrackMoveDestination(r,t.targetTrackY,i.trackId);if(s.status==="blocked"||s.status==="same_track")return!1;const a=s.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),s=r.indexOf(e),a=r.indexOf(t);return s===-1||a===-1?null:a-s}resolveMultiDragTargetTrackId(e,t,i){const r=this.ensureTrackIdByRelativeIndex(e.trackId,e.clip.type,t);if(!r)return e.trackId;const s=this.calculateTrackY(r)+1,a=this.resolveCrossTrackMoveDestination(i,s,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 s=this.calculateTrackY(r)+1,a=this.resolveCrossTrackPreviewDestination(i,s,e.trackId);return a.status==="existing_track"?a.targetTrackId:null}buildMovedClipSnapshot(e,t,i=!1){let r=e.startTime+t;if(i){const s=this.getDurationState();r=Math.max(0,Math.min(r,s-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(),s=this.getTimelineCommands().planCrossTrackMove(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);if(s.status==="missing_target_track_by_position")return N.debugLazy("TimelineManager",()=>"未找到目标轨道"),{status:"blocked"};if(s.status==="same_track")return{status:"same_track",targetTrackId:s.targetTrackId};if(s.status==="missing_target_track_view")return N.warn("TimelineManager","目标轨道不存在",{targetTrackId:s.targetTrackId}),{status:"blocked"};if(s.status==="track_type_mismatch")return N.debugLazy("TimelineManager",()=>"轨道类型不匹配",()=>({targetTrackType:s.targetTrackType,clipType:e.type})),{status:"blocked"};if(s.status==="move_to_track")return{status:"move_to_track",targetTrackId:s.targetTrackId};N.debugLazy("TimelineManager",()=>"没有找到可用轨道,创建新轨道",()=>({clipId:e.id}));const a=this.createTrack(s.trackType,void 0,s.insertionPlacement,s.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 s=this.getTimelineCommands().planCrossTrackPreview(e,t,i,this.getTrackContentTopOffset(),r,this.tracks);return s.status==="existing_track_placeholder"?{status:"existing_track",targetTrackId:s.targetTrackId}:s.status==="new_track_insertion"?{status:"new_track_insertion",trackType:s.trackType,insertionPlacement:s.insertionPlacement,referenceTrackId:s.referenceTrackId}:{status:"clear"}}ensureTrackIdByRelativeIndex(e,t,i){let r=this.getTrackIdsByType(t);const s=r.indexOf(e);if(s===-1)return null;let a=s+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),s=r.indexOf(e);if(s===-1)return null;const a=s+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),s=r==null?void 0:r.updateClipPosition;s&&this.withHistoryBoundary("suppressed",()=>{s.call(r,t,i,!0)})}ensureSelectionBoxRect(){var t;if(this.selectionBoxRect)return this.selectionBoxRect;const e=new Z.Rect({fill:Ps.fill,stroke:Ps.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 s=this.ensureSelectionBoxRect();s.x(e),s.y(t),s.width(Math.max(i,1)),s.height(Math.max(r,1)),s.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(),s=e.clientX-r.left,a=e.clientY-r.top;if(this.isPointOnClip(s,a))return;this.isBoxSelecting=!1,this.boxSelectStartX=s,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(),s=e.clientX-r.left,a=e.clientY-r.top,o=Math.abs(s-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,s),h=Math.min(this.boxSelectStartY,a),d=Math.abs(s-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 s=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);if(!(t<s||t>s+a))for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Ce(o.duration,this.getZoomState());if(e>=l&&e<=l+c&&t>=s+2&&t<=s+a-2)return!0}}return!1}getClipsIntersectingBox(e){const t=[];for(const i of this.tracks){const s=i.getTrackGroup().y(),a=this.resolveTrackRenderHeight(i);for(const o of i.getClips()){const l=fe(o.startTime,this.getZoomState(),this.getScrollLeftState()),c=Ce(o.duration,this.getZoomState()),h=s+2,d=a-4,u=l+c,g=h+d,f=e.x+e.width,m=e.y+e.height;l<f&&u>e.x&&h<m&&g>e.y&&t.push(o.id)}}return t}resolveTrackRenderHeight(e){return _e(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 s=[...this.getTracks()].sort((u,g)=>u.order-g.order),a=s.find(u=>u.order>=e.order),o=a?s[s.findIndex(u=>u.id===a.id)-1]??null:s[s.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,s,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:((s=t[i-1])==null?void 0:s.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 s=(Array.isArray(this.tracks)?this.tracks:[]).find(o=>o.getClips().some(l=>l.id===e));return(s==null?void 0:s.getId())??null}findTrackByClipId(e){return this.getTrackCollection().findTrackByClipId(e)}checkTrackDurationChange(){var a;const e=this.getClips(),t=this.lastTrackDuration,i=this.lastReportedTrackDuration,r=ns(e),s=zn(e);if(r!==t){this.lastTrackDuration=r;const o=$n(r);this.setDurationState(o),(a=this.timeline)==null||a.setDuration(o),this.updateViewportLayout()}if(s!==i&&(this.lastReportedTrackDuration=s,this.emitEvent("track_duration_change",{duration:s})),e.length===0&&this.getCurrentTimeState()!==0&&this.setCurrentTime(0),e.length>0){const o=St(e);o>0&&this.getCurrentTimeState()>o&&this.setCurrentTime(o)}r===t&&s===i||N.debugLazy("TimelineManager",()=>`Track duration changed: total=${s}ms, extent=${r}ms, timeline=${$n(r)}ms`)}resolveSelectedClipSnapshot(){return Lo({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 bp({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(l=>l.id===e);if(!i||i.type!=="video"&&i.type!=="text")return;const r=i.type==="text"?qe:xe,s=r(i.visualTransform),a=r(t);if(bs(s,a))return;const o={visualTransform:a};if(i.type==="text"){const l=ce(i.textStyle);l.anchorVersion!==1&&(o.textStyle={...l,anchorVersion:1})}this.updateClip(e,o)}commitPreviewTextLayout(e,t){const i=this.getClips().find(s=>s.id===e);if(!i||i.type!=="text")return;const r=ce(i.textStyle);r.layoutWidth===t.layoutWidth&&r.layoutHeight===t.layoutHeight||this.updateClip(e,{textStyle:{...r,layoutWidth:t.layoutWidth,layoutHeight:t.layoutHeight,anchorVersion:1}})}commitPreviewTextResolvedLayout(e,t){const i=this.getClips().find(r=>r.id===e);!i||i.type!=="text"||wu(i.textResolvedLayout,t)||this.updateClip(e,{textResolvedLayout:t})}commitPreviewTextFontSize(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=ce(i.textStyle),s=Math.max(ci.MIN,Math.min(ci.MAX,Math.round(t)));r.fontSize!==s&&this.updateClip(e,{textStyle:{...r,fontSize:s}})}commitPreviewTextRotation(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=ce(i.textStyle),s=Math.round(t);r.rotation!==s&&this.updateClip(e,{textStyle:{...r,rotation:s}})}clearAllTracksAndClips(){this.withHistoryBoundary("reset",()=>{var t,i,r,s;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(),(s=this.stage)==null||s.batchDraw(),this.clearHistory()})}}exports.ASPECT_RATIO_BASELINE_SHORT_EDGE_PX=os;exports.CLIP_LAYER=No;exports.Clip=zi;exports.ClipConfigPanel=mo;exports.DEFAULT_CLIP_VIEW_STATE=oa;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Le;exports.DEFAULT_TEXT_CLIP_DURATION_MS=la;exports.DEFAULT_TEXT_CLIP_STYLE=na;exports.DEFAULT_TIMELINE_DURATION_MS=Zt;exports.DiagnosticsCenter=Qa;exports.HistoryManager=ts;exports.MIN_CLIP_LINE_WIDTH=hi;exports.PREVIEW_ASPECT_RATIO_PRESETS=Go;exports.SNAP_SCORING=ha;exports.TEXT_CLIP_FONT_SIZE_LIMITS=ci;exports.TIMELINE_LEFT_PADDING=pe;exports.TIME_SCALE=$o;exports.TRACK_HEIGHT=Hi;exports.TimeUtils=U;exports.TimelineClipConfigController=Do;exports.TimelineManager=Pg;exports.Track=ir;exports.TrackInfoPanel=fo;exports.TrackManager=Oo;exports.VOICE_LINKED_TEXT_REGEN_DEBOUNCE_MS=ca;exports.ZOOM_ANIMATION=zo;exports.ZOOM_GESTURE=Dr;exports.ZOOM_PRESETS=Re;exports.createClipViewState=da;exports.createClipWithViewState=cs;exports.defaultDarkTheme=Yi;exports.devConsole=N;exports.isAudioOnlyTtsClipCandidate=aa;exports.isAutoPreviewAspectRatioMode=kt;exports.isTtsAudioClip=Me;exports.mergeDiagnosticRuntimeState=Mh;exports.normalizePreviewAspectRatio=Ue;exports.normalizePreviewAspectRatioMode=ls;exports.resolveAspectRatioBaselineDimensions=ji;exports.resolveTextClipStyle=ce;exports.resolveTheme=Xi;