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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Po=Object.defineProperty;var _o=(n,e,t)=>e in n?Po(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var p=(n,e,t)=>_o(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P={transparent:"transparent",white:"#ffffff",black:"#000000",panelSurface:"#0f0f0f",buttonSurface:"#2a2a2a",inputSurface:"#2d2d2d",clipSurface:"#2e2e2e",videoClipBackground:"#1e5679",textClipBackground:"#604c32",audioClipBackground:"#254428",mediaClipFailedBackground:"#670014",selectedTrackSurface:"#292929",borderStrong:"#333333",borderMedium:"#444444",borderSubtle:"#555555",textPrimary:"#ffffff",textSecondary:"#e0e0e0",textMuted:"#cccccc",textSubtle:"#aaaaaa",textHint:"#999999",textAudio:"#d0d0d0",textInactive:"#b5b6bf",audioClipAccent:"#b8b8c0",accentFocus:"#409eff",accentSelectedBorder:"#50E3C2",clipSelectedBorder:"#ffffff",accentSelectionBox:"#5082e6",accentAction:"#4c8dff",accentDanger:"#dc3545",accentPlayheadGrip:"#8c90ff",accentCoverFallback:"#FFF2A0",accentAudioPreview:"#b5baff",activeTabBackground:"#595A5D",gridLine:"#E0E0E0",overlayPreview:"rgba(0, 0, 0, 0.56)",overlayShadow:"rgba(0, 0, 0, 0.22)",overlayTransformHandle:"rgba(80, 227, 194, 0.95)",overlaySelectionBoxFill:"rgba(80, 130, 230, 0.15)",overlayVideoDropPreview:"rgba(80, 227, 194, 0.18)",overlayAudioDropPreview:"rgba(181, 186, 255, 0.18)",overlayHitArea:"rgba(0, 0, 0, 0.001)",sliderFillStart:"#f6f8ff",sliderFillEnd:"#dfe4f2",sliderRoad:"rgba(116, 128, 163, 0.26)",sliderThumbBorder:"rgba(230, 236, 250, 0.96)",sliderThumbGlowStart:"#ffffff",sliderThumbGlowEnd:"#eef2fb",sliderThumbInnerShadow:"rgba(255, 255, 255, 0.92)",sliderThumbShadow:"rgba(8, 24, 56, 0.24)"},ee={background:P.black,border:P.borderStrong,timeTick:P.textSecondary,timeText:P.textSubtle,trackBackground:P.black,trackSelectedBackground:P.selectedTrackSurface,trackBorder:P.borderStrong,clipBackground:P.clipSurface,clipBorder:P.black,clipName:P.textPrimary,clipDuration:P.textMuted,clipHandle:P.textPrimary,clipSelectedBorder:P.clipSelectedBorder,clipCoverBackground:P.borderStrong,audioClipText:P.textAudio,audioClipAccent:P.audioClipAccent,playhead:P.textPrimary,grid:P.borderStrong,snapGuideLineColor:P.accentSelectedBorder,scrollbarBackground:P.borderStrong,scrollbarBorder:P.borderSubtle,scrollbarThumb:P.borderMedium},ye={backgroundColor:"#0f0f0f",borderColor:P.borderStrong,textColor:P.textSecondary,labelColor:P.textHint,inputBackground:P.inputSurface,inputBorder:P.borderMedium,inputFocusBorder:P.accentFocus,buttonBackground:P.inputSurface,buttonBorder:P.borderMedium,buttonActiveBackground:P.accentFocus,buttonActiveBorder:P.accentFocus,buttonActiveText:P.white},ke={background:P.panelSurface,border:P.borderStrong,text:P.textPrimary,buttonBackground:P.buttonSurface,buttonHover:"#3a3a3a",buttonDanger:P.accentDanger},It={border:ee.scrollbarBorder,thumb:ee.scrollbarThumb,hitArea:P.overlayHitArea},St={fill:P.white,stroke:P.black,text:P.black},Pe={tabBarBackground:P.buttonSurface,actionBarBackground:P.buttonSurface,activeTabBackground:P.activeTabBackground,activeTabText:P.white,inactiveTabText:P.textInactive,sliderThumbShadow:`0 8px 20px ${P.sliderThumbShadow}`,sliderThumbInnerShadow:`inset 0 1px 1px ${P.sliderThumbInnerShadow}`},ks={grip:P.accentPlayheadGrip,shadow:P.overlayShadow},Ge={background:P.overlayPreview,text:P.white,failedBackground:P.mediaClipFailedBackground,failedText:P.white,actionBackground:P.accentAction,actionText:P.white},ze={border:P.overlayTransformHandle,handleBackground:P.black},ws={fill:P.overlaySelectionBoxFill,stroke:P.accentSelectionBox},Ti={videoFill:P.overlayVideoDropPreview,videoStroke:P.accentSelectedBorder,audioFill:P.overlayAudioDropPreview,audioStroke:P.accentAudioPreview},xs={line:P.gridLine},ta={fontSize:32,color:"#fff",rotation:0,strokeColor:"#000000",strokeWidth:1,paddingX:4};function fe(n){return{...ta,...n??{}}}function ia(n){return n.type==="audio"&&typeof n.textContent=="string"&&n.textContent.trim().length>0&&typeof n.ttsVoiceId=="string"&&n.ttsVoiceId.trim().length>0}function Re(n){return n.type==="audio"&&(typeof n.ttsSourceTextClipId=="string"&&n.ttsSourceTextClipId.trim().length>0||ia(n))}const ra={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},Yi={background:ee.background,border:ee.border,timeTick:ee.timeTick,timeText:ee.timeText,trackBackground:ee.trackBackground,trackSelectedBackground:ee.trackSelectedBackground,trackBorder:ee.trackBorder,clipBackground:ee.clipBackground,clipBorder:ee.clipBorder,clipName:ee.clipName,clipDuration:ee.clipDuration,clipHandle:ee.clipHandle,clipSelectedBorder:ee.clipSelectedBorder,clipCoverBackground:ee.clipCoverBackground,audioClipText:ee.audioClipText,audioClipAccent:ee.audioClipAccent,playhead:ee.playhead,grid:ee.grid,snapGuideLineColor:ee.snapGuideLineColor,snapGuideLineWidth:1,scrollbarBackground:ee.scrollbarBackground,scrollbarBorder:ee.scrollbarBorder,scrollbarThumb:ee.scrollbarThumb};function Xi(n){return n?{...Yi,...n}:{...Yi}}const as=720,Le={mode:"auto-first-added-video",width:16,height:9},Ao=[{key:"default",label:"默认",aspectRatio:{...Le}},{key:"9:16",label:"9:16",aspectRatio:{mode:"manual",width:9,height:16}},{key:"16:9",label:"16:9",aspectRatio:{mode:"manual",width:16,height:9}},{key:"3:4",label:"3:4",aspectRatio:{mode:"manual",width:3,height:4}},{key:"4:3",label:"4:3",aspectRatio:{mode:"manual",width:4,height:3}}];function os(n){return n==="manual"?"manual":"auto-first-added-video"}function bt(n){return os(n)==="auto-first-added-video"}function Ue(n){return{mode:os(n==null?void 0:n.mode),width:typeof(n==null?void 0:n.width)=="number"&&n.width>0?n.width:Le.width,height:typeof(n==null?void 0:n.height)=="number"&&n.height>0?n.height:Le.height}}function qi(n,e=as){const t=Math.max(0,n.width),i=Math.max(0,n.height),r=Math.max(0,e);if(t<=0||i<=0||r<=0)return{width:0,height:0};const s=Math.min(t,i),a=r/s;return{width:Math.round(t*a),height:Math.round(i*a)}}const Io={DEFAULT:1,ACTIVE:2},Me={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Kt=36e5,Dr={SENSITIVITY_FACTOR:.002,CONVERGENCE_THRESHOLD:1e-4},sa=3e3,na=450,aa={ANCHOR_INDEX_WEIGHT:.001},li={MIN:5,MAX:300},Eo={DURATION:300,EASING:"easeOutCubic"},Mo={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},ue=15,ci=6,Fi={TEXT:25,VIDEO:64,AUDIO:48};function oa(n={}){const e=Object.fromEntries(Object.entries(n).filter(([,t])=>t!==void 0));return{...ra,...e}}function ls(n,e={}){return{...n,...oa(e)}}function cs(n){n.disablePictureInPicture=!0,n.setAttribute("disablepictureinpicture","")}class U{static msToSeconds(e){return e/1e3}static secondsToMs(e){return e*1e3}static timeToPixels(e,t){return this.msToSeconds(e)*t}static pixelsToTime(e,t){return this.secondsToMs(e/t)}static formatTime(e){const t=e/1e3,i=Math.floor(t/60),r=Math.floor(t%60),s=Math.floor(e%1e3/10);return`${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}.${s.toString().padStart(2,"0")}`}static formatDuration(e){const t=Math.floor(e/1e3),i=Math.floor(e%1e3/10);return`${t}.${i.toString().padStart(2,"0")}s`}static diffTime(e,t){return Math.abs(e-t)}static isTimeInRange(e,t,i){return e>=t&&e<=i}static clampTime(e,t,i){return Math.max(t,Math.min(i,e))}static calculateEndTime(e,t){return e+t}static getTickConfig(e){let t,i;return e>=1e3?(t=1,i=.1):e>=500?(t=1,i=.5):e>=100?(t=1,i=1):e>=50?(t=5,i=1):e>=10?(t=10,i=2):e>=5?(t=60,i=10):(t=300,i=60),{majorStep:t,minorStep:i}}static generateTimeTicks(e,t=1){const i=[],r=this.msToSeconds(e);for(let s=0;s<=r;s+=t)i.push(this.secondsToMs(s));return i}static generateVisibleTicks(e,t,i,r){const s=[],a=Math.max(0,e);let o=Math.floor(a/i)*i,l=0;const c=100;for(let g=o;g<=t&&(s.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MAJOR}),l++,!(l>=c));g+=i);let h=0;const d=400;let u=Math.floor(a/r)*r;for(let g=u;g<=t&&!(Math.abs(g-Math.round(g/i)*i)>.001&&(s.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MINOR}),h++,h>=d));g+=r);return s.sort((g,f)=>g.time-f.time)}static getVideoDuration(e,t={}){const i=()=>new Promise(r=>{const s=document.createElement("video");s.preload="metadata",cs(s),s.onloadedmetadata=()=>{s.onloadedmetadata=null,s.onerror=null,r(s.duration*1e3)},s.onerror=()=>{s.onloadedmetadata=null,s.onerror=null,r(0)},s.src=e});return t.registry?t.registry.getDuration(t.cacheKey||e,i,{force:t.force}):i()}}p(U,"TICK_TYPE_MAJOR","major"),p(U,"TICK_TYPE_MINOR","minor");const Ro=Math.PI/180;function Lo(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const tt=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},R={_global:tt,version:"10.2.0",isBrowser:Lo(),isUnminified:/param/.test((function(n){}).toString()),dblClickWindow:400,getAngle(n){return R.angleDeg?n*Ro:n},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return R.DD.isDragging},isTransforming(){var n,e;return(e=(n=R.Transformer)===null||n===void 0?void 0:n.isTransforming())!==null&&e!==void 0?e:!1},isDragReady(){return!!R.DD.node},releaseCanvasOnDestroy:!0,document:tt.document,_injectGlobal(n){typeof tt.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),tt.Konva=n}},ae=n=>{R[n.prototype.getClassName()]=n};R._injectGlobal(R);const Do=`Konva.js unsupported environment.
1
+ "use strict";var Fo=Object.defineProperty;var Ho=(n,e,t)=>e in n?Fo(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var p=(n,e,t)=>Ho(n,typeof e!="symbol"?e+"":e,t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const P={transparent:"transparent",white:"#ffffff",black:"#000000",panelSurface:"#0f0f0f",buttonSurface:"#2a2a2a",inputSurface:"#2d2d2d",clipSurface:"#2e2e2e",videoClipBackground:"#1e5679",textClipBackground:"#604c32",audioClipBackground:"#254428",mediaClipFailedBackground:"#670014",selectedTrackSurface:"#292929",borderStrong:"#333333",borderMedium:"#444444",borderSubtle:"#555555",textPrimary:"#ffffff",textSecondary:"#e0e0e0",textMuted:"#cccccc",textSubtle:"#aaaaaa",textHint:"#999999",textAudio:"#d0d0d0",textInactive:"#b5b6bf",audioClipAccent:"#b8b8c0",accentFocus:"#409eff",accentSelectedBorder:"#50E3C2",clipSelectedBorder:"#ffffff",accentSelectionBox:"#5082e6",accentAction:"#4c8dff",accentDanger:"#dc3545",accentPlayheadGrip:"#8c90ff",accentCoverFallback:"#FFF2A0",accentAudioPreview:"#b5baff",activeTabBackground:"#595A5D",gridLine:"#E0E0E0",overlayPreview:"rgba(0, 0, 0, 0.56)",overlayShadow:"rgba(0, 0, 0, 0.22)",overlayTransformHandle:"rgba(80, 227, 194, 0.95)",overlaySelectionBoxFill:"rgba(80, 130, 230, 0.15)",overlayVideoDropPreview:"rgba(80, 227, 194, 0.18)",overlayAudioDropPreview:"rgba(181, 186, 255, 0.18)",overlayHitArea:"rgba(0, 0, 0, 0.001)",sliderFillStart:"#f6f8ff",sliderFillEnd:"#dfe4f2",sliderRoad:"rgba(116, 128, 163, 0.26)",sliderThumbBorder:"rgba(230, 236, 250, 0.96)",sliderThumbGlowStart:"#ffffff",sliderThumbGlowEnd:"#eef2fb",sliderThumbInnerShadow:"rgba(255, 255, 255, 0.92)",sliderThumbShadow:"rgba(8, 24, 56, 0.24)"},ee={background:P.black,border:P.borderStrong,timeTick:P.textSecondary,timeText:P.textSubtle,trackBackground:P.black,trackSelectedBackground:P.selectedTrackSurface,trackBorder:P.borderStrong,clipBackground:P.clipSurface,clipBorder:P.black,clipName:P.textPrimary,clipDuration:P.textMuted,clipHandle:P.textPrimary,clipSelectedBorder:P.clipSelectedBorder,clipCoverBackground:P.borderStrong,audioClipText:P.textAudio,audioClipAccent:P.audioClipAccent,playhead:P.textPrimary,grid:P.borderStrong,snapGuideLineColor:P.accentSelectedBorder,scrollbarBackground:P.borderStrong,scrollbarBorder:P.borderSubtle,scrollbarThumb:P.borderMedium},ye={backgroundColor:"#0f0f0f",borderColor:P.borderStrong,textColor:P.textSecondary,labelColor:P.textHint,inputBackground:P.inputSurface,inputBorder:P.borderMedium,inputFocusBorder:P.accentFocus,buttonBackground:P.inputSurface,buttonBorder:P.borderMedium,buttonActiveBackground:P.accentFocus,buttonActiveBorder:P.accentFocus,buttonActiveText:P.white},ke={background:P.panelSurface,border:P.borderStrong,text:P.textPrimary,buttonBackground:P.buttonSurface,buttonHover:"#3a3a3a",buttonDanger:P.accentDanger},Et={border:ee.scrollbarBorder,thumb:ee.scrollbarThumb,hitArea:P.overlayHitArea},Ct={fill:P.white,stroke:P.black,text:P.black},Pe={tabBarBackground:P.buttonSurface,actionBarBackground:P.buttonSurface,activeTabBackground:P.activeTabBackground,activeTabText:P.white,inactiveTabText:P.textInactive,sliderThumbShadow:`0 8px 20px ${P.sliderThumbShadow}`,sliderThumbInnerShadow:`inset 0 1px 1px ${P.sliderThumbInnerShadow}`},xs={grip:P.accentPlayheadGrip,shadow:P.overlayShadow},Ge={background:P.overlayPreview,text:P.white,failedBackground:P.mediaClipFailedBackground,failedText:P.white,actionBackground:P.accentAction,actionText:P.white},ze={border:P.overlayTransformHandle,handleBackground:P.black},Ps={fill:P.overlaySelectionBoxFill,stroke:P.accentSelectionBox},bi={videoFill:P.overlayVideoDropPreview,videoStroke:P.accentSelectedBorder,audioFill:P.overlayAudioDropPreview,audioStroke:P.accentAudioPreview},_s={line:P.gridLine},na={fontSize:32,color:"#fff",rotation:0,strokeColor:"#000000",strokeWidth:1,paddingX:4};function ce(n){return{...na,...n??{}}}function aa(n){return n.type==="audio"&&typeof n.textContent=="string"&&n.textContent.trim().length>0&&typeof n.ttsVoiceId=="string"&&n.ttsVoiceId.trim().length>0}function Me(n){return n.type==="audio"&&(typeof n.ttsSourceTextClipId=="string"&&n.ttsSourceTextClipId.trim().length>0||aa(n))}const oa={isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,isSelected:!1,zIndex:1,opacity:1},Yi={background:ee.background,border:ee.border,timeTick:ee.timeTick,timeText:ee.timeText,trackBackground:ee.trackBackground,trackSelectedBackground:ee.trackSelectedBackground,trackBorder:ee.trackBorder,clipBackground:ee.clipBackground,clipBorder:ee.clipBorder,clipName:ee.clipName,clipDuration:ee.clipDuration,clipHandle:ee.clipHandle,clipSelectedBorder:ee.clipSelectedBorder,clipCoverBackground:ee.clipCoverBackground,audioClipText:ee.audioClipText,audioClipAccent:ee.audioClipAccent,playhead:ee.playhead,grid:ee.grid,snapGuideLineColor:ee.snapGuideLineColor,snapGuideLineWidth:1,scrollbarBackground:ee.scrollbarBackground,scrollbarBorder:ee.scrollbarBorder,scrollbarThumb:ee.scrollbarThumb};function Xi(n){return n?{...Yi,...n}:{...Yi}}const os=720,Le={mode:"auto-first-added-video",width:16,height:9},Go=[{key:"default",label:"默认",aspectRatio:{...Le}},{key:"9:16",label:"9:16",aspectRatio:{mode:"manual",width:9,height:16}},{key:"16:9",label:"16:9",aspectRatio:{mode:"manual",width:16,height:9}},{key:"3:4",label:"3:4",aspectRatio:{mode:"manual",width:3,height:4}},{key:"4:3",label:"4:3",aspectRatio:{mode:"manual",width:4,height:3}}];function ls(n){return n==="manual"?"manual":"auto-first-added-video"}function kt(n){return ls(n)==="auto-first-added-video"}function Ue(n){return{mode:ls(n==null?void 0:n.mode),width:typeof(n==null?void 0:n.width)=="number"&&n.width>0?n.width:Le.width,height:typeof(n==null?void 0:n.height)=="number"&&n.height>0?n.height:Le.height}}function ji(n,e=os){const t=Math.max(0,n.width),i=Math.max(0,n.height),r=Math.max(0,e);if(t<=0||i<=0||r<=0)return{width:0,height:0};const s=Math.min(t,i),a=r/s;return{width:Math.round(t*a),height:Math.round(i*a)}}const No={DEFAULT:1,ACTIVE:2},Re={MIN:2,SMALL:10,MEDIUM:30,LARGE:60,MAX:100},Zt=36e5,Dr={SENSITIVITY_FACTOR:.002,CONVERGENCE_THRESHOLD:1e-4},la=3e3,ca=450,ha={ANCHOR_INDEX_WEIGHT:.001},ci={MIN:5,MAX:300},zo={DURATION:300,EASING:"easeOutCubic"},$o={DEFAULT_HEIGHT:40,MIN_HEIGHT:20,MAX_HEIGHT:80},pe=15,hi=6,Hi={TEXT:25,VIDEO:64,AUDIO:48};function da(n={}){const e=Object.fromEntries(Object.entries(n).filter(([,t])=>t!==void 0));return{...oa,...e}}function cs(n,e={}){return{...n,...da(e)}}function hs(n){n.disablePictureInPicture=!0,n.setAttribute("disablepictureinpicture","")}class U{static msToSeconds(e){return e/1e3}static secondsToMs(e){return e*1e3}static timeToPixels(e,t){return this.msToSeconds(e)*t}static pixelsToTime(e,t){return this.secondsToMs(e/t)}static formatTime(e){const t=e/1e3,i=Math.floor(t/60),r=Math.floor(t%60),s=Math.floor(e%1e3/10);return`${i.toString().padStart(2,"0")}:${r.toString().padStart(2,"0")}.${s.toString().padStart(2,"0")}`}static formatDuration(e){const t=Math.floor(e/1e3),i=Math.floor(e%1e3/10);return`${t}.${i.toString().padStart(2,"0")}s`}static diffTime(e,t){return Math.abs(e-t)}static isTimeInRange(e,t,i){return e>=t&&e<=i}static clampTime(e,t,i){return Math.max(t,Math.min(i,e))}static calculateEndTime(e,t){return e+t}static getTickConfig(e){let t,i;return e>=1e3?(t=1,i=.1):e>=500?(t=1,i=.5):e>=100?(t=1,i=1):e>=50?(t=5,i=1):e>=10?(t=10,i=2):e>=5?(t=60,i=10):(t=300,i=60),{majorStep:t,minorStep:i}}static generateTimeTicks(e,t=1){const i=[],r=this.msToSeconds(e);for(let s=0;s<=r;s+=t)i.push(this.secondsToMs(s));return i}static generateVisibleTicks(e,t,i,r){const s=[],a=Math.max(0,e);let o=Math.floor(a/i)*i,l=0;const c=100;for(let g=o;g<=t&&(s.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MAJOR}),l++,!(l>=c));g+=i);let h=0;const d=400;let u=Math.floor(a/r)*r;for(let g=u;g<=t&&!(Math.abs(g-Math.round(g/i)*i)>.001&&(s.push({time:this.secondsToMs(g),type:this.TICK_TYPE_MINOR}),h++,h>=d));g+=r);return s.sort((g,f)=>g.time-f.time)}static getVideoDuration(e,t={}){const i=()=>new Promise(r=>{const s=document.createElement("video");s.preload="metadata",hs(s),s.onloadedmetadata=()=>{s.onloadedmetadata=null,s.onerror=null,r(s.duration*1e3)},s.onerror=()=>{s.onloadedmetadata=null,s.onerror=null,r(0)},s.src=e});return t.registry?t.registry.getDuration(t.cacheKey||e,i,{force:t.force}):i()}}p(U,"TICK_TYPE_MAJOR","major"),p(U,"TICK_TYPE_MINOR","minor");const Vo=Math.PI/180;function Uo(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const it=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},M={_global:it,version:"10.2.0",isBrowser:Uo(),isUnminified:/param/.test((function(n){}).toString()),dblClickWindow:400,getAngle(n){return M.angleDeg?n*Vo:n},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return M.DD.isDragging},isTransforming(){var n,e;return(e=(n=M.Transformer)===null||n===void 0?void 0:n.isTransforming())!==null&&e!==void 0?e:!1},isDragReady(){return!!M.DD.node},releaseCanvasOnDestroy:!0,document:it.document,_injectGlobal(n){typeof it.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),it.Konva=n}},ae=n=>{M[n.prototype.getClassName()]=n};M._injectGlobal(M);const Wo=`Konva.js unsupported environment.
2
2
 
3
3
  Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined.
4
4
 
@@ -11,26 +11,26 @@ or
11
11
 
12
12
  bash: npm install skia-canvas
13
13
  js: import "konva/skia-backend";
14
- `,Ps=()=>{if(typeof document>"u")throw new Error(Do)};class ve{constructor(e=[1,0,0,1,0,0]){this.dirty=!1,this.m=e&&e.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new ve(this.m)}copyInto(e){e.m[0]=this.m[0],e.m[1]=this.m[1],e.m[2]=this.m[2],e.m[3]=this.m[3],e.m[4]=this.m[4],e.m[5]=this.m[5]}point(e){const t=this.m;return{x:t[0]*e.x+t[2]*e.y+t[4],y:t[1]*e.x+t[3]*e.y+t[5]}}translate(e,t){return this.m[4]+=this.m[0]*e+this.m[2]*t,this.m[5]+=this.m[1]*e+this.m[3]*t,this}scale(e,t){return this.m[0]*=e,this.m[1]*=e,this.m[2]*=t,this.m[3]*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),r=this.m[0]*t+this.m[2]*i,s=this.m[1]*t+this.m[3]*i,a=this.m[0]*-i+this.m[2]*t,o=this.m[1]*-i+this.m[3]*t;return this.m[0]=r,this.m[1]=s,this.m[2]=a,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(e,t){const i=this.m[0]+this.m[2]*t,r=this.m[1]+this.m[3]*t,s=this.m[2]+this.m[0]*e,a=this.m[3]+this.m[1]*e;return this.m[0]=i,this.m[1]=r,this.m[2]=s,this.m[3]=a,this}multiply(e){const t=this.m[0]*e.m[0]+this.m[2]*e.m[1],i=this.m[1]*e.m[0]+this.m[3]*e.m[1],r=this.m[0]*e.m[2]+this.m[2]*e.m[3],s=this.m[1]*e.m[2]+this.m[3]*e.m[3],a=this.m[0]*e.m[4]+this.m[2]*e.m[5]+this.m[4],o=this.m[1]*e.m[4]+this.m[3]*e.m[5]+this.m[5];return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=s,this.m[4]=a,this.m[5]=o,this}invert(){const e=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),t=this.m[3]*e,i=-this.m[1]*e,r=-this.m[2]*e,s=this.m[0]*e,a=e*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=e*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=s,this.m[4]=a,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const e=this.m[0],t=this.m[1],i=this.m[2],r=this.m[3],s=this.m[4],a=this.m[5],o=e*r-t*i,l={x:s,y:a,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(e!=0||t!=0){const c=Math.sqrt(e*e+t*t);l.rotation=t>0?Math.acos(e/c):-Math.acos(e/c),l.scaleX=c,l.scaleY=o/c,l.skewX=(e*i+t*r)/o,l.skewY=0}else if(i!=0||r!=0){const c=Math.sqrt(i*i+r*r);l.rotation=Math.PI/2-(r>0?Math.acos(-i/c):-Math.acos(i/c)),l.scaleX=o/c,l.scaleY=c,l.skewX=0,l.skewY=(e*i+t*r)/o}return l.rotation=b._getRotation(l.rotation),l}}const Oo="[object Array]",Bo="[object Number]",Fo="[object String]",Ho="[object Boolean]",Go=Math.PI/180,No=180/Math.PI,Et="#",zo="",$o="0",Vo="Konva warning: ",_s="Konva error: ",Uo="rgb(",gr={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},Wo=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let bi=[],Mt=null;const Yo=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(n){setTimeout(n,16)},b={_isElement(n){return!!(n&&n.nodeType==1)},_isFunction(n){return!!(n&&n.constructor&&n.call&&n.apply)},_isPlainObject(n){return!!n&&n.constructor===Object},_isArray(n){return Object.prototype.toString.call(n)===Oo},_isNumber(n){return Object.prototype.toString.call(n)===Bo&&!isNaN(n)&&isFinite(n)},_isString(n){return Object.prototype.toString.call(n)===Fo},_isBoolean(n){return Object.prototype.toString.call(n)===Ho},isObject(n){return n instanceof Object},isValidSelector(n){if(typeof n!="string")return!1;const e=n[0];return e==="#"||e==="."||e===e.toUpperCase()},_sign(n){return n===0||n>0?1:-1},requestAnimFrame(n){bi.push(n),bi.length===1&&Yo(function(){const e=bi;bi=[],e.forEach(function(t){t()})})},createCanvasElement(){Ps();const n=document.createElement("canvas");try{n.style=n.style||{}}catch{}return n},createImageElement(){return Ps(),document.createElement("img")},_isInDocument(n){for(;n=n.parentNode;)if(n==document)return!0;return!1},_urlToImage(n,e){const t=b.createImageElement();t.onload=function(){e(t)},t.src=n},_rgbToHex(n,e,t){return((1<<24)+(n<<16)+(e<<8)+t).toString(16).slice(1)},_hexToRgb(n){n=n.replace(Et,zo);const e=parseInt(n,16);return{r:e>>16&255,g:e>>8&255,b:e&255}},getRandomColor(){let n=(Math.random()*16777215<<0).toString(16);for(;n.length<6;)n=$o+n;return Et+n},isCanvasFarblingActive(){if(Mt!==null)return Mt;if(typeof document>"u")return Mt=!1,!1;const n=this.createCanvasElement();n.width=10,n.height=10;const e=n.getContext("2d",{willReadFrequently:!0});e.clearRect(0,0,10,10),e.fillStyle="#282828",e.fillRect(0,0,10,10);const t=e.getImageData(0,0,10,10).data;let i=!1;for(let r=0;r<100;r++)if(t[r*4]!==40||t[r*4+1]!==40||t[r*4+2]!==40||t[r*4+3]!==255){i=!0;break}return Mt=i,this.releaseCanvas(n),Mt},getHitColor(){const n=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(n):n},getHitColorKey(n,e,t){return this.isCanvasFarblingActive()&&(n=Math.round(n/5)*5,e=Math.round(e/5)*5,t=Math.round(t/5)*5),Et+this._rgbToHex(n,e,t)},getSnappedHexColor(n){const e=this._hexToRgb(n);return Et+this._rgbToHex(Math.round(e.r/5)*5,Math.round(e.g/5)*5,Math.round(e.b/5)*5)},getRGB(n){let e;return n in gr?(e=gr[n],{r:e[0],g:e[1],b:e[2]}):n[0]===Et?this._hexToRgb(n.substring(1)):n.substr(0,4)===Uo?(e=Wo.exec(n.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA(n){return n=n||"black",b._namedColorToRBA(n)||b._hex3ColorToRGBA(n)||b._hex4ColorToRGBA(n)||b._hex6ColorToRGBA(n)||b._hex8ColorToRGBA(n)||b._rgbColorToRGBA(n)||b._rgbaColorToRGBA(n)||b._hslColorToRGBA(n)},_namedColorToRBA(n){const e=gr[n.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(n){if(n.indexOf("rgb(")===0){n=n.match(/rgb\(([^)]+)\)/)[1];const e=n.split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(n){if(n.indexOf("rgba(")===0){n=n.match(/rgba\(([^)]+)\)/)[1];const e=n.split(/ *, */).map((t,i)=>t.slice(-1)==="%"?i===3?parseInt(t)/100:parseInt(t)/100*255:Number(t));return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex8ColorToRGBA(n){if(n[0]==="#"&&n.length===9)return{r:parseInt(n.slice(1,3),16),g:parseInt(n.slice(3,5),16),b:parseInt(n.slice(5,7),16),a:parseInt(n.slice(7,9),16)/255}},_hex6ColorToRGBA(n){if(n[0]==="#"&&n.length===7)return{r:parseInt(n.slice(1,3),16),g:parseInt(n.slice(3,5),16),b:parseInt(n.slice(5,7),16),a:1}},_hex4ColorToRGBA(n){if(n[0]==="#"&&n.length===5)return{r:parseInt(n[1]+n[1],16),g:parseInt(n[2]+n[2],16),b:parseInt(n[3]+n[3],16),a:parseInt(n[4]+n[4],16)/255}},_hex3ColorToRGBA(n){if(n[0]==="#"&&n.length===4)return{r:parseInt(n[1]+n[1],16),g:parseInt(n[2]+n[2],16),b:parseInt(n[3]+n[3],16),a:1}},_hslColorToRGBA(n){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(n)){const[e,...t]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(n),i=Number(t[0])/360,r=Number(t[1])/100,s=Number(t[2])/100;let a,o,l;if(r===0)return l=s*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};s<.5?a=s*(1+r):a=s+r-s*r;const c=2*s-a,h=[0,0,0];for(let d=0;d<3;d++)o=i+1/3*-(d-1),o<0&&o++,o>1&&o--,6*o<1?l=c+(a-c)*6*o:2*o<1?l=a:3*o<2?l=c+(a-c)*(2/3-o)*6:l=c,h[d]=l*255;return{r:Math.round(h[0]),g:Math.round(h[1]),b:Math.round(h[2]),a:1}}},haveIntersection(n,e){return!(e.x>n.x+n.width||e.x+e.width<n.x||e.y>n.y+n.height||e.y+e.height<n.y)},cloneObject(n){const e={};for(const t in n)this._isPlainObject(n[t])?e[t]=this.cloneObject(n[t]):this._isArray(n[t])?e[t]=this.cloneArray(n[t]):e[t]=n[t];return e},cloneArray(n){return n.slice(0)},degToRad(n){return n*Go},radToDeg(n){return n*No},_degToRad(n){return b.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),b.degToRad(n)},_radToDeg(n){return b.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),b.radToDeg(n)},_getRotation(n){return R.angleDeg?b.radToDeg(n):n},_capitalize(n){return n.charAt(0).toUpperCase()+n.slice(1)},throw(n){throw new Error(_s+n)},error(n){console.error(_s+n)},warn(n){R.showWarnings&&console.warn(Vo+n)},each(n,e){for(const t in n)e(t,n[t])},_inRange(n,e,t){return e<=n&&n<t},_getProjectionToSegment(n,e,t,i,r,s){let a,o,l;const c=(n-t)*(n-t)+(e-i)*(e-i);if(c==0)a=n,o=e,l=(r-t)*(r-t)+(s-i)*(s-i);else{const h=((r-n)*(t-n)+(s-e)*(i-e))/c;h<0?(a=n,o=e,l=(n-r)*(n-r)+(e-s)*(e-s)):h>1?(a=t,o=i,l=(t-r)*(t-r)+(i-s)*(i-s)):(a=n+h*(t-n),o=e+h*(i-e),l=(a-r)*(a-r)+(o-s)*(o-s))}return[a,o,l]},_getProjectionToLine(n,e,t){const i=b.cloneObject(n);let r=Number.MAX_VALUE;return e.forEach(function(s,a){if(!t&&a===e.length-1)return;const o=e[(a+1)%e.length],l=b._getProjectionToSegment(s.x,s.y,o.x,o.y,n.x,n.y),c=l[0],h=l[1],d=l[2];d<r&&(i.x=c,i.y=h,r=d)}),i},_prepareArrayForTween(n,e,t){const i=[],r=[];if(n.length>e.length){const a=e;e=n,n=a}for(let a=0;a<n.length;a+=2)i.push({x:n[a],y:n[a+1]});for(let a=0;a<e.length;a+=2)r.push({x:e[a],y:e[a+1]});const s=[];return r.forEach(function(a){const o=b._getProjectionToLine(a,i,t);s.push(o.x),s.push(o.y)}),s},_prepareToStringify(n){let e;n.visitedByCircularReferenceRemoval=!0;for(const t in n)if(n.hasOwnProperty(t)&&n[t]&&typeof n[t]=="object"){if(e=Object.getOwnPropertyDescriptor(n,t),n[t].visitedByCircularReferenceRemoval||b._isElement(n[t]))if(e.configurable)delete n[t];else return null;else if(b._prepareToStringify(n[t])===null)if(e.configurable)delete n[t];else return null}return delete n.visitedByCircularReferenceRemoval,n},_assign(n,e){for(const t in e)n[t]=e[t];return n},_getFirstPointerId(n){return n.touches?n.changedTouches[0].identifier:n.pointerId||999},releaseCanvas(...n){R.releaseCanvasOnDestroy&&n.forEach(e=>{e.width=0,e.height=0})},drawRoundedRectPath(n,e,t,i){let r=e<0?e:0,s=t<0?t:0;e=Math.abs(e),t=Math.abs(t);let a=0,o=0,l=0,c=0;typeof i=="number"?a=o=l=c=Math.min(i,e/2,t/2):(a=Math.min(i[0]||0,e/2,t/2),o=Math.min(i[1]||0,e/2,t/2),c=Math.min(i[2]||0,e/2,t/2),l=Math.min(i[3]||0,e/2,t/2)),n.moveTo(r+a,s),n.lineTo(r+e-o,s),n.arc(r+e-o,s+o,o,Math.PI*3/2,0,!1),n.lineTo(r+e,s+t-c),n.arc(r+e-c,s+t-c,c,0,Math.PI/2,!1),n.lineTo(r+l,s+t),n.arc(r+l,s+t-l,l,Math.PI/2,Math.PI,!1),n.lineTo(r,s+a),n.arc(r+a,s+a,a,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(n,e,t,i,r){i=Math.abs(i);for(let s=0;s<t;s++){const a=e[(s-1+t)%t],o=e[s],l=e[(s+1)%t],c={x:o.x-a.x,y:o.y-a.y},h={x:l.x-o.x,y:l.y-o.y},d=Math.hypot(c.x,c.y),u=Math.hypot(h.x,h.y);let g;typeof r=="number"?g=r:g=s<r.length?r[s]:0,g=i*Math.cos(Math.PI/t)*Math.min(1,g/i*2);const m={x:c.x/d,y:c.y/d},C={x:h.x/u,y:h.y/u},v={x:o.x-m.x*g,y:o.y-m.y*g},S={x:o.x+C.x*g,y:o.y+C.y*g};s===0?n.moveTo(v.x,v.y):n.lineTo(v.x,v.y),n.arcTo(o.x,o.y,S.x,S.y,g)}}};function Xo(n){const e=[],t=n.length,i=b;for(let r=0;r<t;r++){let s=n[r];i._isNumber(s)?s=Math.round(s*1e3)/1e3:i._isString(s)||(s=s+""),e.push(s)}return e}const As=",",qo="(",jo=")",Ko="([",Zo="])",Jo=";",Qo="()",el="=",Is=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],tl=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],il=100;let ki=null;function Es(){if(ki!==null)return ki;try{const e=b.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(ki=!1,!1)}catch{return ki=!1,!1}}class or{constructor(e){this.canvas=e,R.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let i=this.traceArr,r=i.length,s="",a,o,l,c;for(a=0;a<r;a++)o=i[a],l=o.method,l?(c=o.args,s+=l,e?s+=Qo:b._isArray(c[0])?s+=Ko+c.join(As)+Zo:(t&&(c=c.map(h=>typeof h=="number"?Math.floor(h):h)),s+=qo+c.join(As)+jo)):(s+=o.property,e||(s+=el+o.val)),s+=Jo;return s}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=il&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}_applyMiterLimit(e){const t=e.attrs.miterLimit;t!=null&&this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,i,r,s,a){this._context.arc(e,t,i,r,s,a)}arcTo(e,t,i,r,s){this._context.arcTo(e,t,i,r,s)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,i,r,s,a){this._context.bezierCurveTo(e,t,i,r,s,a)}clearRect(e,t,i,r){this._context.clearRect(e,t,i,r)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const i=arguments;if(i.length===2)return this._context.createImageData(e,t);if(i.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,i,r){return this._context.createLinearGradient(e,t,i,r)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,i,r,s,a){return this._context.createRadialGradient(e,t,i,r,s,a)}drawImage(e,t,i,r,s,a,o,l,c){const h=arguments,d=this._context;h.length===3?d.drawImage(e,t,i):h.length===5?d.drawImage(e,t,i,r,s):h.length===9&&d.drawImage(e,t,i,r,s,a,o,l,c)}ellipse(e,t,i,r,s,a,o,l){this._context.ellipse(e,t,i,r,s,a,o,l)}isPointInPath(e,t,i,r){return i?this._context.isPointInPath(i,e,t,r):this._context.isPointInPath(e,t,r)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,i,r){this._context.fillRect(e,t,i,r)}strokeRect(e,t,i,r){this._context.strokeRect(e,t,i,r)}fillText(e,t,i,r){r?this._context.fillText(e,t,i,r):this._context.fillText(e,t,i)}measureText(e){return this._context.measureText(e)}getImageData(e,t,i,r){return this._context.getImageData(e,t,i,r)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,i,r){this._context.rect(e,t,i,r)}roundRect(e,t,i,r,s){this._context.roundRect(e,t,i,r,s)}putImageData(e,t,i){this._context.putImageData(e,t,i)}quadraticCurveTo(e,t,i,r){this._context.quadraticCurveTo(e,t,i,r)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,i,r,s,a){this._context.setTransform(e,t,i,r,s,a)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,i,r){this._context.strokeText(e,t,i,r)}transform(e,t,i,r,s,a){this._context.transform(e,t,i,r,s,a)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=Is.length,i=this.setAttr,r,s;const a=function(o){let l=e[o],c;e[o]=function(){return s=Xo(Array.prototype.slice.call(arguments,0)),c=l.apply(e,arguments),e._trace({method:o,args:s}),c}};for(r=0;r<t;r++)a(Is[r]);e.setAttr=function(){i.apply(e,arguments);const o=arguments[0];let l=arguments[1];(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")&&(l=l/this.canvas.getPixelRatio()),e._trace({property:o,val:l})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}}tl.forEach(function(n){Object.defineProperty(or.prototype,n,{get(){return this._context[n]},set(e){this._context[n]=e}})});class rl extends or{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),i=e.getFillPriority();if(t&&i==="color"){this._fillColor(e);return}const r=e.getFillPatternImage();if(r&&i==="pattern"){this._fillPattern(e);return}const s=e.getFillLinearGradientColorStops();if(s&&i==="linear-gradient"){this._fillLinearGradient(e);return}const a=e.getFillRadialGradientColorStops();if(a&&i==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):r?this._fillPattern(e):s?this._fillLinearGradient(e):a&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),i=e.getStrokeLinearGradientEndPoint(),r=e.getStrokeLinearGradientColorStops(),s=this.createLinearGradient(t.x,t.y,i.x,i.y);if(r){for(let a=0;a<r.length;a+=2)s.addColorStop(r[a],r[a+1]);this.setAttr("strokeStyle",s)}}_stroke(e){const t=e.dash(),i=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!i){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),i||this.restore()}}_applyShadow(e){var t,i,r;const s=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",a=(i=e.getShadowBlur())!==null&&i!==void 0?i:5,o=(r=e.getShadowOffset())!==null&&r!==void 0?r:{x:0,y:0},l=e.getAbsoluteScale(),c=this.canvas.getPixelRatio(),h=l.x*c,d=l.y*c;this.setAttr("shadowColor",s),this.setAttr("shadowBlur",a*Math.min(Math.abs(h),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*h),this.setAttr("shadowOffsetY",o.y*d)}}class sl extends or{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e);const i=e.hitStrokeWidth(),r=i==="auto"?e.strokeWidth():i;this.setAttr("lineWidth",r),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}}let wi;function nl(){if(wi)return wi;const n=b.createCanvasElement(),e=n.getContext("2d");return wi=function(){const t=R._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),b.releaseCanvas(n),wi}class hs{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||R.pixelRatio||nl();this.pixelRatio=i,this._canvas=b.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(r){return b.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class We extends hs{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new rl(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class ds extends hs{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new sl(this),this.setSize(e.width,e.height)}}const J={get isDragging(){let n=!1;return J._dragElements.forEach(e=>{e.dragStatus==="dragging"&&(n=!0)}),n},justDragged:!1,get node(){let n;return J._dragElements.forEach(e=>{n=e.node}),n},_dragElements:new Map,_drag(n){const e=[];J._dragElements.forEach((t,i)=>{const{node:r}=t,s=r.getStage();s.setPointersPositions(n),t.pointerId===void 0&&(t.pointerId=b._getFirstPointerId(n));const a=s._changedPointerPositions.find(o=>o.id===t.pointerId);if(a){if(t.dragStatus!=="dragging"){const o=r.dragDistance();if(Math.max(Math.abs(a.x-t.startPointerPos.x),Math.abs(a.y-t.startPointerPos.y))<o||(r.startDrag({evt:n}),!r.isDragging()))return}r._setDragPosition(n,t),e.push(r)}}),e.forEach(t=>{t.fire("dragmove",{type:"dragmove",target:t,evt:n},!0)})},_endDragBefore(n){const e=[];J._dragElements.forEach(t=>{const{node:i}=t,r=i.getStage();if(n&&r.setPointersPositions(n),!r._changedPointerPositions.find(o=>o.id===t.pointerId))return;(t.dragStatus==="dragging"||t.dragStatus==="stopped")&&(J.justDragged=!0,R._mouseListenClick=!1,R._touchListenClick=!1,R._pointerListenClick=!1,t.dragStatus="stopped");const a=t.node.getLayer()||t.node instanceof R.Stage&&t.node;a&&e.indexOf(a)===-1&&e.push(a)}),e.forEach(t=>{t.draw()})},_endDragAfter(n){J._dragElements.forEach((e,t)=>{e.dragStatus==="stopped"&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:n},!0),e.dragStatus!=="dragging"&&J._dragElements.delete(t)})}};R.isBrowser&&(window.addEventListener("mouseup",J._endDragBefore,!0),window.addEventListener("touchend",J._endDragBefore,!0),window.addEventListener("touchcancel",J._endDragBefore,!0),window.addEventListener("mousemove",J._drag),window.addEventListener("touchmove",J._drag),window.addEventListener("mouseup",J._endDragAfter,!1),window.addEventListener("touchend",J._endDragAfter,!1),window.addEventListener("touchcancel",J._endDragAfter,!1));function je(n){return b._isString(n)?'"'+n+'"':Object.prototype.toString.call(n)==="[object Number]"||b._isBoolean(n)?n:Object.prototype.toString.call(n)}function la(n){return n>255?255:n<0?0:Math.round(n)}function E(){if(R.isUnminified)return function(n,e){return b._isNumber(n)||b.warn(je(n)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),n}}function lr(n){if(R.isUnminified)return function(e,t){let i=b._isNumber(e),r=b._isArray(e)&&e.length==n;return!i&&!r&&b.warn(je(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+n+")"),e}}function us(){if(R.isUnminified)return function(n,e){return b._isNumber(n)||n==="auto"||b.warn(je(n)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),n}}function ot(){if(R.isUnminified)return function(n,e){return b._isString(n)||b.warn(je(n)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),n}}function ca(){if(R.isUnminified)return function(n,e){const t=b._isString(n),i=Object.prototype.toString.call(n)==="[object CanvasGradient]"||n&&n.addColorStop;return t||i||b.warn(je(n)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),n}}function al(){if(R.isUnminified)return function(n,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&n instanceof t||(b._isArray(n)?n.forEach(function(i){b._isNumber(i)||b.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):b.warn(je(n)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),n}}function Ae(){if(R.isUnminified)return function(n,e){return n===!0||n===!1||b.warn(je(n)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),n}}function ol(n){if(R.isUnminified)return function(e,t){return e==null||b.isObject(e)||b.warn(je(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+n),e}}const Rt="get",Lt="set",y={addGetterSetter(n,e,t,i,r){y.addGetter(n,e,t),y.addSetter(n,e,i,r),y.addOverloadedGetterSetter(n,e)},addGetter(n,e,t){const i=Rt+b._capitalize(e);n.prototype[i]=n.prototype[i]||function(){const r=this.attrs[e];return r===void 0?t:r}},addSetter(n,e,t,i){const r=Lt+b._capitalize(e);n.prototype[r]||y.overWriteSetter(n,e,t,i)},overWriteSetter(n,e,t,i){const r=Lt+b._capitalize(e);n.prototype[r]=function(s){return t&&s!==void 0&&s!==null&&(s=t.call(this,s,e)),this._setAttr(e,s),i&&i.call(this),this}},addComponentsGetterSetter(n,e,t,i,r){const s=t.length,a=b._capitalize,o=Rt+a(e),l=Lt+a(e);n.prototype[o]=function(){const h={};for(let d=0;d<s;d++){const u=t[d];h[u]=this.getAttr(e+a(u))}return h};const c=ol(t);n.prototype[l]=function(h){const d=this.attrs[e];i&&(h=i.call(this,h,e)),c&&c.call(this,h,e);for(const u in h)h.hasOwnProperty(u)&&this._setAttr(e+a(u),h[u]);return h||t.forEach(u=>{this._setAttr(e+a(u),void 0)}),this._fireChangeEvent(e,d,h),r&&r.call(this),this},y.addOverloadedGetterSetter(n,e)},addOverloadedGetterSetter(n,e){const t=b._capitalize(e),i=Lt+t,r=Rt+t;n.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[r]()}},addDeprecatedGetterSetter(n,e,t,i){b.error("Adding deprecated "+e);const r=Rt+b._capitalize(e),s=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";n.prototype[r]=function(){b.error(s);const a=this.attrs[e];return a===void 0?t:a},y.addSetter(n,e,i,function(){b.error(s)}),y.addOverloadedGetterSetter(n,e)},backCompat(n,e){b.each(e,function(t,i){const r=n.prototype[i],s=Rt+b._capitalize(t),a=Lt+b._capitalize(t);function o(){r.apply(this,arguments),b.error('"'+t+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}n.prototype[t]=o,n.prototype[s]=o,n.prototype[a]=o})},afterSetFilter(){this._filterUpToDate=!1}};function ll(n){const e=/(\w+)\(([^)]+)\)/g;let t;for(;(t=e.exec(n))!==null;){const[,i,r]=t;switch(i){case"blur":{const s=parseFloat(r.replace("px",""));return function(a){this.blurRadius(s*.5);const o=R.Filters;o&&o.Blur&&o.Blur.call(this,a)}}case"brightness":{const s=r.includes("%")?parseFloat(r)/100:parseFloat(r);return function(a){this.brightness(s);const o=R.Filters;o&&o.Brightness&&o.Brightness.call(this,a)}}case"contrast":{const s=parseFloat(r);return function(a){const o=100*(Math.sqrt(s)-1);this.contrast(o);const l=R.Filters;l&&l.Contrast&&l.Contrast.call(this,a)}}case"grayscale":return function(s){const a=R.Filters;a&&a.Grayscale&&a.Grayscale.call(this,s)};case"sepia":return function(s){const a=R.Filters;a&&a.Sepia&&a.Sepia.call(this,s)};case"invert":return function(s){const a=R.Filters;a&&a.Invert&&a.Invert.call(this,s)};default:b.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Hi="absoluteOpacity",Ms="allEventListeners",Oe="absoluteTransform",Rs="absoluteScale",Qe="canvas",cl="Change",hl="children",dl="konva",Or="listening",ul="mouseenter",pl="mouseleave",gl="pointerenter",fl="pointerleave",ml="touchenter",yl="touchleave",Ls="set",Ds="Shape",Gi=" ",Os="stage",$e="transform",Sl="Stage",Br="visible",Cl=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Gi);let vl=1;class I{constructor(e){this._id=vl++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(e),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(e){(e===$e||e===Oe)&&this._cache.get(e)?this._cache.get(e).dirty=!0:e?this._cache.delete(e):this._cache.clear()}_getCache(e,t){let i=this._cache.get(e);return(i===void 0||(e===$e||e===Oe)&&i.dirty===!0)&&(i=t.call(this),this._cache.set(e,i)),i}_calculate(e,t,i){if(!this._attachedDepsListeners.get(e)){const r=t.map(s=>s+"Change.konva").join(Gi);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(Qe)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Oe&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(Qe)){const{scene:e,filter:t,hit:i}=this._cache.get(Qe);b.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(Qe)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){const t=e||{};let i={};(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)&&(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let r=Math.ceil(t.width||i.width),s=Math.ceil(t.height||i.height),a=t.pixelRatio,o=t.x===void 0?Math.floor(i.x):t.x,l=t.y===void 0?Math.floor(i.y):t.y,c=t.offset||0,h=t.drawBorder||!1,d=t.hitCanvasPixelRatio||1;if(!r||!s){b.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const u=Math.abs(Math.round(i.x)-o)>.5?1:0,g=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=c*2+u,s+=c*2+g,o-=c,l-=c;const f=new We({pixelRatio:a,width:r,height:s}),m=new We({pixelRatio:a,width:0,height:0,willReadFrequently:!0}),C=new ds({pixelRatio:d,width:r,height:s}),v=f.getContext(),S=C.getContext(),T=new We({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(l),pixelRatio:f.pixelRatio}),k=T.getContext();return C.isCache=!0,f.isCache=!0,this._cache.delete(Qe),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,m.getContext()._context.imageSmoothingEnabled=!1),v.save(),S.save(),k.save(),v.translate(-o,-l),S.translate(-o,-l),k.translate(-o,-l),T.x=o,T.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Hi),this._clearSelfAndDescendantCache(Rs),this.drawScene(f,this,T),this.drawHit(C,this),this._isUnderCache=!1,v.restore(),S.restore(),h&&(v.save(),v.beginPath(),v.rect(0,0,r,s),v.closePath(),v.setAttr("strokeStyle","red"),v.setAttr("lineWidth",5),v.stroke(),v.restore()),b.releaseCanvas(T._canvas),this._cache.set(Qe,{scene:f,filter:m,hit:C,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(Qe)}getClientRect(e){throw new Error('abstract "getClientRect" method call')}_transformedRect(e,t){const i=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}];let r=1/0,s=1/0,a=-1/0,o=-1/0;const l=this.getAbsoluteTransform(t);return i.forEach(function(c){const h=l.point(c);r===void 0&&(r=a=h.x,s=o=h.y),r=Math.min(r,h.x),s=Math.min(s,h.y),a=Math.max(a,h.x),o=Math.max(o,h.y)}),{x:r,y:s,width:a-r,height:o-s}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);const t=this._getCanvasCache();e.translate(t.x,t.y);const i=this._getCachedSceneCanvas(),r=i.pixelRatio;e.drawImage(i._canvas,0,0,i.width/r,i.height/r),e.restore()}_drawCachedHitCanvas(e){const t=this._getCanvasCache(),i=t.hit;e.save(),e.translate(t.x,t.y),e.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),i=t.scene,r=t.filter,s=r.getContext(),a,o,l,c;if(!e||e.length===0)return i;if(this._filterUpToDate)return r;let h=!0;for(let u=0;u<e.length;u++)if(typeof e[u]=="string"&&Es(),typeof e[u]!="string"||!Es()){h=!1;break}const d=i.pixelRatio;if(r.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),h){const u=e.join(" ");return s.save(),s.setAttr("filter",u),s.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),s.restore(),this._filterUpToDate=!0,r}try{for(a=e.length,s.clear(),s.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),o=s.getImageData(0,0,r.getWidth(),r.getHeight()),l=0;l<a;l++)c=e[l],typeof c=="string"&&(c=ll(c)),c.call(this,o),s.putImageData(o,0,0)}catch(u){b.error("Unable to apply filter. "+u.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,r}on(e,t){if(this._cache&&this._cache.delete(Ms),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Gi);for(let r=0;r<i.length;r++){const a=i[r].split("."),o=a[0],l=a[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:t})}return this}off(e,t){let i=(e||"").split(Gi),r=i.length,s,a,o,l,c,h;if(this._cache&&this._cache.delete(Ms),!e)for(a in this.eventListeners)this._off(a);for(s=0;s<r;s++)if(o=i[s],l=o.split("."),c=l[0],h=l[1],c)this.eventListeners[c]&&this._off(c,h,t);else for(a in this.eventListeners)this._off(a,h,t);return this}dispatchEvent(e){const t={target:this,type:e.type,evt:e};return this.fire(e.type,t),this}addEventListener(e,t){return this.on(e,function(i){t.call(this,i.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,i){const r=this;this.on(e,function(s){const a=s.target.findAncestors(t,!0,r);for(let o=0;o<a.length;o++)s=b.cloneObject(s),s.currentTarget=a[o],i.call(a[o],s)})}remove(){return this.isDragging()&&this.stopDrag(),J._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Oe),this._clearSelfAndDescendantCache(Hi),this._clearSelfAndDescendantCache(Rs),this._clearSelfAndDescendantCache(Os),this._clearSelfAndDescendantCache(Br),this._clearSelfAndDescendantCache(Or)}_remove(){this._clearCaches();const e=this.getParent();e&&e.children&&(e.children.splice(this.index,1),e._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(e){const t="get"+b._capitalize(e);return b._isFunction(this[t])?this[t]():this.attrs[e]}getAncestors(){let e=this.getParent(),t=[];for(;e;)t.push(e),e=e.getParent();return t}getAttrs(){return this.attrs||{}}setAttrs(e){return this._batchTransformChanges(()=>{let t,i;if(!e)return this;for(t in e)t!==hl&&(i=Ls+b._capitalize(t),b._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(Or,this._isListening)}_isListening(e){if(!this.listening())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isListening(e):!0}isVisible(){return this._getCache(Br,this._isVisible)}_isVisible(e){if(!this.visible())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isVisible(e):!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);const i=this.getLayer();let r=!1;J._dragElements.forEach(a=>{a.dragStatus==="dragging"&&(a.node.nodeType==="Stage"||a.node.getLayer()===i)&&(r=!0)});const s=!t&&!R.hitOnDragEnabled&&(r||R.isTransforming());return this.isListening()&&this.isVisible()&&!s}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let e=this.getDepth(),t=this,i=0,r,s,a,o;function l(h){for(r=[],s=h.length,a=0;a<s;a++)o=h[a],i++,o.nodeType!==Ds&&(r=r.concat(o.getChildren().slice())),o._id===t._id&&(a=s);r.length>0&&r[0].getDepth()<=e&&l(r)}const c=this.getStage();return t.nodeType!==Sl&&c&&l(c.getChildren()),i}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}_batchTransformChanges(e){this._batchingTransformChange=!0,e(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache($e),this._clearSelfAndDescendantCache(Oe)),this._needClearTransformCache=!1}setPosition(e){return this._batchTransformChanges(()=>{this.x(e.x),this.y(e.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const e=this.getStage();if(!e)return null;const t=e.getPointerPosition();if(!t)return null;const i=this.getAbsoluteTransform().copy();return i.invert(),i.point(t)}getAbsolutePosition(e){let t=!1,i=this.parent;for(;i;){if(i.isCached()){t=!0;break}i=i.parent}t&&!e&&(e=!0);const r=this.getAbsoluteTransform(e).getMatrix(),s=new ve,a=this.offset();return s.m=r.slice(),s.translate(a.x,a.y),s.getTranslation()}setAbsolutePosition(e){const{x:t,y:i,...r}=this._clearTransform();this.attrs.x=t,this.attrs.y=i,this._clearCache($e);const s=this._getAbsoluteTransform().copy();return s.invert(),s.translate(e.x,e.y),e={x:this.attrs.x+s.getTranslation().x,y:this.attrs.y+s.getTranslation().y},this._setTransform(r),this.setPosition({x:e.x,y:e.y}),this._clearCache($e),this._clearSelfAndDescendantCache(Oe),this}_setTransform(e){let t;for(t in e)this.attrs[t]=e[t]}_clearTransform(){const e={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,e}move(e){let t=e.x,i=e.y,r=this.x(),s=this.y();return t!==void 0&&(r+=t),i!==void 0&&(s+=i),this.setPosition({x:r,y:s}),this}_eachAncestorReverse(e,t){let i=[],r=this.getParent(),s,a;if(!(t&&t._id===this._id)){for(i.unshift(this);r&&(!t||r._id!==t._id);)i.unshift(r),r=r.parent;for(s=i.length,a=0;a<s;a++)e(i[a])}}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return b.warn("Node has no parent. moveToTop function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return b.warn("Node has no parent. moveUp function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return b.warn("Node has no parent. moveDown function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return b.warn("Node has no parent. moveToBottom function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(e){if(!this.parent)return b.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&b.warn("Unexpected value "+e+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const t=this.index;return this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(Hi,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let e=this.opacity();const t=this.getParent();return t&&!t._isUnderCache&&(e*=t.getAbsoluteOpacity()),e}moveTo(e){return this.getParent()!==e&&(this._remove(),e.add(this)),this}toObject(){let e=this.getAttrs(),t,i,r,s,a;const o={attrs:{},className:this.getClassName()};for(t in e)i=e[t],a=b.isObject(i)&&!b._isPlainObject(i)&&!b._isArray(i),!a&&(r=typeof this[t]=="function"&&this[t],delete e[t],s=r?r.call(this):null,e[t]=i,s!==i&&(o.attrs[t]=i));return b._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,i){const r=[];t&&this._isMatch(e)&&r.push(this);let s=this.parent;for(;s;){if(s===i)return r;s._isMatch(e)&&r.push(s),s=s.parent}return r}isAncestorOf(e){return!1}findAncestor(e,t,i){return this.findAncestors(e,t,i)[0]}_isMatch(e){if(!e)return!1;if(typeof e=="function")return e(this);let t=e.replace(/ /g,"").split(","),i=t.length,r,s;for(r=0;r<i;r++)if(s=t[r],b.isValidSelector(s)||(b.warn('Selector "'+s+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),b.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),b.warn("Konva is awesome, right?")),s.charAt(0)==="#"){if(this.id()===s.slice(1))return!0}else if(s.charAt(0)==="."){if(this.hasName(s.slice(1)))return!0}else if(this.className===s||this.nodeType===s)return!0;return!1}getLayer(){const e=this.getParent();return e?e.getLayer():null}getStage(){return this._getCache(Os,this._getStage)}_getStage(){const e=this.getParent();return e?e.getStage():null}fire(e,t={},i){return t.target=t.target||this,i?this._fireAndBubble(e,t):this._fire(e,t),this}getAbsoluteTransform(e){return e?this._getAbsoluteTransform(e):this._getCache(Oe,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new ve,this._eachAncestorReverse(function(i){const r=i.transformsEnabled();r==="all"?t.multiply(i.getTransform()):r==="position"&&t.translate(i.x()-i.offsetX(),i.y()-i.offsetY())},e),t;{t=this._cache.get(Oe)||new ve,this.parent?this.parent.getAbsoluteTransform().copyInto(t):t.reset();const i=this.transformsEnabled();if(i==="all")t.multiply(this.getTransform());else if(i==="position"){const r=this.attrs.x||0,s=this.attrs.y||0,a=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(r-a,s-o)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;for(;t;)t._isUnderCache&&(e=t),t=t.getParent();const r=this.getAbsoluteTransform(e).decompose();return{x:r.scaleX,y:r.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache($e,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get($e)||new ve;i.reset();const r=this.x(),s=this.y(),a=R.getAngle(this.rotation()),o=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,l=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,c=this.attrs.skewX||0,h=this.attrs.skewY||0,d=this.attrs.offsetX||0,u=this.attrs.offsetY||0;return(r!==0||s!==0)&&i.translate(r,s),a!==0&&i.rotate(a),(c!==0||h!==0)&&i.skew(c,h),(o!==1||l!==1)&&i.scale(o,l),(d!==0||u!==0)&&i.translate(-1*d,-1*u),i.dirty=!1,i}clone(e){let t=b.cloneObject(this.attrs),i,r,s,a,o;for(i in e)t[i]=e[i];const l=new this.constructor(t);for(i in this.eventListeners)for(r=this.eventListeners[i],s=r.length,a=0;a<s;a++)o=r[a],o.name.indexOf(dl)<0&&(l.eventListeners[i]||(l.eventListeners[i]=[]),l.eventListeners[i].push(o));return l}_toKonvaCanvas(e){e=e||{};const t=this.getClientRect(),i=this.getStage(),r=e.x!==void 0?e.x:Math.floor(t.x),s=e.y!==void 0?e.y:Math.floor(t.y),a=e.pixelRatio||1,o=new We({width:e.width||Math.ceil(t.width)||(i?i.width():0),height:e.height||Math.ceil(t.height)||(i?i.height():0),pixelRatio:a}),l=o.getContext(),c=new We({width:o.width/o.pixelRatio+Math.abs(r),height:o.height/o.pixelRatio+Math.abs(s),pixelRatio:o.pixelRatio});return e.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(r||s)&&l.translate(-1*r,-1*s),this.drawScene(o,void 0,c),l.restore(),o}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};const t=e.mimeType||null,i=e.quality||null,r=this._toKonvaCanvas(e).toDataURL(t,i);return e.callback&&e.callback(r),r}toImage(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,b._urlToImage(this.toDataURL(e),function(s){t(s),r==null||r(s)})}catch(r){i(r)}})}toBlob(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,this.toCanvas(e).toBlob(s=>{t(s),r==null||r(s)},e==null?void 0:e.mimeType,e==null?void 0:e.quality)}catch(r){i(r)}})}setSize(e){return this.width(e.width),this.height(e.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():R.dragDistance}_off(e,t,i){let r=this.eventListeners[e],s,a,o;for(s=0;s<r.length;s++)if(a=r[s].name,o=r[s].handler,(a!=="konva"||t==="konva")&&(!t||a===t)&&(!i||i===o)){if(r.splice(s,1),r.length===0){delete this.eventListeners[e];break}s--}}_fireChangeEvent(e,t,i){this._fire(e+cl,{oldVal:t,newVal:i})}addName(e){if(!this.hasName(e)){const t=this.name(),i=t?t+" "+e:e;this.name(i)}return this}hasName(e){if(!e)return!1;const t=this.name();return t?(t||"").split(/\s/g).indexOf(e)!==-1:!1}removeName(e){const t=(this.name()||"").split(/\s/g),i=t.indexOf(e);return i!==-1&&(t.splice(i,1),this.name(t.join(" "))),this}setAttr(e,t){const i=this[Ls+b._capitalize(e)];return b._isFunction(i)?i.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(R.autoDrawEnabled){const e=this.getLayer()||this.getStage();e==null||e.batchDraw()}}_setAttr(e,t){const i=this.attrs[e];i===t&&!b.isObject(t)||(t==null?delete this.attrs[e]:this.attrs[e]=t,this._shouldFireChangeEvents&&this._fireChangeEvent(e,i,t),this._requestDraw())}_setComponentAttr(e,t,i){let r;i!==void 0&&(r=this.attrs[e],r||(this.attrs[e]=this.getAttr(e)),this.attrs[e][t]=i,this._fireChangeEvent(e,r,i))}_fireAndBubble(e,t,i){t&&this.nodeType===Ds&&(t.target=this);const r=[ul,pl,gl,fl,ml,yl];if(!(r.indexOf(e)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(e,t);const a=r.indexOf(e)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!a&&(i&&i.parent?this._fireAndBubble.call(this.parent,e,t,i):this._fireAndBubble.call(this.parent,e,t))}}_getProtoListeners(e){var t,i;const{nodeType:r}=this,s=I.protoListenerMap.get(r)||{};let a=s==null?void 0:s[e];if(a===void 0){a=[];let o=Object.getPrototypeOf(this);for(;o;){const l=(i=(t=o.eventListeners)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:[];a.push(...l),o=Object.getPrototypeOf(o)}s[e]=a,I.protoListenerMap.set(r,s)}return a}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;const i=this._getProtoListeners(e);if(i)for(let s=0;s<i.length;s++)i[s].handler.call(this,t);const r=this.eventListeners[e];if(r)for(let s=0;s<r.length;s++)r[s].handler.call(this,t)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){const t=e?e.pointerId:void 0,i=this.getStage(),r=this.getAbsolutePosition();if(!i)return;const s=i._getPointerById(t)||i._changedPointerPositions[0]||r;J._dragElements.set(this._id,{node:this,startPointerPos:s,offset:{x:s.x-r.x,y:s.y-r.y},dragStatus:"ready",pointerId:t})}startDrag(e,t=!0){J._dragElements.has(this._id)||this._createDragElement(e);const i=J._dragElements.get(this._id);i.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:e&&e.evt},t)}_setDragPosition(e,t){const i=this.getStage()._getPointerById(t.pointerId);if(!i)return;let r={x:i.x-t.offset.x,y:i.y-t.offset.y};const s=this.dragBoundFunc();if(s!==void 0){const a=s.call(this,r,e);a?r=a:b.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==r.x||this._lastPos.y!==r.y)&&(this.setAbsolutePosition(r),this._requestDraw()),this._lastPos=r}stopDrag(e){const t=J._dragElements.get(this._id);t&&(t.dragStatus="stopped"),J._endDragBefore(e),J._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=J._dragElements.get(this._id);return e?e.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(e){if(!(!(e.evt.button!==void 0)||R.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let r=!1;J._dragElements.forEach(s=>{this.isAncestorOf(s.node)&&(r=!0)}),r||this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=J._dragElements.get(this._id),i=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";i?this.stopDrag():r&&J._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(e={x:0,y:0}){const t=this.getStage();if(!t)return!1;const i={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return b.haveIntersection(i,this.getClientRect())}static create(e,t){return b._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let i=I.prototype.getClassName.call(e),r=e.children,s,a,o;t&&(e.attrs.container=t),R[i]||(b.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=R[i];if(s=new l(e.attrs),r)for(a=r.length,o=0;o<a;o++)s.add(I._createNode(r[o]));return s}}I.protoListenerMap=new Map;I.prototype.nodeType="Node";I.prototype._attrsAffectingSize=[];I.prototype.eventListeners={};I.prototype.on.call(I.prototype,Cl,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache($e),this._clearSelfAndDescendantCache(Oe)});I.prototype.on.call(I.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(Br)});I.prototype.on.call(I.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(Or)});I.prototype.on.call(I.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Hi)});const te=y.addGetterSetter;te(I,"zIndex");te(I,"absolutePosition");te(I,"position");te(I,"x",0,E());te(I,"y",0,E());te(I,"globalCompositeOperation","source-over",ot());te(I,"opacity",1,E());te(I,"name","",ot());te(I,"id","",ot());te(I,"rotation",0,E());y.addComponentsGetterSetter(I,"scale",["x","y"]);te(I,"scaleX",1,E());te(I,"scaleY",1,E());y.addComponentsGetterSetter(I,"skew",["x","y"]);te(I,"skewX",0,E());te(I,"skewY",0,E());y.addComponentsGetterSetter(I,"offset",["x","y"]);te(I,"offsetX",0,E());te(I,"offsetY",0,E());te(I,"dragDistance",void 0,E());te(I,"width",0,E());te(I,"height",0,E());te(I,"listening",!0,Ae());te(I,"preventDefault",!0,Ae());te(I,"filters",void 0,function(n){return this._filterUpToDate=!1,n});te(I,"visible",!0,Ae());te(I,"transformsEnabled","all",ot());te(I,"size");te(I,"dragBoundFunc");te(I,"draggable",!1,Ae());y.backCompat(I,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class Te extends I{constructor(){super(...arguments),this.children=[]}getChildren(e){const t=this.children||[];return e?t.filter(e):t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let i=0;i<e.length;i++)this.add(e[i]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const i=[];return this._descendants(r=>{const s=r._isMatch(e);return s&&i.push(r),!!(s&&t)}),i}_descendants(e){let t=!1;const i=this.getChildren();for(const r of i){if(t=e(r),t)return!0;if(r.hasChildren()&&(t=r._descendants(e),t))return!0}return!1}toObject(){const e=I.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=I.prototype.clone.call(this,e);return this.getChildren().forEach(function(i){t.add(i.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(i=>{i.isVisible()&&i.intersects(e)&&t.push(i)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(i){i._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,i){t.index=i}),this._requestDraw()}drawScene(e,t,i){const r=this.getLayer(),s=e||r&&r.getCanvas(),a=s&&s.getContext(),o=this._getCanvasCache(),l=o&&o.scene,c=s&&s.isCache;if(!this.isVisible()&&!c)return this;if(l){a.save();const h=this.getAbsoluteTransform(t).getMatrix();a.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(a),a.restore()}else this._drawChildren("drawScene",s,t,i);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const i=this.getLayer(),r=e||i&&i.hitCanvas,s=r&&r.getContext(),a=this._getCanvasCache();if(a&&a.hit){s.save();const l=this.getAbsoluteTransform(t).getMatrix();s.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(s),s.restore()}else this._drawChildren("drawHit",r,t);return this}_drawChildren(e,t,i,r){var s;const a=t&&t.getContext(),o=this.clipWidth(),l=this.clipHeight(),c=this.clipFunc(),h=typeof o=="number"&&typeof l=="number"||c,d=i===this;if(h){a.save();const g=this.getAbsoluteTransform(i);let f=g.getMatrix();a.transform(f[0],f[1],f[2],f[3],f[4],f[5]),a.beginPath();let m;if(c)m=c.call(this,a,this);else{const C=this.clipX(),v=this.clipY();a.rect(C||0,v||0,o,l)}a.clip.apply(a,m),f=g.copy().invert().getMatrix(),a.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";u&&(a.save(),a._applyGlobalCompositeOperation(this)),(s=this.children)===null||s===void 0||s.forEach(function(g){g[e](t,i,r)}),u&&a.restore(),h&&a.restore()}getClientRect(e={}){var t;const i=e.skipTransform,r=e.relativeTo;let s,a,o,l,c={x:1/0,y:1/0,width:0,height:0};const h=this;(t=this.children)===null||t===void 0||t.forEach(function(g){if(!g.visible())return;const f=g.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});f.width===0&&f.height===0||(s===void 0?(s=f.x,a=f.y,o=f.x+f.width,l=f.y+f.height):(s=Math.min(s,f.x),a=Math.min(a,f.y),o=Math.max(o,f.x+f.width),l=Math.max(l,f.y+f.height)))});const d=this.find("Shape");let u=!1;for(let g=0;g<d.length;g++)if(d[g]._isVisible(this)){u=!0;break}return u&&s!==void 0?c={x:s,y:a,width:o-s,height:l-a}:c={x:0,y:0,width:0,height:0},i?c:this._transformedRect(c,r)}}y.addComponentsGetterSetter(Te,"clip",["x","y","width","height"]);y.addGetterSetter(Te,"clipX",void 0,E());y.addGetterSetter(Te,"clipY",void 0,E());y.addGetterSetter(Te,"clipWidth",void 0,E());y.addGetterSetter(Te,"clipHeight",void 0,E());y.addGetterSetter(Te,"clipFunc");const hi=new Map,ha=R._global.PointerEvent!==void 0;function fr(n){return hi.get(n)}function ps(n){return{evt:n,pointerId:n.pointerId}}function da(n,e){return hi.get(n)===e}function ua(n,e){Zt(n),e.getStage()&&(hi.set(n,e),ha&&e._fire("gotpointercapture",ps(new PointerEvent("gotpointercapture"))))}function Zt(n,e){const t=hi.get(n);if(!t)return;const i=t.getStage();i&&i.content,hi.delete(n),ha&&t._fire("lostpointercapture",ps(new PointerEvent("lostpointercapture")))}const Tl="Stage",bl="string",Bs="px",kl="mouseout",pa="mouseleave",ga="mouseover",fa="mouseenter",ma="mousemove",ya="mousedown",Sa="mouseup",zt="pointermove",$t="pointerdown",Ct="pointerup",Vt="pointercancel",wl="lostpointercapture",xi="pointerout",Ut="pointerleave",Pi="pointerover",_i="pointerenter",Fr="contextmenu",Ca="touchstart",va="touchend",Ta="touchmove",ba="touchcancel",Hr="wheel",xl=5,Pl=[[fa,"_pointerenter"],[ya,"_pointerdown"],[ma,"_pointermove"],[Sa,"_pointerup"],[pa,"_pointerleave"],[Ca,"_pointerdown"],[Ta,"_pointermove"],[va,"_pointerup"],[ba,"_pointercancel"],[ga,"_pointerover"],[Hr,"_wheel"],[Fr,"_contextmenu"],[$t,"_pointerdown"],[zt,"_pointermove"],[Ct,"_pointerup"],[Vt,"_pointercancel"],[Ut,"_pointerleave"],[wl,"_lostpointercapture"]],mr={mouse:{[xi]:kl,[Ut]:pa,[Pi]:ga,[_i]:fa,[zt]:ma,[$t]:ya,[Ct]:Sa,[Vt]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[xi]:"touchout",[Ut]:"touchleave",[Pi]:"touchover",[_i]:"touchenter",[zt]:Ta,[$t]:Ca,[Ct]:va,[Vt]:ba,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[xi]:xi,[Ut]:Ut,[Pi]:Pi,[_i]:_i,[zt]:zt,[$t]:$t,[Ct]:Ct,[Vt]:Vt,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Wt=n=>n.indexOf("pointer")>=0?"pointer":n.indexOf("touch")>=0?"touch":"mouse",ut=n=>{const e=Wt(n);if(e==="pointer")return R.pointerEventsEnabled&&mr.pointer;if(e==="touch")return mr.touch;if(e==="mouse")return mr.mouse};function Fs(n={}){return(n.clipFunc||n.clipWidth||n.clipHeight)&&b.warn("Stage does not support clipping. Please use clip for Layers or Groups."),n}const _l="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",Jt=[];class cr extends Te{constructor(e){super(Fs(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),Jt.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{Fs(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",i=e.getType()==="FastLayer";t||i||b.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const e=this.visible()?"":"none";this.content.style.display=e}setContainer(e){if(typeof e===bl){let t;if(e.charAt(0)==="."){const i=e.slice(1);e=document.getElementsByClassName(i)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),Te.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&b._isInDocument(e)&&this.container().removeChild(e);const t=Jt.indexOf(this);return t>-1&&Jt.splice(t,1),b.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const e=this._pointerPositions[0]||this._changedPointerPositions[0];return e?{x:e.x,y:e.y}:(b.warn(_l),null)}_getPointerById(e){return this._pointerPositions.find(t=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();const t=new We({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),i=t.getContext()._context,r=this.children;return(e.x||e.y)&&i.translate(-1*e.x,-1*e.y),r.forEach(function(s){if(!s.isVisible())return;const a=s._toKonvaCanvas(e);i.drawImage(a._canvas,e.x,e.y,a.getWidth()/a.getPixelRatio(),a.getHeight()/a.getPixelRatio())}),t}getIntersection(e){if(!e)return null;const t=this.children,i=t.length,r=i-1;for(let s=r;s>=0;s--){const a=t[s].getIntersection(e);if(a)return a}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+Bs,this.content.style.height=t+Bs),this.bufferCanvas.setSize(e,t),this.bufferHitCanvas.setSize(e,t),this.children.forEach(i=>{i.setSize({width:e,height:t}),i.draw()})}add(e,...t){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.add(arguments[r]);return this}super.add(e);const i=this.children.length;return i>xl&&b.warn("The stage has "+i+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),R.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return da(e,this)}setPointerCapture(e){ua(e,this)}releaseCapture(e){Zt(e)}getLayers(){return this.children}_bindContentEvents(){R.isBrowser&&Pl.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=ut(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=ut(e.type);t&&this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];return t&&!t.getStage()&&(t=null),t}_pointerleave(e){const t=ut(e.type),i=Wt(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(i),s=!(R.isDragging()||R.isTransforming())||R.hitOnDragEnabled;r&&s?(r._fireAndBubble(t.pointerout,{evt:e}),r._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[i+"targetShape"]=null):s&&(this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){const t=ut(e.type),i=Wt(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(s=>{const a=this.getIntersection(s);if(J.justDragged=!1,R["_"+i+"ListenClick"]=!0,!a||!a.isListening()){this[i+"ClickStartShape"]=void 0;return}R.capturePointerEventsEnabled&&a.setPointerCapture(s.id),this[i+"ClickStartShape"]=a,a._fireAndBubble(t.pointerdown,{evt:e,pointerId:s.id}),r=!0;const o=e.type.indexOf("touch")>=0;a.preventDefault()&&e.cancelable&&o&&e.preventDefault()}),r||this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){const t=ut(e.type),i=Wt(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(R.isDragging()&&J.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(R.isDragging()||R.isTransforming())||R.hitOnDragEnabled))return;const a={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(c=>{const h=fr(c.id)||this.getIntersection(c),d=c.id,u={evt:e,pointerId:d},g=l!==h;if(g&&l&&(l._fireAndBubble(t.pointerout,{...u},h),l._fireAndBubble(t.pointerleave,{...u},h)),h){if(a[h._id])return;a[h._id]=!0}h&&h.isListening()?(o=!0,g&&(h._fireAndBubble(t.pointerover,{...u},l),h._fireAndBubble(t.pointerenter,{...u},l),this[i+"targetShape"]=h),h._fireAndBubble(t.pointermove,{...u})):l&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:d}),this[i+"targetShape"]=null)}),o||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=ut(e.type),i=Wt(e.type);if(!t)return;this.setPointersPositions(e);const r=this[i+"ClickStartShape"],s=this[i+"ClickEndShape"],a={};let o=!1;this._changedPointerPositions.forEach(l=>{const c=fr(l.id)||this.getIntersection(l);if(c){if(c.releaseCapture(l.id),a[c._id])return;a[c._id]=!0}const h=l.id,d={evt:e,pointerId:h};let u=!1;R["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):J.justDragged||(R["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){R["_"+i+"InDblClickWindow"]=!1},R.dblClickWindow),c&&c.isListening()?(o=!0,this[i+"ClickEndShape"]=c,c._fireAndBubble(t.pointerup,{...d}),R["_"+i+"ListenClick"]&&r&&r===c&&(c._fireAndBubble(t.pointerclick,{...d}),u&&s&&s===c&&c._fireAndBubble(t.pointerdblclick,{...d}))):(this[i+"ClickEndShape"]=null,o||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),R["_"+i+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:h}),u&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:h}))}),o||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),R["_"+i+"ListenClick"]=!1,e.cancelable&&i!=="touch"&&i!=="pointer"&&e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Fr,{evt:e}):this._fire(Fr,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Hr,{evt:e}):this._fire(Hr,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=fr(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(Ct,ps(e)),Zt(e.pointerId)}_lostpointercapture(e){Zt(e.pointerId)}setPointersPositions(e){const t=this._getContentPosition();let i=null,r=null;e=e||window.event,e.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,s=>{this._pointerPositions.push({id:s.identifier,x:(s.clientX-t.left)/t.scaleX,y:(s.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,s=>{this._changedPointerPositions.push({id:s.identifier,x:(s.clientX-t.left)/t.scaleX,y:(s.clientY-t.top)/t.scaleY})})):(i=(e.clientX-t.left)/t.scaleX,r=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:i,y:r},this._pointerPositions=[{x:i,y:r,id:b._getFirstPointerId(e)}],this._changedPointerPositions=[{x:i,y:r,id:b._getFirstPointerId(e)}])}_setPointerPosition(e){b.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new We({width:this.width(),height:this.height()}),this.bufferHitCanvas=new ds({pixelRatio:1,width:this.width(),height:this.height()}),!R.isBrowser)return;const e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),this._resizeDOM()}cache(){return b.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}}cr.prototype.nodeType=Tl;ae(cr);y.addGetterSetter(cr,"container");R.isBrowser&&document.addEventListener("visibilitychange",()=>{Jt.forEach(n=>{n.batchDraw()})});const ka="hasShadow",wa="shadowRGBA",xa="patternImage",Pa="linearGradient",_a="radialGradient";let Ai;function yr(){return Ai||(Ai=b.createCanvasElement().getContext("2d"),Ai)}const Qt={};function Al(n){const e=this.attrs.fillRule;e?n.fill(e):n.fill()}function Il(n){n.stroke()}function El(n){const e=this.attrs.fillRule;e?n.fill(e):n.fill()}function Ml(n){n.stroke()}function Rl(){this._clearCache(ka)}function Ll(){this._clearCache(wa)}function Dl(){this._clearCache(xa)}function Ol(){this._clearCache(Pa)}function Bl(){this._clearCache(_a)}class A extends I{constructor(e){super(e);let t,i=0;for(;t=b.getHitColor(),!(t&&!(t in Qt));)if(i++,i>=1e4){b.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=b.getRandomColor();break}this.colorKey=t,Qt[t]=this}getContext(){return b.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return b.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(ka,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(xa,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=yr().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new ve;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(R.getAngle(this.fillPatternRotation())),i.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),i.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const r=i.getMatrix(),s=typeof DOMMatrix>"u"?{a:r[0],b:r[1],c:r[2],d:r[3],e:r[4],f:r[5]}:new DOMMatrix(r);t.setTransform(s)}return t}}_getLinearGradient(){return this._getCache(Pa,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=yr(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),s=t.createLinearGradient(i.x,i.y,r.x,r.y);for(let a=0;a<e.length;a+=2)s.addColorStop(e[a],e[a+1]);return s}}_getRadialGradient(){return this._getCache(_a,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=yr(),i=this.fillRadialGradientStartPoint(),r=this.fillRadialGradientEndPoint(),s=t.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),r.x,r.y,this.fillRadialGradientEndRadius());for(let a=0;a<e.length;a+=2)s.addColorStop(e[a],e[a+1]);return s}}getShadowRGBA(){return this._getCache(wa,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=b.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const e=this.hitStrokeWidth();return e==="auto"?this.hasStroke():this.strokeEnabled()&&!!e}intersects(e){const t=this.getStage();if(!t)return!1;const i=t.bufferHitCanvas;return i.getContext().clear(),this.drawHit(i,void 0,!0),i.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return I.prototype.destroy.call(this),delete Qt[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0?t:!0))return!1;const r=e||this.hasFill(),s=this.hasStroke(),a=this.getAbsoluteOpacity()!==1;if(r&&s&&a)return!0;const o=this.hasShadow(),l=this.shadowForStrokeEnabled();return!!(r&&s&&o&&l)}setStrokeHitEnabled(e){b.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,i=this.getParent();for(;i;){if(i.isCached()){t=!0;break}i=i.getParent()}const r=e.skipTransform,s=e.relativeTo||t&&this.getStage()||void 0,a=this.getSelfRect(),l=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,c=a.width+l,h=a.height+l,d=!e.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,g=d?this.shadowOffsetY():0,f=c+Math.abs(u),m=h+Math.abs(g),C=d&&this.shadowBlur()||0,v=f+C*2,S=m+C*2,T={width:v,height:S,x:-(l/2+C)+Math.min(u,0)+a.x,y:-(l/2+C)+Math.min(g,0)+a.y};return r?T:this._transformedRect(T,s)}drawScene(e,t,i){const r=this.getLayer(),s=e||r.getCanvas(),a=s.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),c=this.hasShadow();let h;const d=t===this;if(!this.isVisible()&&!d)return this;if(o){a.save();const u=this.getAbsoluteTransform(t).getMatrix();return a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(a),a.restore(),this}if(!l)return this;if(a.save(),this._useBufferCanvas()){h=this.getStage();const u=i||h.bufferCanvas,g=u.getContext();i?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,u.width,u.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const f=this.getAbsoluteTransform(t).getMatrix();g.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.call(this,g,this),g.restore();const m=u.pixelRatio;c&&a._applyShadow(this),d||(a._applyOpacity(this),a._applyGlobalCompositeOperation(this)),a.drawImage(u._canvas,u.x||0,u.y||0,u.width/m,u.height/m)}else{if(a._applyLineJoin(this),a._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(t).getMatrix();a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),a._applyOpacity(this),a._applyGlobalCompositeOperation(this)}c&&a._applyShadow(this),l.call(this,a,this)}return a.restore(),this}drawHit(e,t,i=!1){if(!this.shouldDrawHit(t,i))return this;const r=this.getLayer(),s=e||r.hitCanvas,a=s&&s.getContext(),o=this.hitFunc()||this.sceneFunc(),l=this._getCanvasCache(),c=l&&l.hit;if(this.colorKey||b.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),c){a.save();const d=this.getAbsoluteTransform(t).getMatrix();return a.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(a),a.restore(),this}if(!o)return this;if(a.save(),a._applyLineJoin(this),a._applyMiterLimit(this),!(this===t)){const d=this.getAbsoluteTransform(t).getMatrix();a.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,a,this),a.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),i=this._getCachedSceneCanvas(),r=t.hit,s=r.getContext(),a=r.getWidth(),o=r.getHeight();s.clear(),s.drawImage(i._canvas,0,0,a,o);try{const l=s.getImageData(0,0,a,o),c=l.data,h=c.length,d=b._hexToRgb(this.colorKey);for(let u=0;u<h;u+=4)c[u+3]>e?(c[u]=d.r,c[u+1]=d.g,c[u+2]=d.b,c[u+3]=255):c[u+3]=0;s.putImageData(l,0,0)}catch(l){b.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(e){return da(e,this)}setPointerCapture(e){ua(e,this)}releaseCapture(e){Zt(e)}}A.prototype._fillFunc=Al;A.prototype._strokeFunc=Il;A.prototype._fillFuncHit=El;A.prototype._strokeFuncHit=Ml;A.prototype._centroid=!1;A.prototype.nodeType="Shape";ae(A);A.prototype.eventListeners={};A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Rl);A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Ll);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Dl);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Ol);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Bl);y.addGetterSetter(A,"stroke",void 0,ca());y.addGetterSetter(A,"strokeWidth",2,E());y.addGetterSetter(A,"fillAfterStrokeEnabled",!1);y.addGetterSetter(A,"hitStrokeWidth","auto",us());y.addGetterSetter(A,"strokeHitEnabled",!0,Ae());y.addGetterSetter(A,"perfectDrawEnabled",!0,Ae());y.addGetterSetter(A,"shadowForStrokeEnabled",!0,Ae());y.addGetterSetter(A,"lineJoin");y.addGetterSetter(A,"lineCap");y.addGetterSetter(A,"miterLimit");y.addGetterSetter(A,"sceneFunc");y.addGetterSetter(A,"hitFunc");y.addGetterSetter(A,"dash");y.addGetterSetter(A,"dashOffset",0,E());y.addGetterSetter(A,"shadowColor",void 0,ot());y.addGetterSetter(A,"shadowBlur",0,E());y.addGetterSetter(A,"shadowOpacity",1,E());y.addComponentsGetterSetter(A,"shadowOffset",["x","y"]);y.addGetterSetter(A,"shadowOffsetX",0,E());y.addGetterSetter(A,"shadowOffsetY",0,E());y.addGetterSetter(A,"fillPatternImage");y.addGetterSetter(A,"fill",void 0,ca());y.addGetterSetter(A,"fillPatternX",0,E());y.addGetterSetter(A,"fillPatternY",0,E());y.addGetterSetter(A,"fillLinearGradientColorStops");y.addGetterSetter(A,"strokeLinearGradientColorStops");y.addGetterSetter(A,"fillRadialGradientStartRadius",0);y.addGetterSetter(A,"fillRadialGradientEndRadius",0);y.addGetterSetter(A,"fillRadialGradientColorStops");y.addGetterSetter(A,"fillPatternRepeat","repeat");y.addGetterSetter(A,"fillEnabled",!0);y.addGetterSetter(A,"strokeEnabled",!0);y.addGetterSetter(A,"shadowEnabled",!0);y.addGetterSetter(A,"dashEnabled",!0);y.addGetterSetter(A,"strokeScaleEnabled",!0);y.addGetterSetter(A,"fillPriority","color");y.addComponentsGetterSetter(A,"fillPatternOffset",["x","y"]);y.addGetterSetter(A,"fillPatternOffsetX",0,E());y.addGetterSetter(A,"fillPatternOffsetY",0,E());y.addComponentsGetterSetter(A,"fillPatternScale",["x","y"]);y.addGetterSetter(A,"fillPatternScaleX",1,E());y.addGetterSetter(A,"fillPatternScaleY",1,E());y.addComponentsGetterSetter(A,"fillLinearGradientStartPoint",["x","y"]);y.addComponentsGetterSetter(A,"strokeLinearGradientStartPoint",["x","y"]);y.addGetterSetter(A,"fillLinearGradientStartPointX",0);y.addGetterSetter(A,"strokeLinearGradientStartPointX",0);y.addGetterSetter(A,"fillLinearGradientStartPointY",0);y.addGetterSetter(A,"strokeLinearGradientStartPointY",0);y.addComponentsGetterSetter(A,"fillLinearGradientEndPoint",["x","y"]);y.addComponentsGetterSetter(A,"strokeLinearGradientEndPoint",["x","y"]);y.addGetterSetter(A,"fillLinearGradientEndPointX",0);y.addGetterSetter(A,"strokeLinearGradientEndPointX",0);y.addGetterSetter(A,"fillLinearGradientEndPointY",0);y.addGetterSetter(A,"strokeLinearGradientEndPointY",0);y.addComponentsGetterSetter(A,"fillRadialGradientStartPoint",["x","y"]);y.addGetterSetter(A,"fillRadialGradientStartPointX",0);y.addGetterSetter(A,"fillRadialGradientStartPointY",0);y.addComponentsGetterSetter(A,"fillRadialGradientEndPoint",["x","y"]);y.addGetterSetter(A,"fillRadialGradientEndPointX",0);y.addGetterSetter(A,"fillRadialGradientEndPointY",0);y.addGetterSetter(A,"fillPatternRotation",0);y.addGetterSetter(A,"fillRule",void 0,ot());y.backCompat(A,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Fl="beforeDraw",Hl="draw",Aa=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Gl=Aa.length;class lt extends Te{constructor(e){super(e),this.canvas=new We,this.hitCanvas=new ds({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){I.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!I.prototype.moveUp.call(this))return!1;const t=this.getStage();return!t||!t.content?!1:(t.content.removeChild(this.getNativeCanvasElement()),this.index<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[this.index+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(I.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(I.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return I.prototype.remove.call(this),e&&e.parentNode&&b._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),I.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){b.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){b.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,b.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,i=!1;for(;;){for(let r=0;r<Gl;r++){const s=Aa[r],a=this._getIntersection({x:e.x+s.x*t,y:e.y+s.y*t}),o=a.shape;if(o)return o;if(i=!!a.antialiased,!a.antialiased)break}if(i)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,i=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,r=i[3];if(r===255){const s=b.getHitColorKey(i[0],i[1],i[2]),a=Qt[s];return a?{shape:a}:{antialiased:!0}}else if(r>0)return{antialiased:!0};return{}}drawScene(e,t,i){const r=this.getLayer(),s=e||r&&r.getCanvas();return this._fire(Fl,{node:this}),this.clearBeforeDraw()&&s.getContext().clear(),Te.prototype.drawScene.call(this,s,t,i),this._fire(Hl,{node:this}),this}drawHit(e,t){const i=this.getLayer(),r=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),Te.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;!!this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return b.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}lt.prototype.nodeType="Layer";ae(lt);y.addGetterSetter(lt,"imageSmoothingEnabled",!0);y.addGetterSetter(lt,"clearBeforeDraw",!0);y.addGetterSetter(lt,"hitGraphEnabled",!0,Ae());class gs extends lt{constructor(e){super(e),this.listening(!1),b.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}gs.prototype.nodeType="FastLayer";ae(gs);class kt extends Te{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to groups.")}}kt.prototype.nodeType="Group";ae(kt);const Sr=function(){return tt.performance&&tt.performance.now?function(){return tt.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:Sr(),frameRate:0},this.func=e,this.setLayers(t)}setLayers(e){let t=[];return e&&(t=Array.isArray(e)?e:[e]),this.layers=t,this}getLayers(){return this.layers}addLayer(e){const t=this.layers,i=t.length;for(let r=0;r<i;r++)if(t[r]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){const t=we.animations,i=t.length;for(let r=0;r<i;r++)if(t[r].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=Sr(),we._addAnimation(this),this}stop(){return we._removeAnimation(this),this}_updateFrameObject(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(e){this.animations.push(e),this._handleAnimation()}static _removeAnimation(e){const t=e.id,i=this.animations,r=i.length;for(let s=0;s<r;s++)if(i[s].id===t){this.animations.splice(s,1);break}}static _runFrames(){const e={},t=this.animations;for(let i=0;i<t.length;i++){const r=t[i],s=r.layers,a=r.func;r._updateFrameObject(Sr());const o=s.length;let l;if(a?l=a.call(r,r.frame)!==!1:l=!0,!!l)for(let c=0;c<o;c++){const h=s[c];h._id!==void 0&&(e[h._id]=h)}}for(const i in e)e.hasOwnProperty(i)&&e[i].batchDraw()}static _animationLoop(){const e=we;e.animations.length?(e._runFrames(),b.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,b.requestAnimFrame(this._animationLoop))}}we.animations=[];we.animIdCounter=0;we.animRunning=!1;const Nl={node:1,duration:1,easing:1,onFinish:1,yoyo:1},zl=1,Hs=2,Gs=3,Ns=["fill","stroke","shadowColor"];let $l=0;class Vl{constructor(e,t,i,r,s,a,o){this.prop=e,this.propFunc=t,this.begin=r,this._pos=r,this.duration=a,this._change=0,this.prevPos=0,this.yoyo=o,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=i,this._change=s-this.begin,this.pause()}fire(e){const t=this[e];t&&t()}setTime(e){e>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():e<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=e,this.update())}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){return e===void 0&&(e=this._time),this.func(e,this.begin,this._change,this.duration)}play(){this.state=Hs,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=Gs,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const e=this.getTimer()-this._startTime;this.state===Hs?this.setTime(e):this.state===Gs&&this.setTime(this.duration-e)}pause(){this.state=zl,this.fire("onPause")}getTimer(){return new Date().getTime()}}class ie{constructor(e){const t=this,i=e.node,r=i._id,s=e.easing||ei.Linear,a=!!e.yoyo;let o,l;typeof e.duration>"u"?o=.3:e.duration===0?o=.001:o=e.duration,this.node=i,this._id=$l++;const c=i.getLayer()||(i instanceof R.Stage?i.getLayers():null);c||b.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new we(function(){t.tween.onEnterFrame()},c),this.tween=new Vl(l,function(h){t._tweenFunc(h)},s,0,1,o*1e3,a),this._addListeners(),ie.attrs[r]||(ie.attrs[r]={}),ie.attrs[r][this._id]||(ie.attrs[r][this._id]={}),ie.tweens[r]||(ie.tweens[r]={});for(l in e)Nl[l]===void 0&&this._addAttr(l,e[l]);this.reset(),this.onFinish=e.onFinish,this.onReset=e.onReset,this.onUpdate=e.onUpdate}_addAttr(e,t){const i=this.node,r=i._id;let s,a,o,l,c;const h=ie.tweens[r][e];h&&delete ie.attrs[r][h][e];let d=i.getAttr(e);if(b._isArray(t))if(s=[],a=Math.max(t.length,d.length),e==="points"&&t.length!==d.length&&(t.length>d.length?(l=d,d=b._prepareArrayForTween(d,t,i.closed())):(o=t,t=b._prepareArrayForTween(t,d,i.closed()))),e.indexOf("fill")===0)for(let u=0;u<a;u++)if(u%2===0)s.push(t[u]-d[u]);else{const g=b.colorToRGBA(d[u]);c=b.colorToRGBA(t[u]),d[u]=g,s.push({r:c.r-g.r,g:c.g-g.g,b:c.b-g.b,a:c.a-g.a})}else for(let u=0;u<a;u++)s.push(t[u]-d[u]);else Ns.indexOf(e)!==-1?(d=b.colorToRGBA(d),c=b.colorToRGBA(t),s={r:c.r-d.r,g:c.g-d.g,b:c.b-d.b,a:c.a-d.a}):s=t-d;ie.attrs[r][this._id][e]={start:d,diff:s,end:t,trueEnd:o,trueStart:l},ie.tweens[r][e]=this._id}_tweenFunc(e){const t=this.node,i=ie.attrs[t._id][this._id];let r,s,a,o,l,c,h,d;for(r in i){if(s=i[r],a=s.start,o=s.diff,d=s.end,b._isArray(a))if(l=[],h=Math.max(a.length,d.length),r.indexOf("fill")===0)for(c=0;c<h;c++)c%2===0?l.push((a[c]||0)+o[c]*e):l.push("rgba("+Math.round(a[c].r+o[c].r*e)+","+Math.round(a[c].g+o[c].g*e)+","+Math.round(a[c].b+o[c].b*e)+","+(a[c].a+o[c].a*e)+")");else for(c=0;c<h;c++)l.push((a[c]||0)+o[c]*e);else Ns.indexOf(r)!==-1?l="rgba("+Math.round(a.r+o.r*e)+","+Math.round(a.g+o.g*e)+","+Math.round(a.b+o.b*e)+","+(a.a+o.a*e)+")":l=a+o*e;t.setAttr(r,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const e=this.node,t=ie.attrs[e._id][this._id];t.points&&t.points.trueEnd&&e.setAttr("points",t.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const e=this.node,t=ie.attrs[e._id][this._id];t.points&&t.points.trueStart&&e.points(t.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(e){return this.tween.seek(e*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const e=this.node._id,t=this._id,i=ie.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const r in i)delete ie.tweens[e][r];delete ie.attrs[e][t],ie.tweens[e]&&(Object.keys(ie.tweens[e]).length===0&&delete ie.tweens[e],Object.keys(ie.attrs[e]).length===0&&delete ie.attrs[e])}}ie.attrs={};ie.tweens={};I.prototype.to=function(n){const e=n.onFinish;n.node=this,n.onFinish=function(){this.destroy(),e&&e()},new ie(n).play()};const ei={BackEaseIn(n,e,t,i){return t*(n/=i)*n*((1.70158+1)*n-1.70158)+e},BackEaseOut(n,e,t,i){return t*((n=n/i-1)*n*((1.70158+1)*n+1.70158)+1)+e},BackEaseInOut(n,e,t,i){let r=1.70158;return(n/=i/2)<1?t/2*(n*n*(((r*=1.525)+1)*n-r))+e:t/2*((n-=2)*n*(((r*=1.525)+1)*n+r)+2)+e},ElasticEaseIn(n,e,t,i,r,s){let a=0;return n===0?e:(n/=i)===1?e+t:(s||(s=i*.3),!r||r<Math.abs(t)?(r=t,a=s/4):a=s/(2*Math.PI)*Math.asin(t/r),-(r*Math.pow(2,10*(n-=1))*Math.sin((n*i-a)*(2*Math.PI)/s))+e)},ElasticEaseOut(n,e,t,i,r,s){let a=0;return n===0?e:(n/=i)===1?e+t:(s||(s=i*.3),!r||r<Math.abs(t)?(r=t,a=s/4):a=s/(2*Math.PI)*Math.asin(t/r),r*Math.pow(2,-10*n)*Math.sin((n*i-a)*(2*Math.PI)/s)+t+e)},ElasticEaseInOut(n,e,t,i,r,s){let a=0;return n===0?e:(n/=i/2)===2?e+t:(s||(s=i*(.3*1.5)),!r||r<Math.abs(t)?(r=t,a=s/4):a=s/(2*Math.PI)*Math.asin(t/r),n<1?-.5*(r*Math.pow(2,10*(n-=1))*Math.sin((n*i-a)*(2*Math.PI)/s))+e:r*Math.pow(2,-10*(n-=1))*Math.sin((n*i-a)*(2*Math.PI)/s)*.5+t+e)},BounceEaseOut(n,e,t,i){return(n/=i)<1/2.75?t*(7.5625*n*n)+e:n<2/2.75?t*(7.5625*(n-=1.5/2.75)*n+.75)+e:n<2.5/2.75?t*(7.5625*(n-=2.25/2.75)*n+.9375)+e:t*(7.5625*(n-=2.625/2.75)*n+.984375)+e},BounceEaseIn(n,e,t,i){return t-ei.BounceEaseOut(i-n,0,t,i)+e},BounceEaseInOut(n,e,t,i){return n<i/2?ei.BounceEaseIn(n*2,0,t,i)*.5+e:ei.BounceEaseOut(n*2-i,0,t,i)*.5+t*.5+e},EaseIn(n,e,t,i){return t*(n/=i)*n+e},EaseOut(n,e,t,i){return-t*(n/=i)*(n-2)+e},EaseInOut(n,e,t,i){return(n/=i/2)<1?t/2*n*n+e:-t/2*(--n*(n-2)-1)+e},StrongEaseIn(n,e,t,i){return t*(n/=i)*n*n*n*n+e},StrongEaseOut(n,e,t,i){return t*((n=n/i-1)*n*n*n*n+1)+e},StrongEaseInOut(n,e,t,i){return(n/=i/2)<1?t/2*n*n*n*n*n+e:t/2*((n-=2)*n*n*n*n+2)+e},Linear(n,e,t,i){return t*n/i+e}},zs=b._assign(R,{Util:b,Transform:ve,Node:I,Container:Te,Stage:cr,stages:Jt,Layer:lt,FastLayer:gs,Group:kt,DD:J,Shape:A,shapes:Qt,Animation:we,Tween:ie,Easings:ei,Context:or,Canvas:hs});class Be extends A{_sceneFunc(e){const t=R.getAngle(this.angle()),i=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,i),e.arc(0,0,this.innerRadius(),t,0,!i),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),i=this.clockwise(),r=R.getAngle(i?360-this.angle():this.angle()),s=Math.cos(Math.min(r,Math.PI)),a=1,o=Math.sin(Math.min(Math.max(Math.PI,r),3*Math.PI/2)),l=Math.sin(Math.min(r,Math.PI/2)),c=s*(s>0?e:t),h=a*t,d=o*(o>0?e:t),u=l*(l>0?t:e);return{x:c,y:i?-1*u:d,width:h-c,height:u-d}}}Be.prototype._centroid=!0;Be.prototype.className="Arc";Be.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];ae(Be);y.addGetterSetter(Be,"innerRadius",0,E());y.addGetterSetter(Be,"outerRadius",0,E());y.addGetterSetter(Be,"angle",0,E());y.addGetterSetter(Be,"clockwise",!1,Ae());function Gr(n,e,t,i,r,s,a){const o=Math.sqrt(Math.pow(t-n,2)+Math.pow(i-e,2)),l=Math.sqrt(Math.pow(r-t,2)+Math.pow(s-i,2)),c=a*o/(o+l),h=a*l/(o+l),d=t-c*(r-n),u=i-c*(s-e),g=t+h*(r-n),f=i+h*(s-e);return[d,u,g,f]}function $s(n,e){const t=n.length,i=[];for(let r=2;r<t-2;r+=2){const s=Gr(n[r-2],n[r-1],n[r],n[r+1],n[r+2],n[r+3],e);isNaN(s[0])||(i.push(s[0]),i.push(s[1]),i.push(n[r]),i.push(n[r+1]),i.push(s[2]),i.push(s[3]))}return i}function Ul(n){const e=[[n[0],n[2],n[4],n[6]],[n[1],n[3],n[5],n[7]]],t=[];for(const i of e){const r=-3*i[0]+9*i[1]-9*i[2]+3*i[3];if(r!==0){const s=6*i[0]-12*i[1]+6*i[2],a=-3*i[0]+3*i[1],o=s*s-4*r*a;if(o>=0){const l=Math.sqrt(o);t.push((-s+l)/(2*r)),t.push((-s-l)/(2*r))}}}return t.filter(i=>i>0&&i<1).flatMap(i=>e.map(r=>{const s=1-i;return s*s*s*r[0]+3*s*s*i*r[1]+3*s*i*i*r[2]+i*i*i*r[3]}))}class Fe extends A{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),i=t.length,r=this.tension(),s=this.closed(),a=this.bezier();if(!i)return;let o=0;if(e.beginPath(),e.moveTo(t[0],t[1]),r!==0&&i>4){const l=this.getTensionPoints(),c=l.length;for(o=s?0:4,s||e.quadraticCurveTo(l[0],l[1],l[2],l[3]);o<c-2;)e.bezierCurveTo(l[o++],l[o++],l[o++],l[o++],l[o++],l[o++]);s||e.quadraticCurveTo(l[c-2],l[c-1],t[i-2],t[i-1])}else if(a)for(o=2;o<i;)e.bezierCurveTo(t[o++],t[o++],t[o++],t[o++],t[o++],t[o++]);else for(o=2;o<i;o+=2)e.lineTo(t[o],t[o+1]);s?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():$s(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=Gr(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),s=Gr(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),a=$s(e,i);return[r[2],r[3]].concat(a).concat([s[0],s[1],e[t-2],e[t-1],s[2],s[3],r[0],r[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:this.bezier()?e=[e[0],e[1],...Ul(this.points()),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],i=e[0],r=e[1],s=e[1],a,o;for(let l=0;l<e.length/2;l++)a=e[l*2],o=e[l*2+1],t=Math.min(t,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);return{x:t,y:r,width:i-t,height:s-r}}}Fe.prototype.className="Line";Fe.prototype._attrsAffectingSize=["points","bezier","tension"];ae(Fe);y.addGetterSetter(Fe,"closed",!1);y.addGetterSetter(Fe,"bezier",!1);y.addGetterSetter(Fe,"tension",0,E());y.addGetterSetter(Fe,"points",[],al());const Wl=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],Yl=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],Xl=[[1],[1,1],[1,2,1],[1,3,3,1]],Vs=(n,e,t)=>{let i,r;const a=t/2;i=0;for(let o=0;o<20;o++)r=a*Wl[20][o]+a,i+=Yl[20][o]*ql(n,e,r);return a*i},Us=(n,e,t)=>{t===void 0&&(t=1);const i=n[0]-2*n[1]+n[2],r=e[0]-2*e[1]+e[2],s=2*n[1]-2*n[0],a=2*e[1]-2*e[0],o=4*(i*i+r*r),l=4*(i*s+r*a),c=s*s+a*a;if(o===0)return t*Math.sqrt(Math.pow(n[2]-n[0],2)+Math.pow(e[2]-e[0],2));const h=l/(2*o),d=c/o,u=t+h,g=d-h*h,f=u*u+g>0?Math.sqrt(u*u+g):0,m=h*h+g>0?Math.sqrt(h*h+g):0,C=h+Math.sqrt(h*h+g)!==0?g*Math.log(Math.abs((u+f)/(h+m))):0;return Math.sqrt(o)/2*(u*f-h*m+C)};function ql(n,e,t){const i=Nr(1,t,n),r=Nr(1,t,e),s=i*i+r*r;return Math.sqrt(s)}const Nr=(n,e,t)=>{const i=t.length-1;let r,s;if(i===0)return 0;if(n===0){s=0;for(let a=0;a<=i;a++)s+=Xl[i][a]*Math.pow(1-e,i-a)*Math.pow(e,a)*t[a];return s}else{r=new Array(i);for(let a=0;a<i;a++)r[a]=i*(t[a+1]-t[a]);return Nr(n-1,e,r)}},Ws=(n,e,t)=>{let i=1,r=n/e,s=(n-t(r))/e,a=0;for(;i>.001;){const o=t(r+s),l=Math.abs(n-o)/e;if(l<i)i=l,r+=s;else{const c=t(r-s),h=Math.abs(n-c)/e;h<i?(i=h,r-=s):s/=2}if(a++,a>500)break}return r};class re extends A{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=re.parsePathData(this.data()),this.pathLength=re.getPathLength(this.dataArray)}_sceneFunc(e){const t=this.dataArray;e.beginPath();let i=!1;for(let r=0;r<t.length;r++){const s=t[r].command,a=t[r].points;switch(s){case"L":e.lineTo(a[0],a[1]);break;case"M":e.moveTo(a[0],a[1]);break;case"C":e.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5]);break;case"Q":e.quadraticCurveTo(a[0],a[1],a[2],a[3]);break;case"A":const o=a[0],l=a[1],c=a[2],h=a[3],d=a[4],u=a[5],g=a[6],f=a[7],m=c>h?c:h,C=c>h?1:c/h,v=c>h?h/c:1;e.translate(o,l),e.rotate(g),e.scale(C,v),e.arc(0,0,m,d,d+u,1-f),e.scale(1/C,1/v),e.rotate(-g),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const c=l.points[4],h=l.points[5],d=l.points[4]+h;let u=Math.PI/180;if(Math.abs(c-d)<u&&(u=Math.abs(c-d)),h<0)for(let g=c-u;g>d;g-=u){const f=re.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}else for(let g=c+u;g<d;g+=u){const f=re.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}}else if(l.command==="C")for(let c=0;c<=1;c+=.01){const h=re.getPointOnCubicBezier(c,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);e.push(h.x,h.y)}else e=e.concat(l.points)});let t=e[0],i=e[0],r=e[1],s=e[1],a,o;for(let l=0;l<e.length/2;l++)a=e[l*2],o=e[l*2+1],isNaN(a)||(t=Math.min(t,a),i=Math.max(i,a)),isNaN(o)||(r=Math.min(r,o),s=Math.max(s,o));return{x:t,y:r,width:i-t,height:s-r}}getLength(){return this.pathLength}getPointAtLength(e){return re.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,i,r){return Math.sqrt((i-e)*(i-e)+(r-t)*(r-t))}static getPathLength(e){let t=0;for(let i=0;i<e.length;++i)t+=e[i].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let i,r=0,s=t.length;if(!s)return null;for(;r<s&&e>t[r].pathLength;)e-=t[r].pathLength,++r;if(r===s)return i=t[r-1].points.slice(-2),{x:i[0],y:i[1]};if(e<.01)return t[r].command==="M"?(i=t[r].points.slice(0,2),{x:i[0],y:i[1]}):{x:t[r].start.x,y:t[r].start.y};const a=t[r],o=a.points;switch(a.command){case"L":return re.getPointOnLine(e,a.start.x,a.start.y,o[0],o[1]);case"C":return re.getPointOnCubicBezier(Ws(e,re.getPathLength(t),m=>Vs([a.start.x,o[0],o[2],o[4]],[a.start.y,o[1],o[3],o[5]],m)),a.start.x,a.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return re.getPointOnQuadraticBezier(Ws(e,re.getPathLength(t),m=>Us([a.start.x,o[0],o[2]],[a.start.y,o[1],o[3]],m)),a.start.x,a.start.y,o[0],o[1],o[2],o[3]);case"A":const l=o[0],c=o[1],h=o[2],d=o[3],u=o[5],g=o[6];let f=o[4];return f+=u*e/a.pathLength,re.getPointOnEllipticalArc(l,c,h,d,f,g)}return null}static getPointOnLine(e,t,i,r,s,a,o){a=a??t,o=o??i;const l=this.getLineLength(t,i,r,s);if(l<1e-10)return{x:t,y:i};if(r===t)return{x:a,y:o+(s>i?e:-e)};const c=(s-i)/(r-t),h=Math.sqrt(e*e/(1+c*c))*(r<t?-1:1),d=c*h;if(Math.abs(o-i-c*(a-t))<1e-10)return{x:a+h,y:o+d};const u=((a-t)*(r-t)+(o-i)*(s-i))/(l*l),g=t+u*(r-t),f=i+u*(s-i),m=this.getLineLength(a,o,g,f),C=Math.sqrt(e*e-m*m),v=Math.sqrt(C*C/(1+c*c))*(r<t?-1:1),S=c*v;return{x:g+v,y:f+S}}static getPointOnCubicBezier(e,t,i,r,s,a,o,l,c){function h(C){return C*C*C}function d(C){return 3*C*C*(1-C)}function u(C){return 3*C*(1-C)*(1-C)}function g(C){return(1-C)*(1-C)*(1-C)}const f=l*h(e)+a*d(e)+r*u(e)+t*g(e),m=c*h(e)+o*d(e)+s*u(e)+i*g(e);return{x:f,y:m}}static getPointOnQuadraticBezier(e,t,i,r,s,a,o){function l(g){return g*g}function c(g){return 2*g*(1-g)}function h(g){return(1-g)*(1-g)}const d=a*l(e)+r*c(e)+t*h(e),u=o*l(e)+s*c(e)+i*h(e);return{x:d,y:u}}static getPointOnEllipticalArc(e,t,i,r,s,a){const o=Math.cos(a),l=Math.sin(a),c={x:i*Math.cos(s),y:r*Math.sin(s)};return{x:e+(c.x*o-c.y*l),y:t+(c.x*l+c.y*o)}}static parsePathData(e){if(!e)return[];let t=e;const i=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(let d=0;d<i.length;d++)t=t.replace(new RegExp(i[d],"g"),"|"+i[d]);const r=t.split("|"),s=[],a=[];let o=0,l=0;const c=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let h;for(let d=1;d<r.length;d++){let u=r[d],g=u.charAt(0);for(u=u.slice(1),a.length=0;h=c.exec(u);)a.push(h[0]);let f=[],m=g==="A"||g==="a"?0:-1;for(let C=0,v=a.length;C<v;C++){const S=a[C];if(S==="00"){f.push(0,0),m>=0&&(m+=2,m>=7&&(m-=7));continue}if(m>=0){if(m===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),f.push(parseFloat(S.slice(2))),m+=3,m>=7&&(m-=7);continue}if(S==="11"||S==="10"||S==="01"){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),m+=2,m>=7&&(m-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),m+=1,m>=7&&(m-=7);continue}}else if(m===4){if(/^[01]\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseFloat(S.slice(1))),m+=2,m>=7&&(m-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),m+=1,m>=7&&(m-=7);continue}}const T=parseFloat(S);isNaN(T)?f.push(0):f.push(T),m+=1,m>=7&&(m-=7)}else{const T=parseFloat(S);isNaN(T)?f.push(0):f.push(T)}}for(;f.length>0&&!isNaN(f[0]);){let C="",v=[];const S=o,T=l;let k,_,w,D,x,M,O,z,H,$;switch(g){case"l":o+=f.shift(),l+=f.shift(),C="L",v.push(o,l);break;case"L":o=f.shift(),l=f.shift(),v.push(o,l);break;case"m":const V=f.shift(),G=f.shift();if(o+=V,l+=G,C="M",s.length>2&&s[s.length-1].command==="z"){for(let L=s.length-2;L>=0;L--)if(s[L].command==="M"){o=s[L].points[0]+V,l=s[L].points[1]+G;break}}v.push(o,l),g="l";break;case"M":o=f.shift(),l=f.shift(),C="M",v.push(o,l),g="L";break;case"h":o+=f.shift(),C="L",v.push(o,l);break;case"H":o=f.shift(),C="L",v.push(o,l);break;case"v":l+=f.shift(),C="L",v.push(o,l);break;case"V":l=f.shift(),C="L",v.push(o,l);break;case"C":v.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),l=f.shift(),v.push(o,l);break;case"c":v.push(o+f.shift(),l+f.shift(),o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),C="C",v.push(o,l);break;case"S":_=o,w=l,k=s[s.length-1],k.command==="C"&&(_=o+(o-k.points[2]),w=l+(l-k.points[3])),v.push(_,w,f.shift(),f.shift()),o=f.shift(),l=f.shift(),C="C",v.push(o,l);break;case"s":_=o,w=l,k=s[s.length-1],k.command==="C"&&(_=o+(o-k.points[2]),w=l+(l-k.points[3])),v.push(_,w,o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),C="C",v.push(o,l);break;case"Q":v.push(f.shift(),f.shift()),o=f.shift(),l=f.shift(),v.push(o,l);break;case"q":v.push(o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),C="Q",v.push(o,l);break;case"T":_=o,w=l,k=s[s.length-1],k.command==="Q"&&(_=o+(o-k.points[0]),w=l+(l-k.points[1])),o=f.shift(),l=f.shift(),C="Q",v.push(_,w,o,l);break;case"t":_=o,w=l,k=s[s.length-1],k.command==="Q"&&(_=o+(o-k.points[0]),w=l+(l-k.points[1])),o+=f.shift(),l+=f.shift(),C="Q",v.push(_,w,o,l);break;case"A":D=f.shift(),x=f.shift(),M=f.shift(),O=f.shift(),z=f.shift(),H=o,$=l,o=f.shift(),l=f.shift(),C="A",v=this.convertEndpointToCenterParameterization(H,$,o,l,O,z,D,x,M);break;case"a":D=f.shift(),x=f.shift(),M=f.shift(),O=f.shift(),z=f.shift(),H=o,$=l,o+=f.shift(),l+=f.shift(),C="A",v=this.convertEndpointToCenterParameterization(H,$,o,l,O,z,D,x,M);break}s.push({command:C||g,points:v,start:{x:S,y:T},pathLength:this.calcLength(S,T,C||g,v)})}(g==="z"||g==="Z")&&s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(e,t,i,r){let s,a,o,l;const c=re;switch(i){case"L":return c.getLineLength(e,t,r[0],r[1]);case"C":return Vs([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return Us([e,r[0],r[2]],[t,r[1],r[3]],1);case"A":s=0;const h=r[4],d=r[5],u=r[4]+d;let g=Math.PI/180;if(Math.abs(h-u)<g&&(g=Math.abs(h-u)),a=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),d<0)for(l=h-g;l>u;l-=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;else for(l=h+g;l<u;l+=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;return o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],u,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),s}return 0}static convertEndpointToCenterParameterization(e,t,i,r,s,a,o,l,c){const h=c*(Math.PI/180),d=Math.cos(h)*(e-i)/2+Math.sin(h)*(t-r)/2,u=-1*Math.sin(h)*(e-i)/2+Math.cos(h)*(t-r)/2,g=d*d/(o*o)+u*u/(l*l);g>1&&(o*=Math.sqrt(g),l*=Math.sqrt(g));let f=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));s===a&&(f*=-1),isNaN(f)&&(f=0);const m=f*o*u/l,C=f*-l*d/o,v=(e+i)/2+Math.cos(h)*m-Math.sin(h)*C,S=(t+r)/2+Math.sin(h)*m+Math.cos(h)*C,T=function(O){return Math.sqrt(O[0]*O[0]+O[1]*O[1])},k=function(O,z){return(O[0]*z[0]+O[1]*z[1])/(T(O)*T(z))},_=function(O,z){return(O[0]*z[1]<O[1]*z[0]?-1:1)*Math.acos(k(O,z))},w=_([1,0],[(d-m)/o,(u-C)/l]),D=[(d-m)/o,(u-C)/l],x=[(-1*d-m)/o,(-1*u-C)/l];let M=_(D,x);return k(D,x)<=-1&&(M=Math.PI),k(D,x)>=1&&(M=0),a===0&&M>0&&(M=M-2*Math.PI),a===1&&M<0&&(M=M+2*Math.PI),[v,S,o,l,w,M,h,a]}}re.prototype.className="Path";re.prototype._attrsAffectingSize=["data"];ae(re);y.addGetterSetter(re,"data");class ct extends Fe{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,i=this.points();let r=i;const s=this.tension()!==0&&i.length>4;s&&(r=this.getTensionPoints());const a=this.pointerLength(),o=i.length;let l,c;if(s){const u=[r[r.length-4],r[r.length-3],r[r.length-2],r[r.length-1],i[o-2],i[o-1]],g=re.calcLength(r[r.length-4],r[r.length-3],"C",u),f=re.getPointOnQuadraticBezier(Math.min(1,1-a/g),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-f.x,c=i[o-1]-f.y}else l=i[o-2]-i[o-4],c=i[o-1]-i[o-3];const h=(Math.atan2(c,l)+t)%t,d=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(i[o-2],i[o-1]),e.rotate(h),e.moveTo(0,0),e.lineTo(-a,d/2),e.lineTo(-a,-d/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(i[0],i[1]),s?(l=(r[0]+r[2])/2-i[0],c=(r[1]+r[3])/2-i[1]):(l=i[2]-i[0],c=i[3]-i[1]),e.rotate((Math.atan2(-c,-l)+t)%t),e.moveTo(0,0),e.lineTo(-a,d/2),e.lineTo(-a,-d/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}}ct.prototype.className="Arrow";ae(ct);y.addGetterSetter(ct,"pointerLength",10,E());y.addGetterSetter(ct,"pointerWidth",10,E());y.addGetterSetter(ct,"pointerAtBeginning",!1);y.addGetterSetter(ct,"pointerAtEnding",!0);class At extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}At.prototype._centroid=!0;At.prototype.className="Circle";At.prototype._attrsAffectingSize=["radius"];ae(At);y.addGetterSetter(At,"radius",0,E());class Ke extends A{_sceneFunc(e){const t=this.radiusX(),i=this.radiusY();e.beginPath(),e.save(),t!==i&&e.scale(1,i/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}Ke.prototype.className="Ellipse";Ke.prototype._centroid=!0;Ke.prototype._attrsAffectingSize=["radiusX","radiusY"];ae(Ke);y.addComponentsGetterSetter(Ke,"radius",["x","y"]);y.addGetterSetter(Ke,"radiusX",0,E());y.addGetterSetter(Ke,"radiusY",0,E());let Ie=class Ia extends A{constructor(e){super(e),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",t=>{this._removeImageLoad(t.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const e=this.image();e&&e.complete||e&&e.readyState===4||e&&e.addEventListener&&e.addEventListener("load",this._loadListener)}_removeImageLoad(e){e&&e.removeEventListener&&e.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const e=!!this.cornerRadius(),t=this.hasShadow();return e&&t?!0:super._useBufferCanvas(!0)}_sceneFunc(e){const t=this.getWidth(),i=this.getHeight(),r=this.cornerRadius(),s=this.attrs.image;let a;if(s){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?a=[s,this.cropX(),this.cropY(),o,l,0,0,t,i]:a=[s,0,0,t,i]}(this.hasFill()||this.hasStroke()||r)&&(e.beginPath(),r?b.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)),s&&(r&&e.clip(),e.drawImage.apply(e,a))}_hitFunc(e){const t=this.width(),i=this.height(),r=this.cornerRadius();e.beginPath(),r?b.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}getWidth(){var e,t,i;return(i=(e=this.attrs.width)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.width)!==null&&i!==void 0?i:0}getHeight(){var e,t,i;return(i=(e=this.attrs.height)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.height)!==null&&i!==void 0?i:0}static fromURL(e,t,i=null){const r=b.createImageElement();r.onload=function(){const s=new Ia({image:r});t(s)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Ie.prototype.className="Image";Ie.prototype._attrsAffectingSize=["image"];ae(Ie);y.addGetterSetter(Ie,"cornerRadius",0,lr(4));y.addGetterSetter(Ie,"image");y.addComponentsGetterSetter(Ie,"crop",["x","y","width","height"]);y.addGetterSetter(Ie,"cropX",0,E());y.addGetterSetter(Ie,"cropY",0,E());y.addGetterSetter(Ie,"cropWidth",0,E());y.addGetterSetter(Ie,"cropHeight",0,E());const Ea=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],jl="Change.konva",Kl="none",zr="up",$r="right",Vr="down",Ur="left",Zl=Ea.length;class fs extends kt{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,i;const r=function(){t._sync()};for(i=0;i<Zl;i++)e.on(Ea[i]+jl,r)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),i,r,s,a,o,l,c;if(e&&t){switch(i=e.width(),r=e.height(),s=t.pointerDirection(),a=t.pointerWidth(),c=t.pointerHeight(),o=0,l=0,s){case zr:o=i/2,l=-1*c;break;case $r:o=i+a,l=r/2;break;case Vr:o=i/2,l=r+c;break;case Ur:o=-1*a,l=r/2;break}t.setAttrs({x:-1*o,y:-1*l,width:i,height:r}),e.setAttrs({x:-1*o,y:-1*l})}}}fs.prototype.className="Label";ae(fs);class ht extends A{_sceneFunc(e){const t=this.width(),i=this.height(),r=this.pointerDirection(),s=this.pointerWidth(),a=this.pointerHeight(),o=this.cornerRadius();let l=0,c=0,h=0,d=0;typeof o=="number"?l=c=h=d=Math.min(o,t/2,i/2):(l=Math.min(o[0]||0,t/2,i/2),c=Math.min(o[1]||0,t/2,i/2),d=Math.min(o[2]||0,t/2,i/2),h=Math.min(o[3]||0,t/2,i/2)),e.beginPath(),e.moveTo(l,0),r===zr&&(e.lineTo((t-s)/2,0),e.lineTo(t/2,-1*a),e.lineTo((t+s)/2,0)),e.lineTo(t-c,0),e.arc(t-c,c,c,Math.PI*3/2,0,!1),r===$r&&(e.lineTo(t,(i-a)/2),e.lineTo(t+s,i/2),e.lineTo(t,(i+a)/2)),e.lineTo(t,i-d),e.arc(t-d,i-d,d,0,Math.PI/2,!1),r===Vr&&(e.lineTo((t+s)/2,i),e.lineTo(t/2,i+a),e.lineTo((t-s)/2,i)),e.lineTo(h,i),e.arc(h,i-h,h,Math.PI/2,Math.PI,!1),r===Ur&&(e.lineTo(0,(i+a)/2),e.lineTo(-1*s,i/2),e.lineTo(0,(i-a)/2)),e.lineTo(0,l),e.arc(l,l,l,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,i=this.pointerWidth(),r=this.pointerHeight(),s=this.pointerDirection(),a=this.width(),o=this.height();return s===zr?(t-=r,o+=r):s===Vr?o+=r:s===Ur?(e-=i*1.5,a+=i):s===$r&&(a+=i*1.5),{x:e,y:t,width:a,height:o}}}ht.prototype.className="Tag";ae(ht);y.addGetterSetter(ht,"pointerDirection",Kl);y.addGetterSetter(ht,"pointerWidth",0,E());y.addGetterSetter(ht,"pointerHeight",0,E());y.addGetterSetter(ht,"cornerRadius",0,lr(4));class Ci extends A{_sceneFunc(e){const t=this.cornerRadius(),i=this.width(),r=this.height();e.beginPath(),t?b.drawRoundedRectPath(e,i,r,t):e.rect(0,0,i,r),e.closePath(),e.fillStrokeShape(this)}}Ci.prototype.className="Rect";ae(Ci);y.addGetterSetter(Ci,"cornerRadius",0,lr(4));class Ze extends A{_sceneFunc(e){const t=this._getPoints(),i=this.radius(),r=this.sides(),s=this.cornerRadius();if(e.beginPath(),s)b.drawRoundedPolygonPath(e,t,r,i,s);else{e.moveTo(t[0].x,t[0].y);for(let a=1;a<t.length;a++)e.lineTo(t[a].x,t[a].y)}e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,i=[];for(let r=0;r<e;r++)i.push({x:t*Math.sin(r*2*Math.PI/e),y:-1*t*Math.cos(r*2*Math.PI/e)});return i}getSelfRect(){const e=this._getPoints();let t=e[0].x,i=e[0].x,r=e[0].y,s=e[0].y;return e.forEach(a=>{t=Math.min(t,a.x),i=Math.max(i,a.x),r=Math.min(r,a.y),s=Math.max(s,a.y)}),{x:t,y:r,width:i-t,height:s-r}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Ze.prototype.className="RegularPolygon";Ze.prototype._centroid=!0;Ze.prototype._attrsAffectingSize=["radius"];ae(Ze);y.addGetterSetter(Ze,"radius",0,E());y.addGetterSetter(Ze,"sides",0,E());y.addGetterSetter(Ze,"cornerRadius",0,lr(4));const Ys=Math.PI*2;class dt extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,Ys,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),Ys,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}dt.prototype.className="Ring";dt.prototype._centroid=!0;dt.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(dt);y.addGetterSetter(dt,"innerRadius",0,E());y.addGetterSetter(dt,"outerRadius",0,E());class De extends A{constructor(e){super(e),this._updated=!0,this.anim=new we(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,s=this.animations()[t],a=this.frameOffsets(),o=s[r+0],l=s[r+1],c=s[r+2],h=s[r+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,c,h),e.closePath(),e.fillStrokeShape(this)),d)if(a){const u=a[t],g=i*2;e.drawImage(d,o,l,c,h,u[g+0],u[g+1],c,h)}else e.drawImage(d,o,l,c,h,0,0,c,h)}_hitFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,s=this.animations()[t],a=this.frameOffsets(),o=s[r+2],l=s[r+3];if(e.beginPath(),a){const c=a[t],h=i*2;e.rect(c[h+0],c[h+1],o,l)}else e.rect(0,0,o,l);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation(),i=this.animations(),r=i[t],s=r.length/4;e<s-1?this.frameIndex(e+1):this.frameIndex(0)}}De.prototype.className="Sprite";ae(De);y.addGetterSetter(De,"animation");y.addGetterSetter(De,"animations");y.addGetterSetter(De,"frameOffsets");y.addGetterSetter(De,"image");y.addGetterSetter(De,"frameIndex",0,E());y.addGetterSetter(De,"frameRate",17,E());y.backCompat(De,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Je extends A{_sceneFunc(e){const t=this.innerRadius(),i=this.outerRadius(),r=this.numPoints();e.beginPath(),e.moveTo(0,0-i);for(let s=1;s<r*2;s++){const a=s%2===0?i:t,o=a*Math.sin(s*Math.PI/r),l=-1*a*Math.cos(s*Math.PI/r);e.lineTo(o,l)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}Je.prototype.className="Star";Je.prototype._centroid=!0;Je.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(Je);y.addGetterSetter(Je,"numPoints",5,E());y.addGetterSetter(Je,"innerRadius",0,E());y.addGetterSetter(Je,"outerRadius",0,E());function Ve(n){return[...n].reduce((e,t,i,r)=>{if(new RegExp("\\p{Emoji}","u").test(t)){const s=r[i+1];s&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(s)?(e.push(t+s),r[i+1]=""):e.push(t)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(t+(r[i+1]||""))?e.push(t+r[i+1]):i>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(t)?e[e.length-1]+=t:t&&e.push(t);return e},[])}const pt="auto",Jl="center",Ma="inherit",Dt="justify",Ql="Change.konva",ec="2d",Xs="-",Ra="left",tc="text",ic="Text",rc="top",sc="bottom",qs="middle",La="normal",nc="px ",Ii=" ",ac="right",js="rtl",oc="word",lc="char",Ks="none",Cr="…",Da=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],cc=Da.length;function hc(n){return n.split(",").map(e=>{e=e.trim();const t=e.indexOf(" ")>=0,i=e.indexOf('"')>=0||e.indexOf("'")>=0;return t&&!i&&(e=`"${e}"`),e}).join(", ")}let Ei;function vr(){return Ei||(Ei=b.createCanvasElement().getContext(ec),Ei)}function dc(n){n.fillText(this._partialText,this._partialTextX,this._partialTextY)}function uc(n){n.setAttr("miterLimit",2),n.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function pc(n){return n=n||{},!n.fillLinearGradientColorStops&&!n.fillRadialGradientColorStops&&!n.fillPatternImage&&(n.fill=n.fill||"black"),n}class se extends A{constructor(e){super(pc(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<cc;t++)this.on(Da[t]+Ql,this._setTextData);this._setTextData()}_sceneFunc(e){var t,i;const r=this.textArr,s=r.length;if(!this.text())return;let a=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,c=this.verticalAlign(),h=this.direction(),d=0,u=this.align(),g=this.getWidth(),f=this.letterSpacing(),m=this.charRenderFunc(),C=this.fill(),v=this.textDecoration(),S=this.underlineOffset(),T=v.indexOf("underline")!==-1,k=v.indexOf("line-through")!==-1,_;h=h===Ma?e.direction:h;let w=l/2,D=qs;if(!R.legacyTextRendering){const x=this.measureSize("M");D="alphabetic";const M=(t=x.fontBoundingBoxAscent)!==null&&t!==void 0?t:x.actualBoundingBoxAscent,O=(i=x.fontBoundingBoxDescent)!==null&&i!==void 0?i:x.actualBoundingBoxDescent;w=(M-O)/2+l/2}for(h===js&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",D),e.setAttr("textAlign",Ra),c===qs?d=(this.getHeight()-s*l-a*2)/2:c===sc&&(d=this.getHeight()-s*l-a*2),e.translate(a,d+a),_=0;_<s;_++){let x=0,M=0;const O=r[_],z=O.text,H=O.width,$=O.lastInParagraph;if(e.save(),u===ac?x+=g-H-a*2:u===Jl&&(x+=(g-H-a*2)/2),T){e.save(),e.beginPath();const G=S??(R.legacyTextRendering?Math.round(o/2):Math.round(o/4)),L=x,X=w+M+G;e.moveTo(L,X);const B=u===Dt&&!$?g-a*2:H;e.lineTo(L+Math.round(B),X),e.lineWidth=o/15;const Q=this._getLinearGradient();e.strokeStyle=Q||C,e.stroke(),e.restore()}const V=x;if(h!==js&&(f!==0||u===Dt||m)){const G=z.split(" ").length-1,L=Ve(z);for(let X=0;X<L.length;X++){const B=L[X];if(B===" "&&!$&&u===Dt&&(x+=(g-a*2-H)/G),this._partialTextX=x,this._partialTextY=w+M,this._partialText=B,m){e.save();const ne=r.slice(0,_).reduce((K,me)=>K+Ve(me.text).length,0),Y=X+ne;m({char:B,index:Y,x,y:w+M,lineIndex:_,column:X,isLastInLine:$,width:this.measureSize(B).width,context:e})}e.fillStrokeShape(this),m&&e.restore(),x+=this.measureSize(B).width+f}}else f!==0&&e.setAttr("letterSpacing",`${f}px`),this._partialTextX=x,this._partialTextY=w+M,this._partialText=z,e.fillStrokeShape(this);if(k){e.save(),e.beginPath();const G=R.legacyTextRendering?0:-Math.round(o/4),L=V;e.moveTo(L,w+M+G);const X=u===Dt&&!$?g-a*2:H;e.lineTo(L+Math.round(X),w+M+G),e.lineWidth=o/15;const B=this._getLinearGradient();e.strokeStyle=B||C,e.stroke(),e.restore()}e.restore(),s>1&&(w+=l)}}_hitFunc(e){const t=this.getWidth(),i=this.getHeight();e.beginPath(),e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=b._isString(e)?e:e==null?"":e+"";return this._setAttr(tc,t),this}getWidth(){return this.attrs.width===pt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===pt||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return b.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,i,r,s,a,o,l,c,h,d,u;let g=vr(),f=this.fontSize(),m;g.save(),g.font=this._getContextFont(),m=g.measureText(e),g.restore();const C=f/100;return{actualBoundingBoxAscent:(t=m.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*C,actualBoundingBoxDescent:(i=m.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(r=m.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*C,actualBoundingBoxRight:(s=m.actualBoundingBoxRight)!==null&&s!==void 0?s:75.732421875*C,alphabeticBaseline:(a=m.alphabeticBaseline)!==null&&a!==void 0?a:0,emHeightAscent:(o=m.emHeightAscent)!==null&&o!==void 0?o:100*C,emHeightDescent:(l=m.emHeightDescent)!==null&&l!==void 0?l:-20*C,fontBoundingBoxAscent:(c=m.fontBoundingBoxAscent)!==null&&c!==void 0?c:91*C,fontBoundingBoxDescent:(h=m.fontBoundingBoxDescent)!==null&&h!==void 0?h:21*C,hangingBaseline:(d=m.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*C,ideographicBaseline:(u=m.ideographicBaseline)!==null&&u!==void 0?u:-21*C,width:m.width,height:f}}_getContextFont(){return this.fontStyle()+Ii+this.fontVariant()+Ii+(this.fontSize()+nc)+hc(this.fontFamily())}_addTextLine(e){this.align()===Dt&&(e=e.trim());const i=this._getTextWidth(e);return this.textArr.push({text:e,width:i,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),i=e.length;return vr().measureText(e).width+t*i}_setTextData(){let e=this.text().split(`
15
- `),t=+this.fontSize(),i=0,r=this.lineHeight()*t,s=this.attrs.width,a=this.attrs.height,o=s!==pt&&s!==void 0,l=a!==pt&&a!==void 0,c=this.padding(),h=s-c*2,d=a-c*2,u=0,g=this.wrap(),f=g!==Ks,m=g!==lc&&f,C=this.ellipsis();this.textArr=[],vr().font=this._getContextFont();const v=C?this._getTextWidth(Cr):0;for(let S=0,T=e.length;S<T;++S){let k=e[S],_=this._getTextWidth(k);if(o&&_>h)for(;k.length>0;){let w=0,D=Ve(k).length,x="",M=0;for(;w<D;){const O=w+D>>>1,z=Ve(k),H=z.slice(0,O+1).join(""),$=this._getTextWidth(H);(C&&l&&u+r>d?$+v:$)<=h?(w=O+1,x=H,M=$):D=O}if(x){if(m){const H=Ve(k),$=Ve(x),V=H[$.length],G=V===Ii||V===Xs;let L;if(G&&M<=h)L=$.length;else{const X=$.lastIndexOf(Ii),B=$.lastIndexOf(Xs);L=Math.max(X,B)+1}L>0&&(w=L,x=H.slice(0,w).join(""),M=this._getTextWidth(x))}if(x=x.trimRight(),this._addTextLine(x),i=Math.max(i,M),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(k=Ve(k).slice(w).join("").trimLeft(),k.length>0&&(_=this._getTextWidth(k),_<=h)){this._addTextLine(k),u+=r,i=Math.max(i,_);break}}else break}else this._addTextLine(k),u+=r,i=Math.max(i,_),this._shouldHandleEllipsis(u)&&S<T-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),l&&u+r>d)break}this.textHeight=t,this.textWidth=i}_shouldHandleEllipsis(e){const t=+this.fontSize(),i=this.lineHeight()*t,r=this.attrs.height,s=r!==pt&&r!==void 0,a=this.padding(),o=r-a*2;return!(this.wrap()!==Ks)||s&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==pt&&e!==void 0,i=this.padding(),r=e-i*2,s=this.ellipsis(),a=this.textArr[this.textArr.length-1];!a||!s||(t&&(this._getTextWidth(a.text+Cr)<r||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+Cr))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t?!0:super._useBufferCanvas()}}se.prototype._fillFunc=dc;se.prototype._strokeFunc=uc;se.prototype.className=ic;se.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];ae(se);y.overWriteSetter(se,"width",us());y.overWriteSetter(se,"height",us());y.addGetterSetter(se,"direction",Ma);y.addGetterSetter(se,"fontFamily","Arial");y.addGetterSetter(se,"fontSize",12,E());y.addGetterSetter(se,"fontStyle",La);y.addGetterSetter(se,"fontVariant",La);y.addGetterSetter(se,"padding",0,E());y.addGetterSetter(se,"align",Ra);y.addGetterSetter(se,"verticalAlign",rc);y.addGetterSetter(se,"lineHeight",1,E());y.addGetterSetter(se,"wrap",oc);y.addGetterSetter(se,"ellipsis",!1,Ae());y.addGetterSetter(se,"letterSpacing",0,E());y.addGetterSetter(se,"text","",ot());y.addGetterSetter(se,"textDecoration","");y.addGetterSetter(se,"underlineOffset",void 0,E());y.addGetterSetter(se,"charRenderFunc",void 0);const gc="",Oa="normal";function Ba(n){n.fillText(this.partialText,0,0)}function Fa(n){n.strokeText(this.partialText,0,0)}class ce extends A{constructor(e){super(e),this.dummyCanvas=b.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return re.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:re.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=re.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),i=this.fill(),r=this.fontSize(),s=this.glyphInfo,a=t.indexOf("underline")!==-1,o=t.indexOf("line-through")!==-1;a&&e.beginPath();for(let l=0;l<s.length;l++){e.save();const c=s[l].p0;e.translate(c.x,c.y),e.rotate(s[l].rotation),this.partialText=s[l].text,e.fillStrokeShape(this),a&&(l===0&&e.moveTo(0,r/2+1),e.lineTo(s[l].width,r/2+1)),e.restore()}if(a&&(e.strokeStyle=i,e.lineWidth=r/20,e.stroke()),o){e.beginPath();for(let l=0;l<s.length;l++){e.save();const c=s[l].p0;e.translate(c.x,c.y),e.rotate(s[l].rotation),l===0&&e.moveTo(0,0),e.lineTo(s[l].width,0),e.restore()}e.strokeStyle=i,e.lineWidth=r/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const i=t[0].p0;e.moveTo(i.x,i.y)}for(let i=0;i<t.length;i++){const r=t[i].p1;e.lineTo(r.x,r.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return b.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return se.prototype.setText.call(this,e)}_getContextFont(){return se.prototype._getContextFont.call(this)}_getTextSize(e){const i=this.dummyCanvas.getContext("2d");i.save(),i.font=this._getContextFont();const r=i.measureText(e);return i.restore(),{width:r.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const e=Ve(this.text()),t=[];let i=0;for(let d=0;d<e.length;d++)t.push({char:e[d],width:this._getTextSize(e[d]).width}),i+=t[d].width;const{height:r}=this._getTextSize(this.attrs.text);if(this.textWidth=i,this.textHeight=r,this.glyphInfo=[],!this.attrs.data)return null;const s=this.letterSpacing(),a=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*s,0);let c=0;a==="center"&&(c=Math.max(0,this.pathLength/2-l/2)),a==="right"&&(c=Math.max(0,this.pathLength-l));let h=c;for(let d=0;d<t.length;d++){const u=this._getPointAtLength(h);if(!u)return;const g=t[d].char;let f=t[d].width+s;if(g===" "&&a==="justify"){const k=this.text().split(" ").length-1;f+=(this.pathLength-l)/k}const m=this._getPointAtLength(h+f);if(!m)return;const C=re.getLineLength(u.x,u.y,m.x,m.y);let v=0;if(o)try{v=o(t[d-1].char,g)*this.fontSize()}catch{v=0}u.x+=v,m.x+=v,this.textWidth+=v;const S=re.getPointOnLine(v+C/2,u.x,u.y,m.x,m.y),T=Math.atan2(m.y-u.y,m.x-u.x);this.glyphInfo.push({transposeX:S.x,transposeY:S.y,text:e[d],rotation:T,p0:u,p1:m,width:C}),h+=f}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,i=e[0]||0,r=e[1]||0,s=e[1]||0,a,o;for(let c=0;c<e.length/2;c++)a=e[c*2],o=e[c*2+1],t=Math.min(t,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);const l=this.fontSize();return{x:t-l/2,y:r-l/2,width:i-t+l,height:s-r+l}}destroy(){return b.releaseCanvas(this.dummyCanvas),super.destroy()}}ce.prototype._fillFunc=Ba;ce.prototype._strokeFunc=Fa;ce.prototype._fillFuncHit=Ba;ce.prototype._strokeFuncHit=Fa;ce.prototype.className="TextPath";ce.prototype._attrsAffectingSize=["text","fontSize","data"];ae(ce);y.addGetterSetter(ce,"data");y.addGetterSetter(ce,"fontFamily","Arial");y.addGetterSetter(ce,"fontSize",12,E());y.addGetterSetter(ce,"fontStyle",Oa);y.addGetterSetter(ce,"align","left");y.addGetterSetter(ce,"letterSpacing",0,E());y.addGetterSetter(ce,"textBaseline","middle");y.addGetterSetter(ce,"fontVariant",Oa);y.addGetterSetter(ce,"text",gc);y.addGetterSetter(ce,"textDecoration","");y.addGetterSetter(ce,"kerningFunc",void 0);const Ha="tr-konva",fc=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(n=>n+`.${Ha}`).join(" "),Zs="nodesRect",mc=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],yc={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Sc="ontouchstart"in R._global;function Cc(n,e,t){if(n==="rotater")return t;e+=b.degToRad(yc[n]||0);const i=(b.radToDeg(e)%360+360)%360;return b._inRange(i,315+22.5,360)||b._inRange(i,0,22.5)?"ns-resize":b._inRange(i,45-22.5,45+22.5)?"nesw-resize":b._inRange(i,90-22.5,90+22.5)?"ew-resize":b._inRange(i,135-22.5,135+22.5)?"nwse-resize":b._inRange(i,180-22.5,180+22.5)?"ns-resize":b._inRange(i,225-22.5,225+22.5)?"nesw-resize":b._inRange(i,270-22.5,270+22.5)?"ew-resize":b._inRange(i,315-22.5,315+22.5)?"nwse-resize":(b.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}const ji=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function vc(n){return{x:n.x+n.width/2*Math.cos(n.rotation)+n.height/2*Math.sin(-n.rotation),y:n.y+n.height/2*Math.cos(n.rotation)+n.width/2*Math.sin(n.rotation)}}function Ga(n,e,t){const i=t.x+(n.x-t.x)*Math.cos(e)-(n.y-t.y)*Math.sin(e),r=t.y+(n.x-t.x)*Math.sin(e)+(n.y-t.y)*Math.cos(e);return{...n,rotation:n.rotation+e,x:i,y:r}}function Tc(n,e){const t=vc(n);return Ga(n,e,t)}function bc(n,e,t){let i=e;for(let r=0;r<n.length;r++){const s=R.getAngle(n[r]),a=Math.abs(s-e)%(Math.PI*2);Math.min(a,Math.PI*2-a)<t&&(i=s)}return i}let Wr=0;class W extends kt{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(fc,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return b.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return Ha+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(r=>r.isAncestorOf(this)?(b.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(r=>{const s=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(r._attrsAffectingSize.length){const a=r._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");r.on(a,s)}r.on(mc.map(a=>a+`.${this._getEventNamespace()}`).join(" "),s),r.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(r)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,i=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(i,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,i=>{if(!t)return;const r=e.getAbsolutePosition(),s=r.x-t.x,a=r.y-t.y;this.nodes().forEach(o=>{if(o===e||o.isDragging())return;const l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+s,y:l.y+a}),o.startDrag(i)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(Zs),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Zs,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),i){const r=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=e.getAbsoluteScale(i),a=e.getAbsolutePosition(i),o=r.x*s.x-e.offsetX()*s.x,l=r.y*s.y-e.offsetY()*s.y,c=(R.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),h={x:a.x+o*Math.cos(c)+l*Math.sin(-c),y:a.y+l*Math.cos(c)+o*Math.sin(c),width:r.width*s.x,height:r.height*s.y,rotation:c};return Ga(h,-R.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(c=>{const h=c.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:h.x,y:h.y},{x:h.x+h.width,y:h.y},{x:h.x+h.width,y:h.y+h.height},{x:h.x,y:h.y+h.height}],u=c.getAbsoluteTransform();d.forEach(function(g){const f=u.point(g);t.push(f)})});const i=new ve;i.rotate(-R.getAngle(this.rotation()));let r=1/0,s=1/0,a=-1/0,o=-1/0;t.forEach(function(c){const h=i.point(c);r===void 0&&(r=a=h.x,s=o=h.y),r=Math.min(r,h.x),s=Math.min(s,h.y),a=Math.max(a,h.x),o=Math.max(o,h.y)}),i.invert();const l=i.point({x:r,y:s});return{x:l.x,y:l.y,width:a-r,height:o-s,rotation:R.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),ji.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new Ci({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Sc?10:"auto"}),i=this;t.on("mousedown touchstart",function(r){i._handleMouseDown(r)}),t.on("dragstart",r=>{t.stopDrag(),r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),t.on("mouseenter",()=>{const r=R.getAngle(this.rotation()),s=this.rotateAnchorCursor(),a=Cc(e,r,s);t.getStage().content&&(t.getStage().content.style.cursor=a),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new A({name:"back",width:0,height:0,sceneFunc(t,i){const r=i.getParent(),s=r.padding(),a=i.width(),o=i.height();if(t.beginPath(),t.rect(-s,-s,a+s*2,o+s*2),r.rotateEnabled()&&r.rotateLineVisible()){const l=r.rotateAnchorAngle(),c=r.rotateAnchorOffset(),h=b.degToRad(l),d=Math.sin(h),u=-Math.cos(h),g=a/2,f=o/2;let m=1/0;u<0?m=Math.min(m,-f/u):u>0&&(m=Math.min(m,(o-f)/u)),d<0?m=Math.min(m,-g/d):d>0&&(m=Math.min(m,(a-g)/d));const C=g+d*m,v=f+u*m,S=b._sign(o),T=C+d*c*S,k=v+u*c*S;t.moveTo(C,v),t.lineTo(T,k)}t.fillStrokeShape(i)},hitFunc:(t,i)=>{if(!this.shouldOverdrawWholeArea())return;const r=this.padding();t.beginPath(),t.rect(-r,-r,i.width()+r*2,i.height()+r*2),t.fillStrokeShape(i)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),i=t.width,r=t.height,s=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));this.sin=Math.abs(r/s),this.cos=Math.abs(i/s),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const a=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-a.x,y:o.y-a.y},Wr++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(l=>{l._fire("transformstart",{evt:e.evt,target:l})})}_handleMouseMove(e){let t,i,r;const s=this.findOne("."+this._movingAnchorName),a=s.getStage();a.setPointersPositions(e);const o=a.getPointerPosition();let l={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const c=s.getAbsolutePosition();this.anchorDragBoundFunc()&&(l=this.anchorDragBoundFunc()(c,l,e)),s.setAbsolutePosition(l);const h=s.getAbsolutePosition();if(c.x===h.x&&c.y===h.y)return;if(this._movingAnchorName==="rotater"){const S=this._getNodeRect();t=s.x()-S.width/2,i=-s.y()+S.height/2;const T=R.getAngle(this.rotateAnchorAngle());let k=Math.atan2(-i,t)+Math.PI/2-T;S.height<0&&(k-=Math.PI);const w=R.getAngle(this.rotation())+k,D=R.getAngle(this.rotationSnapTolerance()),M=bc(this.rotationSnaps(),w,D)-S.rotation,O=Tc(S,M);this._fitNodesInto(O,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let g=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(S.x-s.x(),2)+Math.pow(S.y-s.y(),2));const T=this.findOne(".top-left").x()>S.x?-1:1,k=this.findOne(".top-left").y()>S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,this.findOne(".top-left").x(S.x-t),this.findOne(".top-left").y(S.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(s.y());else if(this._movingAnchorName==="top-right"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(s.x()-S.x,2)+Math.pow(S.y-s.y(),2));const T=this.findOne(".top-right").x()<S.x?-1:1,k=this.findOne(".top-right").y()>S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,this.findOne(".top-right").x(S.x+t),this.findOne(".top-right").y(S.y-i)}var f=s.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(s.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(s.x());else if(this._movingAnchorName==="bottom-left"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(S.x-s.x(),2)+Math.pow(s.y()-S.y,2));const T=S.x<s.x()?-1:1,k=s.y()<S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,s.x(S.x-t),s.y(S.y+i)}f=s.position(),this.findOne(".top-left").x(f.x),this.findOne(".bottom-right").y(f.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.y());else if(this._movingAnchorName==="bottom-right"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};r=Math.sqrt(Math.pow(s.x()-S.x,2)+Math.pow(s.y()-S.y,2));const T=this.findOne(".bottom-right").x()<S.x?-1:1,k=this.findOne(".bottom-right").y()<S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,this.findOne(".bottom-right").x(S.x+t),this.findOne(".bottom-right").y(S.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(g=this.centeredScaling()||e.altKey,g){const S=this.findOne(".top-left"),T=this.findOne(".bottom-right"),k=S.x(),_=S.y(),w=this.getWidth()-T.x(),D=this.getHeight()-T.y();T.move({x:-k,y:-_}),S.move({x:w,y:D})}const m=this.findOne(".top-left").getAbsolutePosition();t=m.x,i=m.y;const C=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),v=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:i,width:C,height:v,rotation:R.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const i=this.getNode();Wr--,this._fire("transformend",{evt:e,target:i}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),i&&this._nodes.forEach(r=>{var s;r._fire("transformend",{evt:e,target:r}),(s=r.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const i=this._getNodeRect(),r=1;if(b._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(b._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const s=new ve;if(s.rotate(R.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const u=s.point({x:-this.padding()*2,y:0});e.x+=u.x,e.y+=u.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const u=s.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const u=s.point({x:0,y:-this.padding()*2});e.x+=u.x,e.y+=u.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const u=s.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const u=this.boundBoxFunc()(i,e);u?e=u:b.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const a=1e7,o=new ve;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/a,i.height/a);const l=new ve,c=e.width/a,h=e.height/a;this.flipEnabled()===!1?(l.translate(e.x,e.y),l.rotate(e.rotation),l.translate(e.width<0?e.width:0,e.height<0?e.height:0),l.scale(Math.abs(c),Math.abs(h))):(l.translate(e.x,e.y),l.rotate(e.rotation),l.scale(c,h));const d=l.multiply(o.invert());this._nodes.forEach(u=>{var g;if(!u.getStage())return;const f=u.getParent().getAbsoluteTransform(),m=u.getTransform().copy();m.translate(u.offsetX(),u.offsetY());const C=new ve;C.multiply(f.copy().invert()).multiply(d).multiply(f).multiply(m);const v=C.decompose();u.setAttrs(v),(g=u.getLayer())===null||g===void 0||g.batchDraw()}),this.rotation(b._getRotation(e.rotation)),this._nodes.forEach(u=>{this._fire("transform",{evt:t,target:u}),u._fire("transform",{evt:t,target:u})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(b._getRotation(t.rotation));const i=t.width,r=t.height,s=this.enabledAnchors(),a=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),c=this.find("._anchor");c.forEach(w=>{w.setAttrs({width:l,height:l,offsetX:l/2,offsetY:l/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:l/2+o,offsetY:l/2+o,visible:a&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:a&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:a&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:l/2+o,visible:a&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:l/2-o,visible:a&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:l/2+o,offsetY:l/2-o,visible:a&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:l/2-o,visible:a&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:l/2-o,offsetY:l/2-o,visible:a&&s.indexOf("bottom-right")>=0});const h=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=b.degToRad(h),g=Math.sin(u),f=-Math.cos(u),m=i/2,C=r/2;let v=1/0;f<0?v=Math.min(v,-C/f):f>0&&(v=Math.min(v,(r-C)/f)),g<0?v=Math.min(v,-m/g):g>0&&(v=Math.min(v,(i-m)/g));const S=m+g*v,T=C+f*v,k=b._sign(r);this._batchChangeChild(".rotater",{x:S+g*d*k,y:T+f*d*k-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(w=>w.draggable()),x:0,y:0});const _=this.anchorStyleFunc();_&&c.forEach(w=>{_(w)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),kt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return I.prototype.toObject.call(this)}clone(e){return I.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}W.isTransforming=()=>Wr>0;function kc(n){return n instanceof Array||b.warn("enabledAnchors value should be an array"),n instanceof Array&&n.forEach(function(e){ji.indexOf(e)===-1&&b.warn("Unknown anchor name: "+e+". Available names are: "+ji.join(", "))}),n||[]}W.prototype.className="Transformer";ae(W);y.addGetterSetter(W,"enabledAnchors",ji,kc);y.addGetterSetter(W,"flipEnabled",!0,Ae());y.addGetterSetter(W,"resizeEnabled",!0);y.addGetterSetter(W,"anchorSize",10,E());y.addGetterSetter(W,"rotateEnabled",!0);y.addGetterSetter(W,"rotateLineVisible",!0);y.addGetterSetter(W,"rotationSnaps",[]);y.addGetterSetter(W,"rotateAnchorOffset",50,E());y.addGetterSetter(W,"rotateAnchorAngle",0,E());y.addGetterSetter(W,"rotateAnchorCursor","crosshair");y.addGetterSetter(W,"rotationSnapTolerance",5,E());y.addGetterSetter(W,"borderEnabled",!0);y.addGetterSetter(W,"anchorStroke","rgb(0, 161, 255)");y.addGetterSetter(W,"anchorStrokeWidth",1,E());y.addGetterSetter(W,"anchorFill","white");y.addGetterSetter(W,"anchorCornerRadius",0,E());y.addGetterSetter(W,"borderStroke","rgb(0, 161, 255)");y.addGetterSetter(W,"borderStrokeWidth",1,E());y.addGetterSetter(W,"borderDash");y.addGetterSetter(W,"keepRatio",!0);y.addGetterSetter(W,"shiftBehavior","default");y.addGetterSetter(W,"centeredScaling",!1);y.addGetterSetter(W,"ignoreStroke",!1);y.addGetterSetter(W,"padding",0,E());y.addGetterSetter(W,"nodes");y.addGetterSetter(W,"node");y.addGetterSetter(W,"boundBoxFunc");y.addGetterSetter(W,"anchorDragBoundFunc");y.addGetterSetter(W,"anchorStyleFunc");y.addGetterSetter(W,"shouldOverdrawWholeArea",!1);y.addGetterSetter(W,"useSingleNodeRotation",!0);y.backCompat(W,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class He extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,R.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}He.prototype.className="Wedge";He.prototype._centroid=!0;He.prototype._attrsAffectingSize=["radius"];ae(He);y.addGetterSetter(He,"radius",0,E());y.addGetterSetter(He,"angle",0,E());y.addGetterSetter(He,"clockwise",!1);y.backCompat(He,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Js(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const wc=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],xc=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function Pc(n,e){const t=n.data,i=n.width,r=n.height;let s,a,o,l,c,h,d,u,g,f,m,C,v,S,T,k,_,w,D,x;const M=e+e+1,O=i-1,z=r-1,H=e+1,$=H*(H+1)/2,V=new Js,G=wc[e],L=xc[e];let X=null,B=V,Q=null,ne=null;for(let Y=1;Y<M;Y++)B=B.next=new Js,Y===H&&(X=B);B.next=V,o=a=0;for(let Y=0;Y<r;Y++){C=v=S=T=l=c=h=d=0,u=H*(k=t[a]),g=H*(_=t[a+1]),f=H*(w=t[a+2]),m=H*(D=t[a+3]),l+=$*k,c+=$*_,h+=$*w,d+=$*D,B=V;for(let K=0;K<H;K++)B.r=k,B.g=_,B.b=w,B.a=D,B=B.next;for(let K=1;K<H;K++)s=a+((O<K?O:K)<<2),l+=(B.r=k=t[s])*(x=H-K),c+=(B.g=_=t[s+1])*x,h+=(B.b=w=t[s+2])*x,d+=(B.a=D=t[s+3])*x,C+=k,v+=_,S+=w,T+=D,B=B.next;Q=V,ne=X;for(let K=0;K<i;K++)t[a+3]=D=d*G>>L,D!==0?(D=255/D,t[a]=(l*G>>L)*D,t[a+1]=(c*G>>L)*D,t[a+2]=(h*G>>L)*D):t[a]=t[a+1]=t[a+2]=0,l-=u,c-=g,h-=f,d-=m,u-=Q.r,g-=Q.g,f-=Q.b,m-=Q.a,s=o+((s=K+e+1)<O?s:O)<<2,C+=Q.r=t[s],v+=Q.g=t[s+1],S+=Q.b=t[s+2],T+=Q.a=t[s+3],l+=C,c+=v,h+=S,d+=T,Q=Q.next,u+=k=ne.r,g+=_=ne.g,f+=w=ne.b,m+=D=ne.a,C-=k,v-=_,S-=w,T-=D,ne=ne.next,a+=4;o+=i}for(let Y=0;Y<i;Y++){v=S=T=C=c=h=d=l=0,a=Y<<2,u=H*(k=t[a]),g=H*(_=t[a+1]),f=H*(w=t[a+2]),m=H*(D=t[a+3]),l+=$*k,c+=$*_,h+=$*w,d+=$*D,B=V;for(let me=0;me<H;me++)B.r=k,B.g=_,B.b=w,B.a=D,B=B.next;let K=i;for(let me=1;me<=e;me++)a=K+Y<<2,l+=(B.r=k=t[a])*(x=H-me),c+=(B.g=_=t[a+1])*x,h+=(B.b=w=t[a+2])*x,d+=(B.a=D=t[a+3])*x,C+=k,v+=_,S+=w,T+=D,B=B.next,me<z&&(K+=i);a=Y,Q=V,ne=X;for(let me=0;me<r;me++)s=a<<2,t[s+3]=D=d*G>>L,D>0?(D=255/D,t[s]=(l*G>>L)*D,t[s+1]=(c*G>>L)*D,t[s+2]=(h*G>>L)*D):t[s]=t[s+1]=t[s+2]=0,l-=u,c-=g,h-=f,d-=m,u-=Q.r,g-=Q.g,f-=Q.b,m-=Q.a,s=Y+((s=me+H)<z?s:z)*i<<2,l+=C+=Q.r=t[s],c+=v+=Q.g=t[s+1],h+=S+=Q.b=t[s+2],d+=T+=Q.a=t[s+3],Q=Q.next,u+=k=ne.r,g+=_=ne.g,f+=w=ne.b,m+=D=ne.a,C-=k,v-=_,S-=w,T-=D,ne=ne.next,a+=i}}const _c=function(e){const t=Math.round(this.blurRadius());t>0&&Pc(e,t)};y.addGetterSetter(I,"blurRadius",0,E(),y.afterSetFilter);const Ac=function(n){const e=this.brightness()*255,t=n.data,i=t.length;for(let r=0;r<i;r+=4)t[r]+=e,t[r+1]+=e,t[r+2]+=e};y.addGetterSetter(I,"brightness",0,E(),y.afterSetFilter);const Ic=function(n){const e=this.brightness(),t=n.data,i=t.length;for(let r=0;r<i;r+=4)t[r]=Math.min(255,t[r]*e),t[r+1]=Math.min(255,t[r+1]*e),t[r+2]=Math.min(255,t[r+2]*e)},Ec=function(n){const e=Math.pow((this.contrast()+100)/100,2),t=n.data,i=t.length;let r=150,s=150,a=150;for(let o=0;o<i;o+=4)r=t[o],s=t[o+1],a=t[o+2],r/=255,r-=.5,r*=e,r+=.5,r*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,a/=255,a-=.5,a*=e,a+=.5,a*=255,r=r<0?0:r>255?255:r,s=s<0?0:s>255?255:s,a=a<0?0:a>255?255:a,t[o]=r,t[o+1]=s,t[o+2]=a};y.addGetterSetter(I,"contrast",0,E(),y.afterSetFilter);const Mc=function(n){var e,t,i,r,s,a,o,l,c;const h=n.data,d=n.width,u=n.height,g=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),f=Math.min(1,Math.max(0,(r=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&r!==void 0?r:.5)),C=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(a=(s=this.embossDirection)===null||s===void 0?void 0:s.call(this))!==null&&a!==void 0?a:"top-left"])!==null&&o!==void 0?o:315,v=!!((c=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&c!==void 0&&c),S=g*10,T=f*255,k=C*Math.PI/180,_=Math.cos(k),w=Math.sin(k),D=128/1020*S,x=new Uint8ClampedArray(h),M=new Float32Array(d*u);for(let V=0,G=0;G<h.length;G+=4,V++)M[V]=.2126*x[G]+.7152*x[G+1]+.0722*x[G+2];const O=[-1,0,1,-2,0,2,-1,0,1],z=[-1,-2,-1,0,0,0,1,2,1],H=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],$=V=>V<0?0:V>255?255:V;for(let V=1;V<u-1;V++)for(let G=1;G<d-1;G++){const L=V*d+G;let X=0,B=0;X+=M[L+H[0]]*O[0],B+=M[L+H[0]]*z[0],X+=M[L+H[1]]*O[1],B+=M[L+H[1]]*z[1],X+=M[L+H[2]]*O[2],B+=M[L+H[2]]*z[2],X+=M[L+H[3]]*O[3],B+=M[L+H[3]]*z[3],X+=M[L+H[5]]*O[5],B+=M[L+H[5]]*z[5],X+=M[L+H[6]]*O[6],B+=M[L+H[6]]*z[6],X+=M[L+H[7]]*O[7],B+=M[L+H[7]]*z[7],X+=M[L+H[8]]*O[8],B+=M[L+H[8]]*z[8];const Q=_*X+w*B,ne=$(T+Q*D),Y=L*4;if(v){const K=ne-T;h[Y]=$(x[Y]+K),h[Y+1]=$(x[Y+1]+K),h[Y+2]=$(x[Y+2]+K),h[Y+3]=x[Y+3]}else h[Y]=h[Y+1]=h[Y+2]=ne,h[Y+3]=x[Y+3]}for(let V=0;V<d;V++){let G=V*4,L=((u-1)*d+V)*4;h[G]=x[G],h[G+1]=x[G+1],h[G+2]=x[G+2],h[G+3]=x[G+3],h[L]=x[L],h[L+1]=x[L+1],h[L+2]=x[L+2],h[L+3]=x[L+3]}for(let V=1;V<u-1;V++){let G=V*d*4,L=(V*d+(d-1))*4;h[G]=x[G],h[G+1]=x[G+1],h[G+2]=x[G+2],h[G+3]=x[G+3],h[L]=x[L],h[L+1]=x[L+1],h[L+2]=x[L+2],h[L+3]=x[L+3]}return n};y.addGetterSetter(I,"embossStrength",.5,E(),y.afterSetFilter);y.addGetterSetter(I,"embossWhiteLevel",.5,E(),y.afterSetFilter);y.addGetterSetter(I,"embossDirection","top-left",void 0,y.afterSetFilter);y.addGetterSetter(I,"embossBlend",!1,void 0,y.afterSetFilter);function Tr(n,e,t,i,r){const s=t-e,a=r-i;if(s===0)return i+a/2;if(a===0)return i;let o=(n-e)/s;return o=a*o+i,o}const Rc=function(n){const e=n.data,t=e.length;let i=e[0],r=i,s,a=e[1],o=a,l,c=e[2],h=c,d;const u=this.enhance();if(u===0)return;for(let T=0;T<t;T+=4)s=e[T+0],s<i?i=s:s>r&&(r=s),l=e[T+1],l<a?a=l:l>o&&(o=l),d=e[T+2],d<c?c=d:d>h&&(h=d);r===i&&(r=255,i=0),o===a&&(o=255,a=0),h===c&&(h=255,c=0);let g,f,m,C,v,S;if(u>0)g=r+u*(255-r),f=i-u*(i-0),m=o+u*(255-o),C=a-u*(a-0),v=h+u*(255-h),S=c-u*(c-0);else{const T=(r+i)*.5;g=r+u*(r-T),f=i+u*(i-T);const k=(o+a)*.5;m=o+u*(o-k),C=a+u*(a-k);const _=(h+c)*.5;v=h+u*(h-_),S=c+u*(c-_)}for(let T=0;T<t;T+=4)e[T+0]=Tr(e[T+0],i,r,f,g),e[T+1]=Tr(e[T+1],a,o,C,m),e[T+2]=Tr(e[T+2],c,h,S,v)};y.addGetterSetter(I,"enhance",0,E(),y.afterSetFilter);const Lc=function(n){const e=n.data,t=e.length;for(let i=0;i<t;i+=4){const r=.34*e[i]+.5*e[i+1]+.16*e[i+2];e[i]=r,e[i+1]=r,e[i+2]=r}};y.addGetterSetter(I,"hue",0,E(),y.afterSetFilter);y.addGetterSetter(I,"saturation",0,E(),y.afterSetFilter);y.addGetterSetter(I,"luminance",0,E(),y.afterSetFilter);const Dc=function(n){const e=n.data,t=e.length,i=1,r=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=this.luminance()*127,o=i*r*Math.cos(s*Math.PI/180),l=i*r*Math.sin(s*Math.PI/180),c=.299*i+.701*o+.167*l,h=.587*i-.587*o+.33*l,d=.114*i-.114*o-.497*l,u=.299*i-.299*o-.328*l,g=.587*i+.413*o+.035*l,f=.114*i-.114*o+.293*l,m=.299*i-.3*o+1.25*l,C=.587*i-.586*o-1.05*l,v=.114*i+.886*o-.2*l;let S,T,k,_;for(let w=0;w<t;w+=4)S=e[w+0],T=e[w+1],k=e[w+2],_=e[w+3],e[w+0]=c*S+h*T+d*k+a,e[w+1]=u*S+g*T+f*k+a,e[w+2]=m*S+C*T+v*k+a,e[w+3]=_},Oc=function(n){const e=n.data,t=e.length,i=Math.pow(2,this.value()),r=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=i*r*Math.cos(s*Math.PI/180),o=i*r*Math.sin(s*Math.PI/180),l=.299*i+.701*a+.167*o,c=.587*i-.587*a+.33*o,h=.114*i-.114*a-.497*o,d=.299*i-.299*a-.328*o,u=.587*i+.413*a+.035*o,g=.114*i-.114*a+.293*o,f=.299*i-.3*a+1.25*o,m=.587*i-.586*a-1.05*o,C=.114*i+.886*a-.2*o;for(let v=0;v<t;v+=4){const S=e[v+0],T=e[v+1],k=e[v+2],_=e[v+3];e[v+0]=l*S+c*T+h*k,e[v+1]=d*S+u*T+g*k,e[v+2]=f*S+m*T+C*k,e[v+3]=_}};y.addGetterSetter(I,"hue",0,E(),y.afterSetFilter);y.addGetterSetter(I,"saturation",0,E(),y.afterSetFilter);y.addGetterSetter(I,"value",0,E(),y.afterSetFilter);const Bc=function(n){const e=n.data,t=e.length;for(let i=0;i<t;i+=4)e[i]=255-e[i],e[i+1]=255-e[i+1],e[i+2]=255-e[i+2]},Fc=function(n,e,t){const i=n.data,r=e.data,s=n.width,a=n.height,o=t.polarCenterX||s/2,l=t.polarCenterY||a/2;let c=Math.sqrt(o*o+l*l),h=s-o,d=a-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const g=a,f=s,m=360/f*Math.PI/180;for(let C=0;C<f;C+=1){const v=Math.sin(C*m),S=Math.cos(C*m);for(let T=0;T<g;T+=1){h=Math.floor(o+c*T/g*S),d=Math.floor(l+c*T/g*v);let k=(d*s+h)*4;const _=i[k+0],w=i[k+1],D=i[k+2],x=i[k+3];k=(C+T*s)*4,r[k+0]=_,r[k+1]=w,r[k+2]=D,r[k+3]=x}}},Hc=function(n,e,t){const i=n.data,r=e.data,s=n.width,a=n.height,o=t.polarCenterX||s/2,l=t.polarCenterY||a/2;let c=Math.sqrt(o*o+l*l),h=s-o,d=a-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const g=a,f=s,m=0;let C,v;for(h=0;h<s;h+=1)for(d=0;d<a;d+=1){const S=h-o,T=d-l,k=Math.sqrt(S*S+T*T)*g/c;let _=(Math.atan2(T,S)*180/Math.PI+360+m)%360;_=_*f/360,C=Math.floor(_),v=Math.floor(k);let w=(v*s+C)*4;const D=i[w+0],x=i[w+1],M=i[w+2],O=i[w+3];w=(d*s+h)*4,r[w+0]=D,r[w+1]=x,r[w+2]=M,r[w+3]=O}},Gc=function(n){const e=n.width,t=n.height;let i,r,s,a,o,l,c,h,d,u,g=Math.round(this.kaleidoscopePower());const f=Math.round(this.kaleidoscopeAngle()),m=Math.floor(e*(f%360)/360);if(g<1)return;const C=b.createCanvasElement();C.width=e,C.height=t;const v=C.getContext("2d").getImageData(0,0,e,t);b.releaseCanvas(C),Fc(n,v,{polarCenterX:e/2,polarCenterY:t/2});let S=e/Math.pow(2,g);for(;S<=8;)S=S*2,g-=1;S=Math.ceil(S);let T=S,k=0,_=T,w=1;for(m+S>e&&(k=T,_=0,w=-1),r=0;r<t;r+=1)for(i=k;i!==_;i+=w)s=Math.round(i+m)%e,d=(e*r+s)*4,o=v.data[d+0],l=v.data[d+1],c=v.data[d+2],h=v.data[d+3],u=(e*r+i)*4,v.data[u+0]=o,v.data[u+1]=l,v.data[u+2]=c,v.data[u+3]=h;for(r=0;r<t;r+=1)for(T=Math.floor(S),a=0;a<g;a+=1){for(i=0;i<T+1;i+=1)d=(e*r+i)*4,o=v.data[d+0],l=v.data[d+1],c=v.data[d+2],h=v.data[d+3],u=(e*r+T*2-i-1)*4,v.data[u+0]=o,v.data[u+1]=l,v.data[u+2]=c,v.data[u+3]=h;T*=2}Hc(v,n,{})};y.addGetterSetter(I,"kaleidoscopePower",2,E(),y.afterSetFilter);y.addGetterSetter(I,"kaleidoscopeAngle",0,E(),y.afterSetFilter);function Mi(n,e,t){let i=(t*n.width+e)*4;const r=[];return r.push(n.data[i++],n.data[i++],n.data[i++],n.data[i++]),r}function Ot(n,e){return Math.sqrt(Math.pow(n[0]-e[0],2)+Math.pow(n[1]-e[1],2)+Math.pow(n[2]-e[2],2))}function Nc(n){const e=[0,0,0];for(let t=0;t<n.length;t++)e[0]+=n[t][0],e[1]+=n[t][1],e[2]+=n[t][2];return e[0]/=n.length,e[1]/=n.length,e[2]/=n.length,e}function zc(n,e){const t=Mi(n,0,0),i=Mi(n,n.width-1,0),r=Mi(n,0,n.height-1),s=Mi(n,n.width-1,n.height-1),a=e||10;if(Ot(t,i)<a&&Ot(i,s)<a&&Ot(s,r)<a&&Ot(r,t)<a){const o=Nc([i,t,s,r]),l=[];for(let c=0;c<n.width*n.height;c++){const h=Ot(o,[n.data[c*4],n.data[c*4+1],n.data[c*4+2]]);l[c]=h<a?0:255}return l}}function $c(n,e){for(let t=0;t<n.width*n.height;t++)n.data[4*t+3]=e[t]}function Vc(n,e,t){const i=[1,1,1,1,0,1,1,1,1],r=Math.round(Math.sqrt(i.length)),s=Math.floor(r/2),a=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-s,f=l+u-s;if(g>=0&&g<t&&f>=0&&f<e){const m=g*e+f,C=i[d*r+u];h+=n[m]*C}}a[c]=h===255*8?255:0}return a}function Uc(n,e,t){const i=[1,1,1,1,1,1,1,1,1],r=Math.round(Math.sqrt(i.length)),s=Math.floor(r/2),a=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-s,f=l+u-s;if(g>=0&&g<t&&f>=0&&f<e){const m=g*e+f,C=i[d*r+u];h+=n[m]*C}}a[c]=h>=255*4?255:0}return a}function Wc(n,e,t){const i=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],r=Math.round(Math.sqrt(i.length)),s=Math.floor(r/2),a=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-s,f=l+u-s;if(g>=0&&g<t&&f>=0&&f<e){const m=g*e+f,C=i[d*r+u];h+=n[m]*C}}a[c]=h}return a}const Yc=function(n){const e=this.threshold();let t=zc(n,e);return t&&(t=Vc(t,n.width,n.height),t=Uc(t,n.width,n.height),t=Wc(t,n.width,n.height),$c(n,t)),n};y.addGetterSetter(I,"threshold",0,E(),y.afterSetFilter);const Xc=function(n){const e=this.noise()*255,t=n.data,i=t.length,r=e/2;for(let s=0;s<i;s+=4)t[s+0]+=r-2*r*Math.random(),t[s+1]+=r-2*r*Math.random(),t[s+2]+=r-2*r*Math.random()};y.addGetterSetter(I,"noise",.2,E(),y.afterSetFilter);const qc=function(n){let e=Math.ceil(this.pixelSize()),t=n.width,i=n.height,r=Math.ceil(t/e),s=Math.ceil(i/e),a=n.data;if(e<=0){b.error("pixelSize value can not be <= 0");return}for(let o=0;o<r;o+=1)for(let l=0;l<s;l+=1){let c=0,h=0,d=0,u=0;const g=o*e,f=g+e,m=l*e,C=m+e;let v=0;for(let S=g;S<f;S+=1)if(!(S>=t))for(let T=m;T<C;T+=1){if(T>=i)continue;const k=(t*T+S)*4;c+=a[k+0],h+=a[k+1],d+=a[k+2],u+=a[k+3],v+=1}c=c/v,h=h/v,d=d/v,u=u/v;for(let S=g;S<f;S+=1)if(!(S>=t))for(let T=m;T<C;T+=1){if(T>=i)continue;const k=(t*T+S)*4;a[k+0]=c,a[k+1]=h,a[k+2]=d,a[k+3]=u}}};y.addGetterSetter(I,"pixelSize",8,E(),y.afterSetFilter);const jc=function(n){const e=Math.round(this.levels()*254)+1,t=n.data,i=t.length,r=255/e;for(let s=0;s<i;s+=1)t[s]=Math.floor(t[s]/r)*r};y.addGetterSetter(I,"levels",.5,E(),y.afterSetFilter);const Kc=function(n){const e=n.data,t=e.length,i=this.red(),r=this.green(),s=this.blue();for(let a=0;a<t;a+=4){const o=(.34*e[a]+.5*e[a+1]+.16*e[a+2])/255;e[a]=o*i,e[a+1]=o*r,e[a+2]=o*s,e[a+3]=e[a+3]}};y.addGetterSetter(I,"red",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"green",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"blue",0,la,y.afterSetFilter);const Zc=function(n){const e=n.data,t=e.length,i=this.red(),r=this.green(),s=this.blue(),a=this.alpha();for(let o=0;o<t;o+=4){const l=1-a;e[o]=i*a+e[o]*l,e[o+1]=r*a+e[o+1]*l,e[o+2]=s*a+e[o+2]*l}};y.addGetterSetter(I,"red",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"green",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"blue",0,la,y.afterSetFilter);y.addGetterSetter(I,"alpha",1,function(n){return this._filterUpToDate=!1,n>1?1:n<0?0:n});const Jc=function(n){const e=n.data,t=e.length;for(let i=0;i<t;i+=4){const r=e[i+0],s=e[i+1],a=e[i+2];e[i+0]=Math.min(255,r*.393+s*.769+a*.189),e[i+1]=Math.min(255,r*.349+s*.686+a*.168),e[i+2]=Math.min(255,r*.272+s*.534+a*.131)}},Qc=function(n){const t=n.data;for(let i=0;i<t.length;i+=4){const r=t[i],s=t[i+1],a=t[i+2];.2126*r+.7152*s+.0722*a>=128&&(t[i]=255-r,t[i+1]=255-s,t[i+2]=255-a)}return n},eh=function(n){const e=this.threshold()*255,t=n.data,i=t.length;for(let r=0;r<i;r+=1)t[r]=t[r]<e?0:255};y.addGetterSetter(I,"threshold",.5,E(),y.afterSetFilter);const Z=zs.Util._assign(zs,{Arc:Be,Arrow:ct,Circle:At,Ellipse:Ke,Image:Ie,Label:fs,Tag:ht,Line:Fe,Path:re,Rect:Ci,RegularPolygon:Ze,Ring:dt,Sprite:De,Star:Je,Text:se,TextPath:ce,Transformer:W,Wedge:He,Filters:{Blur:_c,Brightness:Ic,Brighten:Ac,Contrast:Ec,Emboss:Mc,Enhance:Rc,Grayscale:Lc,HSL:Dc,HSV:Oc,Invert:Bc,Kaleidoscope:Gc,Mask:Yc,Noise:Xc,Pixelate:qc,Posterize:jc,RGB:Kc,RGBA:Zc,Sepia:Jc,Solarize:Qc,Threshold:eh}}),Na="media-editor-track.diagnostics.v1",Yr="media-editor-track.diagnostics.failure-window.v1",za="media-editor-track-diagnostics",Xe="snapshots",$a="state",Va="latest-failure-window",di=1,ms=1,Qs=40,th=48,ih=250,en=20,rh=100,sh=500,Xr=new Set(["pending-preview.begin","preview.sync.requested","media.seeking","media.seeked"]),nh=new Set([...Xr,"media.current-slot.seek","media.preload-slot.seek","media.play.requested","media.pause.requested","slot.recovery-check","runtime.state"]),tn={debug:10,info:20,warn:30,error:40},Ne={enabled:!0,persist:!0,storageQuotaMb:10,maxSessions:20,maxHotEvents:500,includeFullSourceUrl:!0,consoleSeverityThreshold:"error",highFrequencyEventThrottleMs:sh};function rn(n){return`${n}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function ah(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function Ua(n){if(!n||typeof n!="object")return!1;const e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function Tt(n,e,t){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n??null;if(typeof n=="bigint")return n.toString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack??null,cause:Tt(n.cause,e+1,t)};if(e>=4)return"[max-depth]";if(Array.isArray(n))return n.slice(0,40).map(i=>Tt(i,e+1,t));if(typeof n=="object"){if(t.has(n))return"[circular]";if(t.add(n),"tagName"in n&&typeof n.tagName=="string")return{tagName:n.tagName};if(!Ua(n))return String(n);const i={};for(const r of Object.keys(n).slice(0,60))i[r]=Tt(n[r],e+1,t);return i}return String(n)}function Ki(n){if(!n)return null;const e=Tt(n,0,new WeakSet);return Ua(e)?e:{value:e}}function oh(n){return Ki(n)}function Bt(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Ri(n){return typeof n=="string"&&n.length>0?n:null}function lh(){var i,r,s,a,o;const n=typeof navigator<"u"?navigator:null,e={platform:Ri(n==null?void 0:n.platform),hardwareConcurrency:Bt(n==null?void 0:n.hardwareConcurrency),deviceMemory:Bt(n==null?void 0:n.deviceMemory),maxTouchPoints:Bt(n==null?void 0:n.maxTouchPoints),language:Ri(n==null?void 0:n.language),languages:Array.isArray(n==null?void 0:n.languages)?n.languages.filter(l=>typeof l=="string"):null},t={online:typeof(n==null?void 0:n.onLine)=="boolean"?n.onLine:null,effectiveType:Ri((i=n==null?void 0:n.connection)==null?void 0:i.effectiveType),downlinkMbps:Bt((r=n==null?void 0:n.connection)==null?void 0:r.downlink),rttMs:Bt((s=n==null?void 0:n.connection)==null?void 0:s.rtt),saveData:typeof((a=n==null?void 0:n.connection)==null?void 0:a.saveData)=="boolean"?n.connection.saveData:null,connectionType:Ri((o=n==null?void 0:n.connection)==null?void 0:o.type)};return{hardware:e,network:t}}function sn(n,e={}){const t=lh(),i=Ki(n??null);return{...i??{},hardware:t.hardware,network:t.network,environmentCapturedAt:e.capturedAt??(i==null?void 0:i.environmentCapturedAt)??null,environmentExportedAt:e.exportedAt??(i==null?void 0:i.environmentExportedAt)??null}}function ch(n){return n?n instanceof Error?{name:n.name,message:n.message,stack:n.stack??null,cause:Tt(n.cause,1,new WeakSet)}:{name:null,message:typeof n=="string"?n:String(n),stack:null,cause:Tt(n,1,new WeakSet)}:null}function ti(){return{totalEvents:0,severityCounts:{debug:0,info:0,warn:0,error:0},categoryCounts:{session:0,resource:0,playback:0,runtime:0,recovery:0,"ui-trigger":0},failureCount:0,lastFailureEvent:null}}function hh(n){const e=n??ti();return{totalEvents:e.totalEvents,severityCounts:{debug:e.severityCounts.debug,info:e.severityCounts.info,warn:e.severityCounts.warn,error:e.severityCounts.error},categoryCounts:{session:e.categoryCounts.session,resource:e.categoryCounts.resource,playback:e.categoryCounts.playback,runtime:e.categoryCounts.runtime,recovery:e.categoryCounts.recovery,"ui-trigger":e.categoryCounts["ui-trigger"]},failureCount:e.failureCount,lastFailureEvent:e.lastFailureEvent?{...e.lastFailureEvent}:null}}function Wa(n){const e=ti();return n.forEach(t=>{e.totalEvents+=1,e.severityCounts[t.severity]+=1,e.categoryCounts[t.category]+=1,t.severity==="error"&&(e.failureCount+=1,e.lastFailureEvent={eventId:t.eventId,eventName:t.eventName,timestamp:t.timestamp,isoTime:t.isoTime,message:t.message,trackId:t.trackId,clipId:t.clipId,syncRequestId:t.syncRequestId,playbackAttemptId:t.playbackAttemptId})}),e}function nn(n){return hh(n.summary)}function dh(n){return{sequence:n.sequence,timestamp:n.timestamp,isoTime:n.isoTime,severity:n.severity,category:n.category,eventName:n.eventName,message:n.message,syncRequestId:n.syncRequestId,playbackAttemptId:n.playbackAttemptId,trackId:n.trackId,clipId:n.clipId,extra:n.extra,error:n.error}}function uh(n,e){n.totalEvents+=1,n.severityCounts[e.severity]+=1,n.categoryCounts[e.category]+=1,e.severity==="error"&&(n.failureCount+=1,n.lastFailureEvent={eventId:e.eventId,eventName:e.eventName,timestamp:e.timestamp,isoTime:e.isoTime,message:e.message,trackId:e.trackId,clipId:e.clipId,syncRequestId:e.syncRequestId,playbackAttemptId:e.playbackAttemptId})}function ph(n){return{enabled:(n==null?void 0:n.enabled)??Ne.enabled,persist:(n==null?void 0:n.persist)??Ne.persist,storageQuotaMb:(n==null?void 0:n.storageQuotaMb)??Ne.storageQuotaMb,maxSessions:Math.max(1,(n==null?void 0:n.maxSessions)??Ne.maxSessions),maxHotEvents:Math.max(20,(n==null?void 0:n.maxHotEvents)??Ne.maxHotEvents),includeFullSourceUrl:(n==null?void 0:n.includeFullSourceUrl)??Ne.includeFullSourceUrl,consoleSeverityThreshold:(n==null?void 0:n.consoleSeverityThreshold)??Ne.consoleSeverityThreshold,highFrequencyEventThrottleMs:Math.max(0,(n==null?void 0:n.highFrequencyEventThrottleMs)??Ne.highFrequencyEventThrottleMs)}}function gh(){try{if(typeof globalThis.localStorage>"u")return null;const n=globalThis.localStorage.getItem(Na);if(!n)return null;const e=JSON.parse(n);return(e==null?void 0:e.version)!==di||!Array.isArray(e.sessions)?null:e}catch{return null}}function fh(){try{if(typeof globalThis.localStorage>"u")return null;const n=globalThis.localStorage.getItem(Yr);if(!n)return null;const e=JSON.parse(n);return(e==null?void 0:e.version)!==ms||typeof e.sessionId!="string"||typeof e.failureEventId!="string"||!Array.isArray(e.events)?null:e}catch{return null}}function Ya(n){const e=Array.isArray(n.events)?n.events:[];return{...n,updatedAt:n.updatedAt||n.startedAt,events:e,summary:Wa(e)}}function Ft(n,e,t={}){const i=n.slice(-e.maxSessions).map(s=>{const a=s.events.slice(-e.maxHotEvents);return Ya({...s,events:a,updatedAt:s.updatedAt||s.startedAt})});if(!t.enforceStorageQuota)return i;const r=Math.max(2e5,Math.floor(e.storageQuotaMb*1024*1024));for(;i.length>0&&JSON.stringify({version:di,sessions:i}).length>r;)i.shift();return i}async function mh(n){return Xa($a,n)}async function yh(n){return Xa(Va,n)}async function Xa(n,e){if(typeof indexedDB>"u")return!1;try{const t=await new Promise((i,r)=>{const s=indexedDB.open(za,1);s.onupgradeneeded=()=>{const a=s.result;a.objectStoreNames.contains(Xe)||a.createObjectStore(Xe)},s.onsuccess=()=>i(s.result),s.onerror=()=>r(s.error)});return await new Promise((i,r)=>{const s=t.transaction(Xe,"readwrite");s.objectStore(Xe).put(e,n),s.oncomplete=()=>i(),s.onerror=()=>r(s.error),s.onabort=()=>r(s.error)}),t.close(),!0}catch{return!1}}async function Sh(){const n=await qa($a);return n&&typeof n=="object"&&"version"in n&&n.version===di&&"sessions"in n&&Array.isArray(n.sessions)?n:null}async function Ch(){const n=await qa(Va);return n&&typeof n=="object"&&"version"in n&&n.version===ms&&"sessionId"in n&&typeof n.sessionId=="string"&&"failureEventId"in n&&typeof n.failureEventId=="string"&&"events"in n&&Array.isArray(n.events)?n:null}async function qa(n){if(typeof indexedDB>"u")return null;try{const e=await new Promise((i,r)=>{const s=indexedDB.open(za,1);s.onupgradeneeded=()=>{const a=s.result;a.objectStoreNames.contains(Xe)||a.createObjectStore(Xe)},s.onsuccess=()=>i(s.result),s.onerror=()=>r(s.error)}),t=await new Promise((i,r)=>{const o=e.transaction(Xe,"readonly").objectStore(Xe).get(n);o.onsuccess=()=>i(o.result??null),o.onerror=()=>r(o.error)});return e.close(),t}catch{return null}}function vh(n,e){return!n&&!e?null:{...n??{},...e??{}}}class ja{constructor(e){p(this,"config");p(this,"listeners",new Set);p(this,"liveListeners",new Map);p(this,"state");p(this,"currentSessionId",null);p(this,"latestFailureWindow");p(this,"activeFailureCapture",null);p(this,"notifyTimeoutId",null);p(this,"persistTimeoutId",null);p(this,"highFrequencyEventTimestamps",new Map);this.config=ph(e);const t=gh();this.latestFailureWindow=fh(),this.state={version:di,sessions:Ft((t==null?void 0:t.sessions)??[],this.config,{enforceStorageQuota:this.config.persist})},this.restoreIndexedDbState()}startSession(e){const t=new Date().toISOString(),i={sessionId:rn("diag-session"),startedAt:Date.now(),updatedAt:Date.now(),metadata:sn(e,{capturedAt:t}),sequence:0,events:[],summary:ti()};return this.currentSessionId=i.sessionId,this.state.sessions=Ft([...this.state.sessions,i],this.config),this.emit({severity:"info",category:"session",eventName:"session.started",message:"Diagnostic session started",extra:i.metadata??void 0}),this.getSnapshot()}getCurrentSessionId(){return this.currentSessionId}emit(e){if(!this.config.enabled)return null;const t=this.ensureCurrentSession();if(!t)return null;const i=Date.now();t.updatedAt=i;const r=this.resolveHighFrequencyDecision(e,i);if(r==="drop")return null;const s=this.findCoalescedEvent(t,e,i);if(s)return r==="skip-update"||(this.updateCoalescedEvent(s,e,i),this.schedulePersist(),this.scheduleNotify()),s;t.sequence+=1;const a=this.createEvent(t,e,i,t.sequence);return t.events.push(a),uh(t.summary,a),this.trimSessionEvents(t),this.captureFailureWindow(t,a),this.state.sessions=Ft(this.state.sessions,this.config),this.emitToConsole(a),this.schedulePersist(),this.scheduleNotify(),a}subscribe(e){return this.listeners.add(e),e(this.getSnapshot()),()=>{this.listeners.delete(e)}}subscribeLive(e,t=en){const i=Math.max(1,t);return this.liveListeners.set(e,i),e(this.getLiveSnapshot(this.currentSessionId,i)),()=>{this.liveListeners.delete(e)}}getSnapshot(e=this.currentSessionId){const t=this.resolveSession(e);return{sessionId:t.sessionId,startedAt:t.startedAt,updatedAt:t.updatedAt,metadata:t.metadata,events:[...t.events],summary:nn(t)}}getLiveSnapshot(e=this.currentSessionId,t=en){const i=this.resolveSession(e),r=Math.max(1,t);return{sessionId:i.sessionId,startedAt:i.startedAt,updatedAt:i.updatedAt,metadata:i.metadata,summary:nn(i),recentEvents:i.events.slice(-r).map(s=>dh(s))}}exportPackage(e={}){var c;const t=this.getSnapshot(e.sessionId??this.currentSessionId),i=Math.max(1,e.recentFailureContext??40),r=Math.max(1,e.recentEventsFallback??200),s=new Date().toISOString(),{failureWindow:a,failureWindowSource:o}=this.resolveExportFailureWindow(t,i,r),l=sn(t.metadata,{capturedAt:((c=t.metadata)==null?void 0:c.environmentCapturedAt)??null,exportedAt:s});return{exportedAt:s,session:{sessionId:t.sessionId,startedAt:t.startedAt,updatedAt:t.updatedAt,metadata:l,summary:t.summary},rawEvents:t.events,failureWindow:a,failureWindowSource:o}}clear(e=!0){var t,i;if(this.clearScheduledTasks(),e&&this.currentSessionId){this.state.sessions=this.state.sessions.filter(r=>r.sessionId!==this.currentSessionId),((t=this.latestFailureWindow)==null?void 0:t.sessionId)===this.currentSessionId&&(this.latestFailureWindow=null),((i=this.activeFailureCapture)==null?void 0:i.sessionId)===this.currentSessionId&&(this.activeFailureCapture=null),this.currentSessionId=null,this.persistNow(),this.notifyNow();return}this.state.sessions=[],this.latestFailureWindow=null,this.activeFailureCapture=null,this.currentSessionId=null,this.persistNow(),this.notifyNow()}ensureCurrentSession(){return this.currentSessionId||this.startSession(),this.state.sessions.find(e=>e.sessionId===this.currentSessionId)??null}resolveSession(e=this.currentSessionId){return(e?this.state.sessions.find(t=>t.sessionId===e):null)??this.state.sessions[this.state.sessions.length-1]??{sessionId:"diagnostics-empty",startedAt:Date.now(),updatedAt:Date.now(),metadata:null,sequence:0,events:[],summary:ti()}}createEvent(e,t,i,r,s=rn("diag-event")){return{eventId:s,sessionId:e.sessionId,sequence:r,timestamp:i,isoTime:new Date(i).toISOString(),perfTimeMs:ah(),severity:t.severity,category:t.category,eventName:t.eventName,message:t.message??t.eventName,syncRequestId:t.syncRequestId??null,playbackAttemptId:t.playbackAttemptId??null,previewBackend:t.previewBackend??null,trackId:t.trackId??null,clipId:t.clipId??null,slotKey:t.slotKey??null,sourceUrl:this.normalizeUrl(t.sourceUrl),desiredSourceUrl:this.normalizeUrl(t.desiredSourceUrl),actualSourceUrl:this.normalizeUrl(t.actualSourceUrl),mediaState:Ki(t.mediaState),runtimeState:oh(t.runtimeState),error:ch(t.error),extra:Ki(t.extra)}}trimSessionEvents(e){const t=e.events.length-this.config.maxHotEvents;t<=0||(e.events=e.events.slice(t),e.summary=Wa(e.events))}findCoalescedEvent(e,t,i){if(!Xr.has(t.eventName)||t.severity==="warn"||t.severity==="error")return null;const r=this.buildEventIdentity(t);for(let s=e.events.length-1;s>=0;s-=1){const a=e.events[s];if(i-a.timestamp>rh)break;if(this.areEventIdentitiesEqual(r,a))return a}return null}resolveHighFrequencyDecision(e,t){if(e.severity==="warn"||e.severity==="error"||!nh.has(e.eventName))return"record";const i=this.config.highFrequencyEventThrottleMs;if(i<=0)return"record";const r=this.buildHighFrequencyKey(e),s=this.highFrequencyEventTimestamps.get(r);return s!==void 0&&t-s<i?Xr.has(e.eventName)?"skip-update":"drop":(this.highFrequencyEventTimestamps.set(r,t),"record")}buildHighFrequencyKey(e){const t=this.buildEventIdentity(e);return[t.eventName,t.playbackAttemptId??"",t.trackId??"",t.clipId??"",t.slotKey??"",t.syncRequestId??""].join("|")}buildEventIdentity(e){const t=e.eventName==="preview.sync.requested"||e.eventName==="pending-preview.begin"?null:e.syncRequestId??null;return{eventName:e.eventName,playbackAttemptId:e.playbackAttemptId??null,trackId:e.trackId??null,clipId:e.clipId??null,slotKey:e.slotKey??null,syncRequestId:t}}areEventIdentitiesEqual(e,t){const i=t.eventName==="preview.sync.requested"||t.eventName==="pending-preview.begin"?null:t.syncRequestId;return e.eventName===t.eventName&&e.playbackAttemptId===t.playbackAttemptId&&e.trackId===t.trackId&&e.clipId===t.clipId&&e.slotKey===t.slotKey&&e.syncRequestId===i}updateCoalescedEvent(e,t,i){const r=this.createEvent({sessionId:e.sessionId,startedAt:i,updatedAt:i,metadata:null,sequence:e.sequence,events:[],summary:ti()},t,i,e.sequence,e.eventId);Object.assign(e,r)}normalizeUrl(e){if(!e)return null;if(this.config.includeFullSourceUrl)return e;try{const t=new URL(e,typeof location<"u"?location.href:"https://localhost");return`${t.origin}${t.pathname}`}catch{return e.split("?")[0]||e}}emitToConsole(e){if(tn[e.severity]<tn[this.config.consoleSeverityThreshold]||e.severity!=="warn"&&e.severity!=="error")return;(e.severity==="error"?console.error.bind(console):console.warn.bind(console))(`[Diagnostics:${e.severity}] ${e.eventName}`,{message:e.message,sessionId:e.sessionId,playbackAttemptId:e.playbackAttemptId,syncRequestId:e.syncRequestId,trackId:e.trackId,clipId:e.clipId,error:e.error,extra:e.extra})}scheduleNotify(){this.notifyTimeoutId||(this.notifyTimeoutId=setTimeout(()=>{this.notifyTimeoutId=null,this.notifyNow()},th))}notifyNow(){if(this.listeners.size>0){const e=this.getSnapshot();this.listeners.forEach(t=>t(e))}this.liveListeners.size>0&&this.liveListeners.forEach((e,t)=>{t(this.getLiveSnapshot(this.currentSessionId,e))})}schedulePersist(){this.config.persist&&(this.persistTimeoutId||(this.persistTimeoutId=setTimeout(()=>{this.persistTimeoutId=null,this.persistNow()},ih)))}persistNow(){if(!this.config.persist)return;const e={version:di,sessions:Ft(this.state.sessions,this.config,{enforceStorageQuota:!0})};if(this.state=e,typeof indexedDB>"u"){this.persistToLocalStorage(e);return}Promise.all([mh(e),yh(this.latestFailureWindow)]).then(([t,i])=>{if(!(t&&i))try{this.persistToLocalStorage(t?null:e,i?void 0:this.latestFailureWindow)}catch{}})}clearScheduledTasks(){this.notifyTimeoutId&&(clearTimeout(this.notifyTimeoutId),this.notifyTimeoutId=null),this.persistTimeoutId&&(clearTimeout(this.persistTimeoutId),this.persistTimeoutId=null)}async restoreIndexedDbState(){var i,r;if(!this.config.persist)return;const[e,t]=await Promise.all([Sh(),Ch()]);if((i=e==null?void 0:e.sessions)!=null&&i.length){const s=new Map;[...this.state.sessions,...e.sessions].forEach(a=>{const o=Ya(a),l=s.get(o.sessionId);(!l||l.updatedAt<o.updatedAt)&&s.set(o.sessionId,o)}),this.state.sessions=Ft(Array.from(s.values()).sort((a,o)=>a.startedAt-o.startedAt),this.config,{enforceStorageQuota:!0})}t&&(!this.latestFailureWindow||t.updatedAt>=this.latestFailureWindow.updatedAt)&&(this.latestFailureWindow=t),((r=e==null?void 0:e.sessions)!=null&&r.length||t)&&this.notifyNow()}captureFailureWindow(e,t){if(t.severity==="error"&&(this.activeFailureCapture={sessionId:e.sessionId,failureEventId:t.eventId,remainingAfterEvents:Qs}),!this.activeFailureCapture||this.activeFailureCapture.sessionId!==e.sessionId)return;const i=this.buildFailureWindow(e,this.activeFailureCapture.failureEventId);i.length&&(this.latestFailureWindow={version:ms,sessionId:e.sessionId,updatedAt:t.timestamp,failureEventId:this.activeFailureCapture.failureEventId,events:i},t.eventId!==this.activeFailureCapture.failureEventId&&(this.activeFailureCapture.remainingAfterEvents-=1),this.activeFailureCapture.remainingAfterEvents<=0&&(this.activeFailureCapture=null))}buildFailureWindow(e,t,i=Qs){const r=e.events.findIndex(s=>s.eventId===t);return r<0?[]:e.events.slice(Math.max(0,r-i),Math.min(e.events.length,r+i+1))}resolveExportFailureWindow(e,t,i){var o;const r=e.events.map((l,c)=>({event:l,index:c})).filter(({event:l})=>l.severity==="error"),s=r.length>0?r[r.length-1]:null,a=s?e.events.slice(Math.max(0,s.index-t),Math.min(e.events.length,s.index+t+1)):[];return s?{failureWindow:a,failureWindowSource:"live"}:((o=this.latestFailureWindow)==null?void 0:o.sessionId)===e.sessionId&&this.latestFailureWindow.events.length>0?{failureWindow:[...this.latestFailureWindow.events],failureWindowSource:"persisted"}:{failureWindow:e.events.slice(-i),failureWindowSource:"recent-events"}}persistToLocalStorage(e,t=this.latestFailureWindow){if(!(typeof globalThis.localStorage>"u")&&(e&&globalThis.localStorage.setItem(Na,JSON.stringify(e)),t!==void 0)){if(t){globalThis.localStorage.setItem(Yr,JSON.stringify(t));return}globalThis.localStorage.removeItem(Yr)}}}function Th(n,e){return vh(n,e)}function an(n,e,t,i){const r=`[${n.toUpperCase()}] [${e}]`;if(i===void 0){console[n](`${r} ${t}`);return}console[n](`${r} ${t}`,i)}const N={debug(n,e,t){},debugLazy(n,e,t){},warn(n,e,t){an("warn",n,e,t)},error(n,e,t){an("error",n,e,t)}};class pe{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={},this.brokenImageUrls.clear()}static renderClipCovers(e,t,i,r,s,a=!1){N.debugLazy("ClipCoverRenderer",()=>"renderClipCovers",()=>({videoSrc:s,coverCount:(t==null?void 0:t.length)??0,coverWidth:i,coverHeight:r}));const o=(e.getAttr(this.COVER_RENDER_VERSION_KEY)||0)+1;if(e.setAttr(this.COVER_RENDER_VERSION_KEY,o),e.setAttr(this.COVER_SOURCE_KEY,[...t??[]]),!t||t.length===0){e.destroyChildren(),this.syncCoverBackgroundState(e),a||this.requestRender(e);return}const l=this.buildSegmentsDataSync(t,i,r,s);if(l){this.renderSegments(e,l,i,r),this.syncCoverBackgroundState(e),a||this.requestRender(e);return}a||(e.destroyChildren(),this.syncCoverBackgroundState(e),this.requestRender(e)),this.startRenderJob({coversGroup:e,coverSource:t,coverWidth:i,coverHeight:r,videoSrc:s,version:o})}static async startRenderJob(e){const{coversGroup:t,coverSource:i,coverWidth:r,coverHeight:s,videoSrc:a,version:o}=e,l=await this.buildSegmentsData(i,r,s,a);if(this.isRenderJobCurrent(t,o)){if(this.renderSegments(t,l,r,s),this.syncCoverBackgroundState(t),!this.isRenderJobCurrent(t,o)){t.destroyChildren();return}this.requestRender(t)}}static async buildSegmentsData(e,t,i,r){const s=e.length,a=r||e[0]||"",o=await this.getSafeKeyframeDimensions(a,e[0]),l=o.width/o.height,c=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),h=Math.max(1,Math.ceil(t/c)),d=[];if(h===1)d.push(0);else for(let g=0;g<h;g++)d.push(Math.round(g*(s-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static buildSegmentsDataSync(e,t,i,r){const s=e.length,a=r||e[0]||"",o=this.getCachedKeyframeDimensions(a,e[0]);if(!o)return null;const l=o.width/o.height,c=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),h=Math.max(1,Math.ceil(t/c)),d=[];if(h===1)d.push(0);else for(let g=0;g<h;g++)d.push(Math.round(g*(s-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static requestRender(e){var i,r;const t=(i=e.getLayer)==null?void 0:i.call(e);if((r=t==null?void 0:t.getStage)!=null&&r.call(t))try{e.draw(),t.batchDraw()}catch{}}static isRenderJobCurrent(e,t){return e.getAttr(this.COVER_RENDER_VERSION_KEY)===t}static renderSegments(e,t,i,r){e.destroyChildren(),e.clip({x:0,y:0,width:i,height:r});for(const{coverUrl:s,singleImageWidth:a,segmentStartX:o,segmentWidth:l}of t){const c=Math.max(a,.01),h=this.getCachedImage(s),d=new Z.Group({x:o,y:0,clip:{x:0,y:0,width:l,height:r},name:"cover-segment"});h.src||(h.src=s);const u=new Z.Image({image:h,cornerRadius:2,name:"cover-image",visible:this.isImageRenderable(s,h)});u.x(0),u.y(0),u.width(c),u.height(r),this.bindCoverImageLifecycle(s,h,u,e),d.add(u),e.add(d)}}static async getSafeKeyframeDimensions(e,t){try{const i=await this.getKeyframeDimensions(e,t);if(i!=null&&i.width&&(i!=null&&i.height))return i}catch{}return this.DEFAULT_DIMENSIONS}static getKeyframeDimensions(e,t){const i=t||e;if(this.keyframeDimensionsCache[i])return Promise.resolve(this.keyframeDimensionsCache[i]);if(this.keyframeDimensionsPromiseCache[i])return this.keyframeDimensionsPromiseCache[i];const r=new Promise(s=>{const a=this.getCachedImage(t);if(this.isImageRenderable(t,a)){const l={width:a.width,height:a.height};this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],s(l);return}const o=l=>{this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],s(l)};this.listenToImageEvent(a,"load",()=>{this.brokenImageUrls.delete(t);const l={width:a.width,height:a.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},{once:!0}),this.listenToImageEvent(a,"error",()=>{this.brokenImageUrls.add(t),o(this.DEFAULT_DIMENSIONS)},{once:!0}),a.src||(a.src=t)});return this.keyframeDimensionsPromiseCache[i]=r,r}static getCachedKeyframeDimensions(e,t){const i=t||e,r=this.keyframeDimensionsCache[i];if(r!=null&&r.width&&(r!=null&&r.height))return r;const s=this.imageCache[t];if(s!=null&&s.complete&&s.width>0&&s.height>0){const a={width:s.width,height:s.height};return this.keyframeDimensionsCache[i]=a,a}return null}static getCachedImage(e){const t=this.imageCache[e];if(t)return t;const i=new Image;return this.imageCache[e]=i,this.checkAndTrimCache(),i}static checkAndTrimCache(){const e=Object.keys(this.imageCache);if(e.length<=this.MAX_CACHE_SIZE)return;const t=e.length-this.MAX_CACHE_SIZE,i=e.filter(a=>{const o=this.imageCache[a];return o&&!o.complete}),r=e.filter(a=>!i.includes(a));let s=0;for(const a of i){if(s>=t)break;this.evictCacheKey(a),s++}for(const a of r){if(s>=t)break;this.evictCacheKey(a),s++}}static evictCacheKey(e){delete this.imageCache[e],delete this.keyframeDimensionsCache[e],delete this.keyframeDimensionsPromiseCache[e],this.brokenImageUrls.delete(e)}static bindCoverImageLifecycle(e,t,i,r){this.listenToImageEvent(t,"load",()=>{this.brokenImageUrls.delete(e);try{i.visible(this.isImageRenderable(e,t)),this.syncCoverBackgroundState(r),this.requestRender(r)}catch{}}),this.listenToImageEvent(t,"error",()=>{this.brokenImageUrls.add(e);try{i.visible(!1),this.syncCoverBackgroundState(r),this.requestRender(r)}catch{}})}static isImageRenderable(e,t){if(this.brokenImageUrls.has(e)||!t.complete)return!1;const i=typeof t.naturalWidth=="number"?t.naturalWidth:t.width,r=typeof t.naturalHeight=="number"?t.naturalHeight:t.height;return i>0&&r>0}static listenToImageEvent(e,t,i,r){typeof e.addEventListener=="function"&&e.addEventListener(t,i,r)}static syncCoverBackgroundState(e){var c,h;const t=(c=e.getParent)==null?void 0:c.call(e),i=(h=t==null?void 0:t.findOne)==null?void 0:h.call(t,".clip-cover-background");if(!i)return;const r=e.getAttr("coverFallbackFill"),s=e.getAttr("coverUnavailableFill"),a=e.getAttr(this.COVER_SOURCE_KEY)??[],l=a.length>0&&a.every(d=>this.brokenImageUrls.has(d));i.fill(l?s:r)}}p(pe,"MIN_IMAGE_DISPLAY_WIDTH",24),p(pe,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),p(pe,"COVER_SOURCE_KEY","_coverSource"),p(pe,"MAX_CACHE_SIZE",1e3),p(pe,"DEFAULT_DIMENSIONS",{width:160,height:90}),p(pe,"keyframeDimensionsCache",{}),p(pe,"keyframeDimensionsPromiseCache",{}),p(pe,"imageCache",{}),p(pe,"brokenImageUrls",new Set);const bh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.8437804474494934,2.934130300488281C2.0975289474494936,2.6803818004882816,2.5560352474494934,2.5258255004882812,3.4537861474494935,2.5258255004882812L7.691924847449493,2.5258255004882812C8.589675247449494,2.5258255004882812,9.048181847449493,2.6803818004882816,9.301930747449493,2.934130300488281C9.555688247449494,3.1878788004882814,9.710234947449493,3.6463940004882813,9.710234947449493,4.544136000488281L9.710234947449493,5.154385800488281L9.710234947449493,5.156664400488282L9.710234947449493,8.837531600488282L9.710234947449493,8.839810400488282L9.710234947449493,9.455756700488282C9.710234947449493,10.352920500488281,9.554433147449494,10.811444300488281,9.299509347449494,11.065193200488281C9.045182547449494,11.319528600488281,8.586177147449494,11.474209800488282,7.691924847449493,11.474209800488282L3.4537861474494935,11.474209800488282C2.6371141474494935,11.474209800488282,2.1565246474494932,11.20751000048828,1.8706969474494934,10.86509900048828C1.5731912474494933,10.50867840048828,1.4354756474494934,10.006423900488281,1.4354756474494934,9.455756700488282L1.4354756474494934,4.544136000488281C1.4354756474494934,3.6463940004882813,1.5900319474494935,3.1878788004882814,1.8437804474494934,2.934130300488281ZM9.917876547449493,11.684700500488281C10.391550347449494,11.212192500488282,10.559057547449493,10.52217200048828,10.582387647449494,9.67692760048828L11.516774647449493,10.33260820048828L11.516774647449493,10.33260820048828C11.978190647449493,10.658107800488281,12.521887647449493,10.806299200488281,12.992055647449494,10.562466600488282C13.461642647449493,10.318055200488281,13.653574647449494,9.787735900488281,13.653574647449494,9.222480300488282L13.653574647449494,4.777554700488281C13.653574647449494,4.212299300488281,13.461625647449493,3.6825676004882815,12.992624647449494,3.437568500488281C12.523623647449494,3.1925697004882814,11.980024647449493,3.3384564004882815,11.519194647449494,3.6604486004882815L11.518056647449493,3.661018400488281L10.582387647449494,4.3178380004882815C10.558470047449493,3.475504500488281,10.392209347449493,2.7870953004882812,9.920297947449493,2.315762820488281C9.406961747449493,1.8024266504882813,8.637509647449493,1.6508255004882812,7.691924847449493,1.6508255004882812L3.4537861474494935,1.6508255004882812C2.5082015474494934,1.6508255004882812,1.7387490474494933,1.8024266504882813,1.2254129674494934,2.315762820488281C0.7120767974494934,2.8290989004882814,0.5604756474494934,3.598560200488281,0.5604756474494934,4.544136000488281L0.5604756474494934,9.455756700488282C0.5604756474494934,10.13592340048828,0.7290598274494934,10.86171720048828,1.1986388574494935,11.42521860048828C1.6798959474494934,12.003300500488281,2.4271137474494937,12.349209500488282,3.4537861474494935,12.349209500488282L7.691924847449493,12.349209500488282C8.635176947449493,12.349209500488282,9.403962447449494,12.197448500488282,9.917876547449493,11.684700500488281ZM12.020781647449493,9.61682840048828L10.585234647449493,8.609952000488281L10.585234647449493,5.384101600488281L12.019642647449494,4.377937300488281L12.020212647449494,4.3773675004882815C12.352129647449493,4.145782500488281,12.531874647449493,4.183709400488281,12.587880647449493,4.212877700488281C12.643876647449494,4.242046400488281,12.778574647449494,4.368635700488282,12.778574647449494,4.777554700488281L12.778574647449494,9.222480300488282C12.778574647449494,9.631399600488281,12.643866647449494,9.757436800488282,12.588449647449494,9.786018400488281C12.533620647449494,9.814020200488281,12.354416647449494,9.852481800488281,12.021921647449494,9.617398300488281L12.020781647449493,9.61682840048828ZM3.3313089474494935,3.9374466004882813C3.0898080474494933,3.9374466004882813,2.8938089474494935,4.133445700488281,2.8938089474494935,4.374946600488281C2.8938089474494935,4.616447400488282,3.0898080474494933,4.812446600488281,3.3313089474494935,4.812446600488281L4.815419447449494,4.812446600488281C5.056920347449493,4.812446600488281,5.252919447449494,4.616447400488282,5.252919447449494,4.374946600488281C5.252919447449494,4.133445700488281,5.056920347449493,3.9374466004882813,4.815419447449494,3.9374466004882813L3.3313089474494935,3.9374466004882813Z" fill="#868A9C" fill-opacity="1"/></svg>',kh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="16" height="16" viewBox="0 0 16 16"><path d="M11.206380472434997,2.733718973069763C9.993001372434998,1.991438673069763,8.552978872434998,1.6945722130697631,7.139648772434998,1.8937121730697632C5.7263186724349975,2.092858673069763,4.426350972434998,2.775678773069763,3.4596355724349976,3.825838973069763C2.4930013724349975,4.875998873069763,1.9263509724349976,6.228518873069763,1.8396810724349975,7.652945373069763C1.7596843224349974,9.077412973069762,2.1796875724349976,10.485612273069764,3.0196941724349977,11.637611373069763C3.8597005724349978,12.789678373069764,5.0796712724349975,13.614278373069762,6.459635572434998,13.970879373069764C7.839681072434997,14.327545373069762,9.299641972434998,14.194145373069762,10.593017972434998,13.593478373069763C11.892985472434997,12.992878373069763,12.933024472434997,11.962078373069764,13.552978472434997,10.676812573069764C14.173015472434997,9.391545673069762,14.326335472434998,7.9312790730697635,13.993001472434997,6.544878873069763C13.926350472434997,6.276532073069763,14.093017472434997,6.0061725730697635,14.359700472434998,5.941012273069763C14.626302472434997,5.875851973069763,14.899658472434998,6.040565873069763,14.966308472434998,6.308912673069763C15.353027472434997,7.920145873069763,15.173015472434997,9.617145873069763,14.453044472434998,11.110879373069762C13.732991472434998,12.604545373069763,12.519694472434997,13.802478373069762,11.019694472434997,14.500545373069762C9.513020872434998,15.198611373069763,7.812988672434997,15.353611373069763,6.2063802724349975,14.939145373069763C4.599690772434998,14.524678373069763,3.1930340724349975,13.566345373069764,2.2129720724349973,12.227478373069763C1.2329915724349976,10.888679373069763,0.7530111074349976,9.252079373069764,0.8463542074349976,7.5966790730697635C0.9396973124349975,5.941252573069764,1.5996907924349975,4.369405673069763,2.726318472434998,3.1489456730697634C3.8463543724349973,1.9284919730697632,5.359700572434997,1.134938593069763,6.999674672434997,0.9035053700697632C8.639648772434999,0.6720721230697632,10.312988672434997,1.0170720830697633,11.726318472434997,1.8797255730697633C11.966308472434998,2.023398773069763,12.039714472434998,2.3310454730697634,11.892985472434997,2.5668653730697635C11.753011472434997,2.8026921730697634,11.446370472434998,2.8773921730697634,11.206380472434997,2.733718973069763ZM11.686360472434998,5.413441573069763C11.879639472434997,5.608874673069764,11.879639472434997,5.925454473069763,11.686360472434998,6.1205485730697635L7.2396648724349975,10.559748073069763C7.046305572434997,10.754747773069763,6.7263186724349975,10.754615173069762,6.533040372434997,10.559481973069763L4.312988372434997,8.339814573069763C4.119710372434998,8.144614573069763,4.119710372434998,7.828014773069763,4.312988372434997,7.632747973069764C4.506347772434998,7.437481773069763,4.826334872434998,7.437481773069763,5.019694172434997,7.632747973069764L6.886311872434997,9.499081973069764L10.979655472434997,5.412814473069763C11.173015472434997,5.217727973069763,11.493001472434997,5.218008373069763,11.686360472434998,5.413441573069763Z" fill-rule="evenodd" fill="#24C744" fill-opacity="1"/></svg>',wh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.3164876075,5.2511568456573485C2.7112323875,3.0589928456573485,4.7552132875,1.7354023456573486,6.9998931875,1.7354023456573486C9.2445726875,1.7354023456573486,11.2885531875,3.0589928456573485,12.6832981875,5.2511568456573485C13.0012411875,5.7498953456573485,13.1452941875,6.3880765456573485,13.1452941875,6.9999821456573486C13.1452941875,7.611905345657348,13.0012411875,8.250068445657348,12.6832981875,8.74882484565735C11.2885531875,10.940988745657348,9.2445726875,12.264562345657348,6.9998931875,12.264562345657348C4.7552132875,12.264562345657348,2.7112323875,10.940988745657348,1.3164876075,8.74882484565735C0.9985453175,8.250068445657348,0.8544921875,7.611905345657348,0.8544921875,6.9999821456573486C0.8544921875,6.3880765456573485,0.9985453175,5.749325945657349,1.3164876075,5.2511568456573485ZM6.9998931875,2.6104023456573486C5.1262406875,2.6104023456573486,3.3318786875,3.713480445657349,2.0549823875,5.721323445657349L2.0543771875,5.721323445657349C1.8473052375,6.0456564456573485,1.7294921875,6.509396745657349,1.7294921875,6.9999821456573486C1.7294921875,7.490567445657349,1.8473052375,7.954324945657349,2.0543771875,8.278070645657348L2.0549823875,8.27865814565735C3.3318786875,10.286483045657349,5.1262406875,11.389561845657349,6.9998931875,11.389561845657349C8.8735446875,11.389561845657349,10.6679076875,10.286483045657349,11.9448031875,8.27865814565735L11.9454091875,8.278070645657348C12.1518751875,7.954324945657349,12.2702941875,7.490567445657349,12.2702941875,6.9999821456573486C12.2702941875,6.509396745657349,12.1518751875,6.0456564456573485,11.9454091875,5.721323445657349L11.9448031875,5.721323445657349C10.6679076875,3.713480445657349,8.8735446875,2.6104023456573486,6.9998931875,2.6104023456573486ZM4.4741208875,7.002937045657348C4.4741208875,5.606429845657349,5.6034745875,4.4771115456573485,6.9999641875,4.4771115456573485C8.3964533875,4.4771115456573485,9.5258073875,5.606429845657349,9.5258073875,7.002937045657348C9.5258073875,8.399444345657349,8.3964533875,9.528762545657349,6.9999641875,9.528762545657349C5.6034745875,9.528762545657349,4.4741208875,8.399444345657349,4.4741208875,7.002937045657348ZM6.9999641875,5.3521115456573485C6.0864762875,5.3521115456573485,5.3491210875,6.089431545657349,5.3491210875,7.002937045657348C5.3491210875,7.916442645657349,6.0864762875,8.653762545657349,6.9999641875,8.653762545657349C7.9134516875,8.653762545657349,8.650807387499999,7.916442645657349,8.650807387499999,7.002937045657348C8.650807387499999,6.089431545657349,7.9134516875,5.3521115456573485,6.9999641875,5.3521115456573485Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',xh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="18" height="18" viewBox="0 0 18 18"><path d="M3.5486246148989866,6.472501117640625C3.7632801848989867,6.361666362640625,4.026926634898987,6.445068359640625,4.138366634898987,6.659741711640625C4.944508744898987,8.214329931640625,6.797759844898987,9.340158931640625,8.999857544898987,9.340158931640625C11.201954944898986,9.340158931640625,13.055775244898987,8.214329931640625,13.861347544898987,6.659741711640625C13.972788544898988,6.445068359640625,14.237040544898987,6.361666362640625,14.451090544898987,6.472501117640625C14.665781544898987,6.583905531640625,14.749770544898986,6.847569761640625,14.638366544898988,7.062243101640625C14.367100544898987,7.584907531640625,14.003692544898987,8.060913131640625,13.566192544898987,8.475074731640625L14.459278544898988,9.368161431640626C14.630177544898986,9.539077731640624,14.630177544898986,9.816164531640625,14.459278544898988,9.987080831640625C14.288344544898987,10.157996931640625,14.011275544898988,10.157996931640625,13.840342544898986,9.987080831640625L12.883701944898986,9.030405531640625C12.378519644898986,9.383328631640625,11.808039344898987,9.667999231640625,11.192590844898987,9.869249831640625L11.502344744898986,11.025413531640625C11.564757944898988,11.258743331640625,11.426508544898986,11.499069231640625,11.193196444898987,11.561500531640625C10.959848544898986,11.623913731640625,10.720092444898988,11.485664331640624,10.657109344898988,11.251747131640624L10.345611244898986,10.087999831640625C9.911600744898987,10.171401731640625,9.460677744898987,10.215158931640625,8.999857544898987,10.215158931640625C8.548365244898987,10.215158931640625,8.107340444898988,10.173164131640625,7.681518244898987,10.093233631640626L7.371195444898987,11.251747131640624C7.308781744898987,11.485664331640624,7.069025444898987,11.623913731640625,6.835108144898987,11.561500531640625C6.6017607448989875,11.499069231640625,6.4635111448989875,11.258743331640625,6.525924544898986,11.025413531640625L6.833363644898987,9.877990731640626C6.192280844898987,9.670900831640624,5.600189044898986,9.374000531640625,5.078094344898987,9.003578231640624L4.095179204898987,9.987080831640625C3.924280764898987,10.157996931640625,3.6471760548989867,10.157996931640625,3.476277614898987,9.987080831640625C3.305343588298987,9.816164531640625,3.305343588298987,9.539077731640624,3.476277614898987,9.368161431640626L4.400873744898987,8.443583031640625C3.9779357348989866,8.036987331640624,3.6256001248989866,7.572072231640625,3.361348427898987,7.062243101640625C3.250513676898987,6.847569761640625,3.3339334728989867,6.583905531640625,3.5486246148989866,6.472501117640625Z" fill="#FFFFFF" fill-opacity="1"/></svg>',Ph='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path d="M9.217651334374999,1.6159667934375C8.817657434375,1.7239685034375,8.579650834375,2.1349792434375,8.687652634374999,2.5349731234375C8.794677734375,2.9349670234375003,9.205657934375001,3.1719665234375,9.605651834375,3.0649719234374997C14.537658734375,1.7439575234375,19.612670734375,4.6739807234375,20.934661734375,9.6059570234375C22.255676734375,14.5379635234375,19.325652734375,19.6129765234375,14.393676734375,20.9349675234375C9.461669934375,22.2559815234375,4.3866577343749995,19.3259585234375,3.064666734375,14.3939815234375C2.3956604343750003,11.8969725234375,2.816650434375,9.3629761234375,4.036651634375,7.2969665234375C4.246673534375001,6.9399719234375,4.128662134375,6.4799804234375,3.771667434375,6.2699585234375C3.415649434375,6.0589599234375,2.955657934375,6.1779785234375,2.744659434375,6.5339660234375C1.3286743163749999,8.9329834234375,0.8386535643749999,11.8789675234375,1.615661624375,14.7819825234375C3.151672334375,20.5139775234375,9.049652134375,23.9199825234375,14.781677734375,22.3839725234375C20.513671734375,20.8479615234375,23.919677734375,14.9499815234375,22.383666734375,9.2179565234375C20.847656734375,3.4859619234375,14.949676734375,0.07995602343750008,9.217651334374999,1.6159667934375Z" fill="#C9CBD4" fill-opacity="1"/><path d="M16.7496337890625,12C16.7496337890625,14.6270103,14.6266440890625,16.75,11.9996337890625,16.75C9.3736238890625,16.75,7.2496337890625,14.6270103,7.2496337890625,12C7.2496337890625,9.3739901,9.3736238890625,7.25,11.9996337890625,7.25C14.6266440890625,7.25,16.7496337890625,9.3739901,16.7496337890625,12ZM11.9996337890625,15.25C13.7976336890625,15.25,15.2496337890625,13.7979999,15.2496337890625,12C15.2496337890625,10.2020001,13.7976336890625,8.75,11.9996337890625,8.75C10.2016338890625,8.75,8.7496337890625,10.2020001,8.7496337890625,12C8.7496337890625,13.7979999,10.2016338890625,15.25,11.9996337890625,15.25Z" fill="#C9CBD4" fill-opacity="1"/></svg>',_h='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M12.594244271484374,3.926410052418518C12.594244271484374,3.9339934524185183,12.594244271484374,3.941576852418518,12.594244271484374,3.949160252418518L12.594244271484374,10.004165252418519L12.594244271484374,10.009998952418519C12.591269271484375,11.254248752418517,11.581520271484376,12.261664752418518,10.336686171484375,12.261664752418518C9.090102671484374,12.261664752418518,8.079185971484375,11.250748752418518,8.079185971484375,10.004165252418519C8.079185971484375,8.757582352418517,9.090102671484374,7.746665552418518,10.336686171484375,7.746665552418518C10.857602071484376,7.746665552418518,11.337102871484374,7.922832152418518,11.719244271484374,8.219165952418518L11.719244271484374,4.510315252418518L5.920881771484375,6.091725952418518L5.920881771484375,11.212248752418517L5.920881771484375,11.217499752418519C5.920881771484375,12.464083752418517,4.909947871484375,13.474998752418518,3.663387771484375,13.474998752418518C2.416787071484375,13.474998752418518,1.405852854251865,12.464082752418518,1.405852854251865,11.217499752418519C1.405852854251865,9.970916352418518,2.416786871484375,8.959999652418517,3.663387771484375,8.959999652418517C4.184269171484376,8.959999652418517,4.663780971484375,9.136166252418517,5.045881971484375,9.432499552418518L5.045881971484375,5.765065352418518C5.045881971484375,5.759809652418518,5.045881971484375,5.754577252418518,5.045881971484375,5.749326852418518L5.045881971484375,3.879142852418518C5.045881971484375,2.9108270524185182,5.645524971484375,2.2224822524185184,6.488441471484375,1.9926605524185181L10.128436071484375,1.000982272418518C10.652911171484375,0.8580656054185181,11.273518571484376,0.8131547724185181,11.781602271484376,1.1106431024185182C12.324102271484374,1.4273930824185181,12.594244271484374,2.0416489524185177,12.594244271484374,2.887488152418518L12.594244271484374,3.926410052418518ZM11.719244271484374,2.887487652418518C11.719244271484374,2.216660252418518,11.514435271484375,1.967576852418518,11.340019271484374,1.866071042418518C11.132935571484374,1.744731902418518,10.796352371484375,1.726076842418518,10.358268771484376,1.845648522418518L6.718304671484375,2.8373209524185183C6.231775271484375,2.969731652418518,5.920881771484375,3.330809252418518,5.920881771484375,3.879142452418518L5.920881771484375,5.184648152418518L11.719244271484374,3.603231552418518L11.719244271484374,2.887487652418518ZM3.663388271484375,12.599998752418518C4.426948071484375,12.599998752418518,5.045882471484375,11.981081752418518,5.045882471484375,11.217499752418519C5.045882471484375,10.453916152418518,4.426948271484375,9.834999652418517,3.663388271484375,9.834999652418517C2.8997932714843753,9.834999652418517,2.280853391484375,10.453916152418518,2.280853391484375,11.217499752418519C2.280853391484375,11.981082752418518,2.899793471484375,12.599998752418518,3.663388271484375,12.599998752418518ZM8.954185971484375,10.004165252418519C8.954185971484375,10.767749452418519,9.573102971484374,11.386664752418518,10.336686171484375,11.386664752418518C11.100269271484375,11.386664752418518,11.719244271484374,10.767748452418518,11.719244271484374,10.004165252418519C11.719244271484374,9.240582152418519,11.100269271484375,8.621665552418518,10.336686171484375,8.621665552418518C9.573102971484374,8.621665552418518,8.954185971484375,9.240582152418519,8.954185971484375,10.004165252418519Z" fill="#868A9C" fill-opacity="1"/></svg>',Ah='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M11.305803496070862,2.8583284381607053C11.498882496070863,2.713661038160706,11.773050496070862,2.7521666381607055,11.918296496070862,2.9458338381607057C13.720794496070862,5.347419838160706,13.720794496070862,8.652577538160706,11.918296496070862,11.054163138160705C11.773050496070862,11.247830138160706,11.498882496070863,11.286335138160705,11.305803496070862,11.141669138160706C11.112723496070862,10.996414138160706,11.073630496070862,10.722246738160706,11.218307496070862,10.529166838160705C12.787475496070861,8.439078938160705,12.787475496070861,5.5609179381607055,11.218307496070862,3.4708303381607055C11.073630496070862,3.2777506381607058,11.112723496070862,3.0035830381607056,11.305803496070862,2.8583284381607053ZM10.850643496070862,4.404167338160706C10.705398196070862,4.210500138160706,10.431231096070862,4.171994538160705,10.238133096070861,4.316661938160705C10.044466596070862,4.461916538160706,10.005978196070862,4.736083838160706,10.150637296070862,4.929163538160706C11.072313496070862,6.156499038160706,11.072313496070862,7.843498338160706,10.150637296070862,9.070833838160706C10.005978196070862,9.263913738160706,10.044466596070862,9.538080838160706,10.238133096070861,9.683335938160706C10.431231096070862,9.828002538160705,10.705398196070862,9.789497038160706,10.850643496070862,9.595830538160705C12.005633496070862,8.058162338160706,12.005633496070862,5.941834538160705,10.850643496070862,4.404167338160706ZM6.527554596070861,1.3638305381607054C7.564730296070862,0.4561640581607056,9.188140496070861,1.1929142881607055,9.188140496070861,2.5713347381607052L9.188140496070861,11.428662138160705C9.188140496070861,12.807083138160706,7.564730296070862,13.543833138160705,6.527554596070861,12.636166138160705L3.9608915960708617,10.390329938160706C3.934063996070862,10.367000238160706,3.9002226960708617,10.354164738160705,3.8646364960708617,10.354164738160705L2.917307496070862,10.354164738160705C1.7092156960708618,10.354164738160705,0.7298074960708618,9.374747838160706,0.7298074960708618,8.166665238160705L0.7298074960708618,5.8333321381607055C0.7298074960708618,4.6252492381607055,1.7092156960708618,3.6458321381607055,2.917307496070862,3.6458321381607055L3.8646364960708617,3.6458321381607055C3.9002226960708617,3.6458321381607055,3.934063996070862,3.6329969381607055,3.9608915960708617,3.6096674381607055L6.527554596070861,1.3638305381607054ZM8.313140496070861,2.5713347381607052C8.313140496070861,1.9448317881607056,7.575215496070862,1.6099954881607057,7.103891996070862,2.0224125381607054L4.537228696070862,4.268249638160706C4.351145196070862,4.430994638160706,4.111976496070862,4.520831938160706,3.8646364960708617,4.520831938160706L2.917307496070862,4.520831938160706C2.192217496070862,4.520831938160706,1.6048074960708618,5.108250738160706,1.6048074960708618,5.8333321381607055L1.6048074960708618,8.166665238160705C1.6048074960708618,8.891746138160705,2.192217496070862,9.479165638160705,2.917307496070862,9.479165638160705L3.8646364960708617,9.479165638160705C4.111976496070862,9.479165638160705,4.351145196070862,9.569002738160705,4.537228696070862,9.731748238160705L7.103891996070862,11.977584138160706C7.575215496070862,12.390002138160705,8.313140496070861,12.055165138160705,8.313140496070861,11.428662138160705L8.313140496070861,2.5713347381607052Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',Ih='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M9.188069328125,2.7498358381607053L9.188069328125,2.5713360381607053C9.188069328125,1.1929155481607057,7.564641028125,0.4561653181607056,6.527501128125,1.3638317881607056L3.960820428125,3.6096686381607057C3.933975228125,3.6329981381607057,3.900151528125,3.6458331381607056,3.864583228125,3.6458331381607056L2.917236328125,3.6458331381607056C1.709162358125,3.6458331381607056,0.729736328125,4.625250238160706,0.729736328125,5.833333138160706L0.729736328125,8.166666138160705C0.729736328125,8.990334138160705,1.1847533881249999,9.707831938160705,1.857309928125,10.080586038160705L2.519968628125,9.417918838160706C1.989151028125,9.249912838160705,1.604736328125,8.752919338160705,1.604736328125,8.166666138160705L1.604736328125,5.833333138160706C1.604736328125,5.108252138160705,2.192164028125,4.520833138160706,2.917236328125,4.520833138160706L3.864583228125,4.520833138160706C4.111887428125,4.520833138160706,4.351074028125,4.4309958381607055,4.537139628125,4.268250538160705L7.103820828125,2.0224138381607055C7.575144328125,1.6099967381607057,8.313069328125,1.9448330381607055,8.313069328125,2.5713360381607053L8.313069328125,3.6248358381607058L9.188069328125,2.7498358381607053Z" fill="#FFFFFF" fill-opacity="1"/><path d="M9.188069388879395,6.8751726150512695L8.313069388879395,7.7501726150512695L8.313069388879395,11.42867231505127C8.313069388879395,12.055175315051269,7.575144088879394,12.39001181505127,7.103820288879394,11.97759441505127L5.493814768879394,10.56883951505127L4.8737382888793945,11.18892481505127L6.5275010888793945,12.63617661505127C7.564640988879395,13.54384331505127,9.188069388879395,12.807092715051269,9.188069388879395,11.42867231505127L9.188069388879395,6.8751726150512695Z" fill="#FFFFFF" fill-opacity="1"/><path d="M10.519225743566894,5.543419959263916C11.048904063566894,6.679164689263916,10.926391243566895,8.038332489263915,10.150583580566895,9.070834589263917C10.005889575566895,9.263914589263916,10.044412931566894,9.538081689263915,10.238062213566895,9.683336689263916C10.431141853566894,9.828003889263915,10.705327033566894,9.789498289263916,10.850555063566894,9.595831389263916C11.887160943566894,8.215666289263917,11.993331543566894,6.369420189263916,11.169067043566894,4.893587589263916L10.519225743566894,5.543419959263916Z" fill="#FFFFFF" fill-opacity="1"/><path d="M11.747202221848145,4.3160754470959475C12.761021631848145,6.290655617095947,12.584853731848145,8.708574817095947,11.218093551848144,10.529159117095947C11.073435149848144,10.722238517095947,11.112528165848145,10.996406117095948,11.305607791848145,11.141660717095947C11.498687411848145,11.286328317095947,11.772872571848145,11.247822717095946,11.918100651848144,11.054155317095947C13.545587731848144,8.886487017095948,13.703704331848144,5.9814896170959475,12.392949131848145,3.6703286170959473L11.747202221848145,4.3160754470959475Z" fill="#FFFFFF" fill-opacity="1"/><path d="M12.5598954921875,2.0591658358917235C12.7307934921875,1.8882496358917238,12.7307934921875,1.6117501858917236,12.5598954921875,1.4408339558917236C12.3889614921875,1.2699177268917237,12.1124624921875,1.2699177268917237,11.9415284921875,1.4408339558917236L1.4415283221875,11.940833335891723C1.2706298831875,12.111750335891724,1.2706298831875,12.388249335891723,1.4415283221875,12.559165335891723C1.6124623421875,12.730081335891724,1.8889617921875002,12.730081335891724,2.0598958121875,12.559165335891723L12.5598954921875,2.0591658358917235Z" fill="#FFFFFF" fill-opacity="1"/></svg>',Eh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M3.348292020680237,2.6424992084503174C2.923644920680237,2.6424992084503174,2.578287720680237,2.9849191084503177,2.578287720680237,3.4125035084503175L2.578287720680237,4.474174308450317C2.578287720680237,4.715657508450317,2.382288570680237,4.911674308450317,2.140787720680237,4.911674308450317C1.8992868706802368,4.911674308450317,1.7032877206802368,4.715657508450317,1.7032877206802368,4.474174308450317L1.7032877206802368,3.4125035084503175C1.7032877206802368,2.4984104584503175,2.442957520680237,1.7674992084503174,3.348292020680237,1.7674992084503174L10.651636720680237,1.7674992084503174C11.565124120680236,1.7674992084503174,12.296640720680237,2.5071690084503175,12.296640720680237,3.4125035084503175L12.296640720680237,4.474174308450317C12.296640720680237,4.715657508450317,12.100641720680237,4.911674308450317,11.859140720680237,4.911674308450317C11.617640120680237,4.911674308450317,11.421641020680237,4.715657508450317,11.421641020680237,4.474174308450317L11.421641020680237,3.4125035084503175C11.421641020680237,2.9878386084503177,11.079203220680236,2.6424992084503174,10.651636720680237,2.6424992084503174L7.435114520680237,2.6424992084503174C7.436289420680237,2.657666388450317,7.437464320680236,2.6734210884503176,7.437464320680236,2.6891580184503177L7.437464320680236,11.357500308450318L8.714965420680237,11.357500308450318C8.956466320680237,11.357500308450318,9.152465420680237,11.553499508450317,9.152465420680237,11.795000208450318C9.152465420680237,12.036501208450318,8.956466320680237,12.232500208450318,8.714965420680237,12.232500208450318L5.284962820680237,12.232500208450318C5.043461920680237,12.232500208450318,4.847462820680237,12.036501208450318,4.847462820680237,11.795000208450318C4.847462820680237,11.553499508450317,5.043461920680237,11.357500308450318,5.284962820680237,11.357500308450318L6.562464320680236,11.357500308450318L6.562464320680236,2.6891580184503177C6.562464320680236,2.6734210884503176,6.563033720680237,2.657666388450317,6.564814220680237,2.6424992084503174L3.348292020680237,2.6424992084503174Z" fill="#868A9C" fill-opacity="1"/></svg>',Mh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="2" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="4" y="4.5" width="1" height="6" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="6" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="8" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="10" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="12" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="14" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="16" y="6.5" width="1" height="2" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/></svg>',Rh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="2" y="7" width="15" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="4" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="6" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="8" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="10" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="12" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="14" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="16" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/></svg>',Lh=new Map([["OmAi-camera",bh],["OmAi-accept",kh],["OmAi-display",wh],["OmAi-hide",xh],["OmAi-loading",Ph],["OmAi-music",_h],["OmAi-volume",Ah],["OmAi-volume-mute",Ih],["OmAi-text",Eh],["clip-audio",Mh],["clip-without-audio",Rh]]),on=new Map;function be(n){return Lh.get(n)??""}function Dh(n){const e=on.get(n);if(e)return e;const t=be(n);if(!t)return null;const i=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`,r=typeof Image>"u"?{src:i,complete:!0,naturalWidth:1,addEventListener:()=>{}}:new Image;return"decoding"in r&&(r.decoding="async"),r.src=i,on.set(n,r),r}const de=3,ln=10,Oh=4,Bh=6,cn=8,hn=14,qr=10,Fh=12,Hh=4,Ka=1,Zi=28,Za=8,ii=12,jr=19,Ji=15,Gh=12;function ui(n,e,t,i,r=P.white,s=P.black,a=1){return new Z.Rect({x:n,y:e,width:t,height:i,fill:r,stroke:s,strokeWidth:a})}function wt(n,e,t,i=12,r="Arial",s=P.black,a="left",o="top"){return new Z.Text({text:n,x:e,y:t,fontSize:i,fontFamily:r,fill:s,align:a,verticalAlign:o})}function xt(n=0,e=0){return new Z.Group({x:n,y:e})}function pi(n){n.ellipsis(!1),n.wrap("none"),n.width("auto")}function ys(n){return typeof n=="string"&&n.trim().length>0?n.trim():"媒体丢失"}function hr(n,e,t,i){if(i){n.add(new Z.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),n.add(new Z.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}n.add(new Z.Rect({x:0,y:0,width:de,height:t,name:"clip-resize-left"})),n.add(new Z.Rect({x:e-de,y:0,width:de,height:t,name:"clip-resize-right"}))}function Nh(n,e,t,i){const r=n.findOne(".clip-resize-left"),s=n.findOne(".clip-resize-right");return!r||!s?!1:(r.x(0),r.y(0),r.width(de),r.height(t),s.x(e-de),s.y(0),s.width(de),s.height(t),!0)}function Ja(n,e,t){const i=e?n.clipSelectedBorder:P.transparent,r=e?Ka:0;return t==="audio"?{background:P.audioClipBackground,label:n.audioClipText||n.clipName,accent:n.audioClipAccent||n.clipHandle,coverBackground:n.clipCoverBackground||ee.clipCoverBackground,failedBackground:P.mediaClipFailedBackground,failedLabel:n.audioClipText||n.clipName,border:i,borderWidth:r}:t==="text"?{background:P.textClipBackground,label:n.clipName,accent:n.clipHandle,coverBackground:n.clipCoverBackground||P.accentCoverFallback,failedBackground:P.mediaClipFailedBackground,failedLabel:n.clipName,border:i,borderWidth:r}:{background:P.videoClipBackground,label:n.clipName,accent:n.clipHandle,coverBackground:n.clipCoverBackground||P.accentCoverFallback,failedBackground:P.mediaClipFailedBackground,failedLabel:n.clipName,border:i,borderWidth:r}}function Qa(n,e,t,i,r){const s=wt(i,0,Math.max(0,Math.floor((t-ii)/2)-2),ii,"Arial",r,"center","middle");s.width(e),s.height(ii+6),s.name("clip-media-status"),n.add(s)}function zh(n,e,t,i,r,s){const a=wt(r,e,t,Gh,"Arial",s,"center","middle");a.width(i),a.height(Ji),a.name("clip-media-status"),n.add(a)}function $h(n,e,t,i){const r=ui(0,0,e,t,i.background,i.border,i.borderWidth);r.cornerRadius(Math.min(4,Math.floor(e/2))),r.name("clip-background"),n.add(r),hr(n,e,t,!0)}function Vh(n,e,t){const i=e.mediaStatus==="failed",r=ys(e.mediaStatusMessage),s=ui(0,0,e.width,e.height,t.background,t.border,t.borderWidth);s.cornerRadius(4),s.name("clip-background"),n.add(s),hr(n,e.width,e.height,!1);const a=15,o=e.height-a-4,l=e.width-de*2,c=xt(de,2);c.name("clip-cover-container"),c.clip({x:0,y:0,width:l,height:o}),n.add(c);const h=ui(0,0,l,o,i?t.failedBackground:t.coverBackground,"transparent",0);h.cornerRadius(2),h.name("clip-cover-background"),c.add(h);const d=xt(0,0);d.name("clip-covers-group"),d.setAttr("coverFallbackFill",i?t.failedBackground:t.coverBackground),d.setAttr("coverUnavailableFill",i?t.failedBackground:P.mediaClipFailedBackground),c.add(d),i?(pe.renderClipCovers(d,[],l,o,e.videoSrc,e.deferCoverRender),Qa(c,l,o,r,t.failedLabel)):pe.renderClipCovers(d,e.thumbnails??[],l,o,e.videoSrc,e.deferCoverRender);const u=l>=120?Zi+Za:0,g=wt(`${e.clipName} ${U.formatDuration(e.duration)}`,de,e.height-a,qr,"Arial",t.label,"left","middle");g.height(a),pi(g),g.name("clip-label"),n.add(g),u>0&&to(n,e.width,e.height,e.hasSeparatedAudio)}function Uh(n,e,t){const i=n.findOne(".clip-background"),r=n.findOne(".clip-cover-container"),s=n.findOne(".clip-cover-background"),a=n.findOne(".clip-covers-group"),o=n.findOne(".clip-label"),l=n.findOne(".clip-media-status");if(!i||!r||!s||!a||!o)return!1;const c=e.mediaStatus==="failed",h=ys(e.mediaStatusMessage);if(i.width(e.width),i.height(e.height),i.fill(t.background),i.stroke(t.border),i.strokeWidth(t.borderWidth),i.cornerRadius(4),!Nh(n,e.width,e.height))return!1;const d=15,u=e.height-d-4,g=e.width-de*2;r.x(de),r.y(2),r.clip({x:0,y:0,width:g,height:u}),s.width(g),s.height(u),s.fill(c?t.failedBackground:t.coverBackground),s.cornerRadius(2),a.setAttr("coverFallbackFill",c?t.failedBackground:t.coverBackground),a.setAttr("coverUnavailableFill",c?t.failedBackground:P.mediaClipFailedBackground),c?(pe.renderClipCovers(a,[],g,u,e.videoSrc,e.deferCoverRender),l?(l.text(h),l.x(0),l.y(Math.max(0,Math.floor((u-ii)/2)-2)),l.width(g),l.height(ii+6),l.fill(t.failedLabel)):Qa(r,g,u,h,t.failedLabel)):(l==null||l.destroy(),pe.renderClipCovers(a,e.thumbnails??[],g,u,e.videoSrc,e.deferCoverRender));const f=g>=120?Zi+Za:0;o.text(`${e.clipName} ${U.formatDuration(e.duration)}`),o.x(de),o.y(e.height-d),o.fill(t.label),o.height(d),pi(o);const m=n.findOne(".video-audio-status");return m==null||m.destroy(),f>0&&to(n,e.width,e.height,e.hasSeparatedAudio),!0}function Wh(n,e){e.complete&&e.naturalWidth>0||e.addEventListener("load",()=>{var t,i;(i=(t=n.getLayer)==null?void 0:t.call(n))==null||i.batchDraw()},{once:!0})}function eo(n,e,t,i,r){n.name()||n.name(r);const s=Dh(e);if(!s)return 0;const a=new Z.Image({x:0,y:0,width:t,height:i,image:s,listening:!1});return a.name(`${r}-image`),n.add(a),Wh(n,s),t}function to(n,e,t,i){const r=xt(Math.max(de,e-de-Zi-2),Math.max(0,t-15));r.name("video-audio-status");const s=xt(Math.max(0,Zi-jr),0),a=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";s.name(a),eo(s,o,jr,Ji,`${a}-icon`),r.add(s),n.add(r)}function Yh(n,e,t){const i=e.mediaStatus==="failed",r=ys(e.mediaStatusMessage),s=ui(0,0,e.width,e.height,i?t.failedBackground:t.background,t.border,t.borderWidth);s.cornerRadius(6),s.name("clip-background"),n.add(s),hr(n,e.width,e.height,!1);const a=de+ln,o=Math.max(0,e.width-de*2-ln*2),l=Oh,c=xt(a,l),h=eo(c,"clip-audio",jr,Ji,"audio-clip-icon");n.add(c);const d=a+h+cn,u=Math.max(0,o-h-cn);if(i&&u>0)zh(n,d,l,u,r,t.failedLabel);else if(e.audioBadgeText&&u>0){const f=wt(e.audioBadgeText,d,l,qr,"Arial",t.label,"left","middle");f.height(Ji),pi(f),f.name("audio-clip-badge"),n.add(f)}const g=wt(e.clipName,a,e.height-Bh-hn,qr,"Arial",t.label,"left","middle");g.height(hn),pi(g),g.name("clip-label"),n.add(g)}function Xh(n,e,t){const i=ui(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),n.add(i),hr(n,e.width,e.height,!1);const r=wt(e.clipName,Hh,0,Fh,"Arial",t.label,"left","middle");r.height(e.height),r.lineHeight(1),pi(r),r.name("clip-label"),n.add(r)}function io(n,e){const t=e.width<=ci,i=Ja(e.theme,e.isSelected,e.clipType);if(n.destroyChildren(),t){$h(n,e.width,e.height,i);return}if(e.clipType==="audio"){Yh(n,e,i);return}if(e.clipType==="text"){Xh(n,e,i);return}Vh(n,e,i)}function qh(n,e){if(e.width<=ci||e.clipType!=="video")return!1;const i=Ja(e.theme,e.isSelected,e.clipType);return Uh(n,e,i)}function jh(n,e,t,i,r,s,a,o=!1,l,c,h="video",d=!1,u=!1,g,f,m){const C=xt(n,e);return C.clip({x:0,y:0,width:t,height:i}),io(C,{width:t,height:i,clipName:r,audioBadgeText:g,duration:s,theme:a,isSelected:o,thumbnails:l,videoSrc:c,clipType:h,hasSeparatedAudio:d,deferCoverRender:u,mediaStatus:f,mediaStatusMessage:m}),C}function Kh(n,e,t,i,r,s,a=!1,o,l,c="video",h=!1,d=!1,u,g,f){n.clip({x:0,y:0,width:e,height:t});const m={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:s??Yi,isSelected:a,thumbnails:o,videoSrc:l,clipType:c,hasSeparatedAudio:h,deferCoverRender:d,mediaStatus:g,mediaStatusMessage:f};qh(n,m)||io(n,m)}function Zh(n,e,t,i){return new Z.Rect({x:n,y:e,width:t,height:i,stroke:P.clipSelectedBorder,strokeWidth:Ka,fillEnabled:!1})}function Kr(n,e=St.stroke,t=1){return new Z.Line({points:n,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function Jh(n,e,t,i=12,r="Arial",s=St.text,a="left",o="top"){return new Z.Text({text:n,x:e,y:t,fontSize:i,fontFamily:r,fill:s,align:a,verticalAlign:o})}function Qh(n=0,e=0){return new Z.Group({x:n,y:e})}function ed(n,e,t,i,r,s,a,o){const l=o||i,c=a==="major"?l*.6:l*.3,h=Kr([e,t,e,t+c],s.timeTick,a==="major"?1:.5);if(h.name("time-tick-line"),n.add(h),a==="major"){const d=t+c+5,u=Jh(U.formatTime(r),e,d,10,"Arial",s.timeText,"center");u.name("time-tick-text"),n.add(u)}}function td(n,e,t,i,r,s){const a=Qh(e,t);for(let o=0;o<=i;o+=s)a.add(Kr([o,0,o,r],xs.line,.5));for(let o=0;o<=r;o+=s)a.add(Kr([0,o,i,o],xs.line,.5));n.add(a)}class he{static createStage(e,t,i){return new Z.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new Z.Layer;return t.name(e),t}static createRect(e,t,i,r,s=St.fill,a=St.stroke,o=1){return new Z.Rect({x:e,y:t,width:i,height:r,fill:s,stroke:a,strokeWidth:o})}static createText(e,t,i,r=12,s="Arial",a=St.text,o="left",l="top"){return new Z.Text({text:e,x:t,y:i,fontSize:r,fontFamily:s,fill:a,align:o,verticalAlign:l})}static createLine(e,t=St.stroke,i=1){return new Z.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new Z.Group({x:e,y:t})}static drawTimeTick(e,t,i,r,s,a,o,l){ed(e,t,i,r,s,a,o,l)}static drawGrid(e,t,i,r,s,a){td(e,t,i,r,s,a)}static clearImageCache(){pe.clearImageCache()}static createClipGroup(e,t,i,r,s,a,o,l=!1,c,h,d="video",u=!1,g=!1,f,m,C){return jh(e,t,i,r,s,a,o,l,c,h,d,u,g,f,m,C)}static updateClipGroup(e,t,i,r,s,a,o=!1,l,c,h="video",d=!1,u=!1,g,f,m){Kh(e,t,i,r,s,a,o,l,c,h,d,u,g,f,m)}static createSelectionEffect(e,t,i,r){return Zh(e,t,i,r)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}p(he,"RESIZE_AREA_WIDTH",3);const Yt=8;function ge(n,e,t){return he.timeToPixels(n,e)-t+ue}function Ce(n,e){const t=Math.max(n,0),i=he.timeToPixels(t,e);return i<=ci?ci:i}function id(n,e){const t=ge(n.startTime,n.zoom,n.scrollLeft),i=Ce(n.duration,n.zoom);return t+i>0&&t<e}function rd(n){for(const e of n.clips){const t=ge(e.startTime,n.zoom,n.scrollLeft),i=Ce(e.duration,n.zoom),r=n.y>=n.trackY&&n.y<=n.trackY+n.trackHeight;if(n.x>=t&&n.x<=t+Yt&&r||n.x>=t+i-Yt&&n.x<=t+i&&r)return"ew-resize";if(n.x>t+Yt&&n.x<t+i-Yt&&r)return"pointer"}return"default"}class Ni{constructor(e,t,i){p(this,"clip");p(this,"onUpdate");p(this,"onSplit");this.clip=ls({...e,endTime:U.calculateEndTime(e.startTime,e.duration)},{isDragging:e.isDragging,isResizingLeft:e.isResizingLeft,isResizingRight:e.isResizingRight,isSelected:e.isSelected,isResizing:e.isResizing,zIndex:e.zIndex,opacity:e.opacity}),this.onUpdate=t,this.onSplit=i}getClip(){return{...this.clip}}applyPreviewState(e){this.clip={...this.clip,...e,endTime:U.calculateEndTime(e.startTime,e.duration)}}setSelected(e){this.clip={...this.clip,isSelected:e},this.onUpdate(this.clip)}isPointInResizeHandle(e,t,i,r,s,a){const o=ge(this.clip.startTime,i,a),l=Ce(this.clip.duration,i),c=Yt;return t<r||t>r+s?(this.setResizeHandleState(!1,!1),!1):e>=o&&e<=o+c?(this.setResizeHandleState(!0,!1),!0):e>=o+l-c&&e<=o+l?(this.setResizeHandleState(!1,!0),!0):(this.setResizeHandleState(!1,!1),!1)}startDrag(e){this.clip={...this.clip,isDragging:!0,isResizing:!1,isResizingLeft:!1,isResizingRight:!1},this.onUpdate(this.clip)}startResize(e){this.clip={...this.clip,isDragging:!0,isResizing:!0},this.onUpdate(this.clip)}endDrag(){this.clip={...this.clip,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1}}split(e){e>this.clip.startTime+1&&e<this.clip.endTime-1&&this.onSplit(this.clip,e)}setResizeHandleState(e,t){this.clip={...this.clip,isResizingLeft:e,isResizingRight:t}}}function dr(n){let e=!1;return typeof window<"u"&&(window.addEventListener("mousemove",n.onPointerMove),window.addEventListener("mouseup",n.onPointerEnd),window.addEventListener("blur",n.onWindowBlur||n.onPointerEnd),e=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",n.onVisibilityChange),e=!0),e}function ur(n){typeof window<"u"&&(window.removeEventListener("mousemove",n.onPointerMove),window.removeEventListener("mouseup",n.onPointerEnd),window.removeEventListener("blur",n.onWindowBlur||n.onPointerEnd)),typeof document<"u"&&document.removeEventListener("visibilitychange",n.onVisibilityChange)}function Qi(){return{kind:"idle"}}function dn(n){return!!n&&n.kind!=="idle"}function er(n){return(n==null?void 0:n.kind)==="draggingMove"||(n==null?void 0:n.kind)==="draggingResizeLeft"||(n==null?void 0:n.kind)==="draggingResizeRight"}function gt(n){return!n||n.kind==="idle"||n.kind==="boxSelecting"?null:n.context}function tr(n){return!n||n.kind==="idle"||n.kind==="boxSelecting"?null:n.kind==="pressed"?n.operation:n.kind==="draggingResizeLeft"?"resize-left":n.kind==="draggingResizeRight"?"resize-right":"move"}function sd(n){const e=tr(n);return e?e==="move"?"grabbing":"ew-resize":null}function Li(n,e){if(e.type==="POINTER_DOWN")return{state:{kind:"pressed",operation:e.operation,context:{clipId:e.clipId,originalClipsState:e.originalClipsState,nonDraggedClips:e.nonDraggedClips,snapCandidateClips:e.snapCandidateClips,pointerStartClientX:e.clientX,pointerStartClientY:e.clientY,pointerStartX:e.localX,pointerStartY:e.localY,dragStartScrollLeft:e.scrollLeft,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:e.localY,crossTrackDragOffsetY:0}},effects:{bindGlobalListeners:!0}};if(e.type==="BOX_SELECT_START")return{state:{kind:"boxSelecting",context:{startClientX:e.clientX,startClientY:e.clientY,startLocalX:e.localX,startLocalY:e.localY,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY,additive:e.additive}},effects:{bindGlobalListeners:!0}};if(n.kind==="idle")return{state:n,effects:{}};if(n.kind==="boxSelecting")return e.type==="BOX_SELECT_MOVE"?{state:{kind:"boxSelecting",context:{...n.context,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY}},effects:{updatePreview:!0}}:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP"||e.type==="CANCEL"||e.type==="VISIBILITY_HIDDEN"||e.type==="WINDOW_BLUR"?{state:Qi(),effects:{unbindGlobalListeners:!0,commit:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP",cleanup:!0}}:{state:n,effects:{}};if(e.type==="POINTER_MOVE"){const i=ad(n.context,e,tr(n)||"move");return n.kind==="pressed"?od(n.context,e.activationThreshold,e.clientX,e.clientY)?{state:nd(n.operation,i),effects:{updatePreview:!0}}:{state:{...n,context:i},effects:{}}:{state:{...n,context:i},effects:{updatePreview:!0}}}if(e.type==="SCROLL_LEFT_CHANGED")return{state:n,effects:{updatePreview:er(n)}};const t=e.type==="POINTER_UP"&&er(n);return{state:Qi(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function nd(n,e){return n==="resize-left"?{kind:"draggingResizeLeft",context:e}:n==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function ad(n,e,t){const i=t==="move";return{...n,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:i?e.localY:n.pointerStartY,crossTrackDragOffsetY:i?e.localY-n.pointerStartY:0}}function od(n,e,t,i){const r=t-n.pointerStartClientX,s=i-n.pointerStartClientY;return Math.hypot(r,s)>=Math.max(0,e)}const le=class le{constructor(e,t,i,r,s,a,o,l,c,h,d,u,g,f,m,C,v,S,T,k,_,w,D,x,M,O,z=le.DEFAULT_DRAG_ACTIVATION_THRESHOLD,H=!1,$=le.DEFAULT_CLIP_SNAP_THRESHOLD){p(this,"layer");p(this,"trackGroup");p(this,"dragOverlayLayer",null);p(this,"dropPreviewGroup",null);p(this,"dropPreviewClips",[]);p(this,"config");p(this,"theme");p(this,"trackType");p(this,"clips",[]);p(this,"clipGroups",new Map);p(this,"zoom",100);p(this,"scrollLeft",0);p(this,"trackY",0);p(this,"trackHeight",64);p(this,"selectedClip",null);p(this,"hasSelectedClip",!1);p(this,"selectedClipIds",new Set);p(this,"multiDragOriginalPositions",new Map);p(this,"promotedClipParents",new Map);p(this,"interactionState",Qi());p(this,"isVisualUpdate",!1);p(this,"onClipUpdate");p(this,"onClipAdd");p(this,"onClipRemove");p(this,"onClipSplit");p(this,"onClipSelect");p(this,"onTimeJump");p(this,"onClipOverlap");p(this,"onPrimaryTrackMagnetMove");p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"hasLockedGlobalCursor",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"onHorizontalDragAutoScroll");p(this,"onClipCrossTrackPreview");p(this,"onClipCrossTrack");p(this,"onClearDropPreview");p(this,"onClearSelection");p(this,"onSnapGuideChange");p(this,"onClipToggleSelection");p(this,"onSetSingleSelection");p(this,"getMultiDragClipIds");p(this,"onMultiDragMove");p(this,"onMultiDragInteractionEnd");p(this,"resolveSnapTargetClips");p(this,"dragActivationThreshold");p(this,"enableClipSnap");p(this,"clipSnapThreshold");p(this,"handleGlobalPointerMove",e=>{dn(this.interactionState)&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});p(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});p(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const e=this.interactionState;if(!er(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=gt(e);if(!i||!r){this.stopEdgeAutoScroll();return}const s=i.getBoundingClientRect(),a=r.lastPointerClientX-s.left,o=this.calculateHorizontalAutoScrollVelocity(a,s.width);if(o===0){this.stopEdgeAutoScroll();return}const l=this.scrollLeft,c=this.onHorizontalDragAutoScroll(this.scrollLeft+o),h=typeof c=="number"?c:this.scrollLeft;if(Math.abs(h-l)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.layer=e,this.config=t,this.theme=o,this.trackType=i,this.zoom=r,this.trackY=s,this.trackHeight=a,this.onClipUpdate=l,this.onClipAdd=c,this.onClipRemove=h,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=g,this.onHorizontalDragAutoScroll=f,this.onClipOverlap=m,this.onPrimaryTrackMagnetMove=C,this.onClipCrossTrackPreview=v,this.onClipCrossTrack=S,this.onClearDropPreview=T,this.onClearSelection=k,this.onSnapGuideChange=_,this.onClipToggleSelection=w,this.onSetSingleSelection=D,this.getMultiDragClipIds=x,this.onMultiDragMove=M,this.onMultiDragInteractionEnd=O,this.dragActivationThreshold=Math.max(0,z),this.enableClipSnap=H,this.clipSnapThreshold=Math.max(0,$),this.trackGroup=he.createGroup(0,s),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}initClips(){this.clips=this.config.clips.map(e=>{const t=new Ni(e,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));return this.createClipGroup(e),t})}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const e=he.createGroup(0,0);return e.name("clip-drop-preview"),e.visible(!1),e.listening(!1),this.trackGroup.add(e),this.dropPreviewGroup=e,e}createDropPreviewRect(e){const t=this.trackType==="text"?"rgba(96, 76, 51, 0.28)":this.trackType==="video"?Ti.videoFill:Ti.audioFill,i=this.trackType==="text"?"#C9CBD4":this.trackType==="video"?Ti.videoStroke:Ti.audioStroke,r=ge(e.startTime,this.zoom,this.scrollLeft),s=Ce(e.duration,this.zoom),a=he.createRect(r,2,Math.max(s,1),Math.max(this.trackHeight-4,1),t,i,1);return a.dash([6,4]),a.cornerRadius(4),a.listening(!1),a.visible(r+s>0&&r<this.layer.width()),a}showDropPreview(e){const t=this.ensureDropPreviewGroup(),i=Array.isArray(e)?e:[e];this.dropPreviewClips=i.map(s=>({...s})),t.destroyChildren();let r=!1;for(const s of this.dropPreviewClips){const a=this.createDropPreviewRect(s);r=r||a.visible(),t.add(a)}t.x(0),t.y(0),t.visible(r),t.moveToTop()}hideDropPreview(){var e;this.dropPreviewClips=[],(e=this.dropPreviewGroup)==null||e.visible(!1)}initEventListeners(){const e=this.layer.getStage();e&&e.on("mouseup",()=>{this.handleClipMouseUp()})}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}),this.hasBoundGlobalPointerListenersForDrag=!1)}handleTrackBackgroundClick(e){const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),s=e.clientX-r.left,a=Math.max(0,U.pixelsToTime(s-ue+this.scrollLeft,this.zoom));this.onTimeJump(a),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(e){}getClipDisplayLabel(e){return(e.type==="text"||Re(e))&&e.textContent||e.name}getClipAudioBadgeText(e){if(Re(e))return e.name}isSourceBoundClip(e){return e.type!=="text"}updateClipSelection(e,t){const i=this.clips.find(r=>r.getClip().id===e);i&&(this.isVisualUpdate=!0,i.setSelected(t),this.isVisualUpdate=!1,t?this.selectedClipIds.add(e):this.selectedClipIds.delete(e),this.syncSelectionState(e),this.updateClipGroup(i.getClip()),this.render(!1),this.layer.batchDraw())}createClipGroup(e){const t=ge(e.startTime,this.zoom,this.scrollLeft),i=Ce(e.duration,this.zoom),r=2,s=this.trackHeight-4,a=he.createClipGroup(t,r,i,s,this.getClipDisplayLabel(e),e.duration,this.theme,!1,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,!1,this.getClipAudioBadgeText(e),e.mediaStatus,e.mediaStatusMessage);a.name(`clip-${e.id}`),a.on("click",o=>{this.handleClipClick(e.id,o.evt)}),a.on("mousedown",o=>{this.handleClipMouseDown(e.id,o.evt)}),a.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),a.on("mouseleave",()=>{this.handleClipMouseLeave()}),a.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(a),this.clipGroups.set(e.id,a)}handleClipClick(e,t){if(t.button!==0)return;this.clips.find(r=>r.getClip().id===e)&&this.render()}handleClipMouseDown(e,t){var h;if(t.button!==0)return;if(t.ctrlKey||t.metaKey){this.onClipToggleSelection&&this.onClipToggleSelection(e);return}const i=(h=this.getMultiDragClipIds)==null?void 0:h.call(this,e),r=i!=null&&i.length>1;if(!r)this.selectedClipIds.clear(),this.selectedClipIds.add(e),this.onSetSingleSelection&&this.onSetSingleSelection(e);else{this.selectedClipIds.clear();for(const d of i)this.selectedClipIds.add(d)}this.clips.sort((d,u)=>d.getClip().startTime-u.getClip().startTime);const s=this.clips.map(d=>({...d.getClip()})),a=this.clips.filter(d=>d.getClip().id!==e).map(d=>({...d.getClip()})),l=(this.resolveSnapTargetClips?this.resolveSnapTargetClips():this.clips.map(d=>d.getClip())).filter(d=>d.id!==e).map(d=>({...d})),c=this.clips.find(d=>d.getClip().id===e);if(c){r||(this.applySelectionVisual(new Set([e])),this.onClipSelect(c.getClip())),this.selectedClip=c;const d=this.layer.getStage();if(!d)return;const u=d.container();if(!u)return;const g=u.getBoundingClientRect(),f=t.clientX-g.left,m=t.clientY-g.top;if(r){this.multiDragOriginalPositions.clear();for(const v of this.selectedClipIds){const S=this.clips.find(T=>T.getClip().id===v);if(S){const T=S.getClip();this.multiDragOriginalPositions.set(v,{startTime:T.startTime,duration:T.duration})}}}let C;c.isPointInResizeHandle(f,m,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(C=c.getClip().isResizingLeft?"resize-left":"resize-right",c.startResize({x:f,y:m})):(C="move",c.startDrag({x:f,y:m}),this.trackGroup.moveToTop()),this.applyInteractionTransition(Li(this.interactionState,{type:"POINTER_DOWN",operation:C,clipId:e,originalClipsState:s,nonDraggedClips:a,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:f,localY:m,scrollLeft:this.scrollLeft})),this.render()}}handleClipMouseMove(e){this.updateHoverCursor(e.clientX,e.clientY)}handleTrackBackgroundMouseMove(){if(this.isDragSessionActive())return;const e=this.layer.getStage(),t=e==null?void 0:e.container();t&&(t.style.cursor="default")}handleClipMouseUp(){this.finishPointerInteraction("POINTER_UP")}finishPointerInteraction(e){const t=this.interactionState,i=this.resolveDraggedClipForInteraction(t);try{if(!i)return;const r=i.getClip();if(!r.isDragging)return;i.endDrag();const s=Li(t,{type:e});this.interactionState=s.state,s.effects.commit&&this.handleClipMoveEnd(r,t),this.layer.batchDraw()}finally{this.interactionState=Qi(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}resolveDraggedClipForInteraction(e=this.interactionState){const t=gt(e);if(t!=null&&t.clipId){const r=this.clips.find(s=>s.getClip().id===t.clipId)??null;if(r)return r}const i=this.clips.find(r=>r.getClip().isDragging)??null;return i||this.selectedClip}applyInteractionTransition(e){var i,r;this.interactionState=e.state,e.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const t=sd(e.state);t&&this.lockPointerCursor(t),e.effects.cleanup&&(this.releasePointerCursor(),this.hideDropPreview(),(i=this.onClearDropPreview)==null||i.call(this),this.updateSnapGuideLine(null),this.stopEdgeAutoScroll(),this.clearClipDragOverlay(),this.multiDragOriginalPositions.size>0&&((r=this.onMultiDragInteractionEnd)==null||r.call(this),this.multiDragOriginalPositions.clear())),e.effects.unbindGlobalListeners&&this.unbindGlobalPointerListenersForDrag()}handleClipMoveEnd(e,t){var m,C,v;const i=t??this.interactionState,r=gt(i)||{clipId:e.id,originalClipsState:[e],nonDraggedClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:0,crossTrackDragOffsetY:0},s=tr(i)||(e.isResizingLeft?"resize-left":e.isResizingRight?"resize-right":"move"),a=s==="move",o=a&&this.multiDragOriginalPositions.size>0,l=(m=this.clipGroups)==null?void 0:m.get(e.id);if(l&&l.y(2),o){const S=this.multiDragOriginalPositions.get(e.id),T=S?e.startTime-S.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:e.id,deltaTime:T,targetTrackY:r.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:r.crossTrackDragOffsetY,isFinal:!0})){for(const M of this.selectedClipIds){const O=(C=this.clipGroups)==null?void 0:C.get(M);O==null||O.y(2)}this.multiDragOriginalPositions.clear();return}const k=[],_=[];for(const[x,M]of this.multiDragOriginalPositions){const O=this.clips.find(G=>G.getClip().id===x);if(!O)continue;const z=Math.max(0,M.startTime+T),H={...O.getClip(),startTime:z,endTime:z+M.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(x)};k.push(H);const $=r.originalClipsState.find(G=>G.id===x);$&&_.push($);const V=(v=this.clipGroups)==null?void 0:v.get(x);V&&V.y(2)}const w=[];for(const x of this.clips){const M=x.getClip(),O=k.find(z=>z.id===M.id);O?w.push(O):w.push({...M,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}w.sort((x,M)=>x.startTime-M.startTime),this.isVisualUpdate=!0;for(const x of w)this.clips.find(O=>O.getClip().id===x.id)&&this.handleClipUpdate(x);this.isVisualUpdate=!1;const D=_.map(x=>{const M=k.find(O=>O.id===x.id);return M&&(x.startTime!==M.startTime||x.duration!==M.duration)?{clipId:x.id,previousState:x,newState:M}:null}).filter(x=>x!==null);D.length>0&&this.onClipUpdate(e,_.find(x=>x.id===e.id),D),this.multiDragOriginalPositions.clear();return}if(a&&this.onClipCrossTrack&&this.config.id){const S=r.originalClipsState.find(k=>k.id===e.id)??null;if(this.onClipCrossTrack(e,S,r.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}if(a&&this.config.role==="primary"&&this.onPrimaryTrackMagnetMove&&this.config.id){const S=r.originalClipsState.find(k=>k.id===e.id)??null;if(this.onPrimaryTrackMagnetMove(e,S,[...r.nonDraggedClips],this.config.id))return}const c=a?[...r.nonDraggedClips]:[];let h=!1;const d=e.startTime+e.duration;for(const S of c){const T=S.startTime+S.duration;if(e.startTime<T&&d>S.startTime){h=!0;break}}if(a&&h&&this.onClipOverlap&&this.config.id){const S=r.originalClipsState.find(T=>T.id===e.id)??null;this.onClipOverlap(e,this.config.id,S);return}const u=r.nonDraggedClips.map(S=>({...S}));if(s==="resize-right"){const S=r.originalClipsState.find(T=>T.id===e.id);if(S){const T=this.computeResizeRightPushFollowers(S,e,r.nonDraggedClips);for(const k of T){const _=u.findIndex(w=>w.id===k.id);_>=0&&(u[_]={...k,isSelected:!1})}}}let g=u.findIndex(S=>S.startTime>=e.startTime);g===-1&&(g=u.length),r.nonDraggedClips.forEach(S=>{S.isSelected=!1});const f={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};u.splice(g,0,f),this.config.role==="primary"&&(s==="resize-left"||s==="resize-right")&&this.compactPrimaryTrackClips(u),this.updateAllClips(u),this.buildAndSendUpdates(f,u,r.originalClipsState)}compactPrimaryTrackClips(e){if(e.length<=1)return;const t=e.map((r,s)=>({clip:r,index:s})).sort((r,s)=>r.clip.startTime===s.clip.startTime?r.index-s.index:r.clip.startTime-s.clip.startTime);let i=t[0].clip.startTime+t[0].clip.duration;t[0].clip.endTime=i;for(let r=1;r<t.length;r+=1){const s=t[r].clip;s.startTime=i,s.endTime=s.startTime+s.duration,i=s.endTime}}updateAllClips(e){const t=this.clips??[];this.isVisualUpdate=!0,e.forEach(i=>{t.find(s=>s.getClip().id===i.id)&&this.handleClipUpdate(i)}),this.isVisualUpdate=!1,t.sort((i,r)=>i.getClip().startTime-r.getClip().startTime),this.clips=t}buildAndSendUpdates(e,t,i){const r=i.map(s=>{const a=t.find(o=>o.id===s.id);return a&&(s.startTime!==a.startTime||s.duration!==a.duration||s.opacity!==a.opacity)?{clipId:s.id,previousState:s,newState:a}:null}).filter(s=>s!==null);r.length>0&&this.onClipUpdate(e,i.find(s=>s.id===e.id),r)}updateHoverCursor(e,t){const i=this.layer.getStage();if(!i)return;const r=i.container();if(!r||this.isDragSessionActive())return;const s=r.getBoundingClientRect(),a=e-s.left,o=t-s.top;r.style.cursor=rd({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:a,y:o})}isDragSessionActive(){return dn(this.interactionState)}handleDragMove(e){const t=this.interactionState,i=this.layer.getStage(),r=i==null?void 0:i.container();if(!r)return;const s=r.getBoundingClientRect(),a=Li(t,{type:"POINTER_MOVE",clientX:e.clientX,clientY:e.clientY,localY:e.clientY-s.top,activationThreshold:this.dragActivationThreshold});this.interactionState=a.state,a.effects.updatePreview&&this.updateDraggedClipFromPointer(e.clientX,e.clientY,!0)}handleClipMouseLeave(){if(this.isDragSessionActive())return;const e=this.layer.getStage();e&&e.container()&&(e.container().style.cursor="default")}lockPointerCursor(e){const t=typeof this.layer.getStage=="function"?this.layer.getStage():null,i=t==null?void 0:t.container();i&&(i.style.cursor=e),typeof document<"u"&&document.body&&(document.body.style.cursor=e,this.hasLockedGlobalCursor=!0)}releasePointerCursor(){const e=typeof this.layer.getStage=="function"?this.layer.getStage():null,t=e==null?void 0:e.container();t&&(t.style.cursor="default"),this.hasLockedGlobalCursor&&typeof document<"u"&&document.body&&(document.body.style.cursor="",this.hasLockedGlobalCursor=!1)}updateClipGroup(e,t=!1){const i=this.clipGroups.get(e.id);if(i){const r=Ce(e.duration,this.zoom);this.updateClipViewportState(e);const s=e.isSelected;(e.isDragging||s)&&i.moveToTop(),i.opacity(e.opacity),he.updateClipGroup(i,r,this.trackHeight-4,this.getClipDisplayLabel(e),e.duration,this.theme,s,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,t,this.getClipAudioBadgeText(e),e.mediaStatus,e.mediaStatusMessage)}}handleClipUpdate(e){const t=this.clips.findIndex(i=>i.getClip().id===e.id);if(t!==-1){const i=this.clips[t].getClip(),r={...e,isSelected:this.isVisualUpdate?e.isSelected:this.selectedClipIds.has(e.id)};this.clips[t]=new Ni(r,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this)),this.syncSelectionState(e.id),this.updateClipGroup(r);const s=this.clipGroups.get(e.id);s&&s.opacity(r.opacity),this.isVisualUpdate||this.onClipUpdate(r,i),this.layer.batchDraw()}}handleClipSplit(e,t){const i=t-e.startTime,r=e.duration-i,s=e.startTimeAtSource+i,a={...e,duration:i,endTime:t,endTimeAtSource:s},o={...e,id:`${e.id}_split_${Date.now()}`,startTime:t,duration:r,endTime:U.calculateEndTime(t,r),startTimeAtSource:s,endTimeAtSource:e.endTimeAtSource};this.removeClip(e.id),this.addClip(a),this.addClip(o),this.onClipSplit(a,o),this.layer.batchDraw()}addClip(e){if(e.type!==this.trackType){N.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new Ni(t,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));this.clips.push(i),this.createClipGroup(t),this.onClipAdd(t),this.layer.batchDraw()}removeClip(e){const t=this.clips.findIndex(i=>i.getClip().id===e);if(t!==-1){this.clips.splice(t,1),this.selectedClipIds.delete(e),this.syncSelectionState();const i=this.clipGroups.get(e);i&&(this.getPromotedClipParents().delete(e),i.remove(),this.clipGroups.delete(e)),this.onClipRemove(e),this.hideDropPreview(),this.render(!1),this.layer.batchDraw()}}updateClip(e,t){const i=this.clips.find(r=>r.getClip().id===e);if(i){const s={...i.getClip(),...t};(t.startTime!==void 0||t.duration!==void 0)&&(s.endTime=s.startTime+s.duration),this.handleClipUpdate(s)}}setZoom(e){this.zoom=e,this.clips.forEach(t=>{this.updateClipGroup(t.getClip())}),this.layer.batchDraw()}setCurrentTime(e){}setScrollLeft(e){this.scrollLeft=e,this.clips.forEach(s=>{const a=s.getClip();this.updateClipViewportState(a)});const t=this.interactionState,i=gt(t),r=Li(t,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=r.state,r.effects.updatePreview&&i&&this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1),this.layer.batchDraw()}updateClipVisibility(e){const t=this.clipGroups.get(e.id);if(t){const i=id({startTime:e.startTime,duration:e.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width());t.visible(i)}}updateClipViewportState(e){const t=this.clipGroups.get(e.id);t&&(t.x(ge(e.startTime,this.zoom,this.scrollLeft)),this.updateClipVisibility(e))}setTrackY(e){const t=e-this.trackY;this.trackY=e,this.trackGroup.y(e),this.getPromotedClipParents().forEach((i,r)=>{i.baseY=e;const s=this.clipGroups.get(r);s&&s.y(s.y()+t)})}setTrackStackOrder(e){this.trackGroup.zIndex(e)}setDragOverlayLayer(e){this.dragOverlayLayer=e}setClipsDragOverlayActive(e,t){e.forEach(i=>{this.setClipDragOverlayActive(i,t)})}clearClipDragOverlay(){Array.from(this.getPromotedClipParents().keys()).forEach(e=>{this.setClipDragOverlayActive(e,!1)})}getTrackType(){return this.trackType}render(e=!0){const t=this.getTrackBackgroundFill();if(this.trackGroup.children.length===0){const i=he.createRect(0,0,this.layer.width(),this.trackHeight,t,this.theme.trackBorder,1);i.name("track-background"),i.on("click",r=>{this.handleTrackBackgroundClick(r.evt)}),i.on("mousedown",r=>{this.handleTrackBackgroundMouseDown(r.evt)}),i.on("mousemove",()=>{this.handleTrackBackgroundMouseMove()}),i.on("mouseleave",()=>{this.handleClipMouseLeave()}),this.trackGroup.add(i)}else{const i=this.trackGroup.findOne(".track-background");i&&(i.width(this.layer.width()),typeof i.height=="function"&&i.height(this.trackHeight),i.fill(t),i.stroke(this.theme.trackBorder),i.listening()||i.listening(!0))}e&&this.layer.batchDraw()}getTrackBackgroundFill(){return this.hasSelectedClip?this.theme.trackSelectedBackground||ee.trackSelectedBackground:this.theme.trackBackground}getClips(){return this.clips.map(e=>e.getClip())}getPrimarySelectedClip(){return this.selectedClip?this.selectedClip.getClip():null}clearSelection(){this.setSelection([])}setSelection(e,t){const i=new Set(e);this.applySelectionVisual(i),this.selectedClipIds=i,this.syncSelectionState(t??e[0]??void 0),this.render()}applySelectionVisual(e){this.isVisualUpdate=!0;try{this.clips.forEach(t=>{const i=t.getClip().id,r=e.has(i);t.setSelected(r)})}finally{this.isVisualUpdate=!1}}syncSelectionState(e){var a;const t=this.clips.filter(o=>this.selectedClipIds.has(o.getClip().id)),r=t.length>0?t:this.clips.filter(o=>o.getClip().isSelected);if(this.selectedClipIds=new Set(r.map(o=>o.getClip().id)),this.hasSelectedClip=r.length>0,!this.hasSelectedClip){this.selectedClip=null;return}const s=e??((a=this.selectedClip)==null?void 0:a.getClip().id)??null;this.selectedClip=r.find(o=>o.getClip().id===s)??r[r.length-1]??null}splitSelectedClip(e){const t=this.clips.find(i=>{const r=i.getClip();return e>=r.startTime&&e<r.endTime});t&&t.getClip().type!=="text"&&t.split(e)}removeClipGaps(){N.debugLazy("Track",()=>"Removing clip gaps");const e=this.clips.map(i=>i.getClip()).sort((i,r)=>i.startTime-r.startTime);if(e.length===0)return;let t=0;for(let i=0;i<e.length;i++){const r=e[i];if(t-r.startTime<0||i===0){const a=t,o=a+r.duration;this.handleClipUpdate({...r,startTime:a,endTime:o}),t=o}else t=r.startTime+r.duration}}getTrackGroup(){return this.trackGroup}getId(){return this.config.id||"default"}updateClipPosition(e,t,i,r=0){var l;const s=this.clips.find(c=>c.getClip().id===e);if(!s)return;const a=s.getClip(),o=this.clipGroups.get(e);if(i)this.setClipDragOverlayActive(e,!1),this.updateClipPositionFinal(e,t);else if(o){const c=ge(t,this.zoom,this.scrollLeft);o.x(c),o.y(this.resolveClipRenderY(e,r)),o.moveToTop(),he.updateClipGroup(o,Ce(a.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(a),a.duration,this.theme,!0,a.thumbnails,a.src,a.type,!!a.separatedAudioClipId,!0,this.getClipAudioBadgeText(a),a.mediaStatus,a.mediaStatusMessage),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw()}}updateClipPositionFinal(e,t){const i=this.clips.find(a=>a.getClip().id===e);if(!i)return;const r=i.getClip(),s=this.clipGroups.get(e);this.setClipDragOverlayActive(e,!1),s==null||s.y(2),this.isVisualUpdate=!0,this.handleClipUpdate({...r,startTime:t,endTime:t+r.duration}),this.isVisualUpdate=!1}setTrackHeight(e){var t,i;if(this.trackHeight=e,(t=this.dropPreviewGroup)!=null&&t.visible()&&Array.isArray(this.dropPreviewClips)&&this.dropPreviewClips.length>0)this.showDropPreview(this.dropPreviewClips);else if((i=this.dropPreviewGroup)!=null&&i.visible()){const r=this.dropPreviewGroup.children[0];r==null||r.height(Math.max(this.trackHeight-4,1))}this.clips.forEach(r=>{this.updateClipGroup(r.getClip(),!0)}),this.render(!1)}showClipDropPreview(e){this.showDropPreview(e),this.layer.batchDraw()}showClipDropPreviews(e){this.showDropPreview(e),this.layer.batchDraw()}clearClipDropPreview(){this.hideDropPreview(),this.layer.batchDraw()}getRole(){return this.config.role||"normal"}setClipSnapEnabled(e){this.enableClipSnap=e,e||this.updateSnapGuideLine(null);const t=this.interactionState,i=gt(t);if(er(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var v,S,T,k,_,w;const r=this.interactionState,s=gt(r),a=tr(r),o=this.layer.getStage(),l=this.resolveDraggedClipForInteraction(r);if(!o||!l||!s||!a)return;const c=o.container();if(!c)return;const h=c.getBoundingClientRect(),d=e-h.left,u=t-h.top,g=a==="move",f=g&&this.multiDragOriginalPositions.size>0;g&&N.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:u,currentTrackId:this.config.id,offsetY:s.crossTrackDragOffsetY}));const m=l.getClip(),C=(v=this.clipGroups)==null?void 0:v.get(m.id);if(C){const D=g&&s.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(m.id,D);const x=s.originalClipsState.find(L=>L.id===m.id);if(!x)return;const M=this.buildPreviewClip(m,x,d,s,a);if(!M){this.hideDropPreview(),(S=this.onClearDropPreview)==null||S.call(this),this.updateSnapGuideLine(null);return}const O=M.clip,z=O.startTime-x.startTime,H=this.applyPreviewClipState(l,O),$=ge(O.startTime,this.zoom,this.scrollLeft),V=Ce(O.duration,this.zoom);C.x($),C.y(this.resolveClipRenderY(m.id,s.crossTrackDragOffsetY)),C.visible($+V>0&&$<this.layer.width()),H&&(this.updateClipGroup(O),C.y(this.resolveClipRenderY(m.id,s.crossTrackDragOffsetY)));let G=!1;if(f){this.onMultiDragMove&&this.config.id&&(G=this.onMultiDragMove({draggedClipId:m.id,deltaTime:z,targetTrackY:s.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:s.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[L,X]of this.multiDragOriginalPositions){if(L===m.id)continue;const B=this.clips.find(Y=>Y.getClip().id===L);if(!B)continue;const Q=Math.max(0,X.startTime+z),ne=(T=this.clipGroups)==null?void 0:T.get(L);if(ne){const Y=ge(Q,this.zoom,this.scrollLeft);ne.x(Y),ne.y(this.resolveClipRenderY(L,s.crossTrackDragOffsetY)),ne.visible(Y+Ce(X.duration,this.zoom)>0&&Y<this.layer.width());const K=B.getClip();he.updateClipGroup(ne,Ce(K.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(K),K.duration,this.theme,!0,K.thumbnails,K.src,K.type,!!K.separatedAudioClipId,!0,this.getClipAudioBadgeText(K),K.mediaStatus,K.mediaStatusMessage)}}}if(!f&&M.resizePushFollowers.length>0)for(const L of M.resizePushFollowers){const X=(k=this.clipGroups)==null?void 0:k.get(L.id);if(!X)continue;const B=ge(L.startTime,this.zoom,this.scrollLeft);X.x(B),X.y(this.resolveClipRenderY(L.id,s.crossTrackDragOffsetY)),X.visible(B+Ce(L.duration,this.zoom)>0&&B<this.layer.width())}g&&this.onClipCrossTrackPreview&&this.config.id&&!G?this.onClipCrossTrackPreview(O,s.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():G?this.hideDropPreview():this.showDropPreview(O),this.updateSnapGuideLine(M.guideTime)}else this.hideDropPreview(),(_=this.onClearDropPreview)==null||_.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(d,h.width),this.layer.batchDraw(),(w=this.dragOverlayLayer)==null||w.batchDraw()}buildPreviewClip(e,t,i,r,s){const a=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=U.pixelsToTime(a,this.zoom);let l;s==="resize-left"||e.isResizingLeft?l=this.buildResizeLeftPreviewClip(e,t,o):s==="resize-right"||e.isResizingRight?l=this.buildResizeRightPreviewClip(e,t,o):l={...e,startTime:Math.max(0,t.startTime+o),endTime:Math.max(0,t.startTime+o)+e.duration};const c=this.constrainResizePreviewToTrackBounds(this.applyClipSnap(l,t,r.snapCandidateClips),t,r.nonDraggedClips),h=c.clip.isResizingRight?this.computeResizeRightPushFollowers(t,c.clip,r.nonDraggedClips):[];return{...c,resizePushFollowers:h}}constrainResizePreviewToTrackBounds(e,t,i){if(e.clip.isResizingLeft){const r=this.getResizeLeftBoundaryStart(t,i);if(e.clip.startTime>=r)return e;const s=e.clip.endTime,a=s-r,o=this.isSourceBoundClip(t)?{startTimeAtSource:t.endTimeAtSource-a,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:a,sourceDuration:a};return{clip:{...e.clip,startTime:r,duration:a,endTime:s,...o},guideTime:e.guideTime===r?e.guideTime:null}}return e}getResizeLeftBoundaryStart(e,t){let i=0;for(const r of t){if(r.startTime>=e.startTime)continue;const s=r.startTime+r.duration;i=Math.max(i,s)}return i}computeResizeRightPushFollowers(e,t,i){if(!t.isResizingRight)return[];const r=t.startTime+t.duration,s=U.calculateEndTime(e.startTime,e.duration),a=[...i].filter(h=>h.startTime>=s).sort((h,d)=>h.startTime-d.startTime);if(a.length===0)return[];const o=a[0],l=r-o.startTime;if(l<=0)return[];const c=l;return a.map(h=>({...h,startTime:h.startTime+c,endTime:h.startTime+c+h.duration}))}buildResizeLeftPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const g=U.calculateEndTime(t.startTime,t.duration);let f=Math.max(0,t.startTime+i),m=g-f;return m<le.MIN_CLIP_DURATION_MS&&(m=le.MIN_CLIP_DURATION_MS,f=g-m),{...e,startTime:f,duration:m,endTime:f+m,startTimeAtSource:0,endTimeAtSource:m,sourceDuration:m}}const s=Math.max(0,t.startTime+i)-t.startTime,o=Math.max(0,t.startTimeAtSource+i)-t.startTimeAtSource,l=Math.abs(s)<Math.abs(o)?s:o,c=U.calculateEndTime(t.startTime,t.duration);let h=t.startTime+l,d=t.duration-l,u;return d<le.MIN_CLIP_DURATION_MS?(d=le.MIN_CLIP_DURATION_MS,h=c-d,u=t.endTimeAtSource-d):u=t.startTimeAtSource+l,{...e,startTime:h,duration:d,endTime:h+d,startTimeAtSource:u,endTimeAtSource:t.endTimeAtSource}}buildResizeRightPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const o=Math.max(le.MIN_CLIP_DURATION_MS,t.duration+i);return{...e,startTime:t.startTime,duration:o,endTime:t.startTime+o,startTimeAtSource:0,endTimeAtSource:o,sourceDuration:o}}let r=Math.max(le.MIN_CLIP_DURATION_MS,t.duration+i);const s=t.startTimeAtSource,a=Math.min(t.sourceDuration,s+r);return r=a-s,{...e,startTime:t.startTime,duration:r,endTime:t.startTime+r,startTimeAtSource:s,endTimeAtSource:a}}applyClipSnap(e,t,i){if(!this.enableClipSnap||i.length===0)return{clip:e,guideTime:null};const r=i.flatMap(c=>[c.startTime,c.startTime+c.duration]);if(r.length===0)return{clip:e,guideTime:null};const s=U.pixelsToTime(this.clipSnapThreshold,this.zoom),a=e.startTime+e.duration,o=[];if(e.isResizingLeft)for(const c of r){const h=a-c,d=t.endTimeAtSource-h,u=Math.abs(c-e.startTime);u>s||h<le.MIN_CLIP_DURATION_MS||this.isSourceBoundClip(t)&&d<0||o.push({clip:{...e,startTime:c,duration:h,endTime:a,...this.isSourceBoundClip(t)?{startTimeAtSource:d,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:h,sourceDuration:h}},guideTime:c,distance:u})}else if(e.isResizingRight)for(const c of r){const h=c-e.startTime,d=t.startTimeAtSource+h,u=Math.abs(c-a);u>s||h<le.MIN_CLIP_DURATION_MS||this.isSourceBoundClip(t)&&d>t.sourceDuration||o.push({clip:{...e,duration:h,endTime:e.startTime+h,...this.isSourceBoundClip(t)?{endTimeAtSource:d}:{startTimeAtSource:0,endTimeAtSource:h,sourceDuration:h}},guideTime:c,distance:u})}else for(const c of r){const h=Math.abs(c-e.startTime);h<=s&&c>=0&&o.push({clip:{...e,startTime:c,endTime:c+e.duration},guideTime:c,distance:h});const d=c-e.duration,u=Math.abs(c-a);u<=s&&d>=0&&o.push({clip:{...e,startTime:d,endTime:d+e.duration},guideTime:c,distance:u})}if(o.length===0)return{clip:e,guideTime:null};o.sort((c,h)=>c.distance-h.distance);const l=o[0];return{clip:l.clip,guideTime:l.guideTime}}applyPreviewClipState(e,t){return e&&typeof e.applyPreviewState=="function"?(e.applyPreviewState(t),!0):(this.isVisualUpdate=!0,this.handleClipUpdate(t),this.isVisualUpdate=!1,!1)}setClipDragOverlayActive(e,t){var o,l;const i=this.getPromotedClipParents(),r=this.clipGroups.get(e);if(!r){i.delete(e);return}if(!t){const c=i.get(e);if(!c)return;r.remove(),c.parent.add(r);const h=(o=this.clips.find(d=>d.getClip().id===e))==null?void 0:o.getClip();h&&r.x(ge(h.startTime,this.zoom,this.scrollLeft)),r.y(2),i.delete(e),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw();return}if(i.has(e)||!this.dragOverlayLayer)return;const s=r.getParent();if(!s)return;const a=r.getAbsolutePosition();i.set(e,{parent:s,baseY:this.trackY}),r.remove(),this.dragOverlayLayer.add(r),r.position(a),r.moveToTop(),this.layer.batchDraw(),this.dragOverlayLayer.batchDraw()}resolveClipRenderY(e,t){const i=this.getPromotedClipParents().get(e);return((i==null?void 0:i.baseY)??0)+2+t}getPromotedClipParents(){return this.promotedClipParents instanceof Map||(this.promotedClipParents=new Map),this.promotedClipParents}updateSnapGuideLine(e){var t;(t=this.onSnapGuideChange)==null||t.call(this,this.enableClipSnap?e:null)}updateEdgeAutoScrollState(e,t){if(this.calculateHorizontalAutoScrollVelocity(e,t)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(le.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=le.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)}};p(le,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),p(le,"DEFAULT_CLIP_SNAP_THRESHOLD",8),p(le,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(le,"AUTO_SCROLL_MAX_SPEED",18),p(le,"MIN_CLIP_DURATION_MS",1);let ir=le;/**
14
+ `,As=()=>{if(typeof document>"u")throw new Error(Wo)};class ve{constructor(e=[1,0,0,1,0,0]){this.dirty=!1,this.m=e&&e.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new ve(this.m)}copyInto(e){e.m[0]=this.m[0],e.m[1]=this.m[1],e.m[2]=this.m[2],e.m[3]=this.m[3],e.m[4]=this.m[4],e.m[5]=this.m[5]}point(e){const t=this.m;return{x:t[0]*e.x+t[2]*e.y+t[4],y:t[1]*e.x+t[3]*e.y+t[5]}}translate(e,t){return this.m[4]+=this.m[0]*e+this.m[2]*t,this.m[5]+=this.m[1]*e+this.m[3]*t,this}scale(e,t){return this.m[0]*=e,this.m[1]*=e,this.m[2]*=t,this.m[3]*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),r=this.m[0]*t+this.m[2]*i,s=this.m[1]*t+this.m[3]*i,a=this.m[0]*-i+this.m[2]*t,o=this.m[1]*-i+this.m[3]*t;return this.m[0]=r,this.m[1]=s,this.m[2]=a,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(e,t){const i=this.m[0]+this.m[2]*t,r=this.m[1]+this.m[3]*t,s=this.m[2]+this.m[0]*e,a=this.m[3]+this.m[1]*e;return this.m[0]=i,this.m[1]=r,this.m[2]=s,this.m[3]=a,this}multiply(e){const t=this.m[0]*e.m[0]+this.m[2]*e.m[1],i=this.m[1]*e.m[0]+this.m[3]*e.m[1],r=this.m[0]*e.m[2]+this.m[2]*e.m[3],s=this.m[1]*e.m[2]+this.m[3]*e.m[3],a=this.m[0]*e.m[4]+this.m[2]*e.m[5]+this.m[4],o=this.m[1]*e.m[4]+this.m[3]*e.m[5]+this.m[5];return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=s,this.m[4]=a,this.m[5]=o,this}invert(){const e=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),t=this.m[3]*e,i=-this.m[1]*e,r=-this.m[2]*e,s=this.m[0]*e,a=e*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=e*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=t,this.m[1]=i,this.m[2]=r,this.m[3]=s,this.m[4]=a,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const e=this.m[0],t=this.m[1],i=this.m[2],r=this.m[3],s=this.m[4],a=this.m[5],o=e*r-t*i,l={x:s,y:a,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(e!=0||t!=0){const c=Math.sqrt(e*e+t*t);l.rotation=t>0?Math.acos(e/c):-Math.acos(e/c),l.scaleX=c,l.scaleY=o/c,l.skewX=(e*i+t*r)/o,l.skewY=0}else if(i!=0||r!=0){const c=Math.sqrt(i*i+r*r);l.rotation=Math.PI/2-(r>0?Math.acos(-i/c):-Math.acos(i/c)),l.scaleX=o/c,l.scaleY=c,l.skewX=0,l.skewY=(e*i+t*r)/o}return l.rotation=b._getRotation(l.rotation),l}}const Yo="[object Array]",Xo="[object Number]",jo="[object String]",qo="[object Boolean]",Ko=Math.PI/180,Zo=180/Math.PI,Rt="#",Jo="",Qo="0",el="Konva warning: ",Is="Konva error: ",tl="rgb(",gr={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},il=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let ki=[],Mt=null;const rl=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(n){setTimeout(n,16)},b={_isElement(n){return!!(n&&n.nodeType==1)},_isFunction(n){return!!(n&&n.constructor&&n.call&&n.apply)},_isPlainObject(n){return!!n&&n.constructor===Object},_isArray(n){return Object.prototype.toString.call(n)===Yo},_isNumber(n){return Object.prototype.toString.call(n)===Xo&&!isNaN(n)&&isFinite(n)},_isString(n){return Object.prototype.toString.call(n)===jo},_isBoolean(n){return Object.prototype.toString.call(n)===qo},isObject(n){return n instanceof Object},isValidSelector(n){if(typeof n!="string")return!1;const e=n[0];return e==="#"||e==="."||e===e.toUpperCase()},_sign(n){return n===0||n>0?1:-1},requestAnimFrame(n){ki.push(n),ki.length===1&&rl(function(){const e=ki;ki=[],e.forEach(function(t){t()})})},createCanvasElement(){As();const n=document.createElement("canvas");try{n.style=n.style||{}}catch{}return n},createImageElement(){return As(),document.createElement("img")},_isInDocument(n){for(;n=n.parentNode;)if(n==document)return!0;return!1},_urlToImage(n,e){const t=b.createImageElement();t.onload=function(){e(t)},t.src=n},_rgbToHex(n,e,t){return((1<<24)+(n<<16)+(e<<8)+t).toString(16).slice(1)},_hexToRgb(n){n=n.replace(Rt,Jo);const e=parseInt(n,16);return{r:e>>16&255,g:e>>8&255,b:e&255}},getRandomColor(){let n=(Math.random()*16777215<<0).toString(16);for(;n.length<6;)n=Qo+n;return Rt+n},isCanvasFarblingActive(){if(Mt!==null)return Mt;if(typeof document>"u")return Mt=!1,!1;const n=this.createCanvasElement();n.width=10,n.height=10;const e=n.getContext("2d",{willReadFrequently:!0});e.clearRect(0,0,10,10),e.fillStyle="#282828",e.fillRect(0,0,10,10);const t=e.getImageData(0,0,10,10).data;let i=!1;for(let r=0;r<100;r++)if(t[r*4]!==40||t[r*4+1]!==40||t[r*4+2]!==40||t[r*4+3]!==255){i=!0;break}return Mt=i,this.releaseCanvas(n),Mt},getHitColor(){const n=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(n):n},getHitColorKey(n,e,t){return this.isCanvasFarblingActive()&&(n=Math.round(n/5)*5,e=Math.round(e/5)*5,t=Math.round(t/5)*5),Rt+this._rgbToHex(n,e,t)},getSnappedHexColor(n){const e=this._hexToRgb(n);return Rt+this._rgbToHex(Math.round(e.r/5)*5,Math.round(e.g/5)*5,Math.round(e.b/5)*5)},getRGB(n){let e;return n in gr?(e=gr[n],{r:e[0],g:e[1],b:e[2]}):n[0]===Rt?this._hexToRgb(n.substring(1)):n.substr(0,4)===tl?(e=il.exec(n.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA(n){return n=n||"black",b._namedColorToRBA(n)||b._hex3ColorToRGBA(n)||b._hex4ColorToRGBA(n)||b._hex6ColorToRGBA(n)||b._hex8ColorToRGBA(n)||b._rgbColorToRGBA(n)||b._rgbaColorToRGBA(n)||b._hslColorToRGBA(n)},_namedColorToRBA(n){const e=gr[n.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(n){if(n.indexOf("rgb(")===0){n=n.match(/rgb\(([^)]+)\)/)[1];const e=n.split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(n){if(n.indexOf("rgba(")===0){n=n.match(/rgba\(([^)]+)\)/)[1];const e=n.split(/ *, */).map((t,i)=>t.slice(-1)==="%"?i===3?parseInt(t)/100:parseInt(t)/100*255:Number(t));return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex8ColorToRGBA(n){if(n[0]==="#"&&n.length===9)return{r:parseInt(n.slice(1,3),16),g:parseInt(n.slice(3,5),16),b:parseInt(n.slice(5,7),16),a:parseInt(n.slice(7,9),16)/255}},_hex6ColorToRGBA(n){if(n[0]==="#"&&n.length===7)return{r:parseInt(n.slice(1,3),16),g:parseInt(n.slice(3,5),16),b:parseInt(n.slice(5,7),16),a:1}},_hex4ColorToRGBA(n){if(n[0]==="#"&&n.length===5)return{r:parseInt(n[1]+n[1],16),g:parseInt(n[2]+n[2],16),b:parseInt(n[3]+n[3],16),a:parseInt(n[4]+n[4],16)/255}},_hex3ColorToRGBA(n){if(n[0]==="#"&&n.length===4)return{r:parseInt(n[1]+n[1],16),g:parseInt(n[2]+n[2],16),b:parseInt(n[3]+n[3],16),a:1}},_hslColorToRGBA(n){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(n)){const[e,...t]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(n),i=Number(t[0])/360,r=Number(t[1])/100,s=Number(t[2])/100;let a,o,l;if(r===0)return l=s*255,{r:Math.round(l),g:Math.round(l),b:Math.round(l),a:1};s<.5?a=s*(1+r):a=s+r-s*r;const c=2*s-a,h=[0,0,0];for(let d=0;d<3;d++)o=i+1/3*-(d-1),o<0&&o++,o>1&&o--,6*o<1?l=c+(a-c)*6*o:2*o<1?l=a:3*o<2?l=c+(a-c)*(2/3-o)*6:l=c,h[d]=l*255;return{r:Math.round(h[0]),g:Math.round(h[1]),b:Math.round(h[2]),a:1}}},haveIntersection(n,e){return!(e.x>n.x+n.width||e.x+e.width<n.x||e.y>n.y+n.height||e.y+e.height<n.y)},cloneObject(n){const e={};for(const t in n)this._isPlainObject(n[t])?e[t]=this.cloneObject(n[t]):this._isArray(n[t])?e[t]=this.cloneArray(n[t]):e[t]=n[t];return e},cloneArray(n){return n.slice(0)},degToRad(n){return n*Ko},radToDeg(n){return n*Zo},_degToRad(n){return b.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),b.degToRad(n)},_radToDeg(n){return b.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),b.radToDeg(n)},_getRotation(n){return M.angleDeg?b.radToDeg(n):n},_capitalize(n){return n.charAt(0).toUpperCase()+n.slice(1)},throw(n){throw new Error(Is+n)},error(n){console.error(Is+n)},warn(n){M.showWarnings&&console.warn(el+n)},each(n,e){for(const t in n)e(t,n[t])},_inRange(n,e,t){return e<=n&&n<t},_getProjectionToSegment(n,e,t,i,r,s){let a,o,l;const c=(n-t)*(n-t)+(e-i)*(e-i);if(c==0)a=n,o=e,l=(r-t)*(r-t)+(s-i)*(s-i);else{const h=((r-n)*(t-n)+(s-e)*(i-e))/c;h<0?(a=n,o=e,l=(n-r)*(n-r)+(e-s)*(e-s)):h>1?(a=t,o=i,l=(t-r)*(t-r)+(i-s)*(i-s)):(a=n+h*(t-n),o=e+h*(i-e),l=(a-r)*(a-r)+(o-s)*(o-s))}return[a,o,l]},_getProjectionToLine(n,e,t){const i=b.cloneObject(n);let r=Number.MAX_VALUE;return e.forEach(function(s,a){if(!t&&a===e.length-1)return;const o=e[(a+1)%e.length],l=b._getProjectionToSegment(s.x,s.y,o.x,o.y,n.x,n.y),c=l[0],h=l[1],d=l[2];d<r&&(i.x=c,i.y=h,r=d)}),i},_prepareArrayForTween(n,e,t){const i=[],r=[];if(n.length>e.length){const a=e;e=n,n=a}for(let a=0;a<n.length;a+=2)i.push({x:n[a],y:n[a+1]});for(let a=0;a<e.length;a+=2)r.push({x:e[a],y:e[a+1]});const s=[];return r.forEach(function(a){const o=b._getProjectionToLine(a,i,t);s.push(o.x),s.push(o.y)}),s},_prepareToStringify(n){let e;n.visitedByCircularReferenceRemoval=!0;for(const t in n)if(n.hasOwnProperty(t)&&n[t]&&typeof n[t]=="object"){if(e=Object.getOwnPropertyDescriptor(n,t),n[t].visitedByCircularReferenceRemoval||b._isElement(n[t]))if(e.configurable)delete n[t];else return null;else if(b._prepareToStringify(n[t])===null)if(e.configurable)delete n[t];else return null}return delete n.visitedByCircularReferenceRemoval,n},_assign(n,e){for(const t in e)n[t]=e[t];return n},_getFirstPointerId(n){return n.touches?n.changedTouches[0].identifier:n.pointerId||999},releaseCanvas(...n){M.releaseCanvasOnDestroy&&n.forEach(e=>{e.width=0,e.height=0})},drawRoundedRectPath(n,e,t,i){let r=e<0?e:0,s=t<0?t:0;e=Math.abs(e),t=Math.abs(t);let a=0,o=0,l=0,c=0;typeof i=="number"?a=o=l=c=Math.min(i,e/2,t/2):(a=Math.min(i[0]||0,e/2,t/2),o=Math.min(i[1]||0,e/2,t/2),c=Math.min(i[2]||0,e/2,t/2),l=Math.min(i[3]||0,e/2,t/2)),n.moveTo(r+a,s),n.lineTo(r+e-o,s),n.arc(r+e-o,s+o,o,Math.PI*3/2,0,!1),n.lineTo(r+e,s+t-c),n.arc(r+e-c,s+t-c,c,0,Math.PI/2,!1),n.lineTo(r+l,s+t),n.arc(r+l,s+t-l,l,Math.PI/2,Math.PI,!1),n.lineTo(r,s+a),n.arc(r+a,s+a,a,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(n,e,t,i,r){i=Math.abs(i);for(let s=0;s<t;s++){const a=e[(s-1+t)%t],o=e[s],l=e[(s+1)%t],c={x:o.x-a.x,y:o.y-a.y},h={x:l.x-o.x,y:l.y-o.y},d=Math.hypot(c.x,c.y),u=Math.hypot(h.x,h.y);let g;typeof r=="number"?g=r:g=s<r.length?r[s]:0,g=i*Math.cos(Math.PI/t)*Math.min(1,g/i*2);const m={x:c.x/d,y:c.y/d},C={x:h.x/u,y:h.y/u},v={x:o.x-m.x*g,y:o.y-m.y*g},S={x:o.x+C.x*g,y:o.y+C.y*g};s===0?n.moveTo(v.x,v.y):n.lineTo(v.x,v.y),n.arcTo(o.x,o.y,S.x,S.y,g)}}};function sl(n){const e=[],t=n.length,i=b;for(let r=0;r<t;r++){let s=n[r];i._isNumber(s)?s=Math.round(s*1e3)/1e3:i._isString(s)||(s=s+""),e.push(s)}return e}const Es=",",nl="(",al=")",ol="([",ll="])",cl=";",hl="()",dl="=",Rs=["arc","arcTo","beginPath","bezierCurveTo","clearRect","clip","closePath","createLinearGradient","createPattern","createRadialGradient","drawImage","ellipse","fill","fillText","getImageData","createImageData","lineTo","moveTo","putImageData","quadraticCurveTo","rect","roundRect","restore","rotate","save","scale","setLineDash","setTransform","stroke","strokeText","transform","translate"],ul=["fillStyle","strokeStyle","shadowColor","shadowBlur","shadowOffsetX","shadowOffsetY","letterSpacing","lineCap","lineDashOffset","lineJoin","lineWidth","miterLimit","direction","font","textAlign","textBaseline","globalAlpha","globalCompositeOperation","imageSmoothingEnabled","filter"],pl=100;let wi=null;function Ms(){if(wi!==null)return wi;try{const e=b.createCanvasElement().getContext("2d");return e?!!e&&"filter"in e:(wi=!1,!1)}catch{return wi=!1,!1}}class or{constructor(e){this.canvas=e,M.enableTrace&&(this.traceArr=[],this._enableTrace())}fillShape(e){e.fillEnabled()&&this._fill(e)}_fill(e){}strokeShape(e){e.hasStroke()&&this._stroke(e)}_stroke(e){}fillStrokeShape(e){e.attrs.fillAfterStrokeEnabled?(this.strokeShape(e),this.fillShape(e)):(this.fillShape(e),this.strokeShape(e))}getTrace(e,t){let i=this.traceArr,r=i.length,s="",a,o,l,c;for(a=0;a<r;a++)o=i[a],l=o.method,l?(c=o.args,s+=l,e?s+=hl:b._isArray(c[0])?s+=ol+c.join(Es)+ll:(t&&(c=c.map(h=>typeof h=="number"?Math.floor(h):h)),s+=nl+c.join(Es)+al)):(s+=o.property,e||(s+=dl+o.val)),s+=cl;return s}clearTrace(){this.traceArr=[]}_trace(e){let t=this.traceArr,i;t.push(e),i=t.length,i>=pl&&t.shift()}reset(){const e=this.getCanvas().getPixelRatio();this.setTransform(1*e,0,0,1*e,0,0)}getCanvas(){return this.canvas}clear(e){const t=this.getCanvas();e?this.clearRect(e.x||0,e.y||0,e.width||0,e.height||0):this.clearRect(0,0,t.getWidth()/t.pixelRatio,t.getHeight()/t.pixelRatio)}_applyLineCap(e){const t=e.attrs.lineCap;t&&this.setAttr("lineCap",t)}_applyOpacity(e){const t=e.getAbsoluteOpacity();t!==1&&this.setAttr("globalAlpha",t)}_applyLineJoin(e){const t=e.attrs.lineJoin;t&&this.setAttr("lineJoin",t)}_applyMiterLimit(e){const t=e.attrs.miterLimit;t!=null&&this.setAttr("miterLimit",t)}setAttr(e,t){this._context[e]=t}arc(e,t,i,r,s,a){this._context.arc(e,t,i,r,s,a)}arcTo(e,t,i,r,s){this._context.arcTo(e,t,i,r,s)}beginPath(){this._context.beginPath()}bezierCurveTo(e,t,i,r,s,a){this._context.bezierCurveTo(e,t,i,r,s,a)}clearRect(e,t,i,r){this._context.clearRect(e,t,i,r)}clip(...e){this._context.clip.apply(this._context,e)}closePath(){this._context.closePath()}createImageData(e,t){const i=arguments;if(i.length===2)return this._context.createImageData(e,t);if(i.length===1)return this._context.createImageData(e)}createLinearGradient(e,t,i,r){return this._context.createLinearGradient(e,t,i,r)}createPattern(e,t){return this._context.createPattern(e,t)}createRadialGradient(e,t,i,r,s,a){return this._context.createRadialGradient(e,t,i,r,s,a)}drawImage(e,t,i,r,s,a,o,l,c){const h=arguments,d=this._context;h.length===3?d.drawImage(e,t,i):h.length===5?d.drawImage(e,t,i,r,s):h.length===9&&d.drawImage(e,t,i,r,s,a,o,l,c)}ellipse(e,t,i,r,s,a,o,l){this._context.ellipse(e,t,i,r,s,a,o,l)}isPointInPath(e,t,i,r){return i?this._context.isPointInPath(i,e,t,r):this._context.isPointInPath(e,t,r)}fill(...e){this._context.fill.apply(this._context,e)}fillRect(e,t,i,r){this._context.fillRect(e,t,i,r)}strokeRect(e,t,i,r){this._context.strokeRect(e,t,i,r)}fillText(e,t,i,r){r?this._context.fillText(e,t,i,r):this._context.fillText(e,t,i)}measureText(e){return this._context.measureText(e)}getImageData(e,t,i,r){return this._context.getImageData(e,t,i,r)}lineTo(e,t){this._context.lineTo(e,t)}moveTo(e,t){this._context.moveTo(e,t)}rect(e,t,i,r){this._context.rect(e,t,i,r)}roundRect(e,t,i,r,s){this._context.roundRect(e,t,i,r,s)}putImageData(e,t,i){this._context.putImageData(e,t,i)}quadraticCurveTo(e,t,i,r){this._context.quadraticCurveTo(e,t,i,r)}restore(){this._context.restore()}rotate(e){this._context.rotate(e)}save(){this._context.save()}scale(e,t){this._context.scale(e,t)}setLineDash(e){this._context.setLineDash?this._context.setLineDash(e):"mozDash"in this._context?this._context.mozDash=e:"webkitLineDash"in this._context&&(this._context.webkitLineDash=e)}getLineDash(){return this._context.getLineDash()}setTransform(e,t,i,r,s,a){this._context.setTransform(e,t,i,r,s,a)}stroke(e){e?this._context.stroke(e):this._context.stroke()}strokeText(e,t,i,r){this._context.strokeText(e,t,i,r)}transform(e,t,i,r,s,a){this._context.transform(e,t,i,r,s,a)}translate(e,t){this._context.translate(e,t)}_enableTrace(){let e=this,t=Rs.length,i=this.setAttr,r,s;const a=function(o){let l=e[o],c;e[o]=function(){return s=sl(Array.prototype.slice.call(arguments,0)),c=l.apply(e,arguments),e._trace({method:o,args:s}),c}};for(r=0;r<t;r++)a(Rs[r]);e.setAttr=function(){i.apply(e,arguments);const o=arguments[0];let l=arguments[1];(o==="shadowOffsetX"||o==="shadowOffsetY"||o==="shadowBlur")&&(l=l/this.canvas.getPixelRatio()),e._trace({property:o,val:l})}}_applyGlobalCompositeOperation(e){const t=e.attrs.globalCompositeOperation;!t||t==="source-over"||this.setAttr("globalCompositeOperation",t)}}ul.forEach(function(n){Object.defineProperty(or.prototype,n,{get(){return this._context[n]},set(e){this._context[n]=e}})});class gl extends or{constructor(e,{willReadFrequently:t=!1}={}){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:t})}_fillColor(e){const t=e.fill();this.setAttr("fillStyle",t),e._fillFunc(this)}_fillPattern(e){this.setAttr("fillStyle",e._getFillPattern()),e._fillFunc(this)}_fillLinearGradient(e){const t=e._getLinearGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fillRadialGradient(e){const t=e._getRadialGradient();t&&(this.setAttr("fillStyle",t),e._fillFunc(this))}_fill(e){const t=e.fill(),i=e.getFillPriority();if(t&&i==="color"){this._fillColor(e);return}const r=e.getFillPatternImage();if(r&&i==="pattern"){this._fillPattern(e);return}const s=e.getFillLinearGradientColorStops();if(s&&i==="linear-gradient"){this._fillLinearGradient(e);return}const a=e.getFillRadialGradientColorStops();if(a&&i==="radial-gradient"){this._fillRadialGradient(e);return}t?this._fillColor(e):r?this._fillPattern(e):s?this._fillLinearGradient(e):a&&this._fillRadialGradient(e)}_strokeLinearGradient(e){const t=e.getStrokeLinearGradientStartPoint(),i=e.getStrokeLinearGradientEndPoint(),r=e.getStrokeLinearGradientColorStops(),s=this.createLinearGradient(t.x,t.y,i.x,i.y);if(r){for(let a=0;a<r.length;a+=2)s.addColorStop(r[a],r[a+1]);this.setAttr("strokeStyle",s)}}_stroke(e){const t=e.dash(),i=e.getStrokeScaleEnabled();if(e.hasStroke()){if(!i){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e),t&&e.dashEnabled()&&(this.setLineDash(t),this.setAttr("lineDashOffset",e.dashOffset())),this.setAttr("lineWidth",e.strokeWidth()),e.getShadowForStrokeEnabled()||this.setAttr("shadowColor","rgba(0,0,0,0)"),e.getStrokeLinearGradientColorStops()?this._strokeLinearGradient(e):this.setAttr("strokeStyle",e.stroke()),e._strokeFunc(this),i||this.restore()}}_applyShadow(e){var t,i,r;const s=(t=e.getShadowRGBA())!==null&&t!==void 0?t:"black",a=(i=e.getShadowBlur())!==null&&i!==void 0?i:5,o=(r=e.getShadowOffset())!==null&&r!==void 0?r:{x:0,y:0},l=e.getAbsoluteScale(),c=this.canvas.getPixelRatio(),h=l.x*c,d=l.y*c;this.setAttr("shadowColor",s),this.setAttr("shadowBlur",a*Math.min(Math.abs(h),Math.abs(d))),this.setAttr("shadowOffsetX",o.x*h),this.setAttr("shadowOffsetY",o.y*d)}}class fl extends or{constructor(e){super(e),this._context=e._canvas.getContext("2d",{willReadFrequently:!0})}_fill(e){this.save(),this.setAttr("fillStyle",e.colorKey),e._fillFuncHit(this),this.restore()}strokeShape(e){e.hasHitStroke()&&this._stroke(e)}_stroke(e){if(e.hasHitStroke()){const t=e.getStrokeScaleEnabled();if(!t){this.save();const s=this.getCanvas().getPixelRatio();this.setTransform(s,0,0,s,0,0)}this._applyLineCap(e);const i=e.hitStrokeWidth(),r=i==="auto"?e.strokeWidth():i;this.setAttr("lineWidth",r),this.setAttr("strokeStyle",e.colorKey),e._strokeFuncHit(this),t||this.restore()}}}let xi;function ml(){if(xi)return xi;const n=b.createCanvasElement(),e=n.getContext("2d");return xi=function(){const t=M._global.devicePixelRatio||1,i=e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||e.backingStorePixelRatio||1;return t/i}(),b.releaseCanvas(n),xi}class ds{constructor(e){this.pixelRatio=1,this.width=0,this.height=0,this.isCache=!1;const i=(e||{}).pixelRatio||M.pixelRatio||ml();this.pixelRatio=i,this._canvas=b.createCanvasElement(),this._canvas.style.padding="0",this._canvas.style.margin="0",this._canvas.style.border="0",this._canvas.style.background="transparent",this._canvas.style.position="absolute",this._canvas.style.top="0",this._canvas.style.left="0"}getContext(){return this.context}getPixelRatio(){return this.pixelRatio}setPixelRatio(e){const t=this.pixelRatio;this.pixelRatio=e,this.setSize(this.getWidth()/t,this.getHeight()/t)}setWidth(e){this.width=this._canvas.width=e*this.pixelRatio,this._canvas.style.width=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}setHeight(e){this.height=this._canvas.height=e*this.pixelRatio,this._canvas.style.height=e+"px";const t=this.pixelRatio;this.getContext()._context.scale(t,t)}getWidth(){return this.width}getHeight(){return this.height}setSize(e,t){this.setWidth(e||0),this.setHeight(t||0)}toDataURL(e,t){try{return this._canvas.toDataURL(e,t)}catch{try{return this._canvas.toDataURL()}catch(r){return b.error("Unable to get data URL. "+r.message+" For more info read https://konvajs.org/docs/posts/Tainted_Canvas.html."),""}}}}class We extends ds{constructor(e={width:0,height:0,willReadFrequently:!1}){super(e),this.context=new gl(this,{willReadFrequently:e.willReadFrequently}),this.setSize(e.width,e.height)}}class us extends ds{constructor(e={width:0,height:0}){super(e),this.hitCanvas=!0,this.context=new fl(this),this.setSize(e.width,e.height)}}const J={get isDragging(){let n=!1;return J._dragElements.forEach(e=>{e.dragStatus==="dragging"&&(n=!0)}),n},justDragged:!1,get node(){let n;return J._dragElements.forEach(e=>{n=e.node}),n},_dragElements:new Map,_drag(n){const e=[];J._dragElements.forEach((t,i)=>{const{node:r}=t,s=r.getStage();s.setPointersPositions(n),t.pointerId===void 0&&(t.pointerId=b._getFirstPointerId(n));const a=s._changedPointerPositions.find(o=>o.id===t.pointerId);if(a){if(t.dragStatus!=="dragging"){const o=r.dragDistance();if(Math.max(Math.abs(a.x-t.startPointerPos.x),Math.abs(a.y-t.startPointerPos.y))<o||(r.startDrag({evt:n}),!r.isDragging()))return}r._setDragPosition(n,t),e.push(r)}}),e.forEach(t=>{t.fire("dragmove",{type:"dragmove",target:t,evt:n},!0)})},_endDragBefore(n){const e=[];J._dragElements.forEach(t=>{const{node:i}=t,r=i.getStage();if(n&&r.setPointersPositions(n),!r._changedPointerPositions.find(o=>o.id===t.pointerId))return;(t.dragStatus==="dragging"||t.dragStatus==="stopped")&&(J.justDragged=!0,M._mouseListenClick=!1,M._touchListenClick=!1,M._pointerListenClick=!1,t.dragStatus="stopped");const a=t.node.getLayer()||t.node instanceof M.Stage&&t.node;a&&e.indexOf(a)===-1&&e.push(a)}),e.forEach(t=>{t.draw()})},_endDragAfter(n){J._dragElements.forEach((e,t)=>{e.dragStatus==="stopped"&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:n},!0),e.dragStatus!=="dragging"&&J._dragElements.delete(t)})}};M.isBrowser&&(window.addEventListener("mouseup",J._endDragBefore,!0),window.addEventListener("touchend",J._endDragBefore,!0),window.addEventListener("touchcancel",J._endDragBefore,!0),window.addEventListener("mousemove",J._drag),window.addEventListener("touchmove",J._drag),window.addEventListener("mouseup",J._endDragAfter,!1),window.addEventListener("touchend",J._endDragAfter,!1),window.addEventListener("touchcancel",J._endDragAfter,!1));function Ke(n){return b._isString(n)?'"'+n+'"':Object.prototype.toString.call(n)==="[object Number]"||b._isBoolean(n)?n:Object.prototype.toString.call(n)}function ua(n){return n>255?255:n<0?0:Math.round(n)}function E(){if(M.isUnminified)return function(n,e){return b._isNumber(n)||b.warn(Ke(n)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),n}}function lr(n){if(M.isUnminified)return function(e,t){let i=b._isNumber(e),r=b._isArray(e)&&e.length==n;return!i&&!r&&b.warn(Ke(e)+' is a not valid value for "'+t+'" attribute. The value should be a number or Array<number>('+n+")"),e}}function ps(){if(M.isUnminified)return function(n,e){return b._isNumber(n)||n==="auto"||b.warn(Ke(n)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),n}}function lt(){if(M.isUnminified)return function(n,e){return b._isString(n)||b.warn(Ke(n)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),n}}function pa(){if(M.isUnminified)return function(n,e){const t=b._isString(n),i=Object.prototype.toString.call(n)==="[object CanvasGradient]"||n&&n.addColorStop;return t||i||b.warn(Ke(n)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),n}}function yl(){if(M.isUnminified)return function(n,e){const t=Int8Array?Object.getPrototypeOf(Int8Array):null;return t&&n instanceof t||(b._isArray(n)?n.forEach(function(i){b._isNumber(i)||b.warn('"'+e+'" attribute has non numeric element '+i+". Make sure that all elements are numbers.")}):b.warn(Ke(n)+' is a not valid value for "'+e+'" attribute. The value should be a array of numbers.')),n}}function Ae(){if(M.isUnminified)return function(n,e){return n===!0||n===!1||b.warn(Ke(n)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),n}}function Sl(n){if(M.isUnminified)return function(e,t){return e==null||b.isObject(e)||b.warn(Ke(e)+' is a not valid value for "'+t+'" attribute. The value should be an object with properties '+n),e}}const Lt="get",Dt="set",y={addGetterSetter(n,e,t,i,r){y.addGetter(n,e,t),y.addSetter(n,e,i,r),y.addOverloadedGetterSetter(n,e)},addGetter(n,e,t){const i=Lt+b._capitalize(e);n.prototype[i]=n.prototype[i]||function(){const r=this.attrs[e];return r===void 0?t:r}},addSetter(n,e,t,i){const r=Dt+b._capitalize(e);n.prototype[r]||y.overWriteSetter(n,e,t,i)},overWriteSetter(n,e,t,i){const r=Dt+b._capitalize(e);n.prototype[r]=function(s){return t&&s!==void 0&&s!==null&&(s=t.call(this,s,e)),this._setAttr(e,s),i&&i.call(this),this}},addComponentsGetterSetter(n,e,t,i,r){const s=t.length,a=b._capitalize,o=Lt+a(e),l=Dt+a(e);n.prototype[o]=function(){const h={};for(let d=0;d<s;d++){const u=t[d];h[u]=this.getAttr(e+a(u))}return h};const c=Sl(t);n.prototype[l]=function(h){const d=this.attrs[e];i&&(h=i.call(this,h,e)),c&&c.call(this,h,e);for(const u in h)h.hasOwnProperty(u)&&this._setAttr(e+a(u),h[u]);return h||t.forEach(u=>{this._setAttr(e+a(u),void 0)}),this._fireChangeEvent(e,d,h),r&&r.call(this),this},y.addOverloadedGetterSetter(n,e)},addOverloadedGetterSetter(n,e){const t=b._capitalize(e),i=Dt+t,r=Lt+t;n.prototype[e]=function(){return arguments.length?(this[i](arguments[0]),this):this[r]()}},addDeprecatedGetterSetter(n,e,t,i){b.error("Adding deprecated "+e);const r=Lt+b._capitalize(e),s=e+" property is deprecated and will be removed soon. Look at Konva change log for more information.";n.prototype[r]=function(){b.error(s);const a=this.attrs[e];return a===void 0?t:a},y.addSetter(n,e,i,function(){b.error(s)}),y.addOverloadedGetterSetter(n,e)},backCompat(n,e){b.each(e,function(t,i){const r=n.prototype[i],s=Lt+b._capitalize(t),a=Dt+b._capitalize(t);function o(){r.apply(this,arguments),b.error('"'+t+'" method is deprecated and will be removed soon. Use ""'+i+'" instead.')}n.prototype[t]=o,n.prototype[s]=o,n.prototype[a]=o})},afterSetFilter(){this._filterUpToDate=!1}};function Cl(n){const e=/(\w+)\(([^)]+)\)/g;let t;for(;(t=e.exec(n))!==null;){const[,i,r]=t;switch(i){case"blur":{const s=parseFloat(r.replace("px",""));return function(a){this.blurRadius(s*.5);const o=M.Filters;o&&o.Blur&&o.Blur.call(this,a)}}case"brightness":{const s=r.includes("%")?parseFloat(r)/100:parseFloat(r);return function(a){this.brightness(s);const o=M.Filters;o&&o.Brightness&&o.Brightness.call(this,a)}}case"contrast":{const s=parseFloat(r);return function(a){const o=100*(Math.sqrt(s)-1);this.contrast(o);const l=M.Filters;l&&l.Contrast&&l.Contrast.call(this,a)}}case"grayscale":return function(s){const a=M.Filters;a&&a.Grayscale&&a.Grayscale.call(this,s)};case"sepia":return function(s){const a=M.Filters;a&&a.Sepia&&a.Sepia.call(this,s)};case"invert":return function(s){const a=M.Filters;a&&a.Invert&&a.Invert.call(this,s)};default:b.warn(`CSS filter "${i}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const Gi="absoluteOpacity",Ls="allEventListeners",Oe="absoluteTransform",Ds="absoluteScale",et="canvas",vl="Change",Tl="children",bl="konva",Or="listening",kl="mouseenter",wl="mouseleave",xl="pointerenter",Pl="pointerleave",_l="touchenter",Al="touchleave",Os="set",Bs="Shape",Ni=" ",Fs="stage",$e="transform",Il="Stage",Br="visible",El=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Ni);let Rl=1;class I{constructor(e){this._id=Rl++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(e),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(e){(e===$e||e===Oe)&&this._cache.get(e)?this._cache.get(e).dirty=!0:e?this._cache.delete(e):this._cache.clear()}_getCache(e,t){let i=this._cache.get(e);return(i===void 0||(e===$e||e===Oe)&&i.dirty===!0)&&(i=t.call(this),this._cache.set(e,i)),i}_calculate(e,t,i){if(!this._attachedDepsListeners.get(e)){const r=t.map(s=>s+"Change.konva").join(Ni);this.on(r,()=>{this._clearCache(e)}),this._attachedDepsListeners.set(e,!0)}return this._getCache(e,i)}_getCanvasCache(){return this._cache.get(et)}_clearSelfAndDescendantCache(e){this._clearCache(e),e===Oe&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(et)){const{scene:e,filter:t,hit:i}=this._cache.get(et);b.releaseCanvas(e._canvas,t._canvas,i._canvas),this._cache.delete(et)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(e){const t=e||{};let i={};(t.x===void 0||t.y===void 0||t.width===void 0||t.height===void 0)&&(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let r=Math.ceil(t.width||i.width),s=Math.ceil(t.height||i.height),a=t.pixelRatio,o=t.x===void 0?Math.floor(i.x):t.x,l=t.y===void 0?Math.floor(i.y):t.y,c=t.offset||0,h=t.drawBorder||!1,d=t.hitCanvasPixelRatio||1;if(!r||!s){b.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const u=Math.abs(Math.round(i.x)-o)>.5?1:0,g=Math.abs(Math.round(i.y)-l)>.5?1:0;r+=c*2+u,s+=c*2+g,o-=c,l-=c;const f=new We({pixelRatio:a,width:r,height:s}),m=new We({pixelRatio:a,width:0,height:0,willReadFrequently:!0}),C=new us({pixelRatio:d,width:r,height:s}),v=f.getContext(),S=C.getContext(),T=new We({width:f.width/f.pixelRatio+Math.abs(o),height:f.height/f.pixelRatio+Math.abs(l),pixelRatio:f.pixelRatio}),k=T.getContext();return C.isCache=!0,f.isCache=!0,this._cache.delete(et),this._filterUpToDate=!1,t.imageSmoothingEnabled===!1&&(f.getContext()._context.imageSmoothingEnabled=!1,m.getContext()._context.imageSmoothingEnabled=!1),v.save(),S.save(),k.save(),v.translate(-o,-l),S.translate(-o,-l),k.translate(-o,-l),T.x=o,T.y=l,this._isUnderCache=!0,this._clearSelfAndDescendantCache(Gi),this._clearSelfAndDescendantCache(Ds),this.drawScene(f,this,T),this.drawHit(C,this),this._isUnderCache=!1,v.restore(),S.restore(),h&&(v.save(),v.beginPath(),v.rect(0,0,r,s),v.closePath(),v.setAttr("strokeStyle","red"),v.setAttr("lineWidth",5),v.stroke(),v.restore()),b.releaseCanvas(T._canvas),this._cache.set(et,{scene:f,filter:m,hit:C,x:o,y:l}),this._requestDraw(),this}isCached(){return this._cache.has(et)}getClientRect(e){throw new Error('abstract "getClientRect" method call')}_transformedRect(e,t){const i=[{x:e.x,y:e.y},{x:e.x+e.width,y:e.y},{x:e.x+e.width,y:e.y+e.height},{x:e.x,y:e.y+e.height}];let r=1/0,s=1/0,a=-1/0,o=-1/0;const l=this.getAbsoluteTransform(t);return i.forEach(function(c){const h=l.point(c);r===void 0&&(r=a=h.x,s=o=h.y),r=Math.min(r,h.x),s=Math.min(s,h.y),a=Math.max(a,h.x),o=Math.max(o,h.y)}),{x:r,y:s,width:a-r,height:o-s}}_drawCachedSceneCanvas(e){e.save(),e._applyOpacity(this),e._applyGlobalCompositeOperation(this);const t=this._getCanvasCache();e.translate(t.x,t.y);const i=this._getCachedSceneCanvas(),r=i.pixelRatio;e.drawImage(i._canvas,0,0,i.width/r,i.height/r),e.restore()}_drawCachedHitCanvas(e){const t=this._getCanvasCache(),i=t.hit;e.save(),e.translate(t.x,t.y),e.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),e.restore()}_getCachedSceneCanvas(){let e=this.filters(),t=this._getCanvasCache(),i=t.scene,r=t.filter,s=r.getContext(),a,o,l,c;if(!e||e.length===0)return i;if(this._filterUpToDate)return r;let h=!0;for(let u=0;u<e.length;u++)if(typeof e[u]=="string"&&Ms(),typeof e[u]!="string"||!Ms()){h=!1;break}const d=i.pixelRatio;if(r.setSize(i.width/i.pixelRatio,i.height/i.pixelRatio),h){const u=e.join(" ");return s.save(),s.setAttr("filter",u),s.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),s.restore(),this._filterUpToDate=!0,r}try{for(a=e.length,s.clear(),s.drawImage(i._canvas,0,0,i.getWidth()/d,i.getHeight()/d),o=s.getImageData(0,0,r.getWidth(),r.getHeight()),l=0;l<a;l++)c=e[l],typeof c=="string"&&(c=Cl(c)),c.call(this,o),s.putImageData(o,0,0)}catch(u){b.error("Unable to apply filter. "+u.message+" This post my help you https://konvajs.org/docs/posts/Tainted_Canvas.html.")}return this._filterUpToDate=!0,r}on(e,t){if(this._cache&&this._cache.delete(Ls),arguments.length===3)return this._delegate.apply(this,arguments);const i=e.split(Ni);for(let r=0;r<i.length;r++){const a=i[r].split("."),o=a[0],l=a[1]||"";this.eventListeners[o]||(this.eventListeners[o]=[]),this.eventListeners[o].push({name:l,handler:t})}return this}off(e,t){let i=(e||"").split(Ni),r=i.length,s,a,o,l,c,h;if(this._cache&&this._cache.delete(Ls),!e)for(a in this.eventListeners)this._off(a);for(s=0;s<r;s++)if(o=i[s],l=o.split("."),c=l[0],h=l[1],c)this.eventListeners[c]&&this._off(c,h,t);else for(a in this.eventListeners)this._off(a,h,t);return this}dispatchEvent(e){const t={target:this,type:e.type,evt:e};return this.fire(e.type,t),this}addEventListener(e,t){return this.on(e,function(i){t.call(this,i.evt)}),this}removeEventListener(e){return this.off(e),this}_delegate(e,t,i){const r=this;this.on(e,function(s){const a=s.target.findAncestors(t,!0,r);for(let o=0;o<a.length;o++)s=b.cloneObject(s),s.currentTarget=a[o],i.call(a[o],s)})}remove(){return this.isDragging()&&this.stopDrag(),J._dragElements.delete(this._id),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(Oe),this._clearSelfAndDescendantCache(Gi),this._clearSelfAndDescendantCache(Ds),this._clearSelfAndDescendantCache(Fs),this._clearSelfAndDescendantCache(Br),this._clearSelfAndDescendantCache(Or)}_remove(){this._clearCaches();const e=this.getParent();e&&e.children&&(e.children.splice(this.index,1),e._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(e){const t="get"+b._capitalize(e);return b._isFunction(this[t])?this[t]():this.attrs[e]}getAncestors(){let e=this.getParent(),t=[];for(;e;)t.push(e),e=e.getParent();return t}getAttrs(){return this.attrs||{}}setAttrs(e){return this._batchTransformChanges(()=>{let t,i;if(!e)return this;for(t in e)t!==Tl&&(i=Os+b._capitalize(t),b._isFunction(this[i])?this[i](e[t]):this._setAttr(t,e[t]))}),this}isListening(){return this._getCache(Or,this._isListening)}_isListening(e){if(!this.listening())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isListening(e):!0}isVisible(){return this._getCache(Br,this._isVisible)}_isVisible(e){if(!this.visible())return!1;const i=this.getParent();return i&&i!==e&&this!==e?i._isVisible(e):!0}shouldDrawHit(e,t=!1){if(e)return this._isVisible(e)&&this._isListening(e);const i=this.getLayer();let r=!1;J._dragElements.forEach(a=>{a.dragStatus==="dragging"&&(a.node.nodeType==="Stage"||a.node.getLayer()===i)&&(r=!0)});const s=!t&&!M.hitOnDragEnabled&&(r||M.isTransforming());return this.isListening()&&this.isVisible()&&!s}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let e=this.getDepth(),t=this,i=0,r,s,a,o;function l(h){for(r=[],s=h.length,a=0;a<s;a++)o=h[a],i++,o.nodeType!==Bs&&(r=r.concat(o.getChildren().slice())),o._id===t._id&&(a=s);r.length>0&&r[0].getDepth()<=e&&l(r)}const c=this.getStage();return t.nodeType!==Il&&c&&l(c.getChildren()),i}getDepth(){let e=0,t=this.parent;for(;t;)e++,t=t.parent;return e}_batchTransformChanges(e){this._batchingTransformChange=!0,e(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache($e),this._clearSelfAndDescendantCache(Oe)),this._needClearTransformCache=!1}setPosition(e){return this._batchTransformChanges(()=>{this.x(e.x),this.y(e.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const e=this.getStage();if(!e)return null;const t=e.getPointerPosition();if(!t)return null;const i=this.getAbsoluteTransform().copy();return i.invert(),i.point(t)}getAbsolutePosition(e){let t=!1,i=this.parent;for(;i;){if(i.isCached()){t=!0;break}i=i.parent}t&&!e&&(e=!0);const r=this.getAbsoluteTransform(e).getMatrix(),s=new ve,a=this.offset();return s.m=r.slice(),s.translate(a.x,a.y),s.getTranslation()}setAbsolutePosition(e){const{x:t,y:i,...r}=this._clearTransform();this.attrs.x=t,this.attrs.y=i,this._clearCache($e);const s=this._getAbsoluteTransform().copy();return s.invert(),s.translate(e.x,e.y),e={x:this.attrs.x+s.getTranslation().x,y:this.attrs.y+s.getTranslation().y},this._setTransform(r),this.setPosition({x:e.x,y:e.y}),this._clearCache($e),this._clearSelfAndDescendantCache(Oe),this}_setTransform(e){let t;for(t in e)this.attrs[t]=e[t]}_clearTransform(){const e={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,e}move(e){let t=e.x,i=e.y,r=this.x(),s=this.y();return t!==void 0&&(r+=t),i!==void 0&&(s+=i),this.setPosition({x:r,y:s}),this}_eachAncestorReverse(e,t){let i=[],r=this.getParent(),s,a;if(!(t&&t._id===this._id)){for(i.unshift(this);r&&(!t||r._id!==t._id);)i.unshift(r),r=r.parent;for(s=i.length,a=0;a<s;a++)e(i[a])}}rotate(e){return this.rotation(this.rotation()+e),this}moveToTop(){if(!this.parent)return b.warn("Node has no parent. moveToTop function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.push(this),this.parent._setChildrenIndices(),!0):!1}moveUp(){if(!this.parent)return b.warn("Node has no parent. moveUp function is ignored."),!1;const e=this.index,t=this.parent.getChildren().length;return e<t-1?(this.parent.children.splice(e,1),this.parent.children.splice(e+1,0,this),this.parent._setChildrenIndices(),!0):!1}moveDown(){if(!this.parent)return b.warn("Node has no parent. moveDown function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.splice(e-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return b.warn("Node has no parent. moveToBottom function is ignored."),!1;const e=this.index;return e>0?(this.parent.children.splice(e,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(e){if(!this.parent)return b.warn("Node has no parent. zIndex parameter is ignored."),this;(e<0||e>=this.parent.children.length)&&b.warn("Unexpected value "+e+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const t=this.index;return this.parent.children.splice(t,1),this.parent.children.splice(e,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(Gi,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let e=this.opacity();const t=this.getParent();return t&&!t._isUnderCache&&(e*=t.getAbsoluteOpacity()),e}moveTo(e){return this.getParent()!==e&&(this._remove(),e.add(this)),this}toObject(){let e=this.getAttrs(),t,i,r,s,a;const o={attrs:{},className:this.getClassName()};for(t in e)i=e[t],a=b.isObject(i)&&!b._isPlainObject(i)&&!b._isArray(i),!a&&(r=typeof this[t]=="function"&&this[t],delete e[t],s=r?r.call(this):null,e[t]=i,s!==i&&(o.attrs[t]=i));return b._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(e,t,i){const r=[];t&&this._isMatch(e)&&r.push(this);let s=this.parent;for(;s;){if(s===i)return r;s._isMatch(e)&&r.push(s),s=s.parent}return r}isAncestorOf(e){return!1}findAncestor(e,t,i){return this.findAncestors(e,t,i)[0]}_isMatch(e){if(!e)return!1;if(typeof e=="function")return e(this);let t=e.replace(/ /g,"").split(","),i=t.length,r,s;for(r=0;r<i;r++)if(s=t[r],b.isValidSelector(s)||(b.warn('Selector "'+s+'" is invalid. Allowed selectors examples are "#foo", ".bar" or "Group".'),b.warn('If you have a custom shape with such className, please change it to start with upper letter like "Triangle".'),b.warn("Konva is awesome, right?")),s.charAt(0)==="#"){if(this.id()===s.slice(1))return!0}else if(s.charAt(0)==="."){if(this.hasName(s.slice(1)))return!0}else if(this.className===s||this.nodeType===s)return!0;return!1}getLayer(){const e=this.getParent();return e?e.getLayer():null}getStage(){return this._getCache(Fs,this._getStage)}_getStage(){const e=this.getParent();return e?e.getStage():null}fire(e,t={},i){return t.target=t.target||this,i?this._fireAndBubble(e,t):this._fire(e,t),this}getAbsoluteTransform(e){return e?this._getAbsoluteTransform(e):this._getCache(Oe,this._getAbsoluteTransform)}_getAbsoluteTransform(e){let t;if(e)return t=new ve,this._eachAncestorReverse(function(i){const r=i.transformsEnabled();r==="all"?t.multiply(i.getTransform()):r==="position"&&t.translate(i.x()-i.offsetX(),i.y()-i.offsetY())},e),t;{t=this._cache.get(Oe)||new ve,this.parent?this.parent.getAbsoluteTransform().copyInto(t):t.reset();const i=this.transformsEnabled();if(i==="all")t.multiply(this.getTransform());else if(i==="position"){const r=this.attrs.x||0,s=this.attrs.y||0,a=this.attrs.offsetX||0,o=this.attrs.offsetY||0;t.translate(r-a,s-o)}return t.dirty=!1,t}}getAbsoluteScale(e){let t=this;for(;t;)t._isUnderCache&&(e=t),t=t.getParent();const r=this.getAbsoluteTransform(e).decompose();return{x:r.scaleX,y:r.scaleY}}getAbsoluteRotation(){return this.getAbsoluteTransform().decompose().rotation}getTransform(){return this._getCache($e,this._getTransform)}_getTransform(){var e,t;const i=this._cache.get($e)||new ve;i.reset();const r=this.x(),s=this.y(),a=M.getAngle(this.rotation()),o=(e=this.attrs.scaleX)!==null&&e!==void 0?e:1,l=(t=this.attrs.scaleY)!==null&&t!==void 0?t:1,c=this.attrs.skewX||0,h=this.attrs.skewY||0,d=this.attrs.offsetX||0,u=this.attrs.offsetY||0;return(r!==0||s!==0)&&i.translate(r,s),a!==0&&i.rotate(a),(c!==0||h!==0)&&i.skew(c,h),(o!==1||l!==1)&&i.scale(o,l),(d!==0||u!==0)&&i.translate(-1*d,-1*u),i.dirty=!1,i}clone(e){let t=b.cloneObject(this.attrs),i,r,s,a,o;for(i in e)t[i]=e[i];const l=new this.constructor(t);for(i in this.eventListeners)for(r=this.eventListeners[i],s=r.length,a=0;a<s;a++)o=r[a],o.name.indexOf(bl)<0&&(l.eventListeners[i]||(l.eventListeners[i]=[]),l.eventListeners[i].push(o));return l}_toKonvaCanvas(e){e=e||{};const t=this.getClientRect(),i=this.getStage(),r=e.x!==void 0?e.x:Math.floor(t.x),s=e.y!==void 0?e.y:Math.floor(t.y),a=e.pixelRatio||1,o=new We({width:e.width||Math.ceil(t.width)||(i?i.width():0),height:e.height||Math.ceil(t.height)||(i?i.height():0),pixelRatio:a}),l=o.getContext(),c=new We({width:o.width/o.pixelRatio+Math.abs(r),height:o.height/o.pixelRatio+Math.abs(s),pixelRatio:o.pixelRatio});return e.imageSmoothingEnabled===!1&&(l._context.imageSmoothingEnabled=!1),l.save(),(r||s)&&l.translate(-1*r,-1*s),this.drawScene(o,void 0,c),l.restore(),o}toCanvas(e){return this._toKonvaCanvas(e)._canvas}toDataURL(e){e=e||{};const t=e.mimeType||null,i=e.quality||null,r=this._toKonvaCanvas(e).toDataURL(t,i);return e.callback&&e.callback(r),r}toImage(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,b._urlToImage(this.toDataURL(e),function(s){t(s),r==null||r(s)})}catch(r){i(r)}})}toBlob(e){return new Promise((t,i)=>{try{const r=e==null?void 0:e.callback;r&&delete e.callback,this.toCanvas(e).toBlob(s=>{t(s),r==null||r(s)},e==null?void 0:e.mimeType,e==null?void 0:e.quality)}catch(r){i(r)}})}setSize(e){return this.width(e.width),this.height(e.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():M.dragDistance}_off(e,t,i){let r=this.eventListeners[e],s,a,o;for(s=0;s<r.length;s++)if(a=r[s].name,o=r[s].handler,(a!=="konva"||t==="konva")&&(!t||a===t)&&(!i||i===o)){if(r.splice(s,1),r.length===0){delete this.eventListeners[e];break}s--}}_fireChangeEvent(e,t,i){this._fire(e+vl,{oldVal:t,newVal:i})}addName(e){if(!this.hasName(e)){const t=this.name(),i=t?t+" "+e:e;this.name(i)}return this}hasName(e){if(!e)return!1;const t=this.name();return t?(t||"").split(/\s/g).indexOf(e)!==-1:!1}removeName(e){const t=(this.name()||"").split(/\s/g),i=t.indexOf(e);return i!==-1&&(t.splice(i,1),this.name(t.join(" "))),this}setAttr(e,t){const i=this[Os+b._capitalize(e)];return b._isFunction(i)?i.call(this,t):this._setAttr(e,t),this}_requestDraw(){if(M.autoDrawEnabled){const e=this.getLayer()||this.getStage();e==null||e.batchDraw()}}_setAttr(e,t){const i=this.attrs[e];i===t&&!b.isObject(t)||(t==null?delete this.attrs[e]:this.attrs[e]=t,this._shouldFireChangeEvents&&this._fireChangeEvent(e,i,t),this._requestDraw())}_setComponentAttr(e,t,i){let r;i!==void 0&&(r=this.attrs[e],r||(this.attrs[e]=this.getAttr(e)),this.attrs[e][t]=i,this._fireChangeEvent(e,r,i))}_fireAndBubble(e,t,i){t&&this.nodeType===Bs&&(t.target=this);const r=[kl,wl,xl,Pl,_l,Al];if(!(r.indexOf(e)!==-1&&(i&&(this===i||this.isAncestorOf&&this.isAncestorOf(i))||this.nodeType==="Stage"&&!i))){this._fire(e,t);const a=r.indexOf(e)!==-1&&i&&i.isAncestorOf&&i.isAncestorOf(this)&&!i.isAncestorOf(this.parent);(t&&!t.cancelBubble||!t)&&this.parent&&this.parent.isListening()&&!a&&(i&&i.parent?this._fireAndBubble.call(this.parent,e,t,i):this._fireAndBubble.call(this.parent,e,t))}}_getProtoListeners(e){var t,i;const{nodeType:r}=this,s=I.protoListenerMap.get(r)||{};let a=s==null?void 0:s[e];if(a===void 0){a=[];let o=Object.getPrototypeOf(this);for(;o;){const l=(i=(t=o.eventListeners)===null||t===void 0?void 0:t[e])!==null&&i!==void 0?i:[];a.push(...l),o=Object.getPrototypeOf(o)}s[e]=a,I.protoListenerMap.set(r,s)}return a}_fire(e,t){t=t||{},t.currentTarget=this,t.type=e;const i=this._getProtoListeners(e);if(i)for(let s=0;s<i.length;s++)i[s].handler.call(this,t);const r=this.eventListeners[e];if(r)for(let s=0;s<r.length;s++)r[s].handler.call(this,t)}draw(){return this.drawScene(),this.drawHit(),this}_createDragElement(e){const t=e?e.pointerId:void 0,i=this.getStage(),r=this.getAbsolutePosition();if(!i)return;const s=i._getPointerById(t)||i._changedPointerPositions[0]||r;J._dragElements.set(this._id,{node:this,startPointerPos:s,offset:{x:s.x-r.x,y:s.y-r.y},dragStatus:"ready",pointerId:t})}startDrag(e,t=!0){J._dragElements.has(this._id)||this._createDragElement(e);const i=J._dragElements.get(this._id);i.dragStatus="dragging",this.fire("dragstart",{type:"dragstart",target:this,evt:e&&e.evt},t)}_setDragPosition(e,t){const i=this.getStage()._getPointerById(t.pointerId);if(!i)return;let r={x:i.x-t.offset.x,y:i.y-t.offset.y};const s=this.dragBoundFunc();if(s!==void 0){const a=s.call(this,r,e);a?r=a:b.warn("dragBoundFunc did not return any value. That is unexpected behavior. You must return new absolute position from dragBoundFunc.")}(!this._lastPos||this._lastPos.x!==r.x||this._lastPos.y!==r.y)&&(this.setAbsolutePosition(r),this._requestDraw()),this._lastPos=r}stopDrag(e){const t=J._dragElements.get(this._id);t&&(t.dragStatus="stopped"),J._endDragBefore(e),J._endDragAfter(e)}setDraggable(e){this._setAttr("draggable",e),this._dragChange()}isDragging(){const e=J._dragElements.get(this._id);return e?e.dragStatus==="dragging":!1}_listenDrag(){this._dragCleanup(),this.on("mousedown.konva touchstart.konva",function(e){if(!(!(e.evt.button!==void 0)||M.dragButtons.indexOf(e.evt.button)>=0)||this.isDragging())return;let r=!1;J._dragElements.forEach(s=>{this.isAncestorOf(s.node)&&(r=!0)}),r||this._createDragElement(e)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=J._dragElements.get(this._id),i=t&&t.dragStatus==="dragging",r=t&&t.dragStatus==="ready";i?this.stopDrag():r&&J._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(e={x:0,y:0}){const t=this.getStage();if(!t)return!1;const i={x:-e.x,y:-e.y,width:t.width()+2*e.x,height:t.height()+2*e.y};return b.haveIntersection(i,this.getClientRect())}static create(e,t){return b._isString(e)&&(e=JSON.parse(e)),this._createNode(e,t)}static _createNode(e,t){let i=I.prototype.getClassName.call(e),r=e.children,s,a,o;t&&(e.attrs.container=t),M[i]||(b.warn('Can not find a node with class name "'+i+'". Fallback to "Shape".'),i="Shape");const l=M[i];if(s=new l(e.attrs),r)for(a=r.length,o=0;o<a;o++)s.add(I._createNode(r[o]));return s}}I.protoListenerMap=new Map;I.prototype.nodeType="Node";I.prototype._attrsAffectingSize=[];I.prototype.eventListeners={};I.prototype.on.call(I.prototype,El,function(){if(this._batchingTransformChange){this._needClearTransformCache=!0;return}this._clearCache($e),this._clearSelfAndDescendantCache(Oe)});I.prototype.on.call(I.prototype,"visibleChange.konva",function(){this._clearSelfAndDescendantCache(Br)});I.prototype.on.call(I.prototype,"listeningChange.konva",function(){this._clearSelfAndDescendantCache(Or)});I.prototype.on.call(I.prototype,"opacityChange.konva",function(){this._clearSelfAndDescendantCache(Gi)});const te=y.addGetterSetter;te(I,"zIndex");te(I,"absolutePosition");te(I,"position");te(I,"x",0,E());te(I,"y",0,E());te(I,"globalCompositeOperation","source-over",lt());te(I,"opacity",1,E());te(I,"name","",lt());te(I,"id","",lt());te(I,"rotation",0,E());y.addComponentsGetterSetter(I,"scale",["x","y"]);te(I,"scaleX",1,E());te(I,"scaleY",1,E());y.addComponentsGetterSetter(I,"skew",["x","y"]);te(I,"skewX",0,E());te(I,"skewY",0,E());y.addComponentsGetterSetter(I,"offset",["x","y"]);te(I,"offsetX",0,E());te(I,"offsetY",0,E());te(I,"dragDistance",void 0,E());te(I,"width",0,E());te(I,"height",0,E());te(I,"listening",!0,Ae());te(I,"preventDefault",!0,Ae());te(I,"filters",void 0,function(n){return this._filterUpToDate=!1,n});te(I,"visible",!0,Ae());te(I,"transformsEnabled","all",lt());te(I,"size");te(I,"dragBoundFunc");te(I,"draggable",!1,Ae());y.backCompat(I,{rotateDeg:"rotate",setRotationDeg:"setRotation",getRotationDeg:"getRotation"});class Te extends I{constructor(){super(...arguments),this.children=[]}getChildren(e){const t=this.children||[];return e?t.filter(e):t}hasChildren(){return this.getChildren().length>0}removeChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(e=>{e.parent=null,e.index=0,e.destroy()}),this.children=[],this._requestDraw(),this}add(...e){if(e.length===0)return this;if(e.length>1){for(let i=0;i<e.length;i++)this.add(e[i]);return this}const t=e[0];return t.getParent()?(t.moveTo(this),this):(this._validateAdd(t),t.index=this.getChildren().length,t.parent=this,t._clearCaches(),this.getChildren().push(t),this._fire("add",{child:t}),this._requestDraw(),this)}destroy(){return this.hasChildren()&&this.destroyChildren(),super.destroy(),this}find(e){return this._generalFind(e,!1)}findOne(e){const t=this._generalFind(e,!0);return t.length>0?t[0]:void 0}_generalFind(e,t){const i=[];return this._descendants(r=>{const s=r._isMatch(e);return s&&i.push(r),!!(s&&t)}),i}_descendants(e){let t=!1;const i=this.getChildren();for(const r of i){if(t=e(r),t)return!0;if(r.hasChildren()&&(t=r._descendants(e),t))return!0}return!1}toObject(){const e=I.prototype.toObject.call(this);return e.children=[],this.getChildren().forEach(t=>{e.children.push(t.toObject())}),e}isAncestorOf(e){let t=e.getParent();for(;t;){if(t._id===this._id)return!0;t=t.getParent()}return!1}clone(e){const t=I.prototype.clone.call(this,e);return this.getChildren().forEach(function(i){t.add(i.clone())}),t}getAllIntersections(e){const t=[];return this.find("Shape").forEach(i=>{i.isVisible()&&i.intersects(e)&&t.push(i)}),t}_clearSelfAndDescendantCache(e){var t;super._clearSelfAndDescendantCache(e),!this.isCached()&&((t=this.children)===null||t===void 0||t.forEach(function(i){i._clearSelfAndDescendantCache(e)}))}_setChildrenIndices(){var e;(e=this.children)===null||e===void 0||e.forEach(function(t,i){t.index=i}),this._requestDraw()}drawScene(e,t,i){const r=this.getLayer(),s=e||r&&r.getCanvas(),a=s&&s.getContext(),o=this._getCanvasCache(),l=o&&o.scene,c=s&&s.isCache;if(!this.isVisible()&&!c)return this;if(l){a.save();const h=this.getAbsoluteTransform(t).getMatrix();a.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(a),a.restore()}else this._drawChildren("drawScene",s,t,i);return this}drawHit(e,t){if(!this.shouldDrawHit(t))return this;const i=this.getLayer(),r=e||i&&i.hitCanvas,s=r&&r.getContext(),a=this._getCanvasCache();if(a&&a.hit){s.save();const l=this.getAbsoluteTransform(t).getMatrix();s.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(s),s.restore()}else this._drawChildren("drawHit",r,t);return this}_drawChildren(e,t,i,r){var s;const a=t&&t.getContext(),o=this.clipWidth(),l=this.clipHeight(),c=this.clipFunc(),h=typeof o=="number"&&typeof l=="number"||c,d=i===this;if(h){a.save();const g=this.getAbsoluteTransform(i);let f=g.getMatrix();a.transform(f[0],f[1],f[2],f[3],f[4],f[5]),a.beginPath();let m;if(c)m=c.call(this,a,this);else{const C=this.clipX(),v=this.clipY();a.rect(C||0,v||0,o,l)}a.clip.apply(a,m),f=g.copy().invert().getMatrix(),a.transform(f[0],f[1],f[2],f[3],f[4],f[5])}const u=!d&&this.globalCompositeOperation()!=="source-over"&&e==="drawScene";u&&(a.save(),a._applyGlobalCompositeOperation(this)),(s=this.children)===null||s===void 0||s.forEach(function(g){g[e](t,i,r)}),u&&a.restore(),h&&a.restore()}getClientRect(e={}){var t;const i=e.skipTransform,r=e.relativeTo;let s,a,o,l,c={x:1/0,y:1/0,width:0,height:0};const h=this;(t=this.children)===null||t===void 0||t.forEach(function(g){if(!g.visible())return;const f=g.getClientRect({relativeTo:h,skipShadow:e.skipShadow,skipStroke:e.skipStroke});f.width===0&&f.height===0||(s===void 0?(s=f.x,a=f.y,o=f.x+f.width,l=f.y+f.height):(s=Math.min(s,f.x),a=Math.min(a,f.y),o=Math.max(o,f.x+f.width),l=Math.max(l,f.y+f.height)))});const d=this.find("Shape");let u=!1;for(let g=0;g<d.length;g++)if(d[g]._isVisible(this)){u=!0;break}return u&&s!==void 0?c={x:s,y:a,width:o-s,height:l-a}:c={x:0,y:0,width:0,height:0},i?c:this._transformedRect(c,r)}}y.addComponentsGetterSetter(Te,"clip",["x","y","width","height"]);y.addGetterSetter(Te,"clipX",void 0,E());y.addGetterSetter(Te,"clipY",void 0,E());y.addGetterSetter(Te,"clipWidth",void 0,E());y.addGetterSetter(Te,"clipHeight",void 0,E());y.addGetterSetter(Te,"clipFunc");const di=new Map,ga=M._global.PointerEvent!==void 0;function fr(n){return di.get(n)}function gs(n){return{evt:n,pointerId:n.pointerId}}function fa(n,e){return di.get(n)===e}function ma(n,e){Jt(n),e.getStage()&&(di.set(n,e),ga&&e._fire("gotpointercapture",gs(new PointerEvent("gotpointercapture"))))}function Jt(n,e){const t=di.get(n);if(!t)return;const i=t.getStage();i&&i.content,di.delete(n),ga&&t._fire("lostpointercapture",gs(new PointerEvent("lostpointercapture")))}const Ml="Stage",Ll="string",Hs="px",Dl="mouseout",ya="mouseleave",Sa="mouseover",Ca="mouseenter",va="mousemove",Ta="mousedown",ba="mouseup",$t="pointermove",Vt="pointerdown",vt="pointerup",Ut="pointercancel",Ol="lostpointercapture",Pi="pointerout",Wt="pointerleave",_i="pointerover",Ai="pointerenter",Fr="contextmenu",ka="touchstart",wa="touchend",xa="touchmove",Pa="touchcancel",Hr="wheel",Bl=5,Fl=[[Ca,"_pointerenter"],[Ta,"_pointerdown"],[va,"_pointermove"],[ba,"_pointerup"],[ya,"_pointerleave"],[ka,"_pointerdown"],[xa,"_pointermove"],[wa,"_pointerup"],[Pa,"_pointercancel"],[Sa,"_pointerover"],[Hr,"_wheel"],[Fr,"_contextmenu"],[Vt,"_pointerdown"],[$t,"_pointermove"],[vt,"_pointerup"],[Ut,"_pointercancel"],[Wt,"_pointerleave"],[Ol,"_lostpointercapture"]],mr={mouse:{[Pi]:Dl,[Wt]:ya,[_i]:Sa,[Ai]:Ca,[$t]:va,[Vt]:Ta,[vt]:ba,[Ut]:"mousecancel",pointerclick:"click",pointerdblclick:"dblclick"},touch:{[Pi]:"touchout",[Wt]:"touchleave",[_i]:"touchover",[Ai]:"touchenter",[$t]:xa,[Vt]:ka,[vt]:wa,[Ut]:Pa,pointerclick:"tap",pointerdblclick:"dbltap"},pointer:{[Pi]:Pi,[Wt]:Wt,[_i]:_i,[Ai]:Ai,[$t]:$t,[Vt]:Vt,[vt]:vt,[Ut]:Ut,pointerclick:"pointerclick",pointerdblclick:"pointerdblclick"}},Yt=n=>n.indexOf("pointer")>=0?"pointer":n.indexOf("touch")>=0?"touch":"mouse",pt=n=>{const e=Yt(n);if(e==="pointer")return M.pointerEventsEnabled&&mr.pointer;if(e==="touch")return mr.touch;if(e==="mouse")return mr.mouse};function Gs(n={}){return(n.clipFunc||n.clipWidth||n.clipHeight)&&b.warn("Stage does not support clipping. Please use clip for Layers or Groups."),n}const Hl="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",Qt=[];class cr extends Te{constructor(e){super(Gs(e)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),Qt.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{Gs(this.attrs)}),this._checkVisibility()}_validateAdd(e){const t=e.getType()==="Layer",i=e.getType()==="FastLayer";t||i||b.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const e=this.visible()?"":"none";this.content.style.display=e}setContainer(e){if(typeof e===Ll){let t;if(e.charAt(0)==="."){const i=e.slice(1);e=document.getElementsByClassName(i)[0]}else e.charAt(0)!=="#"?t=e:t=e.slice(1),e=document.getElementById(t);if(!e)throw"Can not find container in document with id "+t}return this._setAttr("container",e),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),e.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const e=this.children,t=e.length;for(let i=0;i<t;i++)e[i].clear();return this}clone(e){return e||(e={}),e.container=typeof document<"u"&&document.createElement("div"),Te.prototype.clone.call(this,e)}destroy(){super.destroy();const e=this.content;e&&b._isInDocument(e)&&this.container().removeChild(e);const t=Qt.indexOf(this);return t>-1&&Qt.splice(t,1),b.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const e=this._pointerPositions[0]||this._changedPointerPositions[0];return e?{x:e.x,y:e.y}:(b.warn(Hl),null)}_getPointerById(e){return this._pointerPositions.find(t=>t.id===e)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(e){e={...e},e.x=e.x||0,e.y=e.y||0,e.width=e.width||this.width(),e.height=e.height||this.height();const t=new We({width:e.width,height:e.height,pixelRatio:e.pixelRatio||1}),i=t.getContext()._context,r=this.children;return(e.x||e.y)&&i.translate(-1*e.x,-1*e.y),r.forEach(function(s){if(!s.isVisible())return;const a=s._toKonvaCanvas(e);i.drawImage(a._canvas,e.x,e.y,a.getWidth()/a.getPixelRatio(),a.getHeight()/a.getPixelRatio())}),t}getIntersection(e){if(!e)return null;const t=this.children,i=t.length,r=i-1;for(let s=r;s>=0;s--){const a=t[s].getIntersection(e);if(a)return a}return null}_resizeDOM(){const e=this.width(),t=this.height();this.content&&(this.content.style.width=e+Hs,this.content.style.height=t+Hs),this.bufferCanvas.setSize(e,t),this.bufferHitCanvas.setSize(e,t),this.children.forEach(i=>{i.setSize({width:e,height:t}),i.draw()})}add(e,...t){if(arguments.length>1){for(let r=0;r<arguments.length;r++)this.add(arguments[r]);return this}super.add(e);const i=this.children.length;return i>Bl&&b.warn("The stage has "+i+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),e.setSize({width:this.width(),height:this.height()}),e.draw(),M.isBrowser&&this.content.appendChild(e.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(e){return fa(e,this)}setPointerCapture(e){ma(e,this)}releaseCapture(e){Jt(e)}getLayers(){return this.children}_bindContentEvents(){M.isBrowser&&Fl.forEach(([e,t])=>{this.content.addEventListener(e,i=>{this[t](i)},{passive:!1})})}_pointerenter(e){this.setPointersPositions(e);const t=pt(e.type);t&&this._fire(t.pointerenter,{evt:e,target:this,currentTarget:this})}_pointerover(e){this.setPointersPositions(e);const t=pt(e.type);t&&this._fire(t.pointerover,{evt:e,target:this,currentTarget:this})}_getTargetShape(e){let t=this[e+"targetShape"];return t&&!t.getStage()&&(t=null),t}_pointerleave(e){const t=pt(e.type),i=Yt(e.type);if(!t)return;this.setPointersPositions(e);const r=this._getTargetShape(i),s=!(M.isDragging()||M.isTransforming())||M.hitOnDragEnabled;r&&s?(r._fireAndBubble(t.pointerout,{evt:e}),r._fireAndBubble(t.pointerleave,{evt:e}),this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this[i+"targetShape"]=null):s&&(this._fire(t.pointerleave,{evt:e,target:this,currentTarget:this}),this._fire(t.pointerout,{evt:e,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(e){const t=pt(e.type),i=Yt(e.type);if(!t)return;this.setPointersPositions(e);let r=!1;this._changedPointerPositions.forEach(s=>{const a=this.getIntersection(s);if(J.justDragged=!1,M["_"+i+"ListenClick"]=!0,!a||!a.isListening()){this[i+"ClickStartShape"]=void 0;return}M.capturePointerEventsEnabled&&a.setPointerCapture(s.id),this[i+"ClickStartShape"]=a,a._fireAndBubble(t.pointerdown,{evt:e,pointerId:s.id}),r=!0;const o=e.type.indexOf("touch")>=0;a.preventDefault()&&e.cancelable&&o&&e.preventDefault()}),r||this._fire(t.pointerdown,{evt:e,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(e){const t=pt(e.type),i=Yt(e.type);if(!t)return;const r=e.type.indexOf("touch")>=0||e.pointerType==="touch";if(M.isDragging()&&J.node.preventDefault()&&e.cancelable&&r&&e.preventDefault(),this.setPointersPositions(e),!(!(M.isDragging()||M.isTransforming())||M.hitOnDragEnabled))return;const a={};let o=!1;const l=this._getTargetShape(i);this._changedPointerPositions.forEach(c=>{const h=fr(c.id)||this.getIntersection(c),d=c.id,u={evt:e,pointerId:d},g=l!==h;if(g&&l&&(l._fireAndBubble(t.pointerout,{...u},h),l._fireAndBubble(t.pointerleave,{...u},h)),h){if(a[h._id])return;a[h._id]=!0}h&&h.isListening()?(o=!0,g&&(h._fireAndBubble(t.pointerover,{...u},l),h._fireAndBubble(t.pointerenter,{...u},l),this[i+"targetShape"]=h),h._fireAndBubble(t.pointermove,{...u})):l&&(this._fire(t.pointerover,{evt:e,target:this,currentTarget:this,pointerId:d}),this[i+"targetShape"]=null)}),o||this._fire(t.pointermove,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(e){const t=pt(e.type),i=Yt(e.type);if(!t)return;this.setPointersPositions(e);const r=this[i+"ClickStartShape"],s=this[i+"ClickEndShape"],a={};let o=!1;this._changedPointerPositions.forEach(l=>{const c=fr(l.id)||this.getIntersection(l);if(c){if(c.releaseCapture(l.id),a[c._id])return;a[c._id]=!0}const h=l.id,d={evt:e,pointerId:h};let u=!1;M["_"+i+"InDblClickWindow"]?(u=!0,clearTimeout(this[i+"DblTimeout"])):J.justDragged||(M["_"+i+"InDblClickWindow"]=!0,clearTimeout(this[i+"DblTimeout"])),this[i+"DblTimeout"]=setTimeout(function(){M["_"+i+"InDblClickWindow"]=!1},M.dblClickWindow),c&&c.isListening()?(o=!0,this[i+"ClickEndShape"]=c,c._fireAndBubble(t.pointerup,{...d}),M["_"+i+"ListenClick"]&&r&&r===c&&(c._fireAndBubble(t.pointerclick,{...d}),u&&s&&s===c&&c._fireAndBubble(t.pointerdblclick,{...d}))):(this[i+"ClickEndShape"]=null,o||(this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),M["_"+i+"ListenClick"]&&this._fire(t.pointerclick,{evt:e,target:this,currentTarget:this,pointerId:h}),u&&this._fire(t.pointerdblclick,{evt:e,target:this,currentTarget:this,pointerId:h}))}),o||this._fire(t.pointerup,{evt:e,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),M["_"+i+"ListenClick"]=!1,e.cancelable&&i!=="touch"&&i!=="pointer"&&e.preventDefault()}_contextmenu(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Fr,{evt:e}):this._fire(Fr,{evt:e,target:this,currentTarget:this})}_wheel(e){this.setPointersPositions(e);const t=this.getIntersection(this.getPointerPosition());t&&t.isListening()?t._fireAndBubble(Hr,{evt:e}):this._fire(Hr,{evt:e,target:this,currentTarget:this})}_pointercancel(e){this.setPointersPositions(e);const t=fr(e.pointerId)||this.getIntersection(this.getPointerPosition());t&&t._fireAndBubble(vt,gs(e)),Jt(e.pointerId)}_lostpointercapture(e){Jt(e.pointerId)}setPointersPositions(e){const t=this._getContentPosition();let i=null,r=null;e=e||window.event,e.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(e.touches,s=>{this._pointerPositions.push({id:s.identifier,x:(s.clientX-t.left)/t.scaleX,y:(s.clientY-t.top)/t.scaleY})}),Array.prototype.forEach.call(e.changedTouches||e.touches,s=>{this._changedPointerPositions.push({id:s.identifier,x:(s.clientX-t.left)/t.scaleX,y:(s.clientY-t.top)/t.scaleY})})):(i=(e.clientX-t.left)/t.scaleX,r=(e.clientY-t.top)/t.scaleY,this.pointerPos={x:i,y:r},this._pointerPositions=[{x:i,y:r,id:b._getFirstPointerId(e)}],this._changedPointerPositions=[{x:i,y:r,id:b._getFirstPointerId(e)}])}_setPointerPosition(e){b.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(e)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const e=this.content.getBoundingClientRect();return{top:e.top,left:e.left,scaleX:e.width/this.content.clientWidth||1,scaleY:e.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new We({width:this.width(),height:this.height()}),this.bufferHitCanvas=new us({pixelRatio:1,width:this.width(),height:this.height()}),!M.isBrowser)return;const e=this.container();if(!e)throw"Stage has no container. A container is required.";e.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),e.appendChild(this.content),this._resizeDOM()}cache(){return b.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(e){e.batchDraw()}),this}}cr.prototype.nodeType=Ml;ae(cr);y.addGetterSetter(cr,"container");M.isBrowser&&document.addEventListener("visibilitychange",()=>{Qt.forEach(n=>{n.batchDraw()})});const _a="hasShadow",Aa="shadowRGBA",Ia="patternImage",Ea="linearGradient",Ra="radialGradient";let Ii;function yr(){return Ii||(Ii=b.createCanvasElement().getContext("2d"),Ii)}const ei={};function Gl(n){const e=this.attrs.fillRule;e?n.fill(e):n.fill()}function Nl(n){n.stroke()}function zl(n){const e=this.attrs.fillRule;e?n.fill(e):n.fill()}function $l(n){n.stroke()}function Vl(){this._clearCache(_a)}function Ul(){this._clearCache(Aa)}function Wl(){this._clearCache(Ia)}function Yl(){this._clearCache(Ea)}function Xl(){this._clearCache(Ra)}class A extends I{constructor(e){super(e);let t,i=0;for(;t=b.getHitColor(),!(t&&!(t in ei));)if(i++,i>=1e4){b.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),t=b.getRandomColor();break}this.colorKey=t,ei[t]=this}getContext(){return b.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return b.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(_a,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(Ia,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=yr().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const i=new ve;i.translate(this.fillPatternX(),this.fillPatternY()),i.rotate(M.getAngle(this.fillPatternRotation())),i.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),i.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const r=i.getMatrix(),s=typeof DOMMatrix>"u"?{a:r[0],b:r[1],c:r[2],d:r[3],e:r[4],f:r[5]}:new DOMMatrix(r);t.setTransform(s)}return t}}_getLinearGradient(){return this._getCache(Ea,this.__getLinearGradient)}__getLinearGradient(){const e=this.fillLinearGradientColorStops();if(e){const t=yr(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),s=t.createLinearGradient(i.x,i.y,r.x,r.y);for(let a=0;a<e.length;a+=2)s.addColorStop(e[a],e[a+1]);return s}}_getRadialGradient(){return this._getCache(Ra,this.__getRadialGradient)}__getRadialGradient(){const e=this.fillRadialGradientColorStops();if(e){const t=yr(),i=this.fillRadialGradientStartPoint(),r=this.fillRadialGradientEndPoint(),s=t.createRadialGradient(i.x,i.y,this.fillRadialGradientStartRadius(),r.x,r.y,this.fillRadialGradientEndRadius());for(let a=0;a<e.length;a+=2)s.addColorStop(e[a],e[a+1]);return s}}getShadowRGBA(){return this._getCache(Aa,this._getShadowRGBA)}_getShadowRGBA(){if(!this.hasShadow())return;const e=b.colorToRGBA(this.shadowColor());if(e)return"rgba("+e.r+","+e.g+","+e.b+","+e.a*(this.shadowOpacity()||1)+")"}hasFill(){return this._calculate("hasFill",["fillEnabled","fill","fillPatternImage","fillLinearGradientColorStops","fillRadialGradientColorStops"],()=>this.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const e=this.hitStrokeWidth();return e==="auto"?this.hasStroke():this.strokeEnabled()&&!!e}intersects(e){const t=this.getStage();if(!t)return!1;const i=t.bufferHitCanvas;return i.getContext().clear(),this.drawHit(i,void 0,!0),i.context.getImageData(Math.round(e.x),Math.round(e.y),1,1).data[3]>0}destroy(){return I.prototype.destroy.call(this),delete ei[this.colorKey],delete this.colorKey,this}_useBufferCanvas(e){var t;if(!((t=this.attrs.perfectDrawEnabled)!==null&&t!==void 0?t:!0))return!1;const r=e||this.hasFill(),s=this.hasStroke(),a=this.getAbsoluteOpacity()!==1;if(r&&s&&a)return!0;const o=this.hasShadow(),l=this.shadowForStrokeEnabled();return!!(r&&s&&o&&l)}setStrokeHitEnabled(e){b.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),e?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const e=this.size();return{x:this._centroid?-e.width/2:0,y:this._centroid?-e.height/2:0,width:e.width,height:e.height}}getClientRect(e={}){let t=!1,i=this.getParent();for(;i;){if(i.isCached()){t=!0;break}i=i.getParent()}const r=e.skipTransform,s=e.relativeTo||t&&this.getStage()||void 0,a=this.getSelfRect(),l=!e.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,c=a.width+l,h=a.height+l,d=!e.skipShadow&&this.hasShadow(),u=d?this.shadowOffsetX():0,g=d?this.shadowOffsetY():0,f=c+Math.abs(u),m=h+Math.abs(g),C=d&&this.shadowBlur()||0,v=f+C*2,S=m+C*2,T={width:v,height:S,x:-(l/2+C)+Math.min(u,0)+a.x,y:-(l/2+C)+Math.min(g,0)+a.y};return r?T:this._transformedRect(T,s)}drawScene(e,t,i){const r=this.getLayer(),s=e||r.getCanvas(),a=s.getContext(),o=this._getCanvasCache(),l=this.getSceneFunc(),c=this.hasShadow();let h;const d=t===this;if(!this.isVisible()&&!d)return this;if(o){a.save();const u=this.getAbsoluteTransform(t).getMatrix();return a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(a),a.restore(),this}if(!l)return this;if(a.save(),this._useBufferCanvas()){h=this.getStage();const u=i||h.bufferCanvas,g=u.getContext();i?(g.save(),g.setTransform(1,0,0,1,0,0),g.clearRect(0,0,u.width,u.height),g.restore()):g.clear(),g.save(),g._applyLineJoin(this),g._applyMiterLimit(this);const f=this.getAbsoluteTransform(t).getMatrix();g.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l.call(this,g,this),g.restore();const m=u.pixelRatio;c&&a._applyShadow(this),d||(a._applyOpacity(this),a._applyGlobalCompositeOperation(this)),a.drawImage(u._canvas,u.x||0,u.y||0,u.width/m,u.height/m)}else{if(a._applyLineJoin(this),a._applyMiterLimit(this),!d){const u=this.getAbsoluteTransform(t).getMatrix();a.transform(u[0],u[1],u[2],u[3],u[4],u[5]),a._applyOpacity(this),a._applyGlobalCompositeOperation(this)}c&&a._applyShadow(this),l.call(this,a,this)}return a.restore(),this}drawHit(e,t,i=!1){if(!this.shouldDrawHit(t,i))return this;const r=this.getLayer(),s=e||r.hitCanvas,a=s&&s.getContext(),o=this.hitFunc()||this.sceneFunc(),l=this._getCanvasCache(),c=l&&l.hit;if(this.colorKey||b.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),c){a.save();const d=this.getAbsoluteTransform(t).getMatrix();return a.transform(d[0],d[1],d[2],d[3],d[4],d[5]),this._drawCachedHitCanvas(a),a.restore(),this}if(!o)return this;if(a.save(),a._applyLineJoin(this),a._applyMiterLimit(this),!(this===t)){const d=this.getAbsoluteTransform(t).getMatrix();a.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return o.call(this,a,this),a.restore(),this}drawHitFromCache(e=0){const t=this._getCanvasCache(),i=this._getCachedSceneCanvas(),r=t.hit,s=r.getContext(),a=r.getWidth(),o=r.getHeight();s.clear(),s.drawImage(i._canvas,0,0,a,o);try{const l=s.getImageData(0,0,a,o),c=l.data,h=c.length,d=b._hexToRgb(this.colorKey);for(let u=0;u<h;u+=4)c[u+3]>e?(c[u]=d.r,c[u+1]=d.g,c[u+2]=d.b,c[u+3]=255):c[u+3]=0;s.putImageData(l,0,0)}catch(l){b.error("Unable to draw hit graph from cached scene canvas. "+l.message)}return this}hasPointerCapture(e){return fa(e,this)}setPointerCapture(e){ma(e,this)}releaseCapture(e){Jt(e)}}A.prototype._fillFunc=Gl;A.prototype._strokeFunc=Nl;A.prototype._fillFuncHit=zl;A.prototype._strokeFuncHit=$l;A.prototype._centroid=!1;A.prototype.nodeType="Shape";ae(A);A.prototype.eventListeners={};A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Vl);A.prototype.on.call(A.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Ul);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Wl);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Yl);A.prototype.on.call(A.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Xl);y.addGetterSetter(A,"stroke",void 0,pa());y.addGetterSetter(A,"strokeWidth",2,E());y.addGetterSetter(A,"fillAfterStrokeEnabled",!1);y.addGetterSetter(A,"hitStrokeWidth","auto",ps());y.addGetterSetter(A,"strokeHitEnabled",!0,Ae());y.addGetterSetter(A,"perfectDrawEnabled",!0,Ae());y.addGetterSetter(A,"shadowForStrokeEnabled",!0,Ae());y.addGetterSetter(A,"lineJoin");y.addGetterSetter(A,"lineCap");y.addGetterSetter(A,"miterLimit");y.addGetterSetter(A,"sceneFunc");y.addGetterSetter(A,"hitFunc");y.addGetterSetter(A,"dash");y.addGetterSetter(A,"dashOffset",0,E());y.addGetterSetter(A,"shadowColor",void 0,lt());y.addGetterSetter(A,"shadowBlur",0,E());y.addGetterSetter(A,"shadowOpacity",1,E());y.addComponentsGetterSetter(A,"shadowOffset",["x","y"]);y.addGetterSetter(A,"shadowOffsetX",0,E());y.addGetterSetter(A,"shadowOffsetY",0,E());y.addGetterSetter(A,"fillPatternImage");y.addGetterSetter(A,"fill",void 0,pa());y.addGetterSetter(A,"fillPatternX",0,E());y.addGetterSetter(A,"fillPatternY",0,E());y.addGetterSetter(A,"fillLinearGradientColorStops");y.addGetterSetter(A,"strokeLinearGradientColorStops");y.addGetterSetter(A,"fillRadialGradientStartRadius",0);y.addGetterSetter(A,"fillRadialGradientEndRadius",0);y.addGetterSetter(A,"fillRadialGradientColorStops");y.addGetterSetter(A,"fillPatternRepeat","repeat");y.addGetterSetter(A,"fillEnabled",!0);y.addGetterSetter(A,"strokeEnabled",!0);y.addGetterSetter(A,"shadowEnabled",!0);y.addGetterSetter(A,"dashEnabled",!0);y.addGetterSetter(A,"strokeScaleEnabled",!0);y.addGetterSetter(A,"fillPriority","color");y.addComponentsGetterSetter(A,"fillPatternOffset",["x","y"]);y.addGetterSetter(A,"fillPatternOffsetX",0,E());y.addGetterSetter(A,"fillPatternOffsetY",0,E());y.addComponentsGetterSetter(A,"fillPatternScale",["x","y"]);y.addGetterSetter(A,"fillPatternScaleX",1,E());y.addGetterSetter(A,"fillPatternScaleY",1,E());y.addComponentsGetterSetter(A,"fillLinearGradientStartPoint",["x","y"]);y.addComponentsGetterSetter(A,"strokeLinearGradientStartPoint",["x","y"]);y.addGetterSetter(A,"fillLinearGradientStartPointX",0);y.addGetterSetter(A,"strokeLinearGradientStartPointX",0);y.addGetterSetter(A,"fillLinearGradientStartPointY",0);y.addGetterSetter(A,"strokeLinearGradientStartPointY",0);y.addComponentsGetterSetter(A,"fillLinearGradientEndPoint",["x","y"]);y.addComponentsGetterSetter(A,"strokeLinearGradientEndPoint",["x","y"]);y.addGetterSetter(A,"fillLinearGradientEndPointX",0);y.addGetterSetter(A,"strokeLinearGradientEndPointX",0);y.addGetterSetter(A,"fillLinearGradientEndPointY",0);y.addGetterSetter(A,"strokeLinearGradientEndPointY",0);y.addComponentsGetterSetter(A,"fillRadialGradientStartPoint",["x","y"]);y.addGetterSetter(A,"fillRadialGradientStartPointX",0);y.addGetterSetter(A,"fillRadialGradientStartPointY",0);y.addComponentsGetterSetter(A,"fillRadialGradientEndPoint",["x","y"]);y.addGetterSetter(A,"fillRadialGradientEndPointX",0);y.addGetterSetter(A,"fillRadialGradientEndPointY",0);y.addGetterSetter(A,"fillPatternRotation",0);y.addGetterSetter(A,"fillRule",void 0,lt());y.backCompat(A,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const jl="beforeDraw",ql="draw",Ma=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Kl=Ma.length;class ct extends Te{constructor(e){super(e),this.canvas=new We,this.hitCanvas=new us({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(e){return this.getContext().clear(e),this.getHitCanvas().getContext().clear(e),this}setZIndex(e){super.setZIndex(e);const t=this.getStage();return t&&t.content&&(t.content.removeChild(this.getNativeCanvasElement()),e<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[e+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement())),this}moveToTop(){I.prototype.moveToTop.call(this);const e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.appendChild(this.getNativeCanvasElement())),!0}moveUp(){if(!I.prototype.moveUp.call(this))return!1;const t=this.getStage();return!t||!t.content?!1:(t.content.removeChild(this.getNativeCanvasElement()),this.index<t.children.length-1?t.content.insertBefore(this.getNativeCanvasElement(),t.children[this.index+1].getCanvas()._canvas):t.content.appendChild(this.getNativeCanvasElement()),!0)}moveDown(){if(I.prototype.moveDown.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[this.index+1].getCanvas()._canvas))}return!0}return!1}moveToBottom(){if(I.prototype.moveToBottom.call(this)){const e=this.getStage();if(e){const t=e.children;e.content&&(e.content.removeChild(this.getNativeCanvasElement()),e.content.insertBefore(this.getNativeCanvasElement(),t[1].getCanvas()._canvas))}return!0}return!1}getLayer(){return this}remove(){const e=this.getNativeCanvasElement();return I.prototype.remove.call(this),e&&e.parentNode&&b._isInDocument(e)&&e.parentNode.removeChild(e),this}getStage(){return this.parent}setSize({width:e,height:t}){return this.canvas.setSize(e,t),this.hitCanvas.setSize(e,t),this._setSmoothEnabled(),this}_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to a layer.")}_toKonvaCanvas(e){return e={...e},e.width=e.width||this.getWidth(),e.height=e.height||this.getHeight(),e.x=e.x!==void 0?e.x:this.x(),e.y=e.y!==void 0?e.y:this.y(),I.prototype._toKonvaCanvas.call(this,e)}_checkVisibility(){this.visible()?this.canvas._canvas.style.display="block":this.canvas._canvas.style.display="none"}_setSmoothEnabled(){this.getContext()._context.imageSmoothingEnabled=this.imageSmoothingEnabled()}getWidth(){if(this.parent)return this.parent.width()}setWidth(){b.warn('Can not change width of layer. Use "stage.width(value)" function instead.')}getHeight(){if(this.parent)return this.parent.height()}setHeight(){b.warn('Can not change height of layer. Use "stage.height(value)" function instead.')}batchDraw(){return this._waitingForDraw||(this._waitingForDraw=!0,b.requestAnimFrame(()=>{this.draw(),this._waitingForDraw=!1})),this}getIntersection(e){if(!this.isListening()||!this.isVisible())return null;let t=1,i=!1;for(;;){for(let r=0;r<Kl;r++){const s=Ma[r],a=this._getIntersection({x:e.x+s.x*t,y:e.y+s.y*t}),o=a.shape;if(o)return o;if(i=!!a.antialiased,!a.antialiased)break}if(i)t+=1;else return null}}_getIntersection(e){const t=this.hitCanvas.pixelRatio,i=this.hitCanvas.context.getImageData(Math.round(e.x*t),Math.round(e.y*t),1,1).data,r=i[3];if(r===255){const s=b.getHitColorKey(i[0],i[1],i[2]),a=ei[s];return a?{shape:a}:{antialiased:!0}}else if(r>0)return{antialiased:!0};return{}}drawScene(e,t,i){const r=this.getLayer(),s=e||r&&r.getCanvas();return this._fire(jl,{node:this}),this.clearBeforeDraw()&&s.getContext().clear(),Te.prototype.drawScene.call(this,s,t,i),this._fire(ql,{node:this}),this}drawHit(e,t){const i=this.getLayer(),r=e||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),Te.prototype.drawHit.call(this,r,t),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(e){b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(e)}getHitGraphEnabled(e){return b.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const e=this.parent;!!this.hitCanvas._canvas.parentNode?e.content.removeChild(this.hitCanvas._canvas):e.content.appendChild(this.hitCanvas._canvas)}destroy(){return b.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}}ct.prototype.nodeType="Layer";ae(ct);y.addGetterSetter(ct,"imageSmoothingEnabled",!0);y.addGetterSetter(ct,"clearBeforeDraw",!0);y.addGetterSetter(ct,"hitGraphEnabled",!0,Ae());class fs extends ct{constructor(e){super(e),this.listening(!1),b.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}fs.prototype.nodeType="FastLayer";ae(fs);class wt extends Te{_validateAdd(e){const t=e.getType();t!=="Group"&&t!=="Shape"&&b.throw("You may only add groups and shapes to groups.")}}wt.prototype.nodeType="Group";ae(wt);const Sr=function(){return it.performance&&it.performance.now?function(){return it.performance.now()}:function(){return new Date().getTime()}}();class we{constructor(e,t){this.id=we.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:Sr(),frameRate:0},this.func=e,this.setLayers(t)}setLayers(e){let t=[];return e&&(t=Array.isArray(e)?e:[e]),this.layers=t,this}getLayers(){return this.layers}addLayer(e){const t=this.layers,i=t.length;for(let r=0;r<i;r++)if(t[r]._id===e._id)return!1;return this.layers.push(e),!0}isRunning(){const t=we.animations,i=t.length;for(let r=0;r<i;r++)if(t[r].id===this.id)return!0;return!1}start(){return this.stop(),this.frame.timeDiff=0,this.frame.lastTime=Sr(),we._addAnimation(this),this}stop(){return we._removeAnimation(this),this}_updateFrameObject(e){this.frame.timeDiff=e-this.frame.lastTime,this.frame.lastTime=e,this.frame.time+=this.frame.timeDiff,this.frame.frameRate=1e3/this.frame.timeDiff}static _addAnimation(e){this.animations.push(e),this._handleAnimation()}static _removeAnimation(e){const t=e.id,i=this.animations,r=i.length;for(let s=0;s<r;s++)if(i[s].id===t){this.animations.splice(s,1);break}}static _runFrames(){const e={},t=this.animations;for(let i=0;i<t.length;i++){const r=t[i],s=r.layers,a=r.func;r._updateFrameObject(Sr());const o=s.length;let l;if(a?l=a.call(r,r.frame)!==!1:l=!0,!!l)for(let c=0;c<o;c++){const h=s[c];h._id!==void 0&&(e[h._id]=h)}}for(const i in e)e.hasOwnProperty(i)&&e[i].batchDraw()}static _animationLoop(){const e=we;e.animations.length?(e._runFrames(),b.requestAnimFrame(e._animationLoop)):e.animRunning=!1}static _handleAnimation(){this.animRunning||(this.animRunning=!0,b.requestAnimFrame(this._animationLoop))}}we.animations=[];we.animIdCounter=0;we.animRunning=!1;const Zl={node:1,duration:1,easing:1,onFinish:1,yoyo:1},Jl=1,Ns=2,zs=3,$s=["fill","stroke","shadowColor"];let Ql=0;class ec{constructor(e,t,i,r,s,a,o){this.prop=e,this.propFunc=t,this.begin=r,this._pos=r,this.duration=a,this._change=0,this.prevPos=0,this.yoyo=o,this._time=0,this._position=0,this._startTime=0,this._finish=0,this.func=i,this._change=s-this.begin,this.pause()}fire(e){const t=this[e];t&&t()}setTime(e){e>this.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():e<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=e,this.update())}getTime(){return this._time}setPosition(e){this.prevPos=this._pos,this.propFunc(e),this._pos=e}getPosition(e){return e===void 0&&(e=this._time),this.func(e,this.begin,this._change,this.duration)}play(){this.state=Ns,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=zs,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(e){this.pause(),this._time=e,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const e=this.getTimer()-this._startTime;this.state===Ns?this.setTime(e):this.state===zs&&this.setTime(this.duration-e)}pause(){this.state=Jl,this.fire("onPause")}getTimer(){return new Date().getTime()}}class ie{constructor(e){const t=this,i=e.node,r=i._id,s=e.easing||ti.Linear,a=!!e.yoyo;let o,l;typeof e.duration>"u"?o=.3:e.duration===0?o=.001:o=e.duration,this.node=i,this._id=Ql++;const c=i.getLayer()||(i instanceof M.Stage?i.getLayers():null);c||b.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new we(function(){t.tween.onEnterFrame()},c),this.tween=new ec(l,function(h){t._tweenFunc(h)},s,0,1,o*1e3,a),this._addListeners(),ie.attrs[r]||(ie.attrs[r]={}),ie.attrs[r][this._id]||(ie.attrs[r][this._id]={}),ie.tweens[r]||(ie.tweens[r]={});for(l in e)Zl[l]===void 0&&this._addAttr(l,e[l]);this.reset(),this.onFinish=e.onFinish,this.onReset=e.onReset,this.onUpdate=e.onUpdate}_addAttr(e,t){const i=this.node,r=i._id;let s,a,o,l,c;const h=ie.tweens[r][e];h&&delete ie.attrs[r][h][e];let d=i.getAttr(e);if(b._isArray(t))if(s=[],a=Math.max(t.length,d.length),e==="points"&&t.length!==d.length&&(t.length>d.length?(l=d,d=b._prepareArrayForTween(d,t,i.closed())):(o=t,t=b._prepareArrayForTween(t,d,i.closed()))),e.indexOf("fill")===0)for(let u=0;u<a;u++)if(u%2===0)s.push(t[u]-d[u]);else{const g=b.colorToRGBA(d[u]);c=b.colorToRGBA(t[u]),d[u]=g,s.push({r:c.r-g.r,g:c.g-g.g,b:c.b-g.b,a:c.a-g.a})}else for(let u=0;u<a;u++)s.push(t[u]-d[u]);else $s.indexOf(e)!==-1?(d=b.colorToRGBA(d),c=b.colorToRGBA(t),s={r:c.r-d.r,g:c.g-d.g,b:c.b-d.b,a:c.a-d.a}):s=t-d;ie.attrs[r][this._id][e]={start:d,diff:s,end:t,trueEnd:o,trueStart:l},ie.tweens[r][e]=this._id}_tweenFunc(e){const t=this.node,i=ie.attrs[t._id][this._id];let r,s,a,o,l,c,h,d;for(r in i){if(s=i[r],a=s.start,o=s.diff,d=s.end,b._isArray(a))if(l=[],h=Math.max(a.length,d.length),r.indexOf("fill")===0)for(c=0;c<h;c++)c%2===0?l.push((a[c]||0)+o[c]*e):l.push("rgba("+Math.round(a[c].r+o[c].r*e)+","+Math.round(a[c].g+o[c].g*e)+","+Math.round(a[c].b+o[c].b*e)+","+(a[c].a+o[c].a*e)+")");else for(c=0;c<h;c++)l.push((a[c]||0)+o[c]*e);else $s.indexOf(r)!==-1?l="rgba("+Math.round(a.r+o.r*e)+","+Math.round(a.g+o.g*e)+","+Math.round(a.b+o.b*e)+","+(a.a+o.a*e)+")":l=a+o*e;t.setAttr(r,l)}}_addListeners(){this.tween.onPlay=()=>{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const e=this.node,t=ie.attrs[e._id][this._id];t.points&&t.points.trueEnd&&e.setAttr("points",t.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const e=this.node,t=ie.attrs[e._id][this._id];t.points&&t.points.trueStart&&e.points(t.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(e){return this.tween.seek(e*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const e=this.node._id,t=this._id,i=ie.tweens[e];this.pause(),this.anim&&this.anim.stop();for(const r in i)delete ie.tweens[e][r];delete ie.attrs[e][t],ie.tweens[e]&&(Object.keys(ie.tweens[e]).length===0&&delete ie.tweens[e],Object.keys(ie.attrs[e]).length===0&&delete ie.attrs[e])}}ie.attrs={};ie.tweens={};I.prototype.to=function(n){const e=n.onFinish;n.node=this,n.onFinish=function(){this.destroy(),e&&e()},new ie(n).play()};const ti={BackEaseIn(n,e,t,i){return t*(n/=i)*n*((1.70158+1)*n-1.70158)+e},BackEaseOut(n,e,t,i){return t*((n=n/i-1)*n*((1.70158+1)*n+1.70158)+1)+e},BackEaseInOut(n,e,t,i){let r=1.70158;return(n/=i/2)<1?t/2*(n*n*(((r*=1.525)+1)*n-r))+e:t/2*((n-=2)*n*(((r*=1.525)+1)*n+r)+2)+e},ElasticEaseIn(n,e,t,i,r,s){let a=0;return n===0?e:(n/=i)===1?e+t:(s||(s=i*.3),!r||r<Math.abs(t)?(r=t,a=s/4):a=s/(2*Math.PI)*Math.asin(t/r),-(r*Math.pow(2,10*(n-=1))*Math.sin((n*i-a)*(2*Math.PI)/s))+e)},ElasticEaseOut(n,e,t,i,r,s){let a=0;return n===0?e:(n/=i)===1?e+t:(s||(s=i*.3),!r||r<Math.abs(t)?(r=t,a=s/4):a=s/(2*Math.PI)*Math.asin(t/r),r*Math.pow(2,-10*n)*Math.sin((n*i-a)*(2*Math.PI)/s)+t+e)},ElasticEaseInOut(n,e,t,i,r,s){let a=0;return n===0?e:(n/=i/2)===2?e+t:(s||(s=i*(.3*1.5)),!r||r<Math.abs(t)?(r=t,a=s/4):a=s/(2*Math.PI)*Math.asin(t/r),n<1?-.5*(r*Math.pow(2,10*(n-=1))*Math.sin((n*i-a)*(2*Math.PI)/s))+e:r*Math.pow(2,-10*(n-=1))*Math.sin((n*i-a)*(2*Math.PI)/s)*.5+t+e)},BounceEaseOut(n,e,t,i){return(n/=i)<1/2.75?t*(7.5625*n*n)+e:n<2/2.75?t*(7.5625*(n-=1.5/2.75)*n+.75)+e:n<2.5/2.75?t*(7.5625*(n-=2.25/2.75)*n+.9375)+e:t*(7.5625*(n-=2.625/2.75)*n+.984375)+e},BounceEaseIn(n,e,t,i){return t-ti.BounceEaseOut(i-n,0,t,i)+e},BounceEaseInOut(n,e,t,i){return n<i/2?ti.BounceEaseIn(n*2,0,t,i)*.5+e:ti.BounceEaseOut(n*2-i,0,t,i)*.5+t*.5+e},EaseIn(n,e,t,i){return t*(n/=i)*n+e},EaseOut(n,e,t,i){return-t*(n/=i)*(n-2)+e},EaseInOut(n,e,t,i){return(n/=i/2)<1?t/2*n*n+e:-t/2*(--n*(n-2)-1)+e},StrongEaseIn(n,e,t,i){return t*(n/=i)*n*n*n*n+e},StrongEaseOut(n,e,t,i){return t*((n=n/i-1)*n*n*n*n+1)+e},StrongEaseInOut(n,e,t,i){return(n/=i/2)<1?t/2*n*n*n*n*n+e:t/2*((n-=2)*n*n*n*n+2)+e},Linear(n,e,t,i){return t*n/i+e}},Vs=b._assign(M,{Util:b,Transform:ve,Node:I,Container:Te,Stage:cr,stages:Qt,Layer:ct,FastLayer:fs,Group:wt,DD:J,Shape:A,shapes:ei,Animation:we,Tween:ie,Easings:ti,Context:or,Canvas:ds});class Be extends A{_sceneFunc(e){const t=M.getAngle(this.angle()),i=this.clockwise();e.beginPath(),e.arc(0,0,this.outerRadius(),0,t,i),e.arc(0,0,this.innerRadius(),t,0,!i),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}getSelfRect(){const e=this.innerRadius(),t=this.outerRadius(),i=this.clockwise(),r=M.getAngle(i?360-this.angle():this.angle()),s=Math.cos(Math.min(r,Math.PI)),a=1,o=Math.sin(Math.min(Math.max(Math.PI,r),3*Math.PI/2)),l=Math.sin(Math.min(r,Math.PI/2)),c=s*(s>0?e:t),h=a*t,d=o*(o>0?e:t),u=l*(l>0?t:e);return{x:c,y:i?-1*u:d,width:h-c,height:u-d}}}Be.prototype._centroid=!0;Be.prototype.className="Arc";Be.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];ae(Be);y.addGetterSetter(Be,"innerRadius",0,E());y.addGetterSetter(Be,"outerRadius",0,E());y.addGetterSetter(Be,"angle",0,E());y.addGetterSetter(Be,"clockwise",!1,Ae());function Gr(n,e,t,i,r,s,a){const o=Math.sqrt(Math.pow(t-n,2)+Math.pow(i-e,2)),l=Math.sqrt(Math.pow(r-t,2)+Math.pow(s-i,2)),c=a*o/(o+l),h=a*l/(o+l),d=t-c*(r-n),u=i-c*(s-e),g=t+h*(r-n),f=i+h*(s-e);return[d,u,g,f]}function Us(n,e){const t=n.length,i=[];for(let r=2;r<t-2;r+=2){const s=Gr(n[r-2],n[r-1],n[r],n[r+1],n[r+2],n[r+3],e);isNaN(s[0])||(i.push(s[0]),i.push(s[1]),i.push(n[r]),i.push(n[r+1]),i.push(s[2]),i.push(s[3]))}return i}function tc(n){const e=[[n[0],n[2],n[4],n[6]],[n[1],n[3],n[5],n[7]]],t=[];for(const i of e){const r=-3*i[0]+9*i[1]-9*i[2]+3*i[3];if(r!==0){const s=6*i[0]-12*i[1]+6*i[2],a=-3*i[0]+3*i[1],o=s*s-4*r*a;if(o>=0){const l=Math.sqrt(o);t.push((-s+l)/(2*r)),t.push((-s-l)/(2*r))}}}return t.filter(i=>i>0&&i<1).flatMap(i=>e.map(r=>{const s=1-i;return s*s*s*r[0]+3*s*s*i*r[1]+3*s*i*i*r[2]+i*i*i*r[3]}))}class Fe extends A{constructor(e){super(e),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(e){const t=this.points(),i=t.length,r=this.tension(),s=this.closed(),a=this.bezier();if(!i)return;let o=0;if(e.beginPath(),e.moveTo(t[0],t[1]),r!==0&&i>4){const l=this.getTensionPoints(),c=l.length;for(o=s?0:4,s||e.quadraticCurveTo(l[0],l[1],l[2],l[3]);o<c-2;)e.bezierCurveTo(l[o++],l[o++],l[o++],l[o++],l[o++],l[o++]);s||e.quadraticCurveTo(l[c-2],l[c-1],t[i-2],t[i-1])}else if(a)for(o=2;o<i;)e.bezierCurveTo(t[o++],t[o++],t[o++],t[o++],t[o++],t[o++]);else for(o=2;o<i;o+=2)e.lineTo(t[o],t[o+1]);s?(e.closePath(),e.fillStrokeShape(this)):e.strokeShape(this)}getTensionPoints(){return this._getCache("tensionPoints",this._getTensionPoints)}_getTensionPoints(){return this.closed()?this._getTensionPointsClosed():Us(this.points(),this.tension())}_getTensionPointsClosed(){const e=this.points(),t=e.length,i=this.tension(),r=Gr(e[t-2],e[t-1],e[0],e[1],e[2],e[3],i),s=Gr(e[t-4],e[t-3],e[t-2],e[t-1],e[0],e[1],i),a=Us(e,i);return[r[2],r[3]].concat(a).concat([s[0],s[1],e[t-2],e[t-1],s[2],s[3],r[0],r[1],e[0],e[1]])}getWidth(){return this.getSelfRect().width}getHeight(){return this.getSelfRect().height}getSelfRect(){let e=this.points();if(e.length<4)return{x:e[0]||0,y:e[1]||0,width:0,height:0};this.tension()!==0?e=[e[0],e[1],...this._getTensionPoints(),e[e.length-2],e[e.length-1]]:this.bezier()?e=[e[0],e[1],...tc(this.points()),e[e.length-2],e[e.length-1]]:e=this.points();let t=e[0],i=e[0],r=e[1],s=e[1],a,o;for(let l=0;l<e.length/2;l++)a=e[l*2],o=e[l*2+1],t=Math.min(t,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);return{x:t,y:r,width:i-t,height:s-r}}}Fe.prototype.className="Line";Fe.prototype._attrsAffectingSize=["points","bezier","tension"];ae(Fe);y.addGetterSetter(Fe,"closed",!1);y.addGetterSetter(Fe,"bezier",!1);y.addGetterSetter(Fe,"tension",0,E());y.addGetterSetter(Fe,"points",[],yl());const ic=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],rc=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],sc=[[1],[1,1],[1,2,1],[1,3,3,1]],Ws=(n,e,t)=>{let i,r;const a=t/2;i=0;for(let o=0;o<20;o++)r=a*ic[20][o]+a,i+=rc[20][o]*nc(n,e,r);return a*i},Ys=(n,e,t)=>{t===void 0&&(t=1);const i=n[0]-2*n[1]+n[2],r=e[0]-2*e[1]+e[2],s=2*n[1]-2*n[0],a=2*e[1]-2*e[0],o=4*(i*i+r*r),l=4*(i*s+r*a),c=s*s+a*a;if(o===0)return t*Math.sqrt(Math.pow(n[2]-n[0],2)+Math.pow(e[2]-e[0],2));const h=l/(2*o),d=c/o,u=t+h,g=d-h*h,f=u*u+g>0?Math.sqrt(u*u+g):0,m=h*h+g>0?Math.sqrt(h*h+g):0,C=h+Math.sqrt(h*h+g)!==0?g*Math.log(Math.abs((u+f)/(h+m))):0;return Math.sqrt(o)/2*(u*f-h*m+C)};function nc(n,e,t){const i=Nr(1,t,n),r=Nr(1,t,e),s=i*i+r*r;return Math.sqrt(s)}const Nr=(n,e,t)=>{const i=t.length-1;let r,s;if(i===0)return 0;if(n===0){s=0;for(let a=0;a<=i;a++)s+=sc[i][a]*Math.pow(1-e,i-a)*Math.pow(e,a)*t[a];return s}else{r=new Array(i);for(let a=0;a<i;a++)r[a]=i*(t[a+1]-t[a]);return Nr(n-1,e,r)}},Xs=(n,e,t)=>{let i=1,r=n/e,s=(n-t(r))/e,a=0;for(;i>.001;){const o=t(r+s),l=Math.abs(n-o)/e;if(l<i)i=l,r+=s;else{const c=t(r-s),h=Math.abs(n-c)/e;h<i?(i=h,r-=s):s/=2}if(a++,a>500)break}return r};class re extends A{constructor(e){super(e),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=re.parsePathData(this.data()),this.pathLength=re.getPathLength(this.dataArray)}_sceneFunc(e){const t=this.dataArray;e.beginPath();let i=!1;for(let r=0;r<t.length;r++){const s=t[r].command,a=t[r].points;switch(s){case"L":e.lineTo(a[0],a[1]);break;case"M":e.moveTo(a[0],a[1]);break;case"C":e.bezierCurveTo(a[0],a[1],a[2],a[3],a[4],a[5]);break;case"Q":e.quadraticCurveTo(a[0],a[1],a[2],a[3]);break;case"A":const o=a[0],l=a[1],c=a[2],h=a[3],d=a[4],u=a[5],g=a[6],f=a[7],m=c>h?c:h,C=c>h?1:c/h,v=c>h?h/c:1;e.translate(o,l),e.rotate(g),e.scale(C,v),e.arc(0,0,m,d,d+u,1-f),e.scale(1/C,1/v),e.rotate(-g),e.translate(-o,-l);break;case"z":i=!0,e.closePath();break}}!i&&!this.hasFill()?e.strokeShape(this):e.fillStrokeShape(this)}getSelfRect(){let e=[];this.dataArray.forEach(function(l){if(l.command==="A"){const c=l.points[4],h=l.points[5],d=l.points[4]+h;let u=Math.PI/180;if(Math.abs(c-d)<u&&(u=Math.abs(c-d)),h<0)for(let g=c-u;g>d;g-=u){const f=re.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}else for(let g=c+u;g<d;g+=u){const f=re.getPointOnEllipticalArc(l.points[0],l.points[1],l.points[2],l.points[3],g,0);e.push(f.x,f.y)}}else if(l.command==="C")for(let c=0;c<=1;c+=.01){const h=re.getPointOnCubicBezier(c,l.start.x,l.start.y,l.points[0],l.points[1],l.points[2],l.points[3],l.points[4],l.points[5]);e.push(h.x,h.y)}else e=e.concat(l.points)});let t=e[0],i=e[0],r=e[1],s=e[1],a,o;for(let l=0;l<e.length/2;l++)a=e[l*2],o=e[l*2+1],isNaN(a)||(t=Math.min(t,a),i=Math.max(i,a)),isNaN(o)||(r=Math.min(r,o),s=Math.max(s,o));return{x:t,y:r,width:i-t,height:s-r}}getLength(){return this.pathLength}getPointAtLength(e){return re.getPointAtLengthOfDataArray(e,this.dataArray)}static getLineLength(e,t,i,r){return Math.sqrt((i-e)*(i-e)+(r-t)*(r-t))}static getPathLength(e){let t=0;for(let i=0;i<e.length;++i)t+=e[i].pathLength;return t}static getPointAtLengthOfDataArray(e,t){let i,r=0,s=t.length;if(!s)return null;for(;r<s&&e>t[r].pathLength;)e-=t[r].pathLength,++r;if(r===s)return i=t[r-1].points.slice(-2),{x:i[0],y:i[1]};if(e<.01)return t[r].command==="M"?(i=t[r].points.slice(0,2),{x:i[0],y:i[1]}):{x:t[r].start.x,y:t[r].start.y};const a=t[r],o=a.points;switch(a.command){case"L":return re.getPointOnLine(e,a.start.x,a.start.y,o[0],o[1]);case"C":return re.getPointOnCubicBezier(Xs(e,re.getPathLength(t),m=>Ws([a.start.x,o[0],o[2],o[4]],[a.start.y,o[1],o[3],o[5]],m)),a.start.x,a.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return re.getPointOnQuadraticBezier(Xs(e,re.getPathLength(t),m=>Ys([a.start.x,o[0],o[2]],[a.start.y,o[1],o[3]],m)),a.start.x,a.start.y,o[0],o[1],o[2],o[3]);case"A":const l=o[0],c=o[1],h=o[2],d=o[3],u=o[5],g=o[6];let f=o[4];return f+=u*e/a.pathLength,re.getPointOnEllipticalArc(l,c,h,d,f,g)}return null}static getPointOnLine(e,t,i,r,s,a,o){a=a??t,o=o??i;const l=this.getLineLength(t,i,r,s);if(l<1e-10)return{x:t,y:i};if(r===t)return{x:a,y:o+(s>i?e:-e)};const c=(s-i)/(r-t),h=Math.sqrt(e*e/(1+c*c))*(r<t?-1:1),d=c*h;if(Math.abs(o-i-c*(a-t))<1e-10)return{x:a+h,y:o+d};const u=((a-t)*(r-t)+(o-i)*(s-i))/(l*l),g=t+u*(r-t),f=i+u*(s-i),m=this.getLineLength(a,o,g,f),C=Math.sqrt(e*e-m*m),v=Math.sqrt(C*C/(1+c*c))*(r<t?-1:1),S=c*v;return{x:g+v,y:f+S}}static getPointOnCubicBezier(e,t,i,r,s,a,o,l,c){function h(C){return C*C*C}function d(C){return 3*C*C*(1-C)}function u(C){return 3*C*(1-C)*(1-C)}function g(C){return(1-C)*(1-C)*(1-C)}const f=l*h(e)+a*d(e)+r*u(e)+t*g(e),m=c*h(e)+o*d(e)+s*u(e)+i*g(e);return{x:f,y:m}}static getPointOnQuadraticBezier(e,t,i,r,s,a,o){function l(g){return g*g}function c(g){return 2*g*(1-g)}function h(g){return(1-g)*(1-g)}const d=a*l(e)+r*c(e)+t*h(e),u=o*l(e)+s*c(e)+i*h(e);return{x:d,y:u}}static getPointOnEllipticalArc(e,t,i,r,s,a){const o=Math.cos(a),l=Math.sin(a),c={x:i*Math.cos(s),y:r*Math.sin(s)};return{x:e+(c.x*o-c.y*l),y:t+(c.x*l+c.y*o)}}static parsePathData(e){if(!e)return[];let t=e;const i=["m","M","l","L","v","V","h","H","z","Z","c","C","q","Q","t","T","s","S","a","A"];t=t.replace(new RegExp(" ","g"),",");for(let d=0;d<i.length;d++)t=t.replace(new RegExp(i[d],"g"),"|"+i[d]);const r=t.split("|"),s=[],a=[];let o=0,l=0;const c=/([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi;let h;for(let d=1;d<r.length;d++){let u=r[d],g=u.charAt(0);for(u=u.slice(1),a.length=0;h=c.exec(u);)a.push(h[0]);let f=[],m=g==="A"||g==="a"?0:-1;for(let C=0,v=a.length;C<v;C++){const S=a[C];if(S==="00"){f.push(0,0),m>=0&&(m+=2,m>=7&&(m-=7));continue}if(m>=0){if(m===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),f.push(parseFloat(S.slice(2))),m+=3,m>=7&&(m-=7);continue}if(S==="11"||S==="10"||S==="01"){f.push(parseInt(S[0],10)),f.push(parseInt(S[1],10)),m+=2,m>=7&&(m-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),m+=1,m>=7&&(m-=7);continue}}else if(m===4){if(/^[01]\d+(?:\.\d+)?$/.test(S)){f.push(parseInt(S[0],10)),f.push(parseFloat(S.slice(1))),m+=2,m>=7&&(m-=7);continue}if(S==="0"||S==="1"){f.push(parseInt(S,10)),m+=1,m>=7&&(m-=7);continue}}const T=parseFloat(S);isNaN(T)?f.push(0):f.push(T),m+=1,m>=7&&(m-=7)}else{const T=parseFloat(S);isNaN(T)?f.push(0):f.push(T)}}for(;f.length>0&&!isNaN(f[0]);){let C="",v=[];const S=o,T=l;let k,_,w,D,x,R,O,z,H,$;switch(g){case"l":o+=f.shift(),l+=f.shift(),C="L",v.push(o,l);break;case"L":o=f.shift(),l=f.shift(),v.push(o,l);break;case"m":const V=f.shift(),G=f.shift();if(o+=V,l+=G,C="M",s.length>2&&s[s.length-1].command==="z"){for(let L=s.length-2;L>=0;L--)if(s[L].command==="M"){o=s[L].points[0]+V,l=s[L].points[1]+G;break}}v.push(o,l),g="l";break;case"M":o=f.shift(),l=f.shift(),C="M",v.push(o,l),g="L";break;case"h":o+=f.shift(),C="L",v.push(o,l);break;case"H":o=f.shift(),C="L",v.push(o,l);break;case"v":l+=f.shift(),C="L",v.push(o,l);break;case"V":l=f.shift(),C="L",v.push(o,l);break;case"C":v.push(f.shift(),f.shift(),f.shift(),f.shift()),o=f.shift(),l=f.shift(),v.push(o,l);break;case"c":v.push(o+f.shift(),l+f.shift(),o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),C="C",v.push(o,l);break;case"S":_=o,w=l,k=s[s.length-1],k.command==="C"&&(_=o+(o-k.points[2]),w=l+(l-k.points[3])),v.push(_,w,f.shift(),f.shift()),o=f.shift(),l=f.shift(),C="C",v.push(o,l);break;case"s":_=o,w=l,k=s[s.length-1],k.command==="C"&&(_=o+(o-k.points[2]),w=l+(l-k.points[3])),v.push(_,w,o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),C="C",v.push(o,l);break;case"Q":v.push(f.shift(),f.shift()),o=f.shift(),l=f.shift(),v.push(o,l);break;case"q":v.push(o+f.shift(),l+f.shift()),o+=f.shift(),l+=f.shift(),C="Q",v.push(o,l);break;case"T":_=o,w=l,k=s[s.length-1],k.command==="Q"&&(_=o+(o-k.points[0]),w=l+(l-k.points[1])),o=f.shift(),l=f.shift(),C="Q",v.push(_,w,o,l);break;case"t":_=o,w=l,k=s[s.length-1],k.command==="Q"&&(_=o+(o-k.points[0]),w=l+(l-k.points[1])),o+=f.shift(),l+=f.shift(),C="Q",v.push(_,w,o,l);break;case"A":D=f.shift(),x=f.shift(),R=f.shift(),O=f.shift(),z=f.shift(),H=o,$=l,o=f.shift(),l=f.shift(),C="A",v=this.convertEndpointToCenterParameterization(H,$,o,l,O,z,D,x,R);break;case"a":D=f.shift(),x=f.shift(),R=f.shift(),O=f.shift(),z=f.shift(),H=o,$=l,o+=f.shift(),l+=f.shift(),C="A",v=this.convertEndpointToCenterParameterization(H,$,o,l,O,z,D,x,R);break}s.push({command:C||g,points:v,start:{x:S,y:T},pathLength:this.calcLength(S,T,C||g,v)})}(g==="z"||g==="Z")&&s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(e,t,i,r){let s,a,o,l;const c=re;switch(i){case"L":return c.getLineLength(e,t,r[0],r[1]);case"C":return Ws([e,r[0],r[2],r[4]],[t,r[1],r[3],r[5]],1);case"Q":return Ys([e,r[0],r[2]],[t,r[1],r[3]],1);case"A":s=0;const h=r[4],d=r[5],u=r[4]+d;let g=Math.PI/180;if(Math.abs(h-u)<g&&(g=Math.abs(h-u)),a=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],h,0),d<0)for(l=h-g;l>u;l-=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;else for(l=h+g;l<u;l+=g)o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],l,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),a=o;return o=c.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],u,0),s+=c.getLineLength(a.x,a.y,o.x,o.y),s}return 0}static convertEndpointToCenterParameterization(e,t,i,r,s,a,o,l,c){const h=c*(Math.PI/180),d=Math.cos(h)*(e-i)/2+Math.sin(h)*(t-r)/2,u=-1*Math.sin(h)*(e-i)/2+Math.cos(h)*(t-r)/2,g=d*d/(o*o)+u*u/(l*l);g>1&&(o*=Math.sqrt(g),l*=Math.sqrt(g));let f=Math.sqrt((o*o*(l*l)-o*o*(u*u)-l*l*(d*d))/(o*o*(u*u)+l*l*(d*d)));s===a&&(f*=-1),isNaN(f)&&(f=0);const m=f*o*u/l,C=f*-l*d/o,v=(e+i)/2+Math.cos(h)*m-Math.sin(h)*C,S=(t+r)/2+Math.sin(h)*m+Math.cos(h)*C,T=function(O){return Math.sqrt(O[0]*O[0]+O[1]*O[1])},k=function(O,z){return(O[0]*z[0]+O[1]*z[1])/(T(O)*T(z))},_=function(O,z){return(O[0]*z[1]<O[1]*z[0]?-1:1)*Math.acos(k(O,z))},w=_([1,0],[(d-m)/o,(u-C)/l]),D=[(d-m)/o,(u-C)/l],x=[(-1*d-m)/o,(-1*u-C)/l];let R=_(D,x);return k(D,x)<=-1&&(R=Math.PI),k(D,x)>=1&&(R=0),a===0&&R>0&&(R=R-2*Math.PI),a===1&&R<0&&(R=R+2*Math.PI),[v,S,o,l,w,R,h,a]}}re.prototype.className="Path";re.prototype._attrsAffectingSize=["data"];ae(re);y.addGetterSetter(re,"data");class ht extends Fe{_sceneFunc(e){super._sceneFunc(e);const t=Math.PI*2,i=this.points();let r=i;const s=this.tension()!==0&&i.length>4;s&&(r=this.getTensionPoints());const a=this.pointerLength(),o=i.length;let l,c;if(s){const u=[r[r.length-4],r[r.length-3],r[r.length-2],r[r.length-1],i[o-2],i[o-1]],g=re.calcLength(r[r.length-4],r[r.length-3],"C",u),f=re.getPointOnQuadraticBezier(Math.min(1,1-a/g),u[0],u[1],u[2],u[3],u[4],u[5]);l=i[o-2]-f.x,c=i[o-1]-f.y}else l=i[o-2]-i[o-4],c=i[o-1]-i[o-3];const h=(Math.atan2(c,l)+t)%t,d=this.pointerWidth();this.pointerAtEnding()&&(e.save(),e.beginPath(),e.translate(i[o-2],i[o-1]),e.rotate(h),e.moveTo(0,0),e.lineTo(-a,d/2),e.lineTo(-a,-d/2),e.closePath(),e.restore(),this.__fillStroke(e)),this.pointerAtBeginning()&&(e.save(),e.beginPath(),e.translate(i[0],i[1]),s?(l=(r[0]+r[2])/2-i[0],c=(r[1]+r[3])/2-i[1]):(l=i[2]-i[0],c=i[3]-i[1]),e.rotate((Math.atan2(-c,-l)+t)%t),e.moveTo(0,0),e.lineTo(-a,d/2),e.lineTo(-a,-d/2),e.closePath(),e.restore(),this.__fillStroke(e))}__fillStroke(e){const t=this.dashEnabled();t&&(this.attrs.dashEnabled=!1,e.setLineDash([])),e.fillStrokeShape(this),t&&(this.attrs.dashEnabled=!0)}getSelfRect(){const e=super.getSelfRect(),t=this.pointerWidth()/2;return{x:e.x,y:e.y-t,width:e.width,height:e.height+t*2}}}ht.prototype.className="Arrow";ae(ht);y.addGetterSetter(ht,"pointerLength",10,E());y.addGetterSetter(ht,"pointerWidth",10,E());y.addGetterSetter(ht,"pointerAtBeginning",!1);y.addGetterSetter(ht,"pointerAtEnding",!0);class It extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius()!==e/2&&this.radius(e/2)}setHeight(e){this.radius()!==e/2&&this.radius(e/2)}}It.prototype._centroid=!0;It.prototype.className="Circle";It.prototype._attrsAffectingSize=["radius"];ae(It);y.addGetterSetter(It,"radius",0,E());class Ze extends A{_sceneFunc(e){const t=this.radiusX(),i=this.radiusY();e.beginPath(),e.save(),t!==i&&e.scale(1,i/t),e.arc(0,0,t,0,Math.PI*2,!1),e.restore(),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(e){this.radiusX(e/2)}setHeight(e){this.radiusY(e/2)}}Ze.prototype.className="Ellipse";Ze.prototype._centroid=!0;Ze.prototype._attrsAffectingSize=["radiusX","radiusY"];ae(Ze);y.addComponentsGetterSetter(Ze,"radius",["x","y"]);y.addGetterSetter(Ze,"radiusX",0,E());y.addGetterSetter(Ze,"radiusY",0,E());let Ie=class La extends A{constructor(e){super(e),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",t=>{this._removeImageLoad(t.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const e=this.image();e&&e.complete||e&&e.readyState===4||e&&e.addEventListener&&e.addEventListener("load",this._loadListener)}_removeImageLoad(e){e&&e.removeEventListener&&e.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const e=!!this.cornerRadius(),t=this.hasShadow();return e&&t?!0:super._useBufferCanvas(!0)}_sceneFunc(e){const t=this.getWidth(),i=this.getHeight(),r=this.cornerRadius(),s=this.attrs.image;let a;if(s){const o=this.attrs.cropWidth,l=this.attrs.cropHeight;o&&l?a=[s,this.cropX(),this.cropY(),o,l,0,0,t,i]:a=[s,0,0,t,i]}(this.hasFill()||this.hasStroke()||r)&&(e.beginPath(),r?b.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)),s&&(r&&e.clip(),e.drawImage.apply(e,a))}_hitFunc(e){const t=this.width(),i=this.height(),r=this.cornerRadius();e.beginPath(),r?b.drawRoundedRectPath(e,t,i,r):e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}getWidth(){var e,t,i;return(i=(e=this.attrs.width)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.width)!==null&&i!==void 0?i:0}getHeight(){var e,t,i;return(i=(e=this.attrs.height)!==null&&e!==void 0?e:(t=this.image())===null||t===void 0?void 0:t.height)!==null&&i!==void 0?i:0}static fromURL(e,t,i=null){const r=b.createImageElement();r.onload=function(){const s=new La({image:r});t(s)},r.onerror=i,r.crossOrigin="Anonymous",r.src=e}};Ie.prototype.className="Image";Ie.prototype._attrsAffectingSize=["image"];ae(Ie);y.addGetterSetter(Ie,"cornerRadius",0,lr(4));y.addGetterSetter(Ie,"image");y.addComponentsGetterSetter(Ie,"crop",["x","y","width","height"]);y.addGetterSetter(Ie,"cropX",0,E());y.addGetterSetter(Ie,"cropY",0,E());y.addGetterSetter(Ie,"cropWidth",0,E());y.addGetterSetter(Ie,"cropHeight",0,E());const Da=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],ac="Change.konva",oc="none",zr="up",$r="right",Vr="down",Ur="left",lc=Da.length;class ms extends wt{constructor(e){super(e),this.on("add.konva",function(t){this._addListeners(t.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(e){let t=this,i;const r=function(){t._sync()};for(i=0;i<lc;i++)e.on(Da[i]+ac,r)}getWidth(){return this.getText().width()}getHeight(){return this.getText().height()}_sync(){let e=this.getText(),t=this.getTag(),i,r,s,a,o,l,c;if(e&&t){switch(i=e.width(),r=e.height(),s=t.pointerDirection(),a=t.pointerWidth(),c=t.pointerHeight(),o=0,l=0,s){case zr:o=i/2,l=-1*c;break;case $r:o=i+a,l=r/2;break;case Vr:o=i/2,l=r+c;break;case Ur:o=-1*a,l=r/2;break}t.setAttrs({x:-1*o,y:-1*l,width:i,height:r}),e.setAttrs({x:-1*o,y:-1*l})}}}ms.prototype.className="Label";ae(ms);class dt extends A{_sceneFunc(e){const t=this.width(),i=this.height(),r=this.pointerDirection(),s=this.pointerWidth(),a=this.pointerHeight(),o=this.cornerRadius();let l=0,c=0,h=0,d=0;typeof o=="number"?l=c=h=d=Math.min(o,t/2,i/2):(l=Math.min(o[0]||0,t/2,i/2),c=Math.min(o[1]||0,t/2,i/2),d=Math.min(o[2]||0,t/2,i/2),h=Math.min(o[3]||0,t/2,i/2)),e.beginPath(),e.moveTo(l,0),r===zr&&(e.lineTo((t-s)/2,0),e.lineTo(t/2,-1*a),e.lineTo((t+s)/2,0)),e.lineTo(t-c,0),e.arc(t-c,c,c,Math.PI*3/2,0,!1),r===$r&&(e.lineTo(t,(i-a)/2),e.lineTo(t+s,i/2),e.lineTo(t,(i+a)/2)),e.lineTo(t,i-d),e.arc(t-d,i-d,d,0,Math.PI/2,!1),r===Vr&&(e.lineTo((t+s)/2,i),e.lineTo(t/2,i+a),e.lineTo((t-s)/2,i)),e.lineTo(h,i),e.arc(h,i-h,h,Math.PI/2,Math.PI,!1),r===Ur&&(e.lineTo(0,(i+a)/2),e.lineTo(-1*s,i/2),e.lineTo(0,(i-a)/2)),e.lineTo(0,l),e.arc(l,l,l,Math.PI,Math.PI*3/2,!1),e.closePath(),e.fillStrokeShape(this)}getSelfRect(){let e=0,t=0,i=this.pointerWidth(),r=this.pointerHeight(),s=this.pointerDirection(),a=this.width(),o=this.height();return s===zr?(t-=r,o+=r):s===Vr?o+=r:s===Ur?(e-=i*1.5,a+=i):s===$r&&(a+=i*1.5),{x:e,y:t,width:a,height:o}}}dt.prototype.className="Tag";ae(dt);y.addGetterSetter(dt,"pointerDirection",oc);y.addGetterSetter(dt,"pointerWidth",0,E());y.addGetterSetter(dt,"pointerHeight",0,E());y.addGetterSetter(dt,"cornerRadius",0,lr(4));class vi extends A{_sceneFunc(e){const t=this.cornerRadius(),i=this.width(),r=this.height();e.beginPath(),t?b.drawRoundedRectPath(e,i,r,t):e.rect(0,0,i,r),e.closePath(),e.fillStrokeShape(this)}}vi.prototype.className="Rect";ae(vi);y.addGetterSetter(vi,"cornerRadius",0,lr(4));class Je extends A{_sceneFunc(e){const t=this._getPoints(),i=this.radius(),r=this.sides(),s=this.cornerRadius();if(e.beginPath(),s)b.drawRoundedPolygonPath(e,t,r,i,s);else{e.moveTo(t[0].x,t[0].y);for(let a=1;a<t.length;a++)e.lineTo(t[a].x,t[a].y)}e.closePath(),e.fillStrokeShape(this)}_getPoints(){const e=this.attrs.sides,t=this.attrs.radius||0,i=[];for(let r=0;r<e;r++)i.push({x:t*Math.sin(r*2*Math.PI/e),y:-1*t*Math.cos(r*2*Math.PI/e)});return i}getSelfRect(){const e=this._getPoints();let t=e[0].x,i=e[0].x,r=e[0].y,s=e[0].y;return e.forEach(a=>{t=Math.min(t,a.x),i=Math.max(i,a.x),r=Math.min(r,a.y),s=Math.max(s,a.y)}),{x:t,y:r,width:i-t,height:s-r}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}Je.prototype.className="RegularPolygon";Je.prototype._centroid=!0;Je.prototype._attrsAffectingSize=["radius"];ae(Je);y.addGetterSetter(Je,"radius",0,E());y.addGetterSetter(Je,"sides",0,E());y.addGetterSetter(Je,"cornerRadius",0,lr(4));const js=Math.PI*2;class ut extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.innerRadius(),0,js,!1),e.moveTo(this.outerRadius(),0),e.arc(0,0,this.outerRadius(),js,0,!0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}ut.prototype.className="Ring";ut.prototype._centroid=!0;ut.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(ut);y.addGetterSetter(ut,"innerRadius",0,E());y.addGetterSetter(ut,"outerRadius",0,E());class De extends A{constructor(e){super(e),this._updated=!0,this.anim=new we(()=>{const t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,s=this.animations()[t],a=this.frameOffsets(),o=s[r+0],l=s[r+1],c=s[r+2],h=s[r+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(e.beginPath(),e.rect(0,0,c,h),e.closePath(),e.fillStrokeShape(this)),d)if(a){const u=a[t],g=i*2;e.drawImage(d,o,l,c,h,u[g+0],u[g+1],c,h)}else e.drawImage(d,o,l,c,h,0,0,c,h)}_hitFunc(e){const t=this.animation(),i=this.frameIndex(),r=i*4,s=this.animations()[t],a=this.frameOffsets(),o=s[r+2],l=s[r+3];if(e.beginPath(),a){const c=a[t],h=i*2;e.rect(c[h+0],c[h+1],o,l)}else e.rect(0,0,o,l);e.closePath(),e.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const e=this;this.interval=setInterval(function(){e._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const e=this.getLayer();this.anim.setLayers(e),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const e=this.frameIndex(),t=this.animation(),i=this.animations(),r=i[t],s=r.length/4;e<s-1?this.frameIndex(e+1):this.frameIndex(0)}}De.prototype.className="Sprite";ae(De);y.addGetterSetter(De,"animation");y.addGetterSetter(De,"animations");y.addGetterSetter(De,"frameOffsets");y.addGetterSetter(De,"image");y.addGetterSetter(De,"frameIndex",0,E());y.addGetterSetter(De,"frameRate",17,E());y.backCompat(De,{index:"frameIndex",getIndex:"getFrameIndex",setIndex:"setFrameIndex"});class Qe extends A{_sceneFunc(e){const t=this.innerRadius(),i=this.outerRadius(),r=this.numPoints();e.beginPath(),e.moveTo(0,0-i);for(let s=1;s<r*2;s++){const a=s%2===0?i:t,o=a*Math.sin(s*Math.PI/r),l=-1*a*Math.cos(s*Math.PI/r);e.lineTo(o,l)}e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(e){this.outerRadius(e/2)}setHeight(e){this.outerRadius(e/2)}}Qe.prototype.className="Star";Qe.prototype._centroid=!0;Qe.prototype._attrsAffectingSize=["innerRadius","outerRadius"];ae(Qe);y.addGetterSetter(Qe,"numPoints",5,E());y.addGetterSetter(Qe,"innerRadius",0,E());y.addGetterSetter(Qe,"outerRadius",0,E());function Ve(n){return[...n].reduce((e,t,i,r)=>{if(new RegExp("\\p{Emoji}","u").test(t)){const s=r[i+1];s&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(s)?(e.push(t+s),r[i+1]=""):e.push(t)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(t+(r[i+1]||""))?e.push(t+r[i+1]):i>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(t)?e[e.length-1]+=t:t&&e.push(t);return e},[])}const gt="auto",cc="center",Oa="inherit",Ot="justify",hc="Change.konva",dc="2d",qs="-",Ba="left",uc="text",pc="Text",gc="top",fc="bottom",Ks="middle",Fa="normal",mc="px ",Ei=" ",yc="right",Zs="rtl",Sc="word",Cc="char",Js="none",Cr="…",Ha=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],vc=Ha.length;function Tc(n){return n.split(",").map(e=>{e=e.trim();const t=e.indexOf(" ")>=0,i=e.indexOf('"')>=0||e.indexOf("'")>=0;return t&&!i&&(e=`"${e}"`),e}).join(", ")}let Ri;function vr(){return Ri||(Ri=b.createCanvasElement().getContext(dc),Ri)}function bc(n){n.fillText(this._partialText,this._partialTextX,this._partialTextY)}function kc(n){n.setAttr("miterLimit",2),n.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function wc(n){return n=n||{},!n.fillLinearGradientColorStops&&!n.fillRadialGradientColorStops&&!n.fillPatternImage&&(n.fill=n.fill||"black"),n}class se extends A{constructor(e){super(wc(e)),this._partialTextX=0,this._partialTextY=0;for(let t=0;t<vc;t++)this.on(Ha[t]+hc,this._setTextData);this._setTextData()}_sceneFunc(e){var t,i;const r=this.textArr,s=r.length;if(!this.text())return;let a=this.padding(),o=this.fontSize(),l=this.lineHeight()*o,c=this.verticalAlign(),h=this.direction(),d=0,u=this.align(),g=this.getWidth(),f=this.letterSpacing(),m=this.charRenderFunc(),C=this.fill(),v=this.textDecoration(),S=this.underlineOffset(),T=v.indexOf("underline")!==-1,k=v.indexOf("line-through")!==-1,_;h=h===Oa?e.direction:h;let w=l/2,D=Ks;if(!M.legacyTextRendering){const x=this.measureSize("M");D="alphabetic";const R=(t=x.fontBoundingBoxAscent)!==null&&t!==void 0?t:x.actualBoundingBoxAscent,O=(i=x.fontBoundingBoxDescent)!==null&&i!==void 0?i:x.actualBoundingBoxDescent;w=(R-O)/2+l/2}for(h===Zs&&e.setAttr("direction",h),e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",D),e.setAttr("textAlign",Ba),c===Ks?d=(this.getHeight()-s*l-a*2)/2:c===fc&&(d=this.getHeight()-s*l-a*2),e.translate(a,d+a),_=0;_<s;_++){let x=0,R=0;const O=r[_],z=O.text,H=O.width,$=O.lastInParagraph;if(e.save(),u===yc?x+=g-H-a*2:u===cc&&(x+=(g-H-a*2)/2),T){e.save(),e.beginPath();const G=S??(M.legacyTextRendering?Math.round(o/2):Math.round(o/4)),L=x,X=w+R+G;e.moveTo(L,X);const B=u===Ot&&!$?g-a*2:H;e.lineTo(L+Math.round(B),X),e.lineWidth=o/15;const Q=this._getLinearGradient();e.strokeStyle=Q||C,e.stroke(),e.restore()}const V=x;if(h!==Zs&&(f!==0||u===Ot||m)){const G=z.split(" ").length-1,L=Ve(z);for(let X=0;X<L.length;X++){const B=L[X];if(B===" "&&!$&&u===Ot&&(x+=(g-a*2-H)/G),this._partialTextX=x,this._partialTextY=w+R,this._partialText=B,m){e.save();const ne=r.slice(0,_).reduce((K,me)=>K+Ve(me.text).length,0),Y=X+ne;m({char:B,index:Y,x,y:w+R,lineIndex:_,column:X,isLastInLine:$,width:this.measureSize(B).width,context:e})}e.fillStrokeShape(this),m&&e.restore(),x+=this.measureSize(B).width+f}}else f!==0&&e.setAttr("letterSpacing",`${f}px`),this._partialTextX=x,this._partialTextY=w+R,this._partialText=z,e.fillStrokeShape(this);if(k){e.save(),e.beginPath();const G=M.legacyTextRendering?0:-Math.round(o/4),L=V;e.moveTo(L,w+R+G);const X=u===Ot&&!$?g-a*2:H;e.lineTo(L+Math.round(X),w+R+G),e.lineWidth=o/15;const B=this._getLinearGradient();e.strokeStyle=B||C,e.stroke(),e.restore()}e.restore(),s>1&&(w+=l)}}_hitFunc(e){const t=this.getWidth(),i=this.getHeight();e.beginPath(),e.rect(0,0,t,i),e.closePath(),e.fillStrokeShape(this)}setText(e){const t=b._isString(e)?e:e==null?"":e+"";return this._setAttr(uc,t),this}getWidth(){return this.attrs.width===gt||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===gt||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return b.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(e){var t,i,r,s,a,o,l,c,h,d,u;let g=vr(),f=this.fontSize(),m;g.save(),g.font=this._getContextFont(),m=g.measureText(e),g.restore();const C=f/100;return{actualBoundingBoxAscent:(t=m.actualBoundingBoxAscent)!==null&&t!==void 0?t:71.58203125*C,actualBoundingBoxDescent:(i=m.actualBoundingBoxDescent)!==null&&i!==void 0?i:0,actualBoundingBoxLeft:(r=m.actualBoundingBoxLeft)!==null&&r!==void 0?r:-7.421875*C,actualBoundingBoxRight:(s=m.actualBoundingBoxRight)!==null&&s!==void 0?s:75.732421875*C,alphabeticBaseline:(a=m.alphabeticBaseline)!==null&&a!==void 0?a:0,emHeightAscent:(o=m.emHeightAscent)!==null&&o!==void 0?o:100*C,emHeightDescent:(l=m.emHeightDescent)!==null&&l!==void 0?l:-20*C,fontBoundingBoxAscent:(c=m.fontBoundingBoxAscent)!==null&&c!==void 0?c:91*C,fontBoundingBoxDescent:(h=m.fontBoundingBoxDescent)!==null&&h!==void 0?h:21*C,hangingBaseline:(d=m.hangingBaseline)!==null&&d!==void 0?d:72.80000305175781*C,ideographicBaseline:(u=m.ideographicBaseline)!==null&&u!==void 0?u:-21*C,width:m.width,height:f}}_getContextFont(){return this.fontStyle()+Ei+this.fontVariant()+Ei+(this.fontSize()+mc)+Tc(this.fontFamily())}_addTextLine(e){this.align()===Ot&&(e=e.trim());const i=this._getTextWidth(e);return this.textArr.push({text:e,width:i,lastInParagraph:!1})}_getTextWidth(e){const t=this.letterSpacing(),i=e.length;return vr().measureText(e).width+t*i}_setTextData(){let e=this.text().split(`
15
+ `),t=+this.fontSize(),i=0,r=this.lineHeight()*t,s=this.attrs.width,a=this.attrs.height,o=s!==gt&&s!==void 0,l=a!==gt&&a!==void 0,c=this.padding(),h=s-c*2,d=a-c*2,u=0,g=this.wrap(),f=g!==Js,m=g!==Cc&&f,C=this.ellipsis();this.textArr=[],vr().font=this._getContextFont();const v=C?this._getTextWidth(Cr):0;for(let S=0,T=e.length;S<T;++S){let k=e[S],_=this._getTextWidth(k);if(o&&_>h)for(;k.length>0;){let w=0,D=Ve(k).length,x="",R=0;for(;w<D;){const O=w+D>>>1,z=Ve(k),H=z.slice(0,O+1).join(""),$=this._getTextWidth(H);(C&&l&&u+r>d?$+v:$)<=h?(w=O+1,x=H,R=$):D=O}if(x){if(m){const H=Ve(k),$=Ve(x),V=H[$.length],G=V===Ei||V===qs;let L;if(G&&R<=h)L=$.length;else{const X=$.lastIndexOf(Ei),B=$.lastIndexOf(qs);L=Math.max(X,B)+1}L>0&&(w=L,x=H.slice(0,w).join(""),R=this._getTextWidth(x))}if(x=x.trimRight(),this._addTextLine(x),i=Math.max(i,R),u+=r,this._shouldHandleEllipsis(u)){this._tryToAddEllipsisToLastLine();break}if(k=Ve(k).slice(w).join("").trimLeft(),k.length>0&&(_=this._getTextWidth(k),_<=h)){this._addTextLine(k),u+=r,i=Math.max(i,_);break}}else break}else this._addTextLine(k),u+=r,i=Math.max(i,_),this._shouldHandleEllipsis(u)&&S<T-1&&this._tryToAddEllipsisToLastLine();if(this.textArr[this.textArr.length-1]&&(this.textArr[this.textArr.length-1].lastInParagraph=!0),l&&u+r>d)break}this.textHeight=t,this.textWidth=i}_shouldHandleEllipsis(e){const t=+this.fontSize(),i=this.lineHeight()*t,r=this.attrs.height,s=r!==gt&&r!==void 0,a=this.padding(),o=r-a*2;return!(this.wrap()!==Js)||s&&e+i>o}_tryToAddEllipsisToLastLine(){const e=this.attrs.width,t=e!==gt&&e!==void 0,i=this.padding(),r=e-i*2,s=this.ellipsis(),a=this.textArr[this.textArr.length-1];!a||!s||(t&&(this._getTextWidth(a.text+Cr)<r||(a.text=a.text.slice(0,a.text.length-3))),this.textArr.splice(this.textArr.length-1,1),this._addTextLine(a.text+Cr))}getStrokeScaleEnabled(){return!0}_useBufferCanvas(){const e=this.textDecoration().indexOf("underline")!==-1||this.textDecoration().indexOf("line-through")!==-1,t=this.hasShadow();return e&&t?!0:super._useBufferCanvas()}}se.prototype._fillFunc=bc;se.prototype._strokeFunc=kc;se.prototype.className=pc;se.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"];ae(se);y.overWriteSetter(se,"width",ps());y.overWriteSetter(se,"height",ps());y.addGetterSetter(se,"direction",Oa);y.addGetterSetter(se,"fontFamily","Arial");y.addGetterSetter(se,"fontSize",12,E());y.addGetterSetter(se,"fontStyle",Fa);y.addGetterSetter(se,"fontVariant",Fa);y.addGetterSetter(se,"padding",0,E());y.addGetterSetter(se,"align",Ba);y.addGetterSetter(se,"verticalAlign",gc);y.addGetterSetter(se,"lineHeight",1,E());y.addGetterSetter(se,"wrap",Sc);y.addGetterSetter(se,"ellipsis",!1,Ae());y.addGetterSetter(se,"letterSpacing",0,E());y.addGetterSetter(se,"text","",lt());y.addGetterSetter(se,"textDecoration","");y.addGetterSetter(se,"underlineOffset",void 0,E());y.addGetterSetter(se,"charRenderFunc",void 0);const xc="",Ga="normal";function Na(n){n.fillText(this.partialText,0,0)}function za(n){n.strokeText(this.partialText,0,0)}class he extends A{constructor(e){super(e),this.dummyCanvas=b.createCanvasElement(),this.dataArray=[],this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute(),this._setTextData()}),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva fontFamilyChange.konva",this._setTextData),this._setTextData()}_getTextPathLength(){return re.getPathLength(this.dataArray)}_getPointAtLength(e){if(!this.attrs.data)return null;const t=this.pathLength;return e>t?null:re.getPointAtLengthOfDataArray(e,this.dataArray)}_readDataAttribute(){this.dataArray=re.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(e){e.setAttr("font",this._getContextFont()),e.setAttr("textBaseline",this.textBaseline()),e.setAttr("textAlign","left"),e.save();const t=this.textDecoration(),i=this.fill(),r=this.fontSize(),s=this.glyphInfo,a=t.indexOf("underline")!==-1,o=t.indexOf("line-through")!==-1;a&&e.beginPath();for(let l=0;l<s.length;l++){e.save();const c=s[l].p0;e.translate(c.x,c.y),e.rotate(s[l].rotation),this.partialText=s[l].text,e.fillStrokeShape(this),a&&(l===0&&e.moveTo(0,r/2+1),e.lineTo(s[l].width,r/2+1)),e.restore()}if(a&&(e.strokeStyle=i,e.lineWidth=r/20,e.stroke()),o){e.beginPath();for(let l=0;l<s.length;l++){e.save();const c=s[l].p0;e.translate(c.x,c.y),e.rotate(s[l].rotation),l===0&&e.moveTo(0,0),e.lineTo(s[l].width,0),e.restore()}e.strokeStyle=i,e.lineWidth=r/20,e.stroke()}e.restore()}_hitFunc(e){e.beginPath();const t=this.glyphInfo;if(t.length>=1){const i=t[0].p0;e.moveTo(i.x,i.y)}for(let i=0;i<t.length;i++){const r=t[i].p1;e.lineTo(r.x,r.y)}e.setAttr("lineWidth",this.fontSize()),e.setAttr("strokeStyle",this.colorKey),e.stroke()}getTextWidth(){return this.textWidth}getTextHeight(){return b.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}setText(e){return se.prototype.setText.call(this,e)}_getContextFont(){return se.prototype._getContextFont.call(this)}_getTextSize(e){const i=this.dummyCanvas.getContext("2d");i.save(),i.font=this._getContextFont();const r=i.measureText(e);return i.restore(),{width:r.width,height:parseInt(`${this.fontSize()}`,10)}}_setTextData(){const e=Ve(this.text()),t=[];let i=0;for(let d=0;d<e.length;d++)t.push({char:e[d],width:this._getTextSize(e[d]).width}),i+=t[d].width;const{height:r}=this._getTextSize(this.attrs.text);if(this.textWidth=i,this.textHeight=r,this.glyphInfo=[],!this.attrs.data)return null;const s=this.letterSpacing(),a=this.align(),o=this.kerningFunc(),l=Math.max(this.textWidth+((this.attrs.text||"").length-1)*s,0);let c=0;a==="center"&&(c=Math.max(0,this.pathLength/2-l/2)),a==="right"&&(c=Math.max(0,this.pathLength-l));let h=c;for(let d=0;d<t.length;d++){const u=this._getPointAtLength(h);if(!u)return;const g=t[d].char;let f=t[d].width+s;if(g===" "&&a==="justify"){const k=this.text().split(" ").length-1;f+=(this.pathLength-l)/k}const m=this._getPointAtLength(h+f);if(!m)return;const C=re.getLineLength(u.x,u.y,m.x,m.y);let v=0;if(o)try{v=o(t[d-1].char,g)*this.fontSize()}catch{v=0}u.x+=v,m.x+=v,this.textWidth+=v;const S=re.getPointOnLine(v+C/2,u.x,u.y,m.x,m.y),T=Math.atan2(m.y-u.y,m.x-u.x);this.glyphInfo.push({transposeX:S.x,transposeY:S.y,text:e[d],rotation:T,p0:u,p1:m,width:C}),h+=f}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const e=[];this.glyphInfo.forEach(function(c){e.push(c.p0.x),e.push(c.p0.y),e.push(c.p1.x),e.push(c.p1.y)});let t=e[0]||0,i=e[0]||0,r=e[1]||0,s=e[1]||0,a,o;for(let c=0;c<e.length/2;c++)a=e[c*2],o=e[c*2+1],t=Math.min(t,a),i=Math.max(i,a),r=Math.min(r,o),s=Math.max(s,o);const l=this.fontSize();return{x:t-l/2,y:r-l/2,width:i-t+l,height:s-r+l}}destroy(){return b.releaseCanvas(this.dummyCanvas),super.destroy()}}he.prototype._fillFunc=Na;he.prototype._strokeFunc=za;he.prototype._fillFuncHit=Na;he.prototype._strokeFuncHit=za;he.prototype.className="TextPath";he.prototype._attrsAffectingSize=["text","fontSize","data"];ae(he);y.addGetterSetter(he,"data");y.addGetterSetter(he,"fontFamily","Arial");y.addGetterSetter(he,"fontSize",12,E());y.addGetterSetter(he,"fontStyle",Ga);y.addGetterSetter(he,"align","left");y.addGetterSetter(he,"letterSpacing",0,E());y.addGetterSetter(he,"textBaseline","middle");y.addGetterSetter(he,"fontVariant",Ga);y.addGetterSetter(he,"text",xc);y.addGetterSetter(he,"textDecoration","");y.addGetterSetter(he,"kerningFunc",void 0);const $a="tr-konva",Pc=["resizeEnabledChange","rotateAnchorOffsetChange","rotateAnchorAngleChange","rotateEnabledChange","enabledAnchorsChange","anchorSizeChange","borderEnabledChange","borderStrokeChange","borderStrokeWidthChange","borderDashChange","anchorStrokeChange","anchorStrokeWidthChange","anchorFillChange","anchorCornerRadiusChange","ignoreStrokeChange","anchorStyleFuncChange"].map(n=>n+`.${$a}`).join(" "),Qs="nodesRect",_c=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],Ac={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},Ic="ontouchstart"in M._global;function Ec(n,e,t){if(n==="rotater")return t;e+=b.degToRad(Ac[n]||0);const i=(b.radToDeg(e)%360+360)%360;return b._inRange(i,315+22.5,360)||b._inRange(i,0,22.5)?"ns-resize":b._inRange(i,45-22.5,45+22.5)?"nesw-resize":b._inRange(i,90-22.5,90+22.5)?"ew-resize":b._inRange(i,135-22.5,135+22.5)?"nwse-resize":b._inRange(i,180-22.5,180+22.5)?"ns-resize":b._inRange(i,225-22.5,225+22.5)?"nesw-resize":b._inRange(i,270-22.5,270+22.5)?"ew-resize":b._inRange(i,315-22.5,315+22.5)?"nwse-resize":(b.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}const qi=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function Rc(n){return{x:n.x+n.width/2*Math.cos(n.rotation)+n.height/2*Math.sin(-n.rotation),y:n.y+n.height/2*Math.cos(n.rotation)+n.width/2*Math.sin(n.rotation)}}function Va(n,e,t){const i=t.x+(n.x-t.x)*Math.cos(e)-(n.y-t.y)*Math.sin(e),r=t.y+(n.x-t.x)*Math.sin(e)+(n.y-t.y)*Math.cos(e);return{...n,rotation:n.rotation+e,x:i,y:r}}function Mc(n,e){const t=Rc(n);return Va(n,e,t)}function Lc(n,e,t){let i=e;for(let r=0;r<n.length;r++){const s=M.getAngle(n[r]),a=Math.abs(s-e)%(Math.PI*2);Math.min(a,Math.PI*2-a)<t&&(i=s)}return i}let Wr=0;class W extends wt{constructor(e){super(e),this._movingAnchorName=null,this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(Pc,this.update),this.getNode()&&this.update()}attachTo(e){return this.setNode(e),this}setNode(e){return b.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([e])}getNode(){return this._nodes&&this._nodes[0]}_getEventNamespace(){return $a+this._id}setNodes(e=[]){this._nodes&&this._nodes.length&&this.detach();const t=e.filter(r=>r.isAncestorOf(this)?(b.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=e=t,e.length===1&&this.useSingleNodeRotation()?this.rotation(e[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(r=>{const s=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(r._attrsAffectingSize.length){const a=r._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");r.on(a,s)}r.on(_c.map(a=>a+`.${this._getEventNamespace()}`).join(" "),s),r.on(`absoluteTransformChange.${this._getEventNamespace()}`,s),this._proxyDrag(r)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(e){let t;e.on(`dragstart.${this._getEventNamespace()}`,i=>{t=e.getAbsolutePosition(),!this.isDragging()&&e!==this.findOne(".back")&&this.startDrag(i,!1)}),e.on(`dragmove.${this._getEventNamespace()}`,i=>{if(!t)return;const r=e.getAbsolutePosition(),s=r.x-t.x,a=r.y-t.y;this.nodes().forEach(o=>{if(o===e||o.isDragging())return;const l=o.getAbsolutePosition();o.setAbsolutePosition({x:l.x+s,y:l.y+a}),o.startDrag(i)}),t=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(e=>{e.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(Qs),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(Qs,this.__getNodeRect)}__getNodeShape(e,t=this.rotation(),i){const r=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),s=e.getAbsoluteScale(i),a=e.getAbsolutePosition(i),o=r.x*s.x-e.offsetX()*s.x,l=r.y*s.y-e.offsetY()*s.y,c=(M.getAngle(e.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),h={x:a.x+o*Math.cos(c)+l*Math.sin(-c),y:a.y+l*Math.cos(c)+o*Math.sin(c),width:r.width*s.x,height:r.height*s.y,rotation:c};return Va(h,-M.getAngle(t),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(c=>{const h=c.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),d=[{x:h.x,y:h.y},{x:h.x+h.width,y:h.y},{x:h.x+h.width,y:h.y+h.height},{x:h.x,y:h.y+h.height}],u=c.getAbsoluteTransform();d.forEach(function(g){const f=u.point(g);t.push(f)})});const i=new ve;i.rotate(-M.getAngle(this.rotation()));let r=1/0,s=1/0,a=-1/0,o=-1/0;t.forEach(function(c){const h=i.point(c);r===void 0&&(r=a=h.x,s=o=h.y),r=Math.min(r,h.x),s=Math.min(s,h.y),a=Math.max(a,h.x),o=Math.max(o,h.y)}),i.invert();const l=i.point({x:r,y:s});return{x:l.x,y:l.y,width:a-r,height:o-s,rotation:M.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),qi.forEach(e=>{this._createAnchor(e)}),this._createAnchor("rotater")}_createAnchor(e){const t=new vi({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:e+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:Ic?10:"auto"}),i=this;t.on("mousedown touchstart",function(r){i._handleMouseDown(r)}),t.on("dragstart",r=>{t.stopDrag(),r.cancelBubble=!0}),t.on("dragend",r=>{r.cancelBubble=!0}),t.on("mouseenter",()=>{const r=M.getAngle(this.rotation()),s=this.rotateAnchorCursor(),a=Ec(e,r,s);t.getStage().content&&(t.getStage().content.style.cursor=a),this._cursorChange=!0}),t.on("mouseout",()=>{t.getStage().content&&(t.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(t)}_createBack(){const e=new A({name:"back",width:0,height:0,sceneFunc(t,i){const r=i.getParent(),s=r.padding(),a=i.width(),o=i.height();if(t.beginPath(),t.rect(-s,-s,a+s*2,o+s*2),r.rotateEnabled()&&r.rotateLineVisible()){const l=r.rotateAnchorAngle(),c=r.rotateAnchorOffset(),h=b.degToRad(l),d=Math.sin(h),u=-Math.cos(h),g=a/2,f=o/2;let m=1/0;u<0?m=Math.min(m,-f/u):u>0&&(m=Math.min(m,(o-f)/u)),d<0?m=Math.min(m,-g/d):d>0&&(m=Math.min(m,(a-g)/d));const C=g+d*m,v=f+u*m,S=b._sign(o),T=C+d*c*S,k=v+u*c*S;t.moveTo(C,v),t.lineTo(T,k)}t.fillStrokeShape(i)},hitFunc:(t,i)=>{if(!this.shouldOverdrawWholeArea())return;const r=this.padding();t.beginPath(),t.rect(-r,-r,i.width()+r*2,i.height()+r*2),t.fillStrokeShape(i)}});this.add(e),this._proxyDrag(e),e.on("dragstart",t=>{t.cancelBubble=!0}),e.on("dragmove",t=>{t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),this.on("dragmove",t=>{this.update()})}_handleMouseDown(e){if(this._transforming)return;this._movingAnchorName=e.target.name().split(" ")[0];const t=this._getNodeRect(),i=t.width,r=t.height,s=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));this.sin=Math.abs(r/s),this.cos=Math.abs(i/s),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const a=e.target.getAbsolutePosition(),o=e.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-a.x,y:o.y-a.y},Wr++,this._fire("transformstart",{evt:e.evt,target:this.getNode()}),this._nodes.forEach(l=>{l._fire("transformstart",{evt:e.evt,target:l})})}_handleMouseMove(e){let t,i,r;const s=this.findOne("."+this._movingAnchorName),a=s.getStage();a.setPointersPositions(e);const o=a.getPointerPosition();let l={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const c=s.getAbsolutePosition();this.anchorDragBoundFunc()&&(l=this.anchorDragBoundFunc()(c,l,e)),s.setAbsolutePosition(l);const h=s.getAbsolutePosition();if(c.x===h.x&&c.y===h.y)return;if(this._movingAnchorName==="rotater"){const S=this._getNodeRect();t=s.x()-S.width/2,i=-s.y()+S.height/2;const T=M.getAngle(this.rotateAnchorAngle());let k=Math.atan2(-i,t)+Math.PI/2-T;S.height<0&&(k-=Math.PI);const w=M.getAngle(this.rotation())+k,D=M.getAngle(this.rotationSnapTolerance()),R=Lc(this.rotationSnaps(),w,D)-S.rotation,O=Mc(S,R);this._fitNodesInto(O,e);return}const d=this.shiftBehavior();let u;d==="inverted"?u=this.keepRatio()&&!e.shiftKey:d==="none"?u=this.keepRatio():u=this.keepRatio()||e.shiftKey;let g=this.centeredScaling()||e.altKey;if(this._movingAnchorName==="top-left"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};r=Math.sqrt(Math.pow(S.x-s.x(),2)+Math.pow(S.y-s.y(),2));const T=this.findOne(".top-left").x()>S.x?-1:1,k=this.findOne(".top-left").y()>S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,this.findOne(".top-left").x(S.x-t),this.findOne(".top-left").y(S.y-i)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(s.y());else if(this._movingAnchorName==="top-right"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};r=Math.sqrt(Math.pow(s.x()-S.x,2)+Math.pow(S.y-s.y(),2));const T=this.findOne(".top-right").x()<S.x?-1:1,k=this.findOne(".top-right").y()>S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,this.findOne(".top-right").x(S.x+t),this.findOne(".top-right").y(S.y-i)}var f=s.position();this.findOne(".top-left").y(f.y),this.findOne(".bottom-right").x(f.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(s.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(s.x());else if(this._movingAnchorName==="bottom-left"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};r=Math.sqrt(Math.pow(S.x-s.x(),2)+Math.pow(s.y()-S.y,2));const T=S.x<s.x()?-1:1,k=s.y()<S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,s.x(S.x-t),s.y(S.y+i)}f=s.position(),this.findOne(".top-left").x(f.x),this.findOne(".bottom-right").y(f.y)}else if(this._movingAnchorName==="bottom-center")this.findOne(".bottom-right").y(s.y());else if(this._movingAnchorName==="bottom-right"){if(u){const S=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-left").x(),y:this.findOne(".top-left").y()};r=Math.sqrt(Math.pow(s.x()-S.x,2)+Math.pow(s.y()-S.y,2));const T=this.findOne(".bottom-right").x()<S.x?-1:1,k=this.findOne(".bottom-right").y()<S.y?-1:1;t=r*this.cos*T,i=r*this.sin*k,this.findOne(".bottom-right").x(S.x+t),this.findOne(".bottom-right").y(S.y+i)}}else console.error(new Error("Wrong position argument of selection resizer: "+this._movingAnchorName));if(g=this.centeredScaling()||e.altKey,g){const S=this.findOne(".top-left"),T=this.findOne(".bottom-right"),k=S.x(),_=S.y(),w=this.getWidth()-T.x(),D=this.getHeight()-T.y();T.move({x:-k,y:-_}),S.move({x:w,y:D})}const m=this.findOne(".top-left").getAbsolutePosition();t=m.x,i=m.y;const C=this.findOne(".bottom-right").x()-this.findOne(".top-left").x(),v=this.findOne(".bottom-right").y()-this.findOne(".top-left").y();this._fitNodesInto({x:t,y:i,width:C,height:v,rotation:M.getAngle(this.rotation())},e)}_handleMouseUp(e){this._removeEvents(e)}getAbsoluteTransform(){return this.getTransform()}_removeEvents(e){var t;if(this._transforming){this._transforming=!1,typeof window<"u"&&(window.removeEventListener("mousemove",this._handleMouseMove),window.removeEventListener("touchmove",this._handleMouseMove),window.removeEventListener("mouseup",this._handleMouseUp,!0),window.removeEventListener("touchend",this._handleMouseUp,!0));const i=this.getNode();Wr--,this._fire("transformend",{evt:e,target:i}),(t=this.getLayer())===null||t===void 0||t.batchDraw(),i&&this._nodes.forEach(r=>{var s;r._fire("transformend",{evt:e,target:r}),(s=r.getLayer())===null||s===void 0||s.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(e,t){const i=this._getNodeRect(),r=1;if(b._inRange(e.width,-this.padding()*2-r,r)){this.update();return}if(b._inRange(e.height,-this.padding()*2-r,r)){this.update();return}const s=new ve;if(s.rotate(M.getAngle(this.rotation())),this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("left")>=0){const u=s.point({x:-this.padding()*2,y:0});e.x+=u.x,e.y+=u.y,e.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y}else if(this._movingAnchorName&&e.width<0&&this._movingAnchorName.indexOf("right")>=0){const u=s.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.width+=this.padding()*2}if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("top")>=0){const u=s.point({x:0,y:-this.padding()*2});e.x+=u.x,e.y+=u.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}else if(this._movingAnchorName&&e.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const u=s.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=u.x,this._anchorDragOffset.y-=u.y,e.height+=this.padding()*2}if(this.boundBoxFunc()){const u=this.boundBoxFunc()(i,e);u?e=u:b.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const a=1e7,o=new ve;o.translate(i.x,i.y),o.rotate(i.rotation),o.scale(i.width/a,i.height/a);const l=new ve,c=e.width/a,h=e.height/a;this.flipEnabled()===!1?(l.translate(e.x,e.y),l.rotate(e.rotation),l.translate(e.width<0?e.width:0,e.height<0?e.height:0),l.scale(Math.abs(c),Math.abs(h))):(l.translate(e.x,e.y),l.rotate(e.rotation),l.scale(c,h));const d=l.multiply(o.invert());this._nodes.forEach(u=>{var g;if(!u.getStage())return;const f=u.getParent().getAbsoluteTransform(),m=u.getTransform().copy();m.translate(u.offsetX(),u.offsetY());const C=new ve;C.multiply(f.copy().invert()).multiply(d).multiply(f).multiply(m);const v=C.decompose();u.setAttrs(v),(g=u.getLayer())===null||g===void 0||g.batchDraw()}),this.rotation(b._getRotation(e.rotation)),this._nodes.forEach(u=>{this._fire("transform",{evt:t,target:u}),u._fire("transform",{evt:t,target:u})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(e,t){this.findOne(e).setAttrs(t)}update(){var e;const t=this._getNodeRect();this.rotation(b._getRotation(t.rotation));const i=t.width,r=t.height,s=this.enabledAnchors(),a=this.resizeEnabled(),o=this.padding(),l=this.anchorSize(),c=this.find("._anchor");c.forEach(w=>{w.setAttrs({width:l,height:l,offsetX:l/2,offsetY:l/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:l/2+o,offsetY:l/2+o,visible:a&&s.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:l/2+o,visible:a&&s.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:l/2-o,offsetY:l/2+o,visible:a&&s.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:l/2+o,visible:a&&s.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:l/2-o,visible:a&&s.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:l/2+o,offsetY:l/2-o,visible:a&&s.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:l/2-o,visible:a&&s.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:l/2-o,offsetY:l/2-o,visible:a&&s.indexOf("bottom-right")>=0});const h=this.rotateAnchorAngle(),d=this.rotateAnchorOffset(),u=b.degToRad(h),g=Math.sin(u),f=-Math.cos(u),m=i/2,C=r/2;let v=1/0;f<0?v=Math.min(v,-C/f):f>0&&(v=Math.min(v,(r-C)/f)),g<0?v=Math.min(v,-m/g):g>0&&(v=Math.min(v,(i-m)/g));const S=m+g*v,T=C+f*v,k=b._sign(r);this._batchChangeChild(".rotater",{x:S+g*d*k,y:T+f*d*k-o*f,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(w=>w.draggable()),x:0,y:0});const _=this.anchorStyleFunc();_&&c.forEach(w=>{_(w)}),(e=this.getLayer())===null||e===void 0||e.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const e=this.findOne("."+this._movingAnchorName);e&&e.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),wt.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return I.prototype.toObject.call(this)}clone(e){return I.prototype.clone.call(this,e)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}}W.isTransforming=()=>Wr>0;function Dc(n){return n instanceof Array||b.warn("enabledAnchors value should be an array"),n instanceof Array&&n.forEach(function(e){qi.indexOf(e)===-1&&b.warn("Unknown anchor name: "+e+". Available names are: "+qi.join(", "))}),n||[]}W.prototype.className="Transformer";ae(W);y.addGetterSetter(W,"enabledAnchors",qi,Dc);y.addGetterSetter(W,"flipEnabled",!0,Ae());y.addGetterSetter(W,"resizeEnabled",!0);y.addGetterSetter(W,"anchorSize",10,E());y.addGetterSetter(W,"rotateEnabled",!0);y.addGetterSetter(W,"rotateLineVisible",!0);y.addGetterSetter(W,"rotationSnaps",[]);y.addGetterSetter(W,"rotateAnchorOffset",50,E());y.addGetterSetter(W,"rotateAnchorAngle",0,E());y.addGetterSetter(W,"rotateAnchorCursor","crosshair");y.addGetterSetter(W,"rotationSnapTolerance",5,E());y.addGetterSetter(W,"borderEnabled",!0);y.addGetterSetter(W,"anchorStroke","rgb(0, 161, 255)");y.addGetterSetter(W,"anchorStrokeWidth",1,E());y.addGetterSetter(W,"anchorFill","white");y.addGetterSetter(W,"anchorCornerRadius",0,E());y.addGetterSetter(W,"borderStroke","rgb(0, 161, 255)");y.addGetterSetter(W,"borderStrokeWidth",1,E());y.addGetterSetter(W,"borderDash");y.addGetterSetter(W,"keepRatio",!0);y.addGetterSetter(W,"shiftBehavior","default");y.addGetterSetter(W,"centeredScaling",!1);y.addGetterSetter(W,"ignoreStroke",!1);y.addGetterSetter(W,"padding",0,E());y.addGetterSetter(W,"nodes");y.addGetterSetter(W,"node");y.addGetterSetter(W,"boundBoxFunc");y.addGetterSetter(W,"anchorDragBoundFunc");y.addGetterSetter(W,"anchorStyleFunc");y.addGetterSetter(W,"shouldOverdrawWholeArea",!1);y.addGetterSetter(W,"useSingleNodeRotation",!0);y.backCompat(W,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class He extends A{_sceneFunc(e){e.beginPath(),e.arc(0,0,this.radius(),0,M.getAngle(this.angle()),this.clockwise()),e.lineTo(0,0),e.closePath(),e.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(e){this.radius(e/2)}setHeight(e){this.radius(e/2)}}He.prototype.className="Wedge";He.prototype._centroid=!0;He.prototype._attrsAffectingSize=["radius"];ae(He);y.addGetterSetter(He,"radius",0,E());y.addGetterSetter(He,"angle",0,E());y.addGetterSetter(He,"clockwise",!1);y.backCompat(He,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function en(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const Oc=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],Bc=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function Fc(n,e){const t=n.data,i=n.width,r=n.height;let s,a,o,l,c,h,d,u,g,f,m,C,v,S,T,k,_,w,D,x;const R=e+e+1,O=i-1,z=r-1,H=e+1,$=H*(H+1)/2,V=new en,G=Oc[e],L=Bc[e];let X=null,B=V,Q=null,ne=null;for(let Y=1;Y<R;Y++)B=B.next=new en,Y===H&&(X=B);B.next=V,o=a=0;for(let Y=0;Y<r;Y++){C=v=S=T=l=c=h=d=0,u=H*(k=t[a]),g=H*(_=t[a+1]),f=H*(w=t[a+2]),m=H*(D=t[a+3]),l+=$*k,c+=$*_,h+=$*w,d+=$*D,B=V;for(let K=0;K<H;K++)B.r=k,B.g=_,B.b=w,B.a=D,B=B.next;for(let K=1;K<H;K++)s=a+((O<K?O:K)<<2),l+=(B.r=k=t[s])*(x=H-K),c+=(B.g=_=t[s+1])*x,h+=(B.b=w=t[s+2])*x,d+=(B.a=D=t[s+3])*x,C+=k,v+=_,S+=w,T+=D,B=B.next;Q=V,ne=X;for(let K=0;K<i;K++)t[a+3]=D=d*G>>L,D!==0?(D=255/D,t[a]=(l*G>>L)*D,t[a+1]=(c*G>>L)*D,t[a+2]=(h*G>>L)*D):t[a]=t[a+1]=t[a+2]=0,l-=u,c-=g,h-=f,d-=m,u-=Q.r,g-=Q.g,f-=Q.b,m-=Q.a,s=o+((s=K+e+1)<O?s:O)<<2,C+=Q.r=t[s],v+=Q.g=t[s+1],S+=Q.b=t[s+2],T+=Q.a=t[s+3],l+=C,c+=v,h+=S,d+=T,Q=Q.next,u+=k=ne.r,g+=_=ne.g,f+=w=ne.b,m+=D=ne.a,C-=k,v-=_,S-=w,T-=D,ne=ne.next,a+=4;o+=i}for(let Y=0;Y<i;Y++){v=S=T=C=c=h=d=l=0,a=Y<<2,u=H*(k=t[a]),g=H*(_=t[a+1]),f=H*(w=t[a+2]),m=H*(D=t[a+3]),l+=$*k,c+=$*_,h+=$*w,d+=$*D,B=V;for(let me=0;me<H;me++)B.r=k,B.g=_,B.b=w,B.a=D,B=B.next;let K=i;for(let me=1;me<=e;me++)a=K+Y<<2,l+=(B.r=k=t[a])*(x=H-me),c+=(B.g=_=t[a+1])*x,h+=(B.b=w=t[a+2])*x,d+=(B.a=D=t[a+3])*x,C+=k,v+=_,S+=w,T+=D,B=B.next,me<z&&(K+=i);a=Y,Q=V,ne=X;for(let me=0;me<r;me++)s=a<<2,t[s+3]=D=d*G>>L,D>0?(D=255/D,t[s]=(l*G>>L)*D,t[s+1]=(c*G>>L)*D,t[s+2]=(h*G>>L)*D):t[s]=t[s+1]=t[s+2]=0,l-=u,c-=g,h-=f,d-=m,u-=Q.r,g-=Q.g,f-=Q.b,m-=Q.a,s=Y+((s=me+H)<z?s:z)*i<<2,l+=C+=Q.r=t[s],c+=v+=Q.g=t[s+1],h+=S+=Q.b=t[s+2],d+=T+=Q.a=t[s+3],Q=Q.next,u+=k=ne.r,g+=_=ne.g,f+=w=ne.b,m+=D=ne.a,C-=k,v-=_,S-=w,T-=D,ne=ne.next,a+=i}}const Hc=function(e){const t=Math.round(this.blurRadius());t>0&&Fc(e,t)};y.addGetterSetter(I,"blurRadius",0,E(),y.afterSetFilter);const Gc=function(n){const e=this.brightness()*255,t=n.data,i=t.length;for(let r=0;r<i;r+=4)t[r]+=e,t[r+1]+=e,t[r+2]+=e};y.addGetterSetter(I,"brightness",0,E(),y.afterSetFilter);const Nc=function(n){const e=this.brightness(),t=n.data,i=t.length;for(let r=0;r<i;r+=4)t[r]=Math.min(255,t[r]*e),t[r+1]=Math.min(255,t[r+1]*e),t[r+2]=Math.min(255,t[r+2]*e)},zc=function(n){const e=Math.pow((this.contrast()+100)/100,2),t=n.data,i=t.length;let r=150,s=150,a=150;for(let o=0;o<i;o+=4)r=t[o],s=t[o+1],a=t[o+2],r/=255,r-=.5,r*=e,r+=.5,r*=255,s/=255,s-=.5,s*=e,s+=.5,s*=255,a/=255,a-=.5,a*=e,a+=.5,a*=255,r=r<0?0:r>255?255:r,s=s<0?0:s>255?255:s,a=a<0?0:a>255?255:a,t[o]=r,t[o+1]=s,t[o+2]=a};y.addGetterSetter(I,"contrast",0,E(),y.afterSetFilter);const $c=function(n){var e,t,i,r,s,a,o,l,c;const h=n.data,d=n.width,u=n.height,g=Math.min(1,Math.max(0,(t=(e=this.embossStrength)===null||e===void 0?void 0:e.call(this))!==null&&t!==void 0?t:.5)),f=Math.min(1,Math.max(0,(r=(i=this.embossWhiteLevel)===null||i===void 0?void 0:i.call(this))!==null&&r!==void 0?r:.5)),C=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(a=(s=this.embossDirection)===null||s===void 0?void 0:s.call(this))!==null&&a!==void 0?a:"top-left"])!==null&&o!==void 0?o:315,v=!!((c=(l=this.embossBlend)===null||l===void 0?void 0:l.call(this))!==null&&c!==void 0&&c),S=g*10,T=f*255,k=C*Math.PI/180,_=Math.cos(k),w=Math.sin(k),D=128/1020*S,x=new Uint8ClampedArray(h),R=new Float32Array(d*u);for(let V=0,G=0;G<h.length;G+=4,V++)R[V]=.2126*x[G]+.7152*x[G+1]+.0722*x[G+2];const O=[-1,0,1,-2,0,2,-1,0,1],z=[-1,-2,-1,0,0,0,1,2,1],H=[-d-1,-d,-d+1,-1,0,1,d-1,d,d+1],$=V=>V<0?0:V>255?255:V;for(let V=1;V<u-1;V++)for(let G=1;G<d-1;G++){const L=V*d+G;let X=0,B=0;X+=R[L+H[0]]*O[0],B+=R[L+H[0]]*z[0],X+=R[L+H[1]]*O[1],B+=R[L+H[1]]*z[1],X+=R[L+H[2]]*O[2],B+=R[L+H[2]]*z[2],X+=R[L+H[3]]*O[3],B+=R[L+H[3]]*z[3],X+=R[L+H[5]]*O[5],B+=R[L+H[5]]*z[5],X+=R[L+H[6]]*O[6],B+=R[L+H[6]]*z[6],X+=R[L+H[7]]*O[7],B+=R[L+H[7]]*z[7],X+=R[L+H[8]]*O[8],B+=R[L+H[8]]*z[8];const Q=_*X+w*B,ne=$(T+Q*D),Y=L*4;if(v){const K=ne-T;h[Y]=$(x[Y]+K),h[Y+1]=$(x[Y+1]+K),h[Y+2]=$(x[Y+2]+K),h[Y+3]=x[Y+3]}else h[Y]=h[Y+1]=h[Y+2]=ne,h[Y+3]=x[Y+3]}for(let V=0;V<d;V++){let G=V*4,L=((u-1)*d+V)*4;h[G]=x[G],h[G+1]=x[G+1],h[G+2]=x[G+2],h[G+3]=x[G+3],h[L]=x[L],h[L+1]=x[L+1],h[L+2]=x[L+2],h[L+3]=x[L+3]}for(let V=1;V<u-1;V++){let G=V*d*4,L=(V*d+(d-1))*4;h[G]=x[G],h[G+1]=x[G+1],h[G+2]=x[G+2],h[G+3]=x[G+3],h[L]=x[L],h[L+1]=x[L+1],h[L+2]=x[L+2],h[L+3]=x[L+3]}return n};y.addGetterSetter(I,"embossStrength",.5,E(),y.afterSetFilter);y.addGetterSetter(I,"embossWhiteLevel",.5,E(),y.afterSetFilter);y.addGetterSetter(I,"embossDirection","top-left",void 0,y.afterSetFilter);y.addGetterSetter(I,"embossBlend",!1,void 0,y.afterSetFilter);function Tr(n,e,t,i,r){const s=t-e,a=r-i;if(s===0)return i+a/2;if(a===0)return i;let o=(n-e)/s;return o=a*o+i,o}const Vc=function(n){const e=n.data,t=e.length;let i=e[0],r=i,s,a=e[1],o=a,l,c=e[2],h=c,d;const u=this.enhance();if(u===0)return;for(let T=0;T<t;T+=4)s=e[T+0],s<i?i=s:s>r&&(r=s),l=e[T+1],l<a?a=l:l>o&&(o=l),d=e[T+2],d<c?c=d:d>h&&(h=d);r===i&&(r=255,i=0),o===a&&(o=255,a=0),h===c&&(h=255,c=0);let g,f,m,C,v,S;if(u>0)g=r+u*(255-r),f=i-u*(i-0),m=o+u*(255-o),C=a-u*(a-0),v=h+u*(255-h),S=c-u*(c-0);else{const T=(r+i)*.5;g=r+u*(r-T),f=i+u*(i-T);const k=(o+a)*.5;m=o+u*(o-k),C=a+u*(a-k);const _=(h+c)*.5;v=h+u*(h-_),S=c+u*(c-_)}for(let T=0;T<t;T+=4)e[T+0]=Tr(e[T+0],i,r,f,g),e[T+1]=Tr(e[T+1],a,o,C,m),e[T+2]=Tr(e[T+2],c,h,S,v)};y.addGetterSetter(I,"enhance",0,E(),y.afterSetFilter);const Uc=function(n){const e=n.data,t=e.length;for(let i=0;i<t;i+=4){const r=.34*e[i]+.5*e[i+1]+.16*e[i+2];e[i]=r,e[i+1]=r,e[i+2]=r}};y.addGetterSetter(I,"hue",0,E(),y.afterSetFilter);y.addGetterSetter(I,"saturation",0,E(),y.afterSetFilter);y.addGetterSetter(I,"luminance",0,E(),y.afterSetFilter);const Wc=function(n){const e=n.data,t=e.length,i=1,r=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=this.luminance()*127,o=i*r*Math.cos(s*Math.PI/180),l=i*r*Math.sin(s*Math.PI/180),c=.299*i+.701*o+.167*l,h=.587*i-.587*o+.33*l,d=.114*i-.114*o-.497*l,u=.299*i-.299*o-.328*l,g=.587*i+.413*o+.035*l,f=.114*i-.114*o+.293*l,m=.299*i-.3*o+1.25*l,C=.587*i-.586*o-1.05*l,v=.114*i+.886*o-.2*l;let S,T,k,_;for(let w=0;w<t;w+=4)S=e[w+0],T=e[w+1],k=e[w+2],_=e[w+3],e[w+0]=c*S+h*T+d*k+a,e[w+1]=u*S+g*T+f*k+a,e[w+2]=m*S+C*T+v*k+a,e[w+3]=_},Yc=function(n){const e=n.data,t=e.length,i=Math.pow(2,this.value()),r=Math.pow(2,this.saturation()),s=Math.abs(this.hue()+360)%360,a=i*r*Math.cos(s*Math.PI/180),o=i*r*Math.sin(s*Math.PI/180),l=.299*i+.701*a+.167*o,c=.587*i-.587*a+.33*o,h=.114*i-.114*a-.497*o,d=.299*i-.299*a-.328*o,u=.587*i+.413*a+.035*o,g=.114*i-.114*a+.293*o,f=.299*i-.3*a+1.25*o,m=.587*i-.586*a-1.05*o,C=.114*i+.886*a-.2*o;for(let v=0;v<t;v+=4){const S=e[v+0],T=e[v+1],k=e[v+2],_=e[v+3];e[v+0]=l*S+c*T+h*k,e[v+1]=d*S+u*T+g*k,e[v+2]=f*S+m*T+C*k,e[v+3]=_}};y.addGetterSetter(I,"hue",0,E(),y.afterSetFilter);y.addGetterSetter(I,"saturation",0,E(),y.afterSetFilter);y.addGetterSetter(I,"value",0,E(),y.afterSetFilter);const Xc=function(n){const e=n.data,t=e.length;for(let i=0;i<t;i+=4)e[i]=255-e[i],e[i+1]=255-e[i+1],e[i+2]=255-e[i+2]},jc=function(n,e,t){const i=n.data,r=e.data,s=n.width,a=n.height,o=t.polarCenterX||s/2,l=t.polarCenterY||a/2;let c=Math.sqrt(o*o+l*l),h=s-o,d=a-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const g=a,f=s,m=360/f*Math.PI/180;for(let C=0;C<f;C+=1){const v=Math.sin(C*m),S=Math.cos(C*m);for(let T=0;T<g;T+=1){h=Math.floor(o+c*T/g*S),d=Math.floor(l+c*T/g*v);let k=(d*s+h)*4;const _=i[k+0],w=i[k+1],D=i[k+2],x=i[k+3];k=(C+T*s)*4,r[k+0]=_,r[k+1]=w,r[k+2]=D,r[k+3]=x}}},qc=function(n,e,t){const i=n.data,r=e.data,s=n.width,a=n.height,o=t.polarCenterX||s/2,l=t.polarCenterY||a/2;let c=Math.sqrt(o*o+l*l),h=s-o,d=a-l;const u=Math.sqrt(h*h+d*d);c=u>c?u:c;const g=a,f=s,m=0;let C,v;for(h=0;h<s;h+=1)for(d=0;d<a;d+=1){const S=h-o,T=d-l,k=Math.sqrt(S*S+T*T)*g/c;let _=(Math.atan2(T,S)*180/Math.PI+360+m)%360;_=_*f/360,C=Math.floor(_),v=Math.floor(k);let w=(v*s+C)*4;const D=i[w+0],x=i[w+1],R=i[w+2],O=i[w+3];w=(d*s+h)*4,r[w+0]=D,r[w+1]=x,r[w+2]=R,r[w+3]=O}},Kc=function(n){const e=n.width,t=n.height;let i,r,s,a,o,l,c,h,d,u,g=Math.round(this.kaleidoscopePower());const f=Math.round(this.kaleidoscopeAngle()),m=Math.floor(e*(f%360)/360);if(g<1)return;const C=b.createCanvasElement();C.width=e,C.height=t;const v=C.getContext("2d").getImageData(0,0,e,t);b.releaseCanvas(C),jc(n,v,{polarCenterX:e/2,polarCenterY:t/2});let S=e/Math.pow(2,g);for(;S<=8;)S=S*2,g-=1;S=Math.ceil(S);let T=S,k=0,_=T,w=1;for(m+S>e&&(k=T,_=0,w=-1),r=0;r<t;r+=1)for(i=k;i!==_;i+=w)s=Math.round(i+m)%e,d=(e*r+s)*4,o=v.data[d+0],l=v.data[d+1],c=v.data[d+2],h=v.data[d+3],u=(e*r+i)*4,v.data[u+0]=o,v.data[u+1]=l,v.data[u+2]=c,v.data[u+3]=h;for(r=0;r<t;r+=1)for(T=Math.floor(S),a=0;a<g;a+=1){for(i=0;i<T+1;i+=1)d=(e*r+i)*4,o=v.data[d+0],l=v.data[d+1],c=v.data[d+2],h=v.data[d+3],u=(e*r+T*2-i-1)*4,v.data[u+0]=o,v.data[u+1]=l,v.data[u+2]=c,v.data[u+3]=h;T*=2}qc(v,n,{})};y.addGetterSetter(I,"kaleidoscopePower",2,E(),y.afterSetFilter);y.addGetterSetter(I,"kaleidoscopeAngle",0,E(),y.afterSetFilter);function Mi(n,e,t){let i=(t*n.width+e)*4;const r=[];return r.push(n.data[i++],n.data[i++],n.data[i++],n.data[i++]),r}function Bt(n,e){return Math.sqrt(Math.pow(n[0]-e[0],2)+Math.pow(n[1]-e[1],2)+Math.pow(n[2]-e[2],2))}function Zc(n){const e=[0,0,0];for(let t=0;t<n.length;t++)e[0]+=n[t][0],e[1]+=n[t][1],e[2]+=n[t][2];return e[0]/=n.length,e[1]/=n.length,e[2]/=n.length,e}function Jc(n,e){const t=Mi(n,0,0),i=Mi(n,n.width-1,0),r=Mi(n,0,n.height-1),s=Mi(n,n.width-1,n.height-1),a=e||10;if(Bt(t,i)<a&&Bt(i,s)<a&&Bt(s,r)<a&&Bt(r,t)<a){const o=Zc([i,t,s,r]),l=[];for(let c=0;c<n.width*n.height;c++){const h=Bt(o,[n.data[c*4],n.data[c*4+1],n.data[c*4+2]]);l[c]=h<a?0:255}return l}}function Qc(n,e){for(let t=0;t<n.width*n.height;t++)n.data[4*t+3]=e[t]}function eh(n,e,t){const i=[1,1,1,1,0,1,1,1,1],r=Math.round(Math.sqrt(i.length)),s=Math.floor(r/2),a=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-s,f=l+u-s;if(g>=0&&g<t&&f>=0&&f<e){const m=g*e+f,C=i[d*r+u];h+=n[m]*C}}a[c]=h===255*8?255:0}return a}function th(n,e,t){const i=[1,1,1,1,1,1,1,1,1],r=Math.round(Math.sqrt(i.length)),s=Math.floor(r/2),a=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-s,f=l+u-s;if(g>=0&&g<t&&f>=0&&f<e){const m=g*e+f,C=i[d*r+u];h+=n[m]*C}}a[c]=h>=255*4?255:0}return a}function ih(n,e,t){const i=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],r=Math.round(Math.sqrt(i.length)),s=Math.floor(r/2),a=[];for(let o=0;o<t;o++)for(let l=0;l<e;l++){const c=o*e+l;let h=0;for(let d=0;d<r;d++)for(let u=0;u<r;u++){const g=o+d-s,f=l+u-s;if(g>=0&&g<t&&f>=0&&f<e){const m=g*e+f,C=i[d*r+u];h+=n[m]*C}}a[c]=h}return a}const rh=function(n){const e=this.threshold();let t=Jc(n,e);return t&&(t=eh(t,n.width,n.height),t=th(t,n.width,n.height),t=ih(t,n.width,n.height),Qc(n,t)),n};y.addGetterSetter(I,"threshold",0,E(),y.afterSetFilter);const sh=function(n){const e=this.noise()*255,t=n.data,i=t.length,r=e/2;for(let s=0;s<i;s+=4)t[s+0]+=r-2*r*Math.random(),t[s+1]+=r-2*r*Math.random(),t[s+2]+=r-2*r*Math.random()};y.addGetterSetter(I,"noise",.2,E(),y.afterSetFilter);const nh=function(n){let e=Math.ceil(this.pixelSize()),t=n.width,i=n.height,r=Math.ceil(t/e),s=Math.ceil(i/e),a=n.data;if(e<=0){b.error("pixelSize value can not be <= 0");return}for(let o=0;o<r;o+=1)for(let l=0;l<s;l+=1){let c=0,h=0,d=0,u=0;const g=o*e,f=g+e,m=l*e,C=m+e;let v=0;for(let S=g;S<f;S+=1)if(!(S>=t))for(let T=m;T<C;T+=1){if(T>=i)continue;const k=(t*T+S)*4;c+=a[k+0],h+=a[k+1],d+=a[k+2],u+=a[k+3],v+=1}c=c/v,h=h/v,d=d/v,u=u/v;for(let S=g;S<f;S+=1)if(!(S>=t))for(let T=m;T<C;T+=1){if(T>=i)continue;const k=(t*T+S)*4;a[k+0]=c,a[k+1]=h,a[k+2]=d,a[k+3]=u}}};y.addGetterSetter(I,"pixelSize",8,E(),y.afterSetFilter);const ah=function(n){const e=Math.round(this.levels()*254)+1,t=n.data,i=t.length,r=255/e;for(let s=0;s<i;s+=1)t[s]=Math.floor(t[s]/r)*r};y.addGetterSetter(I,"levels",.5,E(),y.afterSetFilter);const oh=function(n){const e=n.data,t=e.length,i=this.red(),r=this.green(),s=this.blue();for(let a=0;a<t;a+=4){const o=(.34*e[a]+.5*e[a+1]+.16*e[a+2])/255;e[a]=o*i,e[a+1]=o*r,e[a+2]=o*s,e[a+3]=e[a+3]}};y.addGetterSetter(I,"red",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"green",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"blue",0,ua,y.afterSetFilter);const lh=function(n){const e=n.data,t=e.length,i=this.red(),r=this.green(),s=this.blue(),a=this.alpha();for(let o=0;o<t;o+=4){const l=1-a;e[o]=i*a+e[o]*l,e[o+1]=r*a+e[o+1]*l,e[o+2]=s*a+e[o+2]*l}};y.addGetterSetter(I,"red",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"green",0,function(n){return this._filterUpToDate=!1,n>255?255:n<0?0:Math.round(n)});y.addGetterSetter(I,"blue",0,ua,y.afterSetFilter);y.addGetterSetter(I,"alpha",1,function(n){return this._filterUpToDate=!1,n>1?1:n<0?0:n});const ch=function(n){const e=n.data,t=e.length;for(let i=0;i<t;i+=4){const r=e[i+0],s=e[i+1],a=e[i+2];e[i+0]=Math.min(255,r*.393+s*.769+a*.189),e[i+1]=Math.min(255,r*.349+s*.686+a*.168),e[i+2]=Math.min(255,r*.272+s*.534+a*.131)}},hh=function(n){const t=n.data;for(let i=0;i<t.length;i+=4){const r=t[i],s=t[i+1],a=t[i+2];.2126*r+.7152*s+.0722*a>=128&&(t[i]=255-r,t[i+1]=255-s,t[i+2]=255-a)}return n},dh=function(n){const e=this.threshold()*255,t=n.data,i=t.length;for(let r=0;r<i;r+=1)t[r]=t[r]<e?0:255};y.addGetterSetter(I,"threshold",.5,E(),y.afterSetFilter);const Z=Vs.Util._assign(Vs,{Arc:Be,Arrow:ht,Circle:It,Ellipse:Ze,Image:Ie,Label:ms,Tag:dt,Line:Fe,Path:re,Rect:vi,RegularPolygon:Je,Ring:ut,Sprite:De,Star:Qe,Text:se,TextPath:he,Transformer:W,Wedge:He,Filters:{Blur:Hc,Brightness:Nc,Brighten:Gc,Contrast:zc,Emboss:$c,Enhance:Vc,Grayscale:Uc,HSL:Wc,HSV:Yc,Invert:Xc,Kaleidoscope:Kc,Mask:rh,Noise:sh,Pixelate:nh,Posterize:ah,RGB:oh,RGBA:lh,Sepia:ch,Solarize:hh,Threshold:dh}}),Ua="media-editor-track.diagnostics.v1",Yr="media-editor-track.diagnostics.failure-window.v1",Wa="media-editor-track-diagnostics",Xe="snapshots",Ya="state",Xa="latest-failure-window",ui=1,ys=1,tn=40,uh=48,ph=250,rn=20,gh=100,fh=500,Xr=new Set(["pending-preview.begin","preview.sync.requested","media.seeking","media.seeked"]),mh=new Set([...Xr,"media.current-slot.seek","media.preload-slot.seek","media.play.requested","media.pause.requested","slot.recovery-check","runtime.state"]),sn={debug:10,info:20,warn:30,error:40},Ne={enabled:!0,persist:!0,storageQuotaMb:10,maxSessions:20,maxHotEvents:500,includeFullSourceUrl:!0,consoleSeverityThreshold:"error",highFrequencyEventThrottleMs:fh};function nn(n){return`${n}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,10)}`}function yh(){return typeof performance<"u"&&typeof performance.now=="function"?Number(performance.now().toFixed(3)):null}function ja(n){if(!n||typeof n!="object")return!1;const e=Object.getPrototypeOf(n);return e===Object.prototype||e===null}function bt(n,e,t){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n??null;if(typeof n=="bigint")return n.toString();if(n instanceof Error)return{name:n.name,message:n.message,stack:n.stack??null,cause:bt(n.cause,e+1,t)};if(e>=4)return"[max-depth]";if(Array.isArray(n))return n.slice(0,40).map(i=>bt(i,e+1,t));if(typeof n=="object"){if(t.has(n))return"[circular]";if(t.add(n),"tagName"in n&&typeof n.tagName=="string")return{tagName:n.tagName};if(!ja(n))return String(n);const i={};for(const r of Object.keys(n).slice(0,60))i[r]=bt(n[r],e+1,t);return i}return String(n)}function Ki(n){if(!n)return null;const e=bt(n,0,new WeakSet);return ja(e)?e:{value:e}}function Sh(n){return Ki(n)}function Ft(n){return typeof n=="number"&&Number.isFinite(n)?n:null}function Li(n){return typeof n=="string"&&n.length>0?n:null}function Ch(){var i,r,s,a,o;const n=typeof navigator<"u"?navigator:null,e={platform:Li(n==null?void 0:n.platform),hardwareConcurrency:Ft(n==null?void 0:n.hardwareConcurrency),deviceMemory:Ft(n==null?void 0:n.deviceMemory),maxTouchPoints:Ft(n==null?void 0:n.maxTouchPoints),language:Li(n==null?void 0:n.language),languages:Array.isArray(n==null?void 0:n.languages)?n.languages.filter(l=>typeof l=="string"):null},t={online:typeof(n==null?void 0:n.onLine)=="boolean"?n.onLine:null,effectiveType:Li((i=n==null?void 0:n.connection)==null?void 0:i.effectiveType),downlinkMbps:Ft((r=n==null?void 0:n.connection)==null?void 0:r.downlink),rttMs:Ft((s=n==null?void 0:n.connection)==null?void 0:s.rtt),saveData:typeof((a=n==null?void 0:n.connection)==null?void 0:a.saveData)=="boolean"?n.connection.saveData:null,connectionType:Li((o=n==null?void 0:n.connection)==null?void 0:o.type)};return{hardware:e,network:t}}function an(n,e={}){const t=Ch(),i=Ki(n??null);return{...i??{},hardware:t.hardware,network:t.network,environmentCapturedAt:e.capturedAt??(i==null?void 0:i.environmentCapturedAt)??null,environmentExportedAt:e.exportedAt??(i==null?void 0:i.environmentExportedAt)??null}}function vh(n){return n?n instanceof Error?{name:n.name,message:n.message,stack:n.stack??null,cause:bt(n.cause,1,new WeakSet)}:{name:null,message:typeof n=="string"?n:String(n),stack:null,cause:bt(n,1,new WeakSet)}:null}function ii(){return{totalEvents:0,severityCounts:{debug:0,info:0,warn:0,error:0},categoryCounts:{session:0,resource:0,playback:0,runtime:0,recovery:0,"ui-trigger":0},failureCount:0,lastFailureEvent:null}}function Th(n){const e=n??ii();return{totalEvents:e.totalEvents,severityCounts:{debug:e.severityCounts.debug,info:e.severityCounts.info,warn:e.severityCounts.warn,error:e.severityCounts.error},categoryCounts:{session:e.categoryCounts.session,resource:e.categoryCounts.resource,playback:e.categoryCounts.playback,runtime:e.categoryCounts.runtime,recovery:e.categoryCounts.recovery,"ui-trigger":e.categoryCounts["ui-trigger"]},failureCount:e.failureCount,lastFailureEvent:e.lastFailureEvent?{...e.lastFailureEvent}:null}}function qa(n){const e=ii();return n.forEach(t=>{e.totalEvents+=1,e.severityCounts[t.severity]+=1,e.categoryCounts[t.category]+=1,t.severity==="error"&&(e.failureCount+=1,e.lastFailureEvent={eventId:t.eventId,eventName:t.eventName,timestamp:t.timestamp,isoTime:t.isoTime,message:t.message,trackId:t.trackId,clipId:t.clipId,syncRequestId:t.syncRequestId,playbackAttemptId:t.playbackAttemptId})}),e}function on(n){return Th(n.summary)}function bh(n){return{sequence:n.sequence,timestamp:n.timestamp,isoTime:n.isoTime,severity:n.severity,category:n.category,eventName:n.eventName,message:n.message,syncRequestId:n.syncRequestId,playbackAttemptId:n.playbackAttemptId,trackId:n.trackId,clipId:n.clipId,extra:n.extra,error:n.error}}function kh(n,e){n.totalEvents+=1,n.severityCounts[e.severity]+=1,n.categoryCounts[e.category]+=1,e.severity==="error"&&(n.failureCount+=1,n.lastFailureEvent={eventId:e.eventId,eventName:e.eventName,timestamp:e.timestamp,isoTime:e.isoTime,message:e.message,trackId:e.trackId,clipId:e.clipId,syncRequestId:e.syncRequestId,playbackAttemptId:e.playbackAttemptId})}function wh(n){return{enabled:(n==null?void 0:n.enabled)??Ne.enabled,persist:(n==null?void 0:n.persist)??Ne.persist,storageQuotaMb:(n==null?void 0:n.storageQuotaMb)??Ne.storageQuotaMb,maxSessions:Math.max(1,(n==null?void 0:n.maxSessions)??Ne.maxSessions),maxHotEvents:Math.max(20,(n==null?void 0:n.maxHotEvents)??Ne.maxHotEvents),includeFullSourceUrl:(n==null?void 0:n.includeFullSourceUrl)??Ne.includeFullSourceUrl,consoleSeverityThreshold:(n==null?void 0:n.consoleSeverityThreshold)??Ne.consoleSeverityThreshold,highFrequencyEventThrottleMs:Math.max(0,(n==null?void 0:n.highFrequencyEventThrottleMs)??Ne.highFrequencyEventThrottleMs)}}function xh(){try{if(typeof globalThis.localStorage>"u")return null;const n=globalThis.localStorage.getItem(Ua);if(!n)return null;const e=JSON.parse(n);return(e==null?void 0:e.version)!==ui||!Array.isArray(e.sessions)?null:e}catch{return null}}function Ph(){try{if(typeof globalThis.localStorage>"u")return null;const n=globalThis.localStorage.getItem(Yr);if(!n)return null;const e=JSON.parse(n);return(e==null?void 0:e.version)!==ys||typeof e.sessionId!="string"||typeof e.failureEventId!="string"||!Array.isArray(e.events)?null:e}catch{return null}}function Ka(n){const e=Array.isArray(n.events)?n.events:[];return{...n,updatedAt:n.updatedAt||n.startedAt,events:e,summary:qa(e)}}function Ht(n,e,t={}){const i=n.slice(-e.maxSessions).map(s=>{const a=s.events.slice(-e.maxHotEvents);return Ka({...s,events:a,updatedAt:s.updatedAt||s.startedAt})});if(!t.enforceStorageQuota)return i;const r=Math.max(2e5,Math.floor(e.storageQuotaMb*1024*1024));for(;i.length>0&&JSON.stringify({version:ui,sessions:i}).length>r;)i.shift();return i}async function _h(n){return Za(Ya,n)}async function Ah(n){return Za(Xa,n)}async function Za(n,e){if(typeof indexedDB>"u")return!1;try{const t=await new Promise((i,r)=>{const s=indexedDB.open(Wa,1);s.onupgradeneeded=()=>{const a=s.result;a.objectStoreNames.contains(Xe)||a.createObjectStore(Xe)},s.onsuccess=()=>i(s.result),s.onerror=()=>r(s.error)});return await new Promise((i,r)=>{const s=t.transaction(Xe,"readwrite");s.objectStore(Xe).put(e,n),s.oncomplete=()=>i(),s.onerror=()=>r(s.error),s.onabort=()=>r(s.error)}),t.close(),!0}catch{return!1}}async function Ih(){const n=await Ja(Ya);return n&&typeof n=="object"&&"version"in n&&n.version===ui&&"sessions"in n&&Array.isArray(n.sessions)?n:null}async function Eh(){const n=await Ja(Xa);return n&&typeof n=="object"&&"version"in n&&n.version===ys&&"sessionId"in n&&typeof n.sessionId=="string"&&"failureEventId"in n&&typeof n.failureEventId=="string"&&"events"in n&&Array.isArray(n.events)?n:null}async function Ja(n){if(typeof indexedDB>"u")return null;try{const e=await new Promise((i,r)=>{const s=indexedDB.open(Wa,1);s.onupgradeneeded=()=>{const a=s.result;a.objectStoreNames.contains(Xe)||a.createObjectStore(Xe)},s.onsuccess=()=>i(s.result),s.onerror=()=>r(s.error)}),t=await new Promise((i,r)=>{const o=e.transaction(Xe,"readonly").objectStore(Xe).get(n);o.onsuccess=()=>i(o.result??null),o.onerror=()=>r(o.error)});return e.close(),t}catch{return null}}function Rh(n,e){return!n&&!e?null:{...n??{},...e??{}}}class Qa{constructor(e){p(this,"config");p(this,"listeners",new Set);p(this,"liveListeners",new Map);p(this,"state");p(this,"currentSessionId",null);p(this,"latestFailureWindow");p(this,"activeFailureCapture",null);p(this,"notifyTimeoutId",null);p(this,"persistTimeoutId",null);p(this,"highFrequencyEventTimestamps",new Map);this.config=wh(e);const t=xh();this.latestFailureWindow=Ph(),this.state={version:ui,sessions:Ht((t==null?void 0:t.sessions)??[],this.config,{enforceStorageQuota:this.config.persist})},this.restoreIndexedDbState()}startSession(e){const t=new Date().toISOString(),i={sessionId:nn("diag-session"),startedAt:Date.now(),updatedAt:Date.now(),metadata:an(e,{capturedAt:t}),sequence:0,events:[],summary:ii()};return this.currentSessionId=i.sessionId,this.state.sessions=Ht([...this.state.sessions,i],this.config),this.emit({severity:"info",category:"session",eventName:"session.started",message:"Diagnostic session started",extra:i.metadata??void 0}),this.getSnapshot()}getCurrentSessionId(){return this.currentSessionId}emit(e){if(!this.config.enabled)return null;const t=this.ensureCurrentSession();if(!t)return null;const i=Date.now();t.updatedAt=i;const r=this.resolveHighFrequencyDecision(e,i);if(r==="drop")return null;const s=this.findCoalescedEvent(t,e,i);if(s)return r==="skip-update"||(this.updateCoalescedEvent(s,e,i),this.schedulePersist(),this.scheduleNotify()),s;t.sequence+=1;const a=this.createEvent(t,e,i,t.sequence);return t.events.push(a),kh(t.summary,a),this.trimSessionEvents(t),this.captureFailureWindow(t,a),this.state.sessions=Ht(this.state.sessions,this.config),this.emitToConsole(a),this.schedulePersist(),this.scheduleNotify(),a}subscribe(e){return this.listeners.add(e),e(this.getSnapshot()),()=>{this.listeners.delete(e)}}subscribeLive(e,t=rn){const i=Math.max(1,t);return this.liveListeners.set(e,i),e(this.getLiveSnapshot(this.currentSessionId,i)),()=>{this.liveListeners.delete(e)}}getSnapshot(e=this.currentSessionId){const t=this.resolveSession(e);return{sessionId:t.sessionId,startedAt:t.startedAt,updatedAt:t.updatedAt,metadata:t.metadata,events:[...t.events],summary:on(t)}}getLiveSnapshot(e=this.currentSessionId,t=rn){const i=this.resolveSession(e),r=Math.max(1,t);return{sessionId:i.sessionId,startedAt:i.startedAt,updatedAt:i.updatedAt,metadata:i.metadata,summary:on(i),recentEvents:i.events.slice(-r).map(s=>bh(s))}}exportPackage(e={}){var c;const t=this.getSnapshot(e.sessionId??this.currentSessionId),i=Math.max(1,e.recentFailureContext??40),r=Math.max(1,e.recentEventsFallback??200),s=new Date().toISOString(),{failureWindow:a,failureWindowSource:o}=this.resolveExportFailureWindow(t,i,r),l=an(t.metadata,{capturedAt:((c=t.metadata)==null?void 0:c.environmentCapturedAt)??null,exportedAt:s});return{exportedAt:s,session:{sessionId:t.sessionId,startedAt:t.startedAt,updatedAt:t.updatedAt,metadata:l,summary:t.summary},rawEvents:t.events,failureWindow:a,failureWindowSource:o}}clear(e=!0){var t,i;if(this.clearScheduledTasks(),e&&this.currentSessionId){this.state.sessions=this.state.sessions.filter(r=>r.sessionId!==this.currentSessionId),((t=this.latestFailureWindow)==null?void 0:t.sessionId)===this.currentSessionId&&(this.latestFailureWindow=null),((i=this.activeFailureCapture)==null?void 0:i.sessionId)===this.currentSessionId&&(this.activeFailureCapture=null),this.currentSessionId=null,this.persistNow(),this.notifyNow();return}this.state.sessions=[],this.latestFailureWindow=null,this.activeFailureCapture=null,this.currentSessionId=null,this.persistNow(),this.notifyNow()}ensureCurrentSession(){return this.currentSessionId||this.startSession(),this.state.sessions.find(e=>e.sessionId===this.currentSessionId)??null}resolveSession(e=this.currentSessionId){return(e?this.state.sessions.find(t=>t.sessionId===e):null)??this.state.sessions[this.state.sessions.length-1]??{sessionId:"diagnostics-empty",startedAt:Date.now(),updatedAt:Date.now(),metadata:null,sequence:0,events:[],summary:ii()}}createEvent(e,t,i,r,s=nn("diag-event")){return{eventId:s,sessionId:e.sessionId,sequence:r,timestamp:i,isoTime:new Date(i).toISOString(),perfTimeMs:yh(),severity:t.severity,category:t.category,eventName:t.eventName,message:t.message??t.eventName,syncRequestId:t.syncRequestId??null,playbackAttemptId:t.playbackAttemptId??null,previewBackend:t.previewBackend??null,trackId:t.trackId??null,clipId:t.clipId??null,slotKey:t.slotKey??null,sourceUrl:this.normalizeUrl(t.sourceUrl),desiredSourceUrl:this.normalizeUrl(t.desiredSourceUrl),actualSourceUrl:this.normalizeUrl(t.actualSourceUrl),mediaState:Ki(t.mediaState),runtimeState:Sh(t.runtimeState),error:vh(t.error),extra:Ki(t.extra)}}trimSessionEvents(e){const t=e.events.length-this.config.maxHotEvents;t<=0||(e.events=e.events.slice(t),e.summary=qa(e.events))}findCoalescedEvent(e,t,i){if(!Xr.has(t.eventName)||t.severity==="warn"||t.severity==="error")return null;const r=this.buildEventIdentity(t);for(let s=e.events.length-1;s>=0;s-=1){const a=e.events[s];if(i-a.timestamp>gh)break;if(this.areEventIdentitiesEqual(r,a))return a}return null}resolveHighFrequencyDecision(e,t){if(e.severity==="warn"||e.severity==="error"||!mh.has(e.eventName))return"record";const i=this.config.highFrequencyEventThrottleMs;if(i<=0)return"record";const r=this.buildHighFrequencyKey(e),s=this.highFrequencyEventTimestamps.get(r);return s!==void 0&&t-s<i?Xr.has(e.eventName)?"skip-update":"drop":(this.highFrequencyEventTimestamps.set(r,t),"record")}buildHighFrequencyKey(e){const t=this.buildEventIdentity(e);return[t.eventName,t.playbackAttemptId??"",t.trackId??"",t.clipId??"",t.slotKey??"",t.syncRequestId??""].join("|")}buildEventIdentity(e){const t=e.eventName==="preview.sync.requested"||e.eventName==="pending-preview.begin"?null:e.syncRequestId??null;return{eventName:e.eventName,playbackAttemptId:e.playbackAttemptId??null,trackId:e.trackId??null,clipId:e.clipId??null,slotKey:e.slotKey??null,syncRequestId:t}}areEventIdentitiesEqual(e,t){const i=t.eventName==="preview.sync.requested"||t.eventName==="pending-preview.begin"?null:t.syncRequestId;return e.eventName===t.eventName&&e.playbackAttemptId===t.playbackAttemptId&&e.trackId===t.trackId&&e.clipId===t.clipId&&e.slotKey===t.slotKey&&e.syncRequestId===i}updateCoalescedEvent(e,t,i){const r=this.createEvent({sessionId:e.sessionId,startedAt:i,updatedAt:i,metadata:null,sequence:e.sequence,events:[],summary:ii()},t,i,e.sequence,e.eventId);Object.assign(e,r)}normalizeUrl(e){if(!e)return null;if(this.config.includeFullSourceUrl)return e;try{const t=new URL(e,typeof location<"u"?location.href:"https://localhost");return`${t.origin}${t.pathname}`}catch{return e.split("?")[0]||e}}emitToConsole(e){if(sn[e.severity]<sn[this.config.consoleSeverityThreshold]||e.severity!=="warn"&&e.severity!=="error")return;(e.severity==="error"?console.error.bind(console):console.warn.bind(console))(`[Diagnostics:${e.severity}] ${e.eventName}`,{message:e.message,sessionId:e.sessionId,playbackAttemptId:e.playbackAttemptId,syncRequestId:e.syncRequestId,trackId:e.trackId,clipId:e.clipId,error:e.error,extra:e.extra})}scheduleNotify(){this.notifyTimeoutId||(this.notifyTimeoutId=setTimeout(()=>{this.notifyTimeoutId=null,this.notifyNow()},uh))}notifyNow(){if(this.listeners.size>0){const e=this.getSnapshot();this.listeners.forEach(t=>t(e))}this.liveListeners.size>0&&this.liveListeners.forEach((e,t)=>{t(this.getLiveSnapshot(this.currentSessionId,e))})}schedulePersist(){this.config.persist&&(this.persistTimeoutId||(this.persistTimeoutId=setTimeout(()=>{this.persistTimeoutId=null,this.persistNow()},ph)))}persistNow(){if(!this.config.persist)return;const e={version:ui,sessions:Ht(this.state.sessions,this.config,{enforceStorageQuota:!0})};if(this.state=e,typeof indexedDB>"u"){this.persistToLocalStorage(e);return}Promise.all([_h(e),Ah(this.latestFailureWindow)]).then(([t,i])=>{if(!(t&&i))try{this.persistToLocalStorage(t?null:e,i?void 0:this.latestFailureWindow)}catch{}})}clearScheduledTasks(){this.notifyTimeoutId&&(clearTimeout(this.notifyTimeoutId),this.notifyTimeoutId=null),this.persistTimeoutId&&(clearTimeout(this.persistTimeoutId),this.persistTimeoutId=null)}async restoreIndexedDbState(){var i,r;if(!this.config.persist)return;const[e,t]=await Promise.all([Ih(),Eh()]);if((i=e==null?void 0:e.sessions)!=null&&i.length){const s=new Map;[...this.state.sessions,...e.sessions].forEach(a=>{const o=Ka(a),l=s.get(o.sessionId);(!l||l.updatedAt<o.updatedAt)&&s.set(o.sessionId,o)}),this.state.sessions=Ht(Array.from(s.values()).sort((a,o)=>a.startedAt-o.startedAt),this.config,{enforceStorageQuota:!0})}t&&(!this.latestFailureWindow||t.updatedAt>=this.latestFailureWindow.updatedAt)&&(this.latestFailureWindow=t),((r=e==null?void 0:e.sessions)!=null&&r.length||t)&&this.notifyNow()}captureFailureWindow(e,t){if(t.severity==="error"&&(this.activeFailureCapture={sessionId:e.sessionId,failureEventId:t.eventId,remainingAfterEvents:tn}),!this.activeFailureCapture||this.activeFailureCapture.sessionId!==e.sessionId)return;const i=this.buildFailureWindow(e,this.activeFailureCapture.failureEventId);i.length&&(this.latestFailureWindow={version:ys,sessionId:e.sessionId,updatedAt:t.timestamp,failureEventId:this.activeFailureCapture.failureEventId,events:i},t.eventId!==this.activeFailureCapture.failureEventId&&(this.activeFailureCapture.remainingAfterEvents-=1),this.activeFailureCapture.remainingAfterEvents<=0&&(this.activeFailureCapture=null))}buildFailureWindow(e,t,i=tn){const r=e.events.findIndex(s=>s.eventId===t);return r<0?[]:e.events.slice(Math.max(0,r-i),Math.min(e.events.length,r+i+1))}resolveExportFailureWindow(e,t,i){var o;const r=e.events.map((l,c)=>({event:l,index:c})).filter(({event:l})=>l.severity==="error"),s=r.length>0?r[r.length-1]:null,a=s?e.events.slice(Math.max(0,s.index-t),Math.min(e.events.length,s.index+t+1)):[];return s?{failureWindow:a,failureWindowSource:"live"}:((o=this.latestFailureWindow)==null?void 0:o.sessionId)===e.sessionId&&this.latestFailureWindow.events.length>0?{failureWindow:[...this.latestFailureWindow.events],failureWindowSource:"persisted"}:{failureWindow:e.events.slice(-i),failureWindowSource:"recent-events"}}persistToLocalStorage(e,t=this.latestFailureWindow){if(!(typeof globalThis.localStorage>"u")&&(e&&globalThis.localStorage.setItem(Ua,JSON.stringify(e)),t!==void 0)){if(t){globalThis.localStorage.setItem(Yr,JSON.stringify(t));return}globalThis.localStorage.removeItem(Yr)}}}function Mh(n,e){return Rh(n,e)}function ln(n,e,t,i){const r=`[${n.toUpperCase()}] [${e}]`;if(i===void 0){console[n](`${r} ${t}`);return}console[n](`${r} ${t}`,i)}const N={debug(n,e,t){},debugLazy(n,e,t){},warn(n,e,t){ln("warn",n,e,t)},error(n,e,t){ln("error",n,e,t)}};class ge{static clearImageCache(){this.imageCache={},this.keyframeDimensionsCache={},this.keyframeDimensionsPromiseCache={},this.brokenImageUrls.clear()}static renderClipCovers(e,t,i,r,s,a=!1){N.debugLazy("ClipCoverRenderer",()=>"renderClipCovers",()=>({videoSrc:s,coverCount:(t==null?void 0:t.length)??0,coverWidth:i,coverHeight:r}));const o=(e.getAttr(this.COVER_RENDER_VERSION_KEY)||0)+1;if(e.setAttr(this.COVER_RENDER_VERSION_KEY,o),e.setAttr(this.COVER_SOURCE_KEY,[...t??[]]),!t||t.length===0){e.destroyChildren(),this.syncCoverBackgroundState(e),a||this.requestRender(e);return}const l=this.buildSegmentsDataSync(t,i,r,s);if(l){this.renderSegments(e,l,i,r),this.syncCoverBackgroundState(e),a||this.requestRender(e);return}a||(e.destroyChildren(),this.syncCoverBackgroundState(e),this.requestRender(e)),this.startRenderJob({coversGroup:e,coverSource:t,coverWidth:i,coverHeight:r,videoSrc:s,version:o})}static async startRenderJob(e){const{coversGroup:t,coverSource:i,coverWidth:r,coverHeight:s,videoSrc:a,version:o}=e,l=await this.buildSegmentsData(i,r,s,a);if(this.isRenderJobCurrent(t,o)){if(this.renderSegments(t,l,r,s),this.syncCoverBackgroundState(t),!this.isRenderJobCurrent(t,o)){t.destroyChildren();return}this.requestRender(t)}}static async buildSegmentsData(e,t,i,r){const s=e.length,a=r||e[0]||"",o=await this.getSafeKeyframeDimensions(a,e[0]),l=o.width/o.height,c=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),h=Math.max(1,Math.ceil(t/c)),d=[];if(h===1)d.push(0);else for(let g=0;g<h;g++)d.push(Math.round(g*(s-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static buildSegmentsDataSync(e,t,i,r){const s=e.length,a=r||e[0]||"",o=this.getCachedKeyframeDimensions(a,e[0]);if(!o)return null;const l=o.width/o.height,c=Math.max(i*l,this.MIN_IMAGE_DISPLAY_WIDTH),h=Math.max(1,Math.ceil(t/c)),d=[];if(h===1)d.push(0);else for(let g=0;g<h;g++)d.push(Math.round(g*(s-1)/(h-1)));const u=[];for(let g=0;g<h;g++){const f=e[d[g]];u.push({coverUrl:f,singleImageWidth:c,segmentStartX:g*c,segmentWidth:c})}return u}static requestRender(e){var i,r;const t=(i=e.getLayer)==null?void 0:i.call(e);if((r=t==null?void 0:t.getStage)!=null&&r.call(t))try{e.draw(),t.batchDraw()}catch{}}static isRenderJobCurrent(e,t){return e.getAttr(this.COVER_RENDER_VERSION_KEY)===t}static renderSegments(e,t,i,r){e.destroyChildren(),e.clip({x:0,y:0,width:i,height:r});for(const{coverUrl:s,singleImageWidth:a,segmentStartX:o,segmentWidth:l}of t){const c=Math.max(a,.01),h=this.getCachedImage(s),d=new Z.Group({x:o,y:0,clip:{x:0,y:0,width:l,height:r},name:"cover-segment"});h.src||(h.src=s);const u=new Z.Image({image:h,cornerRadius:2,name:"cover-image",visible:this.isImageRenderable(s,h)});u.x(0),u.y(0),u.width(c),u.height(r),this.bindCoverImageLifecycle(s,h,u,e),d.add(u),e.add(d)}}static async getSafeKeyframeDimensions(e,t){try{const i=await this.getKeyframeDimensions(e,t);if(i!=null&&i.width&&(i!=null&&i.height))return i}catch{}return this.DEFAULT_DIMENSIONS}static getKeyframeDimensions(e,t){const i=t||e;if(this.keyframeDimensionsCache[i])return Promise.resolve(this.keyframeDimensionsCache[i]);if(this.keyframeDimensionsPromiseCache[i])return this.keyframeDimensionsPromiseCache[i];const r=new Promise(s=>{const a=this.getCachedImage(t);if(this.isImageRenderable(t,a)){const l={width:a.width,height:a.height};this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],s(l);return}const o=l=>{this.keyframeDimensionsCache[i]=l,delete this.keyframeDimensionsPromiseCache[i],s(l)};this.listenToImageEvent(a,"load",()=>{this.brokenImageUrls.delete(t);const l={width:a.width,height:a.height};o(l.width>0&&l.height>0?l:this.DEFAULT_DIMENSIONS)},{once:!0}),this.listenToImageEvent(a,"error",()=>{this.brokenImageUrls.add(t),o(this.DEFAULT_DIMENSIONS)},{once:!0}),a.src||(a.src=t)});return this.keyframeDimensionsPromiseCache[i]=r,r}static getCachedKeyframeDimensions(e,t){const i=t||e,r=this.keyframeDimensionsCache[i];if(r!=null&&r.width&&(r!=null&&r.height))return r;const s=this.imageCache[t];if(s!=null&&s.complete&&s.width>0&&s.height>0){const a={width:s.width,height:s.height};return this.keyframeDimensionsCache[i]=a,a}return null}static getCachedImage(e){const t=this.imageCache[e];if(t)return t;const i=new Image;return this.imageCache[e]=i,this.checkAndTrimCache(),i}static checkAndTrimCache(){const e=Object.keys(this.imageCache);if(e.length<=this.MAX_CACHE_SIZE)return;const t=e.length-this.MAX_CACHE_SIZE,i=e.filter(a=>{const o=this.imageCache[a];return o&&!o.complete}),r=e.filter(a=>!i.includes(a));let s=0;for(const a of i){if(s>=t)break;this.evictCacheKey(a),s++}for(const a of r){if(s>=t)break;this.evictCacheKey(a),s++}}static evictCacheKey(e){delete this.imageCache[e],delete this.keyframeDimensionsCache[e],delete this.keyframeDimensionsPromiseCache[e],this.brokenImageUrls.delete(e)}static bindCoverImageLifecycle(e,t,i,r){this.listenToImageEvent(t,"load",()=>{this.brokenImageUrls.delete(e);try{i.visible(this.isImageRenderable(e,t)),this.syncCoverBackgroundState(r),this.requestRender(r)}catch{}}),this.listenToImageEvent(t,"error",()=>{this.brokenImageUrls.add(e);try{i.visible(!1),this.syncCoverBackgroundState(r),this.requestRender(r)}catch{}})}static isImageRenderable(e,t){if(this.brokenImageUrls.has(e)||!t.complete)return!1;const i=typeof t.naturalWidth=="number"?t.naturalWidth:t.width,r=typeof t.naturalHeight=="number"?t.naturalHeight:t.height;return i>0&&r>0}static listenToImageEvent(e,t,i,r){typeof e.addEventListener=="function"&&e.addEventListener(t,i,r)}static syncCoverBackgroundState(e){var c,h;const t=(c=e.getParent)==null?void 0:c.call(e),i=(h=t==null?void 0:t.findOne)==null?void 0:h.call(t,".clip-cover-background");if(!i)return;const r=e.getAttr("coverFallbackFill"),s=e.getAttr("coverUnavailableFill"),a=e.getAttr(this.COVER_SOURCE_KEY)??[],l=a.length>0&&a.every(d=>this.brokenImageUrls.has(d));i.fill(l?s:r)}}p(ge,"MIN_IMAGE_DISPLAY_WIDTH",24),p(ge,"COVER_RENDER_VERSION_KEY","_coverRenderVersion"),p(ge,"COVER_SOURCE_KEY","_coverSource"),p(ge,"MAX_CACHE_SIZE",1e3),p(ge,"DEFAULT_DIMENSIONS",{width:160,height:90}),p(ge,"keyframeDimensionsCache",{}),p(ge,"keyframeDimensionsPromiseCache",{}),p(ge,"imageCache",{}),p(ge,"brokenImageUrls",new Set);const Lh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.8437804474494934,2.934130300488281C2.0975289474494936,2.6803818004882816,2.5560352474494934,2.5258255004882812,3.4537861474494935,2.5258255004882812L7.691924847449493,2.5258255004882812C8.589675247449494,2.5258255004882812,9.048181847449493,2.6803818004882816,9.301930747449493,2.934130300488281C9.555688247449494,3.1878788004882814,9.710234947449493,3.6463940004882813,9.710234947449493,4.544136000488281L9.710234947449493,5.154385800488281L9.710234947449493,5.156664400488282L9.710234947449493,8.837531600488282L9.710234947449493,8.839810400488282L9.710234947449493,9.455756700488282C9.710234947449493,10.352920500488281,9.554433147449494,10.811444300488281,9.299509347449494,11.065193200488281C9.045182547449494,11.319528600488281,8.586177147449494,11.474209800488282,7.691924847449493,11.474209800488282L3.4537861474494935,11.474209800488282C2.6371141474494935,11.474209800488282,2.1565246474494932,11.20751000048828,1.8706969474494934,10.86509900048828C1.5731912474494933,10.50867840048828,1.4354756474494934,10.006423900488281,1.4354756474494934,9.455756700488282L1.4354756474494934,4.544136000488281C1.4354756474494934,3.6463940004882813,1.5900319474494935,3.1878788004882814,1.8437804474494934,2.934130300488281ZM9.917876547449493,11.684700500488281C10.391550347449494,11.212192500488282,10.559057547449493,10.52217200048828,10.582387647449494,9.67692760048828L11.516774647449493,10.33260820048828L11.516774647449493,10.33260820048828C11.978190647449493,10.658107800488281,12.521887647449493,10.806299200488281,12.992055647449494,10.562466600488282C13.461642647449493,10.318055200488281,13.653574647449494,9.787735900488281,13.653574647449494,9.222480300488282L13.653574647449494,4.777554700488281C13.653574647449494,4.212299300488281,13.461625647449493,3.6825676004882815,12.992624647449494,3.437568500488281C12.523623647449494,3.1925697004882814,11.980024647449493,3.3384564004882815,11.519194647449494,3.6604486004882815L11.518056647449493,3.661018400488281L10.582387647449494,4.3178380004882815C10.558470047449493,3.475504500488281,10.392209347449493,2.7870953004882812,9.920297947449493,2.315762820488281C9.406961747449493,1.8024266504882813,8.637509647449493,1.6508255004882812,7.691924847449493,1.6508255004882812L3.4537861474494935,1.6508255004882812C2.5082015474494934,1.6508255004882812,1.7387490474494933,1.8024266504882813,1.2254129674494934,2.315762820488281C0.7120767974494934,2.8290989004882814,0.5604756474494934,3.598560200488281,0.5604756474494934,4.544136000488281L0.5604756474494934,9.455756700488282C0.5604756474494934,10.13592340048828,0.7290598274494934,10.86171720048828,1.1986388574494935,11.42521860048828C1.6798959474494934,12.003300500488281,2.4271137474494937,12.349209500488282,3.4537861474494935,12.349209500488282L7.691924847449493,12.349209500488282C8.635176947449493,12.349209500488282,9.403962447449494,12.197448500488282,9.917876547449493,11.684700500488281ZM12.020781647449493,9.61682840048828L10.585234647449493,8.609952000488281L10.585234647449493,5.384101600488281L12.019642647449494,4.377937300488281L12.020212647449494,4.3773675004882815C12.352129647449493,4.145782500488281,12.531874647449493,4.183709400488281,12.587880647449493,4.212877700488281C12.643876647449494,4.242046400488281,12.778574647449494,4.368635700488282,12.778574647449494,4.777554700488281L12.778574647449494,9.222480300488282C12.778574647449494,9.631399600488281,12.643866647449494,9.757436800488282,12.588449647449494,9.786018400488281C12.533620647449494,9.814020200488281,12.354416647449494,9.852481800488281,12.021921647449494,9.617398300488281L12.020781647449493,9.61682840048828ZM3.3313089474494935,3.9374466004882813C3.0898080474494933,3.9374466004882813,2.8938089474494935,4.133445700488281,2.8938089474494935,4.374946600488281C2.8938089474494935,4.616447400488282,3.0898080474494933,4.812446600488281,3.3313089474494935,4.812446600488281L4.815419447449494,4.812446600488281C5.056920347449493,4.812446600488281,5.252919447449494,4.616447400488282,5.252919447449494,4.374946600488281C5.252919447449494,4.133445700488281,5.056920347449493,3.9374466004882813,4.815419447449494,3.9374466004882813L3.3313089474494935,3.9374466004882813Z" fill="#868A9C" fill-opacity="1"/></svg>',Dh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="16" height="16" viewBox="0 0 16 16"><path d="M11.206380472434997,2.733718973069763C9.993001372434998,1.991438673069763,8.552978872434998,1.6945722130697631,7.139648772434998,1.8937121730697632C5.7263186724349975,2.092858673069763,4.426350972434998,2.775678773069763,3.4596355724349976,3.825838973069763C2.4930013724349975,4.875998873069763,1.9263509724349976,6.228518873069763,1.8396810724349975,7.652945373069763C1.7596843224349974,9.077412973069762,2.1796875724349976,10.485612273069764,3.0196941724349977,11.637611373069763C3.8597005724349978,12.789678373069764,5.0796712724349975,13.614278373069762,6.459635572434998,13.970879373069764C7.839681072434997,14.327545373069762,9.299641972434998,14.194145373069762,10.593017972434998,13.593478373069763C11.892985472434997,12.992878373069763,12.933024472434997,11.962078373069764,13.552978472434997,10.676812573069764C14.173015472434997,9.391545673069762,14.326335472434998,7.9312790730697635,13.993001472434997,6.544878873069763C13.926350472434997,6.276532073069763,14.093017472434997,6.0061725730697635,14.359700472434998,5.941012273069763C14.626302472434997,5.875851973069763,14.899658472434998,6.040565873069763,14.966308472434998,6.308912673069763C15.353027472434997,7.920145873069763,15.173015472434997,9.617145873069763,14.453044472434998,11.110879373069762C13.732991472434998,12.604545373069763,12.519694472434997,13.802478373069762,11.019694472434997,14.500545373069762C9.513020872434998,15.198611373069763,7.812988672434997,15.353611373069763,6.2063802724349975,14.939145373069763C4.599690772434998,14.524678373069763,3.1930340724349975,13.566345373069764,2.2129720724349973,12.227478373069763C1.2329915724349976,10.888679373069763,0.7530111074349976,9.252079373069764,0.8463542074349976,7.5966790730697635C0.9396973124349975,5.941252573069764,1.5996907924349975,4.369405673069763,2.726318472434998,3.1489456730697634C3.8463543724349973,1.9284919730697632,5.359700572434997,1.134938593069763,6.999674672434997,0.9035053700697632C8.639648772434999,0.6720721230697632,10.312988672434997,1.0170720830697633,11.726318472434997,1.8797255730697633C11.966308472434998,2.023398773069763,12.039714472434998,2.3310454730697634,11.892985472434997,2.5668653730697635C11.753011472434997,2.8026921730697634,11.446370472434998,2.8773921730697634,11.206380472434997,2.733718973069763ZM11.686360472434998,5.413441573069763C11.879639472434997,5.608874673069764,11.879639472434997,5.925454473069763,11.686360472434998,6.1205485730697635L7.2396648724349975,10.559748073069763C7.046305572434997,10.754747773069763,6.7263186724349975,10.754615173069762,6.533040372434997,10.559481973069763L4.312988372434997,8.339814573069763C4.119710372434998,8.144614573069763,4.119710372434998,7.828014773069763,4.312988372434997,7.632747973069764C4.506347772434998,7.437481773069763,4.826334872434998,7.437481773069763,5.019694172434997,7.632747973069764L6.886311872434997,9.499081973069764L10.979655472434997,5.412814473069763C11.173015472434997,5.217727973069763,11.493001472434997,5.218008373069763,11.686360472434998,5.413441573069763Z" fill-rule="evenodd" fill="#24C744" fill-opacity="1"/></svg>',Oh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M1.3164876075,5.2511568456573485C2.7112323875,3.0589928456573485,4.7552132875,1.7354023456573486,6.9998931875,1.7354023456573486C9.2445726875,1.7354023456573486,11.2885531875,3.0589928456573485,12.6832981875,5.2511568456573485C13.0012411875,5.7498953456573485,13.1452941875,6.3880765456573485,13.1452941875,6.9999821456573486C13.1452941875,7.611905345657348,13.0012411875,8.250068445657348,12.6832981875,8.74882484565735C11.2885531875,10.940988745657348,9.2445726875,12.264562345657348,6.9998931875,12.264562345657348C4.7552132875,12.264562345657348,2.7112323875,10.940988745657348,1.3164876075,8.74882484565735C0.9985453175,8.250068445657348,0.8544921875,7.611905345657348,0.8544921875,6.9999821456573486C0.8544921875,6.3880765456573485,0.9985453175,5.749325945657349,1.3164876075,5.2511568456573485ZM6.9998931875,2.6104023456573486C5.1262406875,2.6104023456573486,3.3318786875,3.713480445657349,2.0549823875,5.721323445657349L2.0543771875,5.721323445657349C1.8473052375,6.0456564456573485,1.7294921875,6.509396745657349,1.7294921875,6.9999821456573486C1.7294921875,7.490567445657349,1.8473052375,7.954324945657349,2.0543771875,8.278070645657348L2.0549823875,8.27865814565735C3.3318786875,10.286483045657349,5.1262406875,11.389561845657349,6.9998931875,11.389561845657349C8.8735446875,11.389561845657349,10.6679076875,10.286483045657349,11.9448031875,8.27865814565735L11.9454091875,8.278070645657348C12.1518751875,7.954324945657349,12.2702941875,7.490567445657349,12.2702941875,6.9999821456573486C12.2702941875,6.509396745657349,12.1518751875,6.0456564456573485,11.9454091875,5.721323445657349L11.9448031875,5.721323445657349C10.6679076875,3.713480445657349,8.8735446875,2.6104023456573486,6.9998931875,2.6104023456573486ZM4.4741208875,7.002937045657348C4.4741208875,5.606429845657349,5.6034745875,4.4771115456573485,6.9999641875,4.4771115456573485C8.3964533875,4.4771115456573485,9.5258073875,5.606429845657349,9.5258073875,7.002937045657348C9.5258073875,8.399444345657349,8.3964533875,9.528762545657349,6.9999641875,9.528762545657349C5.6034745875,9.528762545657349,4.4741208875,8.399444345657349,4.4741208875,7.002937045657348ZM6.9999641875,5.3521115456573485C6.0864762875,5.3521115456573485,5.3491210875,6.089431545657349,5.3491210875,7.002937045657348C5.3491210875,7.916442645657349,6.0864762875,8.653762545657349,6.9999641875,8.653762545657349C7.9134516875,8.653762545657349,8.650807387499999,7.916442645657349,8.650807387499999,7.002937045657348C8.650807387499999,6.089431545657349,7.9134516875,5.3521115456573485,6.9999641875,5.3521115456573485Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',Bh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="18" height="18" viewBox="0 0 18 18"><path d="M3.5486246148989866,6.472501117640625C3.7632801848989867,6.361666362640625,4.026926634898987,6.445068359640625,4.138366634898987,6.659741711640625C4.944508744898987,8.214329931640625,6.797759844898987,9.340158931640625,8.999857544898987,9.340158931640625C11.201954944898986,9.340158931640625,13.055775244898987,8.214329931640625,13.861347544898987,6.659741711640625C13.972788544898988,6.445068359640625,14.237040544898987,6.361666362640625,14.451090544898987,6.472501117640625C14.665781544898987,6.583905531640625,14.749770544898986,6.847569761640625,14.638366544898988,7.062243101640625C14.367100544898987,7.584907531640625,14.003692544898987,8.060913131640625,13.566192544898987,8.475074731640625L14.459278544898988,9.368161431640626C14.630177544898986,9.539077731640624,14.630177544898986,9.816164531640625,14.459278544898988,9.987080831640625C14.288344544898987,10.157996931640625,14.011275544898988,10.157996931640625,13.840342544898986,9.987080831640625L12.883701944898986,9.030405531640625C12.378519644898986,9.383328631640625,11.808039344898987,9.667999231640625,11.192590844898987,9.869249831640625L11.502344744898986,11.025413531640625C11.564757944898988,11.258743331640625,11.426508544898986,11.499069231640625,11.193196444898987,11.561500531640625C10.959848544898986,11.623913731640625,10.720092444898988,11.485664331640624,10.657109344898988,11.251747131640624L10.345611244898986,10.087999831640625C9.911600744898987,10.171401731640625,9.460677744898987,10.215158931640625,8.999857544898987,10.215158931640625C8.548365244898987,10.215158931640625,8.107340444898988,10.173164131640625,7.681518244898987,10.093233631640626L7.371195444898987,11.251747131640624C7.308781744898987,11.485664331640624,7.069025444898987,11.623913731640625,6.835108144898987,11.561500531640625C6.6017607448989875,11.499069231640625,6.4635111448989875,11.258743331640625,6.525924544898986,11.025413531640625L6.833363644898987,9.877990731640626C6.192280844898987,9.670900831640624,5.600189044898986,9.374000531640625,5.078094344898987,9.003578231640624L4.095179204898987,9.987080831640625C3.924280764898987,10.157996931640625,3.6471760548989867,10.157996931640625,3.476277614898987,9.987080831640625C3.305343588298987,9.816164531640625,3.305343588298987,9.539077731640624,3.476277614898987,9.368161431640626L4.400873744898987,8.443583031640625C3.9779357348989866,8.036987331640624,3.6256001248989866,7.572072231640625,3.361348427898987,7.062243101640625C3.250513676898987,6.847569761640625,3.3339334728989867,6.583905531640625,3.5486246148989866,6.472501117640625Z" fill="#FFFFFF" fill-opacity="1"/></svg>',Fh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="24" height="24" viewBox="0 0 24 24"><path d="M9.217651334374999,1.6159667934375C8.817657434375,1.7239685034375,8.579650834375,2.1349792434375,8.687652634374999,2.5349731234375C8.794677734375,2.9349670234375003,9.205657934375001,3.1719665234375,9.605651834375,3.0649719234374997C14.537658734375,1.7439575234375,19.612670734375,4.6739807234375,20.934661734375,9.6059570234375C22.255676734375,14.5379635234375,19.325652734375,19.6129765234375,14.393676734375,20.9349675234375C9.461669934375,22.2559815234375,4.3866577343749995,19.3259585234375,3.064666734375,14.3939815234375C2.3956604343750003,11.8969725234375,2.816650434375,9.3629761234375,4.036651634375,7.2969665234375C4.246673534375001,6.9399719234375,4.128662134375,6.4799804234375,3.771667434375,6.2699585234375C3.415649434375,6.0589599234375,2.955657934375,6.1779785234375,2.744659434375,6.5339660234375C1.3286743163749999,8.9329834234375,0.8386535643749999,11.8789675234375,1.615661624375,14.7819825234375C3.151672334375,20.5139775234375,9.049652134375,23.9199825234375,14.781677734375,22.3839725234375C20.513671734375,20.8479615234375,23.919677734375,14.9499815234375,22.383666734375,9.2179565234375C20.847656734375,3.4859619234375,14.949676734375,0.07995602343750008,9.217651334374999,1.6159667934375Z" fill="#C9CBD4" fill-opacity="1"/><path d="M16.7496337890625,12C16.7496337890625,14.6270103,14.6266440890625,16.75,11.9996337890625,16.75C9.3736238890625,16.75,7.2496337890625,14.6270103,7.2496337890625,12C7.2496337890625,9.3739901,9.3736238890625,7.25,11.9996337890625,7.25C14.6266440890625,7.25,16.7496337890625,9.3739901,16.7496337890625,12ZM11.9996337890625,15.25C13.7976336890625,15.25,15.2496337890625,13.7979999,15.2496337890625,12C15.2496337890625,10.2020001,13.7976336890625,8.75,11.9996337890625,8.75C10.2016338890625,8.75,8.7496337890625,10.2020001,8.7496337890625,12C8.7496337890625,13.7979999,10.2016338890625,15.25,11.9996337890625,15.25Z" fill="#C9CBD4" fill-opacity="1"/></svg>',Hh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M12.594244271484374,3.926410052418518C12.594244271484374,3.9339934524185183,12.594244271484374,3.941576852418518,12.594244271484374,3.949160252418518L12.594244271484374,10.004165252418519L12.594244271484374,10.009998952418519C12.591269271484375,11.254248752418517,11.581520271484376,12.261664752418518,10.336686171484375,12.261664752418518C9.090102671484374,12.261664752418518,8.079185971484375,11.250748752418518,8.079185971484375,10.004165252418519C8.079185971484375,8.757582352418517,9.090102671484374,7.746665552418518,10.336686171484375,7.746665552418518C10.857602071484376,7.746665552418518,11.337102871484374,7.922832152418518,11.719244271484374,8.219165952418518L11.719244271484374,4.510315252418518L5.920881771484375,6.091725952418518L5.920881771484375,11.212248752418517L5.920881771484375,11.217499752418519C5.920881771484375,12.464083752418517,4.909947871484375,13.474998752418518,3.663387771484375,13.474998752418518C2.416787071484375,13.474998752418518,1.405852854251865,12.464082752418518,1.405852854251865,11.217499752418519C1.405852854251865,9.970916352418518,2.416786871484375,8.959999652418517,3.663387771484375,8.959999652418517C4.184269171484376,8.959999652418517,4.663780971484375,9.136166252418517,5.045881971484375,9.432499552418518L5.045881971484375,5.765065352418518C5.045881971484375,5.759809652418518,5.045881971484375,5.754577252418518,5.045881971484375,5.749326852418518L5.045881971484375,3.879142852418518C5.045881971484375,2.9108270524185182,5.645524971484375,2.2224822524185184,6.488441471484375,1.9926605524185181L10.128436071484375,1.000982272418518C10.652911171484375,0.8580656054185181,11.273518571484376,0.8131547724185181,11.781602271484376,1.1106431024185182C12.324102271484374,1.4273930824185181,12.594244271484374,2.0416489524185177,12.594244271484374,2.887488152418518L12.594244271484374,3.926410052418518ZM11.719244271484374,2.887487652418518C11.719244271484374,2.216660252418518,11.514435271484375,1.967576852418518,11.340019271484374,1.866071042418518C11.132935571484374,1.744731902418518,10.796352371484375,1.726076842418518,10.358268771484376,1.845648522418518L6.718304671484375,2.8373209524185183C6.231775271484375,2.969731652418518,5.920881771484375,3.330809252418518,5.920881771484375,3.879142452418518L5.920881771484375,5.184648152418518L11.719244271484374,3.603231552418518L11.719244271484374,2.887487652418518ZM3.663388271484375,12.599998752418518C4.426948071484375,12.599998752418518,5.045882471484375,11.981081752418518,5.045882471484375,11.217499752418519C5.045882471484375,10.453916152418518,4.426948271484375,9.834999652418517,3.663388271484375,9.834999652418517C2.8997932714843753,9.834999652418517,2.280853391484375,10.453916152418518,2.280853391484375,11.217499752418519C2.280853391484375,11.981082752418518,2.899793471484375,12.599998752418518,3.663388271484375,12.599998752418518ZM8.954185971484375,10.004165252418519C8.954185971484375,10.767749452418519,9.573102971484374,11.386664752418518,10.336686171484375,11.386664752418518C11.100269271484375,11.386664752418518,11.719244271484374,10.767748452418518,11.719244271484374,10.004165252418519C11.719244271484374,9.240582152418519,11.100269271484375,8.621665552418518,10.336686171484375,8.621665552418518C9.573102971484374,8.621665552418518,8.954185971484375,9.240582152418519,8.954185971484375,10.004165252418519Z" fill="#868A9C" fill-opacity="1"/></svg>',Gh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M11.305803496070862,2.8583284381607053C11.498882496070863,2.713661038160706,11.773050496070862,2.7521666381607055,11.918296496070862,2.9458338381607057C13.720794496070862,5.347419838160706,13.720794496070862,8.652577538160706,11.918296496070862,11.054163138160705C11.773050496070862,11.247830138160706,11.498882496070863,11.286335138160705,11.305803496070862,11.141669138160706C11.112723496070862,10.996414138160706,11.073630496070862,10.722246738160706,11.218307496070862,10.529166838160705C12.787475496070861,8.439078938160705,12.787475496070861,5.5609179381607055,11.218307496070862,3.4708303381607055C11.073630496070862,3.2777506381607058,11.112723496070862,3.0035830381607056,11.305803496070862,2.8583284381607053ZM10.850643496070862,4.404167338160706C10.705398196070862,4.210500138160706,10.431231096070862,4.171994538160705,10.238133096070861,4.316661938160705C10.044466596070862,4.461916538160706,10.005978196070862,4.736083838160706,10.150637296070862,4.929163538160706C11.072313496070862,6.156499038160706,11.072313496070862,7.843498338160706,10.150637296070862,9.070833838160706C10.005978196070862,9.263913738160706,10.044466596070862,9.538080838160706,10.238133096070861,9.683335938160706C10.431231096070862,9.828002538160705,10.705398196070862,9.789497038160706,10.850643496070862,9.595830538160705C12.005633496070862,8.058162338160706,12.005633496070862,5.941834538160705,10.850643496070862,4.404167338160706ZM6.527554596070861,1.3638305381607054C7.564730296070862,0.4561640581607056,9.188140496070861,1.1929142881607055,9.188140496070861,2.5713347381607052L9.188140496070861,11.428662138160705C9.188140496070861,12.807083138160706,7.564730296070862,13.543833138160705,6.527554596070861,12.636166138160705L3.9608915960708617,10.390329938160706C3.934063996070862,10.367000238160706,3.9002226960708617,10.354164738160705,3.8646364960708617,10.354164738160705L2.917307496070862,10.354164738160705C1.7092156960708618,10.354164738160705,0.7298074960708618,9.374747838160706,0.7298074960708618,8.166665238160705L0.7298074960708618,5.8333321381607055C0.7298074960708618,4.6252492381607055,1.7092156960708618,3.6458321381607055,2.917307496070862,3.6458321381607055L3.8646364960708617,3.6458321381607055C3.9002226960708617,3.6458321381607055,3.934063996070862,3.6329969381607055,3.9608915960708617,3.6096674381607055L6.527554596070861,1.3638305381607054ZM8.313140496070861,2.5713347381607052C8.313140496070861,1.9448317881607056,7.575215496070862,1.6099954881607057,7.103891996070862,2.0224125381607054L4.537228696070862,4.268249638160706C4.351145196070862,4.430994638160706,4.111976496070862,4.520831938160706,3.8646364960708617,4.520831938160706L2.917307496070862,4.520831938160706C2.192217496070862,4.520831938160706,1.6048074960708618,5.108250738160706,1.6048074960708618,5.8333321381607055L1.6048074960708618,8.166665238160705C1.6048074960708618,8.891746138160705,2.192217496070862,9.479165638160705,2.917307496070862,9.479165638160705L3.8646364960708617,9.479165638160705C4.111976496070862,9.479165638160705,4.351145196070862,9.569002738160705,4.537228696070862,9.731748238160705L7.103891996070862,11.977584138160706C7.575215496070862,12.390002138160705,8.313140496070861,12.055165138160705,8.313140496070861,11.428662138160705L8.313140496070861,2.5713347381607052Z" fill-rule="evenodd" fill="#FFFFFF" fill-opacity="1"/></svg>',Nh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M9.188069328125,2.7498358381607053L9.188069328125,2.5713360381607053C9.188069328125,1.1929155481607057,7.564641028125,0.4561653181607056,6.527501128125,1.3638317881607056L3.960820428125,3.6096686381607057C3.933975228125,3.6329981381607057,3.900151528125,3.6458331381607056,3.864583228125,3.6458331381607056L2.917236328125,3.6458331381607056C1.709162358125,3.6458331381607056,0.729736328125,4.625250238160706,0.729736328125,5.833333138160706L0.729736328125,8.166666138160705C0.729736328125,8.990334138160705,1.1847533881249999,9.707831938160705,1.857309928125,10.080586038160705L2.519968628125,9.417918838160706C1.989151028125,9.249912838160705,1.604736328125,8.752919338160705,1.604736328125,8.166666138160705L1.604736328125,5.833333138160706C1.604736328125,5.108252138160705,2.192164028125,4.520833138160706,2.917236328125,4.520833138160706L3.864583228125,4.520833138160706C4.111887428125,4.520833138160706,4.351074028125,4.4309958381607055,4.537139628125,4.268250538160705L7.103820828125,2.0224138381607055C7.575144328125,1.6099967381607057,8.313069328125,1.9448330381607055,8.313069328125,2.5713360381607053L8.313069328125,3.6248358381607058L9.188069328125,2.7498358381607053Z" fill="#FFFFFF" fill-opacity="1"/><path d="M9.188069388879395,6.8751726150512695L8.313069388879395,7.7501726150512695L8.313069388879395,11.42867231505127C8.313069388879395,12.055175315051269,7.575144088879394,12.39001181505127,7.103820288879394,11.97759441505127L5.493814768879394,10.56883951505127L4.8737382888793945,11.18892481505127L6.5275010888793945,12.63617661505127C7.564640988879395,13.54384331505127,9.188069388879395,12.807092715051269,9.188069388879395,11.42867231505127L9.188069388879395,6.8751726150512695Z" fill="#FFFFFF" fill-opacity="1"/><path d="M10.519225743566894,5.543419959263916C11.048904063566894,6.679164689263916,10.926391243566895,8.038332489263915,10.150583580566895,9.070834589263917C10.005889575566895,9.263914589263916,10.044412931566894,9.538081689263915,10.238062213566895,9.683336689263916C10.431141853566894,9.828003889263915,10.705327033566894,9.789498289263916,10.850555063566894,9.595831389263916C11.887160943566894,8.215666289263917,11.993331543566894,6.369420189263916,11.169067043566894,4.893587589263916L10.519225743566894,5.543419959263916Z" fill="#FFFFFF" fill-opacity="1"/><path d="M11.747202221848145,4.3160754470959475C12.761021631848145,6.290655617095947,12.584853731848145,8.708574817095947,11.218093551848144,10.529159117095947C11.073435149848144,10.722238517095947,11.112528165848145,10.996406117095948,11.305607791848145,11.141660717095947C11.498687411848145,11.286328317095947,11.772872571848145,11.247822717095946,11.918100651848144,11.054155317095947C13.545587731848144,8.886487017095948,13.703704331848144,5.9814896170959475,12.392949131848145,3.6703286170959473L11.747202221848145,4.3160754470959475Z" fill="#FFFFFF" fill-opacity="1"/><path d="M12.5598954921875,2.0591658358917235C12.7307934921875,1.8882496358917238,12.7307934921875,1.6117501858917236,12.5598954921875,1.4408339558917236C12.3889614921875,1.2699177268917237,12.1124624921875,1.2699177268917237,11.9415284921875,1.4408339558917236L1.4415283221875,11.940833335891723C1.2706298831875,12.111750335891724,1.2706298831875,12.388249335891723,1.4415283221875,12.559165335891723C1.6124623421875,12.730081335891724,1.8889617921875002,12.730081335891724,2.0598958121875,12.559165335891723L12.5598954921875,2.0591658358917235Z" fill="#FFFFFF" fill-opacity="1"/></svg>',zh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="14" height="14" viewBox="0 0 14 14"><path d="M3.348292020680237,2.6424992084503174C2.923644920680237,2.6424992084503174,2.578287720680237,2.9849191084503177,2.578287720680237,3.4125035084503175L2.578287720680237,4.474174308450317C2.578287720680237,4.715657508450317,2.382288570680237,4.911674308450317,2.140787720680237,4.911674308450317C1.8992868706802368,4.911674308450317,1.7032877206802368,4.715657508450317,1.7032877206802368,4.474174308450317L1.7032877206802368,3.4125035084503175C1.7032877206802368,2.4984104584503175,2.442957520680237,1.7674992084503174,3.348292020680237,1.7674992084503174L10.651636720680237,1.7674992084503174C11.565124120680236,1.7674992084503174,12.296640720680237,2.5071690084503175,12.296640720680237,3.4125035084503175L12.296640720680237,4.474174308450317C12.296640720680237,4.715657508450317,12.100641720680237,4.911674308450317,11.859140720680237,4.911674308450317C11.617640120680237,4.911674308450317,11.421641020680237,4.715657508450317,11.421641020680237,4.474174308450317L11.421641020680237,3.4125035084503175C11.421641020680237,2.9878386084503177,11.079203220680236,2.6424992084503174,10.651636720680237,2.6424992084503174L7.435114520680237,2.6424992084503174C7.436289420680237,2.657666388450317,7.437464320680236,2.6734210884503176,7.437464320680236,2.6891580184503177L7.437464320680236,11.357500308450318L8.714965420680237,11.357500308450318C8.956466320680237,11.357500308450318,9.152465420680237,11.553499508450317,9.152465420680237,11.795000208450318C9.152465420680237,12.036501208450318,8.956466320680237,12.232500208450318,8.714965420680237,12.232500208450318L5.284962820680237,12.232500208450318C5.043461920680237,12.232500208450318,4.847462820680237,12.036501208450318,4.847462820680237,11.795000208450318C4.847462820680237,11.553499508450317,5.043461920680237,11.357500308450318,5.284962820680237,11.357500308450318L6.562464320680236,11.357500308450318L6.562464320680236,2.6891580184503177C6.562464320680236,2.6734210884503176,6.563033720680237,2.657666388450317,6.564814220680237,2.6424992084503174L3.348292020680237,2.6424992084503174Z" fill="#868A9C" fill-opacity="1"/></svg>',$h='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="2" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="4" y="4.5" width="1" height="6" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="6" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="8" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="10" y="5" width="1" height="5" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="12" y="6" width="1" height="3" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="14" y="4" width="1" height="7" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="16" y="6.5" width="1" height="2" rx="0.5" fill="#B5B6BF" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#B5B6BF" fill-opacity="1"/></svg>',Vh='<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" fill="none" version="1.1" width="19" height="15" viewBox="0 0 19 15"><rect x="0" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="2" y="7" width="15" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="4" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="6" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="8" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="10" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="12" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="14" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="16" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/><rect x="18" y="7" width="1" height="1" rx="0.5" fill="#C9CBD4" fill-opacity="1"/></svg>',Uh=new Map([["OmAi-camera",Lh],["OmAi-accept",Dh],["OmAi-display",Oh],["OmAi-hide",Bh],["OmAi-loading",Fh],["OmAi-music",Hh],["OmAi-volume",Gh],["OmAi-volume-mute",Nh],["OmAi-text",zh],["clip-audio",$h],["clip-without-audio",Vh]]),cn=new Map;function be(n){return Uh.get(n)??""}function Wh(n){const e=cn.get(n);if(e)return e;const t=be(n);if(!t)return null;const i=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`,r=typeof Image>"u"?{src:i,complete:!0,naturalWidth:1,addEventListener:()=>{}}:new Image;return"decoding"in r&&(r.decoding="async"),r.src=i,cn.set(n,r),r}const ue=3,hn=10,Yh=4,Xh=6,dn=8,un=14,jr=10,jh=12,qh=4,eo=1,Zi=28,to=8,ri=12,qr=19,Ji=15,Kh=12;function pi(n,e,t,i,r=P.white,s=P.black,a=1){return new Z.Rect({x:n,y:e,width:t,height:i,fill:r,stroke:s,strokeWidth:a})}function xt(n,e,t,i=12,r="Arial",s=P.black,a="left",o="top"){return new Z.Text({text:n,x:e,y:t,fontSize:i,fontFamily:r,fill:s,align:a,verticalAlign:o})}function Pt(n=0,e=0){return new Z.Group({x:n,y:e})}function gi(n){n.ellipsis(!1),n.wrap("none"),n.width("auto")}function Ss(n){return typeof n=="string"&&n.trim().length>0?n.trim():"媒体丢失"}function hr(n,e,t,i){if(i){n.add(new Z.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-left",listening:!0})),n.add(new Z.Rect({x:0,y:0,width:e,height:t,name:"clip-resize-right",listening:!0}));return}n.add(new Z.Rect({x:0,y:0,width:ue,height:t,name:"clip-resize-left"})),n.add(new Z.Rect({x:e-ue,y:0,width:ue,height:t,name:"clip-resize-right"}))}function Zh(n,e,t,i){const r=n.findOne(".clip-resize-left"),s=n.findOne(".clip-resize-right");return!r||!s?!1:(r.x(0),r.y(0),r.width(ue),r.height(t),s.x(e-ue),s.y(0),s.width(ue),s.height(t),!0)}function io(n,e,t){const i=e?n.clipSelectedBorder:P.transparent,r=e?eo:0;return t==="audio"?{background:P.audioClipBackground,label:n.audioClipText||n.clipName,accent:n.audioClipAccent||n.clipHandle,coverBackground:n.clipCoverBackground||ee.clipCoverBackground,failedBackground:P.mediaClipFailedBackground,failedLabel:n.audioClipText||n.clipName,border:i,borderWidth:r}:t==="text"?{background:P.textClipBackground,label:n.clipName,accent:n.clipHandle,coverBackground:n.clipCoverBackground||P.accentCoverFallback,failedBackground:P.mediaClipFailedBackground,failedLabel:n.clipName,border:i,borderWidth:r}:{background:P.videoClipBackground,label:n.clipName,accent:n.clipHandle,coverBackground:n.clipCoverBackground||P.accentCoverFallback,failedBackground:P.mediaClipFailedBackground,failedLabel:n.clipName,border:i,borderWidth:r}}function ro(n,e,t,i,r){const s=xt(i,0,Math.max(0,Math.floor((t-ri)/2)-2),ri,"Arial",r,"center","middle");s.width(e),s.height(ri+6),s.name("clip-media-status"),n.add(s)}function Jh(n,e,t,i,r,s){const a=xt(r,e,t,Kh,"Arial",s,"center","middle");a.width(i),a.height(Ji),a.name("clip-media-status"),n.add(a)}function Qh(n,e,t,i){const r=pi(0,0,e,t,i.background,i.border,i.borderWidth);r.cornerRadius(Math.min(4,Math.floor(e/2))),r.name("clip-background"),n.add(r),hr(n,e,t,!0)}function ed(n,e,t){const i=e.mediaStatus==="failed",r=Ss(e.mediaStatusMessage),s=pi(0,0,e.width,e.height,t.background,t.border,t.borderWidth);s.cornerRadius(4),s.name("clip-background"),n.add(s),hr(n,e.width,e.height,!1);const a=15,o=e.height-a-4,l=e.width-ue*2,c=Pt(ue,2);c.name("clip-cover-container"),c.clip({x:0,y:0,width:l,height:o}),n.add(c);const h=pi(0,0,l,o,i?t.failedBackground:t.coverBackground,"transparent",0);h.cornerRadius(2),h.name("clip-cover-background"),c.add(h);const d=Pt(0,0);d.name("clip-covers-group"),d.setAttr("coverFallbackFill",i?t.failedBackground:t.coverBackground),d.setAttr("coverUnavailableFill",i?t.failedBackground:P.mediaClipFailedBackground),c.add(d),i?(ge.renderClipCovers(d,[],l,o,e.videoSrc,e.deferCoverRender),ro(c,l,o,r,t.failedLabel)):ge.renderClipCovers(d,e.thumbnails??[],l,o,e.videoSrc,e.deferCoverRender);const u=l>=120?Zi+to:0,g=xt(`${e.clipName} ${U.formatDuration(e.duration)}`,ue,e.height-a,jr,"Arial",t.label,"left","middle");g.height(a),gi(g),g.name("clip-label"),n.add(g),u>0&&no(n,e.width,e.height,e.hasSeparatedAudio)}function td(n,e,t){const i=n.findOne(".clip-background"),r=n.findOne(".clip-cover-container"),s=n.findOne(".clip-cover-background"),a=n.findOne(".clip-covers-group"),o=n.findOne(".clip-label"),l=n.findOne(".clip-media-status");if(!i||!r||!s||!a||!o)return!1;const c=e.mediaStatus==="failed",h=Ss(e.mediaStatusMessage);if(i.width(e.width),i.height(e.height),i.fill(t.background),i.stroke(t.border),i.strokeWidth(t.borderWidth),i.cornerRadius(4),!Zh(n,e.width,e.height))return!1;const d=15,u=e.height-d-4,g=e.width-ue*2;r.x(ue),r.y(2),r.clip({x:0,y:0,width:g,height:u}),s.width(g),s.height(u),s.fill(c?t.failedBackground:t.coverBackground),s.cornerRadius(2),a.setAttr("coverFallbackFill",c?t.failedBackground:t.coverBackground),a.setAttr("coverUnavailableFill",c?t.failedBackground:P.mediaClipFailedBackground),c?(ge.renderClipCovers(a,[],g,u,e.videoSrc,e.deferCoverRender),l?(l.text(h),l.x(0),l.y(Math.max(0,Math.floor((u-ri)/2)-2)),l.width(g),l.height(ri+6),l.fill(t.failedLabel)):ro(r,g,u,h,t.failedLabel)):(l==null||l.destroy(),ge.renderClipCovers(a,e.thumbnails??[],g,u,e.videoSrc,e.deferCoverRender));const f=g>=120?Zi+to:0;o.text(`${e.clipName} ${U.formatDuration(e.duration)}`),o.x(ue),o.y(e.height-d),o.fill(t.label),o.height(d),gi(o);const m=n.findOne(".video-audio-status");return m==null||m.destroy(),f>0&&no(n,e.width,e.height,e.hasSeparatedAudio),!0}function id(n,e){e.complete&&e.naturalWidth>0||e.addEventListener("load",()=>{var t,i;(i=(t=n.getLayer)==null?void 0:t.call(n))==null||i.batchDraw()},{once:!0})}function so(n,e,t,i,r){n.name()||n.name(r);const s=Wh(e);if(!s)return 0;const a=new Z.Image({x:0,y:0,width:t,height:i,image:s,listening:!1});return a.name(`${r}-image`),n.add(a),id(n,s),t}function no(n,e,t,i){const r=Pt(Math.max(ue,e-ue-Zi-2),Math.max(0,t-15));r.name("video-audio-status");const s=Pt(Math.max(0,Zi-qr),0),a=i?"video-audio-status-separated":"video-audio-status-active",o=i?"clip-without-audio":"clip-audio";s.name(a),so(s,o,qr,Ji,`${a}-icon`),r.add(s),n.add(r)}function rd(n,e,t){const i=e.mediaStatus==="failed",r=Ss(e.mediaStatusMessage),s=pi(0,0,e.width,e.height,i?t.failedBackground:t.background,t.border,t.borderWidth);s.cornerRadius(6),s.name("clip-background"),n.add(s),hr(n,e.width,e.height,!1);const a=ue+hn,o=Math.max(0,e.width-ue*2-hn*2),l=Yh,c=Pt(a,l),h=so(c,"clip-audio",qr,Ji,"audio-clip-icon");n.add(c);const d=a+h+dn,u=Math.max(0,o-h-dn);if(i&&u>0)Jh(n,d,l,u,r,t.failedLabel);else if(e.audioBadgeText&&u>0){const f=xt(e.audioBadgeText,d,l,jr,"Arial",t.label,"left","middle");f.height(Ji),gi(f),f.name("audio-clip-badge"),n.add(f)}const g=xt(e.clipName,a,e.height-Xh-un,jr,"Arial",t.label,"left","middle");g.height(un),gi(g),g.name("clip-label"),n.add(g)}function sd(n,e,t){const i=pi(0,0,e.width,e.height,t.background,t.border,t.borderWidth);i.cornerRadius(4),i.name("clip-background"),n.add(i),hr(n,e.width,e.height,!1);const r=xt(e.clipName,qh,0,jh,"Arial",t.label,"left","middle");r.height(e.height),r.lineHeight(1),gi(r),r.name("clip-label"),n.add(r)}function ao(n,e){const t=e.width<=hi,i=io(e.theme,e.isSelected,e.clipType);if(n.destroyChildren(),t){Qh(n,e.width,e.height,i);return}if(e.clipType==="audio"){rd(n,e,i);return}if(e.clipType==="text"){sd(n,e,i);return}ed(n,e,i)}function nd(n,e){if(e.width<=hi||e.clipType!=="video")return!1;const i=io(e.theme,e.isSelected,e.clipType);return td(n,e,i)}function ad(n,e,t,i,r,s,a,o=!1,l,c,h="video",d=!1,u=!1,g,f,m){const C=Pt(n,e);return C.clip({x:0,y:0,width:t,height:i}),ao(C,{width:t,height:i,clipName:r,audioBadgeText:g,duration:s,theme:a,isSelected:o,thumbnails:l,videoSrc:c,clipType:h,hasSeparatedAudio:d,deferCoverRender:u,mediaStatus:f,mediaStatusMessage:m}),C}function od(n,e,t,i,r,s,a=!1,o,l,c="video",h=!1,d=!1,u,g,f){n.clip({x:0,y:0,width:e,height:t});const m={width:e,height:t,clipName:i,audioBadgeText:u,duration:r,theme:s??Yi,isSelected:a,thumbnails:o,videoSrc:l,clipType:c,hasSeparatedAudio:h,deferCoverRender:d,mediaStatus:g,mediaStatusMessage:f};nd(n,m)||ao(n,m)}function ld(n,e,t,i){return new Z.Rect({x:n,y:e,width:t,height:i,stroke:P.clipSelectedBorder,strokeWidth:eo,fillEnabled:!1})}function Kr(n,e=Ct.stroke,t=1){return new Z.Line({points:n,stroke:e,strokeWidth:t,lineCap:"round",lineJoin:"round"})}function cd(n,e,t,i=12,r="Arial",s=Ct.text,a="left",o="top"){return new Z.Text({text:n,x:e,y:t,fontSize:i,fontFamily:r,fill:s,align:a,verticalAlign:o})}function hd(n=0,e=0){return new Z.Group({x:n,y:e})}function dd(n,e,t,i,r,s,a,o){const l=o||i,c=a==="major"?l*.6:l*.3,h=Kr([e,t,e,t+c],s.timeTick,a==="major"?1:.5);if(h.name("time-tick-line"),n.add(h),a==="major"){const d=t+c+5,u=cd(U.formatTime(r),e,d,10,"Arial",s.timeText,"center");u.name("time-tick-text"),n.add(u)}}function ud(n,e,t,i,r,s){const a=hd(e,t);for(let o=0;o<=i;o+=s)a.add(Kr([o,0,o,r],_s.line,.5));for(let o=0;o<=r;o+=s)a.add(Kr([0,o,i,o],_s.line,.5));n.add(a)}class de{static createStage(e,t,i){return new Z.Stage({container:e,width:t,height:i})}static createLayer(e){const t=new Z.Layer;return t.name(e),t}static createRect(e,t,i,r,s=Ct.fill,a=Ct.stroke,o=1){return new Z.Rect({x:e,y:t,width:i,height:r,fill:s,stroke:a,strokeWidth:o})}static createText(e,t,i,r=12,s="Arial",a=Ct.text,o="left",l="top"){return new Z.Text({text:e,x:t,y:i,fontSize:r,fontFamily:s,fill:a,align:o,verticalAlign:l})}static createLine(e,t=Ct.stroke,i=1){return new Z.Line({points:e,stroke:t,strokeWidth:i,lineCap:"round",lineJoin:"round"})}static createGroup(e=0,t=0){return new Z.Group({x:e,y:t})}static drawTimeTick(e,t,i,r,s,a,o,l){dd(e,t,i,r,s,a,o,l)}static drawGrid(e,t,i,r,s,a){ud(e,t,i,r,s,a)}static clearImageCache(){ge.clearImageCache()}static createClipGroup(e,t,i,r,s,a,o,l=!1,c,h,d="video",u=!1,g=!1,f,m,C){return ad(e,t,i,r,s,a,o,l,c,h,d,u,g,f,m,C)}static updateClipGroup(e,t,i,r,s,a,o=!1,l,c,h="video",d=!1,u=!1,g,f,m){od(e,t,i,r,s,a,o,l,c,h,d,u,g,f,m)}static createSelectionEffect(e,t,i,r){return ld(e,t,i,r)}static timeToPixels(e,t){return e/1e3*t}static pixelsToTime(e,t){return e/t*1e3}}p(de,"RESIZE_AREA_WIDTH",3);const Xt=8;function fe(n,e,t){return de.timeToPixels(n,e)-t+pe}function Ce(n,e){const t=Math.max(n,0),i=de.timeToPixels(t,e);return i<=hi?hi:i}function pd(n,e){const t=fe(n.startTime,n.zoom,n.scrollLeft),i=Ce(n.duration,n.zoom);return t+i>0&&t<e}function gd(n){for(const e of n.clips){const t=fe(e.startTime,n.zoom,n.scrollLeft),i=Ce(e.duration,n.zoom),r=n.y>=n.trackY&&n.y<=n.trackY+n.trackHeight;if(n.x>=t&&n.x<=t+Xt&&r||n.x>=t+i-Xt&&n.x<=t+i&&r)return"ew-resize";if(n.x>t+Xt&&n.x<t+i-Xt&&r)return"pointer"}return"default"}class zi{constructor(e,t,i){p(this,"clip");p(this,"onUpdate");p(this,"onSplit");this.clip=cs({...e,endTime:U.calculateEndTime(e.startTime,e.duration)},{isDragging:e.isDragging,isResizingLeft:e.isResizingLeft,isResizingRight:e.isResizingRight,isSelected:e.isSelected,isResizing:e.isResizing,zIndex:e.zIndex,opacity:e.opacity}),this.onUpdate=t,this.onSplit=i}getClip(){return{...this.clip}}applyPreviewState(e){this.clip={...this.clip,...e,endTime:U.calculateEndTime(e.startTime,e.duration)}}setSelected(e){this.clip={...this.clip,isSelected:e},this.onUpdate(this.clip)}isPointInResizeHandle(e,t,i,r,s,a){const o=fe(this.clip.startTime,i,a),l=Ce(this.clip.duration,i),c=Xt;return t<r||t>r+s?(this.setResizeHandleState(!1,!1),!1):e>=o&&e<=o+c?(this.setResizeHandleState(!0,!1),!0):e>=o+l-c&&e<=o+l?(this.setResizeHandleState(!1,!0),!0):(this.setResizeHandleState(!1,!1),!1)}startDrag(e){this.clip={...this.clip,isDragging:!0,isResizing:!1,isResizingLeft:!1,isResizingRight:!1},this.onUpdate(this.clip)}startResize(e){this.clip={...this.clip,isDragging:!0,isResizing:!0},this.onUpdate(this.clip)}endDrag(){this.clip={...this.clip,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1}}split(e){e>this.clip.startTime+1&&e<this.clip.endTime-1&&this.onSplit(this.clip,e)}setResizeHandleState(e,t){this.clip={...this.clip,isResizingLeft:e,isResizingRight:t}}}function dr(n){let e=!1;return typeof window<"u"&&(window.addEventListener("mousemove",n.onPointerMove),window.addEventListener("mouseup",n.onPointerEnd),window.addEventListener("blur",n.onWindowBlur||n.onPointerEnd),e=!0),typeof document<"u"&&(document.addEventListener("visibilitychange",n.onVisibilityChange),e=!0),e}function ur(n){typeof window<"u"&&(window.removeEventListener("mousemove",n.onPointerMove),window.removeEventListener("mouseup",n.onPointerEnd),window.removeEventListener("blur",n.onWindowBlur||n.onPointerEnd)),typeof document<"u"&&document.removeEventListener("visibilitychange",n.onVisibilityChange)}function Qi(){return{kind:"idle"}}function pn(n){return!!n&&n.kind!=="idle"}function er(n){return(n==null?void 0:n.kind)==="draggingMove"||(n==null?void 0:n.kind)==="draggingResizeLeft"||(n==null?void 0:n.kind)==="draggingResizeRight"}function ft(n){return!n||n.kind==="idle"||n.kind==="boxSelecting"?null:n.context}function tr(n){return!n||n.kind==="idle"||n.kind==="boxSelecting"?null:n.kind==="pressed"?n.operation:n.kind==="draggingResizeLeft"?"resize-left":n.kind==="draggingResizeRight"?"resize-right":"move"}function fd(n){const e=tr(n);return e?e==="move"?"grabbing":"ew-resize":null}function Di(n,e){if(e.type==="POINTER_DOWN")return{state:{kind:"pressed",operation:e.operation,context:{clipId:e.clipId,originalClipsState:e.originalClipsState,nonDraggedClips:e.nonDraggedClips,snapCandidateClips:e.snapCandidateClips,pointerStartClientX:e.clientX,pointerStartClientY:e.clientY,pointerStartX:e.localX,pointerStartY:e.localY,dragStartScrollLeft:e.scrollLeft,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:e.localY,crossTrackDragOffsetY:0}},effects:{bindGlobalListeners:!0}};if(e.type==="BOX_SELECT_START")return{state:{kind:"boxSelecting",context:{startClientX:e.clientX,startClientY:e.clientY,startLocalX:e.localX,startLocalY:e.localY,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY,additive:e.additive}},effects:{bindGlobalListeners:!0}};if(n.kind==="idle")return{state:n,effects:{}};if(n.kind==="boxSelecting")return e.type==="BOX_SELECT_MOVE"?{state:{kind:"boxSelecting",context:{...n.context,currentClientX:e.clientX,currentClientY:e.clientY,currentLocalX:e.localX,currentLocalY:e.localY}},effects:{updatePreview:!0}}:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP"||e.type==="CANCEL"||e.type==="VISIBILITY_HIDDEN"||e.type==="WINDOW_BLUR"?{state:Qi(),effects:{unbindGlobalListeners:!0,commit:e.type==="BOX_SELECT_END"||e.type==="POINTER_UP",cleanup:!0}}:{state:n,effects:{}};if(e.type==="POINTER_MOVE"){const i=yd(n.context,e,tr(n)||"move");return n.kind==="pressed"?Sd(n.context,e.activationThreshold,e.clientX,e.clientY)?{state:md(n.operation,i),effects:{updatePreview:!0}}:{state:{...n,context:i},effects:{}}:{state:{...n,context:i},effects:{updatePreview:!0}}}if(e.type==="SCROLL_LEFT_CHANGED")return{state:n,effects:{updatePreview:er(n)}};const t=e.type==="POINTER_UP"&&er(n);return{state:Qi(),effects:{unbindGlobalListeners:!0,commit:t,cleanup:!0}}}function md(n,e){return n==="resize-left"?{kind:"draggingResizeLeft",context:e}:n==="resize-right"?{kind:"draggingResizeRight",context:e}:{kind:"draggingMove",context:e}}function yd(n,e,t){const i=t==="move";return{...n,lastPointerClientX:e.clientX,lastPointerClientY:e.clientY,dragTargetTrackY:i?e.localY:n.pointerStartY,crossTrackDragOffsetY:i?e.localY-n.pointerStartY:0}}function Sd(n,e,t,i){const r=t-n.pointerStartClientX,s=i-n.pointerStartClientY;return Math.hypot(r,s)>=Math.max(0,e)}const le=class le{constructor(e,t,i,r,s,a,o,l,c,h,d,u,g,f,m,C,v,S,T,k,_,w,D,x,R,O,z=le.DEFAULT_DRAG_ACTIVATION_THRESHOLD,H=!1,$=le.DEFAULT_CLIP_SNAP_THRESHOLD){p(this,"layer");p(this,"trackGroup");p(this,"dragOverlayLayer",null);p(this,"dropPreviewGroup",null);p(this,"dropPreviewClips",[]);p(this,"config");p(this,"theme");p(this,"trackType");p(this,"clips",[]);p(this,"clipGroups",new Map);p(this,"zoom",100);p(this,"scrollLeft",0);p(this,"trackY",0);p(this,"trackHeight",64);p(this,"selectedClip",null);p(this,"hasSelectedClip",!1);p(this,"selectedClipIds",new Set);p(this,"multiDragOriginalPositions",new Map);p(this,"promotedClipParents",new Map);p(this,"interactionState",Qi());p(this,"isVisualUpdate",!1);p(this,"onClipUpdate");p(this,"onClipAdd");p(this,"onClipRemove");p(this,"onClipSplit");p(this,"onClipSelect");p(this,"onTimeJump");p(this,"onClipOverlap");p(this,"onPrimaryTrackMagnetMove");p(this,"hasBoundGlobalPointerListenersForDrag",!1);p(this,"hasLockedGlobalCursor",!1);p(this,"edgeAutoScrollAnimationFrameId",null);p(this,"onHorizontalDragAutoScroll");p(this,"onClipCrossTrackPreview");p(this,"onClipCrossTrack");p(this,"onClearDropPreview");p(this,"onClearSelection");p(this,"onSnapGuideChange");p(this,"onClipToggleSelection");p(this,"onSetSingleSelection");p(this,"getMultiDragClipIds");p(this,"onMultiDragMove");p(this,"onMultiDragInteractionEnd");p(this,"resolveSnapTargetClips");p(this,"dragActivationThreshold");p(this,"enableClipSnap");p(this,"clipSnapThreshold");p(this,"handleGlobalPointerMove",e=>{pn(this.interactionState)&&this.handleDragMove(e)});p(this,"handleGlobalPointerEnd",()=>{this.handleClipMouseUp()});p(this,"handleWindowBlur",()=>{this.finishPointerInteraction("WINDOW_BLUR")});p(this,"handleVisibilityChange",()=>{typeof document<"u"&&document.hidden&&this.finishPointerInteraction("VISIBILITY_HIDDEN")});p(this,"handleEdgeAutoScrollFrame",()=>{this.edgeAutoScrollAnimationFrameId=null;const e=this.interactionState;if(!er(e)||!this.onHorizontalDragAutoScroll)return;const t=this.layer.getStage(),i=t==null?void 0:t.container(),r=ft(e);if(!i||!r){this.stopEdgeAutoScroll();return}const s=i.getBoundingClientRect(),a=r.lastPointerClientX-s.left,o=this.calculateHorizontalAutoScrollVelocity(a,s.width);if(o===0){this.stopEdgeAutoScroll();return}const l=this.scrollLeft,c=this.onHorizontalDragAutoScroll(this.scrollLeft+o),h=typeof c=="number"?c:this.scrollLeft;if(Math.abs(h-l)<=.5){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()});this.layer=e,this.config=t,this.theme=o,this.trackType=i,this.zoom=r,this.trackY=s,this.trackHeight=a,this.onClipUpdate=l,this.onClipAdd=c,this.onClipRemove=h,this.onClipSplit=d,this.onClipSelect=u,this.onTimeJump=g,this.onHorizontalDragAutoScroll=f,this.onClipOverlap=m,this.onPrimaryTrackMagnetMove=C,this.onClipCrossTrackPreview=v,this.onClipCrossTrack=S,this.onClearDropPreview=T,this.onClearSelection=k,this.onSnapGuideChange=_,this.onClipToggleSelection=w,this.onSetSingleSelection=D,this.getMultiDragClipIds=x,this.onMultiDragMove=R,this.onMultiDragInteractionEnd=O,this.dragActivationThreshold=Math.max(0,z),this.enableClipSnap=H,this.clipSnapThreshold=Math.max(0,$),this.trackGroup=de.createGroup(0,s),this.layer.add(this.trackGroup),this.initClips(),this.initEventListeners(),this.render()}initClips(){this.clips=this.config.clips.map(e=>{const t=new zi(e,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));return this.createClipGroup(e),t})}ensureDropPreviewGroup(){if(this.dropPreviewGroup)return this.dropPreviewGroup;const e=de.createGroup(0,0);return e.name("clip-drop-preview"),e.visible(!1),e.listening(!1),this.trackGroup.add(e),this.dropPreviewGroup=e,e}createDropPreviewRect(e){const t=this.trackType==="text"?"rgba(96, 76, 51, 0.28)":this.trackType==="video"?bi.videoFill:bi.audioFill,i=this.trackType==="text"?"#C9CBD4":this.trackType==="video"?bi.videoStroke:bi.audioStroke,r=fe(e.startTime,this.zoom,this.scrollLeft),s=Ce(e.duration,this.zoom),a=de.createRect(r,2,Math.max(s,1),Math.max(this.trackHeight-4,1),t,i,1);return a.dash([6,4]),a.cornerRadius(4),a.listening(!1),a.visible(r+s>0&&r<this.layer.width()),a}showDropPreview(e){const t=this.ensureDropPreviewGroup(),i=Array.isArray(e)?e:[e];this.dropPreviewClips=i.map(s=>({...s})),t.destroyChildren();let r=!1;for(const s of this.dropPreviewClips){const a=this.createDropPreviewRect(s);r=r||a.visible(),t.add(a)}t.x(0),t.y(0),t.visible(r),t.moveToTop()}hideDropPreview(){var e;this.dropPreviewClips=[],(e=this.dropPreviewGroup)==null||e.visible(!1)}initEventListeners(){const e=this.layer.getStage();e&&e.on("mouseup",()=>{this.handleClipMouseUp()})}bindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag||(this.hasBoundGlobalPointerListenersForDrag=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}))}unbindGlobalPointerListenersForDrag(){this.hasBoundGlobalPointerListenersForDrag&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange,onWindowBlur:this.handleWindowBlur}),this.hasBoundGlobalPointerListenersForDrag=!1)}handleTrackBackgroundClick(e){const t=this.layer.getStage();if(!t)return;const i=t.container();if(!i)return;const r=i.getBoundingClientRect(),s=e.clientX-r.left,a=Math.max(0,U.pixelsToTime(s-pe+this.scrollLeft,this.zoom));this.onTimeJump(a),this.onClearSelection&&this.onClearSelection()}handleTrackBackgroundMouseDown(e){}getClipDisplayLabel(e){return(e.type==="text"||Me(e))&&e.textContent||e.name}getClipAudioBadgeText(e){if(Me(e))return e.name}isSourceBoundClip(e){return e.type!=="text"}updateClipSelection(e,t){const i=this.clips.find(r=>r.getClip().id===e);i&&(this.isVisualUpdate=!0,i.setSelected(t),this.isVisualUpdate=!1,t?this.selectedClipIds.add(e):this.selectedClipIds.delete(e),this.syncSelectionState(e),this.updateClipGroup(i.getClip()),this.render(!1),this.layer.batchDraw())}createClipGroup(e){const t=fe(e.startTime,this.zoom,this.scrollLeft),i=Ce(e.duration,this.zoom),r=2,s=this.trackHeight-4,a=de.createClipGroup(t,r,i,s,this.getClipDisplayLabel(e),e.duration,this.theme,!1,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,!1,this.getClipAudioBadgeText(e),e.mediaStatus,e.mediaStatusMessage);a.name(`clip-${e.id}`),a.on("click",o=>{this.handleClipClick(e.id,o.evt)}),a.on("mousedown",o=>{this.handleClipMouseDown(e.id,o.evt)}),a.on("mousemove",o=>{this.handleClipMouseMove(o.evt)}),a.on("mouseleave",()=>{this.handleClipMouseLeave()}),a.on("contextmenu",o=>{o.evt.preventDefault()}),this.trackGroup.add(a),this.clipGroups.set(e.id,a)}handleClipClick(e,t){if(t.button!==0)return;this.clips.find(r=>r.getClip().id===e)&&this.render()}handleClipMouseDown(e,t){var h;if(t.button!==0)return;if(t.ctrlKey||t.metaKey){this.onClipToggleSelection&&this.onClipToggleSelection(e);return}const i=(h=this.getMultiDragClipIds)==null?void 0:h.call(this,e),r=i!=null&&i.length>1;if(!r)this.selectedClipIds.clear(),this.selectedClipIds.add(e),this.onSetSingleSelection&&this.onSetSingleSelection(e);else{this.selectedClipIds.clear();for(const d of i)this.selectedClipIds.add(d)}this.clips.sort((d,u)=>d.getClip().startTime-u.getClip().startTime);const s=this.clips.map(d=>({...d.getClip()})),a=this.clips.filter(d=>d.getClip().id!==e).map(d=>({...d.getClip()})),l=(this.resolveSnapTargetClips?this.resolveSnapTargetClips():this.clips.map(d=>d.getClip())).filter(d=>d.id!==e).map(d=>({...d})),c=this.clips.find(d=>d.getClip().id===e);if(c){r||(this.applySelectionVisual(new Set([e])),this.onClipSelect(c.getClip())),this.selectedClip=c;const d=this.layer.getStage();if(!d)return;const u=d.container();if(!u)return;const g=u.getBoundingClientRect(),f=t.clientX-g.left,m=t.clientY-g.top;if(r){this.multiDragOriginalPositions.clear();for(const v of this.selectedClipIds){const S=this.clips.find(T=>T.getClip().id===v);if(S){const T=S.getClip();this.multiDragOriginalPositions.set(v,{startTime:T.startTime,duration:T.duration})}}}let C;c.isPointInResizeHandle(f,m,this.zoom,this.trackY,this.trackHeight,this.scrollLeft)?(C=c.getClip().isResizingLeft?"resize-left":"resize-right",c.startResize({x:f,y:m})):(C="move",c.startDrag({x:f,y:m}),this.trackGroup.moveToTop()),this.applyInteractionTransition(Di(this.interactionState,{type:"POINTER_DOWN",operation:C,clipId:e,originalClipsState:s,nonDraggedClips:a,snapCandidateClips:l,clientX:t.clientX,clientY:t.clientY,localX:f,localY:m,scrollLeft:this.scrollLeft})),this.render()}}handleClipMouseMove(e){this.updateHoverCursor(e.clientX,e.clientY)}handleTrackBackgroundMouseMove(){if(this.isDragSessionActive())return;const e=this.layer.getStage(),t=e==null?void 0:e.container();t&&(t.style.cursor="default")}handleClipMouseUp(){this.finishPointerInteraction("POINTER_UP")}finishPointerInteraction(e){const t=this.interactionState,i=this.resolveDraggedClipForInteraction(t);try{if(!i)return;const r=i.getClip();if(!r.isDragging)return;i.endDrag();const s=Di(t,{type:e});this.interactionState=s.state,s.effects.commit&&this.handleClipMoveEnd(r,t),this.layer.batchDraw()}finally{this.interactionState=Qi(),this.applyInteractionTransition({state:this.interactionState,effects:{cleanup:!0,unbindGlobalListeners:!0}})}}resolveDraggedClipForInteraction(e=this.interactionState){const t=ft(e);if(t!=null&&t.clipId){const r=this.clips.find(s=>s.getClip().id===t.clipId)??null;if(r)return r}const i=this.clips.find(r=>r.getClip().isDragging)??null;return i||this.selectedClip}applyInteractionTransition(e){var i,r;this.interactionState=e.state,e.effects.bindGlobalListeners&&this.bindGlobalPointerListenersForDrag();const t=fd(e.state);t&&this.lockPointerCursor(t),e.effects.cleanup&&(this.releasePointerCursor(),this.hideDropPreview(),(i=this.onClearDropPreview)==null||i.call(this),this.updateSnapGuideLine(null),this.stopEdgeAutoScroll(),this.clearClipDragOverlay(),this.multiDragOriginalPositions.size>0&&((r=this.onMultiDragInteractionEnd)==null||r.call(this),this.multiDragOriginalPositions.clear())),e.effects.unbindGlobalListeners&&this.unbindGlobalPointerListenersForDrag()}handleClipMoveEnd(e,t){var m,C,v;const i=t??this.interactionState,r=ft(i)||{clipId:e.id,originalClipsState:[e],nonDraggedClips:[],dragStartScrollLeft:this.scrollLeft,dragTargetTrackY:0,crossTrackDragOffsetY:0},s=tr(i)||(e.isResizingLeft?"resize-left":e.isResizingRight?"resize-right":"move"),a=s==="move",o=a&&this.multiDragOriginalPositions.size>0,l=(m=this.clipGroups)==null?void 0:m.get(e.id);if(l&&l.y(2),o){const S=this.multiDragOriginalPositions.get(e.id),T=S?e.startTime-S.startTime:0;if(this.onMultiDragMove&&this.config.id&&this.onMultiDragMove({draggedClipId:e.id,deltaTime:T,targetTrackY:r.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:r.crossTrackDragOffsetY,isFinal:!0})){for(const R of this.selectedClipIds){const O=(C=this.clipGroups)==null?void 0:C.get(R);O==null||O.y(2)}this.multiDragOriginalPositions.clear();return}const k=[],_=[];for(const[x,R]of this.multiDragOriginalPositions){const O=this.clips.find(G=>G.getClip().id===x);if(!O)continue;const z=Math.max(0,R.startTime+T),H={...O.getClip(),startTime:z,endTime:z+R.duration,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:this.selectedClipIds.has(x)};k.push(H);const $=r.originalClipsState.find(G=>G.id===x);$&&_.push($);const V=(v=this.clipGroups)==null?void 0:v.get(x);V&&V.y(2)}const w=[];for(const x of this.clips){const R=x.getClip(),O=k.find(z=>z.id===R.id);O?w.push(O):w.push({...R,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1})}w.sort((x,R)=>x.startTime-R.startTime),this.isVisualUpdate=!0;for(const x of w)this.clips.find(O=>O.getClip().id===x.id)&&this.handleClipUpdate(x);this.isVisualUpdate=!1;const D=_.map(x=>{const R=k.find(O=>O.id===x.id);return R&&(x.startTime!==R.startTime||x.duration!==R.duration)?{clipId:x.id,previousState:x,newState:R}:null}).filter(x=>x!==null);D.length>0&&this.onClipUpdate(e,_.find(x=>x.id===e.id),D),this.multiDragOriginalPositions.clear();return}if(a&&this.onClipCrossTrack&&this.config.id){const S=r.originalClipsState.find(k=>k.id===e.id)??null;if(this.onClipCrossTrack(e,S,r.dragTargetTrackY,this.config.id)){this.multiDragOriginalPositions.clear();return}}if(a&&this.config.role==="primary"&&this.onPrimaryTrackMagnetMove&&this.config.id){const S=r.originalClipsState.find(k=>k.id===e.id)??null;if(this.onPrimaryTrackMagnetMove(e,S,[...r.nonDraggedClips],this.config.id))return}const c=a?[...r.nonDraggedClips]:[];let h=!1;const d=e.startTime+e.duration;for(const S of c){const T=S.startTime+S.duration;if(e.startTime<T&&d>S.startTime){h=!0;break}}if(a&&h&&this.onClipOverlap&&this.config.id){const S=r.originalClipsState.find(T=>T.id===e.id)??null;this.onClipOverlap(e,this.config.id,S);return}const u=r.nonDraggedClips.map(S=>({...S}));if(s==="resize-right"){const S=r.originalClipsState.find(T=>T.id===e.id);if(S){const T=this.computeResizeRightPushFollowers(S,e,r.nonDraggedClips);for(const k of T){const _=u.findIndex(w=>w.id===k.id);_>=0&&(u[_]={...k,isSelected:!1})}}}let g=u.findIndex(S=>S.startTime>=e.startTime);g===-1&&(g=u.length),r.nonDraggedClips.forEach(S=>{S.isSelected=!1});const f={...e,isDragging:!1,isResizing:!1,isResizingLeft:!1,isResizingRight:!1,zIndex:1,opacity:1,isSelected:!0};u.splice(g,0,f),this.config.role==="primary"&&(s==="resize-left"||s==="resize-right")&&this.compactPrimaryTrackClips(u),this.updateAllClips(u),this.buildAndSendUpdates(f,u,r.originalClipsState)}compactPrimaryTrackClips(e){if(e.length<=1)return;const t=e.map((r,s)=>({clip:r,index:s})).sort((r,s)=>r.clip.startTime===s.clip.startTime?r.index-s.index:r.clip.startTime-s.clip.startTime);let i=t[0].clip.startTime+t[0].clip.duration;t[0].clip.endTime=i;for(let r=1;r<t.length;r+=1){const s=t[r].clip;s.startTime=i,s.endTime=s.startTime+s.duration,i=s.endTime}}updateAllClips(e){const t=this.clips??[];this.isVisualUpdate=!0,e.forEach(i=>{t.find(s=>s.getClip().id===i.id)&&this.handleClipUpdate(i)}),this.isVisualUpdate=!1,t.sort((i,r)=>i.getClip().startTime-r.getClip().startTime),this.clips=t}buildAndSendUpdates(e,t,i){const r=i.map(s=>{const a=t.find(o=>o.id===s.id);return a&&(s.startTime!==a.startTime||s.duration!==a.duration||s.opacity!==a.opacity)?{clipId:s.id,previousState:s,newState:a}:null}).filter(s=>s!==null);r.length>0&&this.onClipUpdate(e,i.find(s=>s.id===e.id),r)}updateHoverCursor(e,t){const i=this.layer.getStage();if(!i)return;const r=i.container();if(!r||this.isDragSessionActive())return;const s=r.getBoundingClientRect(),a=e-s.left,o=t-s.top;r.style.cursor=gd({clips:this.clips.map(l=>l.getClip()),zoom:this.zoom,scrollLeft:this.scrollLeft,trackY:this.trackY,trackHeight:this.trackHeight,x:a,y:o})}isDragSessionActive(){return pn(this.interactionState)}handleDragMove(e){const t=this.interactionState,i=this.layer.getStage(),r=i==null?void 0:i.container();if(!r)return;const s=r.getBoundingClientRect(),a=Di(t,{type:"POINTER_MOVE",clientX:e.clientX,clientY:e.clientY,localY:e.clientY-s.top,activationThreshold:this.dragActivationThreshold});this.interactionState=a.state,a.effects.updatePreview&&this.updateDraggedClipFromPointer(e.clientX,e.clientY,!0)}handleClipMouseLeave(){if(this.isDragSessionActive())return;const e=this.layer.getStage();e&&e.container()&&(e.container().style.cursor="default")}lockPointerCursor(e){const t=typeof this.layer.getStage=="function"?this.layer.getStage():null,i=t==null?void 0:t.container();i&&(i.style.cursor=e),typeof document<"u"&&document.body&&(document.body.style.cursor=e,this.hasLockedGlobalCursor=!0)}releasePointerCursor(){const e=typeof this.layer.getStage=="function"?this.layer.getStage():null,t=e==null?void 0:e.container();t&&(t.style.cursor="default"),this.hasLockedGlobalCursor&&typeof document<"u"&&document.body&&(document.body.style.cursor="",this.hasLockedGlobalCursor=!1)}updateClipGroup(e,t=!1){const i=this.clipGroups.get(e.id);if(i){const r=Ce(e.duration,this.zoom);this.updateClipViewportState(e);const s=e.isSelected;(e.isDragging||s)&&i.moveToTop(),i.opacity(e.opacity),de.updateClipGroup(i,r,this.trackHeight-4,this.getClipDisplayLabel(e),e.duration,this.theme,s,e.thumbnails,e.src,e.type,!!e.separatedAudioClipId,t,this.getClipAudioBadgeText(e),e.mediaStatus,e.mediaStatusMessage)}}handleClipUpdate(e){const t=this.clips.findIndex(i=>i.getClip().id===e.id);if(t!==-1){const i=this.clips[t].getClip(),r={...e,isSelected:this.isVisualUpdate?e.isSelected:this.selectedClipIds.has(e.id)};this.clips[t]=new zi(r,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this)),this.syncSelectionState(e.id),this.updateClipGroup(r);const s=this.clipGroups.get(e.id);s&&s.opacity(r.opacity),this.isVisualUpdate||this.onClipUpdate(r,i),this.layer.batchDraw()}}handleClipSplit(e,t){const i=t-e.startTime,r=e.duration-i,s=e.startTimeAtSource+i,a={...e,duration:i,endTime:t,endTimeAtSource:s},o={...e,id:`${e.id}_split_${Date.now()}`,startTime:t,duration:r,endTime:U.calculateEndTime(t,r),startTimeAtSource:s,endTimeAtSource:e.endTimeAtSource};this.removeClip(e.id),this.addClip(a),this.addClip(o),this.onClipSplit(a,o),this.layer.batchDraw()}addClip(e){if(e.type!==this.trackType){N.warn("Track",`片段类型不匹配: 轨道类型 ${this.trackType}, 片段类型 ${e.type}`);return}const t={...e,isSelected:!1},i=new zi(t,this.handleClipUpdate.bind(this),this.handleClipSplit.bind(this));this.clips.push(i),this.createClipGroup(t),this.onClipAdd(t),this.layer.batchDraw()}removeClip(e){const t=this.clips.findIndex(i=>i.getClip().id===e);if(t!==-1){this.clips.splice(t,1),this.selectedClipIds.delete(e),this.syncSelectionState();const i=this.clipGroups.get(e);i&&(this.getPromotedClipParents().delete(e),i.remove(),this.clipGroups.delete(e)),this.onClipRemove(e),this.hideDropPreview(),this.render(!1),this.layer.batchDraw()}}updateClip(e,t){const i=this.clips.find(r=>r.getClip().id===e);if(i){const s={...i.getClip(),...t};(t.startTime!==void 0||t.duration!==void 0)&&(s.endTime=s.startTime+s.duration),this.handleClipUpdate(s)}}setZoom(e){this.zoom=e,this.clips.forEach(t=>{this.updateClipGroup(t.getClip())}),this.layer.batchDraw()}setCurrentTime(e){}setScrollLeft(e){this.scrollLeft=e,this.clips.forEach(s=>{const a=s.getClip();this.updateClipViewportState(a)});const t=this.interactionState,i=ft(t),r=Di(t,{type:"SCROLL_LEFT_CHANGED"});this.interactionState=r.state,r.effects.updatePreview&&i&&this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1),this.layer.batchDraw()}updateClipVisibility(e){const t=this.clipGroups.get(e.id);if(t){const i=pd({startTime:e.startTime,duration:e.duration,zoom:this.zoom,scrollLeft:this.scrollLeft},this.layer.width());t.visible(i)}}updateClipViewportState(e){const t=this.clipGroups.get(e.id);t&&(t.x(fe(e.startTime,this.zoom,this.scrollLeft)),this.updateClipVisibility(e))}setTrackY(e){const t=e-this.trackY;this.trackY=e,this.trackGroup.y(e),this.getPromotedClipParents().forEach((i,r)=>{i.baseY=e;const s=this.clipGroups.get(r);s&&s.y(s.y()+t)})}setTrackStackOrder(e){this.trackGroup.zIndex(e)}setDragOverlayLayer(e){this.dragOverlayLayer=e}setClipsDragOverlayActive(e,t){e.forEach(i=>{this.setClipDragOverlayActive(i,t)})}clearClipDragOverlay(){Array.from(this.getPromotedClipParents().keys()).forEach(e=>{this.setClipDragOverlayActive(e,!1)})}getTrackType(){return this.trackType}render(e=!0){const t=this.getTrackBackgroundFill();if(this.trackGroup.children.length===0){const i=de.createRect(0,0,this.layer.width(),this.trackHeight,t,this.theme.trackBorder,1);i.name("track-background"),i.on("click",r=>{this.handleTrackBackgroundClick(r.evt)}),i.on("mousedown",r=>{this.handleTrackBackgroundMouseDown(r.evt)}),i.on("mousemove",()=>{this.handleTrackBackgroundMouseMove()}),i.on("mouseleave",()=>{this.handleClipMouseLeave()}),this.trackGroup.add(i)}else{const i=this.trackGroup.findOne(".track-background");i&&(i.width(this.layer.width()),typeof i.height=="function"&&i.height(this.trackHeight),i.fill(t),i.stroke(this.theme.trackBorder),i.listening()||i.listening(!0))}e&&this.layer.batchDraw()}getTrackBackgroundFill(){return this.hasSelectedClip?this.theme.trackSelectedBackground||ee.trackSelectedBackground:this.theme.trackBackground}getClips(){return this.clips.map(e=>e.getClip())}getPrimarySelectedClip(){return this.selectedClip?this.selectedClip.getClip():null}clearSelection(){this.setSelection([])}setSelection(e,t){const i=new Set(e);this.applySelectionVisual(i),this.selectedClipIds=i,this.syncSelectionState(t??e[0]??void 0),this.render()}applySelectionVisual(e){this.isVisualUpdate=!0;try{this.clips.forEach(t=>{const i=t.getClip().id,r=e.has(i);t.setSelected(r)})}finally{this.isVisualUpdate=!1}}syncSelectionState(e){var a;const t=this.clips.filter(o=>this.selectedClipIds.has(o.getClip().id)),r=t.length>0?t:this.clips.filter(o=>o.getClip().isSelected);if(this.selectedClipIds=new Set(r.map(o=>o.getClip().id)),this.hasSelectedClip=r.length>0,!this.hasSelectedClip){this.selectedClip=null;return}const s=e??((a=this.selectedClip)==null?void 0:a.getClip().id)??null;this.selectedClip=r.find(o=>o.getClip().id===s)??r[r.length-1]??null}splitSelectedClip(e){const t=this.clips.find(i=>{const r=i.getClip();return e>=r.startTime&&e<r.endTime});t&&t.getClip().type!=="text"&&t.split(e)}removeClipGaps(){N.debugLazy("Track",()=>"Removing clip gaps");const e=this.clips.map(i=>i.getClip()).sort((i,r)=>i.startTime-r.startTime);if(e.length===0)return;let t=0;for(let i=0;i<e.length;i++){const r=e[i];if(t-r.startTime<0||i===0){const a=t,o=a+r.duration;this.handleClipUpdate({...r,startTime:a,endTime:o}),t=o}else t=r.startTime+r.duration}}getTrackGroup(){return this.trackGroup}getId(){return this.config.id||"default"}updateClipPosition(e,t,i,r=0){var l;const s=this.clips.find(c=>c.getClip().id===e);if(!s)return;const a=s.getClip(),o=this.clipGroups.get(e);if(i)this.setClipDragOverlayActive(e,!1),this.updateClipPositionFinal(e,t);else if(o){const c=fe(t,this.zoom,this.scrollLeft);o.x(c),o.y(this.resolveClipRenderY(e,r)),o.moveToTop(),de.updateClipGroup(o,Ce(a.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(a),a.duration,this.theme,!0,a.thumbnails,a.src,a.type,!!a.separatedAudioClipId,!0,this.getClipAudioBadgeText(a),a.mediaStatus,a.mediaStatusMessage),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw()}}updateClipPositionFinal(e,t){const i=this.clips.find(a=>a.getClip().id===e);if(!i)return;const r=i.getClip(),s=this.clipGroups.get(e);this.setClipDragOverlayActive(e,!1),s==null||s.y(2),this.isVisualUpdate=!0,this.handleClipUpdate({...r,startTime:t,endTime:t+r.duration}),this.isVisualUpdate=!1}setTrackHeight(e){var t,i;if(this.trackHeight=e,(t=this.dropPreviewGroup)!=null&&t.visible()&&Array.isArray(this.dropPreviewClips)&&this.dropPreviewClips.length>0)this.showDropPreview(this.dropPreviewClips);else if((i=this.dropPreviewGroup)!=null&&i.visible()){const r=this.dropPreviewGroup.children[0];r==null||r.height(Math.max(this.trackHeight-4,1))}this.clips.forEach(r=>{this.updateClipGroup(r.getClip(),!0)}),this.render(!1)}showClipDropPreview(e){this.showDropPreview(e),this.layer.batchDraw()}showClipDropPreviews(e){this.showDropPreview(e),this.layer.batchDraw()}clearClipDropPreview(){this.hideDropPreview(),this.layer.batchDraw()}getRole(){return this.config.role||"normal"}setClipSnapEnabled(e){this.enableClipSnap=e,e||this.updateSnapGuideLine(null);const t=this.interactionState,i=ft(t);if(er(t)&&i){this.updateDraggedClipFromPointer(i.lastPointerClientX,i.lastPointerClientY,!1);return}this.render()}setSnapTargetResolver(e){this.resolveSnapTargetClips=e}updateDraggedClipFromPointer(e,t,i){var v,S,T,k,_,w;const r=this.interactionState,s=ft(r),a=tr(r),o=this.layer.getStage(),l=this.resolveDraggedClipForInteraction(r);if(!o||!l||!s||!a)return;const c=o.container();if(!c)return;const h=c.getBoundingClientRect(),d=e-h.left,u=t-h.top,g=a==="move",f=g&&this.multiDragOriginalPositions.size>0;g&&N.debugLazy("Track",()=>"Cross-track drag detected",()=>({targetTrackY:u,currentTrackId:this.config.id,offsetY:s.crossTrackDragOffsetY}));const m=l.getClip(),C=(v=this.clipGroups)==null?void 0:v.get(m.id);if(C){const D=g&&s.crossTrackDragOffsetY!==0;this.setClipDragOverlayActive(m.id,D);const x=s.originalClipsState.find(L=>L.id===m.id);if(!x)return;const R=this.buildPreviewClip(m,x,d,s,a);if(!R){this.hideDropPreview(),(S=this.onClearDropPreview)==null||S.call(this),this.updateSnapGuideLine(null);return}const O=R.clip,z=O.startTime-x.startTime,H=this.applyPreviewClipState(l,O),$=fe(O.startTime,this.zoom,this.scrollLeft),V=Ce(O.duration,this.zoom);C.x($),C.y(this.resolveClipRenderY(m.id,s.crossTrackDragOffsetY)),C.visible($+V>0&&$<this.layer.width()),H&&(this.updateClipGroup(O),C.y(this.resolveClipRenderY(m.id,s.crossTrackDragOffsetY)));let G=!1;if(f){this.onMultiDragMove&&this.config.id&&(G=this.onMultiDragMove({draggedClipId:m.id,deltaTime:z,targetTrackY:s.dragTargetTrackY,currentTrackId:this.config.id,crossTrackOffsetY:s.crossTrackDragOffsetY,isFinal:!1})===!0);for(const[L,X]of this.multiDragOriginalPositions){if(L===m.id)continue;const B=this.clips.find(Y=>Y.getClip().id===L);if(!B)continue;const Q=Math.max(0,X.startTime+z),ne=(T=this.clipGroups)==null?void 0:T.get(L);if(ne){const Y=fe(Q,this.zoom,this.scrollLeft);ne.x(Y),ne.y(this.resolveClipRenderY(L,s.crossTrackDragOffsetY)),ne.visible(Y+Ce(X.duration,this.zoom)>0&&Y<this.layer.width());const K=B.getClip();de.updateClipGroup(ne,Ce(K.duration,this.zoom),this.trackHeight-4,this.getClipDisplayLabel(K),K.duration,this.theme,!0,K.thumbnails,K.src,K.type,!!K.separatedAudioClipId,!0,this.getClipAudioBadgeText(K),K.mediaStatus,K.mediaStatusMessage)}}}if(!f&&R.resizePushFollowers.length>0)for(const L of R.resizePushFollowers){const X=(k=this.clipGroups)==null?void 0:k.get(L.id);if(!X)continue;const B=fe(L.startTime,this.zoom,this.scrollLeft);X.x(B),X.y(this.resolveClipRenderY(L.id,s.crossTrackDragOffsetY)),X.visible(B+Ce(L.duration,this.zoom)>0&&B<this.layer.width())}g&&this.onClipCrossTrackPreview&&this.config.id&&!G?this.onClipCrossTrackPreview(O,s.dragTargetTrackY,this.config.id)!=="self"&&this.hideDropPreview():G?this.hideDropPreview():this.showDropPreview(O),this.updateSnapGuideLine(R.guideTime)}else this.hideDropPreview(),(_=this.onClearDropPreview)==null||_.call(this),this.updateSnapGuideLine(null);i&&this.updateEdgeAutoScrollState(d,h.width),this.layer.batchDraw(),(w=this.dragOverlayLayer)==null||w.batchDraw()}buildPreviewClip(e,t,i,r,s){const a=i-r.pointerStartX+(this.scrollLeft-r.dragStartScrollLeft),o=U.pixelsToTime(a,this.zoom);let l;s==="resize-left"||e.isResizingLeft?l=this.buildResizeLeftPreviewClip(e,t,o):s==="resize-right"||e.isResizingRight?l=this.buildResizeRightPreviewClip(e,t,o):l={...e,startTime:Math.max(0,t.startTime+o),endTime:Math.max(0,t.startTime+o)+e.duration};const c=this.constrainResizePreviewToTrackBounds(this.applyClipSnap(l,t,r.snapCandidateClips),t,r.nonDraggedClips),h=c.clip.isResizingRight?this.computeResizeRightPushFollowers(t,c.clip,r.nonDraggedClips):[];return{...c,resizePushFollowers:h}}constrainResizePreviewToTrackBounds(e,t,i){if(e.clip.isResizingLeft){const r=this.getResizeLeftBoundaryStart(t,i);if(e.clip.startTime>=r)return e;const s=e.clip.endTime,a=s-r,o=this.isSourceBoundClip(t)?{startTimeAtSource:t.endTimeAtSource-a,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:a,sourceDuration:a};return{clip:{...e.clip,startTime:r,duration:a,endTime:s,...o},guideTime:e.guideTime===r?e.guideTime:null}}return e}getResizeLeftBoundaryStart(e,t){let i=0;for(const r of t){if(r.startTime>=e.startTime)continue;const s=r.startTime+r.duration;i=Math.max(i,s)}return i}computeResizeRightPushFollowers(e,t,i){if(!t.isResizingRight)return[];const r=t.startTime+t.duration,s=U.calculateEndTime(e.startTime,e.duration),a=[...i].filter(h=>h.startTime>=s).sort((h,d)=>h.startTime-d.startTime);if(a.length===0)return[];const o=a[0],l=r-o.startTime;if(l<=0)return[];const c=l;return a.map(h=>({...h,startTime:h.startTime+c,endTime:h.startTime+c+h.duration}))}buildResizeLeftPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const g=U.calculateEndTime(t.startTime,t.duration);let f=Math.max(0,t.startTime+i),m=g-f;return m<le.MIN_CLIP_DURATION_MS&&(m=le.MIN_CLIP_DURATION_MS,f=g-m),{...e,startTime:f,duration:m,endTime:f+m,startTimeAtSource:0,endTimeAtSource:m,sourceDuration:m}}const s=Math.max(0,t.startTime+i)-t.startTime,o=Math.max(0,t.startTimeAtSource+i)-t.startTimeAtSource,l=Math.abs(s)<Math.abs(o)?s:o,c=U.calculateEndTime(t.startTime,t.duration);let h=t.startTime+l,d=t.duration-l,u;return d<le.MIN_CLIP_DURATION_MS?(d=le.MIN_CLIP_DURATION_MS,h=c-d,u=t.endTimeAtSource-d):u=t.startTimeAtSource+l,{...e,startTime:h,duration:d,endTime:h+d,startTimeAtSource:u,endTimeAtSource:t.endTimeAtSource}}buildResizeRightPreviewClip(e,t,i){if(!this.isSourceBoundClip(t)){const o=Math.max(le.MIN_CLIP_DURATION_MS,t.duration+i);return{...e,startTime:t.startTime,duration:o,endTime:t.startTime+o,startTimeAtSource:0,endTimeAtSource:o,sourceDuration:o}}let r=Math.max(le.MIN_CLIP_DURATION_MS,t.duration+i);const s=t.startTimeAtSource,a=Math.min(t.sourceDuration,s+r);return r=a-s,{...e,startTime:t.startTime,duration:r,endTime:t.startTime+r,startTimeAtSource:s,endTimeAtSource:a}}applyClipSnap(e,t,i){if(!this.enableClipSnap||i.length===0)return{clip:e,guideTime:null};const r=i.flatMap(c=>[c.startTime,c.startTime+c.duration]);if(r.length===0)return{clip:e,guideTime:null};const s=U.pixelsToTime(this.clipSnapThreshold,this.zoom),a=e.startTime+e.duration,o=[];if(e.isResizingLeft)for(const c of r){const h=a-c,d=t.endTimeAtSource-h,u=Math.abs(c-e.startTime);u>s||h<le.MIN_CLIP_DURATION_MS||this.isSourceBoundClip(t)&&d<0||o.push({clip:{...e,startTime:c,duration:h,endTime:a,...this.isSourceBoundClip(t)?{startTimeAtSource:d,endTimeAtSource:t.endTimeAtSource}:{startTimeAtSource:0,endTimeAtSource:h,sourceDuration:h}},guideTime:c,distance:u})}else if(e.isResizingRight)for(const c of r){const h=c-e.startTime,d=t.startTimeAtSource+h,u=Math.abs(c-a);u>s||h<le.MIN_CLIP_DURATION_MS||this.isSourceBoundClip(t)&&d>t.sourceDuration||o.push({clip:{...e,duration:h,endTime:e.startTime+h,...this.isSourceBoundClip(t)?{endTimeAtSource:d}:{startTimeAtSource:0,endTimeAtSource:h,sourceDuration:h}},guideTime:c,distance:u})}else for(const c of r){const h=Math.abs(c-e.startTime);h<=s&&c>=0&&o.push({clip:{...e,startTime:c,endTime:c+e.duration},guideTime:c,distance:h});const d=c-e.duration,u=Math.abs(c-a);u<=s&&d>=0&&o.push({clip:{...e,startTime:d,endTime:d+e.duration},guideTime:c,distance:u})}if(o.length===0)return{clip:e,guideTime:null};o.sort((c,h)=>c.distance-h.distance);const l=o[0];return{clip:l.clip,guideTime:l.guideTime}}applyPreviewClipState(e,t){return e&&typeof e.applyPreviewState=="function"?(e.applyPreviewState(t),!0):(this.isVisualUpdate=!0,this.handleClipUpdate(t),this.isVisualUpdate=!1,!1)}setClipDragOverlayActive(e,t){var o,l;const i=this.getPromotedClipParents(),r=this.clipGroups.get(e);if(!r){i.delete(e);return}if(!t){const c=i.get(e);if(!c)return;r.remove(),c.parent.add(r);const h=(o=this.clips.find(d=>d.getClip().id===e))==null?void 0:o.getClip();h&&r.x(fe(h.startTime,this.zoom,this.scrollLeft)),r.y(2),i.delete(e),this.layer.batchDraw(),(l=this.dragOverlayLayer)==null||l.batchDraw();return}if(i.has(e)||!this.dragOverlayLayer)return;const s=r.getParent();if(!s)return;const a=r.getAbsolutePosition();i.set(e,{parent:s,baseY:this.trackY}),r.remove(),this.dragOverlayLayer.add(r),r.position(a),r.moveToTop(),this.layer.batchDraw(),this.dragOverlayLayer.batchDraw()}resolveClipRenderY(e,t){const i=this.getPromotedClipParents().get(e);return((i==null?void 0:i.baseY)??0)+2+t}getPromotedClipParents(){return this.promotedClipParents instanceof Map||(this.promotedClipParents=new Map),this.promotedClipParents}updateSnapGuideLine(e){var t;(t=this.onSnapGuideChange)==null||t.call(this,this.enableClipSnap?e:null)}updateEdgeAutoScrollState(e,t){if(this.calculateHorizontalAutoScrollVelocity(e,t)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(le.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=le.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)}};p(le,"DEFAULT_DRAG_ACTIVATION_THRESHOLD",4),p(le,"DEFAULT_CLIP_SNAP_THRESHOLD",8),p(le,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(le,"AUTO_SCROLL_MAX_SPEED",18),p(le,"MIN_CLIP_DURATION_MS",1);let ir=le;/**
16
16
  * @license
17
17
  * Copyright 2019 Google LLC
18
18
  * SPDX-License-Identifier: BSD-3-Clause
19
- */const zi=globalThis,Ss=zi.ShadowRoot&&(zi.ShadyCSS===void 0||zi.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,ro=Symbol(),un=new WeakMap;let ld=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==ro)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Ss&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=un.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&un.set(t,e))}return e}toString(){return this.cssText}};const cd=n=>new ld(typeof n=="string"?n:n+"",void 0,ro),hd=(n,e)=>{if(Ss)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),r=zi.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,n.appendChild(i)}},pn=Ss?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return cd(t)})(n):n;/**
19
+ */const $i=globalThis,Cs=$i.ShadowRoot&&($i.ShadyCSS===void 0||$i.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,oo=Symbol(),gn=new WeakMap;let Cd=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==oo)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const t=this.t;if(Cs&&e===void 0){const i=t!==void 0&&t.length===1;i&&(e=gn.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&gn.set(t,e))}return e}toString(){return this.cssText}};const vd=n=>new Cd(typeof n=="string"?n:n+"",void 0,oo),Td=(n,e)=>{if(Cs)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const t of e){const i=document.createElement("style"),r=$i.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,n.appendChild(i)}},fn=Cs?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return vd(t)})(n):n;/**
20
20
  * @license
21
21
  * Copyright 2017 Google LLC
22
22
  * SPDX-License-Identifier: BSD-3-Clause
23
- */const{is:dd,defineProperty:ud,getOwnPropertyDescriptor:pd,getOwnPropertyNames:gd,getOwnPropertySymbols:fd,getPrototypeOf:md}=Object,qe=globalThis,gn=qe.trustedTypes,yd=gn?gn.emptyScript:"",br=qe.reactiveElementPolyfillSupport,ri=(n,e)=>n,Zr={toAttribute(n,e){switch(e){case Boolean:n=n?yd:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},so=(n,e)=>!dd(n,e),fn={attribute:!0,type:String,converter:Zr,reflect:!1,useDefault:!1,hasChanged:so};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),qe.litPropertyMetadata??(qe.litPropertyMetadata=new WeakMap);let mt=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=fn){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(e,i,t);r!==void 0&&ud(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){const{get:r,set:s}=pd(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){const o=r==null?void 0:r.call(this);s==null||s.call(this,a),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??fn}static _$Ei(){if(this.hasOwnProperty(ri("elementProperties")))return;const e=md(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(ri("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(ri("properties"))){const t=this.properties,i=[...gd(t),...fd(t)];for(const r of i)this.createProperty(r,t[r])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[i,r]of t)this.elementProperties.set(i,r)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const r=this._$Eu(t,i);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const r of i)t.unshift(pn(r))}else e!==void 0&&t.push(pn(e));return t}static _$Eu(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return hd(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostConnected)==null?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostDisconnected)==null?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){var s;const i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===!0){const a=(((s=i.converter)==null?void 0:s.toAttribute)!==void 0?i.converter:Zr).toAttribute(t,i.type);this._$Em=e,a==null?this.removeAttribute(r):this.setAttribute(r,a),this._$Em=null}}_$AK(e,t){var s,a;const i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const o=i.getPropertyOptions(r),l=typeof o.converter=="function"?{fromAttribute:o.converter}:((s=o.converter)==null?void 0:s.fromAttribute)!==void 0?o.converter:Zr;this._$Em=r;const c=l.fromAttribute(t,o.type);this[r]=c??((a=this._$Ej)==null?void 0:a.get(r))??c,this._$Em=null}}requestUpdate(e,t,i,r=!1,s){var a;if(e!==void 0){const o=this.constructor;if(r===!1&&(s=this[e]),i??(i=o.getPropertyOptions(e)),!((i.hasChanged??so)(s,t)||i.useDefault&&i.reflect&&s===((a=this._$Ej)==null?void 0:a.get(e))&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:r,wrapped:s},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),s!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),r===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[s,a]of this._$Ep)this[s]=a;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[s,a]of r){const{wrapped:o}=a,l=this[s];o!==!0||this._$AL.has(s)||l===void 0||this.C(s,void 0,a,l)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(i=this._$EO)==null||i.forEach(r=>{var s;return(s=r.hostUpdate)==null?void 0:s.call(r)}),this.update(t)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(i=>{var r;return(r=i.hostUpdated)==null?void 0:r.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};mt.elementStyles=[],mt.shadowRootOptions={mode:"open"},mt[ri("elementProperties")]=new Map,mt[ri("finalized")]=new Map,br==null||br({ReactiveElement:mt}),(qe.reactiveElementVersions??(qe.reactiveElementVersions=[])).push("2.1.2");/**
23
+ */const{is:bd,defineProperty:kd,getOwnPropertyDescriptor:wd,getOwnPropertyNames:xd,getOwnPropertySymbols:Pd,getPrototypeOf:_d}=Object,je=globalThis,mn=je.trustedTypes,Ad=mn?mn.emptyScript:"",br=je.reactiveElementPolyfillSupport,si=(n,e)=>n,Zr={toAttribute(n,e){switch(e){case Boolean:n=n?Ad:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},lo=(n,e)=>!bd(n,e),yn={attribute:!0,type:String,converter:Zr,reflect:!1,useDefault:!1,hasChanged:lo};Symbol.metadata??(Symbol.metadata=Symbol("metadata")),je.litPropertyMetadata??(je.litPropertyMetadata=new WeakMap);let yt=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??(this.l=[])).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=yn){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),r=this.getPropertyDescriptor(e,i,t);r!==void 0&&kd(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){const{get:r,set:s}=wd(this.prototype,e)??{get(){return this[t]},set(a){this[t]=a}};return{get:r,set(a){const o=r==null?void 0:r.call(this);s==null||s.call(this,a),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??yn}static _$Ei(){if(this.hasOwnProperty(si("elementProperties")))return;const e=_d(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(si("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(si("properties"))){const t=this.properties,i=[...xd(t),...Pd(t)];for(const r of i)this.createProperty(r,t[r])}const e=this[Symbol.metadata];if(e!==null){const t=litPropertyMetadata.get(e);if(t!==void 0)for(const[i,r]of t)this.elementProperties.set(i,r)}this._$Eh=new Map;for(const[t,i]of this.elementProperties){const r=this._$Eu(t,i);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const r of i)t.unshift(fn(r))}else e!==void 0&&t.push(fn(e));return t}static _$Eu(e,t){const i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){var e;this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),(e=this.constructor.l)==null||e.forEach(t=>t(this))}addController(e){var t;(this._$EO??(this._$EO=new Set)).add(e),this.renderRoot!==void 0&&this.isConnected&&((t=e.hostConnected)==null||t.call(e))}removeController(e){var t;(t=this._$EO)==null||t.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return Td(e,this.constructor.elementStyles),e}connectedCallback(){var e;this.renderRoot??(this.renderRoot=this.createRenderRoot()),this.enableUpdating(!0),(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostConnected)==null?void 0:i.call(t)})}enableUpdating(e){}disconnectedCallback(){var e;(e=this._$EO)==null||e.forEach(t=>{var i;return(i=t.hostDisconnected)==null?void 0:i.call(t)})}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){var s;const i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===!0){const a=(((s=i.converter)==null?void 0:s.toAttribute)!==void 0?i.converter:Zr).toAttribute(t,i.type);this._$Em=e,a==null?this.removeAttribute(r):this.setAttribute(r,a),this._$Em=null}}_$AK(e,t){var s,a;const i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){const o=i.getPropertyOptions(r),l=typeof o.converter=="function"?{fromAttribute:o.converter}:((s=o.converter)==null?void 0:s.fromAttribute)!==void 0?o.converter:Zr;this._$Em=r;const c=l.fromAttribute(t,o.type);this[r]=c??((a=this._$Ej)==null?void 0:a.get(r))??c,this._$Em=null}}requestUpdate(e,t,i,r=!1,s){var a;if(e!==void 0){const o=this.constructor;if(r===!1&&(s=this[e]),i??(i=o.getPropertyOptions(e)),!((i.hasChanged??lo)(s,t)||i.useDefault&&i.reflect&&s===((a=this._$Ej)==null?void 0:a.get(e))&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:r,wrapped:s},a){i&&!(this._$Ej??(this._$Ej=new Map)).has(e)&&(this._$Ej.set(e,a??t??this[e]),s!==!0||a!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),r===!0&&this._$Em!==e&&(this._$Eq??(this._$Eq=new Set)).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){var i;if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??(this.renderRoot=this.createRenderRoot()),this._$Ep){for(const[s,a]of this._$Ep)this[s]=a;this._$Ep=void 0}const r=this.constructor.elementProperties;if(r.size>0)for(const[s,a]of r){const{wrapped:o}=a,l=this[s];o!==!0||this._$AL.has(s)||l===void 0||this.C(s,void 0,a,l)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),(i=this._$EO)==null||i.forEach(r=>{var s;return(s=r.hostUpdate)==null?void 0:s.call(r)}),this.update(t)):this._$EM()}catch(r){throw e=!1,this._$EM(),r}e&&this._$AE(t)}willUpdate(e){}_$AE(e){var t;(t=this._$EO)==null||t.forEach(i=>{var r;return(r=i.hostUpdated)==null?void 0:r.call(i)}),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&(this._$Eq=this._$Eq.forEach(t=>this._$ET(t,this[t]))),this._$EM()}updated(e){}firstUpdated(e){}};yt.elementStyles=[],yt.shadowRootOptions={mode:"open"},yt[si("elementProperties")]=new Map,yt[si("finalized")]=new Map,br==null||br({ReactiveElement:yt}),(je.reactiveElementVersions??(je.reactiveElementVersions=[])).push("2.1.2");/**
24
24
  * @license
25
25
  * Copyright 2017 Google LLC
26
26
  * SPDX-License-Identifier: BSD-3-Clause
27
- */const si=globalThis,mn=n=>n,rr=si.trustedTypes,yn=rr?rr.createPolicy("lit-html",{createHTML:n=>n}):void 0,no="$lit$",Ye=`lit$${Math.random().toFixed(9).slice(2)}$`,ao="?"+Ye,Sd=`<${ao}>`,nt=document,gi=()=>nt.createComment(""),fi=n=>n===null||typeof n!="object"&&typeof n!="function",Cs=Array.isArray,Cd=n=>Cs(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",kr=`[
28
- \f\r]`,Ht=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Sn=/-->/g,Cn=/>/g,et=RegExp(`>|${kr}(?:([^\\s"'>=/]+)(${kr}*=${kr}*(?:[^
29
- \f\r"'\`<>=]|("|')|))|$)`,"g"),vn=/'/g,Tn=/"/g,oo=/^(?:script|style|textarea|title)$/i,vd=n=>(e,...t)=>({_$litType$:n,strings:e,values:t}),j=vd(1),at=Symbol.for("lit-noChange"),oe=Symbol.for("lit-nothing"),bn=new WeakMap,it=nt.createTreeWalker(nt,129);function lo(n,e){if(!Cs(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return yn!==void 0?yn.createHTML(e):e}const Td=(n,e)=>{const t=n.length-1,i=[];let r,s=e===2?"<svg>":e===3?"<math>":"",a=Ht;for(let o=0;o<t;o++){const l=n[o];let c,h,d=-1,u=0;for(;u<l.length&&(a.lastIndex=u,h=a.exec(l),h!==null);)u=a.lastIndex,a===Ht?h[1]==="!--"?a=Sn:h[1]!==void 0?a=Cn:h[2]!==void 0?(oo.test(h[2])&&(r=RegExp("</"+h[2],"g")),a=et):h[3]!==void 0&&(a=et):a===et?h[0]===">"?(a=r??Ht,d=-1):h[1]===void 0?d=-2:(d=a.lastIndex-h[2].length,c=h[1],a=h[3]===void 0?et:h[3]==='"'?Tn:vn):a===Tn||a===vn?a=et:a===Sn||a===Cn?a=Ht:(a=et,r=void 0);const g=a===et&&n[o+1].startsWith("/>")?" ":"";s+=a===Ht?l+Sd:d>=0?(i.push(c),l.slice(0,d)+no+l.slice(d)+Ye+g):l+Ye+(d===-2?o:g)}return[lo(n,s+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class mi{constructor({strings:e,_$litType$:t},i){let r;this.parts=[];let s=0,a=0;const o=e.length-1,l=this.parts,[c,h]=Td(e,t);if(this.el=mi.createElement(c,i),it.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=it.nextNode())!==null&&l.length<o;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(no)){const u=h[a++],g=r.getAttribute(d).split(Ye),f=/([.?@])?(.*)/.exec(u);l.push({type:1,index:s,name:f[2],strings:g,ctor:f[1]==="."?kd:f[1]==="?"?wd:f[1]==="@"?xd:pr}),r.removeAttribute(d)}else d.startsWith(Ye)&&(l.push({type:6,index:s}),r.removeAttribute(d));if(oo.test(r.tagName)){const d=r.textContent.split(Ye),u=d.length-1;if(u>0){r.textContent=rr?rr.emptyScript:"";for(let g=0;g<u;g++)r.append(d[g],gi()),it.nextNode(),l.push({type:2,index:++s});r.append(d[u],gi())}}}else if(r.nodeType===8)if(r.data===ao)l.push({type:2,index:s});else{let d=-1;for(;(d=r.data.indexOf(Ye,d+1))!==-1;)l.push({type:7,index:s}),d+=Ye.length-1}s++}}static createElement(e,t){const i=nt.createElement("template");return i.innerHTML=e,i}}function Pt(n,e,t=n,i){var a,o;if(e===at)return e;let r=i!==void 0?(a=t._$Co)==null?void 0:a[i]:t._$Cl;const s=fi(e)?void 0:e._$litDirective$;return(r==null?void 0:r.constructor)!==s&&((o=r==null?void 0:r._$AO)==null||o.call(r,!1),s===void 0?r=void 0:(r=new s(n),r._$AT(n,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=r:t._$Cl=r),r!==void 0&&(e=Pt(n,r._$AS(n,e.values),r,i)),e}class bd{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,r=((e==null?void 0:e.creationScope)??nt).importNode(t,!0);it.currentNode=r;let s=it.nextNode(),a=0,o=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new vi(s,s.nextSibling,this,e):l.type===1?c=new l.ctor(s,l.name,l.strings,this,e):l.type===6&&(c=new Pd(s,this,e)),this._$AV.push(c),l=i[++o]}a!==(l==null?void 0:l.index)&&(s=it.nextNode(),a++)}return it.currentNode=nt,r}p(e){let t=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class vi{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,i,r){this.type=2,this._$AH=oe,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=r,this._$Cv=(r==null?void 0:r.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=Pt(this,e,t),fi(e)?e===oe||e==null||e===""?(this._$AH!==oe&&this._$AR(),this._$AH=oe):e!==this._$AH&&e!==at&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Cd(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==oe&&fi(this._$AH)?this._$AA.nextSibling.data=e:this.T(nt.createTextNode(e)),this._$AH=e}$(e){var s;const{values:t,_$litType$:i}=e,r=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=mi.createElement(lo(i.h,i.h[0]),this.options)),i);if(((s=this._$AH)==null?void 0:s._$AD)===r)this._$AH.p(t);else{const a=new bd(r,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=bn.get(e.strings);return t===void 0&&bn.set(e.strings,t=new mi(e)),t}k(e){Cs(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,r=0;for(const s of e)r===t.length?t.push(i=new vi(this.O(gi()),this.O(gi()),this,this.options)):i=t[r],i._$AI(s),r++;r<t.length&&(this._$AR(i&&i._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,t);e!==this._$AB;){const r=mn(e).nextSibling;mn(e).remove(),e=r}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class pr{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,r,s){this.type=1,this._$AH=oe,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=s,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=oe}_$AI(e,t=this,i,r){const s=this.strings;let a=!1;if(s===void 0)e=Pt(this,e,t,0),a=!fi(e)||e!==this._$AH&&e!==at,a&&(this._$AH=e);else{const o=e;let l,c;for(e=s[0],l=0;l<s.length-1;l++)c=Pt(this,o[i+l],t,l),c===at&&(c=this._$AH[l]),a||(a=!fi(c)||c!==this._$AH[l]),c===oe?e=oe:e!==oe&&(e+=(c??"")+s[l+1]),this._$AH[l]=c}a&&!r&&this.j(e)}j(e){e===oe?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class kd extends pr{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===oe?void 0:e}}class wd extends pr{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==oe)}}class xd extends pr{constructor(e,t,i,r,s){super(e,t,i,r,s),this.type=5}_$AI(e,t=this){if((e=Pt(this,e,t,0)??oe)===at)return;const i=this._$AH,r=e===oe&&i!==oe||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==oe&&(i===oe||r);r&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class Pd{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){Pt(this,e)}}const wr=si.litHtmlPolyfillSupport;wr==null||wr(mi,vi),(si.litHtmlVersions??(si.litHtmlVersions=[])).push("3.3.2");const yi=(n,e,t)=>{const i=(t==null?void 0:t.renderBefore)??e;let r=i._$litPart$;if(r===void 0){const s=(t==null?void 0:t.renderBefore)??null;i._$litPart$=r=new vi(e.insertBefore(gi(),s),s,void 0,t??{})}return r._$AI(n),r};/**
27
+ */const ni=globalThis,Sn=n=>n,rr=ni.trustedTypes,Cn=rr?rr.createPolicy("lit-html",{createHTML:n=>n}):void 0,co="$lit$",Ye=`lit$${Math.random().toFixed(9).slice(2)}$`,ho="?"+Ye,Id=`<${ho}>`,at=document,fi=()=>at.createComment(""),mi=n=>n===null||typeof n!="object"&&typeof n!="function",vs=Array.isArray,Ed=n=>vs(n)||typeof(n==null?void 0:n[Symbol.iterator])=="function",kr=`[
28
+ \f\r]`,Gt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,vn=/-->/g,Tn=/>/g,tt=RegExp(`>|${kr}(?:([^\\s"'>=/]+)(${kr}*=${kr}*(?:[^
29
+ \f\r"'\`<>=]|("|')|))|$)`,"g"),bn=/'/g,kn=/"/g,uo=/^(?:script|style|textarea|title)$/i,Rd=n=>(e,...t)=>({_$litType$:n,strings:e,values:t}),q=Rd(1),ot=Symbol.for("lit-noChange"),oe=Symbol.for("lit-nothing"),wn=new WeakMap,rt=at.createTreeWalker(at,129);function po(n,e){if(!vs(n)||!n.hasOwnProperty("raw"))throw Error("invalid template strings array");return Cn!==void 0?Cn.createHTML(e):e}const Md=(n,e)=>{const t=n.length-1,i=[];let r,s=e===2?"<svg>":e===3?"<math>":"",a=Gt;for(let o=0;o<t;o++){const l=n[o];let c,h,d=-1,u=0;for(;u<l.length&&(a.lastIndex=u,h=a.exec(l),h!==null);)u=a.lastIndex,a===Gt?h[1]==="!--"?a=vn:h[1]!==void 0?a=Tn:h[2]!==void 0?(uo.test(h[2])&&(r=RegExp("</"+h[2],"g")),a=tt):h[3]!==void 0&&(a=tt):a===tt?h[0]===">"?(a=r??Gt,d=-1):h[1]===void 0?d=-2:(d=a.lastIndex-h[2].length,c=h[1],a=h[3]===void 0?tt:h[3]==='"'?kn:bn):a===kn||a===bn?a=tt:a===vn||a===Tn?a=Gt:(a=tt,r=void 0);const g=a===tt&&n[o+1].startsWith("/>")?" ":"";s+=a===Gt?l+Id:d>=0?(i.push(c),l.slice(0,d)+co+l.slice(d)+Ye+g):l+Ye+(d===-2?o:g)}return[po(n,s+(n[t]||"<?>")+(e===2?"</svg>":e===3?"</math>":"")),i]};class yi{constructor({strings:e,_$litType$:t},i){let r;this.parts=[];let s=0,a=0;const o=e.length-1,l=this.parts,[c,h]=Md(e,t);if(this.el=yi.createElement(c,i),rt.currentNode=this.el.content,t===2||t===3){const d=this.el.content.firstChild;d.replaceWith(...d.childNodes)}for(;(r=rt.nextNode())!==null&&l.length<o;){if(r.nodeType===1){if(r.hasAttributes())for(const d of r.getAttributeNames())if(d.endsWith(co)){const u=h[a++],g=r.getAttribute(d).split(Ye),f=/([.?@])?(.*)/.exec(u);l.push({type:1,index:s,name:f[2],strings:g,ctor:f[1]==="."?Dd:f[1]==="?"?Od:f[1]==="@"?Bd:pr}),r.removeAttribute(d)}else d.startsWith(Ye)&&(l.push({type:6,index:s}),r.removeAttribute(d));if(uo.test(r.tagName)){const d=r.textContent.split(Ye),u=d.length-1;if(u>0){r.textContent=rr?rr.emptyScript:"";for(let g=0;g<u;g++)r.append(d[g],fi()),rt.nextNode(),l.push({type:2,index:++s});r.append(d[u],fi())}}}else if(r.nodeType===8)if(r.data===ho)l.push({type:2,index:s});else{let d=-1;for(;(d=r.data.indexOf(Ye,d+1))!==-1;)l.push({type:7,index:s}),d+=Ye.length-1}s++}}static createElement(e,t){const i=at.createElement("template");return i.innerHTML=e,i}}function _t(n,e,t=n,i){var a,o;if(e===ot)return e;let r=i!==void 0?(a=t._$Co)==null?void 0:a[i]:t._$Cl;const s=mi(e)?void 0:e._$litDirective$;return(r==null?void 0:r.constructor)!==s&&((o=r==null?void 0:r._$AO)==null||o.call(r,!1),s===void 0?r=void 0:(r=new s(n),r._$AT(n,t,i)),i!==void 0?(t._$Co??(t._$Co=[]))[i]=r:t._$Cl=r),r!==void 0&&(e=_t(n,r._$AS(n,e.values),r,i)),e}class Ld{constructor(e,t){this._$AV=[],this._$AN=void 0,this._$AD=e,this._$AM=t}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(e){const{el:{content:t},parts:i}=this._$AD,r=((e==null?void 0:e.creationScope)??at).importNode(t,!0);rt.currentNode=r;let s=rt.nextNode(),a=0,o=0,l=i[0];for(;l!==void 0;){if(a===l.index){let c;l.type===2?c=new Ti(s,s.nextSibling,this,e):l.type===1?c=new l.ctor(s,l.name,l.strings,this,e):l.type===6&&(c=new Fd(s,this,e)),this._$AV.push(c),l=i[++o]}a!==(l==null?void 0:l.index)&&(s=rt.nextNode(),a++)}return rt.currentNode=at,r}p(e){let t=0;for(const i of this._$AV)i!==void 0&&(i.strings!==void 0?(i._$AI(e,i,t),t+=i.strings.length-2):i._$AI(e[t])),t++}}class Ti{get _$AU(){var e;return((e=this._$AM)==null?void 0:e._$AU)??this._$Cv}constructor(e,t,i,r){this.type=2,this._$AH=oe,this._$AN=void 0,this._$AA=e,this._$AB=t,this._$AM=i,this.options=r,this._$Cv=(r==null?void 0:r.isConnected)??!0}get parentNode(){let e=this._$AA.parentNode;const t=this._$AM;return t!==void 0&&(e==null?void 0:e.nodeType)===11&&(e=t.parentNode),e}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(e,t=this){e=_t(this,e,t),mi(e)?e===oe||e==null||e===""?(this._$AH!==oe&&this._$AR(),this._$AH=oe):e!==this._$AH&&e!==ot&&this._(e):e._$litType$!==void 0?this.$(e):e.nodeType!==void 0?this.T(e):Ed(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==oe&&mi(this._$AH)?this._$AA.nextSibling.data=e:this.T(at.createTextNode(e)),this._$AH=e}$(e){var s;const{values:t,_$litType$:i}=e,r=typeof i=="number"?this._$AC(e):(i.el===void 0&&(i.el=yi.createElement(po(i.h,i.h[0]),this.options)),i);if(((s=this._$AH)==null?void 0:s._$AD)===r)this._$AH.p(t);else{const a=new Ld(r,this),o=a.u(this.options);a.p(t),this.T(o),this._$AH=a}}_$AC(e){let t=wn.get(e.strings);return t===void 0&&wn.set(e.strings,t=new yi(e)),t}k(e){vs(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,r=0;for(const s of e)r===t.length?t.push(i=new Ti(this.O(fi()),this.O(fi()),this,this.options)):i=t[r],i._$AI(s),r++;r<t.length&&(this._$AR(i&&i._$AB.nextSibling,r),t.length=r)}_$AR(e=this._$AA.nextSibling,t){var i;for((i=this._$AP)==null?void 0:i.call(this,!1,!0,t);e!==this._$AB;){const r=Sn(e).nextSibling;Sn(e).remove(),e=r}}setConnected(e){var t;this._$AM===void 0&&(this._$Cv=e,(t=this._$AP)==null||t.call(this,e))}}class pr{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(e,t,i,r,s){this.type=1,this._$AH=oe,this._$AN=void 0,this.element=e,this.name=t,this._$AM=r,this.options=s,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=oe}_$AI(e,t=this,i,r){const s=this.strings;let a=!1;if(s===void 0)e=_t(this,e,t,0),a=!mi(e)||e!==this._$AH&&e!==ot,a&&(this._$AH=e);else{const o=e;let l,c;for(e=s[0],l=0;l<s.length-1;l++)c=_t(this,o[i+l],t,l),c===ot&&(c=this._$AH[l]),a||(a=!mi(c)||c!==this._$AH[l]),c===oe?e=oe:e!==oe&&(e+=(c??"")+s[l+1]),this._$AH[l]=c}a&&!r&&this.j(e)}j(e){e===oe?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,e??"")}}class Dd extends pr{constructor(){super(...arguments),this.type=3}j(e){this.element[this.name]=e===oe?void 0:e}}class Od extends pr{constructor(){super(...arguments),this.type=4}j(e){this.element.toggleAttribute(this.name,!!e&&e!==oe)}}class Bd extends pr{constructor(e,t,i,r,s){super(e,t,i,r,s),this.type=5}_$AI(e,t=this){if((e=_t(this,e,t,0)??oe)===ot)return;const i=this._$AH,r=e===oe&&i!==oe||e.capture!==i.capture||e.once!==i.once||e.passive!==i.passive,s=e!==oe&&(i===oe||r);r&&this.element.removeEventListener(this.name,this,i),s&&this.element.addEventListener(this.name,this,e),this._$AH=e}handleEvent(e){var t;typeof this._$AH=="function"?this._$AH.call(((t=this.options)==null?void 0:t.host)??this.element,e):this._$AH.handleEvent(e)}}class Fd{constructor(e,t,i){this.element=e,this.type=6,this._$AN=void 0,this._$AM=t,this.options=i}get _$AU(){return this._$AM._$AU}_$AI(e){_t(this,e)}}const wr=ni.litHtmlPolyfillSupport;wr==null||wr(yi,Ti),(ni.litHtmlVersions??(ni.litHtmlVersions=[])).push("3.3.2");const Si=(n,e,t)=>{const i=(t==null?void 0:t.renderBefore)??e;let r=i._$litPart$;if(r===void 0){const s=(t==null?void 0:t.renderBefore)??null;i._$litPart$=r=new Ti(e.insertBefore(fi(),s),s,void 0,t??{})}return r._$AI(n),r};/**
30
30
  * @license
31
31
  * Copyright 2017 Google LLC
32
32
  * SPDX-License-Identifier: BSD-3-Clause
33
- */const rt=globalThis;let $i=class extends mt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t;const e=super.createRenderRoot();return(t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=yi(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return at}};var ea;$i._$litElement$=!0,$i.finalized=!0,(ea=rt.litElementHydrateSupport)==null||ea.call(rt,{LitElement:$i});const xr=rt.litElementPolyfillSupport;xr==null||xr({LitElement:$i});(rt.litElementVersions??(rt.litElementVersions=[])).push("4.2.2");class _d{constructor(){p(this,"container",null)}mount(e,t){return this.container=e,yi(this.renderTemplate(t),e),e.classList.add("timeline-manager-root"),e.style.gridTemplateColumns=`${t.leftPanelWidth}px minmax(0, 1fr)`,e.style.gridTemplateRows=`${t.timeScaleHeight}px minmax(0, 1fr)`,e.style.background=t.theme.background,{headerCorner:this.requireElement(e,'[data-layout-role="header-corner"]'),headerViewport:this.requireElement(e,'[data-layout-role="header-viewport"]'),headerCanvasHost:this.requireElement(e,'[data-layout-role="header-canvas-host"]'),trackInfoViewport:this.requireElement(e,'[data-layout-role="track-info-viewport"]'),bodyViewport:this.requireElement(e,'[data-layout-role="body-viewport"]'),bodyCanvasHost:this.requireElement(e,'[data-layout-role="body-canvas-host"]'),verticalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="vertical-scrollbar-host"]'),horizontalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="horizontal-scrollbar-host"]'),playheadOverlay:this.requireElement(e,'[data-layout-role="playhead-overlay"]')}}destroy(){this.container&&yi(null,this.container),this.container=null}renderTemplate(e){const{theme:t,timeScaleHeight:i,leftPanelWidth:r,scrollbarSize:s}=e,a=["position:relative","min-width:0","min-height:0","max-width:100%","box-sizing:border-box",`background:${t.background}`,`color:${t.clipName}`].join(";");return j`
33
+ */const st=globalThis;let Vi=class extends yt{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){var t;const e=super.createRenderRoot();return(t=this.renderOptions).renderBefore??(t.renderBefore=e.firstChild),e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Si(t,this.renderRoot,this.renderOptions)}connectedCallback(){var e;super.connectedCallback(),(e=this._$Do)==null||e.setConnected(!0)}disconnectedCallback(){var e;super.disconnectedCallback(),(e=this._$Do)==null||e.setConnected(!1)}render(){return ot}};var sa;Vi._$litElement$=!0,Vi.finalized=!0,(sa=st.litElementHydrateSupport)==null||sa.call(st,{LitElement:Vi});const xr=st.litElementPolyfillSupport;xr==null||xr({LitElement:Vi});(st.litElementVersions??(st.litElementVersions=[])).push("4.2.2");class Hd{constructor(){p(this,"container",null)}mount(e,t){return this.container=e,Si(this.renderTemplate(t),e),e.classList.add("timeline-manager-root"),e.style.gridTemplateColumns=`${t.leftPanelWidth}px minmax(0, 1fr)`,e.style.gridTemplateRows=`${t.timeScaleHeight}px minmax(0, 1fr)`,e.style.background=t.theme.background,{headerCorner:this.requireElement(e,'[data-layout-role="header-corner"]'),headerViewport:this.requireElement(e,'[data-layout-role="header-viewport"]'),headerCanvasHost:this.requireElement(e,'[data-layout-role="header-canvas-host"]'),trackInfoViewport:this.requireElement(e,'[data-layout-role="track-info-viewport"]'),bodyViewport:this.requireElement(e,'[data-layout-role="body-viewport"]'),bodyCanvasHost:this.requireElement(e,'[data-layout-role="body-canvas-host"]'),verticalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="vertical-scrollbar-host"]'),horizontalScrollbarCanvasHost:this.requireElement(e,'[data-layout-role="horizontal-scrollbar-host"]'),playheadOverlay:this.requireElement(e,'[data-layout-role="playhead-overlay"]')}}destroy(){this.container&&Si(null,this.container),this.container=null}renderTemplate(e){const{theme:t,timeScaleHeight:i,leftPanelWidth:r,scrollbarSize:s}=e,a=["position:relative","min-width:0","min-height:0","max-width:100%","box-sizing:border-box",`background:${t.background}`,`color:${t.clipName}`].join(";");return q`
34
34
  <div
35
35
  class="timeline-manager-header-corner"
36
36
  data-layout-role="header-corner"
@@ -78,7 +78,7 @@ js: import "konva/skia-backend";
78
78
  data-layout-role="playhead-overlay"
79
79
  style=${["position:absolute",`left:${r}px`,"top:0","right:0","bottom:0","pointer-events:none","z-index:3"].join(";")}
80
80
  ></div>
81
- `}requireElement(e,t){const i=e.querySelector(t);if(!i)throw new Error(`Missing timeline manager layout element: ${t}`);return i}}const Si=80,Jr=8,kn="timeline-manager-managed-layout-styles";function Ad(){if(typeof document>"u"||document.getElementById(kn))return;const n=document.createElement("style");n.id=kn,n.textContent=`
81
+ `}requireElement(e,t){const i=e.querySelector(t);if(!i)throw new Error(`Missing timeline manager layout element: ${t}`);return i}}const Ci=80,Jr=8,xn="timeline-manager-managed-layout-styles";function Gd(){if(typeof document>"u"||document.getElementById(xn))return;const n=document.createElement("style");n.id=xn,n.textContent=`
82
82
  .timeline-manager-root {
83
83
  position: relative;
84
84
  overflow: hidden;
@@ -104,15 +104,15 @@ js: import "konva/skia-backend";
104
104
  height: 0;
105
105
  display: none;
106
106
  }
107
- `,document.head.appendChild(n)}function Id(n,e){Ad();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??Si,scrollbarSize:e.scrollbarSize??Jr};return new _d().mount(n,t)}/**
107
+ `,document.head.appendChild(n)}function Nd(n,e){Gd();const t={theme:e.theme,timeScaleHeight:e.timeScaleHeight,leftPanelWidth:e.leftPanelWidth??Ci,scrollbarSize:e.scrollbarSize??Jr};return new Hd().mount(n,t)}/**
108
108
  * @license
109
109
  * Copyright 2017 Google LLC
110
110
  * SPDX-License-Identifier: BSD-3-Clause
111
- */const Ed={CHILD:2},Md=n=>(...e)=>({_$litDirective$:n,values:e});class Rd{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
111
+ */const zd={CHILD:2},$d=n=>(...e)=>({_$litDirective$:n,values:e});class Vd{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}}/**
112
112
  * @license
113
113
  * Copyright 2017 Google LLC
114
114
  * SPDX-License-Identifier: BSD-3-Clause
115
- */class Qr extends Rd{constructor(e){if(super(e),this.it=oe,e.type!==Ed.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===oe||e==null)return this._t=void 0,this.it=e;if(e===at)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}}Qr.directiveName="unsafeHTML",Qr.resultType=1;const sr=Md(Qr);function _e(n){return n==="text"?Fi.TEXT:n==="video"?Fi.VIDEO:Fi.AUDIO}function Gt(n,e,t){let i=t;for(const r of n){if(r.id===e)break;i+=_e(r.type)}return i}function wn(n,e){return n.reduce((t,i)=>t+_e(i.type),e)}function Ld(n,e){let t=e;return n.map(i=>{const r=_e(i.type),s={trackId:i.id,y:t,height:r};return t+=r,s})}class co{constructor(){p(this,"container",null);p(this,"viewModel",null)}mount(e){this.container=e,this.renderCurrent()}update(e){this.viewModel=e,this.renderCurrent()}destroy(){this.container&&yi(oe,this.container),this.container=null,this.viewModel=null}get mountedContainer(){return this.container}afterRender(e,t){}renderCurrent(){!this.container||!this.viewModel||(yi(this.renderTemplate(this.viewModel),this.container),this.afterRender(this.container,this.viewModel))}}class Dd extends co{renderTemplate(e){const{theme:t,tracks:i,scrollTop:r,timeScaleHeight:s,includeTimeScaleSpacer:a,onMuteTrack:o,icons:l}=e;return j`
115
+ */class Qr extends Vd{constructor(e){if(super(e),this.it=oe,e.type!==zd.CHILD)throw Error(this.constructor.directiveName+"() can only be used in child bindings")}render(e){if(e===oe||e==null)return this._t=void 0,this.it=e;if(e===ot)return e;if(typeof e!="string")throw Error(this.constructor.directiveName+"() called with a non-string value");if(e===this.it)return this._t;this.it=e;const t=[e];return t.raw=t,this._t={_$litType$:this.constructor.resultType,strings:t,values:[]}}}Qr.directiveName="unsafeHTML",Qr.resultType=1;const sr=$d(Qr);function _e(n){return n==="text"?Hi.TEXT:n==="video"?Hi.VIDEO:Hi.AUDIO}function Nt(n,e,t){let i=t;for(const r of n){if(r.id===e)break;i+=_e(r.type)}return i}function Pn(n,e){return n.reduce((t,i)=>t+_e(i.type),e)}function Ud(n,e){let t=e;return n.map(i=>{const r=_e(i.type),s={trackId:i.id,y:t,height:r};return t+=r,s})}class go{constructor(){p(this,"container",null);p(this,"viewModel",null)}mount(e){this.container=e,this.renderCurrent()}update(e){this.viewModel=e,this.renderCurrent()}destroy(){this.container&&Si(oe,this.container),this.container=null,this.viewModel=null}get mountedContainer(){return this.container}afterRender(e,t){}renderCurrent(){!this.container||!this.viewModel||(Si(this.renderTemplate(this.viewModel),this.container),this.afterRender(this.container,this.viewModel))}}class Wd extends go{renderTemplate(e){const{theme:t,tracks:i,scrollTop:r,timeScaleHeight:s,includeTimeScaleSpacer:a,onMuteTrack:o,icons:l}=e;return q`
116
116
  <style>
117
117
  .track-info-item:hover {
118
118
  background: ${t.buttonHover};
@@ -122,14 +122,14 @@ js: import "konva/skia-backend";
122
122
  background: ${t.buttonBackground};
123
123
  }
124
124
  </style>
125
- ${a?j`<div class="track-info-spacer" style=${`height:${s}px;`}></div>`:null}
125
+ ${a?q`<div class="track-info-spacer" style=${`height:${s}px;`}></div>`:null}
126
126
  <div
127
127
  class="track-info-list"
128
128
  style=${`will-change:transform;transform:translateY(-${Math.max(0,r)}px);`}
129
129
  >
130
130
  ${i.map((c,h)=>this.renderTrackItem(c,h,t,o,l))}
131
131
  </div>
132
- `}renderTrackItem(e,t,i,r,s){const a=_e(e.type),o=e.type==="text"?s.textTrack:e.type==="video"?s.videoTrack:s.audioTrack,l=e.type==="text"?e.isMuted?s.hide:s.display:e.isMuted?s.volumeMuted:s.volume,c=e.type==="text"?e.isMuted?"显示文本轨":"隐藏文本轨":e.isMuted?"取消静音":"静音";return j`
132
+ `}renderTrackItem(e,t,i,r,s){const a=_e(e.type),o=e.type==="text"?s.textTrack:e.type==="video"?s.videoTrack:s.audioTrack,l=e.type==="text"?e.isMuted?s.hide:s.display:e.isMuted?s.volumeMuted:s.volume,c=e.type==="text"?e.isMuted?"显示文本轨":"隐藏文本轨":e.isMuted?"取消静音":"静音";return q`
133
133
  <div
134
134
  class="track-info-item"
135
135
  data-index=${String(t)}
@@ -151,7 +151,7 @@ js: import "konva/skia-backend";
151
151
  ${l?sr(this.resizeSvg(l,14)):e.isMuted?"🔇":"🔊"}
152
152
  </button>
153
153
  </div>
154
- `}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class ho{constructor(e,t,i,r){p(this,"container");p(this,"tracks",[]);p(this,"theme");p(this,"width",Si);p(this,"timeScaleHeight",40);p(this,"includeTimeScaleSpacer",!0);p(this,"scrollTop",0);p(this,"renderer",new Dd);p(this,"iconCache",new Map);p(this,"onMuteTrack");var s,a,o,l,c,h;this.container=e.container,this.width=e.width??Si,this.timeScaleHeight=e.timeScaleHeight||40,this.includeTimeScaleSpacer=e.includeTimeScaleSpacer??!0,this.theme={background:((s=e.theme)==null?void 0:s.background)||ke.background,border:((a=e.theme)==null?void 0:a.border)||ke.border,text:((o=e.theme)==null?void 0:o.text)||ke.text,buttonBackground:((l=e.theme)==null?void 0:l.buttonBackground)||ke.buttonBackground,buttonHover:((c=e.theme)==null?void 0:c.buttonHover)||ke.buttonHover,buttonDanger:((h=e.theme)==null?void 0:h.buttonDanger)||ke.buttonDanger},this.onMuteTrack=r,this.iconCache.set("OmAi-camera",be("OmAi-camera")),this.iconCache.set("OmAi-display",be("OmAi-display")),this.iconCache.set("OmAi-hide",be("OmAi-hide")),this.iconCache.set("OmAi-music",be("OmAi-music")),this.iconCache.set("OmAi-text",be("OmAi-text")),this.iconCache.set("OmAi-volume",be("OmAi-volume")),this.iconCache.set("OmAi-volume-mute",be("OmAi-volume-mute")),this.init()}init(){this.container.className="track-info-panel",this.container.style.position="relative",this.container.style.overflow="hidden",this.container.style.width=`${this.width}px`,this.container.style.background=this.theme.background,this.container.style.borderRight=`1px solid ${this.theme.border}`,this.container.style.color=this.theme.text,this.renderer.mount(this.container),this.render()}setTracks(e){this.tracks=[...e],this.render()}getTracks(){return[...this.tracks]}render(){this.renderer.update({tracks:this.tracks,scrollTop:this.scrollTop,theme:this.theme,timeScaleHeight:this.timeScaleHeight,includeTimeScaleSpacer:this.includeTimeScaleSpacer,onMuteTrack:this.onMuteTrack,icons:{textTrack:this.iconCache.get("OmAi-text")??"",videoTrack:this.iconCache.get("OmAi-camera")??"",audioTrack:this.iconCache.get("OmAi-music")??"",display:this.iconCache.get("OmAi-display")??"",hide:this.iconCache.get("OmAi-hide")??"",volume:this.iconCache.get("OmAi-volume")??"",volumeMuted:this.iconCache.get("OmAi-volume-mute")??""}})}setScrollTop(e){this.scrollTop=Math.max(0,e),this.render()}destroy(){this.renderer.destroy(),this.container.innerHTML=""}}const Od={visual:"画面",audio:"音频",text:"文本",voice:"音色"},F={container:"clip-config-panel",tabBar:"clip-config-tab-bar",tabButton:"clip-config-tab-button",content:"clip-config-content",visualPanel:"clip-config-visual-panel",audioPanel:"clip-config-audio-panel",textPanel:"clip-config-text-panel",voicePanel:"clip-config-voice-panel",actionBar:"clip-config-action-bar",section:"clip-config-section",sectionTitle:"clip-config-section-title",row:"clip-config-row",label:"clip-config-label",slider:"clip-config-slider",input:"clip-config-input",textarea:"clip-config-textarea",colorInput:"clip-config-color-input",presetGrid:"clip-config-preset-grid",presetButton:"clip-config-preset-button",resetButton:"clip-config-reset-button",emptyState:"clip-config-empty-state",filterGroup:"clip-config-filter-group",filterButton:"clip-config-filter-button",voiceCardGrid:"clip-config-voice-grid",voiceCard:"clip-config-voice-card",voiceCardPreviewing:"clip-config-voice-card--previewing",voiceCardAvatar:"clip-config-voice-avatar",voiceCardMeta:"clip-config-voice-meta",voiceCardTitle:"clip-config-voice-title",voiceCardSubtitle:"clip-config-voice-subtitle",voiceCardCheck:"clip-config-voice-check",voiceCardAvatarWrap:"clip-config-voice-avatar-wrap",voiceCardAvatarWrapFirstRow:"clip-config-voice-avatar-wrap--first-row",voiceCardAvatarTooltip:"clip-config-voice-avatar-tooltip",voiceCardAvatarMask:"clip-config-voice-avatar-mask",voiceCardAvatarSpeaker:"clip-config-voice-avatar-speaker",voiceCheckbox:"clip-config-voice-checkbox",primaryButton:"clip-config-primary-button",errorText:"clip-config-error-text",voiceLoadingOverlay:"clip-config-voice-loading-overlay",voiceLoadingCard:"clip-config-voice-loading-card",voiceLoadingIcon:"clip-config-voice-loading-icon",voiceLoadingText:"clip-config-voice-loading-text"},vt=class vt extends co{renderTemplate(e){const{theme:t}=e;return j`
154
+ `}resizeSvg(e,t){return e?e.replace(/width="[^"]*"/,`width="${t}"`).replace(/height="[^"]*"/,`height="${t}"`):""}}class fo{constructor(e,t,i,r){p(this,"container");p(this,"tracks",[]);p(this,"theme");p(this,"width",Ci);p(this,"timeScaleHeight",40);p(this,"includeTimeScaleSpacer",!0);p(this,"scrollTop",0);p(this,"renderer",new Wd);p(this,"iconCache",new Map);p(this,"onMuteTrack");var s,a,o,l,c,h;this.container=e.container,this.width=e.width??Ci,this.timeScaleHeight=e.timeScaleHeight||40,this.includeTimeScaleSpacer=e.includeTimeScaleSpacer??!0,this.theme={background:((s=e.theme)==null?void 0:s.background)||ke.background,border:((a=e.theme)==null?void 0:a.border)||ke.border,text:((o=e.theme)==null?void 0:o.text)||ke.text,buttonBackground:((l=e.theme)==null?void 0:l.buttonBackground)||ke.buttonBackground,buttonHover:((c=e.theme)==null?void 0:c.buttonHover)||ke.buttonHover,buttonDanger:((h=e.theme)==null?void 0:h.buttonDanger)||ke.buttonDanger},this.onMuteTrack=r,this.iconCache.set("OmAi-camera",be("OmAi-camera")),this.iconCache.set("OmAi-display",be("OmAi-display")),this.iconCache.set("OmAi-hide",be("OmAi-hide")),this.iconCache.set("OmAi-music",be("OmAi-music")),this.iconCache.set("OmAi-text",be("OmAi-text")),this.iconCache.set("OmAi-volume",be("OmAi-volume")),this.iconCache.set("OmAi-volume-mute",be("OmAi-volume-mute")),this.init()}init(){this.container.className="track-info-panel",this.container.style.position="relative",this.container.style.overflow="hidden",this.container.style.width=`${this.width}px`,this.container.style.background=this.theme.background,this.container.style.borderRight=`1px solid ${this.theme.border}`,this.container.style.color=this.theme.text,this.renderer.mount(this.container),this.render()}setTracks(e){this.tracks=[...e],this.render()}getTracks(){return[...this.tracks]}render(){this.renderer.update({tracks:this.tracks,scrollTop:this.scrollTop,theme:this.theme,timeScaleHeight:this.timeScaleHeight,includeTimeScaleSpacer:this.includeTimeScaleSpacer,onMuteTrack:this.onMuteTrack,icons:{textTrack:this.iconCache.get("OmAi-text")??"",videoTrack:this.iconCache.get("OmAi-camera")??"",audioTrack:this.iconCache.get("OmAi-music")??"",display:this.iconCache.get("OmAi-display")??"",hide:this.iconCache.get("OmAi-hide")??"",volume:this.iconCache.get("OmAi-volume")??"",volumeMuted:this.iconCache.get("OmAi-volume-mute")??""}})}setScrollTop(e){this.scrollTop=Math.max(0,e),this.render()}destroy(){this.renderer.destroy(),this.container.innerHTML=""}}const Yd={visual:"画面",audio:"音频",text:"文本",voice:"音色"},F={container:"clip-config-panel",tabBar:"clip-config-tab-bar",tabButton:"clip-config-tab-button",content:"clip-config-content",visualPanel:"clip-config-visual-panel",audioPanel:"clip-config-audio-panel",textPanel:"clip-config-text-panel",voicePanel:"clip-config-voice-panel",actionBar:"clip-config-action-bar",section:"clip-config-section",sectionTitle:"clip-config-section-title",row:"clip-config-row",label:"clip-config-label",slider:"clip-config-slider",input:"clip-config-input",textarea:"clip-config-textarea",colorInput:"clip-config-color-input",presetGrid:"clip-config-preset-grid",presetButton:"clip-config-preset-button",resetButton:"clip-config-reset-button",emptyState:"clip-config-empty-state",filterGroup:"clip-config-filter-group",filterButton:"clip-config-filter-button",voiceCardGrid:"clip-config-voice-grid",voiceCard:"clip-config-voice-card",voiceCardPreviewing:"clip-config-voice-card--previewing",voiceCardAvatar:"clip-config-voice-avatar",voiceCardMeta:"clip-config-voice-meta",voiceCardTitle:"clip-config-voice-title",voiceCardSubtitle:"clip-config-voice-subtitle",voiceCardCheck:"clip-config-voice-check",voiceCardAvatarWrap:"clip-config-voice-avatar-wrap",voiceCardAvatarWrapFirstRow:"clip-config-voice-avatar-wrap--first-row",voiceCardAvatarTooltip:"clip-config-voice-avatar-tooltip",voiceCardAvatarMask:"clip-config-voice-avatar-mask",voiceCardAvatarSpeaker:"clip-config-voice-avatar-speaker",voiceCheckbox:"clip-config-voice-checkbox",primaryButton:"clip-config-primary-button",errorText:"clip-config-error-text",voiceLoadingOverlay:"clip-config-voice-loading-overlay",voiceLoadingCard:"clip-config-voice-loading-card",voiceLoadingIcon:"clip-config-voice-loading-icon",voiceLoadingText:"clip-config-voice-loading-text"},Tt=class Tt extends go{renderTemplate(e){const{theme:t}=e;return q`
155
155
  <style>
156
156
  @keyframes clip-config-voice-loading-spin {
157
157
  from { transform: rotate(0deg); }
@@ -395,7 +395,7 @@ js: import "konva/skia-backend";
395
395
  ${e.emptyStateMessage?this.renderEmptyState(t,e.emptyStateMessage):this.renderPanel(e)}
396
396
  </div>
397
397
  ${this.renderVoiceLoadingOverlay(e)}
398
- `}renderVoiceLoadingOverlay(e){return e.isVoiceLoadingOverlayVisible?j`
398
+ `}renderVoiceLoadingOverlay(e){return e.isVoiceLoadingOverlayVisible?q`
399
399
  <div
400
400
  class=${F.voiceLoadingOverlay}
401
401
  style=${["position:fixed","inset:0","display:flex","align-items:center","justify-content:center","background:rgba(0,0,0,0.45)","z-index:9999","animation-fill-mode:forwards",`animation:${e.isVoiceLoadingOverlayExiting?"clip-config-voice-loading-overlay-exit 180ms ease":"clip-config-voice-loading-overlay-enter 180ms ease"}`].join(";")}
@@ -418,14 +418,14 @@ js: import "konva/skia-backend";
418
418
  </div>
419
419
  </div>
420
420
  </div>
421
- `:null}renderEmptyState(e,t){return j`
421
+ `:null}renderEmptyState(e,t){return q`
422
422
  <div
423
423
  class=${F.emptyState}
424
424
  style=${`height:100%;display:flex;align-items:center;justify-content:center;padding:40px 20px;color:${e.labelColor};text-align:center;box-sizing:border-box;`}
425
425
  >
426
426
  <div style="font-size:13px;">${t}</div>
427
427
  </div>
428
- `}renderPanel(e){const t=e.availableTabs,i=this.shouldUseVoiceInnerScroll(e);return j`
428
+ `}renderPanel(e){const t=e.availableTabs,i=this.shouldUseVoiceInnerScroll(e);return q`
429
429
  ${t.length>1?this.renderTabBar(e,t):null}
430
430
  <div
431
431
  class=${F.content}
@@ -434,29 +434,29 @@ js: import "konva/skia-backend";
434
434
  ${t.map(r=>this.renderTabPanel(e,r))}
435
435
  </div>
436
436
  ${this.renderActionBar(e)}
437
- `}shouldUseVoiceInnerScroll(e){return e.activeTab==="voice"&&this.supportsVoicePanel(e.selectionState)}renderTabPanel(e,t){return t==="visual"?this.renderVisualPanel(e):t==="audio"?this.renderAudioPanel(e):t==="text"?this.renderTextPanel(e):t==="voice"?this.renderVoicePanel(e):null}renderTabBar(e,t){return j`
437
+ `}shouldUseVoiceInnerScroll(e){return e.activeTab==="voice"&&this.supportsVoicePanel(e.selectionState)}renderTabPanel(e,t){return t==="visual"?this.renderVisualPanel(e):t==="audio"?this.renderAudioPanel(e):t==="text"?this.renderTextPanel(e):t==="voice"?this.renderVoicePanel(e):null}renderTabBar(e,t){return q`
438
438
  <div
439
439
  class=${F.tabBar}
440
440
  style=${`display:flex;gap:12px;padding:4px;background-color:${Pe.tabBarBackground};border-radius:4px 4px 0 0;height:32px;`}
441
441
  >
442
- ${t.map(i=>{const r=e.activeTab===i;return j`
442
+ ${t.map(i=>{const r=e.activeTab===i;return q`
443
443
  <button
444
444
  class=${F.tabButton}
445
445
  style=${["line-height:22px","padding:0 6px","border:none","cursor:pointer","font-size:13px","font-family:inherit","transition:background-color 0.15s, color 0.15s",`background-color:${r?Pe.activeTabBackground:P.transparent}`,`color:${r?Pe.activeTabText:Pe.inactiveTabText}`,"border-radius:4px"].join(";")}
446
446
  @click=${()=>e.callbacks.onTabChange(i)}
447
447
  >
448
- ${Od[i]}
448
+ ${Yd[i]}
449
449
  </button>
450
450
  `})}
451
451
  </div>
452
- `}renderActionBar(e){const t=e.activeTab==="voice"&&this.supportsVoicePanel(e.selectionState);return j`
452
+ `}renderActionBar(e){const t=e.activeTab==="voice"&&this.supportsVoicePanel(e.selectionState);return q`
453
453
  <div
454
454
  class=${F.actionBar}
455
455
  style=${[`border-top:1px solid ${e.theme.borderColor}`,"border-radius:0 0 4px 4px","min-height:32px",`background-color:${Pe.actionBarBackground}`,"padding:8px 10px"].join(";")}
456
456
  >
457
457
  ${t?this.renderVoiceActionBar(e):null}
458
458
  </div>
459
- `}renderVoiceActionBar(e){const t=e.clip,i=!e.selectedVoiceId,r=(t==null?void 0:t.type)==="audio"?"配音随文本更新":"本次生成后随文本更新",s=(t==null?void 0:t.type)==="audio"?"变换音色":"生成配音";return j`
459
+ `}renderVoiceActionBar(e){const t=e.clip,i=!e.selectedVoiceId,r=(t==null?void 0:t.type)==="audio"?"配音随文本更新":"本次生成后随文本更新",s=(t==null?void 0:t.type)==="audio"?"变换音色":"生成配音";return q`
460
460
  <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;">
461
461
  <label
462
462
  class=${F.voiceCheckbox}
@@ -478,19 +478,19 @@ js: import "konva/skia-backend";
478
478
  ${s}
479
479
  </button>
480
480
  </div>
481
- `}renderVisualPanel(e){const t=e.activeTab==="visual"?"block":"none";return j`
481
+ `}renderVisualPanel(e){const t=e.activeTab==="visual"?"block":"none";return q`
482
482
  <div class=${F.visualPanel} style=${`display:${t};`}>
483
483
  ${this.renderPositionSection(e)}
484
484
  ${this.renderScaleSection(e)}
485
485
  </div>
486
- `}renderPositionSection(e){return j`
486
+ `}renderPositionSection(e){return q`
487
487
  <div class=${F.section} style="margin-bottom:16px;">
488
488
  ${this.renderSectionTitle("位置",e.theme)}
489
489
  ${this.renderPositionControl(e,"X","x")}
490
490
  ${this.renderPositionControl(e,"Y","y")}
491
491
  ${this.renderPresetGrid(e)}
492
492
  </div>
493
- `}renderScaleSection(e){const t=this.getTransform(e.clip);return j`
493
+ `}renderScaleSection(e){const t=this.getTransform(e.clip);return q`
494
494
  <div
495
495
  class=${F.section}
496
496
  style=${`border-top:1px solid ${e.theme.borderColor};padding-top:16px;`}
@@ -508,7 +508,7 @@ js: import "konva/skia-backend";
508
508
  </button>
509
509
  </div>
510
510
  </div>
511
- `}renderAudioPanel(e){var r;const t=e.activeTab==="audio"?"block":"none",i=((r=e.clip)==null?void 0:r.volume)??1;return j`
511
+ `}renderAudioPanel(e){var r;const t=e.activeTab==="audio"?"block":"none",i=((r=e.clip)==null?void 0:r.volume)??1;return q`
512
512
  <div class=${F.audioPanel} style=${`display:${t};`}>
513
513
  <div class=${F.section}>
514
514
  ${this.renderSectionTitle("音量",e.theme)}
@@ -519,9 +519,9 @@ js: import "konva/skia-backend";
519
519
  </div>
520
520
  </div>
521
521
  </div>
522
- `}renderTextPanel(e){const t=e.clip,i=this.getTransform(t),r=fe(t==null?void 0:t.textStyle),s=e.activeTab==="text"?"block":"none";return j`
522
+ `}renderTextPanel(e){const t=e.clip,i=this.getTransform(t),r=ce(t==null?void 0:t.textStyle),s=e.activeTab==="text"?"block":"none";return q`
523
523
  <div class=${F.textPanel} style=${`display:${s};`}>
524
- ${e.isTextContentEditable?j`
524
+ ${e.isTextContentEditable?q`
525
525
  <div class=${F.section} style="margin-bottom:16px;">
526
526
  ${this.renderSectionTitle("文本",e.theme)}
527
527
  <textarea
@@ -548,7 +548,7 @@ js: import "konva/skia-backend";
548
548
  class=${F.colorInput}
549
549
  .value=${r.color}
550
550
  style=${["width:108px","height:48px","padding:4px",`border:1px solid ${e.theme.inputBorder}`,"border-radius:8px",`background-color:${e.theme.inputBackground}`].join(";")}
551
- @input=${vt.createColorInputHandler(e)}
551
+ @input=${Tt.createColorInputHandler(e)}
552
552
  />
553
553
  </div>
554
554
  <div class=${F.section} style="margin-bottom:16px;">
@@ -565,7 +565,7 @@ js: import "konva/skia-backend";
565
565
  </div>
566
566
  </div>
567
567
  </div>
568
- `}renderVoicePanel(e){const t=e.activeTab==="voice"?"block":"none",i=[{key:"女",label:"女声"},{key:"男",label:"男声"},{key:"普通话",label:"普通话"},{key:"粤语",label:"粤语"}],r=e.voiceCatalog.filter(l=>!e.activeVoiceFilterTag||l.tags.includes(e.activeVoiceFilterTag)),s=this.shouldUseVoiceInnerScroll(e),o=[`display:${t==="block"?s?"flex":"block":"none"}`,s?"flex-direction:column":"",s?"flex:1":"",s?"min-height:0":"",s?"overflow:hidden":""].filter(Boolean).join(";");return j`
568
+ `}renderVoicePanel(e){const t=e.activeTab==="voice"?"block":"none",i=[{key:"女",label:"女声"},{key:"男",label:"男声"},{key:"普通话",label:"普通话"},{key:"粤语",label:"粤语"}],r=e.voiceCatalog.filter(l=>!e.activeVoiceFilterTag||l.tags.includes(e.activeVoiceFilterTag)),s=this.shouldUseVoiceInnerScroll(e),o=[`display:${t==="block"?s?"flex":"block":"none"}`,s?"flex-direction:column":"",s?"flex:1":"",s?"min-height:0":"",s?"overflow:hidden":""].filter(Boolean).join(";");return q`
569
569
  <div class=${F.voicePanel} style=${o}>
570
570
  <div class=${F.section} style=${s?"flex-shrink:0;margin-bottom:12px;":"margin-bottom:16px;"}>
571
571
  <div class=${F.filterGroup} style="display:flex;gap:8px;flex-wrap:wrap;">
@@ -579,12 +579,12 @@ js: import "konva/skia-backend";
579
579
  <div class=${F.voiceCardGrid} style="display:grid;grid-template-columns:repeat(2, minmax(0, 1fr));gap:8px;">
580
580
  ${r.map((l,c)=>this.renderVoiceCard(e,l,c))}
581
581
  </div>
582
- ${r.length===0?j`
582
+ ${r.length===0?q`
583
583
  <div style=${`padding:16px 0;font-size:12px;color:${e.theme.labelColor};`}>
584
584
  当前筛选下暂无音色
585
585
  </div>
586
586
  `:null}
587
- ${e.voiceErrorMessage?j`
587
+ ${e.voiceErrorMessage?q`
588
588
  <div
589
589
  class=${F.errorText}
590
590
  style=${`padding-top:12px;font-size:12px;color:${P.accentDanger};`}
@@ -594,7 +594,7 @@ js: import "konva/skia-backend";
594
594
  `:null}
595
595
  </div>
596
596
  </div>
597
- `}renderFilterButton(e,t,i,r,s){return j`
597
+ `}renderFilterButton(e,t,i,r,s){return q`
598
598
  <button
599
599
  class=${F.filterButton}
600
600
  style=${["padding:6px 12px","border:none","border-radius:999px","cursor:pointer","font-size:12px",`background:${r?Pe.activeTabBackground:e.theme.buttonBackground}`,`color:${r?e.theme.buttonActiveText:e.theme.textColor}`].join(";")}
@@ -603,13 +603,13 @@ js: import "konva/skia-backend";
603
603
  >
604
604
  ${i}
605
605
  </button>
606
- `}renderVoiceCard(e,t,i){const r=e.selectedVoiceId===t.id,s=e.previewingVoiceId===t.id,a=t.avatar,o=i<2;return j`
606
+ `}renderVoiceCard(e,t,i){const r=e.selectedVoiceId===t.id,s=e.previewingVoiceId===t.id,a=t.avatar,o=i<2;return q`
607
607
  <button
608
608
  class=${[F.voiceCard,s?F.voiceCardPreviewing:""].filter(Boolean).join(" ")}
609
609
  style=${["position:relative","display:flex","align-items:center","gap:12px","width:100%","padding:8px","border-radius:12px","text-align:left","cursor:pointer",`border:${r?`1px solid ${e.theme.buttonActiveBorder}`:""}`,`background:${r?Pe.activeTabBackground:e.theme.buttonBackground}`,`color:${e.theme.textColor}`].join(";")}
610
610
  @click=${()=>e.callbacks.onVoiceSelect(t.id)}
611
611
  >
612
- ${a?j`
612
+ ${a?q`
613
613
  <span
614
614
  class=${[F.voiceCardAvatarWrap,o?F.voiceCardAvatarWrapFirstRow:""].filter(Boolean).join(" ")}
615
615
  >
@@ -636,7 +636,7 @@ js: import "konva/skia-backend";
636
636
  </span>
637
637
  <span class=${F.voiceCardAvatarTooltip}>试听</span>
638
638
  </span>
639
- `:j`
639
+ `:q`
640
640
  <div
641
641
  class=${F.voiceCardAvatar}
642
642
  style=${["width:32px","height:32px","border-radius:8px","flex-shrink:0","display:flex","align-items:center","justify-content:center","background:linear-gradient(135deg, #6c7080 0%, #424656 100%)",`color:${P.white}`,"font-size:18px","font-weight:600"].join(";")}
@@ -658,7 +658,7 @@ js: import "konva/skia-backend";
658
658
  ${t.lang} · ${t.emotion}
659
659
  </div>
660
660
  </div>
661
- ${r?j`
661
+ ${r?q`
662
662
  <div
663
663
  class=${F.voiceCardCheck}
664
664
  style="position:absolute;top:50%;right:8px;transform:translateY(-42%);"
@@ -667,7 +667,7 @@ js: import "konva/skia-backend";
667
667
  </div>
668
668
  `:null}
669
669
  </button>
670
- `}renderPositionControl(e,t,i){const r=this.getTransform(e.clip),s=r.scale/2,a=-s,o=1+s;return j`
670
+ `}renderPositionControl(e,t,i){const r=this.getTransform(e.clip),s=r.scale/2,a=-s,o=1+s;return q`
671
671
  <div
672
672
  class=${F.row}
673
673
  style="display:flex;align-items:center;gap:8px;margin-bottom:8px;"
@@ -681,12 +681,12 @@ js: import "konva/skia-backend";
681
681
  ${this.renderRangeInput({min:String(a),max:String(o),step:"0.01",value:String(r[i]),onInput:l=>e.callbacks.onTransformChange(i,l)})}
682
682
  ${this.renderNumberInput(e.theme,{min:String(a),max:String(o),step:"0.01",value:String(r[i]),onChange:l=>e.callbacks.onTransformChange(i,l)})}
683
683
  </div>
684
- `}renderPresetGrid(e){const t=[{label:"↖ 左上",x:"left",y:"top"},{label:"↑ 上中",x:"center",y:"top"},{label:"↗ 右上",x:"right",y:"top"},{label:"← 左中",x:"left",y:"center"},{label:"● 居中",x:"center",y:"center"},{label:"右中 →",x:"right",y:"center"},{label:"↙ 左下",x:"left",y:"bottom"},{label:"↓ 下中",x:"center",y:"bottom"},{label:"↘ 右下",x:"right",y:"bottom"}];return j`
684
+ `}renderPresetGrid(e){const t=[{label:"↖ 左上",x:"left",y:"top"},{label:"↑ 上中",x:"center",y:"top"},{label:"↗ 右上",x:"right",y:"top"},{label:"← 左中",x:"left",y:"center"},{label:"● 居中",x:"center",y:"center"},{label:"右中 →",x:"right",y:"center"},{label:"↙ 左下",x:"left",y:"bottom"},{label:"↓ 下中",x:"center",y:"bottom"},{label:"↘ 右下",x:"right",y:"bottom"}];return q`
685
685
  <div
686
686
  class=${F.presetGrid}
687
687
  style="display:grid;grid-template-columns:repeat(3, 1fr);gap:4px;"
688
688
  >
689
- ${t.map(i=>j`
689
+ ${t.map(i=>q`
690
690
  <button
691
691
  class=${F.presetButton}
692
692
  style=${["padding:6px",`border:1px solid ${e.theme.buttonBorder}`,"border-radius:4px",`background:${e.theme.buttonBackground}`,"font-size:11px","cursor:pointer",`color:${e.theme.textColor}`].join(";")}
@@ -696,14 +696,14 @@ js: import "konva/skia-backend";
696
696
  </button>
697
697
  `)}
698
698
  </div>
699
- `}renderSectionTitle(e,t){return j`
699
+ `}renderSectionTitle(e,t){return q`
700
700
  <div
701
701
  class=${F.sectionTitle}
702
702
  style=${`font-size:12px;color:${t.labelColor};margin-bottom:8px;text-transform:uppercase;`}
703
703
  >
704
704
  ${e}
705
705
  </div>
706
- `}renderRangeInput(e){return j`
706
+ `}renderRangeInput(e){return q`
707
707
  <input
708
708
  type="range"
709
709
  class=${F.slider}
@@ -714,7 +714,7 @@ js: import "konva/skia-backend";
714
714
  style=${this.getSliderStyle(e.min,e.max,e.value)}
715
715
  @input=${t=>e.onInput(Number.parseFloat(t.target.value))}
716
716
  />
717
- `}renderNumberInput(e,t){return j`
717
+ `}renderNumberInput(e,t){return q`
718
718
  <input
719
719
  type="number"
720
720
  class=${F.input}
@@ -725,10 +725,10 @@ js: import "konva/skia-backend";
725
725
  style=${["width:60px","padding:4px 6px",`border:1px solid ${e.inputBorder}`,"border-radius:4px","font-size:12px",`background-color:${e.inputBackground}`,`color:${e.textColor}`].join(";")}
726
726
  @change=${i=>t.onChange(Number.parseFloat(i.target.value))}
727
727
  />
728
- `}renderLabeledNumberInput(e,t,i,r,s="0.01",a="-9999",o="9999"){return j`
728
+ `}renderLabeledNumberInput(e,t,i,r,s="0.01",a="-9999",o="9999"){return q`
729
729
  <label style="display:flex;align-items:center;gap:8px;">
730
730
  <span style=${`min-width:18px;font-size:13px;color:${e.theme.labelColor};`}>${t}</span>
731
731
  ${this.renderNumberInput(e.theme,{min:a,max:o,step:s,value:String(i),onChange:r})}
732
732
  </label>
733
- `}getContainerStyle(e){return[`background-color:${e.backgroundColor}`,"border-radius:4px",`color:${e.textColor}`,'font-family:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size:13px","display:flex","flex-direction:column","overflow:hidden","height:100%",`--clip-slider-fill-start:${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(vt.colorRafId),vt.colorRafId=requestAnimationFrame(()=>{e.callbacks.onTextStyleChange("color",i)})}}};p(vt,"colorRafId",0);let es=vt;const Bd={...ye};function xn(n){return n?{primaryClip:n,selectedClips:[n],selectionCount:1,groupKind:n.type,supportsVoiceBatch:n.type==="text"||Re(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 Fd(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 uo{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",xn(null));p(this,"activeTab","visual");p(this,"iconCache",new Map);p(this,"pendingPreferredTab",null);p(this,"selectedVoiceId",null);p(this,"activeVoiceFilterTag","男");p(this,"textDraftContent","");p(this,"followTextUpdates",!0);p(this,"voiceLoadingBusyCount",0);p(this,"isVoiceLoadingOverlayRendered",!1);p(this,"isVoiceLoadingOverlayExiting",!1);p(this,"voiceLoadingOverlayHideTimer",null);p(this,"voiceErrorMessage",null);p(this,"voicePreviewAudio",null);p(this,"previewingVoiceId",null);p(this,"handleVoicePreviewEnded",()=>{this.stopVoicePreview()});this.container=e.container,this.theme=e.theme??Bd,this.voiceCatalog=e.voiceCatalog??[],this.onClipUpdate=e.onClipUpdate,this.onGenerateVoice=e.onGenerateVoice,this.iconCache.set("OmAi-camera",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(xn(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=!Fd(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={...fe(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(li.MIN,Math.min(li.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 Hd(n){return n==="text"?"文本":n==="video"?"视频":"音频"}class Pn{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:`${Hd(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(Me.MIN,Math.min(Me.MAX,e));return this.updateZoom(t)}setSpeed(e){const t=Math.max(.1,Math.min(10,e));return this.updateSpeed(t)}updateSelection(e){const t=this.timelineStore.getPrimarySelectedClipId();return t===e?{previousClipId:t,nextClipId:e,changed:!1}:(e===null?this.timelineStore.clearSelection():this.timelineStore.setPrimarySelectedClipId(e),{previousClipId:t,nextClipId:e,changed:!0})}updateCurrentTime(e){const t=this.timelineStore.getCurrentTime();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setCurrentTime(e),{previousValue:t,nextValue:e,changed:!0})}updateZoom(e){const t=this.timelineStore.getZoom();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setZoom(e),{previousValue:t,nextValue:e,changed:!0})}updateSpeed(e){const t=this.timelineStore.getSpeed();return t===e?{previousValue:t,nextValue:e,changed:!1}:(this.timelineStore.setSpeed(e),{previousValue:t,nextValue:e,changed:!0})}resolveTrackId(e){return typeof e.getId=="function"?e.getId():typeof e.id=="string"?e.id:null}resolveTrackType(e){return typeof e.getTrackType=="function"?e.getTrackType():e.type??null}resolveTrackTargetByY(e,t,i,r){let 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 _n{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 Gd=["type","externalId","src","name","isMuted","startTime","duration","endTime","startTimeAtSource","endTimeAtSource","sourceDuration","thumbnails","style","visualTransform","separatedAudioClipId","separatedFromVideoClipId","volume","textContent","textStyle","ttsSourceTextClipId","ttsVoiceId","ttsVoiceName","ttsFollowTextUpdates"],Nd=new Set(["thumbnails"]);function zd(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 An{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(Gd.forEach(d=>{zd(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=>Nd.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 Di(n){var e;n.notifySelectionChange(),(e=n.emitSelectionChangeEvent)==null||e.call(n),n.emitSelectedClipChangeIfNeeded(),n.handleClipChange()}function $d(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 Vd(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 yt(n){return n.length===0?0:Math.max(...n.map(e=>e.endTime))}function Ud(n,e){return e<yt(n)}function Wd(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 Yd(n){const e=!n.id&&n.startTime>0;return{shouldJumpToTime:e,jumpTime:e?n.startTime:null,shouldSelectClip:!!n.id}}function Vi(n){var e;return n.applied?(n.isExecutingHistoryAction||(e=n.recordHistory)==null||e.call(n),n.applyEffects(),!0):!1}function Xd(n){return Vi({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 qd(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},po=.06,In={x:.5,y:1-po-48/720/2},jd=.1,Kd=8;function ni(n,e){return typeof n=="number"&&Number.isFinite(n)?n:e}function Zd(n){return Math.min(Kd,Math.max(jd,n))}function xe(n){return{x:ni(n==null?void 0:n.x,Pr.x),y:ni(n==null?void 0:n.y,Pr.y),scale:Zd(ni(n==null?void 0:n.scale,Pr.scale))}}function Ui(n){return{x:ni(n==null?void 0:n.x,In.x),y:ni(n==null?void 0:n.y,In.y),scale:1}}function vs(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 go(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 En(n,e,t){const i=go(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 fo(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 Jd(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 Qd=1,eu=48,tu=48,mo=16,iu=4e3,ru=4e3,su=1.35;function Ts(n){return n>0?n:1}function nu(n,e,t,i){const r=Ts(i);return{fontSize:n*r,paddingX:e*r,strokeWidth:t*r}}function au(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 ou(n,e,t,i){const r=Math.max(1,n),s=e.split(`
734
- `),a=Math.max(1,t-i*2),o=Math.max(1,Math.floor(a/(r*.55)));let l=0;for(const c of s){const h=c.length>0?c:" ";l+=Math.max(1,Math.ceil(h.length/o))}return Math.max(mo,Math.round(r*su*l))}function lu(n,e=eu){const t=n>0?n:720;return{x:.5,y:1-po-e/t/2,scale:1}}function cu(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 yo(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 e.anchorVersion===Qd?r:cu(r,t,i)}function So(n){return Math.min(iu,Math.max(tu,n))}function Co(n){return Math.min(ru,Math.max(mo,n))}function bs(n){var o,l,c;const e=n.textStyle,t=((o=n.styleOverride)==null?void 0:o.fontSize)??e.fontSize,i=n.frameSize,r=Ts(n.baselineScale),s=So(((l=n.styleOverride)==null?void 0:l.layoutWidth)??e.layoutWidth??au(i.width,r,e.paddingX,n.visualTransform.x)),a=Co(((c=n.styleOverride)==null?void 0:c.layoutHeight)??e.layoutHeight??ou(t,n.contentText,s,e.paddingX));return{layoutWidth:s,layoutHeight:a}}function vo(n){const{layoutWidth:e,layoutHeight:t}=bs(n),i=e*n.baselineScale,r=t*n.baselineScale,s=n.frameSize.width*n.visualTransform.x,a=n.frameSize.height*n.visualTransform.y,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 hu(n,e,t,i,r){const s=Ts(r),a=Math.abs(n-t),o=Math.abs(e-i);return{layoutWidth:So(Math.round(a*2/s)),layoutHeight:Co(Math.round(o*2/s))}}function du(n,e,t,i){const r=fe(n.clip.textStyle),s=n.clip.textContent||n.clip.name||"",{layoutHeight:a}=bs({frameSize:e,baselineScale:t,visualTransform:{x:.5,y:.5,scale:1},textStyle:r,contentText:s,styleOverride:i}),o=a*t,l=yo(n.clip.visualTransform,r,e,o);return vo({frameSize:e,baselineScale:t,visualTransform:l,textStyle:r,contentText:s,styleOverride:i})}function uu(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 Mn(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){uu(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=hu(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=fo(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=Jd(g,f,i.x,i.y,this.interaction.baseRect,this.interaction.startTransform)}this.interaction.nextTransform=r,this.interaction.changed=!vs(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:Mn(this.frameElement.style.left),top:Mn(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 gu{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 fu(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 Rn(n,e){return n.entry?e?n.entry.clip.id===e:!0:!1}function mu(n,e){return e?!Rn(n.current,e.clip.id)&&Rn(n.preload,e.clip.id):!1}function yu(n){return n.current.role="preload",n.preload.role="current",{current:n.preload,preload:n.current}}const Su=2,Cu=.5,vu=750,Tu="媒体丢失";function Wi(n){return!!n&&typeof n.then=="function"}function is(n){return n.getAttribute("src")||n.currentSrc||n.src||""}function ai(n){return n.getAttribute("src")||""}function _t(n){return typeof HTMLVideoElement<"u"?n instanceof HTMLVideoElement:n.tagName==="VIDEO"}function Xt(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 Ln(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 Dn(n){if(!n)return 0;const e=Number.parseFloat(n);return Number.isFinite(e)?e:0}function bu(n){const e=n.buffered;return!e||typeof e.length!="number"||e.length<=0?null:e.end(e.length-1)}function ku(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:bu(n),videoWidth:_t(n)?n.videoWidth:0,videoHeight:_t(n)?n.videoHeight:0,error:n.error?{code:n.error.code,message:n.error.message}:null}}function On(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 st(n){var e;return((e=n.externalId)==null?void 0:e.trim())||n.src}class wu{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>=Su||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(vu,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 xu(n,e){return!bt(n.mode)||!e?n:{mode:Le.mode,width:e.width,height:e.height}}class Pu{constructor(e){p(this,"container",null);p(this,"rootElement",null);p(this,"frameElement",null);p(this,"resizeObserver",null);p(this,"requestedAspectRatio",{...Le});p(this,"resolvedAutoAspectRatio",null);p(this,"transformOverlay");this.transformOverlay=e}attach(e,t){if(this.container===e&&this.rootElement){this.updateFrameLayout();return}this.detach(),this.container=e;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.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 xu(this.requestedAspectRatio,this.resolvedAutoAspectRatio)}resolveAutoAspectRatio(e,t,i){e<=0||t<=0||(this.resolvedAutoAspectRatio={width:e,height:t},this.updateFrameLayout(),i&&bt(this.requestedAspectRatio.mode)&&i(this.getAspectRatio()))}tryResolveAutoAspectRatioFromSlot(e,t){if(!bt(this.requestedAspectRatio.mode)||this.resolvedAutoAspectRatio||e.kind!=="video")return;const i=e.element;_t(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=En(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 f;if(!e)return null;const s=this.getFrameSize();if(s.width<=0||s.height<=0)return null;for(const m of t){if(m.kind!=="video"||!m.isActive||!m.entry||m.entry.clip.id!==e)continue;const C=this.getMediaSize(m,m.entry,s),v=r(m.entry);return{clipId:m.entry.clip.id,transform:v,frameSize:s,baseRect:go(s,C),displayRect:En(s,C,v),clipType:"video"}}const a=i.getEntry(e);if(!a||!this.frameElement)return null;const o=this.getTextBaselineMetrics(s),l=((f=i.getTextLayoutOverride)==null?void 0:f.call(i,e))??null,c=du(a.entry,s,o.scale,l),h=fe(a.entry.clip.textStyle),d=c.visualTransform,u=i.getTransientFontSize(e)??h.fontSize,g=i.getTransientRotation(e)??h.rotation;return{clipId:e,transform:d,frameSize:s,baseRect:{left:0,top:0,width:s.width,height:s.height,centerX:s.width/2,centerY:s.height/2},displayRect:c.frameRect,clipType:"text",currentFontSize:u,currentRotation:g,currentLayoutWidth:c.layoutWidth,currentLayoutHeight:c.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:Dn((s=this.frameElement)==null?void 0:s.style.width),height:t>0?t:Dn((a=this.frameElement)==null?void 0:a.style.height)}}getTextBaselineMetrics(e){const t=qi(this.getAspectRatio(),as);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 fo(e,t,i,this.getFrameSize())}transformsEqual(e,t){return vs(e,t)}updateFrameLayout(){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`}getMediaSize(e,t,i){if(_t(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=Tu,e.element.style.visibility=t?"hidden":"visible"}}const _u=500;class Bn{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,"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,"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()}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"),Xt(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=ai(this.element),r=is(this.element),s=!i&&!!e.url,a=this.boundStableKey!==t||s||!On(i,r,e.url);return a?(this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url,this.hasReadyEventSinceSourceChange=!1,this.element.setAttribute("src",e.url),Xt(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),Xt(this.element),this.boundStableKey=t,this.stableSourceUrl=e.stableSourceUrl,this.desiredSource=e.url):(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 On(ai(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"||!ai(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 t,i,r,s,a;this.sourceGen+=1,this.cleanup.forEach(o=>o()),this.cleanup=[],qt(this.element),e(this.objectUrl),this.objectUrl=null,this.element.removeAttribute("src"),Xt(this.element),(i=(t=this.gainNode)==null?void 0:t.disconnect)==null||i.call(t),(s=(r=this.sourceNode)==null?void 0:r.disconnect)==null||s.call(r),(a=this.wrapper)==null||a.remove(),this.element.remove()}syncCurrentPlayback(e,t,i){const r=e.mediaTime/1e3,s=t==="playing"?Math.max(Cu,i*.15):ar("current",i),a=t==="playing"&&!this.element.ended;Math.abs(this.element.currentTime-r)>s&&(this.isSeeking=!0,Ln(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)&&Ln(this.element,t)}setVisible(e,t){this.wrapper&&(this.wrapper.style.display=e?"block":"none",this.wrapper.style.zIndex=String(t),_t(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,_t(r)?(cs(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;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:ku(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 Au(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 Iu{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 Eu{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?st(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){this.options.releaseObjectUrl(e.objectUrl),e.objectUrl=null,e.clear(),this.options.onStateChange();return}const a=st(t.entry.clip),o=this.options.sourceService.getReusableSource(e.boundStableKey,e.stableSourceUrl,e.desiredSource,e.objectUrl,t.entry);e.desiredSource&&!ai(e.element)&&(e.element.setAttribute("src",e.desiredSource),Xt(e.element)),r&&r!==a?(this.options.releaseObjectUrl(e.objectUrl),e.objectUrl=null,e.sourceGen+=1):!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){d!=null&&d.objectUrl&&(u||g)&&this.options.sourceService.revokeObjectUrl(d.objectUrl);return}if(e.isResolvingSource=!1,!ai(e.element)&&!d.url){e.fail("未找到可用预览源");return}if(e.phase==="failed"&&e.errorMessage){this.options.onStateChange();return}e.assignSource(d,a);const f=d.objectUrl??(d.url.startsWith("blob:")?d.url:null);this.options.rememberObjectUrl(e,f),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 jt(n){return n.role==="current"&&n.isActive&&n.kind==="video"&&!!n.entry}function Fn(n){const e=jt(n),t=Au(n,e);return e&&n.requestedPlayState==="playing"&&n.maybeResumePlayback("runtime-check"),t}const Mu={aac:"audio/aac",m4a:"audio/mp4",mp3:"audio/mpeg",ogg:"audio/ogg",wav:"audio/wav"};function Ru(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 Lu(n){const e=Ru(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=Mu[e];return t?{url:n.src,mimeType:t,kind:"audio"}:null}class Du{constructor(e={}){p(this,"dependencies");p(this,"pendingRuntime",new Map);this.dependencies=e}resolve(e,t){if(t.reuse)return t.reuse;const i=this.dependencies.previewSourceResolver??Lu,r=this.dependencies.sourceMediaRegistry,s=st(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=st(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}}revokeObjectUrl(e){var t;e&&((t=this.dependencies.resourceCacheManager)==null||t.revokeObjectUrl(e))}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=st(e.clip),l=`${o}:${s.url}`,c=this.pendingRuntime.get(l);if(c)return c;const h=a.resolvePlayableUrl({url:s.url,mimeType:s.mimeType,kind:s.kind,sourceKey:o}).then(d=>this.normalizeCachedResult(s.url,d,i,r)).catch(()=>i()!==r?null:{stableSourceUrl:s.url,url:s.url,objectUrl:null,sizeBytes:null}).finally(()=>{this.pendingRuntime.delete(l)});return this.pendingRuntime.set(l,h),h}normalizeCachedResult(e,t,i,r){var s;return i()!==r?((s=t==null?void 0:t.url)!=null&&s.startsWith("blob:")&&this.revokeObjectUrl(t.url),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)}}function Ou(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 To(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function _r(n){return`"${To(n)}"`}function Hn(n){return n.clip.textContent||n.clip.name||""}function Bu(){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="flex",e.style.alignItems="center",e.style.justifyContent="center",e.style.width="100%",e.style.height="100%",e.style.textAlign="center",e.style.whiteSpace="pre-wrap",e.style.overflowWrap="break-word",e.style.overflow="hidden",e.style.boxSizing="border-box",n.appendChild(e),{boxElement:n,contentElement:e}}const Ar="Arial, sans-serif";class Fu{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");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}=Bu(),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=vo({frameSize:i,baselineScale:r,visualTransform:s(o.entry),textStyle:fe(o.entry.clip.textStyle),contentText:Hn(o.entry),styleOverride:l});o.lastLayout=c,this.applyBoxLayout(o,c,l),this.applyContent(o,r,l)}}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)}applyBoxLayout(e,t,i){const r=fe(e.entry.clip.textStyle),s=(i==null?void 0:i.rotation)??r.rotation,{frameRect:a}=t;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=`${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=fe(e.entry.clip.textStyle),s=(i==null?void 0:i.fontSize)??r.fontSize,a=nu(s,r.paddingX,r.strokeWidth,t);e.contentElement.textContent=Hn(e.entry),e.contentElement.style.color=r.color,e.contentElement.style.fontFamily=this.getFontFamily(),e.contentElement.style.fontSize=`${a.fontSize}px`,e.contentElement.style.padding=`0 ${a.paddingX}px`,e.contentElement.style.textShadow=Ou(a.strokeWidth,r.strokeColor),e.boxElement.style.zIndex=String(2e3-e.entry.trackOrder)}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("${To(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 Hu=250,Gu=100;class Nu{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 wu);p(this,"runtimePublisher",new Iu);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);this.callbacks=e,this.dependencies=t,this.pendingOverlayRenderer=new gu(()=>{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;(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 Pu(i),this.textLayer=new Fu(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)},lastSyncedPlayState:()=>this.lastSyncedPlayState}),this.textLayer.setTextPreviewFont(t.textPreviewFont??null),this.sourceService=new Du({previewSourceResolver:t.previewSourceResolver,sourceMediaRegistry:t.sourceMediaRegistry,resourceCacheManager:t.resourceCacheManager,onDiagnostic:(r,s)=>this.emitDiagnostic("info","resource",r,{extra:s})}),this.syncCoordinator=new Eu({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:r=>this.sourceService.revokeObjectUrl(r),rememberObjectUrl:(r,s)=>{r.objectUrl&&r.objectUrl!==s&&this.sourceService.revokeObjectUrl(r.objectUrl),r.objectUrl=s??null},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||st(r.entry.clip)===a)})}hasPreview(){return!!this.container}attach(e){this.compositor.attach(e,{rootClassName:this.dependencies.rootClassName,frameClassName:this.dependencies.frameClassName}),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(o=>this.sourceService.revokeObjectUrl(o)),a.destroy(o=>this.sourceService.revokeObjectUrl(o));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=fu(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=>Fn(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=>jt(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)jt(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(mu(t,e.current.entry)){const i=yu(t);this.trackSlots.set(e.trackId,i),t=i}return this.syncCoordinator.applyTrackPlan(e)}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(l=>this.sourceService.revokeObjectUrl(l)),i.preload.destroy(l=>this.sourceService.revokeObjectUrl(l)),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 Bn(e,t,"current",r),preload:new Bn(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(!jt(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(!jt(l))continue;t+=1;const c=Fn(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||!bt(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=st(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 cs(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"?Ui(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=fe(e.clip.textStyle),{layoutHeight:a}=bs({frameSize:i,baselineScale:r,visualTransform:t,textStyle:s,contentText:e.clip.textContent||e.clip.name||"",styleOverride:this.getTextLayoutOverride(e)});return yo(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=>this.getEffectiveVisualTransform(e)}}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=>this.getEffectiveVisualTransform(e),this.getTextLayoutOptions()),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},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()},Hu))}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()},Gu))}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 zu extends Nu{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 $u(n){return"dom"}const Vu=36e5,Uu=3e5;function ss(n){return n.length===0?0:n.reduce((e,t)=>Math.max(e,t.startTime+t.duration),0)}function Gn(n){return ss(n)}function Nn(n){return Math.max(n+Uu,Vu)}class zn{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 Wu(n){return[...n].sort((e,t)=>e.order-t.order)}function Yu(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 Xu{resolveActiveClipsAtTime(e,t){return this.resolvePlaybackPlan(e,t).activeClips}resolvePlaybackPlan(e,t,i={}){const r=Wu(e),s=[],a=[];let o=null;for(const l of r){const c=Yu(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 qu{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 ju=1e3;class Ku{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??ju}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)),$n(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};$n(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 $n(n,e){return n.status===e.status&&n.isLoading===e.isLoading&&n.reason===e.reason}const Zu=["togglePlay","deleteSelectedClips","copySelectedClips","cutSelectedClips","pasteClipboardClips","toggleSelectedClipsAudio","splitCurrentClip","undo","redo"],Ju={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 Qu(){return typeof navigator>"u"?!1:/Mac|iPhone|iPad|iPod/i.test(navigator.platform)}function ep(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 tp(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=ep(c);if(!h||r)return null;r=h}}return r?{action:n,code:r,altKey:s,ctrlKey:a,metaKey:o,shiftKey:l}:null}function ip(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 rp(n,e){return n.code===e.code&&n.altKey===e.altKey&&n.ctrlKey===e.ctrlKey&&n.metaKey===e.metaKey&&n.shiftKey===e.shiftKey}function sp(n,e){return n===!1||(n==null?void 0:n.enabled)===!1?[]:Zu.flatMap(t=>{var s;const i=(s=n==null?void 0:n.bindings)==null?void 0:s[t];return(i===void 0?Ju[t]:Array.isArray(i)?i:[i]).map(a=>tp(t,a,e)).filter(a=>a!==null)})}class np{constructor(e){p(this,"callbacks");p(this,"bindings");p(this,"enabled");p(this,"keydownListener",e=>{this.handleKeydown(e)});var i;const t=e.isMacLike??Qu();e.root,this.callbacks=e.callbacks,this.bindings=sp(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(ip(e.target))return;const t=this.bindings.find(i=>rp(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 bo(n){var t;const e=n.getPrimarySelectedClip()||((t=n.findFallbackSelectedClip)==null?void 0:t.call(n))||null;return{clip:e,hasSelectedClip:!!e}}function ap(n){const e=bo(n),t=n.getSelectedClipIds(),i=n.getSelectedClipAudioAction();return{...e,selectedClipIds:t,canDeleteSelectedClips:t.length>0,canSplitSelectedClip:n.canSplitSelectedClip(),selectedClipAudioAction:i,canToggleSelectedClipsAudio:i!==null}}function op(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 lp{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 cp(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 hp(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=cp(n.trackCollection,e);return t?n.trackCollection.addClipToTrack(t,n.clip):!1}function Vn(n,e,t){return e.trackId?n.removeClipFromTrack(e.trackId,t):!1}function dp(n){return n.trackCollection.moveClipToTrack(n.command.clip,n.command.sourceTrackId,n.command.targetTrackId)}function Oi(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 ko{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 uo({container:e.container,theme:t,voiceCatalog:e.voiceCatalog,onClipUpdate:(i,r)=>{this.isInternalUpdate=!0,this.resolveUpdateTargets(i,r).forEach(a=>{e.updateClip(a.id,r)}),setTimeout(()=>{this.isInternalUpdate=!1},0)},onGenerateVoice:e.onGenerateVoice})}update(){if(!this.panel||!this.config)return;const e=this.config.getPrimarySelectedClip(),t=this.config.getSelectedClips();this.currentSelectionState=this.buildSelectionState(e,t),this.panel.setSelectionState(this.currentSelectionState)}updateFromExternal(){this.isInternalUpdate||this.update()}destroy(){this.panel&&(this.panel.destroy(),this.panel=null),this.config=null}setPreferredTab(e){var t;(t=this.panel)==null||t.setPreferredTab(e)}showVoiceGenerationLoading(){var e;(e=this.panel)==null||e.showVoiceGenerationLoading()}hideVoiceGenerationLoading(){var e;(e=this.panel)==null||e.hideVoiceGenerationLoading()}setVoiceGenerationBusy(e){var t;(t=this.panel)==null||t.setVoiceGenerationBusy(e)}buildSelectionState(e,t){const i=t.length>0?t:e?[e]:[],r=e??i[0]??null;if(!r||i.length===0)return{primaryClip:null,selectedClips:[],selectionCount:0,groupKind:"empty",supportsVoiceBatch:!1,supportsTextContentBatch:!1,supportsVisualBatch:!1,supportsVolumeBatch:!1};const a=new Set(i.map(c=>c.type)).size>1?"mixed":r.type,o=i.length>1,l=a==="audio"&&i.every(c=>Re(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=>Re(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 up{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 ho({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:Si,timeScaleHeight:e.timeScaleHeight||40,includeTimeScaleSpacer:e.includeTimeScaleSpacer},e.onRenameTrack,e.onRemoveTrack,e.onMuteTrack)}hasPanel(){return!!this.panel}update(e){var t;(t=this.panel)==null||t.setTracks(e)}setScrollTop(e){var t;(t=this.panel)==null||t.setScrollTop(e)}destroy(){var e;(e=this.panel)==null||e.destroy(),this.panel=null}}class Un{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 pp=100*1024*1024,gp=10*1024*1024*1024,fp=30*24*60*60*1e3,mp=["video/mp4","audio/aac","audio/mpeg","audio/mp4","audio/mp3","audio/ogg","audio/wav","audio/x-wav"],oi={enabled:!1,maxEntryBytes:pp,maxTotalBytes:gp,ttlMs:fp,preferStorage:"opfs",resolveMode:"prefer-fast-start",allowedMimeTypes:mp},yp="timeline-preview-resource-cache",Sp=1,Se="metadata";function Cp(){return new Promise((n,e)=>{const t=indexedDB.open(yp,Sp);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 vp{constructor(){p(this,"dbPromise",null)}getDb(){return this.dbPromise||(this.dbPromise=Cp().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 Tp="timeline-preview-resource-cache",bp="timeline-preview-resource-cache-blobs",kp=1,Ee="blobs";function wp(){return new Promise((n,e)=>{const t=indexedDB.open(bp,kp);t.onupgradeneeded=()=>{const i=t.result;i.objectStoreNames.contains(Ee)||i.createObjectStore(Ee)},t.onerror=()=>e(t.error),t.onsuccess=()=>n(t.result)})}function Mr(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=wp().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 Mr(r)}async delete(e){const i=(await this.getDb()).transaction(Ee,"readwrite");i.objectStore(Ee).delete(e),await Mr(i)}async clear(){const t=(await this.getDb()).transaction(Ee,"readwrite");t.objectStore(Ee).clear(),await Mr(t)}}class Pp{constructor(){p(this,"kind","opfs");p(this,"directoryPromise",null)}async getDirectory(){return this.directoryPromise||(this.directoryPromise=navigator.storage.getDirectory().then(e=>e.getDirectoryHandle(Tp,{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 _p(n){var e;if(n.preferStorage==="opfs"&&typeof navigator<"u"&&typeof((e=navigator.storage)==null?void 0:e.getDirectory)=="function"){const t=new Pp;if(await t.ensureReady())return t}return new xp}function Ap(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Wn(n){return n.split(";",1)[0].trim().toLowerCase()}async function Ip(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 Ap(new Uint8Array(t))}function Rr(n){return n?[...n]:[...oi.allowedMimeTypes]}function Ep(n){return n?n===!0?{...oi,enabled:!0,allowedMimeTypes:Rr(void 0)}:{...oi,...n,enabled:n.enabled??!0,allowedMimeTypes:Rr(n.allowedMimeTypes)}:{...oi,allowedMimeTypes:Rr(void 0)}}function Mp(n){try{const e=new URL(n);return e.hash="",e.toString()}catch{return n.trim()}}async function Rp(n){var t;const e=((t=n.sourceKey)==null?void 0:t.trim())||Mp(n.url);return Ip(e)}function Yn(n,e=oi.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=Wn(n.mimeType);return!e.some(r=>Wn(r)===i)}function Lp(n){return n&&n.split(";",1)[0].trim().toLowerCase()||null}function Xn(n){if(!n)return null;const e=Number(n);return Number.isSafeInteger(e)&&e>=0?e:null}function Dp(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 qn(n,e,t){return{url:e,ok:n.ok,status:n.status,mimeType:Lp(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 Op{async probe(e){var r;try{const s=await fetch(e,{method:"HEAD"}),a=Xn(s.headers.get("content-length"));if(s.ok&&a!==null)return qn(s,e,a)}catch{}const t=await fetch(e,{method:"GET",headers:{Range:"bytes=0-0"}}),i=Dp(t.headers.get("content-range"))??Xn(t.headers.get("content-length"));try{await((r=t.body)==null?void 0:r.cancel())}catch{}return qn(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 Bp={createObjectURL(n){return URL.createObjectURL(n)},revokeObjectURL(n){URL.revokeObjectURL(n)}};function ft(n,e){return{url:n.url,cacheStatus:e,sourceUrl:n.url}}function Fp(n,e){return n.etag||e.etag?n.etag===e.etag&&n.sizeBytes===e.contentLength:n.sizeBytes===e.contentLength&&n.lastModified===e.lastModified}class Hp{constructor(e={}){p(this,"options");p(this,"metadataStore");p(this,"storagePromise");p(this,"http");p(this,"objectUrl");p(this,"now");p(this,"cacheKeyBuilder");p(this,"onEvent");p(this,"objectUrls",new Set);p(this,"inflightDownloads",new Map);this.options=Ep(e.options),this.metadataStore=e.metadataStore??new vp,this.storagePromise=e.storage?Promise.resolve(e.storage):_p({preferStorage:this.options.preferStorage}),this.http=e.http??new Op,this.objectUrl=e.objectUrl??Bp,this.now=e.now??(()=>Date.now()),this.cacheKeyBuilder=e.cacheKeyBuilder??Rp,this.onEvent=e.onEvent}async resolve(e){return this.resolvePlayableUrl(e)}async resolvePlayableUrl(e){if(!this.options.enabled||Yn(e,this.options.allowedMimeTypes))return this.emitEvent("resource-cache.bypass",{sourceUrl:e.url}),ft(e,"bypass");try{const t=await this.cacheKeyBuilder(e),i=await this.storagePromise,r=await this.metadataStore.get(t);if(r){const l=await i.read(t);if(l){if(r.expiresAt>this.now()){const c={...r,lastAccessedAt:this.now()};return await this.metadataStore.put(c),this.emitEvent("resource-cache.hit",{sourceUrl:e.url,sizeBytes:c.sizeBytes}),this.blobResult(e.url,l,c,"hit")}return await this.resolveExpired(e,t,r,l,i)}await this.metadataStore.delete(t)}if(this.options.resolveMode==="prefer-fast-start")return this.probeAndDownload(t,e,i).catch(()=>{}),this.emitEvent("resource-cache.miss",{sourceUrl:e.url}),ft(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(e.url,a,o,"miss")}catch{return this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),ft(e,"fallback")}}revokeObjectUrl(e){this.objectUrls.delete(e)&&this.objectUrl.revokeObjectURL(e)}async cleanupExpired(){const e=await this.storagePromise,t=this.now(),i=await this.metadataStore.list();await Promise.all(i.filter(r=>r.expiresAt<=t).map(r=>this.deleteEntry(r.cacheKey,e)))}async clear(){const e=await this.storagePromise;await Promise.all([e.clear(),this.metadataStore.clear()]);for(const t of[...this.objectUrls])this.revokeObjectUrl(t)}async getStats(){const e=await this.metadataStore.list();return{entryCount:e.length,totalBytes:e.reduce((t,i)=>t+i.sizeBytes,0),maxTotalBytes:this.options.maxTotalBytes}}async resolveExpired(e,t,i,r,s){const a=await this.probeCacheable(e);if(a.cacheStatus!=="miss")return a.result;if(Fp(a.probe,i)){const c=this.now(),h={...i,updatedAt:c,lastAccessedAt:c,expiresAt:c+this.options.ttlMs};return await this.metadataStore.put(h),this.emitEvent("resource-cache.revalidate.success",{sourceUrl:e.url,sizeBytes:h.sizeBytes}),this.blobResult(e.url,r,h,"stale-revalidated")}this.emitEvent("resource-cache.revalidate.stale",{sourceUrl:e.url}),await this.deleteEntry(t,s);const{blob:o,metadata:l}=await this.getOrCreateDownload(t,e,a.probe,s);return this.blobResult(e.url,o,l,"miss")}async probeCacheable(e){const t=await this.http.probe(e.url);return t.ok?t.sizeBytes===null?(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:ft(e,"fallback")}):Yn({...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:ft(e,"bypass")}):{cacheStatus:"miss",probe:t}:(this.emitEvent("resource-cache.fallback",{sourceUrl:e.url}),{cacheStatus:"fallback",result:ft(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){await Promise.all([t.delete(e),this.metadataStore.delete(e)]),this.emitEvent("resource-cache.cleanup.deleted",{cacheKey:e})}blobResult(e,t,i,r){const s=this.objectUrl.createObjectURL(t);return this.objectUrls.add(s),{url:s,cacheStatus:r,sourceUrl:e,sizeBytes:i.sizeBytes,objectUrl:s}}emitEvent(e,t){var i;(i=this.onEvent)==null||i.call(this,e,t)}}function Gp(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(!Gp(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 jn{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 Np{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 zp(n){return n==="text"?"文本":n==="video"?"视频":"音频"}function Bi(n){return n==="text"?0:n==="video"?1:2}class wo{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||`${zp(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=>Bi(l.type)>Bi(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)=>Bi(c.type)<=Bi(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 $p{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 xo{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 Vp{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 Kn{constructor(e){p(this,"selectionStore");p(this,"playbackStore");p(this,"viewportStore");this.selectionStore=new xo,this.playbackStore=new $p({currentTime:e.currentTime,playState:e.playState,speed:e.speed}),this.viewportStore=new Vp({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 Up{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||Kt,zoom:i.zoom||Me.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-ue+this.scrollLeft,this.config.zoom)}timeToPixel(e){return U.timeToPixels(e,this.config.zoom)-this.scrollLeft+ue}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=he.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&&he.drawTimeTick(this.layer,u,0,this.timeScaleHeight,d.time,{timeTick:this.theme.timeTick,timeText:this.theme.timeText},d.type,this.timeScaleHeight)}}clampScrollLeft(e){const t=Math.max(0,U.timeToPixels(this.config.duration,this.config.zoom)-this.stage.width());return Math.max(0,Math.min(t,e))}}const q=class q{constructor(e,t,i,r,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(q.SVG_NS,"svg"),this.visualElement.setAttribute("class","timeline-manager-playhead-visual"),this.visualElement.setAttribute("width",`${q.VISUAL_WIDTH}`),this.visualElement.style.position="absolute",this.visualElement.style.top="0",this.visualElement.style.marginLeft=`${-14/2}px`,this.visualElement.style.pointerEvents="none",this.visualElement.style.overflow="visible",this.lineHitAreaElement=document.createElement("div"),this.lineHitAreaElement.className="timeline-manager-playhead-hit-area",this.lineHitAreaElement.style.position="absolute",this.lineHitAreaElement.style.top="0",this.lineHitAreaElement.style.width=`${q.LINE_HIT_WIDTH}px`,this.lineHitAreaElement.style.marginLeft=`${-12/2}px`,this.lineHitAreaElement.style.background="transparent",this.lineHitAreaElement.style.cursor="ew-resize",this.lineHitAreaElement.style.pointerEvents="auto",this.container.appendChild(this.visualElement),this.container.appendChild(this.lineHitAreaElement),this.lineHitAreaElement.addEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.addEventListener("click",this.handleHandleClick),this.render()}setCurrentTime(e){this.currentTime=Math.max(0,e),this.render()}setTime(e){this.setCurrentTime(e)}setZoom(e){this.zoom=e,this.render()}setScrollLeft(e){this.scrollLeft=Math.max(0,e),this.render()}setHeight(e){this.height=Math.max(0,e),this.render()}destroy(){this.lineHitAreaElement.removeEventListener("mousedown",this.handleMouseDown),this.lineHitAreaElement.removeEventListener("click",this.handleHandleClick),this.stopEdgeAutoScroll(),this.unbindGlobalPointerListeners(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=dr({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}))}unbindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners&&(ur({onPointerMove:this.handleGlobalPointerMove,onPointerEnd:this.handleGlobalPointerEnd,onVisibilityChange:this.handleVisibilityChange}),this.hasBoundGlobalPointerListeners=!1)}updateTimeFromClientX(e){const t=this.container.getBoundingClientRect(),i=e-t.left,r=U.pixelsToTime(i-ue+this.scrollLeft,this.zoom);this.onTimeChange(Math.max(0,r),"scrub")}updateEdgeAutoScrollState(e){if(!this.onHorizontalAutoScroll)return;const t=this.container.getBoundingClientRect(),i=e-t.left;if(this.calculateHorizontalAutoScrollVelocity(i,t.width)===0){this.stopEdgeAutoScroll();return}this.startEdgeAutoScroll()}calculateHorizontalAutoScrollVelocity(e,t){if(t<=0)return 0;const i=Math.min(q.AUTO_SCROLL_EDGE_THRESHOLD,t/2),r=q.AUTO_SCROLL_MAX_SPEED;if(e<=0)return-r;if(e>=t)return r;if(e<i){const 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+ue,t=e>=0&&e<=this.container.clientWidth,i=Math.max(q.HANDLE_HEIGHT+q.END_CAP_HEIGHT,this.height);this.visualElement.style.display=t?"block":"none",this.lineHitAreaElement.style.display=t?"block":"none",this.visualElement.style.left=`${e}px`,this.visualElement.style.height=`${i}px`,this.visualElement.setAttribute("height",`${i}`),this.visualElement.setAttribute("viewBox",`0 0 ${q.VISUAL_WIDTH} ${i}`),this.lineHitAreaElement.style.left=`${e}px`,this.lineHitAreaElement.style.height=`${i}px`,this.renderVisual(i)}renderVisual(e){const t=ks.grip,i=Math.max(q.HANDLE_HEIGHT,e-q.END_CAP_HEIGHT);this.visualElement.replaceChildren(this.createHandleShadowPath(),this.createHandleBadgePath(this.theme.playhead),...this.createGripLines(t),this.createMainLine(i),this.createEndCap(i))}createHandleShadowPath(){const e=document.createElementNS(q.SVG_NS,"path");return e.setAttribute("class","timeline-manager-playhead-shadow"),e.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),e.setAttribute("fill",ks.shadow),e.setAttribute("transform","translate(-0.5, 0.75)"),e}createHandleBadgePath(e){const t=document.createElementNS(q.SVG_NS,"path");return t.setAttribute("class","timeline-manager-playhead-badge"),t.setAttribute("d","M3.5 1 H10.5 C11.3 1 12 1.7 12 2.5 V8.5 C12 9 11.7 9.6 11.3 10 L7.8 14.3 C7.4 14.8 6.6 14.8 6.2 14.3 L2.7 10 C2.3 9.6 2 9 2 8.5 V2.5 C2 1.7 2.7 1 3.5 1 Z"),t.setAttribute("fill",e),t}createGripLines(e){return[4.5,7,9.5].map(t=>{const i=document.createElementNS(q.SVG_NS,"line");return i.setAttribute("class","timeline-manager-playhead-grip-line"),i.setAttribute("x1","5"),i.setAttribute("x2","9"),i.setAttribute("y1",`${t}`),i.setAttribute("y2",`${t}`),i.setAttribute("stroke",e),i.setAttribute("stroke-width","1.5"),i.setAttribute("stroke-linecap","round"),i})}createMainLine(e){const t=document.createElementNS(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-line"),t.setAttribute("x",`${(q.VISUAL_WIDTH-q.LINE_WIDTH)/2}`),t.setAttribute("y",`${q.HANDLE_LINE_START}`),t.setAttribute("width",`${q.LINE_WIDTH}`),t.setAttribute("height",`${Math.max(0,e-q.HANDLE_LINE_START+1)}`),t.setAttribute("rx","1"),t.setAttribute("fill",this.theme.playhead),t}createEndCap(e){const t=document.createElementNS(q.SVG_NS,"rect");return t.setAttribute("class","timeline-manager-playhead-end-cap"),t.setAttribute("x","3"),t.setAttribute("y",`${e}`),t.setAttribute("width",`${q.END_CAP_WIDTH}`),t.setAttribute("height",`${q.END_CAP_HEIGHT}`),t.setAttribute("rx","1.5"),t.setAttribute("fill","#ffffff"),t}};p(q,"SVG_NS","http://www.w3.org/2000/svg"),p(q,"VISUAL_WIDTH",14),p(q,"HANDLE_HEIGHT",16),p(q,"HANDLE_LINE_START",13),p(q,"LINE_WIDTH",1),p(q,"LINE_HIT_WIDTH",12),p(q,"END_CAP_WIDTH",8),p(q,"END_CAP_HEIGHT",1),p(q,"AUTO_SCROLL_EDGE_THRESHOLD",48),p(q,"AUTO_SCROLL_MAX_SPEED",18);let ns=q;class Zn{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=he.createRect(0,0,0,0,It.hitArea,"transparent",0),this.hitAreaRect.name("scrollbar-hit-area"),this.thumbRect=he.createRect(0,0,0,0,this.theme.scrollbarThumb||It.thumb,this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||It.border,1),this.thumbRect.name("scrollbar-thumb"),this.thumbRect.cornerRadius(999),this.layer.add(this.hitAreaRect),this.layer.add(this.thumbRect),this.stage.on("mousedown",this.handleStageMouseDown),this.stage.on("mouseup",this.handleStageMouseUp),this.stage.on("mouseenter",this.handleStageMouseEnter),this.stage.on("mousemove",this.handleStageMouseMove),this.stage.on("mouseleave",this.handleStageMouseLeave),this.render()}setViewportMetrics(e,t){this.viewportSize=Math.max(0,e),this.contentSize=Math.max(0,t),this.scrollOffset=this.clampScrollOffset(this.scrollOffset),this.render()}setScrollLeft(e){this.orientation==="horizontal"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}setScrollTop(e){this.orientation==="vertical"&&(this.scrollOffset=this.clampScrollOffset(e),this.render())}resize(){this.render()}destroy(){this.unbindGlobalPointerListeners(),this.container.style.cursor="default",this.stage.destroy(),this.container.innerHTML=""}bindGlobalPointerListeners(){this.hasBoundGlobalPointerListeners||(this.hasBoundGlobalPointerListeners=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||It.thumb),this.thumbRect.stroke(this.theme.scrollbarThumbBorder||this.theme.scrollbarBorder||It.border);const r=this.getAvailableTrackSize();if(r<=0||i){this.thumbRect.visible(!1),this.container.style.cursor="default",this.stage.batchDraw();return}const 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 Wp=48;function Yp(n,e,t){return U.timeToPixels(n,e)-t+ue}function Xp(n,e,t){const i=Math.max(0,t-e);return Math.max(0,Math.min(i,n))}function qp(n){const{time:e,zoom:t,scrollLeft:i,viewportWidth:r,contentWidth:s,margin:a=Wp}=n;if(r<=0||Math.max(0,s-r)<=0)return null;const l=Yp(e,t,i),c=r-a;if(l>=a&&l<=c)return null;const h=U.timeToPixels(e,t),d=l<a?h+ue-a:h+ue-c,u=Xp(d,r,s);return Math.abs(u-i)<=.5?null:u}class Jn{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 jp="@linker-design-plus/timeline-track",Kp="2.1.6",Nt={name:jp,version:Kp},Zp=1,Jp=2,Qp=250,eg=750,tg=1500;function Qn(n){return n==null?n:JSON.parse(JSON.stringify(n))}function ig(n,e){return n.length!==e.length?!1:n.every((t,i)=>t===e[i])}function rg(n){return n==="text"?"文本":n==="video"?"视频":"音频"}class sg{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 Jn);p(this,"pendingDraftData",null);p(this,"selectionStore",new xo);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||Kt,zoom:e.zoom||Me.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 ja(this.config.diagnostics),this.resourceCacheManager=this.config.resourceCache?new Hp({options:this.config.resourceCache,onEvent:(t,i)=>{this.emitDiagnostic({...this.buildPreviewDiagnosticsContext(),severity:t.endsWith(".failed")||t.endsWith(".fallback")?"warn":"info",category:"resource",eventName:t,message:t,extra:i})}}):null,this.diagnostics.startSession({packageName:Nt.name,packageVersion:Nt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.config.previewBackend}),this.thumbnailProvider=e.thumbnailProvider||null,this.trackInfoPanelController=new up,this.eventDispatcher=new zn({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 An(this.history),this.trackManager=new wo,this.timelineStore=new Kn({currentTime:this.config.currentTime,playState:this.config.playState,speed:this.config.speed||1,zoom:this.config.zoom,duration:this.config.duration}),this.timelineCommands=new Pn(this.timelineStore),this.timelinePresentationAdapter=new Un,this.timelineTrackBridge=new jn({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)||Me.MEDIUM,h=((s=this.config)==null?void 0:s.duration)||Kt;this.timelineStore=new Kn({currentTime:a,playState:o,speed:l,zoom:c,duration:h})}return this.timelineStore}getTimelineCommands(){return this.timelineCommands||(this.timelineCommands=new Pn(this.getTimelineStore())),this.timelineCommands}getTrackCollection(){return new Np(this.tracks)}getTimelinePresentationAdapter(){return this.timelinePresentationAdapter||(this.timelinePresentationAdapter=new Un),this.timelinePresentationAdapter}getTimelineTrackBridge(){return this.timelineTrackBridge||(this.timelineTrackBridge=new jn({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 Xu),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 Ku({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 qu({createBackendCallbacks:e=>this.createPreviewBackendCallbacks(e),createBackend:(e,t)=>new zu({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||$u(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)},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 zn({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 An(this.history)),this.timelineHistoryRecorder}withStructureSession(e){const t=this.activeStructureSession;if(t)return e(t);const i=new lp({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:Kt,zoom:Me.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=qp({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=yt(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<Qp}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)<=eg?(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(!ig(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=Id(e,{theme:this.config.theme,timeScaleHeight:this.getTimeScaleHeight(),leftPanelWidth:Si,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 Up(this.headerStage,this.headerLayer,this.config,this.handleTimeChange.bind(this),this.handleScrollChange.bind(this)),this.playhead=new ns(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 Zn({container:this.layout.horizontalScrollbarCanvasHost,orientation:"horizontal",theme:this.config.theme,leadingInset:ue,onScrollChange:this.handleScrollChange.bind(this)}),this.verticalScrollbar=new Zn({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 Gt(this.trackManager.getTracks(),e,this.getTrackContentTopOffset())}calculateTotalHeight(){return wn(this.trackManager.getTracks(),this.getTrackContentTopOffset())}updateAllTrackPositions(){var t,i;const e=Ld(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=he.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=Gt(r,c.id,this.getTrackContentTopOffset());return t==="before_track"?h:h+_e(c.type)}}if(t==="top_of_type_region"&&a)return Gt(r,a.id,this.getTrackContentTopOffset());if(t==="bottom_of_type_region"&&o)return Gt(r,o.id,this.getTrackContentTopOffset())+_e(o.type);if(!s)return e!=="audio"?this.getTrackContentTopOffset():wn(r,this.getTrackContentTopOffset());const l=Gt(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-ue+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=he.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=ge(this.snapGuideTime,this.getZoomState(),this.getScrollLeftState());this.snapGuideLine.points([i,0,i,this.calculateTotalHeight()]),this.snapGuideLine.visible(!0),this.snapGuideLine.getParent()&&this.snapGuideLine.moveToTop(),e&&((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===Zp)return e*16;if(t===Jp){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(Me.MIN,Math.min(Me.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()>=yt(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=yt(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-ue+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-ue);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?ss(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?sa: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=ls({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?Ui(e.visualTransform??lu(qi(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?{...fe(e.textStyle),anchorVersion:((C=e.textStyle)==null?void 0:C.anchorVersion)??1}: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),Vi({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=hp({clip:g,placement:v,trackCollection:S,createTrack:this.createTrack.bind(this)});Vi({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=>{Vi({applied:Vn(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=Vn(this.getTrackCollection(),a,s)||r)}})}),r?(Di({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),Oi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this),updateTrackInfoPanel:this.updateTrackInfoPanel.bind(this),cleanupEmptyTracks:this.cleanupEmptyTracks.bind(this)}),!0):!1}updateClip(e,t){if(this.getTimelineCommands().findClipById(this.tracks,e)){if(this.getTrackCollection().updateClip(e,t),Object.prototype.hasOwnProperty.call(t,"thumbnails")){const i=this.findClipById(e);i&&this.markClipThumbnailLoadCompleted(i)}Oi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitClip(e,t){const i=this.getTimelineCommands().findClipById(this.tracks,e);if((i==null?void 0:i.clip.type)==="text")return;const r=i==null?void 0:i.track.splitSelectedClip;if(r){const s=()=>{this.withSplitOperation(()=>{r.call(i.track,t)})};this.shouldNormalizePrimaryTrackForTrackIds([i.trackId])?this.withHistoryTransaction("split_primary_track_clip",s):s(),Oi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}splitCurrentClip(){const e=this.getCurrentTime(),t=this.resolveSelectedClipAtTime(e);if((t==null?void 0:t.clip.type)==="text")return;const i=t==null?void 0:t.track.splitSelectedClip;if(i){const r=()=>{this.withSplitOperation(()=>{i.call(t.track,e)})};this.shouldNormalizePrimaryTrackForTrackIds([t.trackId])?this.withHistoryTransaction("split_primary_track_clip",r):r(),Oi({checkTrackDurationChange:this.checkTrackDurationChange.bind(this),updateCanPlayState:this.updateCanPlayState.bind(this)})}}getClips(){return this.getTrackCollection().getAllClips()}syncTimelineClipMediaStateFromPreview(e){const t=this.getFailedPreviewClipIds(),i=new Set;e.slots.forEach(r=>{const 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;const e=this.getPreviewAspectRatio();let t=e.width,i=e.height;if(bt(e.mode)&&t===Le.width&&i===Le.height){const l=(s=this.getAutoAspectRatioClip())==null?void 0:s.clip,c=(a=l==null?void 0:l.style)==null?void 0:a.sys_width,h=(o=l==null?void 0:l.style)==null?void 0:o.sys_height;typeof c=="number"&&c>0&&typeof h=="number"&&h>0&&(t=c,i=h)}const r=qi({width:t,height:i});return{width:r.width,height:r.height,aspectRatio:`${r.width}:${r.height}`,mode:e.mode}}getExportCoverUrl(e){var r;let t=null,i=null;for(const 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.getResolvedTracksSnapshot().slice().sort((i,r)=>i.order-r.order).map(i=>{const r=i.clips.map(s=>({id:s.id,type:s.type,externalId:s.externalId,src:s.src,name:s.name,isMuted:s.isMuted??!1,startTime:Math.round(s.startTime),duration:Math.round(s.duration),endTime:Math.round(s.endTime),startTimeAtSource:Math.round(s.startTimeAtSource),endTimeAtSource:Math.round(s.endTimeAtSource),sourceDuration:Math.round(s.sourceDuration),thumbnails:s.thumbnails,visualTransform:s.type==="text"?Ui(s.visualTransform):s.type==="video"?xe(s.visualTransform):void 0,separatedAudioClipId:s.separatedAudioClipId,separatedFromVideoClipId:s.separatedFromVideoClipId,volume:s.volume??1,textContent:s.textContent,textStyle:s.textStyle,ttsSourceTextClipId:s.ttsSourceTextClipId,ttsVoiceId:s.ttsVoiceId,ttsVoiceName:s.ttsVoiceName,ttsFollowTextUpdates:s.ttsFollowTextUpdates})).sort((s,a)=>s.startTime-a.startTime);return{id:i.id,type:i.type,name:i.name||"未命名轨道",order:i.order,role:i.role??"normal",isMuted:i.isMuted??!1,clips:r}}),t=this.getExportCoverUrl(e);return{version:this.getVersion(),exportTime:Date.now(),coverUrl:t,composition:this.getExportComposition(),tracks:e}}async importTimeline(e){if(!e||!e.composition||!e.tracks){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,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 Nt.version}undo(){return this.history.undo()}redo(){return this.history.redo()}getHistoryState(){return this.history.getState()}fitZoom(){var l;const e=this.getClips();if(e.length===0)return;const t=Math.min(...e.map(c=>c.startTime)),r=(Math.max(...e.map(c=>c.endTime))-t)/1e3,s=((l=this.stage)==null?void 0:l.width())||0,a=s-ue*2;N.debugLazy("TimelineManager",()=>"适合缩放",()=>({duration:r,containerWidth:s,availableWidth:a}));const o=Math.min(a/r,Me.MAX);if(this.setZoom(o),this.timeline){const c=e.reduce((h,d)=>d.startTime<h.startTime?d:h);this.scrollToClip(c.id)}}removeClipGaps(){const e=this.getClips().map(t=>({...t}));this.getTrackCollection().removeClipGaps(),e.length>0&&this.getTimelineHistoryRecorder().recordRemoveGaps(e),this.checkTrackDurationChange()}handleTimeChange(e,t="seek"){var i;this.previewSyncInteractionMode=t,this.previewClockSeekAlignmentTargetTime=t==="seek"?this.clampPlaybackSeekTime(e):null,this.previewClockSeekAlignmentDeadlineMs=t==="seek"?Date.now()+tg: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;$d({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),reloadClipThumbnailsIfNeeded:()=>this.reloadClipThumbnailsIfNeeded(e,t),checkTrackDurationChange:this.checkTrackDurationChange.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)}),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}),Di({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)&&Di({notifySelectionChange:this.notifySelectionChange.bind(this),emitSelectionChangeEvent:this.emitSelectionChangeEvent.bind(this),emitSelectedClipChangeIfNeeded:this.emitSelectedClipChangeIfNeeded.bind(this),handleClipChange:this.handleClipChange.bind(this)})}reloadClipThumbnailsIfNeeded(e,t){Vd(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=Ud(e,t),r=this.canPlay;this.canPlay=Wd({currentCanPlay:this.canPlay,nextCanPlay:i,playState:this.getPlayStateState(),clipEndTime:yt(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})})},na)}async flushPendingVoiceLinkedTextRegeneration(){const e=this.pendingVoiceLinkedTextRegeneration;if(this.pendingVoiceLinkedTextRegeneration=null,!e)return;const t=this.findClipById(e.clipId),i=(t==null?void 0:t.type)==="text"?{...t,textContent:e.nextText}:null,r=e.nextText,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 M=T+D;if(_+=Math.abs(M-x.preferredTrackIndex),M<0||M>=a.length){w+=1;continue}if(this.doesClipGroupOverlapOnTrack(a[M].id,x.clips,o)){k=!1;break}}k&&(_+=w*.1,_+=Math.abs(T-h)*aa.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"||!Re(e))return[];const t=this.getSelectedClips();if(!(t.length>0&&t.every(s=>Re(s))))return[e];const r=t.filter(s=>Re(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"||!Re(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=>{qd({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:()=>Di({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=Yd(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 _n(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 _n(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=op({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=`${rg(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:Qn(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:Qn(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 ko,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:Nt.name,packageVersion:Nt.version,userAgent:typeof navigator<"u"?navigator.userAgent:null,href:typeof location<"u"?location.href:null,configuredPreviewBackend:this.getPreviewBackendType()})}setPreviewAspectRatio(e){var t;this.previewAspectRatio=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=dp({command:{...s,clip:u},trackCollection:this.getTrackCollection()}),S=this.getClips().find(T=>T.id===e)??null;return Xd({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,M)=>{this.getTimelineHistoryRecorder().recordMoveClipBetweenTracks(T,k,_,w,D,x,M,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 Gn(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 Jn),(e=this.keyboardShortcutsController)==null||e.destroy(),this.keyboardShortcutsController=new np({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:ws.fill,stroke:ws.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=ge(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=ge(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=ss(e),s=Gn(e);if(r!==t){this.lastTrackDuration=r;const o=Nn(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=yt(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=${Nn(r)}ms`)}resolveSelectedClipSnapshot(){return bo({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 ap({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"?Ui:xe,s=r(i.visualTransform),a=r(t);if(vs(s,a))return;const o={visualTransform:a};if(i.type==="text"){const l=fe(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=fe(i.textStyle);r.layoutWidth===t.layoutWidth&&r.layoutHeight===t.layoutHeight||this.updateClip(e,{textStyle:{...r,layoutWidth:t.layoutWidth,layoutHeight:t.layoutHeight,anchorVersion:1}})}commitPreviewTextFontSize(e,t){const i=this.getClips().find(a=>a.id===e);if(!i||i.type!=="text")return;const r=fe(i.textStyle),s=Math.max(li.MIN,Math.min(li.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=fe(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=as;exports.CLIP_LAYER=Io;exports.Clip=Ni;exports.ClipConfigPanel=uo;exports.DEFAULT_CLIP_VIEW_STATE=ra;exports.DEFAULT_PREVIEW_ASPECT_RATIO=Le;exports.DEFAULT_TEXT_CLIP_DURATION_MS=sa;exports.DEFAULT_TEXT_CLIP_STYLE=ta;exports.DEFAULT_TIMELINE_DURATION_MS=Kt;exports.DiagnosticsCenter=ja;exports.HistoryManager=ts;exports.MIN_CLIP_LINE_WIDTH=ci;exports.PREVIEW_ASPECT_RATIO_PRESETS=Ao;exports.SNAP_SCORING=aa;exports.TEXT_CLIP_FONT_SIZE_LIMITS=li;exports.TIMELINE_LEFT_PADDING=ue;exports.TIME_SCALE=Mo;exports.TRACK_HEIGHT=Fi;exports.TimeUtils=U;exports.TimelineClipConfigController=ko;exports.TimelineManager=sg;exports.Track=ir;exports.TrackInfoPanel=ho;exports.TrackManager=wo;exports.VOICE_LINKED_TEXT_REGEN_DEBOUNCE_MS=na;exports.ZOOM_ANIMATION=Eo;exports.ZOOM_GESTURE=Dr;exports.ZOOM_PRESETS=Me;exports.createClipViewState=oa;exports.createClipWithViewState=ls;exports.defaultDarkTheme=Yi;exports.devConsole=N;exports.isAudioOnlyTtsClipCandidate=ia;exports.isAutoPreviewAspectRatioMode=bt;exports.isTtsAudioClip=Re;exports.mergeDiagnosticRuntimeState=Th;exports.normalizePreviewAspectRatio=Ue;exports.normalizePreviewAspectRatioMode=os;exports.resolveAspectRatioBaselineDimensions=qi;exports.resolveTextClipStyle=fe;exports.resolveTheme=Xi;
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;