@vkontakte/videoplayer-interactive 1.0.36-dev.ca6258d6.0 → 1.0.36-dev.cf7ccf83.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.36-dev.ca6258d6.0
3
- * Tue, 29 Apr 2025 09:02:16 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.36-dev.cf7ccf83.0
3
+ * Tue, 29 Apr 2025 11:04:39 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-36/doc/
5
5
  */
6
- var Mt="1.0.36-dev.ca6258d6.0";import{fromEvent as qt,Subscription as Li}from"@vkontakte/videoplayer-shared/evergreen";var et=class{constructor(e){this.layout=e}},Ee=class extends et{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})`,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))`}};import{Subject as wi}from"@vkontakte/videoplayer-shared/evergreen";function Vt(n){return"features"in n}var V=class{constructor(e,t,...i){this.severity=e;this.category=t;this.data=i}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};function Ie({emitter$:n,error:e,subjectId:t,message:i="",severity:r=1,category:o=1}){let l=new V(r,o,{message:i,error:e,details:{id:t}});n.next(l)}var J=class{constructor(e,t){this.error$=new wi;this.container=e,this.options=t,this.factories=new Map,this.controls=[],this.setControls()}featureIsEnabled(e){return this.options&&Vt(this.options)&&this.options.features[e]}onError(e="",t){Ie({emitter$:this.error$,error:t,message:e,subjectId:this.container.id})}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 le,once as Qt}from"@vkontakte/videoplayer-shared/evergreen";var G=(n,e)=>Object.prototype.toString.call(n)===`[object ${e}]`,z=n=>G(n,"Object"),Te=n=>G(n,"String"),xe=n=>G(n,"Array"),Ae=n=>G(n,"Number"),Pt=n=>G(n,"Function"),Lt=n=>G(n,"Boolean"),nt=n=>Ae(n)&&!isNaN(n);var Q=n=>z(n)&&Object.keys(n).length===0,rt=n=>xe(n)&&!n.length;var re=(n,e)=>Te(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 Ot="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||{}),Nt=(i=>(i.start="left",i.end="right",i.center="center",i))(Nt||{}),Se=({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&&Nt[e.alignment])??"center"},we=({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},Re=({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})`,l=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=l},Bt=({target:n,isDark:e,baseDimension:t,fallback:i})=>{let l=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:l}`;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 ae,Subject as Vi,Subscription as Pi}from"@vkontakte/videoplayer-shared/evergreen";function ke(n){for(;n>Math.PI;)n-=2*Math.PI;for(;n<=-Math.PI;)n+=2*Math.PI;return n}function jt(n){return n*180/Math.PI}var ot="interactive-control-tap",te={common:ot,animation:`${ot}-animation`,visible:`${ot}-visible`};var Ri=60,Me=class{constructor({controlRotateAngleRad:e,clickCancelCondition:t,circleDiameterPx:i=Ri,useDimensionsBasedSize:r=!1}){this.onElementClick=e=>{if(!e.target||!e.currentTarget||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),l=i.left+i.width/2,s=i.top+i.height/2,a=e.clientX-l,h=e.clientY-s,d=ki(a,h,ke(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.stopPropagation(),!(!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 ki(n,e,t){return{x:n*Math.cos(t)-e*Math.sin(t),y:n*Math.sin(t)+e*Math.cos(t)}}var st="int",X=(i=>(i.AREA=`${st}_area`,i.TEXT=`${st}_text`,i.BUTTON=`${st}_bttn`,i))(X||{});function at(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;import{isSupportedManifest as Pe,ContainerTypes as qn,ControlTypes as Le,EventActionTypes as T,EventTypes as Yn,migrateManifestToLatestVersion as Ut,compareVersions as Jn}from"@interactiveplatform/movika-manifest";var Dt={metadata:"Object",chapters:"Array"},Ht=n=>{if(!z(n))return!1;for(let e in Dt)if(!n[e]||!G(n[e],Dt[e]))return!1;return Pe(n.metadata.version)},Ve=n=>n.type===Le.Text,Hn=n=>n.type===Le.Button,Un=n=>n.type===Le.Area,Gn={Choice:"Choice",TextInput:"TextInput"},zn={Button:"Button",Area:"Area",Text:"Text"},Wn={onClick:"onClick",onSuspense:"onSuspense"},Kn={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var Oe=n=>xe(n)&&!rt(n),H=n=>n.order==="end",$e=n=>xe(n.containers)&&!rt(n.containers)&&H(n),Gt=(n,e)=>{let t=n*1e3;return Oe(e.controls)&&t<(e.startTime??0)},lt=(n,e)=>{let t=n*1e3;return Oe(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"),Mi=n=>n?.length===1,ie=n=>Mi(n)&&Ve(n[0]);function zt(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&&!i.willRemoved)}function Fe({gameControllers:n=[],subjectName:e,subjectId:t,execFn:i}){for(let r of n)if(e==="container"&&r.container.container.id===t){i(r),zt(n,r.container.container.endTime,[r.container.container.id]).forEach(l=>{i(l)});break}}function Wt(n){for(let e of n.events)if(e.action.type==="openURI")return!0;return!1}var Kt=(n,e)=>{let t=x=>e.find(({container:p})=>p.container.id===x)?.container.isRemoved,i=Z(n.events)&&!t(n.id),r=(x,y=!1,p=!1)=>{let c=p?"every":"some";return x.controls[c](m=>{let u=y?x.endTime===n.endTime:!0;return m.events?.[c](f=>f.action?.type===T.openURI)&&u})},o=x=>x.some(({container:y})=>r(y.container,!0,!1)&&!y.isRemoved),l=x=>x.every(({container:y})=>y.isRemoved||y.willRemoved?!0:r(y.container,!0,!0)),s=zt(e,n.endTime,[n.id]).length,a=x=>x.controls.some(y=>y.events?.some(p=>p.action?.args?.shouldOpenNow)),h=i||s>0,d=o(e),v=r(n),C=l(e),b=i?!1:s>0,P=a(n);return{isExpectTime:h,hasOtherExpect:s>0,hasOpenURIEvent:d,hasOpenURIEventInCurrentContainer:v,isAllOpenURIEventsValid:C,isExpectEventForCurrentContainer:b,hasShouldOpenNowEvent:P}};var W=class n{constructor(e,t){this.control=e;this.options=t;this.container=null;this.controlElement=null;this.subscriptions=new Pi;this.error$=new Vi;this.isInteracted=!1;this.isRemoved=!1;this.onControlSelect=()=>{this.container?.isManifestContainerDisabled()||Wt(this.control)||this.container?.element?.classList.add("interactive-control-wrapper-selected")};this.onTransitionEnd=e=>{e.stopPropagation(),!(!e.target||!e.currentTarget)&&e.target===e.currentTarget&&this.removeView()}}removeView(e=!1){let t=this.getElement();if(t){if(e){if(t.classList.contains("interactive-control-before-remove"))return;t.classList.add("interactive-control-before-remove"),this.subscriptions.add(ae(t,"transitionend").subscribe(this.onTransitionEnd,r=>this.onError(`${n.name} remove view transition error`,r))).add(ae(t,"transitioncancel").subscribe(this.onTransitionEnd,r=>this.onError(`${n.name} remove view transition error`,r)));return}this.removeListeners(),t.remove(),this.isRemoved=!0}}onError(e="",t){Ie({emitter$:this.error$,error:t,message:e,subjectId:this.control.id})}addControlTap(e){if(this.featureIsEnabled("controlsTapPlace")&&this.container){let t=this.control.layoutParams.angle??w.angle;this.controlTap=new Me({controlRotateAngleRad:t,clickCancelCondition:this.container.isManifestContainerDisabled,circleDiameterPx:this.isTouch()?_t:void 0}),this.subscriptions.add(ae(e,"click").subscribe(this.controlTap.onElementClick,i=>this.onError("Control click tap animation error",i))).add(ae(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=!0,e()}}featureIsEnabled(e){return this.options&&at(this.options)&&this.options.features[e]}isTouch(){return this.options&&at(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(ae(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 pt="interactive-blink-anim-reference",L={common:pt,animation:`${pt}-animation`,disabled:`${pt}-disabled`},Ne=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 ht="interactive-container",O={common:ht,hidden:`${ht}-hidden`,disabled:`${ht}-disabled`};var Be=(n,e)=>{if(n.type.trim().toLowerCase()==="area")return new mt(n,e)},mt=class extends W{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;this.isInteracted=!1,this.isRemoved=!1;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.area),i.setAttribute("data-testid",X.AREA),Re({target:i,props:this.control.props,fallback:{...w,backgroundColor:"transparent"}}),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),this.addControlTap(i),this.subscriptions.add(le(this.container.element,"click").pipe(Qt()).subscribe(this.onControlSelect,r=>this.onError("Control click handler error",r))),this.container.element.append(i),e.append(this.container.element),this.controlElement=i,this.updateShadowStyles(),this.registerBlinkAnimationEvents()}registerBlinkAnimationEvents(){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}updateShadowStyles(e){if(!(!this.container||!this.controlElement))if(Lt(e)){let t=Math.min(this.controlElement.offsetWidth,this.controlElement.offsetHeight)+"px";Bt({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(le(e,"animationiteration").pipe(Qt()).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 ce,once as Xt}from"@vkontakte/videoplayer-shared/evergreen";var je=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 U="interactive-control-fill-animation",$={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 _e=class n{constructor(e){this.widthExpansionCoef=0;let t=document.createElement("div");t.classList.add($.common);let i=document.createElement("div");i.classList.add($.fillerWrapper);let r=document.createElement("div");r.classList.add($.filler),i.append(r),t.append(i);let o=ke(e.rotateAngle),l=o>Math.PI/2&&o<=Math.PI||o<0&&o<-Math.PI/2,s=o===Math.PI/2,a=o===-Math.PI/2,h=!l&&!s&&!a,d=s||a,v=!!(o%Math.PI/2)&&!d,C=v?o:0;t.style.borderRadius=e.borderRadius,i.style.transform=`skew(${C*-1}rad)`,d?(r.classList.add($.fillHeight,s?$.fromTop:$.fromBottom),i.classList.add($.fillHeight,s?$.fromTop:$.fromBottom)):(r.classList.add($.fillWidth,h?$.fromLeft:$.fromRight),i.classList.add($.fillWidth)),e.debug&&console.log(`[interactive ${n.name}]`,{widthExpansionCoef:this.widthExpansionCoef,opts:e,shouldFillHeight:d,rotateAngleRad:o,rotateAngelDeg:jt(o),rotateAngleRaw:e.rotateAngle,fromRight:l,fromTop:s,fromBottom:a,fromLeft:h}),this.useSkew=v,this.fromLeft=h,this.rotateAngle=o,this.fillAnimationElement=t,this.fillAnimationFillerElement=r,this.fillAnimationFillerWrapperElement=i,this.startTime=e.startTime,this.endTime=e.endTime,this.shouldFillHeight=d,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 De=(n,e)=>{if(n.type.trim().toLowerCase()==="button")return new dt(n,e)},dt=class extends W{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;this.isInteracted=!1,this.isRemoved=!1;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.button),i.setAttribute("data-testid",X.BUTTON),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),Re({target:i,props:this.control.props,fallback:w}),se({target:i,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),Se({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=je(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;we({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 _e({startTime:this.startTime,endTime:this.endTime,rotateAngle:this.control.layoutParams.angle??w.angle,borderRadius:i.style.borderRadius})),this.subscriptions.add(ce(i,"click").pipe(Xt()).subscribe(this.onControlSelect,l=>this.onError("Control click handler error",l))),i.append(r,this.controlFillAnimation?.fillAnimationElement??""),this.container.element.append(this.controlTap?.element??"",i),e.append(this.container.element),this.controlElement=i,this.registerBlinkAnimationEvents()}registerBlinkAnimationEvents(){if(!this.featureIsEnabled("controlsExpectTimeBlinkAnimation"))return;let e=this.container?.element.parentElement;!e||!this.controlElement||(this.subscriptions.add(ce(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(ce(this.controlElement,"mouseenter").subscribe(()=>{e.classList.contains(O.disabled)||this.onBlinkHovering()},t=>this.onError("Error happened in mouseenter callback",t))).add(ce(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(ce(e,"animationiteration").pipe(Xt()).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 Zt=(n,e)=>{if(n.type.trim().toLowerCase()==="text")return new ut(n,e)},ut=class extends W{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;this.isInteracted=!1,this.isRemoved=!1;let i=document.createElement("div");i.classList.add(S.common,S.text),i.setAttribute("data-testid",X.TEXT),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),Se({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=je(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;we({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(){}};var He=(n,e,t)=>{if(n.type.trim().toLowerCase()==="choice")return new ft(n,e,t)},ft=class n extends J{constructor(t,i,r){super(t,r);this.containerElement=null;this.subscriptions=new Li;this.onTransitionEnd=t=>{t.stopPropagation(),!(!t.target||!t.currentTarget)&&t.target===t.currentTarget&&this.removeView()};this.rootElement=i,this.layout=new Ee(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",De),this.addControlFactory("text",Zt),this.addControlFactory("area",Be)}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.subscriptions.add(o.error$.subscribe(this.error$))}),this.rootElement.append(r),this.isRemoved=!1,this.willRemoved=!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(t=!1,i=!1){let r=this.getElement();if(r){if(t){if(this.willRemoved)return;this.willRemoved=!0,i&&r.classList.add("interactive-container-before-remove-delay"),r.classList.add("interactive-container-before-remove"),this.subscriptions.add(qt(r,"transitionend").subscribe(this.onTransitionEnd,l=>this.onError(`${n.name} remove view transition error`,l))).add(qt(r,"transitioncancel").subscribe(this.onTransitionEnd,l=>this.onError(`${n.name} remove view transition error`,l)));return}this.subscriptions.unsubscribe(),this.removeAllControls(),r.remove(),this.isRemoved=!0,this.willRemoved=!1,this.containerElement=null}}removeAllControls(t=!1){this.controls.forEach(i=>i.removeView(t))}removeNonInteractedControls(t=!1){this.controls.forEach(i=>{i.isInteracted||i.removeView(t)})}isInteracted(){return this.controls.some(t=>t.isInteracted)}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 on,InterfaceLanguage as sn,Observable as Ti,once as an,Subject as F,Subscription as wt,ValueSubject as j,fromEvent as xi}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as Ce}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as Oi}from"@vkontakte/videoplayer-shared/evergreen";function pe(n,e){let t;return(...i)=>{clearTimeout(t),t=setTimeout(()=>n(...i),e)}}var Yt="video_interactive",Jt="videoint";var ei=250,he=class{constructor(e){this.handleZoomChange=pe(e=>{this.lastZoomInfo=e},ei);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,!Ae(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=$i(e),this.resizeObserver=new ResizeObserver(pe(this.onResize,ei)),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 Oi(this.lang,Yt,Jt)}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 $i(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 me=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 l=o.startTime-e;if(l<=r&&(o.endTime&&r<=o.endTime||o.endTime===null)){i=!0;break}r<l&&(t=t===-1?l:Math.min(t,l))}return!i&&t!==-1?t:null}}};var Ue=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 Ge=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{Pt(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 Di}from"@vkontakte/videoplayer-shared/evergreen";var ze=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Fi(...this.loaders[e])(t)}};function Fi(...n){return async function(t){let i=[...n];for(;i.length>0;)t=await i.shift()(t);return t}}function de(n,e,t){return n?{...n,[e]:n[e]?[t,...n[e]]:[t]}:{[e]:[t]}}function We({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 l=n.getMedia(r.media,o.videoId),s=n.getGraph(r.graph,o.id);return l?{...i,actions:n,errors:e,result:{chapter:o,media:l,graph:s}}:{...i,errors:de(e,We.name,"Could not find media"),actions:n}}}}return{...i,errors:de(e,We.name,"Could not find chapter"),actions:n}}var vt=(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 Ni=async n=>{try{let e={},t;if(Te(n)){t=new URL(n).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(z(n))e=n;else return{};if(!Ht(e))return{};let i=e.metadata.media;if(Te(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 _i(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ti(n){let{manifest:e,manifestURL:t}=await Ni(n);if(!e)throw new Error("Failed on fetch");let i=Ut(e);return i.media=Bi(i.media,t),delete i.metadata.media,i}function Ke(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 yt(n,e){return n.videos.find(t=>t.id===e)}function Bi(n,e){return{...n,videos:n.videos.map(t=>({...t,variants:t.variants.map(i=>{let r="url"in i?i.url:"",o=ji(r,e);return{...i,url:o||r}})}))}}function ji(n="",e){try{return new URL(n,e).href}catch{return""}}function _i(n){return vt(n,"3.2.0")>=0}var ne=class extends ze{constructor(t,i){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new Di(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:de},result:null,errors:null,source:t});return i.errors&&this.errorHandler(i.errors),this.manifest=await ti(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",We({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:bt,getChapter:Ke,getMedia:yt,getByBranches:this.getByBranches.bind(this),addErrorMessage:de},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=Ke(this.manifest.chapters,t);if(i){let r=yt(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=Ke(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 Hi}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as Et,Tracer as Ui,ValueSubject as Gi}from"@vkontakte/videoplayer-shared/evergreen";var ii=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 Ct(){let n=new Map;function e({listId:o=Math.random().toString(),itemId:l=Math.random().toString(),...s}){let a=n.get(o),h={...s};return a?a[l]=h:n.set(o,{[l]:h}),{listId:o,itemId:l,...s}}function t(o){o.player.destroy(),o.container.remove(),o.subscription.unsubscribe(),o.statistics?.oneStat.destroy(),o.statistics?.statSubscription.unsubscribe()}function i(o,l){let s=n.get(o);if(!s)throw Error("Can't remove. Not find.");if(l){let a=s[l];a&&t(a),delete s[l],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 gt(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 ue=(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 zi=2;function It(n){let e=Ct(),t=new Et,i={},r=null,o=!1,l,s=new Gi(null);n&&a(n);function a(y){r=y}function h(y,p,c){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let u=(e.map.get(y)??{})[p];if(u){i={chapterId:c,listId:y,itemId:p,...u};let f=i.player;i.subscription.add(f.info.currentQuality$.subscribe(g=>{let A=f.info.position$.getValue(),N=f.info.isAutoQualityEnabled$.getValue();if(!(!g||!A||N))for(let E of e.map)Object.values(E[1]).forEach(({player:k})=>{ue(k,g)})})).add(f.events.started$.subscribe(()=>{d(p)})),u.container.remove(),r.setPlayer(u.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(y){if(!r)throw Error("need to set interactive controller");if(Q(i)||y!==i.itemId)return;let p=r.getChapterBranches(),c=new Set;for(let m of p)c.has(m.media.id)||(await C({media:m.media,chapterId:m.chapter.id,setAsActive:!1,title:m.chapter.label}),c.add(m.media.id))}async function v({chapter:{id:y},manifestVideo:p}){if(Q(i)||!r)return;let c=i.player.info.muted$.getValue(),m=i.player.info.currentQuality$.getValue(),u=i.player.info.isAutoQualityEnabled$.getValue(),f=i.player.info.volume$.getValue(),g=i.player.info.currentPlaybackRate$.getValue(),A=!u,N=!1;for(let E of e.map)if(E[0]===p.id&&!r.state.isReplay$.getValue()){let k=Object.keys(E[1]);for(let M of k)M===i.itemId?(k.length<zi||(N=!0),e.removePlayer(E[0],M)):(N=!0,h(E[0],M,y),A?ue(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(f),i.player.setMuted(c),i.player.setPlaybackRate(g))}else e.removePlayer(E[0]);N||(await C({media:p,chapterId:y,setAsActive:!0,playbackRate:g}),A?ue(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(f),i.player.setMuted(c))}async function C({media:y,chapterId:p,prefetch:c=!0,setAsActive:m=!0,autoplay:u=!1,preferredExt:f,title:g,playbackRate:A}){let N=Math.random().toString(),E=document.createElement("div");l.append(E);let k;if(r?.options?.vkVideoLoader){let ge=ii(y);ge.length&&(k=await r.options.vkVideoLoader(...ge))}let M=r?.options?.coreConfig||void 0,_={...M,configName:[...M?.configName??[],"interactive"]},K={container:E,...k?.videos?.[0]||{sources:gt(y,f).sources},title:g,failoverHosts:k?.failoverHosts||[]},B=new Hi(_,Ui.createRootTracer());B.initVideo(K);let q=null;if(k?.videos&&r?.options.createOneStat){let ge=k.videos[0],Je=r.options.createOneStat(ge),kt=new Et;Je&&(kt.add(Je.attachTo(B)),q={oneStat:Je,statSubscription:kt})}let Rt=new Et,Si=i?.player?.info.isAutoQualityEnabled$.getValue();Rt.add(B.events.canplay$.subscribe(function(){Si||ue(B,i.player.info.currentQuality$.getValue()),A&&B.setPlaybackRate(A)}));let Y=e.createPlayer({listId:y.id,itemId:N,player:B,container:E,sources:gt(y,f).sources,config:K,subscription:Rt,statistics:q});return m&&h(y.id,Y.itemId,p),u&&Y.player.play(),c&&!u&&Y.player.prepare(),{player:Y.player,config:Y.config,statistics:Y.statistics}}function b(){P(),r=null,l.remove()}function P(){t.unsubscribe(),e.removeAll(),i={},o=!1}async function x(){if(!r)throw Error("need to set interactive controller");P(),l=document.createElement("div");let{media:y,chapter:p}=r.getCurrentChapter();y&&p?(t.add(r.events.chapterChanged$.subscribe(v)),await C({media:y,chapterId:p.id,title:p.label})):console.error("not found")}return{...e,init:x,setInteractiveController:a,createPlayer:C,removeAll:b,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"},fe={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as Wi}from"@vkontakte/videoplayer-shared/evergreen";function Tt(n){return function(...t){return n(...t.reverse())}}function ve(n,...e){return(...t)=>z(e[0])&&z(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:l,globalEventEmitter:s,getContainerEventState:a,permanentTextControls:h,interactiveTimeOpenUri:d,disabledControls$:v,onRemove:C,onError:b,features:P}){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,l)=>{let{isExpectTime:s,hasOtherExpect:a,hasOpenURIEvent:h,hasOpenURIEventInCurrentContainer:d,isAllOpenURIEventsValid:v,hasShouldOpenNowEvent:C}=this.getContainerEventState(),b=this.interactiveTimeOpenUri&&!d,P=this.interactiveTimeOpenUri&&d;if((!this.interactiveTimeOpenUri||b)&&(this.isSelectedControlEvent=!0),o!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||b)){if(this.interactiveTimeOpenUri){let x=!a&&!v&&d;x&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:x})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&h&&this.gameState!==5){if(P){let y=((p,c,m,u)=>!p&&!c&&m||p&&!c&&m&&!u||p&&!c&&m&&u)(s,a,v,this.isSelectedContainerEvent);this.fakeRemoveView(y)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!s||!a||!C)&&(this.selectBranches.stopExpect(),l())}},isEOV:()=>this.gameState===4},i=ve(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();if(!(e instanceof HTMLVideoElement?e.readyState:void 0)||this.isRemovedOrDestroyed()&&!this.isPermanentText)return;let r=this.player.getExactTime();if(Gt(r,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(lt(r,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let a=this.gameState;this.gameState=3,a===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:a}=this.getContainerEventState(),h=this.selectBranches.state.isExpect,d=this.interactiveTimeOpenUri&&a;if(d&&!h){let v=this.container.getElement();v&&(v.style.visibility!=="hidden"&&this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView())}!this.isPermanentText&&!d&&this.removeView()}let o=lt(r,this.container.container),l=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],s={subjectId:this.container.container.id,subjectName:"container",range:l,currentTime:r,isInteractiveTime:o};this.container.onProgress(r*1e3,o),this.globalEventEmitter.emit(I.eachTick,s),this.globalEvents.eachTick$.next(s)};this.container=t,this.branches=i,this.selectBranches=r,this.subscription=new Wi,this.player=e,this.interactiveEvents=o,this.getContainerEventState=a,this.isPermanentText=h&&ie(t.container.controls),this.interactiveTimeOpenUri=d,this.disabledControls$=v,this.onRemove=C,this.globalEventEmitter=s,this.gameState=0,this.globalEvents=l,this.onError=b,this.features=P,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:R.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:R.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(e=this.features.controlsHideAnimation){if(e){if(this.isRemovedOrDestroyed())return;this.container.removeNonInteractedControls(!0),this.container.removeView(!0,!0)}else this.container.removeView();this.globalEventEmitter.emit(I.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.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)}isInteracted(){return this.container.isInteracted()}isRemovedOrDestroyed(e=!0){let t=e?this.container.willRemoved:!1;return this.gameState===5||t||this.gameState===6}destroy(e=!1){this.reset(),this.removeView(e),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 ri=(n=[])=>n.reduce((e,t,i)=>{let r=(t?.controls??[]).filter(o=>!Ve(o));if(Oe(r)){let o=[t.startTime??0,t.endTime??1/0],l={id:t.id,isRemoved:!1};if(!i)e.push({subjects:[l],range:o});else{let s=[],a=-1/0,h=1/0,d=[],v=[];for(let C=0;C<e.length;C++){let b=e[C];if(v.push(...b.subjects),b.range[0]<h&&(h=b.range[0]),b.range[1]>a&&(a=b.range[1]),o[0]>=b.range[0]&&o[1]<=b.range[1])return e[C].subjects.push(l),e;o[0]<b.range[0]&&o[1]>b.range[0]&&(s.push(C),d=d.concat(b.subjects)),o[0]>=b.range[0]&&o[0]<=b.range[1]&&(s.push(C),d=d.concat(b.subjects),o[0]=b.range[0]),o[1]>=b.range[0]&&o[1]<=b.range[1]&&(s.push(C),d=d.concat(b.subjects),o[1]=b.range[1])}if(v.push(l),o[0]<=h&&o[1]>=a)return[{subjects:v,range:o}];s.length&&s.reverse().forEach(C=>{e.splice(C,1)}),e.push({subjects:d.concat([l]),range:o})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function oi(){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(nt(s)){let d=n[s]??null;if(d&&a&&re(a,!0)){let v={},C=d[a];return C&&(v={...v,...C}),v=Q(v)?null:v,v&&re(h,!0)?v[h]??null:v}return d}return null}function o({timestamp:s,priority:a,initiator:h}){if(nt(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],!Q(n[s][a]))return!0}else return!1;if(delete n[s][a],!Q(n[s]))return!0}else return!1;return delete n[s]}else return!1;return!1}function l({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:l,removeAll:e,get:r,getLte:t,getGte:i}}var Ki=[T.expect,T.setNextBranch],Qi=1/0;function si(n,e){let t=n,i,r=Xi(e),o=oi(),l,s=()=>{b(),p()},a=c=>{o.add.call(void 0,c),P()},h=(c=[])=>{for(let m of c)if(m.action(),Ki.includes(m.actionType))break},d=(c=1/0)=>{let m=Xe(o.get({timestamp:c,priority:"control"})??{}),u=Xe(o.get({timestamp:c,priority:"container"})??{}),f=Xe(o.get({timestamp:c,priority:"chapter"})??{});return[...m,...u,...f]},v=c=>{r.isReady(c)&&h(d(c))},C=()=>{h([...Xe(o.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{i&&(l?.unsubscribe(),i=void 0)},P=()=>{i||(i=()=>setTimeout(()=>{v(1/0)}),l=t.events.ended$.subscribe(i))},x=c=>{b(),t=c},y=c=>{c.priority==="container"&&r.resetCalled(c.timestamp),o.remove(c)},p=()=>{r.release(),o.removeAll()};return{setPlayer:x,add:a,remove:y,exec:v,execEndOfVideo:C,listen:P,unlisten:b,release:s,containersEventsCallState:r,getPreparedToExecActions:d}}function Xi(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??Qi,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===T.expect?-1:1)}var ai={videoContentHeight:0,videoContentWidth:0},li=n=>{let{height:e,width:t}=n.info.intrinsicVideoSize$.getValue()||{};if(!(e&&t))return ai;let{clientHeight:i,clientWidth:r}=n.experimental.element$.getValue()||{};if(!(i&&r))return ai;let o=e/t,l=i/r,s,a;return l>o?(a=r,s=r*o):l<o?(a=i/o,s=i):(a=r,s=i),{videoContentWidth:a,videoContentHeight:s}};var Zi=250;function ci(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}=li(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=pe(s=>{let{fns:a=[]}=n();i(s);for(let h of a)h()},Zi);function l(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:l}}var qi=n=>Math.floor(Math.random()*n),hi=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},mi=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 di=n=>{let e=n.length,t=qi(e);return n[t]},pi=1,ui=n=>{let e=0;for(let i=0;i<n.length;++i)e+=n[i].weight??pi;let t=Math.random()*e;e=0;for(let i=0;i<n.length-1;++i)if(e+=n[i].weight??pi,e>=t)return n[i];return n[n.length-1]};var fi={shouldOpenNow:!0,isDetachContainer:!0},vi="after-expect",xt=(n,e=!1)=>({...n,args:e?{...n.args,...fi}:{...fi,...n.args}}),bi=({globalEventEmitter:n,globalEvents:e,player:t,interactiveEvents:i})=>{let r={isExpect:!1},o=()=>{r.isExpect&&(r.isExpect=!1)},l=({action:p,controlType:c,controlId:m,containerId:u,branches:f=[],onEvent:g,isEOV:A=()=>!1,isDisabled:N=()=>!1})=>{let E=xt(p,A()),k={timestamp:1/0,priority:"control",initiator:m,actionType:E.type},M=N(),_=n.emit.bind(n,I.interactives,{subjectId:m,subjectType:c,subjectName:"control",type:M?R.actionChoiceCanceled:R.actionChoice,actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:u,...E.args}}),K=()=>{e.interactiveActionChoice$.next({subjectId:m,subjectType:c,subjectName:"control",type:M?"action-choice-canceled":"action-choice",actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:u,...E.args}})};if(M){_(),K();return}switch(E.type.trim().toLowerCase()){case T.setNextBranch.trim().toLowerCase():{let B=f.find(q=>q.id===E.args.branchId);if(!B)return;g(E.args.isDetachContainer,b.bind(null,{subjectId:m,subjectName:"control"})),_(),K(),E.args.shouldOpenNow?x({subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}}):i.add({...k,action:x.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}})});return}case T.continuePlayback.trim().toLowerCase():{g(E.args.isDetachContainer,b.bind(null,{subjectId:m,subjectName:"control"})),_(),K(),E.args.shouldOpenNow?P({subjectId:m,subjectName:"control",subjectType:c,action:p}):i.add({...k,action:P.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:p})});return}case T.openURI.trim().toLowerCase():{g(E.args.isDetachContainer,b.bind(null,{subjectId:m,subjectName:"control"})),_(),K(),E.args.shouldOpenNow?y({subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{URI:p.args.uri}}):i.add({...k,action:y.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{URI:p.args.uri}})});return}default:{let B="Unexpected control event",q=new V(1,1,{message:B});d(q,B);return}}},s=({action:p,container:{id:c,endTime:m},branches:u=[],isEOV:f=!1,autoSelected:g=!1})=>{let A=xt(p,f),N={timestamp:!A.args.shouldOpenNow||f?1/0:m??1/0,priority:"container",initiator:c,actionType:A.type},E=n.emit.bind(n,I.interactives,{subjectId:c,subjectName:"container",type:R.actionChoice,actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}}),k=()=>{e.interactiveActionChoice$.next({subjectId:c,subjectName:"container",type:"action-choice",actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}})};switch(A.type.trim().toLowerCase()){case T.setNextBranch.trim().toLowerCase():{let M=u.find(_=>_.id===A.args.branchId);if(!M)return;E(),k(),i.add({...N,action:x.bind(null,{subjectId:c,subjectName:"container",action:A,payload:{chapterId:M.chapterId,autoSelect:g}})});return}case T.setMaxWeightBranch.trim().toLowerCase():return;case T.setMinWeightBranch.trim().toLowerCase():return;case T.setRandomBranch.trim().toLowerCase():return;case T.setWeightlessRandomBranch.trim().toLowerCase():return;case T.continuePlayback.trim().toLowerCase():{E(),k(),i.add({...N,action:P.bind(null,{subjectId:c,subjectName:"container",action:A})});return}case T.openURI.trim().toLowerCase():{E(),k(),i.add({...N,action:y.bind(null,{subjectId:c,subjectName:"container",action:A,payload:{URI:p.args.uri}})});return}default:{let M="Unexpected container event",_=new V(1,1,{message:M});d(_,M);return}}};function a({container:p,branches:c,isEOV:m=!1}){let u=ct(p.events);if(u){let f=xt(u.action,m);n.emit(I.interactives,{subjectId:p.id,subjectName:"container",type:R.actionChoice,actionType:f.type,payload:{invokeImmediately:f.args.shouldOpenNow,...f.args}}),e.interactiveActionChoice$.next({subjectId:p.id,subjectName:"container",type:"action-choice",actionType:f.type,payload:{invokeImmediately:f.args.shouldOpenNow,...f.args}}),i.add({timestamp:m?1/0:p.endTime??1/0,priority:"container",initiator:p.id,actionType:T.expect,action:C.bind(null,{subjectId:p.id,subjectName:"container"})}),r.isExpect=!0}else for(let f of p.events??[])s({action:f.action,container:p,branches:c,isEOV:m})}let h=({chapterId:p,action:c,branches:m=[]})=>{let u=n.emit.bind(n,I.interactives,{subjectId:p,subjectName:"chapter",type:R.actionChoice,actionType:c.type,payload:c.args}),f=()=>{e.interactiveActionChoice$.next({subjectId:p,subjectName:"chapter",type:"action-choice",actionType:c.type,payload:c.args})};switch(c.type.trim().toLowerCase()){case T.setNextBranch.trim().toLowerCase():{let g=m.find(A=>A.id===c.args.branchId);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setWeightlessRandomBranch.trim().toLowerCase():{let g=di(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setRandomBranch.trim().toLowerCase():{let g=ui(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setMaxWeightBranch.trim().toLowerCase():{let g=mi(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setMinWeightBranch.trim().toLowerCase():{let g=hi(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.continuePlayback.trim().toLowerCase():return u(),f(),P.bind(null,{subjectId:p,subjectName:"chapter",action:c});case T.openURI.trim().toLowerCase():return u(),f(),y.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{URI:c.args.uri}});default:{let g="Unexpected chapter event",A=new V(1,1,{message:g});d(A,g);return}}};function d(p,c){console.error(c),e.error$.next(p),n.emit(I.errors,p)}function v(p){let c=ct(p.events);if(c){if(H(p))return;n.emit(I.interactives,{subjectId:p.id,subjectName:"chapter",type:R.actionChoice,actionType:c.action.type,payload:c.action.args}),e.interactiveActionChoice$.next({subjectId:p.id,subjectName:"chapter",type:"action-choice",actionType:c.action.type,payload:c.action.args}),i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:T.expect,action:C.bind(null,{subjectId:p.id,subjectName:"chapter"})})}else p.events?.forEach(m=>{let u=h({chapterId:p.id,action:m.action,branches:p.branches});u&&i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:m.action.type,action:u})})}let C=({subjectId:p,subjectName:c})=>{t.pause(),n.emit(I.interactives,{subjectId:p,subjectName:c,type:R.actionExecution,actionType:T.expect}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,type:"action-execution",actionType:T.expect})},b=({subjectId:p,subjectName:c})=>{t.info.isEnded$.getValue()?i.execEndOfVideo():t.play(),n.emit(I.interactives,{subjectId:p,subjectName:c,type:R.actionExecution,actionType:vi}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,type:"action-execution",actionType:vi})},P=({subjectId:p,subjectName:c,subjectType:m,action:u})=>{n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:u.type})},x=({subjectId:p,subjectName:c,subjectType:m,action:u,payload:f})=>{f.behaviour="change-chapter",n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:u.type,payload:f}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:u.type,payload:f})},y=({subjectId:p,subjectName:c,subjectType:m,action:u,payload:f})=>{if(!f.URI)return;let g=window.open(f.URI,"_blank","noopener,noreferrer");g&&(g.opener=null),n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:u.type})};return{onControlEvent:l,onContainerEvent:s,onChapterEvent:h,onExpectEvent:C,expectEventHandler:b,setManifestChapterEvents:v,setManifestContainerEvents:a,stopExpect:o,state:r}};import{Subscription as nn,Subject as St,ValueSubject as be}from"@vkontakte/videoplayer-shared/evergreen";var At=(n,e)=>{let t={};return n.map(i=>{if(!t[i]){let r=e.chapters.find(l=>l.id===i);if(!r)return null;let o=e.media.videos.find(l=>r.videoId===l.id);if(!o)return null;t[i]=yi(o)}return t[i]}).filter(Boolean)},Ji=n=>{for(let e of n.variants)if(en(e)&&e.payload)return e.payload.id},en=n=>!!(n.type==="custom"&&n.payload&&n.payload.type==="vk"),yi=n=>{let e=Ji(n);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},tn=(n,e)=>{for(let t of n.media.videos)if(e===yi(t)){for(let i of n.chapters)if(i.videoId===t.id)return i.id;return}},Ci=(n,e)=>n.reduce((t,i)=>{let r=tn(e,i);return r?[...t,r]:t},[]);var ye=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:i,historyApi:r,settings:o}){this.state={history$:new be([]),hasPrevChapter$:new be(!1),prevChapter$:new be(null),isInitialChapter$:new be(!1),isGoBackLimited$:new be(!1)};this.#i=null;this.#s=!1;this.#e=null;this.#p=null;this.events={inited$:new St,destroyed$:new St,error$:new St};this.#n=null;this.#r=null;this.#t=null;this.#a=new nn;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(l=>{this.state.prevChapter$.next(l.at(-2)||null),this.state.hasPrevChapter$.next(l.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,l=At(o,i);if(this.#p=l,this.state.history$.next(o),!(!t||!this.#i||!this.#n))try{await this.#i.save(this.#n,l)}catch{let a=new V(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 V(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 V(1,5,"Error while trying to fetch data");this.events.error$.next(o),this.#t?.emit(I.errors,o)}let i=Ci(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 At([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 Ze=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 qe=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=`
6
+ var Mt="1.0.36-dev.cf7ccf83.0";import{fromEvent as qt,Subscription as Li}from"@vkontakte/videoplayer-shared/evergreen";var et=class{constructor(e){this.layout=e}},Ee=class extends et{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})`,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))`}};import{Subject as wi}from"@vkontakte/videoplayer-shared/evergreen";function Vt(n){return"features"in n}var V=class{constructor(e,t,...i){this.severity=e;this.category=t;this.data=i}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};function Ie({emitter$:n,error:e,subjectId:t,message:i="",severity:r=1,category:o=1}){let l=new V(r,o,{message:i,error:e,details:{id:t}});n.next(l)}var J=class{constructor(e,t){this.error$=new wi;this.container=e,this.options=t,this.factories=new Map,this.controls=[],this.setControls()}featureIsEnabled(e){return this.options&&Vt(this.options)&&this.options.features[e]}onError(e="",t){Ie({emitter$:this.error$,error:t,message:e,subjectId:this.container.id})}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 le,once as Qt}from"@vkontakte/videoplayer-shared/evergreen";var G=(n,e)=>Object.prototype.toString.call(n)===`[object ${e}]`,z=n=>G(n,"Object"),Te=n=>G(n,"String"),xe=n=>G(n,"Array"),Ae=n=>G(n,"Number"),Pt=n=>G(n,"Function"),Lt=n=>G(n,"Boolean"),nt=n=>Ae(n)&&!isNaN(n);var Q=n=>z(n)&&Object.keys(n).length===0,rt=n=>xe(n)&&!n.length;var re=(n,e)=>Te(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 Ot="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||{}),Nt=(i=>(i.start="left",i.end="right",i.center="center",i))(Nt||{}),Se=({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&&Nt[e.alignment])??"center"},we=({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},Re=({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})`,l=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=l},Bt=({target:n,isDark:e,baseDimension:t,fallback:i})=>{let l=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:l}`;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 ae,Subject as Vi,Subscription as Pi}from"@vkontakte/videoplayer-shared/evergreen";function ke(n){for(;n>Math.PI;)n-=2*Math.PI;for(;n<=-Math.PI;)n+=2*Math.PI;return n}function jt(n){return n*180/Math.PI}var ot="interactive-control-tap",te={common:ot,animation:`${ot}-animation`,visible:`${ot}-visible`};var Ri=60,Me=class{constructor({controlRotateAngleRad:e,clickCancelCondition:t,circleDiameterPx:i=Ri,useDimensionsBasedSize:r=!1}){this.onElementClick=e=>{if(!e.target||!e.currentTarget||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),l=i.left+i.width/2,s=i.top+i.height/2,a=e.clientX-l,h=e.clientY-s,d=ki(a,h,ke(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.stopPropagation(),!(!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 ki(n,e,t){return{x:n*Math.cos(t)-e*Math.sin(t),y:n*Math.sin(t)+e*Math.cos(t)}}var st="int",X=(i=>(i.AREA=`${st}_area`,i.TEXT=`${st}_text`,i.BUTTON=`${st}_bttn`,i))(X||{});function at(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;import{isSupportedManifest as Pe,ContainerTypes as qn,ControlTypes as Le,EventActionTypes as T,EventTypes as Yn,migrateManifestToLatestVersion as Ut,compareVersions as Jn}from"@interactiveplatform/movika-manifest";var Dt={metadata:"Object",chapters:"Array"},Ht=n=>{if(!z(n))return!1;for(let e in Dt)if(!n[e]||!G(n[e],Dt[e]))return!1;return Pe(n.metadata.version)},Ve=n=>n.type===Le.Text,Hn=n=>n.type===Le.Button,Un=n=>n.type===Le.Area,Gn={Choice:"Choice",TextInput:"TextInput"},zn={Button:"Button",Area:"Area",Text:"Text"},Wn={onClick:"onClick",onSuspense:"onSuspense"},Kn={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var Oe=n=>xe(n)&&!rt(n),H=n=>n.order==="end",$e=n=>xe(n.containers)&&!rt(n.containers)&&H(n),Gt=(n,e)=>{let t=n*1e3;return Oe(e.controls)&&t<(e.startTime??0)},lt=(n,e)=>{let t=n*1e3;return Oe(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"),Mi=n=>n?.length===1,ie=n=>Mi(n)&&Ve(n[0]);function zt(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&&!i.willRemoved)}function Fe({gameControllers:n=[],subjectName:e,subjectId:t,execFn:i}){for(let r of n)if(e==="container"&&r.container.container.id===t){i(r),zt(n,r.container.container.endTime,[r.container.container.id]).forEach(l=>{i(l)});break}}function Wt(n){for(let e of n.events)if(e.action.type==="openURI")return!0;return!1}var Kt=(n,e)=>{let t=x=>e.find(({container:p})=>p.container.id===x)?.container.isRemoved,i=Z(n.events)&&!t(n.id),r=(x,y=!1,p=!1)=>{let c=p?"every":"some";return x.controls[c](m=>{let u=y?x.endTime===n.endTime:!0;return m.events?.[c](f=>f.action?.type===T.openURI)&&u})},o=x=>x.some(({container:y})=>r(y.container,!0,!1)&&!y.isRemoved),l=x=>x.every(({container:y})=>y.isRemoved||y.willRemoved?!0:r(y.container,!0,!0)),s=zt(e,n.endTime,[n.id]).length,a=x=>x.controls.some(y=>y.events?.some(p=>p.action?.args?.shouldOpenNow)),h=i||s>0,d=o(e),v=r(n),C=l(e),b=i?!1:s>0,P=a(n);return{isExpectTime:h,hasOtherExpect:s>0,hasOpenURIEvent:d,hasOpenURIEventInCurrentContainer:v,isAllOpenURIEventsValid:C,isExpectEventForCurrentContainer:b,hasShouldOpenNowEvent:P}};var W=class n{constructor(e,t){this.control=e;this.options=t;this.container=null;this.controlElement=null;this.subscriptions=new Pi;this.error$=new Vi;this.isInteracted=!1;this.isRemoved=!1;this.onControlSelect=()=>{this.container?.isManifestContainerDisabled()||Wt(this.control)||this.container?.element?.classList.add("interactive-control-wrapper-selected")};this.onTransitionEnd=e=>{e.stopPropagation(),!(!e.target||!e.currentTarget)&&e.target===e.currentTarget&&this.removeView()}}removeView(e=!1){let t=this.getElement();if(t){if(e){if(t.classList.contains("interactive-control-before-remove"))return;t.classList.add("interactive-control-before-remove"),this.subscriptions.add(ae(t,"transitionend").subscribe(this.onTransitionEnd,r=>this.onError(`${n.name} remove view transition error`,r))).add(ae(t,"transitioncancel").subscribe(this.onTransitionEnd,r=>this.onError(`${n.name} remove view transition error`,r)));return}this.removeListeners(),t.remove(),this.isRemoved=!0}}onError(e="",t){Ie({emitter$:this.error$,error:t,message:e,subjectId:this.control.id})}addControlTap(e){if(this.featureIsEnabled("controlsTapPlace")&&this.container){let t=this.control.layoutParams.angle??w.angle;this.controlTap=new Me({controlRotateAngleRad:t,clickCancelCondition:this.container.isManifestContainerDisabled,circleDiameterPx:this.isTouch()?_t:void 0}),this.subscriptions.add(ae(e,"click").subscribe(this.controlTap.onElementClick,i=>this.onError("Control click tap animation error",i))).add(ae(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=!0,e()}}featureIsEnabled(e){return this.options&&at(this.options)&&this.options.features[e]}isTouch(){return this.options&&at(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(ae(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 pt="interactive-blink-anim-reference",L={common:pt,animation:`${pt}-animation`,disabled:`${pt}-disabled`},Ne=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 ht="interactive-container",O={common:ht,hidden:`${ht}-hidden`,disabled:`${ht}-disabled`};var Be=(n,e)=>{if(n.type.trim().toLowerCase()==="area")return new mt(n,e)},mt=class extends W{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;this.isInteracted=!1,this.isRemoved=!1;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.area),i.setAttribute("data-testid",X.AREA),Re({target:i,props:this.control.props,fallback:{...w,backgroundColor:"transparent"}}),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),this.addControlTap(i),this.subscriptions.add(le(this.container.element,"click").pipe(Qt()).subscribe(this.onControlSelect,r=>this.onError("Control click handler error",r))),this.container.element.append(i),e.append(this.container.element),this.controlElement=i,this.updateShadowStyles(),this.registerBlinkAnimationEvents()}registerBlinkAnimationEvents(){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}updateShadowStyles(e){if(!(!this.container||!this.controlElement))if(Lt(e)){let t=Math.min(this.controlElement.offsetWidth,this.controlElement.offsetHeight)+"px";Bt({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(le(e,"animationiteration").pipe(Qt()).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 ce,once as Xt}from"@vkontakte/videoplayer-shared/evergreen";var je=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 U="interactive-control-fill-animation",$={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 _e=class n{constructor(e){this.widthExpansionCoef=0;let t=document.createElement("div");t.classList.add($.common);let i=document.createElement("div");i.classList.add($.fillerWrapper);let r=document.createElement("div");r.classList.add($.filler),i.append(r),t.append(i);let o=ke(e.rotateAngle),l=o>Math.PI/2&&o<=Math.PI||o<0&&o<-Math.PI/2,s=o===Math.PI/2,a=o===-Math.PI/2,h=!l&&!s&&!a,d=s||a,v=!!(o%Math.PI/2)&&!d,C=v?o:0;t.style.borderRadius=e.borderRadius,i.style.transform=`skew(${C*-1}rad)`,d?(r.classList.add($.fillHeight,s?$.fromTop:$.fromBottom),i.classList.add($.fillHeight,s?$.fromTop:$.fromBottom)):(r.classList.add($.fillWidth,h?$.fromLeft:$.fromRight),i.classList.add($.fillWidth)),e.debug&&console.log(`[interactive ${n.name}]`,{widthExpansionCoef:this.widthExpansionCoef,opts:e,shouldFillHeight:d,rotateAngleRad:o,rotateAngelDeg:jt(o),rotateAngleRaw:e.rotateAngle,fromRight:l,fromTop:s,fromBottom:a,fromLeft:h}),this.useSkew=v,this.fromLeft=h,this.rotateAngle=o,this.fillAnimationElement=t,this.fillAnimationFillerElement=r,this.fillAnimationFillerWrapperElement=i,this.startTime=e.startTime,this.endTime=e.endTime,this.shouldFillHeight=d,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 De=(n,e)=>{if(n.type.trim().toLowerCase()==="button")return new dt(n,e)},dt=class extends W{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;this.isInteracted=!1,this.isRemoved=!1;let i=document.createElement("button");i.type="button",i.classList.add(S.common,S.button),i.setAttribute("data-testid",X.BUTTON),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),Re({target:i,props:this.control.props,fallback:w}),se({target:i,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),Se({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=je(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;we({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 _e({startTime:this.startTime,endTime:this.endTime,rotateAngle:this.control.layoutParams.angle??w.angle,borderRadius:i.style.borderRadius})),this.subscriptions.add(ce(i,"click").pipe(Xt()).subscribe(this.onControlSelect,l=>this.onError("Control click handler error",l))),i.append(r,this.controlFillAnimation?.fillAnimationElement??""),this.container.element.append(this.controlTap?.element??"",i),e.append(this.container.element),this.controlElement=i,this.registerBlinkAnimationEvents()}registerBlinkAnimationEvents(){if(!this.featureIsEnabled("controlsExpectTimeBlinkAnimation"))return;let e=this.container?.element.parentElement;!e||!this.controlElement||(this.subscriptions.add(ce(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(ce(this.controlElement,"mouseenter").subscribe(()=>{e.classList.contains(O.disabled)||this.onBlinkHovering()},t=>this.onError("Error happened in mouseenter callback",t))).add(ce(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(ce(e,"animationiteration").pipe(Xt()).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 Zt=(n,e)=>{if(n.type.trim().toLowerCase()==="text")return new ut(n,e)},ut=class extends W{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;this.isInteracted=!1,this.isRemoved=!1;let i=document.createElement("div");i.classList.add(S.common,S.text),i.setAttribute("data-testid",X.TEXT),ee({target:i,layoutParams:this.control.layoutParams,fallback:w}),Se({target:i,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=je(this.control.type.trim().toLowerCase()),o=r.firstElementChild??r;we({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(){}};var He=(n,e,t)=>{if(n.type.trim().toLowerCase()==="choice")return new ft(n,e,t)},ft=class n extends J{constructor(t,i,r){super(t,r);this.containerElement=null;this.subscriptions=new Li;this.onTransitionEnd=t=>{t.stopPropagation(),!(!t.target||!t.currentTarget)&&t.target===t.currentTarget&&this.removeView()};this.rootElement=i,this.layout=new Ee(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",De),this.addControlFactory("text",Zt),this.addControlFactory("area",Be)}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.subscriptions.add(o.error$.subscribe(this.error$))}),this.rootElement.append(r),this.isRemoved=!1,this.willRemoved=!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(t=!1,i=!1){let r=this.getElement();if(r){if(t){if(this.willRemoved)return;this.willRemoved=!0,i&&r.classList.add("interactive-container-before-remove-delay"),r.classList.add("interactive-container-before-remove"),this.subscriptions.add(qt(r,"transitionend").subscribe(this.onTransitionEnd,l=>this.onError(`${n.name} remove view transition error`,l))).add(qt(r,"transitioncancel").subscribe(this.onTransitionEnd,l=>this.onError(`${n.name} remove view transition error`,l)));return}this.subscriptions.unsubscribe(),this.removeAllControls(),r.remove(),this.isRemoved=!0,this.willRemoved=!1,this.containerElement=null}}removeAllControls(t=!1){this.controls.forEach(i=>i.removeView(t))}removeNonInteractedControls(t=!1){this.controls.forEach(i=>{i.isInteracted||i.removeView(t)})}isInteracted(){return this.controls.some(t=>t.isInteracted)}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 on,InterfaceLanguage as sn,Observable as Ti,once as an,Subject as F,Subscription as wt,ValueSubject as j,fromEvent as xi}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as Ce}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as Oi}from"@vkontakte/videoplayer-shared/evergreen";function pe(n,e){let t;return(...i)=>{clearTimeout(t),t=setTimeout(()=>n(...i),e)}}var Yt="video_interactive",Jt="videoint";var ei=250,he=class{constructor(e){this.handleZoomChange=pe(e=>{this.lastZoomInfo=e},ei);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,!Ae(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=$i(e),this.resizeObserver=new ResizeObserver(pe(this.onResize,ei)),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 Oi(this.lang,Yt,Jt)}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 $i(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 me=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 l=o.startTime-e;if(l<=r&&(o.endTime&&r<=o.endTime||o.endTime===null)){i=!0;break}r<l&&(t=t===-1?l:Math.min(t,l))}return!i&&t!==-1?t:null}}};var Ue=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 Ge=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{Pt(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 Di}from"@vkontakte/videoplayer-shared/evergreen";var ze=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Fi(...this.loaders[e])(t)}};function Fi(...n){return async function(t){let i=[...n];for(;i.length>0;)t=await i.shift()(t);return t}}function de(n,e,t){return n?{...n,[e]:n[e]?[t,...n[e]]:[t]}:{[e]:[t]}}function We({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 l=n.getMedia(r.media,o.videoId),s=n.getGraph(r.graph,o.id);return l?{...i,actions:n,errors:e,result:{chapter:o,media:l,graph:s}}:{...i,errors:de(e,We.name,"Could not find media"),actions:n}}}}return{...i,errors:de(e,We.name,"Could not find chapter"),actions:n}}var vt=(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 Ni=async n=>{try{let e={},t;if(Te(n)){t=new URL(n).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(z(n))e=n;else return{};if(!Ht(e))return{};let i=e.metadata.media;if(Te(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 _i(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function ti(n){let{manifest:e,manifestURL:t}=await Ni(n);if(!e)throw new Error("Failed on fetch");let i=Ut(e);return i.media=Bi(i.media,t),delete i.metadata.media,i}function Ke(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 yt(n,e){return n.videos.find(t=>t.id===e)}function Bi(n,e){return{...n,videos:n.videos.map(t=>({...t,variants:t.variants.map(i=>{let r="url"in i?i.url:"",o=ji(r,e);return{...i,url:o||r}})}))}}function ji(n="",e){try{return new URL(n,e).href}catch{return""}}function _i(n){return vt(n,"3.2.0")>=0}var ne=class extends ze{constructor(t,i){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new Di(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:de},result:null,errors:null,source:t});return i.errors&&this.errorHandler(i.errors),this.manifest=await ti(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",We({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:bt,getChapter:Ke,getMedia:yt,getByBranches:this.getByBranches.bind(this),addErrorMessage:de},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=Ke(this.manifest.chapters,t);if(i){let r=yt(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=Ke(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 Hi}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as Et,Tracer as Ui,ValueSubject as Gi}from"@vkontakte/videoplayer-shared/evergreen";var ii=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 Ct(){let n=new Map;function e({listId:o=Math.random().toString(),itemId:l=Math.random().toString(),...s}){let a=n.get(o),h={...s};return a?a[l]=h:n.set(o,{[l]:h}),{listId:o,itemId:l,...s}}function t(o){o.player.destroy(),o.container.remove(),o.subscription.unsubscribe(),o.statistics?.oneStat.destroy(),o.statistics?.statSubscription.unsubscribe()}function i(o,l){let s=n.get(o);if(!s)throw Error("Can't remove. Not find.");if(l){let a=s[l];a&&t(a),delete s[l],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 gt(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 ue=(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 zi=2;function It(n){let e=Ct(),t=new Et,i={},r=null,o=!1,l,s=new Gi(null);n&&a(n);function a(y){r=y}function h(y,p,c){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let u=(e.map.get(y)??{})[p];if(u){i={chapterId:c,listId:y,itemId:p,...u};let f=i.player;i.subscription.add(f.info.currentQuality$.subscribe(g=>{let A=f.info.position$.getValue(),N=f.info.isAutoQualityEnabled$.getValue();if(!(!g||!A||N))for(let E of e.map)Object.values(E[1]).forEach(({player:k})=>{ue(k,g)})})).add(f.events.started$.subscribe(()=>{d(p)})),u.container.remove(),r.setPlayer(u.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(y){if(!r)throw Error("need to set interactive controller");if(Q(i)||y!==i.itemId)return;let p=r.getChapterBranches(),c=new Set;for(let m of p)c.has(m.media.id)||(await C({media:m.media,chapterId:m.chapter.id,setAsActive:!1,title:m.chapter.label}),c.add(m.media.id))}async function v({chapter:{id:y},manifestVideo:p}){if(Q(i)||!r)return;let c=i.player.info.muted$.getValue(),m=i.player.info.currentQuality$.getValue(),u=i.player.info.isAutoQualityEnabled$.getValue(),f=i.player.info.volume$.getValue(),g=i.player.info.currentPlaybackRate$.getValue(),A=!u,N=!1;for(let E of e.map)if(E[0]===p.id&&!r.state.isReplay$.getValue()){let k=Object.keys(E[1]);for(let M of k)M===i.itemId?(k.length<zi||(N=!0),e.removePlayer(E[0],M)):(N=!0,h(E[0],M,y),A?ue(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(f),i.player.setMuted(c),i.player.setPlaybackRate(g))}else e.removePlayer(E[0]);N||(await C({media:p,chapterId:y,setAsActive:!0,playbackRate:g}),A?ue(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(f),i.player.setMuted(c))}async function C({media:y,chapterId:p,prefetch:c=!0,setAsActive:m=!0,autoplay:u=!1,preferredExt:f,title:g,playbackRate:A}){let N=Math.random().toString(),E=document.createElement("div");l.append(E);let k;if(r?.options?.vkVideoLoader){let ge=ii(y);ge.length&&(k=await r.options.vkVideoLoader(...ge))}let M=r?.options?.coreConfig||void 0,_={...M,configName:[...M?.configName??[],"interactive"]},K={container:E,...k?.videos?.[0]||{sources:gt(y,f).sources},title:g,failoverHosts:k?.failoverHosts||[]},B=new Hi(_,Ui.createRootTracer());B.initVideo(K);let q=null;if(k?.videos&&r?.options.createOneStat){let ge=k.videos[0],Je=r.options.createOneStat(ge),kt=new Et;Je&&(kt.add(Je.attachTo(B)),q={oneStat:Je,statSubscription:kt})}let Rt=new Et,Si=i?.player?.info.isAutoQualityEnabled$.getValue();Rt.add(B.events.canplay$.subscribe(function(){Si||ue(B,i.player.info.currentQuality$.getValue()),A&&B.setPlaybackRate(A)}));let Y=e.createPlayer({listId:y.id,itemId:N,player:B,container:E,sources:gt(y,f).sources,config:K,subscription:Rt,statistics:q});return m&&h(y.id,Y.itemId,p),u&&Y.player.play(),c&&!u&&Y.player.prepare(),{player:Y.player,config:Y.config,statistics:Y.statistics}}function b(){P(),r=null,l.remove()}function P(){t.unsubscribe(),e.removeAll(),i={},o=!1}async function x(){if(!r)throw Error("need to set interactive controller");P(),l=document.createElement("div");let{media:y,chapter:p}=r.getCurrentChapter();y&&p?(t.add(r.events.chapterChanged$.subscribe(v)),await C({media:y,chapterId:p.id,title:p.label})):console.error("not found")}return{...e,init:x,setInteractiveController:a,createPlayer:C,removeAll:b,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"},fe={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},R={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as Wi}from"@vkontakte/videoplayer-shared/evergreen";function Tt(n){return function(...t){return n(...t.reverse())}}function ve(n,...e){return(...t)=>z(e[0])&&z(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:l,globalEventEmitter:s,getContainerEventState:a,permanentTextControls:h,interactiveTimeOpenUri:d,disabledControls$:v,onRemove:C,onError:b,features:P}){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,l)=>{let{isExpectTime:s,hasOtherExpect:a,hasOpenURIEvent:h,hasOpenURIEventInCurrentContainer:d,isAllOpenURIEventsValid:v,hasShouldOpenNowEvent:C}=this.getContainerEventState(),b=this.interactiveTimeOpenUri&&!d,P=this.interactiveTimeOpenUri&&d;if((!this.interactiveTimeOpenUri||b)&&(this.isSelectedControlEvent=!0),o!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||b)){if(this.interactiveTimeOpenUri){let x=!a&&!v&&d;x&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:x})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&h&&this.gameState!==5){if(P){let y=((p,c,m,u)=>!p&&!c&&m||p&&!c&&m&&!u||p&&!c&&m&&u)(s,a,v,this.isSelectedContainerEvent);this.fakeRemoveView(y)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!s||!a||!C)&&(this.selectBranches.stopExpect(),l())}},isEOV:()=>this.gameState===4},i=ve(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();if(!(e instanceof HTMLVideoElement?e.readyState:void 0)||this.isRemovedOrDestroyed()&&!this.isPermanentText)return;let r=this.player.getExactTime();if(Gt(r,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(lt(r,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let a=this.gameState;this.gameState=3,a===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:a}=this.getContainerEventState(),h=this.selectBranches.state.isExpect,d=this.interactiveTimeOpenUri&&a;if(d&&!h){let v=this.container.getElement();v&&(v.style.visibility!=="hidden"&&this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView())}!this.isPermanentText&&!d&&this.removeView()}let o=lt(r,this.container.container),l=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],s={subjectId:this.container.container.id,subjectName:"container",range:l,currentTime:r,isInteractiveTime:o};this.container.onProgress(r*1e3,o),this.globalEventEmitter.emit(I.eachTick,s),this.globalEvents.eachTick$.next(s)};this.container=t,this.branches=i,this.selectBranches=r,this.subscription=new Wi,this.player=e,this.interactiveEvents=o,this.getContainerEventState=a,this.isPermanentText=h&&ie(t.container.controls),this.interactiveTimeOpenUri=d,this.disabledControls$=v,this.onRemove=C,this.globalEventEmitter=s,this.gameState=0,this.globalEvents=l,this.onError=b,this.features=P,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:R.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:R.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(e=this.features.controlsHideAnimation){if(e){if(this.isRemovedOrDestroyed())return;this.container.removeNonInteractedControls(!0),this.container.removeView(!0,!0)}else this.container.removeView();this.globalEventEmitter.emit(I.interactives,{subjectId:this.container.container.id,subjectName:"container",type:R.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)}isInteracted(){return this.container.isInteracted()}isRemovedOrDestroyed(e=!0){let t=e?this.container.willRemoved:!1;return this.gameState===5||t||this.gameState===6}destroy(e=!1){this.reset(),this.removeView(e),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 ri=(n=[])=>n.reduce((e,t,i)=>{let r=(t?.controls??[]).filter(o=>!Ve(o));if(Oe(r)){let o=[t.startTime??0,t.endTime??1/0],l={id:t.id,isRemoved:!1};if(!i)e.push({subjects:[l],range:o});else{let s=[],a=-1/0,h=1/0,d=[],v=[];for(let C=0;C<e.length;C++){let b=e[C];if(v.push(...b.subjects),b.range[0]<h&&(h=b.range[0]),b.range[1]>a&&(a=b.range[1]),o[0]>=b.range[0]&&o[1]<=b.range[1])return e[C].subjects.push(l),e;o[0]<b.range[0]&&o[1]>b.range[0]&&(s.push(C),d=d.concat(b.subjects)),o[0]>=b.range[0]&&o[0]<=b.range[1]&&(s.push(C),d=d.concat(b.subjects),o[0]=b.range[0]),o[1]>=b.range[0]&&o[1]<=b.range[1]&&(s.push(C),d=d.concat(b.subjects),o[1]=b.range[1])}if(v.push(l),o[0]<=h&&o[1]>=a)return[{subjects:v,range:o}];s.length&&s.reverse().forEach(C=>{e.splice(C,1)}),e.push({subjects:d.concat([l]),range:o})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function oi(){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(nt(s)){let d=n[s]??null;if(d&&a&&re(a,!0)){let v={},C=d[a];return C&&(v={...v,...C}),v=Q(v)?null:v,v&&re(h,!0)?v[h]??null:v}return d}return null}function o({timestamp:s,priority:a,initiator:h}){if(nt(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],!Q(n[s][a]))return!0}else return!1;if(delete n[s][a],!Q(n[s]))return!0}else return!1;return delete n[s]}else return!1;return!1}function l({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:l,removeAll:e,get:r,getLte:t,getGte:i}}var Ki=[T.expect,T.setNextBranch],Qi=1/0;function si(n,e){let t=n,i,r=Xi(e),o=oi(),l,s=()=>{b(),p()},a=c=>{o.add.call(void 0,c),P()},h=(c=[])=>{for(let m of c)if(m.action(),Ki.includes(m.actionType))break},d=(c=1/0)=>{let m=Xe(o.get({timestamp:c,priority:"control"})??{}),u=Xe(o.get({timestamp:c,priority:"container"})??{}),f=Xe(o.get({timestamp:c,priority:"chapter"})??{});return[...m,...u,...f]},v=c=>{r.isReady(c)&&h(d(c))},C=()=>{h([...Xe(o.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{i&&(l?.unsubscribe(),i=void 0)},P=()=>{i||(i=()=>setTimeout(()=>{v(1/0)}),l=t.events.ended$.subscribe(i))},x=c=>{b(),t=c},y=c=>{c.priority==="container"&&r.resetCalled(c.timestamp),o.remove(c)},p=()=>{r.release(),o.removeAll()};return{setPlayer:x,add:a,remove:y,exec:v,execEndOfVideo:C,listen:P,unlisten:b,release:s,containersEventsCallState:r,getPreparedToExecActions:d}}function Xi(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??Qi,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===T.expect?-1:1)}var ai={videoContentHeight:0,videoContentWidth:0},li=n=>{let{height:e,width:t}=n.info.intrinsicVideoSize$.getValue()||{};if(!(e&&t))return ai;let{clientHeight:i,clientWidth:r}=n.experimental.element$.getValue()||{};if(!(i&&r))return ai;let o=e/t,l=i/r,s,a;return l>o?(a=r,s=r*o):l<o?(a=i/o,s=i):(a=r,s=i),{videoContentWidth:a,videoContentHeight:s}};var Zi=250;function ci(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}=li(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=pe(s=>{let{fns:a=[]}=n();i(s);for(let h of a)h()},Zi);function l(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:l}}var qi=n=>Math.floor(Math.random()*n),hi=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},mi=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 di=n=>{let e=n.length,t=qi(e);return n[t]},pi=1,ui=n=>{let e=0;for(let i=0;i<n.length;++i)e+=n[i].weight??pi;let t=Math.random()*e;e=0;for(let i=0;i<n.length-1;++i)if(e+=n[i].weight??pi,e>=t)return n[i];return n[n.length-1]};var fi={shouldOpenNow:!0,isDetachContainer:!0},vi="after-expect",xt=(n,e=!1)=>({...n,args:e?{...n.args,...fi}:{...fi,...n.args}}),bi=({globalEventEmitter:n,globalEvents:e,player:t,interactiveEvents:i})=>{let r={isExpect:!1},o=()=>{r.isExpect&&(r.isExpect=!1)},l=({action:p,controlType:c,controlId:m,containerId:u,branches:f=[],onEvent:g,isEOV:A=()=>!1,isDisabled:N=()=>!1})=>{let E=xt(p,A()),k={timestamp:1/0,priority:"control",initiator:m,actionType:E.type},M=N(),_=n.emit.bind(n,I.interactives,{subjectId:m,subjectType:c,subjectName:"control",type:M?R.actionChoiceCanceled:R.actionChoice,actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:u,...E.args}}),K=()=>{e.interactiveActionChoice$.next({subjectId:m,subjectType:c,subjectName:"control",type:M?"action-choice-canceled":"action-choice",actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:u,...E.args}})};if(M){_(),K();return}switch(E.type.trim().toLowerCase()){case T.setNextBranch.trim().toLowerCase():{let B=f.find(q=>q.id===E.args.branchId);if(!B)return;g(E.args.isDetachContainer,b.bind(null,{subjectId:m,subjectName:"control"})),_(),K(),E.args.shouldOpenNow?x({subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}}):i.add({...k,action:x.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}})});return}case T.continuePlayback.trim().toLowerCase():{g(E.args.isDetachContainer,b.bind(null,{subjectId:m,subjectName:"control"})),_(),K(),E.args.shouldOpenNow?P({subjectId:m,subjectName:"control",subjectType:c,action:p}):i.add({...k,action:P.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:p})});return}case T.openURI.trim().toLowerCase():{g(E.args.isDetachContainer,b.bind(null,{subjectId:m,subjectName:"control"})),_(),K(),E.args.shouldOpenNow?y({subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{URI:p.args.uri}}):i.add({...k,action:y.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{URI:p.args.uri}})});return}default:{let B="Unexpected control event",q=new V(1,1,{message:B});d(q,B);return}}},s=({action:p,container:{id:c,endTime:m},branches:u=[],isEOV:f=!1,autoSelected:g=!1})=>{let A=xt(p,f),N={timestamp:!A.args.shouldOpenNow||f?1/0:m??1/0,priority:"container",initiator:c,actionType:A.type},E=n.emit.bind(n,I.interactives,{subjectId:c,subjectName:"container",type:R.actionChoice,actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}}),k=()=>{e.interactiveActionChoice$.next({subjectId:c,subjectName:"container",type:"action-choice",actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}})};switch(A.type.trim().toLowerCase()){case T.setNextBranch.trim().toLowerCase():{let M=u.find(_=>_.id===A.args.branchId);if(!M)return;E(),k(),i.add({...N,action:x.bind(null,{subjectId:c,subjectName:"container",action:A,payload:{chapterId:M.chapterId,autoSelect:g}})});return}case T.setMaxWeightBranch.trim().toLowerCase():return;case T.setMinWeightBranch.trim().toLowerCase():return;case T.setRandomBranch.trim().toLowerCase():return;case T.setWeightlessRandomBranch.trim().toLowerCase():return;case T.continuePlayback.trim().toLowerCase():{E(),k(),i.add({...N,action:P.bind(null,{subjectId:c,subjectName:"container",action:A})});return}case T.openURI.trim().toLowerCase():{E(),k(),i.add({...N,action:y.bind(null,{subjectId:c,subjectName:"container",action:A,payload:{URI:p.args.uri}})});return}default:{let M="Unexpected container event",_=new V(1,1,{message:M});d(_,M);return}}};function a({container:p,branches:c,isEOV:m=!1}){let u=ct(p.events);if(u){let f=xt(u.action,m);n.emit(I.interactives,{subjectId:p.id,subjectName:"container",type:R.actionChoice,actionType:f.type,payload:{invokeImmediately:f.args.shouldOpenNow,...f.args}}),e.interactiveActionChoice$.next({subjectId:p.id,subjectName:"container",type:"action-choice",actionType:f.type,payload:{invokeImmediately:f.args.shouldOpenNow,...f.args}}),i.add({timestamp:m?1/0:p.endTime??1/0,priority:"container",initiator:p.id,actionType:T.expect,action:C.bind(null,{subjectId:p.id,subjectName:"container"})}),r.isExpect=!0}else for(let f of p.events??[])s({action:f.action,container:p,branches:c,isEOV:m})}let h=({chapterId:p,action:c,branches:m=[]})=>{let u=n.emit.bind(n,I.interactives,{subjectId:p,subjectName:"chapter",type:R.actionChoice,actionType:c.type,payload:c.args}),f=()=>{e.interactiveActionChoice$.next({subjectId:p,subjectName:"chapter",type:"action-choice",actionType:c.type,payload:c.args})};switch(c.type.trim().toLowerCase()){case T.setNextBranch.trim().toLowerCase():{let g=m.find(A=>A.id===c.args.branchId);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setWeightlessRandomBranch.trim().toLowerCase():{let g=di(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setRandomBranch.trim().toLowerCase():{let g=ui(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setMaxWeightBranch.trim().toLowerCase():{let g=mi(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.setMinWeightBranch.trim().toLowerCase():{let g=hi(m);return g?.chapterId?(u(),f(),x.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case T.continuePlayback.trim().toLowerCase():return u(),f(),P.bind(null,{subjectId:p,subjectName:"chapter",action:c});case T.openURI.trim().toLowerCase():return u(),f(),y.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{URI:c.args.uri}});default:{let g="Unexpected chapter event",A=new V(1,1,{message:g});d(A,g);return}}};function d(p,c){console.error(c),e.error$.next(p),n.emit(I.errors,p)}function v(p){let c=ct(p.events);if(c){if(H(p))return;n.emit(I.interactives,{subjectId:p.id,subjectName:"chapter",type:R.actionChoice,actionType:c.action.type,payload:c.action.args}),e.interactiveActionChoice$.next({subjectId:p.id,subjectName:"chapter",type:"action-choice",actionType:c.action.type,payload:c.action.args}),i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:T.expect,action:C.bind(null,{subjectId:p.id,subjectName:"chapter"})})}else p.events?.forEach(m=>{let u=h({chapterId:p.id,action:m.action,branches:p.branches});u&&i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:m.action.type,action:u})})}let C=({subjectId:p,subjectName:c})=>{t.pause(),n.emit(I.interactives,{subjectId:p,subjectName:c,type:R.actionExecution,actionType:T.expect}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,type:"action-execution",actionType:T.expect})},b=({subjectId:p,subjectName:c})=>{t.info.isEnded$.getValue()?i.execEndOfVideo():t.play(),n.emit(I.interactives,{subjectId:p,subjectName:c,type:R.actionExecution,actionType:vi}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,type:"action-execution",actionType:vi})},P=({subjectId:p,subjectName:c,subjectType:m,action:u})=>{n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:u.type})},x=({subjectId:p,subjectName:c,subjectType:m,action:u,payload:f})=>{f.behaviour="change-chapter",n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:u.type,payload:f}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:u.type,payload:f})},y=({subjectId:p,subjectName:c,subjectType:m,action:u,payload:f})=>{if(!f.URI)return;let g=window.open(f.URI,"_blank","noopener,noreferrer");g&&(g.opener=null),n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:u.type})};return{onControlEvent:l,onContainerEvent:s,onChapterEvent:h,onExpectEvent:C,expectEventHandler:b,setManifestChapterEvents:v,setManifestContainerEvents:a,stopExpect:o,state:r}};import{Subscription as nn,Subject as St,ValueSubject as be}from"@vkontakte/videoplayer-shared/evergreen";var At=(n,e)=>{let t={};return n.map(i=>{if(!t[i]){let r=e.chapters.find(l=>l.id===i);if(!r)return null;let o=e.media.videos.find(l=>r.videoId===l.id);if(!o)return null;t[i]=yi(o)}return t[i]}).filter(Boolean)},Ji=n=>{for(let e of n.variants)if(en(e)&&e.payload)return e.payload.id},en=n=>!!(n.type==="custom"&&n.payload&&n.payload.type==="vk"),yi=n=>{let e=Ji(n);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},tn=(n,e)=>{for(let t of n.media.videos)if(e===yi(t)){for(let i of n.chapters)if(i.videoId===t.id)return i.id;return}},Ci=(n,e)=>n.reduce((t,i)=>{let r=tn(e,i);return r?[...t,r]:t},[]);var ye=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:i,historyApi:r,settings:o}){this.state={history$:new be([]),hasPrevChapter$:new be(!1),prevChapter$:new be(null),isInitialChapter$:new be(!1),isGoBackLimited$:new be(!1)};this.#i=null;this.#s=!1;this.#e=null;this.#p=null;this.events={inited$:new St,destroyed$:new St,error$:new St};this.#n=null;this.#r=null;this.#t=null;this.#a=new nn;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(l=>{this.state.prevChapter$.next(l.at(-2)||null),this.state.hasPrevChapter$.next(l.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,l=At(o,i);if(this.#p=l,this.state.history$.next(o),!(!t||!this.#i||!this.#n))try{await this.#i.save(this.#n,l)}catch{let a=new V(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 V(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 V(1,5,"Error while trying to fetch data");this.events.error$.next(o),this.#t?.emit(I.errors,o)}let i=Ci(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 At([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 Ze=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 qe=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;
@@ -163,7 +163,7 @@ var Mt="1.0.36-dev.ca6258d6.0";import{fromEvent as qt,Subscription as Li}from"@v
163
163
  border: none;
164
164
  }
165
165
 
166
- .interactive-control-disabled {
166
+ .interactive-control.interactive-control-disabled {
167
167
  cursor: default;
168
168
  }
169
169
 
@@ -282,4 +282,4 @@ var Mt="1.0.36-dev.ca6258d6.0";import{fromEvent as qt,Subscription as Li}from"@v
282
282
  .interactive-control-fill-animation-filler.interactive-control-fill-animation-from-bottom {
283
283
  transform-origin: bottom;
284
284
  }
285
- `;var Ii=n=>{let e=document.createElement("style");e.textContent=Ei,n.prepend(e)};import{clientChecker as ln}from"@vkontakte/videoplayer-core/evergreen";var Ai=Object.freeze({lang:sn.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 Ye=class{constructor(e){this.playerSubscriptions=new wt;this.subscriptions=new wt;this.globalEventEmitter=new Ue;this.animation=new Ge;this.seekToInteractiveController=new me;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=cn();this.factories=new Map([["choice",He]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new wt;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 F,graphVisibilityChanged$:new F,watchAgainIsClicked$:new F,chapterChanged$:new F,playerChanged$:new F,error$:new F,eachTick$:new F,manifestChanged$:new F,interactiveRangeEnded$:new F,interactiveContainerRemoved$:new F,interactiveContainerFakeRemoved$:new F,interactiveActionExecution$:new F,interactiveActionChoice$:new F,interactiveVisibilityChanged$:new F};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=({removeTextControls:e=!0,withTransition:t=!1}={})=>{for(let i of this.gameControllers)!e&&i.isPermanentText||(this.animation.removeFn(i.whilePlaying),i.destroy(t))};this.completeInteractiveRange=e=>{let{interactiveRanges$:t}=this.state,r=t.getValue().map(o=>({...o,subjects:o.subjects.filter(l=>l.id!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};if(this._options={...Ai,...e,config:{...Ai.config,...e.config}},this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation){this.blinkAnimationRef=new Ne,this.blinkAnimationRef.create();let r=this.blinkAnimationRef.element;r&&this.rootElement.append(r)}this._options.parentElement.append(this.rootElement),this.historyController=new ye({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 qe({parentElement:this._options.parentElement,onError:r=>{let o=new V(1,6,r);this.emitErrorEvent(o)}})),Ii(this._options.parentElement),this.subscriptions.add(xi(this.rootElement,"mousedown").subscribe(r=>r.stopPropagation())).add(xi(this.rootElement,"mouseup").subscribe(r=>r.stopPropagation())),this.manifestController=new ne(this._options.loaders,r=>{let o=new V(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=ci(()=>({player:this.player,parentElement:this._options.parentElement,fns:i})),this._options.graph&&(this.graph=new he({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:r=>{this.setChapter({chapterId:r}),this.globalEventEmitter.emit(I.graph,{type:fe.watchAgainClicked,chapterId:r}),this.events.watchAgainIsClicked$.next(r)},onError:r=>{let o=new V(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({removeTextControls:!1,withTransition:this._options.animationsFeatureToggles?.controlsHideAnimation})}))}async initSeamless(){this.seamlessController=It(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:R.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(an()).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(on({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:C})=>d<a&&a<v&&C.some(b=>!b.isRemoved)&&C.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(),l=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(l&&this.selectBranches&&this.interactiveEvents&&this.player){let s=new Qe({player:this.player,container:l,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,getContainerEventState:()=>Kt(i,this.gameControllers),permanentTextControls:this._options.permanentTextControls,interactiveTimeOpenUri:this._options.interactiveTimeOpenUri,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(i.id)},onError:this.emitErrorEvent,features:{controlsHideAnimation:this._options.animationsFeatureToggles?.controlsHideAnimation}});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)&&$e(i))??!1,o=this.manifestController.manifest?.metadata.initChapterId===e,l=this.historyController.state.history$.getValue();if(o||r&&t){this.historyController.updateHistory([e]);return}l.at(-1)!==e&&this.historyController.updateHistory([...l,e])}handleFakeRemoval(e,t){let{interactiveRanges$:i}=this.state,o=i.getValue().map(l=>{let s=l.subjects.some(h=>h.id===e),a=l.subjects.map(h=>t&&s||h.id===e?{...h,isRemoved:!0}:h);return{...l,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)};Fe({...e,gameControllers:this.gameControllers,execFn:ve(Tt(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?Fe({...e,gameControllers:this.gameControllers,execFn:ve(Tt(t),!1)}):Fe({...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=si(this.player,this._options.interactiveTimeOpenUri),this.selectBranches=bi({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&&ln.browser.isSafari&&await gi(35);let r=!i&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:o,media:l,graph:s}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!o||!l)&&(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:l}),this.globalEventEmitter.emit(I.chapterChanged,{chapter:o,media:l,graph:s}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new Ti(e=>{this.subscriptions.add(this.events.graphVisibilityChanged$.subscribe(t=>{e.next(t?Ce.GRAPH_SHOW:Ce.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{e.next(Ce.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:i,subjectType:r})=>{t!=="action-choice"||i!=="control"||(r==="Button"&&e.next(Ce.NEXT_BUTTON),r==="Area"&&e.next(Ce.NEXT_AREA))}))}),nextMovie$:new Ti(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:fe.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===T.setNextBranch)}allControlsAreRemoved(e=!0){return!this.gameControllers.some(i=>{let r=e&&this._options.animationsFeatureToggles?.controlsHideAnimation?i.container.willRemoved:!0;return!i.container.isRemoved||!r})}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&&!i.container.willRemoved&&r.endTime===null&&Z(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&Pe(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 ri(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 pn={Container:J,createChoiceContainer:He,createAreaControl:Be,createButtonControl:De,classnamesPrefix:Ot};var xa={version:Mt};export{qn as ContainerTypes,Le as ControlTypes,V as CustomError,I as EVENT_NAMES,T as EventActionTypes,Yn as EventTypes,Ye as Interactives,ne as ManifestController,xa as SDKInfo,At as chapterIdsToVKVideoIds,vt as compareVersions,Gn as containerTypes,zn as controlTypes,Kn as eventActionTypes,Wn as eventTypes,tn as getChapterIdByVkVideoId,yi as getVKVideoIdByMedia,Ji as getVideoRawIdByMedia,fe as graphEventTypes,$e as hasEndTemplate,R as interactivesEventTypes,Un as isAreaControl,Hn as isButtonControl,H as isLastChapter,ie as isOneTextCtrlContainer,Pe as isSupportedManifest,Ve as isTextControl,en as isVKVariantItem,Ht as isValidManifest,Ut as migrateManifestToLatestVersion,pn as utils,Ci as vkVideoIdsToChapterIds};
285
+ `;var Ii=n=>{let e=document.createElement("style");e.textContent=Ei,n.prepend(e)};import{clientChecker as ln}from"@vkontakte/videoplayer-core/evergreen";var Ai=Object.freeze({lang:sn.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,controlsHideAnimation:!1}});function cn(){let n=document.createElement("div");return n.classList.add("interactive-chapter"),n}var Ye=class{constructor(e){this.playerSubscriptions=new wt;this.subscriptions=new wt;this.globalEventEmitter=new Ue;this.animation=new Ge;this.seekToInteractiveController=new me;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=cn();this.factories=new Map([["choice",He]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new wt;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 F,graphVisibilityChanged$:new F,watchAgainIsClicked$:new F,chapterChanged$:new F,playerChanged$:new F,error$:new F,eachTick$:new F,manifestChanged$:new F,interactiveRangeEnded$:new F,interactiveContainerRemoved$:new F,interactiveContainerFakeRemoved$:new F,interactiveActionExecution$:new F,interactiveActionChoice$:new F,interactiveVisibilityChanged$:new F};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=({removeTextControls:e=!0,withTransition:t=!1}={})=>{for(let i of this.gameControllers)!e&&i.isPermanentText||(this.animation.removeFn(i.whilePlaying),i.destroy(t))};this.completeInteractiveRange=e=>{let{interactiveRanges$:t}=this.state,r=t.getValue().map(o=>({...o,subjects:o.subjects.filter(l=>l.id!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};if(this._options={...Ai,...e,config:{...Ai.config,...e.config}},this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation){this.blinkAnimationRef=new Ne,this.blinkAnimationRef.create();let r=this.blinkAnimationRef.element;r&&this.rootElement.append(r)}this._options.parentElement.append(this.rootElement),this.historyController=new ye({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 qe({parentElement:this._options.parentElement,onError:r=>{let o=new V(1,6,r);this.emitErrorEvent(o)}})),Ii(this._options.parentElement),this.subscriptions.add(xi(this.rootElement,"mousedown").subscribe(r=>r.stopPropagation())).add(xi(this.rootElement,"mouseup").subscribe(r=>r.stopPropagation())),this.manifestController=new ne(this._options.loaders,r=>{let o=new V(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=ci(()=>({player:this.player,parentElement:this._options.parentElement,fns:i})),this._options.graph&&(this.graph=new he({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:r=>{this.setChapter({chapterId:r}),this.globalEventEmitter.emit(I.graph,{type:fe.watchAgainClicked,chapterId:r}),this.events.watchAgainIsClicked$.next(r)},onError:r=>{let o=new V(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({removeTextControls:!1,withTransition:this._options.animationsFeatureToggles?.controlsHideAnimation})}))}async initSeamless(){this.seamlessController=It(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:R.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(an()).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(on({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:C})=>d<a&&a<v&&C.some(b=>!b.isRemoved)&&C.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(),l=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(l&&this.selectBranches&&this.interactiveEvents&&this.player){let s=new Qe({player:this.player,container:l,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,getContainerEventState:()=>Kt(i,this.gameControllers),permanentTextControls:this._options.permanentTextControls,interactiveTimeOpenUri:this._options.interactiveTimeOpenUri,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(i.id)},onError:this.emitErrorEvent,features:{controlsHideAnimation:this._options.animationsFeatureToggles?.controlsHideAnimation}});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)&&$e(i))??!1,o=this.manifestController.manifest?.metadata.initChapterId===e,l=this.historyController.state.history$.getValue();if(o||r&&t){this.historyController.updateHistory([e]);return}l.at(-1)!==e&&this.historyController.updateHistory([...l,e])}handleFakeRemoval(e,t){let{interactiveRanges$:i}=this.state,o=i.getValue().map(l=>{let s=l.subjects.some(h=>h.id===e),a=l.subjects.map(h=>t&&s||h.id===e?{...h,isRemoved:!0}:h);return{...l,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)};Fe({...e,gameControllers:this.gameControllers,execFn:ve(Tt(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?Fe({...e,gameControllers:this.gameControllers,execFn:ve(Tt(t),!1)}):Fe({...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=si(this.player,this._options.interactiveTimeOpenUri),this.selectBranches=bi({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&&ln.browser.isSafari&&await gi(35);let r=!i&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:o,media:l,graph:s}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!o||!l)&&(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:l}),this.globalEventEmitter.emit(I.chapterChanged,{chapter:o,media:l,graph:s}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new Ti(e=>{this.subscriptions.add(this.events.graphVisibilityChanged$.subscribe(t=>{e.next(t?Ce.GRAPH_SHOW:Ce.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{e.next(Ce.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:i,subjectType:r})=>{t!=="action-choice"||i!=="control"||(r==="Button"&&e.next(Ce.NEXT_BUTTON),r==="Area"&&e.next(Ce.NEXT_AREA))}))}),nextMovie$:new Ti(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:fe.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===T.setNextBranch)}allControlsAreRemoved(e=!0){return!this.gameControllers.some(i=>{let r=e&&this._options.animationsFeatureToggles?.controlsHideAnimation?i.container.willRemoved:!0;return!i.container.isRemoved||!r})}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&&!i.container.willRemoved&&r.endTime===null&&Z(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&Pe(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 ri(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 pn={Container:J,createChoiceContainer:He,createAreaControl:Be,createButtonControl:De,classnamesPrefix:Ot};var xa={version:Mt};export{qn as ContainerTypes,Le as ControlTypes,V as CustomError,I as EVENT_NAMES,T as EventActionTypes,Yn as EventTypes,Ye as Interactives,ne as ManifestController,xa as SDKInfo,At as chapterIdsToVKVideoIds,vt as compareVersions,Gn as containerTypes,zn as controlTypes,Kn as eventActionTypes,Wn as eventTypes,tn as getChapterIdByVkVideoId,yi as getVKVideoIdByMedia,Ji as getVideoRawIdByMedia,fe as graphEventTypes,$e as hasEndTemplate,R as interactivesEventTypes,Un as isAreaControl,Hn as isButtonControl,H as isLastChapter,ie as isOneTextCtrlContainer,Pe as isSupportedManifest,Ve as isTextControl,en as isVKVariantItem,Ht as isValidManifest,Ut as migrateManifestToLatestVersion,pn as utils,Ci as vkVideoIdsToChapterIds};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.36-dev.ca6258d6.0",
3
+ "version": "1.0.36-dev.cf7ccf83.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.131-dev.1b9d4a49.0",
60
- "@vkontakte/videoplayer-shared": "1.0.59-dev.4d0599d9.0",
61
- "@vkontakte/videoplayer-statistics": "1.0.77-dev.91b6acbc.0"
59
+ "@vkontakte/videoplayer-core": "2.0.130",
60
+ "@vkontakte/videoplayer-shared": "1.0.58",
61
+ "@vkontakte/videoplayer-statistics": "1.0.76"
62
62
  }
63
63
  }