@vkontakte/videoplayer-interactive 1.0.39-dev.6edf3cda.0 → 1.0.39-dev.a77510fe.0

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/evergreen.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.39-dev.6edf3cda.0
3
- * Mon, 09 Jun 2025 10:20:24 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.39-dev.a77510fe.0
3
+ * Tue, 10 Jun 2025 05:38:44 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-39/doc/
5
5
  */
6
- var Me="1.0.39-dev.6edf3cda.0";import{Subject as Di,Subscription as Hi}from"@vkontakte/videoplayer-shared/evergreen";var Jt=class{constructor(t){this.layout=t}},yt=class extends Jt{constructor(t){super(t)}setContainerLayout(t){t.style.position="relative"}setControlLayout(t,e){t.style.position="absolute",t.style.width=`calc(var(--interactive-content-width) * (${e.width} + ${2e-4}))`,t.style.height=`calc(var(--interactive-content-height) * ${e.height})`,t.style.left=`calc(var(--interactive-content-width) * ${e.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,t.style.top=`calc(var(--interactive-content-height) * ${e.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}};function Pe(n){return"features"in n}var J=class{constructor(t,e){this.container=t,this.options=e,this.factories=new Map,this.controls=[],this.setControls()}featureIsEnabled(t){return this.options&&Pe(this.options)&&this.options.features[t]}addControlFactory(t,e){this.factories.set(t.trim().toLowerCase(),e),this.setControls()}removeControlFactory(t){this.factories.delete(t.trim().toLowerCase()),this.setControls()}setControls(){this.controls=this.chooseControls()}chooseControls(){return this.container.controls?.reduce((t,e)=>{let i=e.type.trim().toLowerCase(),r=this.factories.get(i);if(r){let o=r(e,this.options);if(o)return[...t,o]}return[...t]},[])||[]}};import{fromEvent as wt,once as $i}from"@vkontakte/videoplayer-shared/evergreen";var G=(n,t)=>Object.prototype.toString.call(n)===`[object ${t}]`,W=n=>G(n,"Object"),Ct=n=>G(n,"String"),gt=n=>G(n,"Array"),Et=n=>G(n,"Number"),Oe=n=>G(n,"Function"),Le=n=>G(n,"Boolean"),te=n=>Et(n)&&!isNaN(n);var X=n=>W(n)&&Object.keys(n).length===0,ee=n=>gt(n)&&!n.length;var rt=(n,t)=>Ct(n)&&(t?n.trim():n).length;function ot(n,t=1){let e="0",i="0",r="0";return n.length===4?(e="0x"+n[1]+n[1],i="0x"+n[2]+n[2],r="0x"+n[3]+n[3]):n.length===7&&(e="0x"+n[1]+n[2],i="0x"+n[3]+n[4],r="0x"+n[5]+n[6]),`rgba(${+e},${+i},${+r},${t})`}var Ne="interactive",w={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderWidthRawValue:"1px",roundCornersRawValue:"0",borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0,shadowColorLight:"#fff",shadowColorDark:"#000",shadowColorAlpha:.24},$e=(i=>(i.top="flex-start",i.bottom="flex-end",i.center="center",i))($e||{}),Fe=(i=>(i.start="flex-start",i.end="flex-end",i.center="center",i))(Fe||{}),Be=(i=>(i.start="left",i.end="right",i.center="center",i))(Be||{}),It=({target:n,props:t})=>{n.style.alignItems=(t?.gravityVertical&&$e[t.gravityVertical])??"center",n.style.justifyContent=(t?.gravityHorizontal&&Fe[t.gravityHorizontal])??"center",n.style.textAlign=(t?.alignment&&Be[t.alignment])??"center"},Tt=({target:n,props:t,fallback:e,dependsOn:i})=>{n.style.color=t?.text?.color??e.textColor,n.style.fontSize=`calc(${i.height} * ${t?.text?.size??e.textSize})`,n.textContent=t?.text?.value??e.textContent},xt=({target:n,props:t,fallback:e})=>{n.style.backgroundColor=ot(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},st=({target:n,props:t,fallback:e,dependsOn:i,useRawValues:r=!1})=>{let o=r?e.borderWidthRawValue:`calc(${i.height} * ${t?.shape?.border?.width??e.borderWidth})`,c=r?e.roundCornersRawValue:`calc(${i.height} * ${t?.shape?.roundCorners??e.roundCorners})`;n.style.borderWidth=o,n.style.borderStyle="solid",n.style.borderColor=ot(r?e.borderColor:t?.shape?.border?.color??e.borderColor,r?e.borderAlpha:t?.shape?.border?.alpha??e.borderAlpha),n.style.borderRadius=c},je=({target:n,isDark:t,baseDimension:e,fallback:i})=>{let c=ot(i.shadowColorLight,i.shadowColorAlpha),s=ot(i.shadowColorDark,i.shadowColorAlpha),a=`calc(${e} * ${.25})`,h=`calc(${e} * ${.11})`,d=`0px 0px ${a} ${h} ${t?s:c}`;n.style.boxShadow=d},tt=({target:n,layoutParams:t,fallback:e})=>{let i=t.angle??e.angle;i=i&&i*-1,n.style.transform=`rotate(${i}rad)`};import{fromEvent as oe,Subject as Oi,Subscription as Li,ValueSubject as Ni}from"@vkontakte/videoplayer-shared/evergreen";var ie="interactive-control-tap",et={common:ie,animation:`${ie}-animation`,visible:`${ie}-visible`};var Mi=60,At=class{constructor({controlRotateAngleRad:t,clickCancelCondition:e,circleDiameterPx:i=Mi,useDimensionsBasedSize:r=!1}){this.onElementClick=t=>{if(!t.target||!t.currentTarget||this.clickCancelCondition())return;let e=t.currentTarget.parentElement;if(!e)return;let i=e.getBoundingClientRect(),r={width:this.useDimensionsBasedSize?e.offsetWidth:this.circleDiameterPx,height:this.useDimensionsBasedSize?e.offsetHeight:this.circleDiameterPx},o=Math.min(r.width,r.height),c=i.left+i.width/2,s=i.top+i.height/2,a=t.clientX-c,h=t.clientY-s,d=Pi(a,h,this.controlRotateAngleRad);this.element.style.width=o+"px",this.element.style.left=d.x+i.width/2-o/2+"px",this.element.style.top=d.y+i.height/2-o/2+"px",this.element.classList.add(et.visible,et.animation)};this.onAnimationEnd=t=>{!t.target||!t.currentTarget||t.target===t.currentTarget&&this.element.classList.remove(et.visible,et.animation)};let o=document.createElement("div");o.classList.add(et.common),this.controlRotateAngleRad=t,this.element=o,this.clickCancelCondition=e,this.circleDiameterPx=i,this.useDimensionsBasedSize=r}};function Pi(n,t,e){return{x:n*Math.cos(e)-t*Math.sin(e),y:n*Math.sin(e)+t*Math.cos(e)}}var ne="int",K=(i=>(i.AREA=`${ne}_area`,i.TEXT=`${ne}_text`,i.BUTTON=`${ne}_bttn`,i))(K||{});function re(n){return"features"in n}var D="interactive-control",S={common:D,selected:`${D}-selected`,wrapper:`${D}-wrapper`,disabled:`${D}-disabled`,button:`${D}-button`,area:`${D}-area`,text:`${D}-text`,blinkAnim:`${D}-blink-anim`,blinkAnimButton:`${D}-blink-anim-button`,blinkAnimArea:`${D}-blink-anim-area`},_e=40;var P=class{constructor(t,e,...i){this.severity=t;this.category=e;this.data=i}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var z=class{constructor(t,e){this.control=t;this.options=e;this.container=null;this.controlElement=null;this.subscriptions=new Li;this.error$=new Oi;this.isInteracted$=new Ni(!1)}onError(t="",e){let i=new P(1,1,{message:t,error:e,details:{id:this.control.id}});this.error$.next(i)}addControlTap(t){if(this.featureIsEnabled("controlsTapPlace")&&this.container){let e=this.control.layoutParams.angle??w.angle;this.controlTap=new At({controlRotateAngleRad:e,clickCancelCondition:this.container.isManifestContainerDisabled,circleDiameterPx:this.isTouch()?_e:void 0}),this.subscriptions.add(oe(t,"click").subscribe(this.controlTap.onElementClick,i=>this.onError("Control click tap animation error",i))).add(oe(this.controlTap.element,"animationend").subscribe(this.controlTap.onAnimationEnd,i=>this.onError("Tap animationend error",i))),this.container.element.append(this.controlTap.element)}}createContainerElement(t){let e=document.createElement("div");e.classList.add(S.wrapper),t.setControlLayout(e,this.control.layoutParams);let i=(this.control.layoutParams.innerSizesDependOn??w.innerSizesDependOn)==="self"?{height:e.style.height,width:e.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"},r=()=>t.isContainerDisabled?.()??!1;this.container={element:e,dimensions:i,isManifestContainerDisabled:r}}createClickListener(t){return e=>{e.stopPropagation(),this.isInteracted$.next(!0),t()}}featureIsEnabled(t){return this.options&&re(this.options)&&this.options.features[t]}isTouch(){return this.options&&re(this.options)&&this.options.isTouch}setEvents(t){!this.container||!this.control.events||this.control.events.forEach(e=>{switch(e.type.trim().toLowerCase()){case"onclick":{if(!this.container)break;this.subscriptions.add(oe(this.container.element,"click").subscribe(this.createClickListener(()=>t({action:e.action,controlId:this.control.id,controlType:this.control.type})),r=>this.onError("Error happened on control interaction",r)));break}default:break}})}removeListeners(){this.subscriptions.unsubscribe()}};var le="interactive-blink-anim-reference",O={common:le,animation:`${le}-animation`,disabled:`${le}-disabled`},St=class{constructor(){this._RAFId=0;this._element=void 0}get element(){return this._element}create(){if(this._element)return;let t=document.createElement("div");t.classList.add(O.common,O.animation),this._element=t}restart(){this._element&&(this._element.classList.add(O.disabled),this.cleanupRAF(),this._RAFId=requestAnimationFrame(()=>{this._element&&(this._element.classList.remove(O.disabled),this.cleanupRAF())}))}cleanupRAF(){this._RAFId&&(cancelAnimationFrame(this._RAFId),this._RAFId=0)}destroy(){this.cleanupRAF(),this._element=void 0}};var ce="interactive-container",L={common:ce,hidden:`${ce}-hidden`,disabled:`${ce}-disabled`};var kt=(n,t)=>{if(n.type.trim().toLowerCase()==="area")return new pe(n,t)},pe=class extends z{constructor(t,e){super(t,e)}createView({parentElement:t,callbacks:e}){if(super.createContainerElement(e),!this.container)return;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.area),i.setAttribute("data-testid",K.AREA),xt({target:i,props:this.control.props,fallback:{...w,backgroundColor:"transparent"}}),tt({target:i,layoutParams:this.control.layoutParams,fallback:w}),this.addControlTap(i),this.container.element.append(i),t.append(this.container.element),this.controlElement=i,this.updateShadowStyles(),this.registerEvents()}registerEvents(){if(!this.featureIsEnabled("controlsExpectTimeBlinkAnimation"))return;let t=this.container?.element.parentElement;!t||!this.controlElement||(this.subscriptions.add(wt(this.controlElement,"mouseleave").subscribe(()=>{if(t.classList.contains(L.disabled))return;let e=t.parentElement;if(e){let i=e.querySelector(`.${O.common}`);i&&this.syncBlinkAnimation(i)}},e=>this.onError("Error happened in mouseleave callback",e))),this.subscriptions.add(wt(this.controlElement,"mouseenter").subscribe(()=>{t.classList.contains(L.disabled)||this.onBlinkHovering()},e=>this.onError("Error happened in mouseenter callback",e))).add(wt(this.controlElement,"mouseleave").subscribe(()=>{this.controlElement&&(this.controlElement.style.animation="")},e=>this.onError("Error happened in mouseleave callback",e))))}disable(){this.controlElement&&this.controlElement.classList.add(S.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(S.disabled)}getElement(){return this.controlElement}updateShadowStyles(t){if(!(!this.container||!this.controlElement))if(Le(t)){let e=Math.min(this.controlElement.offsetWidth,this.controlElement.offsetHeight)+"px";je({target:this.controlElement,props:this.control.props,fallback:w,isDark:t,baseDimension:e}),st({target:this.controlElement,props:this.control.props,fallback:{...w,borderColor:t?w.shadowColorDark:w.shadowColorLight,borderAlpha:1,borderWidthRawValue:"0.1px",roundCornersRawValue:`calc(${this.container.dimensions.height} * ${this.control.props?.shape?.roundCorners??w.roundCorners})`},dependsOn:this.container.dimensions,useRawValues:!0})}else st({target:this.controlElement,props:this.control.props,fallback:{...w,borderAlpha:0},dependsOn:this.container.dimensions})}toggleBlinkAnimation(t){this.controlElement?.classList.toggle(S.blinkAnim,t),this.controlElement?.classList.toggle(S.blinkAnimArea,t)}syncBlinkAnimation(t){this.controlElement&&(!this.controlElement.classList.contains(`${S.blinkAnimArea}`)||this.controlElement.classList.contains(S.selected)||this.controlElement.classList.contains(O.disabled)||(this.controlElement.classList.add(O.disabled),this.subscriptions.add(wt(t,"animationiteration").pipe($i()).subscribe(()=>{this.controlElement&&this.controlElement.classList.remove(O.disabled)},e=>this.onError("Error happened in animationiteration callback",e)))))}onBlinkHovering(){if(!this.controlElement||!this.controlElement.classList.contains(`${S.blinkAnimArea}`)||this.controlElement.classList.contains(S.selected))return;let t=window.getComputedStyle(this.controlElement),e=t.getPropertyValue("--interactive-area-hover-opacity").trim();this.controlElement.style.opacity=t.opacity,this.controlElement.style.animation="none",requestAnimationFrame(()=>{this.controlElement&&(this.controlElement.style.opacity=e)})}setShowTimeRange(){}updateFillAnimationDimensions(){}onProgress(){}onResize(){}};import{fromEvent as Ot,once as _i}from"@vkontakte/videoplayer-shared/evergreen";var Rt=n=>{let t=document.createElement("span");switch(n){case"Button":case"button":{let e=document.createElement("div"),i={overflow:"hidden",display:"flex",justifyContent:"center",alignItems:"center"};Object.assign(e.style,i),e.append(t);let r={display:"inline-block",whiteSpace:"pre",textOverflow:"ellipsis",maxWidth:"initial",maxHeight:"100%",wordBreak:"normal"};return Object.assign(t.style,r),e}default:{let e={display:"inline-block",whiteSpace:"break-spaces",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",maxHeight:"100%",wordBreak:"break-all"};return Object.assign(t.style,e),t}}};var Vt=Math.PI,he=2*Vt,Mt=Vt/2,De=3*Mt,Fi=0,Bi=[Fi,Mt,Vt,De];function He(n){return n===Mt}function Ue(n){return n===Vt}function Ge(n){return n===De}function We(n){return(n%he+he)%he}function ji(n){for(let t of Bi)if(n===t)return t}function ze(n){if(ji(n))return null;let e=Math.floor(n/Mt)+1;return[1,2,3,4][e-1]}function Qe(n){return n*180/Math.PI}var U="interactive-control-fill-animation",N={common:U,fillerWrapper:`${U}-filler-wrapper`,filler:`${U}-filler`,fillHeight:`${U}-fill-height`,fillWidth:`${U}-fill-width`,fromTop:`${U}-from-top`,fromBottom:`${U}-from-bottom`,fromLeft:`${U}-from-left`,fromRight:`${U}-from-right`};var Pt=class n{constructor(t){this.widthExpansionCoef=0;let e=document.createElement("div");e.classList.add(N.common);let i=document.createElement("div");i.classList.add(N.fillerWrapper);let r=document.createElement("div");r.classList.add(N.filler),i.append(r),e.append(i);let o=We(t.rotateAngle),c=ze(o),s=c!==null,h=c===2||!s&&Ue(o)||c===3,d=!s&&He(o),v=!s&&Ge(o),y=!h&&!d&&!v,u=d||v,R=s&&!u,I=R?o:0;e.style.borderRadius=t.borderRadius,i.style.transform=`skew(${I*-1}rad)`,u?(r.classList.add(N.fillHeight,d?N.fromTop:N.fromBottom),i.classList.add(N.fillHeight,d?N.fromTop:N.fromBottom)):(r.classList.add(N.fillWidth,y?N.fromLeft:N.fromRight),i.classList.add(N.fillWidth)),t.debug&&console.log(`[interactive ${n.name}]`,{widthExpansionCoef:this.widthExpansionCoef,opts:t,shouldFillHeight:u,rotateAngleRad:o,rotateAngelDeg:Qe(o),rotateAngleRaw:t.rotateAngle,fromRight:h,fromTop:d,fromBottom:v,fromLeft:y}),this.useSkew=R,this.fromLeft=y,this.rotateAngle=o,this.fillAnimationElement=e,this.fillAnimationFillerElement=r,this.fillAnimationFillerWrapperElement=i,this.startTime=t.startTime,this.endTime=t.endTime,this.shouldFillHeight=u,this.isDebug=t.debug??!1}updateDimension(t){this.fillAnimationElement.style.top=`${t.borderWidth*-1}px`,this.fillAnimationElement.style.left=`${t.borderWidth*-1}px`,this.fillAnimationElement.style.width=`${t.width}px`,this.fillAnimationElement.style.height=`${t.height}px`;let e=this.calcWidthExpansionCoef({rotateAngle:this.rotateAngle,isSkewed:this.useSkew,initWidth:t.width,initHeight:t.height});!this.shouldFillHeight&&(this.fillAnimationFillerWrapperElement.style.width=100*e+100+"%",this.fillAnimationFillerWrapperElement.style[`${this.fromLeft?"left":"right"}`]=`calc((${e} * 100%) / 2 * -1)`),this.widthExpansionCoef=e}updateAnimation(t){if((o=>o<this.startTime||o>this.endTime)(t))return;let i=this.endTime-this.startTime,r=Math.min(Math.max((t-this.startTime)/i,0),1);this.shouldFillHeight?this.fillAnimationFillerElement.style.transform=`scaleY(${r})`:this.fillAnimationFillerElement.style.transform=`scaleX(${r})`}calcWidthExpansionCoef({rotateAngle:t,isSkewed:e=!1,initWidth:i,initHeight:r}){return e?(i+r*Math.abs(Math.tan(t)))/i-1:0}};var Lt=(n,t)=>{if(n.type.trim().toLowerCase()==="button")return new me(n,t)},me=class extends z{constructor(t,e){super(t,e)}createView({parentElement:t,callbacks:e}){if(super.createContainerElement(e),!this.container)return;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.button),i.setAttribute("data-testid",K.BUTTON),tt({target:i,layoutParams:this.control.layoutParams,fallback:w}),xt({target:i,props:this.control.props,fallback:w}),st({target:i,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),It({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=Rt(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;Tt({target:o,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),this.addControlTap(i),this.startTime!==void 0&&this.endTime!==void 0&&this.featureIsEnabled("controlsFillAnimation")&&(this.controlFillAnimation=new Pt({startTime:this.startTime,endTime:this.endTime,rotateAngle:this.control.layoutParams.angle??w.angle,borderRadius:i.style.borderRadius})),i.append(r,this.controlFillAnimation?.fillAnimationElement??""),this.container.element.append(this.controlTap?.element??"",i),t.append(this.container.element),this.controlElement=i,this.registerEvents()}registerEvents(){if(!this.featureIsEnabled("controlsExpectTimeBlinkAnimation"))return;let t=this.container?.element.parentElement;!t||!this.controlElement||(this.subscriptions.add(Ot(this.controlElement,"mouseleave").subscribe(()=>{if(t.classList.contains(L.disabled))return;let e=t.parentElement;if(e){let i=e.querySelector(`.${O.common}`);i&&this.syncBlinkAnimation(i)}},e=>this.onError("Error happened in mouseleave callback",e))),this.subscriptions.add(Ot(this.controlElement,"mouseenter").subscribe(()=>{t.classList.contains(L.disabled)||this.onBlinkHovering()},e=>this.onError("Error happened in mouseenter callback",e))).add(Ot(this.controlElement,"mouseleave").subscribe(()=>{this.controlElement&&(this.controlElement.style.animation="")},e=>this.onError("Error happened in mouseleave callback",e))))}disable(){this.controlElement&&this.controlElement.classList.add(S.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(S.disabled)}getElement(){return this.controlElement}toggleBlinkAnimation(t){this.controlElement?.classList.toggle(S.blinkAnim,t),this.controlElement?.classList.toggle(S.blinkAnimButton,t)}syncBlinkAnimation(t){this.controlElement&&(!this.controlElement.classList.contains(`${S.blinkAnimButton}`)||this.controlElement.classList.contains(S.selected)||this.controlElement.classList.contains(O.disabled)||(this.controlElement.classList.add(O.disabled),this.subscriptions.add(Ot(t,"animationiteration").pipe(_i()).subscribe(()=>{this.controlElement&&this.controlElement.classList.remove(O.disabled)},e=>this.onError("Error happened in animationiteration callback",e)))))}onBlinkHovering(){if(!this.controlElement||!this.controlElement.classList.contains(`${S.blinkAnimButton}`)||this.controlElement.classList.contains(S.selected))return;let t=window.getComputedStyle(this.controlElement),e=t.getPropertyValue("--interactive-button-hover-opacity").trim();this.controlElement.style.opacity=t.opacity,this.controlElement.style.animation="none",requestAnimationFrame(()=>{this.controlElement&&(this.controlElement.style.opacity=e)})}updateFillAnimationDimensions(){if(!this.container||!this.controlElement||!this.controlFillAnimation)return;let t=getComputedStyle(this.controlElement),e={width:parseFloat(t.width),height:parseFloat(t.height),borderWidth:parseFloat(t.borderWidth)||0};this.controlFillAnimation.updateDimension(e)}setShowTimeRange(t,e){this.startTime=t,this.endTime=e}onProgress(t){this.controlFillAnimation?.updateAnimation(t)}onResize(){this.updateFillAnimationDimensions()}updateShadowStyles(){}};var Xe=(n,t)=>{if(n.type.trim().toLowerCase()==="text")return new de(n,t)},de=class extends z{constructor(t,e){super(t,e)}createView({parentElement:t,callbacks:e}){if(super.createContainerElement(e),!this.container)return;let i=document.createElement("div");i.classList.add(S.common,S.text),i.setAttribute("data-testid",K.TEXT),tt({target:i,layoutParams:this.control.layoutParams,fallback:w}),It({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=Rt(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;Tt({target:o,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),i.append(r),this.container.element.append(i),t.append(this.container.element),this.controlElement=i}getElement(){return this.controlElement}disable(){}enable(){}onProgress(){}onResize(){}updateShadowStyles(){}toggleBlinkAnimation(){}setShowTimeRange(){}updateFillAnimationDimensions(){}onError(){}};var Nt=(n,t,e)=>{if(n.type.trim().toLowerCase()==="choice")return new ue(n,t,e)},ue=class extends J{constructor(e,i,r){super(e,r);this.containerElement=null;this.controlSubscriptions=new Hi;this.error$=new Di;this.rootElement=i,this.layout=new yt(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Lt),this.addControlFactory("text",Xe),this.addControlFactory("area",kt)}createView({eventCallback:e,videoDurationMs:i}){let r=document.createElement("div");return r.classList.add(L.common,L.disabled),requestAnimationFrame(()=>{r.classList.remove(L.disabled)}),this.layout.setContainerLayout(r),this.controls.forEach(o=>{o.setShowTimeRange(this.container.startTime,this.container.endTime??i),o.createView({parentElement:r,callbacks:{setControlLayout:this.layout.setControlLayout,isContainerDisabled:()=>this.isDisabled}}),o.setEvents(e),this.controlSubscriptions.add(o.error$.subscribe(this.error$))}),this.rootElement.append(r),this.isRemoved=!1,this.containerElement=r,this.updateControlsFillAnimationDimensions(),r}updateControlsFillAnimationDimensions(){for(let e of this.controls)e.updateFillAnimationDimensions()}hide(){let e=this.getElement();e&&e.classList.add(L.hidden)}show(){let e=this.getElement();e&&e.classList.remove(L.hidden)}enable(){let e=this.getElement();e&&(e.classList.remove(L.disabled),this.controls.forEach(i=>i.enable()),this.isDisabled=!1)}disable(){let e=this.getElement();e&&(e.classList.add(L.disabled),this.controls.forEach(i=>i.disable()),this.isDisabled=!0)}removeView(){let e=this.getElement();e&&(this.controlSubscriptions.unsubscribe(),this.controls.forEach(i=>i.removeListeners()),e.remove(),this.isRemoved=!0,this.containerElement=null)}fakeRemove(){this.isRemoved||(this.isRemoved=!0)}getElement(){return this.containerElement}onProgress(e,i){i&&this.controls.forEach(r=>{r.onProgress(e)})}onResize(e){e&&this.controls.forEach(i=>{i.onResize()})}updateControlsShadowStyles(e){this.controls.forEach(i=>i.updateShadowStyles(e))}toggleBlinkAnimation(e){this.controls.forEach(i=>i.toggleBlinkAnimation(e))}};import{combine as fn,InterfaceLanguage as bn,Observable as wi,once as vn,Subject as $,Subscription as ke,ValueSubject as j,fromEvent as ki}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as bt}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as Ui}from"@vkontakte/videoplayer-shared/evergreen";function at(n,t){let e;return(...i)=>{clearTimeout(e),e=setTimeout(()=>n(...i),t)}}var Ke="video_interactive",Ze="videoint";var qe=250,lt=class{constructor(t){this.handleZoomChange=at(t=>{this.lastZoomInfo=t},qe);this.onResize=t=>{if(!this.isReady||this.isHidden||!t[0].contentRect.width||!t[0].contentRect.height)return;let e=this.getNextPoint();e&&this.ngEditor?.zoomTo(e,void 0,{isFromCenter:!0}),this.ngEditorSize={width:t[0].contentRect.width,height:t[0].contentRect.height}};this.handleChapterChange=t=>{if(this.manifest){if(this.isHidden||this.hide(),!t?.id){this.onError?.("Chapter id is not found");return}this.visitedChapterIds.add(t.id),this.ngEditor?.selectChapter(t.id),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=t.id,this.lastZoomInfo=null}};this.handleManifestChange=(t,e=[])=>{if(this.isReady=!1,!Et(t.graph.edit.chapters[0].x)){this.onError?.("Can't show graph");return}this.lastZoomInfo=null,this.manifest=t,this.visitedChapterIds=new Set(e),this.ngEditor&&(this.manifest.metadata.id!==this.currentManifestId?(this.ngEditor.update(t),this.currentManifestId=this.manifest.metadata.id):this.ngEditor.setVisitedChapters(Array.from(e)),this.isReady=!0)};this.init(t)}init({root:t,onOpenPreviewClick:e,onError:i,lang:r,visitedChapters:o=[]}){this.isReady=!1,this.isHidden=!0,this.manifest=null,this.visitedChapterIds=new Set(o),this.onOpenPreviewClick=e,this.onError=i,this.lang=r??"ru",this.zoom=.7,this.lastZoomInfo=null,this.currentManifestId=null,this.currentChapterId=null,this.ngEditor=null,this.ngEditorSize=null,this.graphWrapperElement=Gi(t),this.resizeObserver=new ResizeObserver(at(this.onResize,qe)),this.resizeObserver.observe(this.graphWrapperElement)}getNextPoint(t=this.ngEditorSize){return!this.lastZoomInfo||!t?null:[(this.lastZoomInfo.x-t.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-t.height/2)/this.lastZoomInfo.value*-1]}setVisitedChapters(t){this.visitedChapterIds=new Set([...this.visitedChapterIds,...t]),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(t){this.ngEditor?.updateVideosInfo(t)}async show(){this.manifest&&(this.ngEditor||await this.initNgEditor(),this.graphWrapperElement.style.display="block",!this.lastZoomInfo&&this.currentChapterId&&this.ngEditor?.focusChapter(this.currentChapterId),this.isHidden=!1)}async initNgEditor(){if(!this.manifest)return;let t;try{t=await Ui(this.lang,Ke,Ze)}catch{this.onError?.("Unable to load graph language pack")}let{GraphEditor:e}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new e(this.graphWrapperElement,{mode:"view",lang:this.lang==="ru"?"ru":"en",translation:t}),this.currentManifestId=this.manifest.metadata.id,this.ngEditor.update(this.manifest),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId&&this.ngEditor.selectChapter(this.currentChapterId),this.ngEditor.on("control",({name:i,...r})=>{i==="openPreview"&&"chapterId"in r&&this.onOpenPreviewClick?.(r.chapterId)}),this.ngEditor.on("zoom",this.handleZoomChange),this.isReady=!0}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.manifest=null,this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}};function Gi(n){let t=document.createElement("div");return t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.height="100%",t.style.width="100%",t.style.display="none",n.append(t),t}var ct=class{constructor(){this._containers=[];this._player=null;this.setPlayer=t=>{this._player=t};this.setContainers=t=>{this._containers=t};this.deleteContainer=t=>{this._containers=this._containers.filter(e=>e.id!==t)};this.getNextInteractiveTime=(t=3e3)=>{if(!this._containers.length||this._player===null)return null;let e=-1,i=!1,r=Math.round(this._player.info.position$.getValue()*1e3);for(let o of this._containers){let c=o.startTime-t;if(c<=r&&(o.endTime&&r<=o.endTime||o.endTime===null)){i=!0;break}r<c&&(e=e===-1?c:Math.min(e,c))}return!i&&e!==-1?e:null}}};import{isSupportedManifest as Ft,ContainerTypes as go,ControlTypes as Bt,EventActionTypes as x,EventTypes as Eo,migrateManifestToLatestVersion as ei,compareVersions as Io}from"@interactiveplatform/movika-manifest";var Ye={metadata:"Object",chapters:"Array"},Je=n=>{if(!W(n))return!1;for(let t in Ye)if(!n[t]||!G(n[t],Ye[t]))return!1;return Ft(n.metadata.version)},$t=n=>n.type===Bt.Text,ho=n=>n.type===Bt.Button,mo=n=>n.type===Bt.Area,uo={Choice:"Choice",TextInput:"TextInput"},fo={Button:"Button",Area:"Area",Text:"Text"},bo={onClick:"onClick",onSuspense:"onSuspense"},ti={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var jt=class{constructor(){this.listeners={}}addListener(t,e){return this.listeners[t]=this.listeners[t]||[],this.listeners[t].push(e),this}on(t,e){return this.addListener(t,e)}once(t,e){this.listeners[t]=this.listeners[t]||[];let i=()=>{e(),this.off(t,i)};return this.listeners[t].push(i),this}off(t,e){return this.removeListener(t,e)}reset(){this.listeners={}}removeListener(t,e){let i=this.listeners[t]||[];for(let r=i.length;r>0;r--)if(i[r]===e){i.splice(r,1);break}return this}emit(t,...e){let i=this.listeners[t];return i?(i.forEach(r=>{r(...e)}),!0):!1}listenerCount(t){return this.rawListeners(t).length}rawListeners(t){return this.listeners[t]||[]}};var _t=class{constructor(t){this.fns=[];this.addFn=(t,e=!1)=>{Oe(t)&&(this.fns.push(t),e&&this.updateFn())};this.removeFn=(t,e=!1)=>{this.fns=this.fns.filter(i=>i!==t),e&&this.updateFn()};this.updateFn=()=>{this.fn=()=>{this.fns.forEach(t=>t()),this.raf&&this.forceRequestAnimation()}};this.forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};this.requestAnimation=()=>{this.raf||this.forceRequestAnimation()};this.cancelAnimation=()=>{this.raf&&(cancelAnimationFrame(this.raf),this.raf=void 0)};t&&(this.fn=t,this.addFn(t))}release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}};import{ValueSubject as qi}from"@vkontakte/videoplayer-shared/evergreen";var Dt=class{constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return Wi(...this.loaders[t])(e)}};function Wi(...n){return async function(e){let i=[...n];for(;i.length>0;)e=await i.shift()(e);return e}}function pt(n,t,e){return n?{...n,[t]:n[t]?[e,...n[t]]:[e]}:{[t]:[e]}}function Ht({actions:n,errors:t,chapterId:e,...i}){if(e){let r=n.getManifest();if(r){let o=n.getChapter(r.chapters,e);if(o){let c=n.getMedia(r.media,o.videoId),s=n.getGraph(r.graph,o.id);return c?{...i,actions:n,errors:t,result:{chapter:o,media:c,graph:s}}:{...i,errors:pt(t,Ht.name,"Could not find media"),actions:n}}}}return{...i,errors:pt(t,Ht.name,"Could not find chapter"),actions:n}}var fe=(n="",t="")=>{let e=n.split("."),i=t.split("."),r=0;for(let o=0;o<Math.max(e.length,i.length)&&!r;o++)e[o]>i[o]?r=1:e[o]<i[o]?r=-1:r=0;return r};var zi=async n=>{try{let t={},e;if(Ct(n)){e=new URL(n).href;let r=await fetch(e);if(!r.ok)return{};t=await r.json()}else if(W(n))t=n;else return{};if(!Je(t))return{};let i=t.metadata.media;if(Ct(i)&&!("media"in t))try{let r;e?r=new URL(i,e).href:(r=new URL(i).href,e=r);let o=await fetch(r);if(!o.ok)throw new Error;t.metadata.media=await o.json()}catch{return Ki(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function ii(n){let{manifest:t,manifestURL:e}=await zi(n);if(!t)throw new Error("Failed on fetch");let i=ei(t);return i.media=Qi(i.media,e),delete i.metadata.media,i}function Ut(n,t){if(t)return n.find(e=>e.id===t)}function be(n,t){return n.edit?.chapters?n.edit.chapters.find(e=>e.id===t):n.view?.chapters?n.view.chapters.find(e=>e.id===t):void 0}function ve(n,t){return n.videos.find(e=>e.id===t)}function Qi(n,t){return{...n,videos:n.videos.map(e=>({...e,variants:e.variants.map(i=>{let r="url"in i?i.url:"",o=Xi(r,t);return{...i,url:o||r}})}))}}function Xi(n="",t){try{return new URL(n,t).href}catch{return""}}function Ki(n){return fe(n,"3.2.0")>=0}var Gt=n=>gt(n)&&!ee(n),H=n=>n.order==="end",Wt=n=>gt(n.containers)&&!ee(n.containers)&&H(n),ni=(n,t)=>{let e=n*1e3;return Gt(t.controls)&&e<(t.startTime??0)},ye=(n,t)=>{let e=n*1e3;return Gt(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)};var Z=(n=[])=>n.some(t=>t.action.type==="expect"),Ce=(n=[])=>n.find(t=>t.action.type==="expect"),Zi=n=>n?.length===1,it=n=>Zi(n)&&$t(n[0]);function ri(n=[],t=1/0,e=[]){return n.filter(({container:i})=>!e.includes(i.container.id)&&Z(i.container.events)&&i.container.endTime===t&&!i.isRemoved)}function zt({gameControllers:n=[],subjectName:t,subjectId:e,execFn:i}){for(let r of n)if(t==="container"&&r.container.container.id===e){i(r),ri(n,r.container.container.endTime,[r.container.container.id]).forEach(c=>{i(c)});break}}var oi=(n,t)=>{let e=I=>t.find(({container:p})=>p.container.id===I)?.container.isRemoved,i=Z(n.events)&&!e(n.id),r=(I,C=!1,p=!1)=>{let l=p?"every":"some";return I.controls[l](m=>{let f=C?I.endTime===n.endTime:!0;return m.events?.[l](b=>b.action?.type===ti.openURI)&&f})},o=I=>I.some(({container:C})=>r(C.container,!0,!1)&&!C.isRemoved),c=I=>I.every(({container:C})=>C.isRemoved?!0:r(C.container,!0,!0)),s=ri(t,n.endTime,[n.id]).length,a=I=>I.controls.some(C=>C.events?.some(p=>p.action?.args?.shouldOpenNow)),h=i||s>0,d=o(t),v=r(n),y=c(t),u=i?!1:s>0,R=a(n);return{isExpectTime:h,hasOtherExpect:s>0,hasOpenURIEvent:d,hasOpenURIEventInCurrentContainer:v,isAllOpenURIEventsValid:y,isExpectEventForCurrentContainer:u,hasShouldOpenNowEvent:R}};var nt=class extends Dt{constructor(e,i){super(e);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new qi(null);this.onError=i,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(e){this.release();let i=await this.exec("manifestLoaders",{actions:{addErrorMessage:pt},result:null,errors:null,source:e});return i.errors&&this.errorHandler(i.errors),this.manifest=await ii(i.result??e),this}async setInitial(){return this.setNext()}async setNext(e=this.manifest?.metadata.initChapterId){if(!e)return this;this.prevChapter$.next(this.chapter);let i=await this.exec("chapterLoaders",Ht({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:be,getChapter:Ut,getMedia:ve,getByBranches:this.getByBranches.bind(this),addErrorMessage:pt},result:null,errors:null,chapterId:e}));return i.errors&&this.errorHandler(i.errors),i.result&&(this.chapter=i.result.chapter,this.media=i.result.media,this.graph=i.result.graph),this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest?.metadata.initChapterId)||null}getByChapterId(e=this.manifest?.metadata.initChapterId){if(!e||!this.manifest)return null;let i=Ut(this.manifest.chapters,e);if(i){let r=ve(this.manifest.media,i.videoId),o=be(this.manifest.graph,i.id);if(r)return{chapter:i,media:r,graph:o}}return null}getBranches(e=this.chapter?.id){if(e===this.chapter?.id)return this.getByBranches(this.chapter?.branches);{let i=Ut(this.manifest?.chapters||[],e);return this.getByBranches(i?.branches)}}getByBranches(e=[]){return e.reduce((i,r)=>{let o=this.getByChapterId(r.chapterId);return o&&i.push(o),i},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter?.id===this.manifest?.metadata.initChapterId}isEndChapter(){return this.chapter?H(this.chapter):!1}};import{Player as Yi}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as Ie,Tracer as Ji,ValueSubject as tn}from"@vkontakte/videoplayer-shared/evergreen";var si=n=>{let t=n.variants.find(e=>e.payload?.type==="vk");if(t&&t.payload){let[e,i]=t.payload.id.split("_");return[e,i]}return[]};function ge(){let n=new Map;function t({listId:o=Math.random().toString(),itemId:c=Math.random().toString(),...s}){let a=n.get(o),h={...s};return a?a[c]=h:n.set(o,{[c]:h}),{listId:o,itemId:c,...s}}function e(o){o.player.destroy(),o.container.remove(),o.subscription.unsubscribe(),o.statistics?.oneStat.destroy(),o.statistics?.statSubscription.unsubscribe()}function i(o,c){let s=n.get(o);if(!s)throw Error("Can't remove. Not find.");if(c){let a=s[c];a&&e(a),delete s[c],Object.keys(s).length||n.delete(o)}else{for(let a of Object.values(s))e(a);n.delete(o)}}function r(){for(let o of n)i(o[0])}return{createPlayer:t,removePlayer:i,map:n,removeAll:r}}function Ee(n,t=[]){let e={},i,r=!t.length;for(let o of n.variants)if(!i&&"cover"in o&&(i=o.cover),"url"in o)switch(o.type.toLowerCase()){case"mp4":(r||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[o.standard??"Invariant quality"]:o.url});break;case"mpeg":(r||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[o.standard??"Invariant quality"]:o.url});break;case"hls":(r||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:o.url}});break;case"dash":(r||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:o.url}});break;default:break}return{sources:e,thumbUrl:i,title:n.title??""}}var ht=(n,t)=>{let e=n.info.currentQuality$.getValue(),i=n.info.availableQualities$.getValue();e!==t&&i.includes(t)&&(n.setQuality(t),n.setAutoQuality(!1))};var en=2;function Te(n){let t=ge(),e=new Ie,i={},r=null,o=!1,c,s=new tn(null);n&&a(n);function a(C){r=C}function h(C,p,l){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let f=(t.map.get(C)??{})[p];if(f){i={chapterId:l,listId:C,itemId:p,...f};let b=i.player;i.subscription.add(b.info.currentQuality$.subscribe(g=>{let A=b.info.position$.getValue(),F=b.info.isAutoQualityEnabled$.getValue();if(!(!g||!A||F))for(let E of t.map)Object.values(E[1]).forEach(({player:V})=>{ht(V,g)})})).add(b.events.started$.subscribe(()=>{d(p)})),f.container.remove(),r.setPlayer(f.player),o||(r.init(),o=!0),s.next({player:i.player,config:i.config,statistics:i.statistics});return}throw Error("Can't set. Not find.")}async function d(C){if(!r)throw Error("need to set interactive controller");if(X(i)||C!==i.itemId)return;let p=r.getChapterBranches(),l=new Set;for(let m of p)l.has(m.media.id)||(await y({media:m.media,chapterId:m.chapter.id,setAsActive:!1,title:m.chapter.label}),l.add(m.media.id))}async function v({chapter:{id:C},manifestVideo:p}){if(X(i)||!r)return;let l=i.player.info.muted$.getValue(),m=i.player.info.currentQuality$.getValue(),f=i.player.info.isAutoQualityEnabled$.getValue(),b=i.player.info.volume$.getValue(),g=i.player.info.currentPlaybackRate$.getValue(),A=!f,F=!1;for(let E of t.map)if(E[0]===p.id&&!r.state.isReplay$.getValue()){let V=Object.keys(E[1]);for(let M of V)M===i.itemId?(V.length<en||(F=!0),t.removePlayer(E[0],M)):(F=!0,h(E[0],M,C),A?ht(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(b),i.player.setMuted(l),i.player.setPlaybackRate(g))}else t.removePlayer(E[0]);F||(await y({media:p,chapterId:C,setAsActive:!0,playbackRate:g}),A?ht(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(b),i.player.setMuted(l))}async function y({media:C,chapterId:p,prefetch:l=!0,setAsActive:m=!0,autoplay:f=!1,preferredExt:b,title:g,playbackRate:A}){let F=Math.random().toString(),E=document.createElement("div");c.append(E);let V;if(r?.options?.vkVideoLoader){let vt=si(C);vt.length&&(V=await r.options.vkVideoLoader(...vt))}let M=r?.options?.coreConfig||void 0,_={...M,configName:[...M?.configName??[],"interactive"]},Q={container:E,...V?.videos?.[0]||{sources:Ee(C,b).sources},title:g,failoverHosts:V?.failoverHosts||[]},B=new Yi(_,Ji.createRootTracer());B.initVideo(Q);let q=null;if(V?.videos&&r?.options.createOneStat){let vt=V.videos[0],Yt=r.options.createOneStat(vt),Ve=new Ie;Yt&&(Ve.add(Yt.attachTo(B)),q={oneStat:Yt,statSubscription:Ve})}let Re=new Ie,Vi=i?.player?.info.isAutoQualityEnabled$.getValue();Re.add(B.events.canplay$.subscribe(function(){Vi||ht(B,i.player.info.currentQuality$.getValue()),A&&B.setPlaybackRate(A)}));let Y=t.createPlayer({listId:C.id,itemId:F,player:B,container:E,sources:Ee(C,b).sources,config:Q,subscription:Re,statistics:q});return m&&h(C.id,Y.itemId,p),f&&Y.player.play(),l&&!f&&Y.player.prepare(),{player:Y.player,config:Y.config,statistics:Y.statistics}}function u(){R(),r=null,c.remove()}function R(){e.unsubscribe(),t.removeAll(),i={},o=!1}async function I(){if(!r)throw Error("need to set interactive controller");R(),c=document.createElement("div");let{media:C,chapter:p}=r.getCurrentChapter();C&&p?(e.add(r.events.chapterChanged$.subscribe(v)),await y({media:C,chapterId:p.id,title:p.label})):console.error("not found")}return{...t,init:I,setInteractiveController:a,createPlayer:y,removeAll:u,getActivePlayer:function(){return i},activePlayerChanged:s}}var T={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},mt={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},k={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as nn}from"@vkontakte/videoplayer-shared/evergreen";function xe(n){return function(...e){return n(...e.reverse())}}function dt(n,...t){return(...e)=>W(t[0])&&W(e[0])?n({...t[0],...e[0]}):n(...t,...e)}var Qt=class{constructor({player:t,container:e,branches:i,selectBranches:r,interactiveEvents:o,globalEvents:c,globalEventEmitter:s,getContainerEventState:a,permanentTextControls:h,interactiveTimeOpenUri:d,disabledControls$:v,onRemove:y,onError:u,disableTextControlContainerVisibilityEvents:R=!1}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(Z(this.container.container.events)&&this.gameState===3||this.selectBranches.state.isExpect||(this.gameState!==2&&this.container.hide?.(),this.emitContainerVisibilityEvent(!1)))})};this.show=()=>{if(this.gameState!==2||this.isSelectedControlEvent)return;if(this.container.getElement()){let{hasOpenURIEventInCurrentContainer:e}=this.getContainerEventState();if(this.container.show?.(),this.interactiveTimeOpenUri&&e||this.disableTextControlContainerVisibilityEvents)return;this.emitContainerVisibilityEvent(!0,!1)}else{let e={isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.emitContainerVisibilityEvent(!1)},onEvent:(o,c)=>{let{isExpectTime:s,hasOtherExpect:a,hasOpenURIEvent:h,hasOpenURIEventInCurrentContainer:d,isAllOpenURIEventsValid:v,hasShouldOpenNowEvent:y}=this.getContainerEventState(),u=this.interactiveTimeOpenUri&&!d,R=this.interactiveTimeOpenUri&&d;if((!this.interactiveTimeOpenUri||u)&&(this.isSelectedControlEvent=!0),o!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||u)){if(this.interactiveTimeOpenUri){let I=!a&&!v&&d;I&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:I})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&h&&this.gameState!==5){if(R){let C=((p,l,m,f)=>!p&&!l&&m||p&&!l&&m&&!f||p&&!l&&m&&f)(s,a,v,this.isSelectedContainerEvent);this.fakeRemoveView(C)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!s||!a||!y)&&(this.selectBranches.stopExpect(),c())}},isEOV:()=>this.gameState===4},i=dt(this.selectBranches.onControlEvent,e),r=(this.player?.info.duration$.getValue()??1/0)*1e3;this.container.createView({eventCallback:i,videoDurationMs:r}),this.disableTextControlContainerVisibilityEvents||this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let t=this.player.experimental.element$.getValue(),i=t instanceof HTMLVideoElement?t.readyState:void 0,r=[6,5];if(!i||r.includes(this.gameState)&&!this.isPermanentText)return;let o=this.player.getExactTime();if(ni(o,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(ye(o,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let h=this.gameState;this.gameState=3,h===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:h}=this.getContainerEventState(),d=this.selectBranches.state.isExpect,v=this.interactiveTimeOpenUri&&h;if(v&&!d){let y=this.container.getElement();y&&(y.style.visibility!=="hidden"&&this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView())}!this.isPermanentText&&!v&&this.removeView()}let c=ye(o,this.container.container),s=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],a={subjectId:this.container.container.id,subjectName:"container",range:s,currentTime:o,isInteractiveTime:c};this.container.onProgress(o*1e3,c),this.globalEventEmitter.emit(T.eachTick,a),this.globalEvents.eachTick$.next(a)};this.container=e,this.branches=i,this.selectBranches=r,this.subscription=new nn,this.player=t,this.interactiveEvents=o,this.getContainerEventState=a;let I=it(e.container.controls);this.isPermanentText=h&&I,this.disableTextControlContainerVisibilityEvents=R&&I,this.interactiveTimeOpenUri=d,this.disabledControls$=v,this.onRemove=y,this.globalEventEmitter=s,this.gameState=0,this.globalEvents=c,this.onError=u,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(t,e=!1){t?(this.globalEventEmitter.emit(T.interactives,{subjectId:this.container.container.id,subjectName:"container",type:k.visibility,visibility:t,isFirst:e}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:t,isFirst:e})):(this.globalEventEmitter.emit(T.interactives,{subjectId:this.container.container.id,subjectName:"container",type:k.visibility,visibility:!1}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:t}))}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(t=>{t?this.container.disable?.():this.container.enable?.()})),this.subscription.add(this.container.error$.subscribe(this.onError))}selectContainerEvent(t=!1){let{isExpectEventForCurrentContainer:e}=this.getContainerEventState();this.interactiveEvents.containersEventsCallState.setCalled({timestamp:t?1/0:this.container.container.endTime??1/0,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,!e&&!this.container.isRemoved&&this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:t}),!t&&this.interactiveEvents.exec(this.container.container.endTime??1/0))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);let{isExpectTime:t,hasOpenURIEventInCurrentContainer:e}=this.getContainerEventState(),i=this.interactiveTimeOpenUri?t||e:Z(this.container.container.events)||t;(this.isSelectedControlEvent||!i)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.emitContainerVisibilityEvent(!1)}onResize(t){this.container.onResize(t)}reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=1}removeView(){this.container.removeView(),this.globalEventEmitter.emit(T.interactives,{subjectId:this.container.container.id,subjectName:"container",type:k.containerRemoved,visibility:!1}),this.globalEvents.interactiveContainerRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-removed"}),this.gameState=5,this.onRemove?.()}fakeRemoveView(t=!1){this.container.isRemoved||this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:t}),this.container.fakeRemove()}updateControlsShadowStyles(t){this.container.updateControlsShadowStyles(t)}toggleBlinkAnimation(t){this.container.toggleBlinkAnimation(t)}destroy(){this.reset(),this.removeView(),this.gameState=6,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}};var li=(n=[])=>n.reduce((t,e,i)=>{let r=(e?.controls??[]).filter(o=>!$t(o));if(Gt(r)){let o=[e.startTime??0,e.endTime??1/0],c={id:e.id,isRemoved:!1};if(!i)t.push({subjects:[c],range:o});else{let s=[],a=-1/0,h=1/0,d=[],v=[];for(let y=0;y<t.length;y++){let u=t[y];if(v.push(...u.subjects),u.range[0]<h&&(h=u.range[0]),u.range[1]>a&&(a=u.range[1]),o[0]>=u.range[0]&&o[1]<=u.range[1])return t[y].subjects.push(c),t;o[0]<u.range[0]&&o[1]>u.range[0]&&(s.push(y),d=d.concat(u.subjects)),o[0]>=u.range[0]&&o[0]<=u.range[1]&&(s.push(y),d=d.concat(u.subjects),o[0]=u.range[0]),o[1]>=u.range[0]&&o[1]<=u.range[1]&&(s.push(y),d=d.concat(u.subjects),o[1]=u.range[1])}if(v.push(c),o[0]<=h&&o[1]>=a)return[{subjects:v,range:o}];s.length&&s.reverse().forEach(y=>{t.splice(y,1)}),t.push({subjects:d.concat([c]),range:o})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]);function ci(){let n={};function t(){for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&delete n[s]}function e(s){let a={};for(let h in n)+h<=s&&(a[h]=n[h]);return a}function i(s){let a={};for(let h in n)+h>=s&&(a[h]=n[h]);return a}function r({timestamp:s,priority:a,initiator:h}){if(te(s)){let d=n[s]??null;if(d&&a&&rt(a,!0)){let v={},y=d[a];return y&&(v={...v,...y}),v=X(v)?null:v,v&&rt(h,!0)?v[h]??null:v}return d}return null}function o({timestamp:s,priority:a,initiator:h}){if(te(s))if(n[s]){if(a&&rt(a,!0))if(n[s][a]){if(h&&rt(h,!0))if(n[s][a][h]){if(delete n[s][a][h],!X(n[s][a]))return!0}else return!1;if(delete n[s][a],!X(n[s]))return!0}else return!1;return delete n[s]}else return!1;return!1}function c({timestamp:s,priority:a,initiator:h,...d}){n[s]?.[a]?.[h]?n[s][a][h].push({...d}):n[s]?.[a]?n[s][a]={...n[s][a],[h]:[{...d}]}:n[s]?n[s]={...n[s],[a]:{[h]:[{...d}]}}:n[s]={[a]:{[h]:[{...d}]}}}return{map:n,remove:o,add:c,removeAll:t,get:r,getLte:e,getGte:i}}var rn=[x.expect,x.setNextBranch],on=1/0;function pi(n,t){let e=n,i,r=sn(t),o=ci(),c,s=()=>{u(),p()},a=l=>{o.add.call(void 0,l),R()},h=(l=[])=>{for(let m of l)if(m.action(),rn.includes(m.actionType))break},d=(l=1/0)=>{let m=Xt(o.get({timestamp:l,priority:"control"})??{}),f=Xt(o.get({timestamp:l,priority:"container"})??{}),b=Xt(o.get({timestamp:l,priority:"chapter"})??{});return[...m,...f,...b]},v=l=>{r.isReady(l)&&h(d(l))},y=()=>{h([...Xt(o.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{i&&(c?.unsubscribe(),i=void 0)},R=()=>{i||(i=()=>setTimeout(()=>{v(1/0)}),c=e.events.ended$.subscribe(i))},I=l=>{u(),e=l},C=l=>{l.priority==="container"&&r.resetCalled(l.timestamp),o.remove(l)},p=()=>{r.release(),o.removeAll()};return{setPlayer:I,add:a,remove:C,exec:v,execEndOfVideo:y,listen:R,unlisten:u,release:s,containersEventsCallState:r,getPreparedToExecActions:d}}function sn(n){let t=new Map;return{setCalled:({timestamp:s,id:a})=>{let h=t.get(s);h&&h[a]!==void 0&&(h[a]=!0)},setData:(s=[])=>{for(let a of s){let h=a.endTime??on,d=t.get(h);t.set(h,{...d,[a.id]:!1})}},resetCalled:s=>{let a=t.get(s);if(a)for(let h in a)a[h]=!1},isReady:s=>{let a=t.get(s);if(!a)return!0;let h=Object.values(a);return n?h.some(v=>v):!h.some(v=>!v)},release:()=>t.clear()}}function Xt(n){return Object.values(n).flat().sort(t=>t.actionType===x.expect?-1:1)}var hi={videoContentHeight:0,videoContentWidth:0},mi=n=>{let{height:t,width:e}=n.info.intrinsicVideoSize$.getValue()||{};if(!(t&&e))return hi;let{clientHeight:i,clientWidth:r}=n.experimental.element$.getValue()||{};if(!(i&&r))return hi;let o=t/e,c=i/r,s,a;return c>o?(a=r,s=r*o):c<o?(a=i/o,s=i):(a=r,s=i),{videoContentWidth:a,videoContentHeight:s}};var an=250;function di(n){let t,e=new ResizeObserver(s=>{o(s),t=o.bind(null,s)});function i(s){let{parentElement:a,player:h}=n();if(a&&h){let{videoContentWidth:d,videoContentHeight:v}=mi(h);a.style.setProperty("--interactive-content-width",`${d}px`),a.style.setProperty("--interactive-content-height",`${v}px`),a.style.setProperty("--interactive-width",`${s[0].contentRect.width}px`),a.style.setProperty("--interactive-height",`${s[0].contentRect.height}px`)}}function r(){let{parentElement:s}=n();s.removeAttribute("style")}let o=at(s=>{let{fns:a=[]}=n();i(s);for(let h of a)h()},an);function c(){t=void 0,e.disconnect(),r()}return{resizeObserver:e,calc:()=>{t?.()},release:c}}var ln=n=>Math.floor(Math.random()*n),fi=n=>{let t=n.length,e=1/0,i=null;for(;t--;){let r=n[t],o=r.weight??1;o<e&&(e=o,i=r)}return i},bi=n=>{let t=n.length,e=-1/0,i=null;for(;t--;){let r=n[t],o=r.weight??0;o>e&&(e=o,i=r)}return i};var vi=n=>{let t=n.length,e=ln(t);return n[e]},ui=1,yi=n=>{let t=0;for(let i=0;i<n.length;++i)t+=n[i].weight??ui;let e=Math.random()*t;t=0;for(let i=0;i<n.length-1;++i)if(t+=n[i].weight??ui,t>=e)return n[i];return n[n.length-1]};var Ci={shouldOpenNow:!0,isDetachContainer:!0},gi="after-expect",Ae=(n,t=!1)=>({...n,args:t?{...n.args,...Ci}:{...Ci,...n.args}}),Ei=({globalEventEmitter:n,globalEvents:t,player:e,interactiveEvents:i})=>{let r={isExpect:!1},o=()=>{r.isExpect&&(r.isExpect=!1)},c=({action:p,controlType:l,controlId:m,containerId:f,branches:b=[],onEvent:g,isEOV:A=()=>!1,isDisabled:F=()=>!1})=>{let E=Ae(p,A()),V={timestamp:1/0,priority:"control",initiator:m,actionType:E.type},M=F(),_=n.emit.bind(n,T.interactives,{subjectId:m,subjectType:l,subjectName:"control",type:M?k.actionChoiceCanceled:k.actionChoice,actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:f,...E.args}}),Q=()=>{t.interactiveActionChoice$.next({subjectId:m,subjectType:l,subjectName:"control",type:M?"action-choice-canceled":"action-choice",actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:f,...E.args}})};if(M){_(),Q();return}switch(E.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let B=b.find(q=>q.id===E.args.branchId);if(!B)return;g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?I({subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}}):i.add({...V,action:I.bind(null,{subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}})});return}case x.continuePlayback.trim().toLowerCase():{g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?R({subjectId:m,subjectName:"control",subjectType:l,action:p}):i.add({...V,action:R.bind(null,{subjectId:m,subjectName:"control",subjectType:l,action:p})});return}case x.openURI.trim().toLowerCase():{g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?C({subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{URI:p.args.uri}}):i.add({...V,action:C.bind(null,{subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{URI:p.args.uri}})});return}default:{let B="Unexpected control event",q=new P(1,1,{message:B});d(q,B);return}}},s=({action:p,container:{id:l,endTime:m},branches:f=[],isEOV:b=!1,autoSelected:g=!1})=>{let A=Ae(p,b),F={timestamp:!A.args.shouldOpenNow||b?1/0:m??1/0,priority:"container",initiator:l,actionType:A.type},E=n.emit.bind(n,T.interactives,{subjectId:l,subjectName:"container",type:k.actionChoice,actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}}),V=()=>{t.interactiveActionChoice$.next({subjectId:l,subjectName:"container",type:"action-choice",actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}})};switch(A.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let M=f.find(_=>_.id===A.args.branchId);if(!M)return;E(),V(),i.add({...F,action:I.bind(null,{subjectId:l,subjectName:"container",action:A,payload:{chapterId:M.chapterId,autoSelect:g}})});return}case x.setMaxWeightBranch.trim().toLowerCase():return;case x.setMinWeightBranch.trim().toLowerCase():return;case x.setRandomBranch.trim().toLowerCase():return;case x.setWeightlessRandomBranch.trim().toLowerCase():return;case x.continuePlayback.trim().toLowerCase():{E(),V(),i.add({...F,action:R.bind(null,{subjectId:l,subjectName:"container",action:A})});return}case x.openURI.trim().toLowerCase():{E(),V(),i.add({...F,action:C.bind(null,{subjectId:l,subjectName:"container",action:A,payload:{URI:p.args.uri}})});return}default:{let M="Unexpected container event",_=new P(1,1,{message:M});d(_,M);return}}};function a({container:p,branches:l,isEOV:m=!1}){let f=Ce(p.events);if(f){let b=Ae(f.action,m);n.emit(T.interactives,{subjectId:p.id,subjectName:"container",type:k.actionChoice,actionType:b.type,payload:{invokeImmediately:b.args.shouldOpenNow,...b.args}}),t.interactiveActionChoice$.next({subjectId:p.id,subjectName:"container",type:"action-choice",actionType:b.type,payload:{invokeImmediately:b.args.shouldOpenNow,...b.args}}),i.add({timestamp:m?1/0:p.endTime??1/0,priority:"container",initiator:p.id,actionType:x.expect,action:y.bind(null,{subjectId:p.id,subjectName:"container"})}),r.isExpect=!0}else for(let b of p.events??[])s({action:b.action,container:p,branches:l,isEOV:m})}let h=({chapterId:p,action:l,branches:m=[]})=>{let f=n.emit.bind(n,T.interactives,{subjectId:p,subjectName:"chapter",type:k.actionChoice,actionType:l.type,payload:l.args}),b=()=>{t.interactiveActionChoice$.next({subjectId:p,subjectName:"chapter",type:"action-choice",actionType:l.type,payload:l.args})};switch(l.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let g=m.find(A=>A.id===l.args.branchId);return g?.chapterId?(f(),b(),I.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setWeightlessRandomBranch.trim().toLowerCase():{let g=vi(m);return g?.chapterId?(f(),b(),I.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setRandomBranch.trim().toLowerCase():{let g=yi(m);return g?.chapterId?(f(),b(),I.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setMaxWeightBranch.trim().toLowerCase():{let g=bi(m);return g?.chapterId?(f(),b(),I.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setMinWeightBranch.trim().toLowerCase():{let g=fi(m);return g?.chapterId?(f(),b(),I.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.continuePlayback.trim().toLowerCase():return f(),b(),R.bind(null,{subjectId:p,subjectName:"chapter",action:l});case x.openURI.trim().toLowerCase():return f(),b(),C.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{URI:l.args.uri}});default:{let g="Unexpected chapter event",A=new P(1,1,{message:g});d(A,g);return}}};function d(p,l){console.error(l),t.error$.next(p),n.emit(T.errors,p)}function v(p){let l=Ce(p.events);if(l){if(H(p))return;n.emit(T.interactives,{subjectId:p.id,subjectName:"chapter",type:k.actionChoice,actionType:l.action.type,payload:l.action.args}),t.interactiveActionChoice$.next({subjectId:p.id,subjectName:"chapter",type:"action-choice",actionType:l.action.type,payload:l.action.args}),i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:x.expect,action:y.bind(null,{subjectId:p.id,subjectName:"chapter"})})}else p.events?.forEach(m=>{let f=h({chapterId:p.id,action:m.action,branches:p.branches});f&&i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:m.action.type,action:f})})}let y=({subjectId:p,subjectName:l})=>{e.pause(),n.emit(T.interactives,{subjectId:p,subjectName:l,type:k.actionExecution,actionType:x.expect}),t.interactiveActionExecution$.next({subjectId:p,subjectName:l,type:"action-execution",actionType:x.expect})},u=({subjectId:p,subjectName:l})=>{e.info.isEnded$.getValue()?i.execEndOfVideo():e.play(),n.emit(T.interactives,{subjectId:p,subjectName:l,type:k.actionExecution,actionType:gi}),t.interactiveActionExecution$.next({subjectId:p,subjectName:l,type:"action-execution",actionType:gi})},R=({subjectId:p,subjectName:l,subjectType:m,action:f})=>{n.emit(T.interactives,{subjectId:p,subjectName:l,subjectType:m,type:k.actionExecution,actionType:f.type}),t.interactiveActionExecution$.next({subjectId:p,subjectName:l,subjectType:m,type:"action-execution",actionType:f.type})},I=({subjectId:p,subjectName:l,subjectType:m,action:f,payload:b})=>{b.behaviour="change-chapter",n.emit(T.interactives,{subjectId:p,subjectName:l,subjectType:m,type:k.actionExecution,actionType:f.type,payload:b}),t.interactiveActionExecution$.next({subjectId:p,subjectName:l,subjectType:m,type:"action-execution",actionType:f.type,payload:b})},C=({subjectId:p,subjectName:l,subjectType:m,action:f,payload:b})=>{if(!b.URI)return;let g=window.open(b.URI,"_blank","noopener,noreferrer");g&&(g.opener=null),n.emit(T.interactives,{subjectId:p,subjectName:l,subjectType:m,type:k.actionExecution,actionType:f.type}),t.interactiveActionExecution$.next({subjectId:p,subjectName:l,subjectType:m,type:"action-execution",actionType:f.type})};return{onControlEvent:c,onContainerEvent:s,onChapterEvent:h,onExpectEvent:y,expectEventHandler:u,setManifestChapterEvents:v,setManifestContainerEvents:a,stopExpect:o,state:r}};import{Subscription as dn,Subject as we,ValueSubject as ut}from"@vkontakte/videoplayer-shared/evergreen";var Se=(n,t)=>{let e={};return n.map(i=>{if(!e[i]){let r=t.chapters.find(c=>c.id===i);if(!r)return null;let o=t.media.videos.find(c=>r.videoId===c.id);if(!o)return null;e[i]=Ii(o)}return e[i]}).filter(Boolean)},pn=n=>{for(let t of n.variants)if(hn(t)&&t.payload)return t.payload.id},hn=n=>!!(n.type==="custom"&&n.payload&&n.payload.type==="vk"),Ii=n=>{let t=pn(n);if(!t)return null;let e=t.split("_").pop();return e?parseInt(e,10):null},mn=(n,t)=>{for(let e of n.media.videos)if(t===Ii(e)){for(let i of n.chapters)if(i.videoId===e.id)return i.id;return}},Ti=(n,t)=>n.reduce((e,i)=>{let r=mn(t,i);return r?[...e,r]:e},[]);var ft=class{constructor({globalEventEmitter:t,videoId:e,interactiveController:i,historyApi:r,settings:o}){this.state={history$:new ut([]),hasPrevChapter$:new ut(!1),prevChapter$:new ut(null),isInitialChapter$:new ut(!1),isGoBackLimited$:new ut(!1)};this.#i=null;this.#s=!1;this.#t=null;this.#p=null;this.events={inited$:new we,destroyed$:new we,error$:new we};this.#n=null;this.#r=null;this.#e=null;this.#a=new dn;this.#l=!1;this.#c=0;this.#n=e,this.#e=t,this.#r=i,this.#i=r,this.#o=o,this.state.history$&&this.#a&&this.#a?.add(this.state.history$.subscribe(c=>{this.state.prevChapter$.next(c.at(-2)||null),this.state.hasPrevChapter$.next(c.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#t?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#c===this.#o.maxLength-1)}))}#i;#o;#s;#t;#p;#n;#r;#e;#a;#l;#c;async setManifest(t){if(!this.#r||!this.#e)return;this.#t=t,await this.getProjectHistory();let e=this.getInitialChapterId();await this.#r.setChapter({chapterId:e,pushToHistory:!1}),this.#s||(this.#s=!0,this.events.inited$.next({initChapterId:e}))}get inited(){return this.#s}async updateHistory(t,e=!0){if(!this.#t)return;this.#l?(this.#l=!1,this.#c++):this.#c=0;let i=this.#t,r=t.length-this.#o.maxLength,o=r>0?t.slice(r):t,c=Se(o,i);if(this.#p=c,this.state.history$.next(o),!(!e||!this.#i||!this.#n))try{await this.#i.save(this.#n,c)}catch{let a=new P(1,5,"Unable to save interactive history");this.events.error$.next(a),this.#e?.emit(T.errors,a)}}async goBack(){if(!this.state||!this.#r){let i=new P(1,5,"Unable to save interactive history");return this.events.error$.next(i),this.#e?.emit(T.errors,i)}this.#l=!0;let t=this.state.history$.getValue().slice(0,-1),e=t.pop();this.state.history$.next(t),await this.#r.setChapter({chapterId:e,playPrev:!0})}async getProjectHistory(){if(!this.#t||!this.#n)return;let t=this.#t,e=[this.getInitialVideoId()];if(this.#i)try{let r=await this.#i.get(this.#n);r.length&&(e=r)}catch{let o=new P(1,5,"Error while trying to fetch data");this.events.error$.next(o),this.#e?.emit(T.errors,o)}let i=Ti(e,t);this.state.history$.next(i)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#o.initChapterId||this.#t?.metadata.initChapterId}getInitialVideoId(){if(this.#t){let t=this.getInitialChapterId();return Se([t],this.#t).pop()}return null}destroy(){this.#n=null,this.#i=null,this.#r=null,this.#a?.unsubscribe(),this.#a=null,this.#s=!1,this.#e?.emit(T.historyDestroyed),this.events.destroyed$.next(),this.#e=null}};var Kt=class{constructor(){this._prevSizeId=0;this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){let t=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!t)return!1;let e=t.data,i=e.length;for(let r=3;r<i;r+=40)if(e[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(t){this.canvasImgSrc=t}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(t,e=!1){let i=t.width+t.height;if(this._prevSizeId===i)return;let r;e&&(r=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&r&&this.restore(r),this._prevSizeId=i}async save(){let t=this.rootElement.toDataURL("image/jpeg",1),e=new Image;return e.crossOrigin="anonymous",e.src=t,await e.decode(),e}restore(t){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(t,0,0,this.rootElement.width,this.rootElement.height)}};var Zt=class{constructor({parentElement:t,endOffsetMs:e=250,onError:i}){this.currentVideoDurationMs=1/0;this._containerTimeFrameShouldReceived=!1;this._endTimeFrameReceived=!1;this._shouldCallSkip=!1;this.onEachTick=t=>{let e=t??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,i=this.isChapterEndTime(e);if(this.isContainerTime(e))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(i)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};this.onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
6
+ var Mt="1.0.39-dev.a77510fe.0";import{Subject as Di,Subscription as Hi}from"@vkontakte/videoplayer-shared/evergreen";var Je=class{constructor(e){this.layout=e}},ye=class extends Je{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * (${t.width} + ${2e-4}))`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}};function Pt(n){return"features"in n}var J=class{constructor(e,t){this.container=e,this.options=t,this.factories=new Map,this.controls=[],this.setControls()}featureIsEnabled(e){return this.options&&Pt(this.options)&&this.options.features[e]}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.setControls()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.setControls()}setControls(){this.controls=this.chooseControls()}chooseControls(){return this.container.controls?.reduce((e,t)=>{let i=t.type.trim().toLowerCase(),r=this.factories.get(i);if(r){let o=r(t,this.options);if(o)return[...e,o]}return[...e]},[])||[]}};import{fromEvent as we,once as $i}from"@vkontakte/videoplayer-shared/evergreen";var G=(n,e)=>Object.prototype.toString.call(n)===`[object ${e}]`,W=n=>G(n,"Object"),Ce=n=>G(n,"String"),ge=n=>G(n,"Array"),Ee=n=>G(n,"Number"),Lt=n=>G(n,"Function"),Ot=n=>G(n,"Boolean"),et=n=>Ee(n)&&!isNaN(n);var X=n=>W(n)&&Object.keys(n).length===0,tt=n=>ge(n)&&!n.length;var re=(n,e)=>Ce(n)&&(e?n.trim():n).length;function oe(n,e=1){let t="0",i="0",r="0";return n.length===4?(t="0x"+n[1]+n[1],i="0x"+n[2]+n[2],r="0x"+n[3]+n[3]):n.length===7&&(t="0x"+n[1]+n[2],i="0x"+n[3]+n[4],r="0x"+n[5]+n[6]),`rgba(${+t},${+i},${+r},${e})`}var Nt="interactive",w={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderWidthRawValue:"1px",roundCornersRawValue:"0",borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0,shadowColorLight:"#fff",shadowColorDark:"#000",shadowColorAlpha:.24},$t=(i=>(i.top="flex-start",i.bottom="flex-end",i.center="center",i))($t||{}),Ft=(i=>(i.start="flex-start",i.end="flex-end",i.center="center",i))(Ft||{}),Bt=(i=>(i.start="left",i.end="right",i.center="center",i))(Bt||{}),Ie=({target:n,props:e})=>{n.style.alignItems=(e?.gravityVertical&&$t[e.gravityVertical])??"center",n.style.justifyContent=(e?.gravityHorizontal&&Ft[e.gravityHorizontal])??"center",n.style.textAlign=(e?.alignment&&Bt[e.alignment])??"center"},Te=({target:n,props:e,fallback:t,dependsOn:i})=>{n.style.color=e?.text?.color??t.textColor,n.style.fontSize=`calc(${i.height} * ${e?.text?.size??t.textSize})`,n.textContent=e?.text?.value??t.textContent},xe=({target:n,props:e,fallback:t})=>{n.style.backgroundColor=oe(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},se=({target:n,props:e,fallback:t,dependsOn:i,useRawValues:r=!1})=>{let o=r?t.borderWidthRawValue:`calc(${i.height} * ${e?.shape?.border?.width??t.borderWidth})`,c=r?t.roundCornersRawValue:`calc(${i.height} * ${e?.shape?.roundCorners??t.roundCorners})`;n.style.borderWidth=o,n.style.borderStyle="solid",n.style.borderColor=oe(r?t.borderColor:e?.shape?.border?.color??t.borderColor,r?t.borderAlpha:e?.shape?.border?.alpha??t.borderAlpha),n.style.borderRadius=c},jt=({target:n,isDark:e,baseDimension:t,fallback:i})=>{let c=oe(i.shadowColorLight,i.shadowColorAlpha),s=oe(i.shadowColorDark,i.shadowColorAlpha),a=`calc(${t} * ${.25})`,h=`calc(${t} * ${.11})`,d=`0px 0px ${a} ${h} ${e?s:c}`;n.style.boxShadow=d},ee=({target:n,layoutParams:e,fallback:t})=>{let i=e.angle??t.angle;i=i&&i*-1,n.style.transform=`rotate(${i}rad)`};import{fromEvent as ot,Subject as Li,Subscription as Oi,ValueSubject as Ni}from"@vkontakte/videoplayer-shared/evergreen";var it="interactive-control-tap",te={common:it,animation:`${it}-animation`,visible:`${it}-visible`};var Mi=60,Ae=class{constructor({controlRotateAngleRad:e,clickCancelCondition:t,circleDiameterPx:i=Mi,useDimensionsBasedSize:r=!1}){this.onElementClick=e=>{if(!e.target||!e.currentTarget||this.clickCancelCondition())return;let t=e.currentTarget.parentElement;if(!t)return;let i=t.getBoundingClientRect(),r={width:this.useDimensionsBasedSize?t.offsetWidth:this.circleDiameterPx,height:this.useDimensionsBasedSize?t.offsetHeight:this.circleDiameterPx},o=Math.min(r.width,r.height),c=i.left+i.width/2,s=i.top+i.height/2,a=e.clientX-c,h=e.clientY-s,d=Pi(a,h,this.controlRotateAngleRad);this.element.style.width=o+"px",this.element.style.left=d.x+i.width/2-o/2+"px",this.element.style.top=d.y+i.height/2-o/2+"px",this.element.classList.add(te.visible,te.animation)};this.onAnimationEnd=e=>{!e.target||!e.currentTarget||e.target===e.currentTarget&&this.element.classList.remove(te.visible,te.animation)};let o=document.createElement("div");o.classList.add(te.common),this.controlRotateAngleRad=e,this.element=o,this.clickCancelCondition=t,this.circleDiameterPx=i,this.useDimensionsBasedSize=r}};function Pi(n,e,t){return{x:n*Math.cos(t)-e*Math.sin(t),y:n*Math.sin(t)+e*Math.cos(t)}}var nt="int",K=(i=>(i.AREA=`${nt}_area`,i.TEXT=`${nt}_text`,i.BUTTON=`${nt}_bttn`,i))(K||{});function rt(n){return"features"in n}var D="interactive-control",S={common:D,selected:`${D}-selected`,wrapper:`${D}-wrapper`,disabled:`${D}-disabled`,button:`${D}-button`,area:`${D}-area`,text:`${D}-text`,blinkAnim:`${D}-blink-anim`,blinkAnimButton:`${D}-blink-anim-button`,blinkAnimArea:`${D}-blink-anim-area`},_t=40;var P=class{constructor(e,t,...i){this.severity=e;this.category=t;this.data=i}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var z=class{constructor(e,t){this.control=e;this.options=t;this.container=null;this.controlElement=null;this.subscriptions=new Oi;this.error$=new Li;this.isInteracted$=new Ni(!1)}onError(e="",t){let i=new P(1,1,{message:e,error:t,details:{id:this.control.id}});this.error$.next(i)}addControlTap(e){if(this.featureIsEnabled("controlsTapPlace")&&this.container){let t=this.control.layoutParams.angle??w.angle;this.controlTap=new Ae({controlRotateAngleRad:t,clickCancelCondition:this.container.isManifestContainerDisabled,circleDiameterPx:this.isTouch()?_t:void 0}),this.subscriptions.add(ot(e,"click").subscribe(this.controlTap.onElementClick,i=>this.onError("Control click tap animation error",i))).add(ot(this.controlTap.element,"animationend").subscribe(this.controlTap.onAnimationEnd,i=>this.onError("Tap animationend error",i))),this.container.element.append(this.controlTap.element)}}createContainerElement(e){let t=document.createElement("div");t.classList.add(S.wrapper),e.setControlLayout(t,this.control.layoutParams);let i=(this.control.layoutParams.innerSizesDependOn??w.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"},r=()=>e.isContainerDisabled?.()??!1;this.container={element:t,dimensions:i,isManifestContainerDisabled:r}}createClickListener(e){return t=>{t.stopPropagation(),this.isInteracted$.next(!0),e()}}featureIsEnabled(e){return this.options&&rt(this.options)&&this.options.features[e]}isTouch(){return this.options&&rt(this.options)&&this.options.isTouch}setEvents(e){!this.container||!this.control.events||this.control.events.forEach(t=>{switch(t.type.trim().toLowerCase()){case"onclick":{if(!this.container)break;this.subscriptions.add(ot(this.container.element,"click").subscribe(this.createClickListener(()=>e({action:t.action,controlId:this.control.id,controlType:this.control.type})),r=>this.onError("Error happened on control interaction",r)));break}default:break}})}removeListeners(){this.subscriptions.unsubscribe()}};var lt="interactive-blink-anim-reference",L={common:lt,animation:`${lt}-animation`,disabled:`${lt}-disabled`},Se=class{constructor(){this._RAFId=0;this._element=void 0}get element(){return this._element}create(){if(this._element)return;let e=document.createElement("div");e.classList.add(L.common,L.animation),this._element=e}restart(){this._element&&(this._element.classList.add(L.disabled),this.cleanupRAF(),this._RAFId=requestAnimationFrame(()=>{this._element&&(this._element.classList.remove(L.disabled),this.cleanupRAF())}))}cleanupRAF(){this._RAFId&&(cancelAnimationFrame(this._RAFId),this._RAFId=0)}destroy(){this.cleanupRAF(),this._element=void 0}};var ct="interactive-container",O={common:ct,hidden:`${ct}-hidden`,disabled:`${ct}-disabled`};var ke=(n,e)=>{if(n.type.trim().toLowerCase()==="area")return new pt(n,e)},pt=class extends z{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.area),i.setAttribute("data-testid",K.AREA),xe({target:i,props:this.control.props,fallback:{...w,backgroundColor:"transparent"}}),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),this.addControlTap(i),this.container.element.append(i),e.append(this.container.element),this.controlElement=i,this.updateShadowStyles(),this.registerEvents()}registerEvents(){if(!this.featureIsEnabled("controlsExpectTimeBlinkAnimation"))return;let e=this.container?.element.parentElement;!e||!this.controlElement||(this.subscriptions.add(we(this.controlElement,"mouseleave").subscribe(()=>{if(e.classList.contains(O.disabled))return;let t=e.parentElement;if(t){let i=t.querySelector(`.${L.common}`);i&&this.syncBlinkAnimation(i)}},t=>this.onError("Error happened in mouseleave callback",t))),this.subscriptions.add(we(this.controlElement,"mouseenter").subscribe(()=>{e.classList.contains(O.disabled)||this.onBlinkHovering()},t=>this.onError("Error happened in mouseenter callback",t))).add(we(this.controlElement,"mouseleave").subscribe(()=>{this.controlElement&&(this.controlElement.style.animation="")},t=>this.onError("Error happened in mouseleave callback",t))))}disable(){this.controlElement&&this.controlElement.classList.add(S.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(S.disabled)}getElement(){return this.controlElement}updateShadowStyles(e){if(!(!this.container||!this.controlElement))if(Ot(e)){let t=Math.min(this.controlElement.offsetWidth,this.controlElement.offsetHeight)+"px";jt({target:this.controlElement,props:this.control.props,fallback:w,isDark:e,baseDimension:t}),se({target:this.controlElement,props:this.control.props,fallback:{...w,borderColor:e?w.shadowColorDark:w.shadowColorLight,borderAlpha:1,borderWidthRawValue:"0.1px",roundCornersRawValue:`calc(${this.container.dimensions.height} * ${this.control.props?.shape?.roundCorners??w.roundCorners})`},dependsOn:this.container.dimensions,useRawValues:!0})}else se({target:this.controlElement,props:this.control.props,fallback:{...w,borderAlpha:0},dependsOn:this.container.dimensions})}toggleBlinkAnimation(e){this.controlElement?.classList.toggle(S.blinkAnim,e),this.controlElement?.classList.toggle(S.blinkAnimArea,e)}syncBlinkAnimation(e){this.controlElement&&(!this.controlElement.classList.contains(`${S.blinkAnimArea}`)||this.controlElement.classList.contains(S.selected)||this.controlElement.classList.contains(L.disabled)||(this.controlElement.classList.add(L.disabled),this.subscriptions.add(we(e,"animationiteration").pipe($i()).subscribe(()=>{this.controlElement&&this.controlElement.classList.remove(L.disabled)},t=>this.onError("Error happened in animationiteration callback",t)))))}onBlinkHovering(){if(!this.controlElement||!this.controlElement.classList.contains(`${S.blinkAnimArea}`)||this.controlElement.classList.contains(S.selected))return;let e=window.getComputedStyle(this.controlElement),t=e.getPropertyValue("--interactive-area-hover-opacity").trim();this.controlElement.style.opacity=e.opacity,this.controlElement.style.animation="none",requestAnimationFrame(()=>{this.controlElement&&(this.controlElement.style.opacity=t)})}setShowTimeRange(){}updateFillAnimationDimensions(){}onProgress(){}onResize(){}};import{fromEvent as Le,once as _i}from"@vkontakte/videoplayer-shared/evergreen";var Re=n=>{let e=document.createElement("span");switch(n){case"Button":case"button":{let t=document.createElement("div"),i={overflow:"hidden",display:"flex",justifyContent:"center",alignItems:"center"};Object.assign(t.style,i),t.append(e);let r={display:"inline-block",whiteSpace:"pre",textOverflow:"ellipsis",maxWidth:"initial",maxHeight:"100%",wordBreak:"normal"};return Object.assign(e.style,r),t}default:{let t={display:"inline-block",whiteSpace:"break-spaces",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",maxHeight:"100%",wordBreak:"break-all"};return Object.assign(e.style,t),e}}};var Ve=Math.PI,ht=2*Ve,Me=Ve/2,Dt=3*Me,Fi=0,Bi=[Fi,Me,Ve,Dt];function Ht(n){return n===Me}function Ut(n){return n===Ve}function Gt(n){return n===Dt}function Wt(n){return(n%ht+ht)%ht}function ji(n){for(let e of Bi)if(n===e)return e}function zt(n){if(ji(n))return null;let t=Math.floor(n/Me)+1;return[1,2,3,4][t-1]}function Qt(n){return n*180/Math.PI}var U="interactive-control-fill-animation",N={common:U,fillerWrapper:`${U}-filler-wrapper`,filler:`${U}-filler`,fillHeight:`${U}-fill-height`,fillWidth:`${U}-fill-width`,fromTop:`${U}-from-top`,fromBottom:`${U}-from-bottom`,fromLeft:`${U}-from-left`,fromRight:`${U}-from-right`};var Pe=class n{constructor(e){this.widthExpansionCoef=0;let t=document.createElement("div");t.classList.add(N.common);let i=document.createElement("div");i.classList.add(N.fillerWrapper);let r=document.createElement("div");r.classList.add(N.filler),i.append(r),t.append(i);let o=Wt(e.rotateAngle),c=zt(o),s=c!==null,h=c===2||!s&&Ut(o)||c===3,d=!s&&Ht(o),v=!s&&Gt(o),y=!h&&!d&&!v,u=d||v,V=s&&!u,T=V?o:0;t.style.borderRadius=e.borderRadius,i.style.transform=`skew(${T*-1}rad)`,u?(r.classList.add(N.fillHeight,d?N.fromTop:N.fromBottom),i.classList.add(N.fillHeight,d?N.fromTop:N.fromBottom)):(r.classList.add(N.fillWidth,y?N.fromLeft:N.fromRight),i.classList.add(N.fillWidth)),e.debug&&console.log(`[interactive ${n.name}]`,{widthExpansionCoef:this.widthExpansionCoef,opts:e,shouldFillHeight:u,rotateAngleRad:o,rotateAngelDeg:Qt(o),rotateAngleRaw:e.rotateAngle,fromRight:h,fromTop:d,fromBottom:v,fromLeft:y}),this.useSkew=V,this.fromLeft=y,this.rotateAngle=o,this.fillAnimationElement=t,this.fillAnimationFillerElement=r,this.fillAnimationFillerWrapperElement=i,this.startTime=e.startTime,this.endTime=e.endTime,this.shouldFillHeight=u,this.isDebug=e.debug??!1}updateDimension(e){this.fillAnimationElement.style.top=`${e.borderWidth*-1}px`,this.fillAnimationElement.style.left=`${e.borderWidth*-1}px`,this.fillAnimationElement.style.width=`${e.width}px`,this.fillAnimationElement.style.height=`${e.height}px`;let t=this.calcWidthExpansionCoef({rotateAngle:this.rotateAngle,isSkewed:this.useSkew,initWidth:e.width,initHeight:e.height});!this.shouldFillHeight&&(this.fillAnimationFillerWrapperElement.style.width=100*t+100+"%",this.fillAnimationFillerWrapperElement.style[`${this.fromLeft?"left":"right"}`]=`calc((${t} * 100%) / 2 * -1)`),this.widthExpansionCoef=t}updateAnimation(e){if((o=>o<this.startTime||o>this.endTime)(e))return;let i=this.endTime-this.startTime,r=Math.min(Math.max((e-this.startTime)/i,0),1);this.shouldFillHeight?this.fillAnimationFillerElement.style.transform=`scaleY(${r})`:this.fillAnimationFillerElement.style.transform=`scaleX(${r})`}calcWidthExpansionCoef({rotateAngle:e,isSkewed:t=!1,initWidth:i,initHeight:r}){return t?(i+r*Math.abs(Math.tan(e)))/i-1:0}};var Oe=(n,e)=>{if(n.type.trim().toLowerCase()==="button")return new mt(n,e)},mt=class extends z{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.button),i.setAttribute("data-testid",K.BUTTON),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),xe({target:i,props:this.control.props,fallback:w}),se({target:i,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),Ie({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=Re(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;Te({target:o,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),this.addControlTap(i),this.startTime!==void 0&&this.endTime!==void 0&&this.featureIsEnabled("controlsFillAnimation")&&(this.controlFillAnimation=new Pe({startTime:this.startTime,endTime:this.endTime,rotateAngle:this.control.layoutParams.angle??w.angle,borderRadius:i.style.borderRadius})),i.append(r,this.controlFillAnimation?.fillAnimationElement??""),this.container.element.append(this.controlTap?.element??"",i),e.append(this.container.element),this.controlElement=i,this.registerEvents()}registerEvents(){if(!this.featureIsEnabled("controlsExpectTimeBlinkAnimation"))return;let e=this.container?.element.parentElement;!e||!this.controlElement||(this.subscriptions.add(Le(this.controlElement,"mouseleave").subscribe(()=>{if(e.classList.contains(O.disabled))return;let t=e.parentElement;if(t){let i=t.querySelector(`.${L.common}`);i&&this.syncBlinkAnimation(i)}},t=>this.onError("Error happened in mouseleave callback",t))),this.subscriptions.add(Le(this.controlElement,"mouseenter").subscribe(()=>{e.classList.contains(O.disabled)||this.onBlinkHovering()},t=>this.onError("Error happened in mouseenter callback",t))).add(Le(this.controlElement,"mouseleave").subscribe(()=>{this.controlElement&&(this.controlElement.style.animation="")},t=>this.onError("Error happened in mouseleave callback",t))))}disable(){this.controlElement&&this.controlElement.classList.add(S.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(S.disabled)}getElement(){return this.controlElement}toggleBlinkAnimation(e){this.controlElement?.classList.toggle(S.blinkAnim,e),this.controlElement?.classList.toggle(S.blinkAnimButton,e)}syncBlinkAnimation(e){this.controlElement&&(!this.controlElement.classList.contains(`${S.blinkAnimButton}`)||this.controlElement.classList.contains(S.selected)||this.controlElement.classList.contains(L.disabled)||(this.controlElement.classList.add(L.disabled),this.subscriptions.add(Le(e,"animationiteration").pipe(_i()).subscribe(()=>{this.controlElement&&this.controlElement.classList.remove(L.disabled)},t=>this.onError("Error happened in animationiteration callback",t)))))}onBlinkHovering(){if(!this.controlElement||!this.controlElement.classList.contains(`${S.blinkAnimButton}`)||this.controlElement.classList.contains(S.selected))return;let e=window.getComputedStyle(this.controlElement),t=e.getPropertyValue("--interactive-button-hover-opacity").trim();this.controlElement.style.opacity=e.opacity,this.controlElement.style.animation="none",requestAnimationFrame(()=>{this.controlElement&&(this.controlElement.style.opacity=t)})}updateFillAnimationDimensions(){if(!this.container||!this.controlElement||!this.controlFillAnimation)return;let e=getComputedStyle(this.controlElement),t={width:parseFloat(e.width),height:parseFloat(e.height),borderWidth:parseFloat(e.borderWidth)||0};this.controlFillAnimation.updateDimension(t)}setShowTimeRange(e,t){this.startTime=e,this.endTime=t}onProgress(e){this.controlFillAnimation?.updateAnimation(e)}onResize(){this.updateFillAnimationDimensions()}updateShadowStyles(){}};var Xt=(n,e)=>{if(n.type.trim().toLowerCase()==="text")return new dt(n,e)},dt=class extends z{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;let i=document.createElement("div");i.classList.add(S.common,S.text),i.setAttribute("data-testid",K.TEXT),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),Ie({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=Re(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;Te({target:o,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),i.append(r),this.container.element.append(i),e.append(this.container.element),this.controlElement=i}getElement(){return this.controlElement}disable(){}enable(){}onProgress(){}onResize(){}updateShadowStyles(){}toggleBlinkAnimation(){}setShowTimeRange(){}updateFillAnimationDimensions(){}onError(){}};var Ne=(n,e,t)=>{if(n.type.trim().toLowerCase()==="choice")return new ut(n,e,t)},ut=class extends J{constructor(t,i,r){super(t,r);this.containerElement=null;this.controlSubscriptions=new Hi;this.error$=new Di;this.rootElement=i,this.layout=new ye(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Oe),this.addControlFactory("text",Xt),this.addControlFactory("area",ke)}createView({eventCallback:t,videoDurationMs:i}){let r=document.createElement("div");return r.classList.add(O.common,O.disabled),requestAnimationFrame(()=>{r.classList.remove(O.disabled)}),this.layout.setContainerLayout(r),this.controls.forEach(o=>{o.setShowTimeRange(this.container.startTime,this.container.endTime??i),o.createView({parentElement:r,callbacks:{setControlLayout:this.layout.setControlLayout,isContainerDisabled:()=>this.isDisabled}}),o.setEvents(t),this.controlSubscriptions.add(o.error$.subscribe(this.error$))}),this.rootElement.append(r),this.isRemoved=!1,this.containerElement=r,this.updateControlsFillAnimationDimensions(),r}updateControlsFillAnimationDimensions(){for(let t of this.controls)t.updateFillAnimationDimensions()}hide(){let t=this.getElement();t&&t.classList.add(O.hidden)}show(){let t=this.getElement();t&&t.classList.remove(O.hidden)}enable(){let t=this.getElement();t&&(t.classList.remove(O.disabled),this.controls.forEach(i=>i.enable()),this.isDisabled=!1)}disable(){let t=this.getElement();t&&(t.classList.add(O.disabled),this.controls.forEach(i=>i.disable()),this.isDisabled=!0)}removeView(){let t=this.getElement();t&&(this.controlSubscriptions.unsubscribe(),this.controls.forEach(i=>i.removeListeners()),t.remove(),this.isRemoved=!0,this.containerElement=null)}fakeRemove(){this.isRemoved||(this.isRemoved=!0)}getElement(){return this.containerElement}onProgress(t,i){i&&this.controls.forEach(r=>{r.onProgress(t)})}onResize(t){t&&this.controls.forEach(i=>{i.onResize()})}updateControlsShadowStyles(t){this.controls.forEach(i=>i.updateShadowStyles(t))}toggleBlinkAnimation(t){this.controls.forEach(i=>i.toggleBlinkAnimation(t))}};import{combine as fn,InterfaceLanguage as bn,Observable as wi,once as vn,Subject as $,Subscription as kt,ValueSubject as j,fromEvent as ki}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as be}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as Ui}from"@vkontakte/videoplayer-shared/evergreen";function ae(n,e){let t;return(...i)=>{clearTimeout(t),t=setTimeout(()=>n(...i),e)}}var Kt="video_interactive",Zt="videoint";var qt=250,le=class{constructor(e){this.handleZoomChange=ae(e=>{this.lastZoomInfo=e},qt);this.onResize=e=>{if(!this.isReady||this.isHidden||!e[0].contentRect.width||!e[0].contentRect.height)return;let t=this.getNextPoint();t&&this.ngEditor?.zoomTo(t,void 0,{isFromCenter:!0}),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}};this.handleChapterChange=e=>{if(this.manifest){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Chapter id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor?.selectChapter(e.id),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=null}};this.handleManifestChange=(e,t=[])=>{if(this.isReady=!1,!Ee(e.graph.edit.chapters[0].x)){this.onError?.("Can't show graph");return}this.lastZoomInfo=null,this.manifest=e,this.visitedChapterIds=new Set(t),this.ngEditor&&(this.manifest.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=this.manifest.metadata.id):this.ngEditor.setVisitedChapters(Array.from(t)),this.isReady=!0)};this.init(e)}init({root:e,onOpenPreviewClick:t,onError:i,lang:r,visitedChapters:o=[]}){this.isReady=!1,this.isHidden=!0,this.manifest=null,this.visitedChapterIds=new Set(o),this.onOpenPreviewClick=t,this.onError=i,this.lang=r??"ru",this.zoom=.7,this.lastZoomInfo=null,this.currentManifestId=null,this.currentChapterId=null,this.ngEditor=null,this.ngEditorSize=null,this.graphWrapperElement=Gi(e),this.resizeObserver=new ResizeObserver(ae(this.onResize,qt)),this.resizeObserver.observe(this.graphWrapperElement)}getNextPoint(e=this.ngEditorSize){return!this.lastZoomInfo||!e?null:[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor?.updateVideosInfo(e)}async show(){this.manifest&&(this.ngEditor||await this.initNgEditor(),this.graphWrapperElement.style.display="block",!this.lastZoomInfo&&this.currentChapterId&&this.ngEditor?.focusChapter(this.currentChapterId),this.isHidden=!1)}async initNgEditor(){if(!this.manifest)return;let e;try{e=await Ui(this.lang,Kt,Zt)}catch{this.onError?.("Unable to load graph language pack")}let{GraphEditor:t}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new t(this.graphWrapperElement,{mode:"view",lang:this.lang==="ru"?"ru":"en",translation:e}),this.currentManifestId=this.manifest.metadata.id,this.ngEditor.update(this.manifest),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId&&this.ngEditor.selectChapter(this.currentChapterId),this.ngEditor.on("control",({name:i,...r})=>{i==="openPreview"&&"chapterId"in r&&this.onOpenPreviewClick?.(r.chapterId)}),this.ngEditor.on("zoom",this.handleZoomChange),this.isReady=!0}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.manifest=null,this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}};function Gi(n){let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",n.append(e),e}var ce=class{constructor(){this._containers=[];this._player=null;this.setPlayer=e=>{this._player=e};this.setContainers=e=>{this._containers=e};this.deleteContainer=e=>{this._containers=this._containers.filter(t=>t.id!==e)};this.getNextInteractiveTime=(e=3e3)=>{if(!this._containers.length||this._player===null)return null;let t=-1,i=!1,r=Math.round(this._player.info.position$.getValue()*1e3);for(let o of this._containers){let c=o.startTime-e;if(c<=r&&(o.endTime&&r<=o.endTime||o.endTime===null)){i=!0;break}r<c&&(t=t===-1?c:Math.min(t,c))}return!i&&t!==-1?t:null}}};import{isSupportedManifest as Fe,ContainerTypes as go,ControlTypes as Be,EventActionTypes as x,EventTypes as Eo,migrateManifestToLatestVersion as ti,compareVersions as Io}from"@interactiveplatform/movika-manifest";var Yt={metadata:"Object",chapters:"Array"},Jt=n=>{if(!W(n))return!1;for(let e in Yt)if(!n[e]||!G(n[e],Yt[e]))return!1;return Fe(n.metadata.version)},$e=n=>n.type===Be.Text,ho=n=>n.type===Be.Button,mo=n=>n.type===Be.Area,uo={Choice:"Choice",TextInput:"TextInput"},fo={Button:"Button",Area:"Area",Text:"Text"},bo={onClick:"onClick",onSuspense:"onSuspense"},ei={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var je=class{constructor(){this.listeners={}}addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];let i=()=>{t(),this.off(e,i)};return this.listeners[e].push(i),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){let i=this.listeners[e]||[];for(let r=i.length;r>0;r--)if(i[r]===t){i.splice(r,1);break}return this}emit(e,...t){let i=this.listeners[e];return i?(i.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return this.rawListeners(e).length}rawListeners(e){return this.listeners[e]||[]}};var _e=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{Lt(e)&&(this.fns.push(e),t&&this.updateFn())};this.removeFn=(e,t=!1)=>{this.fns=this.fns.filter(i=>i!==e),t&&this.updateFn()};this.updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};this.forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};this.requestAnimation=()=>{this.raf||this.forceRequestAnimation()};this.cancelAnimation=()=>{this.raf&&(cancelAnimationFrame(this.raf),this.raf=void 0)};e&&(this.fn=e,this.addFn(e))}release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}};import{ValueSubject as qi}from"@vkontakte/videoplayer-shared/evergreen";var De=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Wi(...this.loaders[e])(t)}};function Wi(...n){return async function(t){let i=[...n];for(;i.length>0;)t=await i.shift()(t);return t}}function pe(n,e,t){return n?{...n,[e]:n[e]?[t,...n[e]]:[t]}:{[e]:[t]}}function He({actions:n,errors:e,chapterId:t,...i}){if(t){let r=n.getManifest();if(r){let o=n.getChapter(r.chapters,t);if(o){let c=n.getMedia(r.media,o.videoId),s=n.getGraph(r.graph,o.id);return c?{...i,actions:n,errors:e,result:{chapter:o,media:c,graph:s}}:{...i,errors:pe(e,He.name,"Could not find media"),actions:n}}}}return{...i,errors:pe(e,He.name,"Could not find chapter"),actions:n}}var ft=(n="",e="")=>{let t=n.split("."),i=e.split("."),r=0;for(let o=0;o<Math.max(t.length,i.length)&&!r;o++)t[o]>i[o]?r=1:t[o]<i[o]?r=-1:r=0;return r};var zi=async n=>{try{let e={},t;if(Ce(n)){t=new URL(n).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(W(n))e=n;else return{};if(!Jt(e))return{};let i=e.metadata.media;if(Ce(i)&&!("media"in e))try{let r;t?r=new URL(i,t).href:(r=new URL(i).href,t=r);let o=await fetch(r);if(!o.ok)throw new Error;e.metadata.media=await o.json()}catch{return Ki(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ii(n){let{manifest:e,manifestURL:t}=await zi(n);if(!e)throw new Error("Failed on fetch");let i=ti(e);return i.media=Qi(i.media,t),delete i.metadata.media,i}function Ue(n,e){if(e)return n.find(t=>t.id===e)}function bt(n,e){return n.edit?.chapters?n.edit.chapters.find(t=>t.id===e):n.view?.chapters?n.view.chapters.find(t=>t.id===e):void 0}function vt(n,e){return n.videos.find(t=>t.id===e)}function Qi(n,e){return{...n,videos:n.videos.map(t=>({...t,variants:t.variants.map(i=>{let r="url"in i?i.url:"",o=Xi(r,e);return{...i,url:o||r}})}))}}function Xi(n="",e){try{return new URL(n,e).href}catch{return""}}function Ki(n){return ft(n,"3.2.0")>=0}var Ge=n=>ge(n)&&!tt(n),H=n=>n.order==="end",We=n=>ge(n.containers)&&!tt(n.containers)&&H(n),ni=(n,e)=>{let t=n*1e3;return Ge(e.controls)&&t<(e.startTime??0)},yt=(n,e)=>{let t=n*1e3;return Ge(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var Z=(n=[])=>n.some(e=>e.action.type==="expect"),Ct=(n=[])=>n.find(e=>e.action.type==="expect"),Zi=n=>n?.length===1,ie=n=>Zi(n)&&$e(n[0]);function ri(n=[],e=1/0,t=[]){return n.filter(({container:i})=>!t.includes(i.container.id)&&Z(i.container.events)&&i.container.endTime===e&&!i.isRemoved)}function ze({gameControllers:n=[],subjectName:e,subjectId:t,execFn:i}){for(let r of n)if(e==="container"&&r.container.container.id===t){i(r),ri(n,r.container.container.endTime,[r.container.container.id]).forEach(c=>{i(c)});break}}var oi=(n,e)=>{let t=T=>e.find(({container:p})=>p.container.id===T)?.container.isRemoved,i=Z(n.events)&&!t(n.id),r=(T,C=!1,p=!1)=>{let l=p?"every":"some";return T.controls[l](m=>{let f=C?T.endTime===n.endTime:!0;return m.events?.[l](b=>b.action?.type===ei.openURI)&&f})},o=T=>T.some(({container:C})=>r(C.container,!0,!1)&&!C.isRemoved),c=T=>T.every(({container:C})=>C.isRemoved?!0:r(C.container,!0,!0)),s=ri(e,n.endTime,[n.id]).length,a=T=>T.controls.some(C=>C.events?.some(p=>p.action?.args?.shouldOpenNow)),h=i||s>0,d=o(e),v=r(n),y=c(e),u=i?!1:s>0,V=a(n);return{isExpectTime:h,hasOtherExpect:s>0,hasOpenURIEvent:d,hasOpenURIEventInCurrentContainer:v,isAllOpenURIEventsValid:y,isExpectEventForCurrentContainer:u,hasShouldOpenNowEvent:V}};var ne=class extends De{constructor(t,i){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new qi(null);this.onError=i,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(t){this.release();let i=await this.exec("manifestLoaders",{actions:{addErrorMessage:pe},result:null,errors:null,source:t});return i.errors&&this.errorHandler(i.errors),this.manifest=await ii(i.result??t),this}async setInitial(){return this.setNext()}async setNext(t=this.manifest?.metadata.initChapterId){if(!t)return this;this.prevChapter$.next(this.chapter);let i=await this.exec("chapterLoaders",He({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:bt,getChapter:Ue,getMedia:vt,getByBranches:this.getByBranches.bind(this),addErrorMessage:pe},result:null,errors:null,chapterId:t}));return i.errors&&this.errorHandler(i.errors),i.result&&(this.chapter=i.result.chapter,this.media=i.result.media,this.graph=i.result.graph),this}errorHandler(t){this.onError(t),console.error("Something went wrong with loaders",{errors:t})}getInitial(){return this.getByChapterId(this.manifest?.metadata.initChapterId)||null}getByChapterId(t=this.manifest?.metadata.initChapterId){if(!t||!this.manifest)return null;let i=Ue(this.manifest.chapters,t);if(i){let r=vt(this.manifest.media,i.videoId),o=bt(this.manifest.graph,i.id);if(r)return{chapter:i,media:r,graph:o}}return null}getBranches(t=this.chapter?.id){if(t===this.chapter?.id)return this.getByBranches(this.chapter?.branches);{let i=Ue(this.manifest?.chapters||[],t);return this.getByBranches(i?.branches)}}getByBranches(t=[]){return t.reduce((i,r)=>{let o=this.getByChapterId(r.chapterId);return o&&i.push(o),i},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter?.id===this.manifest?.metadata.initChapterId}isEndChapter(){return this.chapter?H(this.chapter):!1}};import{Player as Yi}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as It,Tracer as Ji,ValueSubject as en}from"@vkontakte/videoplayer-shared/evergreen";var si=n=>{let e=n.variants.find(t=>t.payload?.type==="vk");if(e&&e.payload){let[t,i]=e.payload.id.split("_");return[t,i]}return[]};function gt(){let n=new Map;function e({listId:o=Math.random().toString(),itemId:c=Math.random().toString(),...s}){let a=n.get(o),h={...s};return a?a[c]=h:n.set(o,{[c]:h}),{listId:o,itemId:c,...s}}function t(o){o.player.destroy(),o.container.remove(),o.subscription.unsubscribe(),o.statistics?.oneStat.destroy(),o.statistics?.statSubscription.unsubscribe()}function i(o,c){let s=n.get(o);if(!s)throw Error("Can't remove. Not find.");if(c){let a=s[c];a&&t(a),delete s[c],Object.keys(s).length||n.delete(o)}else{for(let a of Object.values(s))t(a);n.delete(o)}}function r(){for(let o of n)i(o[0])}return{createPlayer:e,removePlayer:i,map:n,removeAll:r}}function Et(n,e=[]){let t={},i,r=!e.length;for(let o of n.variants)if(!i&&"cover"in o&&(i=o.cover),"url"in o)switch(o.type.toLowerCase()){case"mp4":(r||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[o.standard??"Invariant quality"]:o.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[o.standard??"Invariant quality"]:o.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:o.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:o.url}});break;default:break}return{sources:t,thumbUrl:i,title:n.title??""}}var he=(n,e)=>{let t=n.info.currentQuality$.getValue(),i=n.info.availableQualities$.getValue();t!==e&&i.includes(e)&&(n.setQuality(e),n.setAutoQuality(!1))};var tn=2;function Tt(n){let e=gt(),t=new It,i={},r=null,o=!1,c,s=new en(null);n&&a(n);function a(C){r=C}function h(C,p,l){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let f=(e.map.get(C)??{})[p];if(f){i={chapterId:l,listId:C,itemId:p,...f};let b=i.player;i.subscription.add(b.info.currentQuality$.subscribe(g=>{let A=b.info.position$.getValue(),F=b.info.isAutoQualityEnabled$.getValue();if(!(!g||!A||F))for(let E of e.map)Object.values(E[1]).forEach(({player:R})=>{he(R,g)})})).add(b.events.started$.subscribe(()=>{d(p)})),f.container.remove(),r.setPlayer(f.player),o||(r.init(),o=!0),s.next({player:i.player,config:i.config,statistics:i.statistics});return}throw Error("Can't set. Not find.")}async function d(C){if(!r)throw Error("need to set interactive controller");if(X(i)||C!==i.itemId)return;let p=r.getChapterBranches(),l=new Set;for(let m of p)l.has(m.media.id)||(await y({media:m.media,chapterId:m.chapter.id,setAsActive:!1,title:m.chapter.label}),l.add(m.media.id))}async function v({chapter:{id:C},manifestVideo:p}){if(X(i)||!r)return;let l=i.player.info.muted$.getValue(),m=i.player.info.currentQuality$.getValue(),f=i.player.info.isAutoQualityEnabled$.getValue(),b=i.player.info.volume$.getValue(),g=i.player.info.currentPlaybackRate$.getValue(),A=!f,F=!1;for(let E of e.map)if(E[0]===p.id&&!r.state.isReplay$.getValue()){let R=Object.keys(E[1]);for(let M of R)M===i.itemId?(R.length<tn||(F=!0),e.removePlayer(E[0],M)):(F=!0,h(E[0],M,C),A?he(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(b),i.player.setMuted(l),i.player.setPlaybackRate(g))}else e.removePlayer(E[0]);F||(await y({media:p,chapterId:C,setAsActive:!0,playbackRate:g}),A?he(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(b),i.player.setMuted(l))}async function y({media:C,chapterId:p,prefetch:l=!0,setAsActive:m=!0,autoplay:f=!1,preferredExt:b,title:g,playbackRate:A}){let F=Math.random().toString(),E=document.createElement("div");c.append(E);let R;if(r?.options?.vkVideoLoader){let ve=si(C);ve.length&&(R=await r.options.vkVideoLoader(...ve))}let M=r?.options?.coreConfig||void 0,_={...M,configName:[...M?.configName??[],"interactive"]},Q={container:E,...R?.videos?.[0]||{sources:Et(C,b).sources},title:g,failoverHosts:R?.failoverHosts||[]},B=new Yi(_,Ji.createRootTracer());B.initVideo(Q);let q=null;if(R?.videos&&r?.options.createOneStat){let ve=R.videos[0],Ye=r.options.createOneStat(ve),Vt=new It;Ye&&(Vt.add(Ye.attachTo(B)),q={oneStat:Ye,statSubscription:Vt})}let Rt=new It,Vi=i?.player?.info.isAutoQualityEnabled$.getValue();Rt.add(B.events.canplay$.subscribe(function(){Vi||he(B,i.player.info.currentQuality$.getValue()),A&&B.setPlaybackRate(A)}));let Y=e.createPlayer({listId:C.id,itemId:F,player:B,container:E,sources:Et(C,b).sources,config:Q,subscription:Rt,statistics:q});return m&&h(C.id,Y.itemId,p),f&&Y.player.play(),l&&!f&&Y.player.prepare(),{player:Y.player,config:Y.config,statistics:Y.statistics}}function u(){V(),r=null,c.remove()}function V(){t.unsubscribe(),e.removeAll(),i={},o=!1}async function T(){if(!r)throw Error("need to set interactive controller");V(),c=document.createElement("div");let{media:C,chapter:p}=r.getCurrentChapter();C&&p?(t.add(r.events.chapterChanged$.subscribe(v)),await y({media:C,chapterId:p.id,title:p.label})):console.error("not found")}return{...e,init:T,setInteractiveController:a,createPlayer:y,removeAll:u,getActivePlayer:function(){return i},activePlayerChanged:s}}var I={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},me={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},k={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as nn}from"@vkontakte/videoplayer-shared/evergreen";function xt(n){return function(...t){return n(...t.reverse())}}function de(n,...e){return(...t)=>W(e[0])&&W(t[0])?n({...e[0],...t[0]}):n(...e,...t)}var Qe=class{constructor({player:e,container:t,branches:i,selectBranches:r,interactiveEvents:o,globalEvents:c,globalEventEmitter:s,getContainerEventState:a,permanentTextControls:h,interactiveTimeOpenUri:d,disabledControls$:v,onRemove:y,onError:u}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(Z(this.container.container.events)&&this.gameState===3||this.selectBranches.state.isExpect||(this.gameState!==2&&this.container.hide?.(),this.emitContainerVisibilityEvent(!1)))})};this.show=()=>{if(this.gameState!==2||this.isSelectedControlEvent)return;if(this.container.getElement()){let{hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState();if(this.container.show?.(),this.interactiveTimeOpenUri&&t)return;this.emitContainerVisibilityEvent(!0,!1)}else{let t={isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.emitContainerVisibilityEvent(!1)},onEvent:(o,c)=>{let{isExpectTime:s,hasOtherExpect:a,hasOpenURIEvent:h,hasOpenURIEventInCurrentContainer:d,isAllOpenURIEventsValid:v,hasShouldOpenNowEvent:y}=this.getContainerEventState(),u=this.interactiveTimeOpenUri&&!d,V=this.interactiveTimeOpenUri&&d;if((!this.interactiveTimeOpenUri||u)&&(this.isSelectedControlEvent=!0),o!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||u)){if(this.interactiveTimeOpenUri){let T=!a&&!v&&d;T&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:T})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&h&&this.gameState!==5){if(V){let C=((p,l,m,f)=>!p&&!l&&m||p&&!l&&m&&!f||p&&!l&&m&&f)(s,a,v,this.isSelectedContainerEvent);this.fakeRemoveView(C)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!s||!a||!y)&&(this.selectBranches.stopExpect(),c())}},isEOV:()=>this.gameState===4},i=de(this.selectBranches.onControlEvent,t),r=(this.player?.info.duration$.getValue()??1/0)*1e3;this.container.createView({eventCallback:i,videoDurationMs:r}),this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let e=this.player.experimental.element$.getValue(),i=e instanceof HTMLVideoElement?e.readyState:void 0,r=[6,5];if(!i||r.includes(this.gameState)&&!this.isPermanentText)return;let o=this.player.getExactTime();if(ni(o,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(yt(o,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let h=this.gameState;this.gameState=3,h===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:h}=this.getContainerEventState(),d=this.selectBranches.state.isExpect,v=this.interactiveTimeOpenUri&&h;if(v&&!d){let y=this.container.getElement();y&&(y.style.visibility!=="hidden"&&this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView())}!this.isPermanentText&&!v&&this.removeView()}let c=yt(o,this.container.container),s=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],a={subjectId:this.container.container.id,subjectName:"container",range:s,currentTime:o,isInteractiveTime:c};this.container.onProgress(o*1e3,c),this.globalEventEmitter.emit(I.eachTick,a),this.globalEvents.eachTick$.next(a)};this.container=t,this.branches=i,this.selectBranches=r,this.subscription=new nn,this.player=e,this.interactiveEvents=o,this.getContainerEventState=a,this.isPermanentText=h&&ie(t.container.controls),this.interactiveTimeOpenUri=d,this.disabledControls$=v,this.onRemove=y,this.globalEventEmitter=s,this.gameState=0,this.globalEvents=c,this.onError=u,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(I.interactives,{subjectId:this.container.container.id,subjectName:"container",type:k.visibility,visibility:e,isFirst:t}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e,isFirst:t})):(this.globalEventEmitter.emit(I.interactives,{subjectId:this.container.container.id,subjectName:"container",type:k.visibility,visibility:!1}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e}))}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(e=>{e?this.container.disable?.():this.container.enable?.()})),this.subscription.add(this.container.error$.subscribe(this.onError))}selectContainerEvent(e=!1){let{isExpectEventForCurrentContainer:t}=this.getContainerEventState();this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime??1/0,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,!t&&!this.container.isRemoved&&this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime??1/0))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);let{isExpectTime:e,hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState(),i=this.interactiveTimeOpenUri?e||t:Z(this.container.container.events)||e;(this.isSelectedControlEvent||!i)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.emitContainerVisibilityEvent(!1)}onResize(e){this.container.onResize(e)}reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=1}removeView(){this.container.removeView(),this.globalEventEmitter.emit(I.interactives,{subjectId:this.container.container.id,subjectName:"container",type:k.containerRemoved,visibility:!1}),this.globalEvents.interactiveContainerRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-removed"}),this.gameState=5,this.onRemove?.()}fakeRemoveView(e=!1){this.container.isRemoved||this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:e}),this.container.fakeRemove()}updateControlsShadowStyles(e){this.container.updateControlsShadowStyles(e)}toggleBlinkAnimation(e){this.container.toggleBlinkAnimation(e)}destroy(){this.reset(),this.removeView(),this.gameState=6,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}};var li=(n=[])=>n.reduce((e,t,i)=>{let r=(t?.controls??[]).filter(o=>!$e(o));if(Ge(r)){let o=[t.startTime??0,t.endTime??1/0],c={id:t.id,isRemoved:!1};if(!i)e.push({subjects:[c],range:o});else{let s=[],a=-1/0,h=1/0,d=[],v=[];for(let y=0;y<e.length;y++){let u=e[y];if(v.push(...u.subjects),u.range[0]<h&&(h=u.range[0]),u.range[1]>a&&(a=u.range[1]),o[0]>=u.range[0]&&o[1]<=u.range[1])return e[y].subjects.push(c),e;o[0]<u.range[0]&&o[1]>u.range[0]&&(s.push(y),d=d.concat(u.subjects)),o[0]>=u.range[0]&&o[0]<=u.range[1]&&(s.push(y),d=d.concat(u.subjects),o[0]=u.range[0]),o[1]>=u.range[0]&&o[1]<=u.range[1]&&(s.push(y),d=d.concat(u.subjects),o[1]=u.range[1])}if(v.push(c),o[0]<=h&&o[1]>=a)return[{subjects:v,range:o}];s.length&&s.reverse().forEach(y=>{e.splice(y,1)}),e.push({subjects:d.concat([c]),range:o})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function ci(){let n={};function e(){for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&delete n[s]}function t(s){let a={};for(let h in n)+h<=s&&(a[h]=n[h]);return a}function i(s){let a={};for(let h in n)+h>=s&&(a[h]=n[h]);return a}function r({timestamp:s,priority:a,initiator:h}){if(et(s)){let d=n[s]??null;if(d&&a&&re(a,!0)){let v={},y=d[a];return y&&(v={...v,...y}),v=X(v)?null:v,v&&re(h,!0)?v[h]??null:v}return d}return null}function o({timestamp:s,priority:a,initiator:h}){if(et(s))if(n[s]){if(a&&re(a,!0))if(n[s][a]){if(h&&re(h,!0))if(n[s][a][h]){if(delete n[s][a][h],!X(n[s][a]))return!0}else return!1;if(delete n[s][a],!X(n[s]))return!0}else return!1;return delete n[s]}else return!1;return!1}function c({timestamp:s,priority:a,initiator:h,...d}){n[s]?.[a]?.[h]?n[s][a][h].push({...d}):n[s]?.[a]?n[s][a]={...n[s][a],[h]:[{...d}]}:n[s]?n[s]={...n[s],[a]:{[h]:[{...d}]}}:n[s]={[a]:{[h]:[{...d}]}}}return{map:n,remove:o,add:c,removeAll:e,get:r,getLte:t,getGte:i}}var rn=[x.expect,x.setNextBranch],on=1/0;function pi(n,e){let t=n,i,r=sn(e),o=ci(),c,s=()=>{u(),p()},a=l=>{o.add.call(void 0,l),V()},h=(l=[])=>{for(let m of l)if(m.action(),rn.includes(m.actionType))break},d=(l=1/0)=>{let m=Xe(o.get({timestamp:l,priority:"control"})??{}),f=Xe(o.get({timestamp:l,priority:"container"})??{}),b=Xe(o.get({timestamp:l,priority:"chapter"})??{});return[...m,...f,...b]},v=l=>{r.isReady(l)&&h(d(l))},y=()=>{h([...Xe(o.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{i&&(c?.unsubscribe(),i=void 0)},V=()=>{i||(i=()=>setTimeout(()=>{v(1/0)}),c=t.events.ended$.subscribe(i))},T=l=>{u(),t=l},C=l=>{l.priority==="container"&&r.resetCalled(l.timestamp),o.remove(l)},p=()=>{r.release(),o.removeAll()};return{setPlayer:T,add:a,remove:C,exec:v,execEndOfVideo:y,listen:V,unlisten:u,release:s,containersEventsCallState:r,getPreparedToExecActions:d}}function sn(n){let e=new Map;return{setCalled:({timestamp:s,id:a})=>{let h=e.get(s);h&&h[a]!==void 0&&(h[a]=!0)},setData:(s=[])=>{for(let a of s){let h=a.endTime??on,d=e.get(h);e.set(h,{...d,[a.id]:!1})}},resetCalled:s=>{let a=e.get(s);if(a)for(let h in a)a[h]=!1},isReady:s=>{let a=e.get(s);if(!a)return!0;let h=Object.values(a);return n?h.some(v=>v):!h.some(v=>!v)},release:()=>e.clear()}}function Xe(n){return Object.values(n).flat().sort(e=>e.actionType===x.expect?-1:1)}var hi={videoContentHeight:0,videoContentWidth:0},mi=n=>{let{height:e,width:t}=n.info.intrinsicVideoSize$.getValue()||{};if(!(e&&t))return hi;let{clientHeight:i,clientWidth:r}=n.experimental.element$.getValue()||{};if(!(i&&r))return hi;let o=e/t,c=i/r,s,a;return c>o?(a=r,s=r*o):c<o?(a=i/o,s=i):(a=r,s=i),{videoContentWidth:a,videoContentHeight:s}};var an=250;function di(n){let e,t=new ResizeObserver(s=>{o(s),e=o.bind(null,s)});function i(s){let{parentElement:a,player:h}=n();if(a&&h){let{videoContentWidth:d,videoContentHeight:v}=mi(h);a.style.setProperty("--interactive-content-width",`${d}px`),a.style.setProperty("--interactive-content-height",`${v}px`),a.style.setProperty("--interactive-width",`${s[0].contentRect.width}px`),a.style.setProperty("--interactive-height",`${s[0].contentRect.height}px`)}}function r(){let{parentElement:s}=n();s.removeAttribute("style")}let o=ae(s=>{let{fns:a=[]}=n();i(s);for(let h of a)h()},an);function c(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:c}}var ln=n=>Math.floor(Math.random()*n),fi=n=>{let e=n.length,t=1/0,i=null;for(;e--;){let r=n[e],o=r.weight??1;o<t&&(t=o,i=r)}return i},bi=n=>{let e=n.length,t=-1/0,i=null;for(;e--;){let r=n[e],o=r.weight??0;o>t&&(t=o,i=r)}return i};var vi=n=>{let e=n.length,t=ln(e);return n[t]},ui=1,yi=n=>{let e=0;for(let i=0;i<n.length;++i)e+=n[i].weight??ui;let t=Math.random()*e;e=0;for(let i=0;i<n.length-1;++i)if(e+=n[i].weight??ui,e>=t)return n[i];return n[n.length-1]};var Ci={shouldOpenNow:!0,isDetachContainer:!0},gi="after-expect",At=(n,e=!1)=>({...n,args:e?{...n.args,...Ci}:{...Ci,...n.args}}),Ei=({globalEventEmitter:n,globalEvents:e,player:t,interactiveEvents:i})=>{let r={isExpect:!1},o=()=>{r.isExpect&&(r.isExpect=!1)},c=({action:p,controlType:l,controlId:m,containerId:f,branches:b=[],onEvent:g,isEOV:A=()=>!1,isDisabled:F=()=>!1})=>{let E=At(p,A()),R={timestamp:1/0,priority:"control",initiator:m,actionType:E.type},M=F(),_=n.emit.bind(n,I.interactives,{subjectId:m,subjectType:l,subjectName:"control",type:M?k.actionChoiceCanceled:k.actionChoice,actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:f,...E.args}}),Q=()=>{e.interactiveActionChoice$.next({subjectId:m,subjectType:l,subjectName:"control",type:M?"action-choice-canceled":"action-choice",actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:f,...E.args}})};if(M){_(),Q();return}switch(E.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let B=b.find(q=>q.id===E.args.branchId);if(!B)return;g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?T({subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}}):i.add({...R,action:T.bind(null,{subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}})});return}case x.continuePlayback.trim().toLowerCase():{g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?V({subjectId:m,subjectName:"control",subjectType:l,action:p}):i.add({...R,action:V.bind(null,{subjectId:m,subjectName:"control",subjectType:l,action:p})});return}case x.openURI.trim().toLowerCase():{g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?C({subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{URI:p.args.uri}}):i.add({...R,action:C.bind(null,{subjectId:m,subjectName:"control",subjectType:l,action:E,payload:{URI:p.args.uri}})});return}default:{let B="Unexpected control event",q=new P(1,1,{message:B});d(q,B);return}}},s=({action:p,container:{id:l,endTime:m},branches:f=[],isEOV:b=!1,autoSelected:g=!1})=>{let A=At(p,b),F={timestamp:!A.args.shouldOpenNow||b?1/0:m??1/0,priority:"container",initiator:l,actionType:A.type},E=n.emit.bind(n,I.interactives,{subjectId:l,subjectName:"container",type:k.actionChoice,actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}}),R=()=>{e.interactiveActionChoice$.next({subjectId:l,subjectName:"container",type:"action-choice",actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}})};switch(A.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let M=f.find(_=>_.id===A.args.branchId);if(!M)return;E(),R(),i.add({...F,action:T.bind(null,{subjectId:l,subjectName:"container",action:A,payload:{chapterId:M.chapterId,autoSelect:g}})});return}case x.setMaxWeightBranch.trim().toLowerCase():return;case x.setMinWeightBranch.trim().toLowerCase():return;case x.setRandomBranch.trim().toLowerCase():return;case x.setWeightlessRandomBranch.trim().toLowerCase():return;case x.continuePlayback.trim().toLowerCase():{E(),R(),i.add({...F,action:V.bind(null,{subjectId:l,subjectName:"container",action:A})});return}case x.openURI.trim().toLowerCase():{E(),R(),i.add({...F,action:C.bind(null,{subjectId:l,subjectName:"container",action:A,payload:{URI:p.args.uri}})});return}default:{let M="Unexpected container event",_=new P(1,1,{message:M});d(_,M);return}}};function a({container:p,branches:l,isEOV:m=!1}){let f=Ct(p.events);if(f){let b=At(f.action,m);n.emit(I.interactives,{subjectId:p.id,subjectName:"container",type:k.actionChoice,actionType:b.type,payload:{invokeImmediately:b.args.shouldOpenNow,...b.args}}),e.interactiveActionChoice$.next({subjectId:p.id,subjectName:"container",type:"action-choice",actionType:b.type,payload:{invokeImmediately:b.args.shouldOpenNow,...b.args}}),i.add({timestamp:m?1/0:p.endTime??1/0,priority:"container",initiator:p.id,actionType:x.expect,action:y.bind(null,{subjectId:p.id,subjectName:"container"})}),r.isExpect=!0}else for(let b of p.events??[])s({action:b.action,container:p,branches:l,isEOV:m})}let h=({chapterId:p,action:l,branches:m=[]})=>{let f=n.emit.bind(n,I.interactives,{subjectId:p,subjectName:"chapter",type:k.actionChoice,actionType:l.type,payload:l.args}),b=()=>{e.interactiveActionChoice$.next({subjectId:p,subjectName:"chapter",type:"action-choice",actionType:l.type,payload:l.args})};switch(l.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let g=m.find(A=>A.id===l.args.branchId);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setWeightlessRandomBranch.trim().toLowerCase():{let g=vi(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setRandomBranch.trim().toLowerCase():{let g=yi(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setMaxWeightBranch.trim().toLowerCase():{let g=bi(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setMinWeightBranch.trim().toLowerCase():{let g=fi(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.continuePlayback.trim().toLowerCase():return f(),b(),V.bind(null,{subjectId:p,subjectName:"chapter",action:l});case x.openURI.trim().toLowerCase():return f(),b(),C.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{URI:l.args.uri}});default:{let g="Unexpected chapter event",A=new P(1,1,{message:g});d(A,g);return}}};function d(p,l){console.error(l),e.error$.next(p),n.emit(I.errors,p)}function v(p){let l=Ct(p.events);if(l){if(H(p))return;n.emit(I.interactives,{subjectId:p.id,subjectName:"chapter",type:k.actionChoice,actionType:l.action.type,payload:l.action.args}),e.interactiveActionChoice$.next({subjectId:p.id,subjectName:"chapter",type:"action-choice",actionType:l.action.type,payload:l.action.args}),i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:x.expect,action:y.bind(null,{subjectId:p.id,subjectName:"chapter"})})}else p.events?.forEach(m=>{let f=h({chapterId:p.id,action:m.action,branches:p.branches});f&&i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:m.action.type,action:f})})}let y=({subjectId:p,subjectName:l})=>{t.pause(),n.emit(I.interactives,{subjectId:p,subjectName:l,type:k.actionExecution,actionType:x.expect}),e.interactiveActionExecution$.next({subjectId:p,subjectName:l,type:"action-execution",actionType:x.expect})},u=({subjectId:p,subjectName:l})=>{t.info.isEnded$.getValue()?i.execEndOfVideo():t.play(),n.emit(I.interactives,{subjectId:p,subjectName:l,type:k.actionExecution,actionType:gi}),e.interactiveActionExecution$.next({subjectId:p,subjectName:l,type:"action-execution",actionType:gi})},V=({subjectId:p,subjectName:l,subjectType:m,action:f})=>{n.emit(I.interactives,{subjectId:p,subjectName:l,subjectType:m,type:k.actionExecution,actionType:f.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:l,subjectType:m,type:"action-execution",actionType:f.type})},T=({subjectId:p,subjectName:l,subjectType:m,action:f,payload:b})=>{b.behaviour="change-chapter",n.emit(I.interactives,{subjectId:p,subjectName:l,subjectType:m,type:k.actionExecution,actionType:f.type,payload:b}),e.interactiveActionExecution$.next({subjectId:p,subjectName:l,subjectType:m,type:"action-execution",actionType:f.type,payload:b})},C=({subjectId:p,subjectName:l,subjectType:m,action:f,payload:b})=>{if(!b.URI)return;let g=window.open(b.URI,"_blank","noopener,noreferrer");g&&(g.opener=null),n.emit(I.interactives,{subjectId:p,subjectName:l,subjectType:m,type:k.actionExecution,actionType:f.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:l,subjectType:m,type:"action-execution",actionType:f.type})};return{onControlEvent:c,onContainerEvent:s,onChapterEvent:h,onExpectEvent:y,expectEventHandler:u,setManifestChapterEvents:v,setManifestContainerEvents:a,stopExpect:o,state:r}};import{Subscription as dn,Subject as wt,ValueSubject as ue}from"@vkontakte/videoplayer-shared/evergreen";var St=(n,e)=>{let t={};return n.map(i=>{if(!t[i]){let r=e.chapters.find(c=>c.id===i);if(!r)return null;let o=e.media.videos.find(c=>r.videoId===c.id);if(!o)return null;t[i]=Ii(o)}return t[i]}).filter(Boolean)},pn=n=>{for(let e of n.variants)if(hn(e)&&e.payload)return e.payload.id},hn=n=>!!(n.type==="custom"&&n.payload&&n.payload.type==="vk"),Ii=n=>{let e=pn(n);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},mn=(n,e)=>{for(let t of n.media.videos)if(e===Ii(t)){for(let i of n.chapters)if(i.videoId===t.id)return i.id;return}},Ti=(n,e)=>n.reduce((t,i)=>{let r=mn(e,i);return r?[...t,r]:t},[]);var fe=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:i,historyApi:r,settings:o}){this.state={history$:new ue([]),hasPrevChapter$:new ue(!1),prevChapter$:new ue(null),isInitialChapter$:new ue(!1),isGoBackLimited$:new ue(!1)};this.#i=null;this.#s=!1;this.#e=null;this.#p=null;this.events={inited$:new wt,destroyed$:new wt,error$:new wt};this.#n=null;this.#r=null;this.#t=null;this.#a=new dn;this.#l=!1;this.#c=0;this.#n=t,this.#t=e,this.#r=i,this.#i=r,this.#o=o,this.state.history$&&this.#a&&this.#a?.add(this.state.history$.subscribe(c=>{this.state.prevChapter$.next(c.at(-2)||null),this.state.hasPrevChapter$.next(c.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#e?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#c===this.#o.maxLength-1)}))}#i;#o;#s;#e;#p;#n;#r;#t;#a;#l;#c;async setManifest(e){if(!this.#r||!this.#t)return;this.#e=e,await this.getProjectHistory();let t=this.getInitialChapterId();await this.#r.setChapter({chapterId:t,pushToHistory:!1}),this.#s||(this.#s=!0,this.events.inited$.next({initChapterId:t}))}get inited(){return this.#s}async updateHistory(e,t=!0){if(!this.#e)return;this.#l?(this.#l=!1,this.#c++):this.#c=0;let i=this.#e,r=e.length-this.#o.maxLength,o=r>0?e.slice(r):e,c=St(o,i);if(this.#p=c,this.state.history$.next(o),!(!t||!this.#i||!this.#n))try{await this.#i.save(this.#n,c)}catch{let a=new P(1,5,"Unable to save interactive history");this.events.error$.next(a),this.#t?.emit(I.errors,a)}}async goBack(){if(!this.state||!this.#r){let i=new P(1,5,"Unable to save interactive history");return this.events.error$.next(i),this.#t?.emit(I.errors,i)}this.#l=!0;let e=this.state.history$.getValue().slice(0,-1),t=e.pop();this.state.history$.next(e),await this.#r.setChapter({chapterId:t,playPrev:!0})}async getProjectHistory(){if(!this.#e||!this.#n)return;let e=this.#e,t=[this.getInitialVideoId()];if(this.#i)try{let r=await this.#i.get(this.#n);r.length&&(t=r)}catch{let o=new P(1,5,"Error while trying to fetch data");this.events.error$.next(o),this.#t?.emit(I.errors,o)}let i=Ti(t,e);this.state.history$.next(i)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#o.initChapterId||this.#e?.metadata.initChapterId}getInitialVideoId(){if(this.#e){let e=this.getInitialChapterId();return St([e],this.#e).pop()}return null}destroy(){this.#n=null,this.#i=null,this.#r=null,this.#a?.unsubscribe(),this.#a=null,this.#s=!1,this.#t?.emit(I.historyDestroyed),this.events.destroyed$.next(),this.#t=null}};var Ke=class{constructor(){this._prevSizeId=0;this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){let e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;let t=e.data,i=t.length;for(let r=3;r<i;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){let i=e.width+e.height;if(this._prevSizeId===i)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=i}async save(){let e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}};var Ze=class{constructor({parentElement:e,endOffsetMs:t=250,onError:i}){this.currentVideoDurationMs=1/0;this._containerTimeFrameShouldReceived=!1;this._endTimeFrameReceived=!1;this._shouldCallSkip=!1;this.onEachTick=e=>{let t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,i=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(i)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};this.onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
7
7
  position: absolute;
8
8
  top: 0;
9
9
  left: 0;
@@ -11,12 +11,12 @@ var Me="1.0.39-dev.6edf3cda.0";import{Subject as Di,Subscription as Hi}from"@vko
11
11
  height: var(--interactive-height);
12
12
  background-color: var(--black);
13
13
  visibility: hidden;
14
- `,this.lastFrameCanvas=new Kt,this.endOffsetMs=e,this._callbacks={onError:i},this.lastFrameCanvas.rootElement.style.cssText=`
14
+ `,this.lastFrameCanvas=new Ke,this.endOffsetMs=t,this._callbacks={onError:i},this.lastFrameCanvas.rootElement.style.cssText=`
15
15
  position: absolute;
16
16
  top: 50%;
17
17
  left: 50%;
18
18
  transform: translate(-50%, -50%);
19
- `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),t.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(t){this.currentVideoDurationMs=t}setVideoElement(t){this.lastFrameCanvas.setCanvasImageSource(t)}setCurrentChapter(t){this.currentChapter=t}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(t=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(t=!1);let e=getComputedStyle(this.rootElement),i={width:parseInt(e.getPropertyValue("--interactive-content-width"),10),height:parseInt(e.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(i,t)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(t){return this.currentVideoDurationMs&&t>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(t){if(this.currentChapter)return this.currentChapter.containers.some(e=>e.controls?.length&&t>=(e.startTime??0)&&t<=Math.min(e.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(t){this._callbacks?.onError?.(t)}};function xi(n=0){return new Promise(t=>{setTimeout(()=>{t(0)},n)})}var Ai=`/* interactive-container */
19
+ `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);let t=getComputedStyle(this.rootElement),i={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(i,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}};function xi(n=0){return new Promise(e=>{setTimeout(()=>{e(0)},n)})}var Ai=`/* interactive-container */
20
20
  .interactive-container {
21
21
  opacity: 1;
22
22
  visibility: visible;
@@ -251,4 +251,4 @@ var Me="1.0.39-dev.6edf3cda.0";import{Subject as Di,Subscription as Hi}from"@vko
251
251
  .interactive-control-fill-animation-filler.interactive-control-fill-animation-from-bottom {
252
252
  transform-origin: bottom;
253
253
  }
254
- `;var Si=n=>{let t=document.createElement("style");t.textContent=Ai,n.prepend(t)};import{clientChecker as yn}from"@vkontakte/videoplayer-core/evergreen";var Ri=Object.freeze({lang:bn.RU,loaders:{},graph:!1,initSeamless:!1,lastFrame:!1,permanentTextControls:!0,interactiveTimeOpenUri:!1,config:{historyMaxLength:100,noInteractionEventTimeout:3e4},isTouch:!1,disableTextControlContainerVisibilityEvents:!1,animationsFeatureToggles:{areaControlShadow:!1,controlsExpectTimeBlinkAnimation:!1,controlsTapPlace:!1,controlsFillAnimation:!1}});function Cn(){let n=document.createElement("div");return n.classList.add("interactive-chapter"),n}var qt=class{constructor(t){this.playerSubscriptions=new ke;this.subscriptions=new ke;this.globalEventEmitter=new jt;this.animation=new _t;this.seekToInteractiveController=new ct;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=Cn();this.factories=new Map([["choice",Nt]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new ke;this.graph=null;this.lastFrame=null;this.blinkAnimationRef=null;this.appState=0;this.state={prevChapter$:new j(null),isInitialChapter$:new j(!1),isFirstChapter$:new j(!0),isEndChapter$:new j(!1),isInteractiveExpectation$:new j(!1),isReplay$:new j(!1),calledByInteractive$:new j(!1),lastChapterChangeWasInitiatedByInteractive$:new j(!1),disabledControls$:new j(!1),interactiveRanges$:new j([]),isInteractiveTime$:new j(!1),statistics$:new j(null),isSeekable$:new j(!1)};this.events={noInteraction$:new $,graphVisibilityChanged$:new $,watchAgainIsClicked$:new $,chapterChanged$:new $,playerChanged$:new $,error$:new $,eachTick$:new $,manifestChanged$:new $,interactiveRangeEnded$:new $,interactiveContainerRemoved$:new $,interactiveContainerFakeRemoved$:new $,interactiveActionExecution$:new $,interactiveActionChoice$:new $,interactiveVisibilityChanged$:new $};this.emitErrorEvent=t=>{this.events.error$.next(t),this.globalEventEmitter.emit(T.errors,t)};this.clearHistoryIfEnded=()=>{let t=this.player?.info.isEnded$.getValue(),e=this.state.isInteractiveExpectation$.getValue(),{chapter:i}=this.getCurrentChapter();t&&i&&H(i)&&!e&&this.historyController.updateHistory([]),window.removeEventListener("beforeunload",this.clearHistoryIfEnded)};this.handleSeamlessPlayerChanged=t=>{if(!t)return;let{statistics:e,...i}=t;if(e){let{statSubscription:r,oneStat:o}=e;r.add(o.attachToInteractive(this.getStatEvents())),this.state.statistics$.next(e)}this.state.isReplay$.getValue()&&this.state.isReplay$.next(!1),this.events.playerChanged$.next(i),this.globalEventEmitter.emit(T.playerChanged,i)};this.onPlaybackStarted=()=>{this.resizeManager?.calc(),this.animation.requestAnimation()};this.destroyGameControllers=(t=!0)=>{this.gameControllers.forEach(e=>{!t&&e.isPermanentText||(this.animation.removeFn(e.whilePlaying),e.destroy())})};this.completeInteractiveRange=t=>{let{interactiveRanges$:e}=this.state,r=e.getValue().map(o=>({...o,subjects:o.subjects.filter(c=>c.id!==t)}));e.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};if(this._options={...Ri,...t,config:{...Ri.config,...t.config}},this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation){this.blinkAnimationRef=new St,this.blinkAnimationRef.create();let r=this.blinkAnimationRef.element;r&&this.rootElement.append(r)}this._options.parentElement.append(this.rootElement),this.historyController=new ft({interactiveController:this,globalEventEmitter:this.globalEventEmitter,videoId:this._options.projectInfo?.videoId,historyApi:this._options.historyApi,settings:{maxLength:this._options.config.historyMaxLength,initChapterId:this._options.initChapterId}}),this._options.lastFrame&&(this.lastFrame=new Zt({parentElement:this._options.parentElement,onError:r=>{let o=new P(1,6,r);this.emitErrorEvent(o)}})),Si(this._options.parentElement),this.subscriptions.add(ki(this.rootElement,"mousedown").subscribe(r=>r.stopPropagation())).add(ki(this.rootElement,"mouseup").subscribe(r=>r.stopPropagation())),this.manifestController=new nt(this._options.loaders,r=>{let o=new P(1,3,r);this.emitErrorEvent(o)});let i=[];this._options.lastFrame&&i.push(()=>{this.lastFrame?.updateCanvasDimensions(!0)}),i.push(()=>{let r=this.state.isInteractiveTime$.getValue();for(let o of this.gameControllers)o.onResize(r)}),this.resizeManager=di(()=>({player:this.player,parentElement:this._options.parentElement,fns:i})),this._options.graph&&(this.graph=new lt({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:r=>{this.setChapter({chapterId:r}),this.globalEventEmitter.emit(T.graph,{type:mt.watchAgainClicked,chapterId:r}),this.events.watchAgainIsClicked$.next(r)},onError:r=>{let o=new P(1,2,{message:r});this.emitErrorEvent(o)}})),this.initSubscriptions()}initSubscriptions(){this.playerSubscriptions.add(this.historyController.events.inited$.subscribe(async({videosInfo:t=[]})=>{this._options.initSeamless&&(await this.initSeamless(),this.updateGraphVideosInfo(t))})),this.subscriptions.add(this.events.interactiveContainerRemoved$.subscribe(({subjectId:t})=>{this.completeInteractiveRange(t)})).add(this.events.interactiveContainerFakeRemoved$.subscribe(({subjectId:t,removeAllOpenURI:e})=>{this.handleFakeRemoval(t,e)})).add(this.events.interactiveActionExecution$.subscribe(t=>{if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),t.payload?.behaviour==="change-chapter"){let{chapterId:e}=t.payload;this.setChapter({chapterId:e}),this.state.isFirstChapter$.getValue()&&this.state.isFirstChapter$.next(!1)}else if(t.payload?.behaviour==="change-manifest"){let{manifestURL:e}=t.payload;e&&this.setManifest(e)}t.actionType==="expect"?(this.state.isInteractiveExpectation$.next(!0),this.updateControlsShadowStyles({subjectName:t.subjectName,subjectId:t.subjectId,isExpect:!0}),this.toggleBlinkAnimation({subjectName:t.subjectName,subjectId:t.subjectId,isExpect:!0})):t.actionType==="after-expect"&&(this.state.isInteractiveExpectation$.next(!1),this.updateControlsShadowStyles({subjectName:t.subjectName,subjectId:t.subjectId,isExpect:!1}),this.toggleBlinkAnimation({subjectName:t.subjectName,subjectId:t.subjectId,isExpect:!1}))})).add(this.events.manifestChanged$.subscribe(()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:e,payload:i})=>{t!=="action-choice"||e==="chapter"||"invokeImmediately"in i&&i.invokeImmediately||this.destroyGameControllers(!1)}))}async initSeamless(){this.seamlessController=Te(this),this.seamlessControllerSubs.add(this.seamlessController.activePlayerChanged.subscribe(this.handleSeamlessPlayerChanged)),await this.seamlessController.init()}handlePositionChange(t){(!this.graph||this.graph.isHidden)&&this.checkIfSeekable();let e=t*1e3,r=this.getInteractiveRanges().reverse().find(({range:o})=>e>=o[1]);if(r){let o=r.range.join("-");this.endedRanges.has(o)||(this.endedRanges.add(o),this.globalEventEmitter.emit(T.interactives,{type:k.rangeEnded,payload:r,visibility:!0}),this.events.interactiveRangeEnded$.next({type:"range-ended",payload:r}))}}registerVideoEvents(){this.player&&(window.removeEventListener("beforeunload",this.clearHistoryIfEnded),this.playerSubscriptions.unsubscribe(),window.addEventListener("beforeunload",this.clearHistoryIfEnded),this.playerSubscriptions.add(this.player.events.started$.pipe(vn()).subscribe(this.onPlaybackStarted)).add(this.player.events.playing$.subscribe(this.animation.requestAnimation)).add(this.player.events.willPause$.subscribe(this.animation.cancelAnimation)).add(this.player.info.position$.subscribe(this.handlePositionChange.bind(this))).add(this.manifestController.prevChapter$.subscribe(t=>this.state.prevChapter$.next(t))).add(fn({position:this.player.info.position$,interactiveRanges:this.state.interactiveRanges$,isInteractiveExpectation:this.state.isInteractiveExpectation$}).subscribe(({position:t,interactiveRanges:e,isInteractiveExpectation:i})=>{let r;if(i)r=!0;else{let a=t*1e3;r=!!e.find(({range:[d,v],subjects:y})=>d<a&&a<v&&y.some(u=>!u.isRemoved)&&y.length)}r!==this.state.isInteractiveTime$.getValue()&&this.state.isInteractiveTime$.next(r);let o=!!this.noInteractionTimeout,s=this.player?.info.playbackState$.getValue()==="playing"||i;r&&!o&&s?this.noInteractionTimeout=window.setTimeout(()=>{this.events.noInteraction$.next()},this._options.config.noInteractionEventTimeout):o&&!s&&this.clearNoInteractionTimeout()})),this.playerSubscriptions.add(this.historyController.events.error$.subscribe(this.events.error$)),this._options.lastFrame&&this.playerSubscriptions.add(this.player.info.duration$.subscribe(t=>{this.lastFrame?.setVideoDuration(t*1e3)})).add(this.player.experimental.element$.subscribe(t=>{t&&this.lastFrame?.setVideoElement(t)})).add(this.player.events.firstFrame$.subscribe(()=>{this.lastFrame?.reset(),setTimeout(()=>{this.lastFrame?.hide(),this.lastFrame?.lastFrameCanvas.clear()},50)})).add(this.player.events.seeked$.subscribe(this.lastFrame.onSeek)))}setGameControllers(){let t=this.manifestController.chapter;t&&this.appState===1&&(this.selectBranches?.setManifestChapterEvents(t),this.gameControllers=this.getGameControllers(t),this.interactiveEvents?.containersEventsCallState.setData(t.containers),this.seekToInteractiveController.setContainers(this.gameControllers.map(e=>e.container.container).filter(e=>!it(e.controls))),this._options.lastFrame&&this.animation.addFn(()=>{this.player&&this.lastFrame?.onEachTick(this.player.info.position$.getValue()*1e3)},!0),this.state.interactiveRanges$.next(this.getInteractiveRanges()),this.appState=2)}getGameControllers(t){let e=[];return t.containers.forEach(i=>{let r=i.type.trim().toLowerCase(),c=this.factories.get(r)?.(i,this.rootElement,{isTouch:this._options?.isTouch??!1,features:{controlsExpectTimeBlinkAnimation:this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation,controlsTapPlace:this._options.animationsFeatureToggles?.controlsTapPlace,controlsFillAnimation:this._options.animationsFeatureToggles?.controlsFillAnimation}});if(c&&this.selectBranches&&this.interactiveEvents&&this.player){let s=new Qt({player:this.player,container:c,branches:t.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,getContainerEventState:()=>oi(i,this.gameControllers),permanentTextControls:this._options.permanentTextControls,interactiveTimeOpenUri:this._options.interactiveTimeOpenUri,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(i.id)},onError:this.emitErrorEvent,disableTextControlContainerVisibilityEvents:this.options.disableTextControlContainerVisibilityEvents??!1});this.animation.addFn(s.whilePlaying,!0),e.push(s)}}),e}checkIfSeekable(){if(this.state.isInteractiveExpectation$.getValue()){this.state.isSeekable$.next(!1);return}let e=this.state.isSeekable$.getValue(),i=!!this.seekToInteractiveController.getNextInteractiveTime();(i&&!e||!i&&e)&&this.state.isSeekable$.next(!e)}updateLastEventInfo(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}pushChapterToHistory(t){if(this.updateLastEventInfo(),!this.historyController.inited)return;let e=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),i=this.state.prevChapter$.getValue(),r=(i&&H(i)&&Wt(i))??!1,o=this.manifestController.manifest?.metadata.initChapterId===t,c=this.historyController.state.history$.getValue();if(o||r&&e){this.historyController.updateHistory([t]);return}c.at(-1)!==t&&this.historyController.updateHistory([...c,t])}handleFakeRemoval(t,e){let{interactiveRanges$:i}=this.state,o=i.getValue().map(c=>{let s=c.subjects.some(h=>h.id===t),a=c.subjects.map(h=>e&&s||h.id===t?{...h,isRemoved:!0}:h);return{...c,subjects:a}});i.next(o)}reset(){this.appState===2&&(this.destroyGameControllers(),this.gameControllers=[],this.animation.release(),this.interactiveEvents?.release(),this.appState=1,this.state.isSeekable$.next(!1),this.clearNoInteractionTimeout())}toggleBlinkAnimation(t){if(!this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation)return;let e=(i,r)=>{i.toggleBlinkAnimation(r)};zt({...t,gameControllers:this.gameControllers,execFn:dt(xe(e),t.isExpect)}),t.isExpect&&this.blinkAnimationRef?.restart()}updateControlsShadowStyles(t){if(!this._options.animationsFeatureToggles?.areaControlShadow)return;let e=(i,r)=>{i.updateControlsShadowStyles(r)};t.isExpect?zt({...t,gameControllers:this.gameControllers,execFn:dt(xe(e),!1)}):zt({...t,gameControllers:this.gameControllers,execFn:e})}get options(){return this._options}init(){this.manifestController.chapter&&this._options.parentElement&&this.player&&this._options.fullscreenTargetElement&&this.appState===0&&(this.resizeManager?.resizeObserver.observe(this._options.fullscreenTargetElement),this.registerVideoEvents(),this.appState=1,this.setGameControllers())}async setManifest(t){this.reset(),this.isFirstChapterFetched=!1;let e=await this.manifestController.setManifest(t);if(e.manifest)return this.graph&&this.graph.handleManifestChange(e.manifest),await this.historyController.setManifest(e.manifest),this.events.manifestChanged$.next(e.manifest),this.globalEventEmitter.emit(T.manifestChanged,{manifest:e.manifest}),this.setGameControllers(),e.manifest}setPlayer(t){this.reset(),this.player=t,this.seekToInteractiveController.setPlayer(this.player),this.interactiveEvents?this.interactiveEvents.setPlayer(this.player):this.interactiveEvents=pi(this.player,this._options.interactiveTimeOpenUri),this.selectBranches=Ei({player:this.player,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter}),this.appState===1&&(this.registerVideoEvents(),this.setGameControllers())}async setChapter({chapterId:t,pushToHistory:e=!0,playPrev:i=!1}={}){this.reset(),this.lastFrame&&this.isFirstChapterFetched&&(this.lastFrame.draw(),this.lastFrame.show()),this.lastFrame&&yn.browser.isSafari&&await xi(35);let r=!i&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===t;this.state.isReplay$.next(r);let{chapter:o,media:c,graph:s}=await(t?this.manifestController.setNext(t):this.manifestController.setInitial());(!t||r)&&this.state.isFirstChapter$.next(!0),!(!o||!c)&&(e&&this.pushChapterToHistory(o.id),this.state.isInitialChapter$.next(this.manifestController.isInitialChapter()),this.state.isEndChapter$.next(this.manifestController.isEndChapter()),this.graph&&this.graph.handleChapterChange(o),this.lastFrame?.setCurrentChapter(o),this.events.chapterChanged$.next({chapter:o,manifestVideo:c}),this.globalEventEmitter.emit(T.chapterChanged,{chapter:o,media:c,graph:s}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new wi(t=>{this.subscriptions.add(this.events.graphVisibilityChanged$.subscribe(e=>{t.next(e?bt.GRAPH_SHOW:bt.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{t.next(bt.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:e,subjectName:i,subjectType:r})=>{e!=="action-choice"||i!=="control"||(r==="Button"&&t.next(bt.NEXT_BUTTON),r==="Area"&&t.next(bt.NEXT_AREA))}))}),nextMovie$:new wi(t=>{this.events.playerChanged$.subscribe(({config:e})=>{e?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&t.next(e.unitedVideoId)})})}}async toggleGraphView(t=!0){this.graph&&(t?(await this.graph.show(),this.state.isSeekable$.next(!1)):(this.graph.hide(),this.checkIfSeekable()),this.globalEventEmitter.emit(T.graph,{type:mt.visibility,visibility:t}),this.events.graphVisibilityChanged$.next(t))}setVisitedChapters(t){Array.isArray(t)&&this.graph?.setVisitedChapters(t)}updateGraphVideosInfo(t){Array.isArray(t)&&this.graph?.updateVideosInfo(t)}deadEndCheck(){return!(this.interactiveEvents?.getPreparedToExecActions()||[]).some(i=>i.actionType===x.setNextBranch)}allControlsAreRemoved(){return!this.gameControllers.some(e=>!e.container.isRemoved)}isEndedExpectation(){if(!this.player||!this.gameControllers)return!1;let t=this.player.info.position$.getValue(),e=this.player.info.duration$.getValue();return t===e&&this.gameControllers.some(i=>{let r=i.container.container;return!i.container.isRemoved&&r.endTime===null&&Z(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(t){this.state.disabledControls$.next(t)}isSupport(t=this.manifestController.manifest){return!!t&&Ft(t.metadata.version)}getInitialVideoInfo(){return{videoId:this.historyController.getInitialVideoId(),chapterId:this.historyController.getInitialChapterId()}}getHistoryState(){return this.historyController.state}getIsSeekable(){return this.state.isSeekable$}getInteractiveRanges(){return li(this.manifestController.chapter?.containers)}getNextInteractiveStartTime(t){return this.seekToInteractiveController.getNextInteractiveTime(t)}getChapterBranches(t){return this.manifestController.getBranches(t)}getCurrentChapter(){return this.manifestController.getCurrent()}getCurrentManifest(){return this.manifestController.manifest}on(t,e){return this.globalEventEmitter.on(t,e),this}off(t,e){return this.globalEventEmitter.off(t,e),this}once(t,e){return this.globalEventEmitter.once(t,e),this}destroy(){this.clearHistoryIfEnded(),this.blinkAnimationRef?.destroy(),this.destroyGameControllers(),this.gameControllers=[],this.graph?.destroy(),this.seamlessControllerSubs.unsubscribe(),this.seamlessController?.removeAll(),this.resizeManager?.release(),this.animation.release(),this.interactiveEvents?.release(),this.manifestController.release(),this.playerSubscriptions.unsubscribe(),this.subscriptions.unsubscribe(),this.globalEventEmitter.reset(),this.lastFrame?.destroy(),this.rootElement.remove(),this.historyController.destroy(),this.isFirstChapterFetched=!1,this.appState=3}};var gn={Container:J,createChoiceContainer:Nt,createAreaControl:kt,createButtonControl:Lt,classnamesPrefix:Ne};var Sa={version:Me};export{go as ContainerTypes,Bt as ControlTypes,P as CustomError,T as EVENT_NAMES,x as EventActionTypes,Eo as EventTypes,qt as Interactives,nt as ManifestController,Sa as SDKInfo,Se as chapterIdsToVKVideoIds,fe as compareVersions,uo as containerTypes,fo as controlTypes,ti as eventActionTypes,bo as eventTypes,mn as getChapterIdByVkVideoId,Ii as getVKVideoIdByMedia,pn as getVideoRawIdByMedia,mt as graphEventTypes,Wt as hasEndTemplate,k as interactivesEventTypes,mo as isAreaControl,ho as isButtonControl,H as isLastChapter,it as isOneTextCtrlContainer,Ft as isSupportedManifest,$t as isTextControl,hn as isVKVariantItem,Je as isValidManifest,ei as migrateManifestToLatestVersion,gn as utils,Ti as vkVideoIdsToChapterIds};
254
+ `;var Si=n=>{let e=document.createElement("style");e.textContent=Ai,n.prepend(e)};import{clientChecker as yn}from"@vkontakte/videoplayer-core/evergreen";var Ri=Object.freeze({lang:bn.RU,loaders:{},graph:!1,initSeamless:!1,lastFrame:!1,permanentTextControls:!0,interactiveTimeOpenUri:!1,config:{historyMaxLength:100,noInteractionEventTimeout:3e4},isTouch:!1,animationsFeatureToggles:{areaControlShadow:!1,controlsExpectTimeBlinkAnimation:!1,controlsTapPlace:!1,controlsFillAnimation:!1}});function Cn(){let n=document.createElement("div");return n.classList.add("interactive-chapter"),n}var qe=class{constructor(e){this.playerSubscriptions=new kt;this.subscriptions=new kt;this.globalEventEmitter=new je;this.animation=new _e;this.seekToInteractiveController=new ce;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=Cn();this.factories=new Map([["choice",Ne]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new kt;this.graph=null;this.lastFrame=null;this.blinkAnimationRef=null;this.appState=0;this.state={prevChapter$:new j(null),isInitialChapter$:new j(!1),isFirstChapter$:new j(!0),isEndChapter$:new j(!1),isInteractiveExpectation$:new j(!1),isReplay$:new j(!1),calledByInteractive$:new j(!1),lastChapterChangeWasInitiatedByInteractive$:new j(!1),disabledControls$:new j(!1),interactiveRanges$:new j([]),isInteractiveTime$:new j(!1),statistics$:new j(null),isSeekable$:new j(!1)};this.events={noInteraction$:new $,graphVisibilityChanged$:new $,watchAgainIsClicked$:new $,chapterChanged$:new $,playerChanged$:new $,error$:new $,eachTick$:new $,manifestChanged$:new $,interactiveRangeEnded$:new $,interactiveContainerRemoved$:new $,interactiveContainerFakeRemoved$:new $,interactiveActionExecution$:new $,interactiveActionChoice$:new $,interactiveVisibilityChanged$:new $};this.emitErrorEvent=e=>{this.events.error$.next(e),this.globalEventEmitter.emit(I.errors,e)};this.clearHistoryIfEnded=()=>{let e=this.player?.info.isEnded$.getValue(),t=this.state.isInteractiveExpectation$.getValue(),{chapter:i}=this.getCurrentChapter();e&&i&&H(i)&&!t&&this.historyController.updateHistory([]),window.removeEventListener("beforeunload",this.clearHistoryIfEnded)};this.handleSeamlessPlayerChanged=e=>{if(!e)return;let{statistics:t,...i}=e;if(t){let{statSubscription:r,oneStat:o}=t;r.add(o.attachToInteractive(this.getStatEvents())),this.state.statistics$.next(t)}this.state.isReplay$.getValue()&&this.state.isReplay$.next(!1),this.events.playerChanged$.next(i),this.globalEventEmitter.emit(I.playerChanged,i)};this.onPlaybackStarted=()=>{this.resizeManager?.calc(),this.animation.requestAnimation()};this.destroyGameControllers=(e=!0)=>{this.gameControllers.forEach(t=>{!e&&t.isPermanentText||(this.animation.removeFn(t.whilePlaying),t.destroy())})};this.completeInteractiveRange=e=>{let{interactiveRanges$:t}=this.state,r=t.getValue().map(o=>({...o,subjects:o.subjects.filter(c=>c.id!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};if(this._options={...Ri,...e,config:{...Ri.config,...e.config}},this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation){this.blinkAnimationRef=new Se,this.blinkAnimationRef.create();let r=this.blinkAnimationRef.element;r&&this.rootElement.append(r)}this._options.parentElement.append(this.rootElement),this.historyController=new fe({interactiveController:this,globalEventEmitter:this.globalEventEmitter,videoId:this._options.projectInfo?.videoId,historyApi:this._options.historyApi,settings:{maxLength:this._options.config.historyMaxLength,initChapterId:this._options.initChapterId}}),this._options.lastFrame&&(this.lastFrame=new Ze({parentElement:this._options.parentElement,onError:r=>{let o=new P(1,6,r);this.emitErrorEvent(o)}})),Si(this._options.parentElement),this.subscriptions.add(ki(this.rootElement,"mousedown").subscribe(r=>r.stopPropagation())).add(ki(this.rootElement,"mouseup").subscribe(r=>r.stopPropagation())),this.manifestController=new ne(this._options.loaders,r=>{let o=new P(1,3,r);this.emitErrorEvent(o)});let i=[];this._options.lastFrame&&i.push(()=>{this.lastFrame?.updateCanvasDimensions(!0)}),i.push(()=>{let r=this.state.isInteractiveTime$.getValue();for(let o of this.gameControllers)o.onResize(r)}),this.resizeManager=di(()=>({player:this.player,parentElement:this._options.parentElement,fns:i})),this._options.graph&&(this.graph=new le({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:r=>{this.setChapter({chapterId:r}),this.globalEventEmitter.emit(I.graph,{type:me.watchAgainClicked,chapterId:r}),this.events.watchAgainIsClicked$.next(r)},onError:r=>{let o=new P(1,2,{message:r});this.emitErrorEvent(o)}})),this.initSubscriptions()}initSubscriptions(){this.playerSubscriptions.add(this.historyController.events.inited$.subscribe(async({videosInfo:e=[]})=>{this._options.initSeamless&&(await this.initSeamless(),this.updateGraphVideosInfo(e))})),this.subscriptions.add(this.events.interactiveContainerRemoved$.subscribe(({subjectId:e})=>{this.completeInteractiveRange(e)})).add(this.events.interactiveContainerFakeRemoved$.subscribe(({subjectId:e,removeAllOpenURI:t})=>{this.handleFakeRemoval(e,t)})).add(this.events.interactiveActionExecution$.subscribe(e=>{if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){let{chapterId:t}=e.payload;this.setChapter({chapterId:t}),this.state.isFirstChapter$.getValue()&&this.state.isFirstChapter$.next(!1)}else if(e.payload?.behaviour==="change-manifest"){let{manifestURL:t}=e.payload;t&&this.setManifest(t)}e.actionType==="expect"?(this.state.isInteractiveExpectation$.next(!0),this.updateControlsShadowStyles({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!0}),this.toggleBlinkAnimation({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!0})):e.actionType==="after-expect"&&(this.state.isInteractiveExpectation$.next(!1),this.updateControlsShadowStyles({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!1}),this.toggleBlinkAnimation({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!1}))})).add(this.events.manifestChanged$.subscribe(()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})).add(this.events.interactiveActionChoice$.subscribe(({type:e,subjectName:t,payload:i})=>{e!=="action-choice"||t==="chapter"||"invokeImmediately"in i&&i.invokeImmediately||this.destroyGameControllers(!1)}))}async initSeamless(){this.seamlessController=Tt(this),this.seamlessControllerSubs.add(this.seamlessController.activePlayerChanged.subscribe(this.handleSeamlessPlayerChanged)),await this.seamlessController.init()}handlePositionChange(e){(!this.graph||this.graph.isHidden)&&this.checkIfSeekable();let t=e*1e3,r=this.getInteractiveRanges().reverse().find(({range:o})=>t>=o[1]);if(r){let o=r.range.join("-");this.endedRanges.has(o)||(this.endedRanges.add(o),this.globalEventEmitter.emit(I.interactives,{type:k.rangeEnded,payload:r,visibility:!0}),this.events.interactiveRangeEnded$.next({type:"range-ended",payload:r}))}}registerVideoEvents(){this.player&&(window.removeEventListener("beforeunload",this.clearHistoryIfEnded),this.playerSubscriptions.unsubscribe(),window.addEventListener("beforeunload",this.clearHistoryIfEnded),this.playerSubscriptions.add(this.player.events.started$.pipe(vn()).subscribe(this.onPlaybackStarted)).add(this.player.events.playing$.subscribe(this.animation.requestAnimation)).add(this.player.events.willPause$.subscribe(this.animation.cancelAnimation)).add(this.player.info.position$.subscribe(this.handlePositionChange.bind(this))).add(this.manifestController.prevChapter$.subscribe(e=>this.state.prevChapter$.next(e))).add(fn({position:this.player.info.position$,interactiveRanges:this.state.interactiveRanges$,isInteractiveExpectation:this.state.isInteractiveExpectation$}).subscribe(({position:e,interactiveRanges:t,isInteractiveExpectation:i})=>{let r;if(i)r=!0;else{let a=e*1e3;r=!!t.find(({range:[d,v],subjects:y})=>d<a&&a<v&&y.some(u=>!u.isRemoved)&&y.length)}r!==this.state.isInteractiveTime$.getValue()&&this.state.isInteractiveTime$.next(r);let o=!!this.noInteractionTimeout,s=this.player?.info.playbackState$.getValue()==="playing"||i;r&&!o&&s?this.noInteractionTimeout=window.setTimeout(()=>{this.events.noInteraction$.next()},this._options.config.noInteractionEventTimeout):o&&!s&&this.clearNoInteractionTimeout()})),this.playerSubscriptions.add(this.historyController.events.error$.subscribe(this.events.error$)),this._options.lastFrame&&this.playerSubscriptions.add(this.player.info.duration$.subscribe(e=>{this.lastFrame?.setVideoDuration(e*1e3)})).add(this.player.experimental.element$.subscribe(e=>{e&&this.lastFrame?.setVideoElement(e)})).add(this.player.events.firstFrame$.subscribe(()=>{this.lastFrame?.reset(),setTimeout(()=>{this.lastFrame?.hide(),this.lastFrame?.lastFrameCanvas.clear()},50)})).add(this.player.events.seeked$.subscribe(this.lastFrame.onSeek)))}setGameControllers(){let e=this.manifestController.chapter;e&&this.appState===1&&(this.selectBranches?.setManifestChapterEvents(e),this.gameControllers=this.getGameControllers(e),this.interactiveEvents?.containersEventsCallState.setData(e.containers),this.seekToInteractiveController.setContainers(this.gameControllers.map(t=>t.container.container).filter(t=>!ie(t.controls))),this._options.lastFrame&&this.animation.addFn(()=>{this.player&&this.lastFrame?.onEachTick(this.player.info.position$.getValue()*1e3)},!0),this.state.interactiveRanges$.next(this.getInteractiveRanges()),this.appState=2)}getGameControllers(e){let t=[];return e.containers.forEach(i=>{let r=i.type.trim().toLowerCase(),c=this.factories.get(r)?.(i,this.rootElement,{isTouch:this._options?.isTouch??!1,features:{controlsExpectTimeBlinkAnimation:this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation,controlsTapPlace:this._options.animationsFeatureToggles?.controlsTapPlace,controlsFillAnimation:this._options.animationsFeatureToggles?.controlsFillAnimation}});if(c&&this.selectBranches&&this.interactiveEvents&&this.player){let s=new Qe({player:this.player,container:c,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,getContainerEventState:()=>oi(i,this.gameControllers),permanentTextControls:this._options.permanentTextControls,interactiveTimeOpenUri:this._options.interactiveTimeOpenUri,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(i.id)},onError:this.emitErrorEvent});this.animation.addFn(s.whilePlaying,!0),t.push(s)}}),t}checkIfSeekable(){if(this.state.isInteractiveExpectation$.getValue()){this.state.isSeekable$.next(!1);return}let t=this.state.isSeekable$.getValue(),i=!!this.seekToInteractiveController.getNextInteractiveTime();(i&&!t||!i&&t)&&this.state.isSeekable$.next(!t)}updateLastEventInfo(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}pushChapterToHistory(e){if(this.updateLastEventInfo(),!this.historyController.inited)return;let t=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),i=this.state.prevChapter$.getValue(),r=(i&&H(i)&&We(i))??!1,o=this.manifestController.manifest?.metadata.initChapterId===e,c=this.historyController.state.history$.getValue();if(o||r&&t){this.historyController.updateHistory([e]);return}c.at(-1)!==e&&this.historyController.updateHistory([...c,e])}handleFakeRemoval(e,t){let{interactiveRanges$:i}=this.state,o=i.getValue().map(c=>{let s=c.subjects.some(h=>h.id===e),a=c.subjects.map(h=>t&&s||h.id===e?{...h,isRemoved:!0}:h);return{...c,subjects:a}});i.next(o)}reset(){this.appState===2&&(this.destroyGameControllers(),this.gameControllers=[],this.animation.release(),this.interactiveEvents?.release(),this.appState=1,this.state.isSeekable$.next(!1),this.clearNoInteractionTimeout())}toggleBlinkAnimation(e){if(!this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation)return;let t=(i,r)=>{i.toggleBlinkAnimation(r)};ze({...e,gameControllers:this.gameControllers,execFn:de(xt(t),e.isExpect)}),e.isExpect&&this.blinkAnimationRef?.restart()}updateControlsShadowStyles(e){if(!this._options.animationsFeatureToggles?.areaControlShadow)return;let t=(i,r)=>{i.updateControlsShadowStyles(r)};e.isExpect?ze({...e,gameControllers:this.gameControllers,execFn:de(xt(t),!1)}):ze({...e,gameControllers:this.gameControllers,execFn:t})}get options(){return this._options}init(){this.manifestController.chapter&&this._options.parentElement&&this.player&&this._options.fullscreenTargetElement&&this.appState===0&&(this.resizeManager?.resizeObserver.observe(this._options.fullscreenTargetElement),this.registerVideoEvents(),this.appState=1,this.setGameControllers())}async setManifest(e){this.reset(),this.isFirstChapterFetched=!1;let t=await this.manifestController.setManifest(e);if(t.manifest)return this.graph&&this.graph.handleManifestChange(t.manifest),await this.historyController.setManifest(t.manifest),this.events.manifestChanged$.next(t.manifest),this.globalEventEmitter.emit(I.manifestChanged,{manifest:t.manifest}),this.setGameControllers(),t.manifest}setPlayer(e){this.reset(),this.player=e,this.seekToInteractiveController.setPlayer(this.player),this.interactiveEvents?this.interactiveEvents.setPlayer(this.player):this.interactiveEvents=pi(this.player,this._options.interactiveTimeOpenUri),this.selectBranches=Ei({player:this.player,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter}),this.appState===1&&(this.registerVideoEvents(),this.setGameControllers())}async setChapter({chapterId:e,pushToHistory:t=!0,playPrev:i=!1}={}){this.reset(),this.lastFrame&&this.isFirstChapterFetched&&(this.lastFrame.draw(),this.lastFrame.show()),this.lastFrame&&yn.browser.isSafari&&await xi(35);let r=!i&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:o,media:c,graph:s}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!o||!c)&&(t&&this.pushChapterToHistory(o.id),this.state.isInitialChapter$.next(this.manifestController.isInitialChapter()),this.state.isEndChapter$.next(this.manifestController.isEndChapter()),this.graph&&this.graph.handleChapterChange(o),this.lastFrame?.setCurrentChapter(o),this.events.chapterChanged$.next({chapter:o,manifestVideo:c}),this.globalEventEmitter.emit(I.chapterChanged,{chapter:o,media:c,graph:s}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new wi(e=>{this.subscriptions.add(this.events.graphVisibilityChanged$.subscribe(t=>{e.next(t?be.GRAPH_SHOW:be.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{e.next(be.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:i,subjectType:r})=>{t!=="action-choice"||i!=="control"||(r==="Button"&&e.next(be.NEXT_BUTTON),r==="Area"&&e.next(be.NEXT_AREA))}))}),nextMovie$:new wi(e=>{this.events.playerChanged$.subscribe(({config:t})=>{t?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&e.next(t.unitedVideoId)})})}}async toggleGraphView(e=!0){this.graph&&(e?(await this.graph.show(),this.state.isSeekable$.next(!1)):(this.graph.hide(),this.checkIfSeekable()),this.globalEventEmitter.emit(I.graph,{type:me.visibility,visibility:e}),this.events.graphVisibilityChanged$.next(e))}setVisitedChapters(e){Array.isArray(e)&&this.graph?.setVisitedChapters(e)}updateGraphVideosInfo(e){Array.isArray(e)&&this.graph?.updateVideosInfo(e)}deadEndCheck(){return!(this.interactiveEvents?.getPreparedToExecActions()||[]).some(i=>i.actionType===x.setNextBranch)}allControlsAreRemoved(){return!this.gameControllers.some(t=>!t.container.isRemoved)}isEndedExpectation(){if(!this.player||!this.gameControllers)return!1;let e=this.player.info.position$.getValue(),t=this.player.info.duration$.getValue();return e===t&&this.gameControllers.some(i=>{let r=i.container.container;return!i.container.isRemoved&&r.endTime===null&&Z(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&Fe(e.metadata.version)}getInitialVideoInfo(){return{videoId:this.historyController.getInitialVideoId(),chapterId:this.historyController.getInitialChapterId()}}getHistoryState(){return this.historyController.state}getIsSeekable(){return this.state.isSeekable$}getInteractiveRanges(){return li(this.manifestController.chapter?.containers)}getNextInteractiveStartTime(e){return this.seekToInteractiveController.getNextInteractiveTime(e)}getChapterBranches(e){return this.manifestController.getBranches(e)}getCurrentChapter(){return this.manifestController.getCurrent()}getCurrentManifest(){return this.manifestController.manifest}on(e,t){return this.globalEventEmitter.on(e,t),this}off(e,t){return this.globalEventEmitter.off(e,t),this}once(e,t){return this.globalEventEmitter.once(e,t),this}destroy(){this.clearHistoryIfEnded(),this.blinkAnimationRef?.destroy(),this.destroyGameControllers(),this.gameControllers=[],this.graph?.destroy(),this.seamlessControllerSubs.unsubscribe(),this.seamlessController?.removeAll(),this.resizeManager?.release(),this.animation.release(),this.interactiveEvents?.release(),this.manifestController.release(),this.playerSubscriptions.unsubscribe(),this.subscriptions.unsubscribe(),this.globalEventEmitter.reset(),this.lastFrame?.destroy(),this.rootElement.remove(),this.historyController.destroy(),this.isFirstChapterFetched=!1,this.appState=3}};var gn={Container:J,createChoiceContainer:Ne,createAreaControl:ke,createButtonControl:Oe,classnamesPrefix:Nt};var Sa={version:Mt};export{go as ContainerTypes,Be as ControlTypes,P as CustomError,I as EVENT_NAMES,x as EventActionTypes,Eo as EventTypes,qe as Interactives,ne as ManifestController,Sa as SDKInfo,St as chapterIdsToVKVideoIds,ft as compareVersions,uo as containerTypes,fo as controlTypes,ei as eventActionTypes,bo as eventTypes,mn as getChapterIdByVkVideoId,Ii as getVKVideoIdByMedia,pn as getVideoRawIdByMedia,me as graphEventTypes,We as hasEndTemplate,k as interactivesEventTypes,mo as isAreaControl,ho as isButtonControl,H as isLastChapter,ie as isOneTextCtrlContainer,Fe as isSupportedManifest,$e as isTextControl,hn as isVKVariantItem,Jt as isValidManifest,ti as migrateManifestToLatestVersion,gn as utils,Ti as vkVideoIdsToChapterIds};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.39-dev.6edf3cda.0",
3
+ "version": "1.0.39-dev.a77510fe.0",
4
4
  "author": "vk.com",
5
5
  "description": "Movika interactive SDK",
6
6
  "homepage": "https://vk.com",
@@ -56,8 +56,8 @@
56
56
  "dependencies": {
57
57
  "@interactiveplatform/movika-graph-editor": "2.1.7",
58
58
  "@interactiveplatform/movika-manifest": "1.0.1",
59
- "@vkontakte/videoplayer-core": "2.0.134-dev.464b6f35.0",
60
- "@vkontakte/videoplayer-shared": "1.0.62-dev.f077e9bc.0",
61
- "@vkontakte/videoplayer-statistics": "1.0.80-dev.e12b0c65.0"
59
+ "@vkontakte/videoplayer-core": "2.0.134-dev.6250ee46.0",
60
+ "@vkontakte/videoplayer-shared": "1.0.62-dev.23036491.0",
61
+ "@vkontakte/videoplayer-statistics": "1.0.80-dev.6184b715.0"
62
62
  }
63
63
  }
@@ -46,7 +46,6 @@ export interface IInteractiveOptions {
46
46
  * @deprecated
47
47
  * */
48
48
  disableControlsOnPause?: boolean;
49
- disableTextControlContainerVisibilityEvents?: boolean;
50
49
  isTouch?: boolean;
51
50
  animationsFeatureToggles?: AnimationsFeatureToggles;
52
51
  }
@@ -23,7 +23,6 @@ type ConstructorArg = {
23
23
  disabledControls$: IValueSubject<boolean>;
24
24
  onRemove: () => void;
25
25
  onError: (error: CustomError) => void;
26
- disableTextControlContainerVisibilityEvents?: boolean;
27
26
  };
28
27
  export declare class GameController {
29
28
  container: ChoiceContainer;
@@ -43,8 +42,7 @@ export declare class GameController {
43
42
  isSelectedContainerEvent: boolean;
44
43
  globalEvents: GlobalEvents;
45
44
  onError: ConstructorArg['onError'];
46
- disableTextControlContainerVisibilityEvents: boolean;
47
- constructor({ player, container, branches, selectBranches, interactiveEvents, globalEvents, globalEventEmitter, getContainerEventState, permanentTextControls, interactiveTimeOpenUri, disabledControls$, onRemove, onError, disableTextControlContainerVisibilityEvents, }: ConstructorArg);
45
+ constructor({ player, container, branches, selectBranches, interactiveEvents, globalEvents, globalEventEmitter, getContainerEventState, permanentTextControls, interactiveTimeOpenUri, disabledControls$, onRemove, onError, }: ConstructorArg);
48
46
  private emitContainerVisibilityEvent;
49
47
  registerEvents(): void;
50
48
  hide: () => void;