@vkontakte/videoplayer-interactive 1.0.61 → 1.0.62-dev.04ce2cd1.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.
Files changed (87) hide show
  1. package/es2015.cjs +8 -7
  2. package/es2015.esm.js +8 -7
  3. package/es2018.cjs +8 -7
  4. package/es2018.esm.js +8 -7
  5. package/es2024.cjs +8 -7
  6. package/es2024.esm.js +8 -7
  7. package/esnext.cjs +8 -7
  8. package/esnext.esm.js +8 -7
  9. package/evergreen.esm.js +8 -7
  10. package/package.json +4 -4
  11. package/types/index.d.ts +9 -8
  12. package/types/manifest/index.d.ts +3 -3
  13. package/types/manifest/utils.d.ts +33 -32
  14. package/types/modules/Graph/Graph.d.ts +47 -46
  15. package/types/modules/Graph/index.d.ts +1 -1
  16. package/types/modules/Interactives/Interactives.d.ts +138 -135
  17. package/types/modules/Interactives/Layout.d.ts +11 -11
  18. package/types/modules/Interactives/containers/ChoiceContainer.d.ts +31 -31
  19. package/types/modules/Interactives/containers/Container.d.ts +19 -19
  20. package/types/modules/Interactives/containers/index.d.ts +4 -4
  21. package/types/modules/Interactives/containers/types.d.ts +6 -6
  22. package/types/modules/Interactives/containers/utils.d.ts +3 -3
  23. package/types/modules/Interactives/controls/AreaControl.d.ts +17 -16
  24. package/types/modules/Interactives/controls/ButtonControl.d.ts +21 -20
  25. package/types/modules/Interactives/controls/Control.d.ts +42 -41
  26. package/types/modules/Interactives/controls/TextControl.d.ts +14 -13
  27. package/types/modules/Interactives/controls/index.d.ts +6 -6
  28. package/types/modules/Interactives/controls/types.d.ts +22 -19
  29. package/types/modules/Interactives/controls/utils.d.ts +10 -10
  30. package/types/modules/Interactives/index.d.ts +14 -95
  31. package/types/modules/Interactives/styles/index.d.ts +1 -1
  32. package/types/modules/Interactives/types.d.ts +64 -64
  33. package/types/modules/Interactives/utils/BlinkAnimationRef.d.ts +10 -10
  34. package/types/modules/Interactives/utils/ControlFillAnimation/ControlFillAnimation.d.ts +30 -30
  35. package/types/modules/Interactives/utils/ControlFillAnimation/index.d.ts +1 -1
  36. package/types/modules/Interactives/utils/ControlFillAnimation/utils.d.ts +9 -9
  37. package/types/modules/Interactives/utils/ControlTap/ControlTap.d.ts +12 -12
  38. package/types/modules/Interactives/utils/ControlTap/index.d.ts +1 -1
  39. package/types/modules/Interactives/utils/ControlTap/utils.d.ts +3 -3
  40. package/types/modules/Interactives/utils/GameController.d.ts +66 -66
  41. package/types/modules/Interactives/utils/GroupsStack.d.ts +18 -20
  42. package/types/modules/Interactives/utils/HistoryController.d.ts +39 -40
  43. package/types/modules/Interactives/utils/InteractiveEvents.d.ts +30 -29
  44. package/types/modules/Interactives/utils/ResizeManager.d.ts +10 -10
  45. package/types/modules/Interactives/utils/SelectBranches.d.ts +15 -15
  46. package/types/modules/Interactives/utils/SelectBranches.types.d.ts +53 -53
  47. package/types/modules/Interactives/utils/angleUtils.d.ts +13 -13
  48. package/types/modules/Interactives/utils/createControlText.d.ts +2 -2
  49. package/types/modules/Interactives/utils/emitOnError.d.ts +10 -10
  50. package/types/modules/Interactives/utils/events.d.ts +67 -67
  51. package/types/modules/Interactives/utils/events.types.d.ts +35 -32
  52. package/types/modules/Interactives/utils/fallbackStrategies.d.ts +15 -14
  53. package/types/modules/Interactives/utils/functionUtils.d.ts +9 -2
  54. package/types/modules/Interactives/utils/gameUtils.d.ts +22 -21
  55. package/types/modules/Interactives/utils/getInteractiveRanges.d.ts +5 -5
  56. package/types/modules/Interactives/utils/renderingUtils.d.ts +48 -53
  57. package/types/modules/Loaders/index.d.ts +1 -1
  58. package/types/modules/Loaders/movikaProjectIdLoader/index.d.ts +1 -1
  59. package/types/modules/Loaders/vkVideoLoader/CustomVkVideoLoader.d.ts +8 -8
  60. package/types/modules/Loaders/vkVideoLoader/index.d.ts +1 -1
  61. package/types/modules/Loaders/vkVideoLoader/types.d.ts +231 -231
  62. package/types/modules/Loaders/vkVideoLoader/utils.d.ts +1 -1
  63. package/types/modules/ManifestController/Loadable.d.ts +5 -5
  64. package/types/modules/ManifestController/ManifestController.d.ts +29 -29
  65. package/types/modules/ManifestController/index.d.ts +1 -1
  66. package/types/modules/ManifestController/utils.d.ts +6 -6
  67. package/types/modules/SeamlessController/InstanceManager.d.ts +10 -10
  68. package/types/modules/SeamlessController/SeamlessController.d.ts +30 -27
  69. package/types/modules/SeamlessController/utils.d.ts +6 -6
  70. package/types/modules/SeekToInteractiveController/SeekToInteractiveController.d.ts +8 -8
  71. package/types/modules/SeekToInteractiveController/index.d.ts +1 -1
  72. package/types/types/CustomError.d.ts +9 -9
  73. package/types/types/index.d.ts +2 -2
  74. package/types/utils/CssVarsManager.d.ts +21 -21
  75. package/types/utils/Error.d.ts +6 -6
  76. package/types/utils/EventEmitter.d.ts +10 -10
  77. package/types/utils/LastFrame.d.ts +29 -29
  78. package/types/utils/LastFrameCanvasAPI.d.ts +17 -17
  79. package/types/utils/MultiMap.d.ts +8 -8
  80. package/types/utils/Raf.d.ts +11 -11
  81. package/types/utils/chapterHelpers.d.ts +1 -1
  82. package/types/utils/compareVersions.d.ts +12 -12
  83. package/types/utils/extractVkMovieId.d.ts +1 -1
  84. package/types/utils/getVideoContentSize.d.ts +3 -3
  85. package/types/utils/hexToRgb.d.ts +2 -2
  86. package/types/utils/throttle.d.ts +1 -1
  87. package/types/utils/typeCheck.d.ts +7 -7
package/evergreen.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.61
3
- * Wed, 11 Mar 2026 06:05:39 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-61/doc/
2
+ * @vkontakte/videoplayer-interactive v1.0.62-dev.04ce2cd1.0
3
+ * Wed, 18 Mar 2026 16:34:21 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-62/doc/
5
5
  */
6
- var Lt="1.0.61";import{fromEvent as si,Subscription as Gi}from"@vkontakte/videoplayer-shared/evergreen";var it=class{constructor(e,t){this.layout=e;this.cssVarsManager=t}},Ee=class extends it{constructor(t,i){super(t,i);this.cssVarsManager=i;this.cssVarsManager=i}setContainerLayout(t){t.style.position="relative"}setControlLayout(t,i){let r=this.cssVarsManager.getPropValue("--interactive-content-width"),o=this.cssVarsManager.getPropValue("--interactive-content-height"),a=this.cssVarsManager.getPropValue("--interactive-width"),s=this.cssVarsManager.getPropValue("--interactive-height"),l=2e-4;t.style.position="absolute",t.style.width=`calc(${r} * (${i.width} + ${l}))`,t.style.height=`calc(${o} * ${i.height})`,t.style.left=`calc(${r} * ${i.x} + ((${a} - ${r}) / 2))`,t.style.top=`calc(${o} * ${i.y} + ((${s} - ${o}) / 2))`}};import{Subject as Fi}from"@vkontakte/videoplayer-shared/evergreen";function Ot(n){return"features"in n}var M=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 a=new M(r,o,{message:i,error:e,details:{id:t}});n.next(a)}var J=class{constructor(e,t,i){this.error$=new Fi;this.container=e,this.options=i,this.factories=new Map,this.controls=[],this.setControls(),this.cssVarsManager=t}featureIsEnabled(e){return this.options&&this.options.features&&Ot(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 Zt}from"@vkontakte/videoplayer-shared/evergreen";var W=(n,e)=>Object.prototype.toString.call(n)===`[object ${e}]`,G=n=>W(n,"Object"),Te=n=>W(n,"String"),xe=n=>W(n,"Array"),Ae=n=>W(n,"Number"),$t=n=>W(n,"Function"),Ft=n=>W(n,"Boolean"),ot=n=>Ae(n)&&!isNaN(n);var X=n=>G(n)&&Object.keys(n).length===0,st=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 Nt="interactive",w={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderWidthRawValue:"1px",roundCornersRawValue:"0",borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0,shadowColorLight:"#fff",shadowColorDark:"#000",shadowColorAlpha:.24},Bt=(i=>(i.top="flex-start",i.bottom="flex-end",i.center="center",i))(Bt||{}),jt=(i=>(i.start="flex-start",i.end="flex-end",i.center="center",i))(jt||{}),_t=(i=>(i.start="left",i.end="right",i.center="center",i))(_t||{}),Se=({target:n,props:e})=>{n.style.alignItems=(e?.gravityVertical&&Bt[e.gravityVertical])??"center",n.style.justifyContent=(e?.gravityHorizontal&&jt[e.gravityHorizontal])??"center",n.style.textAlign=(e?.alignment&&_t[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})`,a=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=a},Ht=({target:n,isDark:e,baseDimension:t,fallback:i})=>{let a=oe(i.shadowColorLight,i.shadowColorAlpha),s=oe(i.shadowColorDark,i.shadowColorAlpha),l=`calc(${t} * ${.25})`,h=`calc(${t} * ${.11})`,d=`0px 0px ${l} ${h} ${e?s:a}`;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 _i,Subscription as Hi}from"@vkontakte/videoplayer-shared/evergreen";var at="interactive-control-tap",te={common:at,animation:`${at}-animation`,visible:`${at}-visible`};var Ni=60,ke=class{constructor({controlRotateAngleRad:e,clickCancelCondition:t,circleDiameterPx:i=Ni,useDimensionsBasedSize:r=!1}){this.onElementClick=e=>{if(!e.target||!e.currentTarget||this.clickCancelCondition())return;let t=e.currentTarget.parentElement;if(!t)return;let i=t.getBoundingClientRect(),r={width:this.useDimensionsBasedSize?t.offsetWidth:this.circleDiameterPx,height:this.useDimensionsBasedSize?t.offsetHeight:this.circleDiameterPx},o=Math.min(r.width,r.height),a=i.left+i.width/2,s=i.top+i.height/2,l=e.clientX-a,h=e.clientY-s,d=Bi(l,h,this.controlRotateAngleRad);this.element.style.width=o+"px",this.element.style.left=d.x+i.width/2-o/2+"px",this.element.style.top=d.y+i.height/2-o/2+"px",this.element.classList.add(te.visible,te.animation)};this.onAnimationEnd=e=>{e.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 Bi(n,e,t){return{x:n*Math.cos(t)-e*Math.sin(t),y:n*Math.sin(t)+e*Math.cos(t)}}var lt="int",K=(i=>(i.AREA=`${lt}_area`,i.TEXT=`${lt}_text`,i.BUTTON=`${lt}_bttn`,i))(K||{});function ct(n){return"features"in n}var H="interactive-control",S={common:H,selected:`${H}-selected`,wrapper:`${H}-wrapper`,disabled:`${H}-disabled`,button:`${H}-button`,area:`${H}-area`,text:`${H}-text`,blinkAnim:`${H}-blink-anim`,blinkAnimButton:`${H}-blink-anim-button`,blinkAnimArea:`${H}-blink-anim-area`},Dt=40;import{isSupportedManifest as Me,ContainerTypes as ar,ControlTypes as Pe,EventActionTypes as x,EventTypes as lr,migrateManifestToLatestVersion as Gt,compareVersions as cr}from"@interactiveplatform/movika-manifest";var Ut={metadata:"Object",chapters:"Array"},Wt=n=>{if(!G(n))return!1;for(let e in Ut)if(!n[e]||!W(n[e],Ut[e]))return!1;return Me(n.metadata.version)},Ve=n=>n.type===Pe.Text,Yn=n=>n.type===Pe.Button,Jn=n=>n.type===Pe.Area,er={Choice:"Choice",TextInput:"TextInput"},tr={Button:"Button",Area:"Area",Text:"Text"},ir={onClick:"onClick",onSuspense:"onSuspense"},nr={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var Le=n=>xe(n)&&!st(n),D=n=>n.order==="end",Oe=n=>xe(n.containers)&&!st(n.containers)&&D(n),zt=(n,e)=>{let t=n*1e3;return Le(e.controls)&&t<(e.startTime??0)},pt=(n,e)=>{let t=n*1e3;return Le(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var Z=(n=[])=>n.some(e=>e.action.type==="expect"),ht=(n=[])=>n.find(e=>e.action.type==="expect"),ji=n=>n?.length===1,ie=n=>ji(n)&&Ve(n[0]);function Qt(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 $e({gameControllers:n=[],subjectName:e,subjectId:t,execFn:i}){for(let r of n)if(e==="container"&&r.container.container.id===t){i(r),Qt(n,r.container.container.endTime,[r.container.container.id]).forEach(a=>{i(a)});break}}function Xt(n){for(let e of n.events)if(e.action.type==="openURI")return!0;return!1}var Kt=(n,e)=>{let t=T=>e.find(({container:p})=>p.container.id===T)?.container.isRemoved,i=Z(n.events)&&!t(n.id),r=(T,v=!1,p=!1)=>{let c=p?"every":"some";return T.controls[c](m=>{let f=v?T.endTime===n.endTime:!0;return m.events?.[c](b=>b.action?.type===x.openURI)&&f})},o=T=>T.some(({container:v})=>r(v.container,!0,!1)&&!v.isRemoved),a=T=>T.every(({container:v})=>v.isRemoved||v.willRemoved?!0:r(v.container,!0,!0)),s=Qt(e,n.endTime,[n.id]).length,l=T=>T.controls.some(v=>v.events?.some(p=>p.action?.args?.shouldOpenNow)),h=i||s>0,d=o(e),y=r(n),C=a(e),u=i?!1:s>0,k=l(n);return{isExpectTime:h,hasOtherExpect:s>0,hasOpenURIEvent:d,hasOpenURIEventInCurrentContainer:y,isAllOpenURIEventsValid:C,isExpectEventForCurrentContainer:u,hasShouldOpenNowEvent:k}};var z=class n{constructor(e,t){this.control=e;this.options=t;this.container=null;this.controlElement=null;this.subscriptions=new Hi;this.error$=new _i;this.isInteracted=!1;this.isRemoved=!1;this.cssVarsManager=null;this.onControlSelect=()=>{this.container?.isManifestContainerDisabled()||Xt(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()}}setCssVarsManager(e){this.cssVarsManager=e}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 ke({controlRotateAngleRad:t,clickCancelCondition:this.container.isManifestContainerDisabled,circleDiameterPx:this.isTouch()?Dt: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:this.cssVarsManager?.getPropValue("--interactive-content-height")??0,width:this.cssVarsManager?.getPropValue("--interactive-content-width")??0},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&&ct(this.options)&&this.options.features[e]}isTouch(){return this.options&&ct(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 mt="interactive-blink-anim-reference",L={common:mt,animation:`${mt}-animation`,disabled:`${mt}-disabled`},Fe=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 dt="interactive-container",O={common:dt,hidden:`${dt}-hidden`,disabled:`${dt}-disabled`};var Ne=(n,e)=>{if(n.type.trim().toLowerCase()==="area")return new ut(n,e)},ut=class extends z{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",K.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(Zt()).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(Ft(e)){let t=Math.min(this.controlElement.offsetWidth,this.controlElement.offsetHeight)+"px";Ht({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(Zt()).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 ri}from"@vkontakte/videoplayer-shared/evergreen";var Be=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 je=Math.PI,ft=2*je,_e=je/2,qt=3*_e,Di=0,Ui=[Di,_e,je,qt];function Yt(n){return n===_e}function Jt(n){return n===je}function ei(n){return n===qt}function ti(n){return(n%ft+ft)%ft}function Wi(n){for(let e of Ui)if(n===e)return e}function ii(n){if(Wi(n))return null;let t=Math.floor(n/_e)+1;return[1,2,3,4][t-1]}function ni(n){return n*180/Math.PI}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 He=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=ti(e.rotateAngle),a=ii(o),s=a!==null,h=a===2||!s&&Jt(o)||a===3,d=!s&&Yt(o),y=!s&&ei(o),C=!h&&!d&&!y,u=d||y,k=s&&!u,T=k?o:0;t.style.borderRadius=e.borderRadius,i.style.transform=`skew(${T*-1}rad)`,u?(r.classList.add($.fillHeight,d?$.fromTop:$.fromBottom),i.classList.add($.fillHeight,d?$.fromTop:$.fromBottom)):(r.classList.add($.fillWidth,C?$.fromLeft:$.fromRight),i.classList.add($.fillWidth)),e.debug&&console.log(`[interactive ${n.name}]`,{widthExpansionCoef:this.widthExpansionCoef,opts:e,shouldFillHeight:u,rotateAngleRad:o,rotateAngelDeg:ni(o),rotateAngleRaw:e.rotateAngle,fromRight:h,fromTop:d,fromBottom:y,fromLeft:C}),this.useSkew=k,this.fromLeft=C,this.rotateAngle=o,this.fillAnimationElement=t,this.fillAnimationFillerElement=r,this.fillAnimationFillerWrapperElement=i,this.startTime=e.startTime,this.endTime=e.endTime,this.shouldFillHeight=u,this.isDebug=e.debug??!1}updateDimension(e){this.fillAnimationElement.style.top=`${e.borderWidth*-1}px`,this.fillAnimationElement.style.left=`${e.borderWidth*-1}px`,this.fillAnimationElement.style.width=`${e.width}px`,this.fillAnimationElement.style.height=`${e.height}px`;let t=this.calcWidthExpansionCoef({rotateAngle:this.rotateAngle,isSkewed:this.useSkew,initWidth:e.width,initHeight:e.height});!this.shouldFillHeight&&(this.fillAnimationFillerWrapperElement.style.width=100*t+100+"%",this.fillAnimationFillerWrapperElement.style[`${this.fromLeft?"left":"right"}`]=`calc((${t} * 100%) / 2 * -1)`),this.widthExpansionCoef=t}updateAnimation(e){if((o=>o<this.startTime||o>this.endTime)(e))return;let i=this.endTime-this.startTime,r=Math.min(Math.max((e-this.startTime)/i,0),1);this.shouldFillHeight?this.fillAnimationFillerElement.style.transform=`scaleY(${r})`:this.fillAnimationFillerElement.style.transform=`scaleX(${r})`}calcWidthExpansionCoef({rotateAngle:e,isSkewed:t=!1,initWidth:i,initHeight:r}){return t?(i+r*Math.abs(Math.tan(e)))/i-1:0}};var De=(n,e)=>{if(n.type.trim().toLowerCase()==="button")return new bt(n,e)},bt=class extends z{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",K.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=Be(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 He({startTime:this.startTime,endTime:this.endTime,rotateAngle:this.control.layoutParams.angle??w.angle,borderRadius:i.style.borderRadius})),this.subscriptions.add(ce(i,"click").pipe(ri()).subscribe(this.onControlSelect,a=>this.onError("Control click handler error",a))),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(ri()).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 oi=(n,e)=>{if(n.type.trim().toLowerCase()==="text")return new vt(n,e)},vt=class extends z{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",K.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=Be(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 Ue=(n,e,t,i)=>{if(n.type.trim().toLowerCase()==="choice")return new yt(n,e,t,i)},yt=class n extends J{constructor(t,i,r,o){super(t,r,o);this.containerElement=null;this.subscriptions=new Gi;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,r),this.cssVarsManager=r,this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",De),this.addControlFactory("text",oi),this.addControlFactory("area",Ne)}createView({eventCallback:t,videoDurationMs:i}){let r=document.createElement("div");return r.classList.add(O.common,O.disabled),r.setAttribute("data-subjectId",this.container.id),requestAnimationFrame(()=>{r.classList.remove(O.disabled)}),this.layout.setContainerLayout(r),this.controls.forEach(o=>{o.setShowTimeRange(this.container.startTime,this.container.endTime??i),o.setCssVarsManager(this.cssVarsManager),o.createView({parentElement:r,callbacks:{setControlLayout:(a,s)=>this.layout.setControlLayout(a,s),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(si(r,"transitionend").subscribe(this.onTransitionEnd,a=>this.onError(`${n.name} remove view transition error`,a))).add(si(r,"transitioncancel").subscribe(this.onTransitionEnd,a=>this.onError(`${n.name} remove view transition error`,a)));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 vn,InterfaceLanguage as yn,Observable as Pi,once as Cn,Subject as F,Subscription as Vt,ValueSubject as j,fromEvent as Li}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as Ce}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as zi}from"@vkontakte/videoplayer-shared/evergreen";function pe(n,e){let t;return(...i)=>{clearTimeout(t),t=setTimeout(()=>n(...i),e)}}var ai="video_interactive",li="videoint";var ci=250,he=class{constructor(e){this.handleZoomChange=pe(e=>{this.lastZoomInfo=e},ci);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=Qi(e),this.resizeObserver=new ResizeObserver(pe(this.onResize,ci)),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 zi(this.lang,ai,li)}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 Qi(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 a=o.startTime-e;if(a<=r&&(o.endTime&&r<=o.endTime||o.endTime===null)){i=!0;break}r<a&&(t=t===-1?a:Math.min(t,a))}return!i&&t!==-1?t:null}}};var We=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)=>{$t(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=[]}};var ze=class n{constructor(e){this.rootElement=e;this.rootElementProps={};this.isCssVarsSupported=n.checkCssVarsSupport(e)}static checkCssVarsSupport(e){let t="--test-key",i="test";e.style.setProperty(t,i);let r=e.style.getPropertyValue(t)===i;return r&&e.style.removeProperty(t),r}getPropValue(e){return this.isCssVarsSupported?`var(${e})`:this.rootElementProps[e]??""}setup(e){if(this.rootElementProps={...this.rootElementProps,...e},this.isCssVarsSupported)for(let[t,i]of Object.entries(e))this.rootElement.style.setProperty(t,i)}cleanup(){for(let e in this.rootElementProps)this.rootElement.style.removeProperty(e);this.rootElementProps={}}setProp(e,t){this.rootElementProps[e]=t,this.isCssVarsSupported&&this.rootElement.style.setProperty(e,t)}};import{ValueSubject as Ji}from"@vkontakte/videoplayer-shared/evergreen";var Qe=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Xi(...this.loaders[e])(t)}};function Xi(...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 Xe({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 a=n.getMedia(r.media,o.videoId),s=n.getGraph(r.graph,o.id);return a?{...i,actions:n,errors:e,result:{chapter:o,media:a,graph:s}}:{...i,errors:de(e,Xe.name,"Could not find media"),actions:n}}}}return{...i,errors:de(e,Xe.name,"Could not find chapter"),actions:n}}var Ct=(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 Ki=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(G(n))e=n;else return{};if(!Wt(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 Yi(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function pi(n){let{manifest:e,manifestURL:t}=await Ki(n);if(!e)throw new Error("Failed on fetch");let i=Gt(e);return i.media=Zi(i.media,t),delete i.metadata.media,i}function Ke(n,e){if(e)return n.find(t=>t.id===e)}function gt(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 Et(n,e){return n.videos.find(t=>t.id===e)}function Zi(n,e){return{...n,videos:n.videos.map(t=>({...t,variants:t.variants.map(i=>{let r="url"in i?i.url:"",o=qi(r,e);return{...i,url:o||r}})}))}}function qi(n="",e){try{return new URL(n,e).href}catch{return""}}function Yi(n){return Ct(n,"3.2.0")>=0}var ne=class extends Qe{constructor(t,i){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new Ji(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 pi(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",Xe({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:gt,getChapter:Ke,getMedia:Et,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=Et(this.manifest.media,i.videoId),o=gt(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?D(this.chapter):!1}};import{Player as en}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as xt,TracerFactory as tn,ValueSubject as nn}from"@vkontakte/videoplayer-shared/evergreen";var hi=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 It(){let n=new Map;function e({listId:o=Math.random().toString(),itemId:a=Math.random().toString(),...s}){let l=n.get(o),h={...s};return l?l[a]=h:n.set(o,{[a]:h}),{listId:o,itemId:a,...s}}function t(o){o.player.destroy(),o.container.remove(),o.subscription.unsubscribe(),o.statistics?.oneStat.destroy(),o.statistics?.statSubscription.unsubscribe()}function i(o,a){let s=n.get(o);if(!s)throw Error("Can't remove. Not find.");if(a){let l=s[a];l&&t(l),delete s[a],Object.keys(s).length||n.delete(o)}else{for(let l of Object.values(s))t(l);n.delete(o)}}function r(){for(let o of n)i(o[0])}return{createPlayer:e,removePlayer:i,map:n,removeAll:r}}function Tt(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 rn=2;function At(n){let e=It(),t=new xt,i={},r=null,o=!1,a,s=new nn(null);n&&l(n);function l(v){r=v}function h(v,p,c){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let f=(e.map.get(v)??{})[p];if(f){i={chapterId:c,listId:v,itemId:p,...f};let b=i.player;i.subscription.add(b.info.currentQuality$.subscribe(g=>{let A=b.info.position$.getValue(),N=b.info.isAutoQualityEnabled$.getValue();if(!(!g||!A||N))for(let E of e.map)Object.values(E[1]).forEach(({player:V})=>{ue(V,g)})})).add(b.events.started$.subscribe(()=>{d(p)})),f.container.remove(),r.setPlayer(f.player),o||(r.init(),o=!0),s.next({player:i.player,config:i.config,statistics:i.statistics});return}throw Error("Can't set. Not find.")}async function d(v){if(!r)throw Error("need to set interactive controller");if(X(i)||v!==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 y({chapter:{id:v},manifestVideo:p}){if(X(i)||!r)return;let c=i.player.info.muted$.getValue(),m=i.player.info.currentQuality$.getValue(),f=i.player.info.isAutoQualityEnabled$.getValue(),b=i.player.info.volume$.getValue(),g=i.player.info.currentPlaybackRate$.getValue(),A=!f,N=!1;for(let E of e.map)if(E[0]===p.id&&!r.state.isReplay$.getValue()){let V=Object.keys(E[1]);for(let P of V)P===i.itemId?(V.length<rn||(N=!0),e.removePlayer(E[0],P)):(N=!0,h(E[0],P,v),A?ue(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(b),i.player.setMuted(c),i.player.setPlaybackRate(g))}else e.removePlayer(E[0]);N||(await C({media:p,chapterId:v,setAsActive:!0,playbackRate:g}),A?ue(i.player,m):i.player.setAutoQuality(!0),i.player.setVolume(b),i.player.setMuted(c))}async function C({media:v,chapterId:p,prefetch:c=!0,setAsActive:m=!0,autoplay:f=!1,preferredExt:b,title:g,playbackRate:A}){let N=Math.random().toString(),E=document.createElement("div");a.append(E);let V;if(r?.options?.vkVideoLoader){let ge=hi(v);ge.length&&(V=await r.options.vkVideoLoader(...ge))}let _={...r?.options?.coreConfig||void 0},Q={container:E,...V?.videos?.[0]||{sources:Tt(v,b).sources},title:g,failoverHosts:V?.failoverHosts||[]},B=new en(_,tn.createRootTracer());B.initVideo(Q);let q=null;if(V?.videos&&r?.options.createOneStat){let ge=V.videos[0],tt=r.options.createOneStat(ge),Pt=new xt;tt&&(Pt.add(tt.attachTo(B)),q={oneStat:tt,statSubscription:Pt})}let Mt=new xt,$i=i?.player?.info.isAutoQualityEnabled$.getValue();Mt.add(B.events.canplay$.subscribe(function(){$i||ue(B,i.player.info.currentQuality$.getValue()),A&&B.setPlaybackRate(A)}));let Y=e.createPlayer({listId:v.id,itemId:N,player:B,container:E,sources:Tt(v,b).sources,config:Q,subscription:Mt,statistics:q});return m&&h(v.id,Y.itemId,p),f&&Y.player.play(),c&&!f&&Y.player.prepare(),{player:Y.player,config:Y.config,statistics:Y.statistics}}function u(){k(),r=null,a.remove()}function k(){t.unsubscribe(),e.removeAll(),i={},o=!1}async function T(){if(!r)throw Error("need to set interactive controller");k(),a=document.createElement("div");let{media:v,chapter:p}=r.getCurrentChapter();v&&p?(t.add(r.events.chapterChanged$.subscribe(y)),await C({media:v,chapterId:p.id,title:p.label})):console.error("not found")}return{...e,init:T,setInteractiveController:l,createPlayer:C,removeAll:u,getActivePlayer:function(){return i},activePlayerChanged:s}}var I={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},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 on}from"@vkontakte/videoplayer-shared/evergreen";function St(n){return function(...t){return n(...t.reverse())}}function be(n,...e){return(...t)=>G(e[0])&&G(t[0])?n({...e[0],...t[0]}):n(...e,...t)}var Ze=class{constructor({player:e,container:t,branches:i,selectBranches:r,interactiveEvents:o,globalEvents:a,globalEventEmitter:s,getContainerEventState:l,permanentTextControls:h,interactiveTimeOpenUri:d,disabledControls$:y,onRemove:C,onError:u,disableTextControlContainerVisibilityEvents:k=!1,features:T}){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||this.disableTextControlContainerVisibilityEvents)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,a)=>{let{isExpectTime:s,hasOtherExpect:l,hasOpenURIEvent:h,hasOpenURIEventInCurrentContainer:d,isAllOpenURIEventsValid:y,hasShouldOpenNowEvent:C}=this.getContainerEventState(),u=this.interactiveTimeOpenUri&&!d,k=this.interactiveTimeOpenUri&&d;if((!this.interactiveTimeOpenUri||u)&&(this.isSelectedControlEvent=!0),o!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||u)){if(this.interactiveTimeOpenUri){let T=!l&&!y&&d;T&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:T})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&h&&this.gameState!==5){if(k){let v=((p,c,m,f)=>!p&&!c&&m||p&&!c&&m&&!f||p&&!c&&m&&f)(s,l,y,this.isSelectedContainerEvent);this.fakeRemoveView(v)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!s||!l||!C)&&(this.selectBranches.stopExpect(),a())}},isEOV:()=>this.gameState===4},i=be(this.selectBranches.onControlEvent,t),r=(this.player?.info.duration$.getValue()??1/0)*1e3;this.container.createView({eventCallback:i,videoDurationMs:r}),this.disableTextControlContainerVisibilityEvents||this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let e=this.player.experimental.element$.getValue(),t=e instanceof HTMLVideoElement;if(this.features.enableAvPlayerSupport&&(t||=e instanceof HTMLObjectElement&&e?.getAttribute("type")==="application/avplayer"),!(t?e?.readyState:void 0)||this.isRemovedOrDestroyed()&&!this.isPermanentText)return;let r=this.player.getExactTime();if(zt(r,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(pt(r,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let l=this.gameState;this.gameState=3,l===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:l}=this.getContainerEventState(),h=this.selectBranches.state.isExpect,d=this.interactiveTimeOpenUri&&l;if(d&&!h){let y=this.container.getElement();y&&(y.style.visibility!=="hidden"&&this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView())}!this.isPermanentText&&!d&&this.removeView()}let o=pt(r,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],s={subjectId:this.container.container.id,subjectName:"container",range:a,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 on,this.player=e,this.interactiveEvents=o,this.getContainerEventState=l;let v=ie(t.container.controls);this.isPermanentText=h&&v,this.disableTextControlContainerVisibilityEvents=k&&v,this.interactiveTimeOpenUri=d,this.disabledControls$=y,this.onRemove=C,this.globalEventEmitter=s,this.gameState=0,this.globalEvents=a,this.onError=u,this.features=T,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 di=(n=[])=>n.reduce((e,t,i)=>{let r=(t?.controls??[]).filter(o=>!Ve(o));if(Le(r)){let o=[t.startTime??0,t.endTime??1/0],a={id:t.id,isRemoved:!1};if(!i)e.push({subjects:[a],range:o});else{let s=[],l=-1/0,h=1/0,d=[],y=[];for(let C=0;C<e.length;C++){let u=e[C];if(y.push(...u.subjects),u.range[0]<h&&(h=u.range[0]),u.range[1]>l&&(l=u.range[1]),o[0]>=u.range[0]&&o[1]<=u.range[1])return e[C].subjects.push(a),e;o[0]<u.range[0]&&o[1]>u.range[0]&&(s.push(C),d=d.concat(u.subjects)),o[0]>=u.range[0]&&o[0]<=u.range[1]&&(s.push(C),d=d.concat(u.subjects),o[0]=u.range[0]),o[1]>=u.range[0]&&o[1]<=u.range[1]&&(s.push(C),d=d.concat(u.subjects),o[1]=u.range[1])}if(y.push(a),o[0]<=h&&o[1]>=l)return[{subjects:y,range:o}];s.length&&s.reverse().forEach(C=>{e.splice(C,1)}),e.push({subjects:d.concat([a]),range:o})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function ui(){let n={};function e(){for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&delete n[s]}function t(s){let l={};for(let h in n)+h<=s&&(l[h]=n[h]);return l}function i(s){let l={};for(let h in n)+h>=s&&(l[h]=n[h]);return l}function r({timestamp:s,priority:l,initiator:h}){if(ot(s)){let d=n[s]??null;if(d&&l&&re(l,!0)){let y={},C=d[l];return C&&(y={...y,...C}),y=X(y)?null:y,y&&re(h,!0)?y[h]??null:y}return d}return null}function o({timestamp:s,priority:l,initiator:h}){if(ot(s))if(n[s]){if(l&&re(l,!0))if(n[s][l]){if(h&&re(h,!0))if(n[s][l][h]){if(delete n[s][l][h],!X(n[s][l]))return!0}else return!1;if(delete n[s][l],!X(n[s]))return!0}else return!1;return delete n[s]}else return!1;return!1}function a({timestamp:s,priority:l,initiator:h,...d}){n[s]?.[l]?.[h]?n[s][l][h].push({...d}):n[s]?.[l]?n[s][l]={...n[s][l],[h]:[{...d}]}:n[s]?n[s]={...n[s],[l]:{[h]:[{...d}]}}:n[s]={[l]:{[h]:[{...d}]}}}return{map:n,remove:o,add:a,removeAll:e,get:r,getLte:t,getGte:i}}var sn=[x.expect,x.setNextBranch],an=1/0;function fi(n,e){let t=n,i,r=ln(e),o=ui(),a,s=()=>{u(),p()},l=c=>{o.add.call(void 0,c),k()},h=(c=[])=>{for(let m of c)if(m.action(),sn.includes(m.actionType))break},d=(c=1/0)=>{let m=qe(o.get({timestamp:c,priority:"control"})??{}),f=qe(o.get({timestamp:c,priority:"container"})??{}),b=qe(o.get({timestamp:c,priority:"chapter"})??{});return[...m,...f,...b]},y=c=>{r.isReady(c)&&h(d(c))},C=()=>{h([...qe(o.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{i&&(a?.unsubscribe(),i=void 0)},k=()=>{i||(i=()=>setTimeout(()=>{y(1/0)}),a=t.events.ended$.subscribe(i))},T=c=>{u(),t=c},v=c=>{c.priority==="container"&&r.resetCalled(c.timestamp),o.remove(c)},p=()=>{r.release(),o.removeAll()};return{setPlayer:T,add:l,remove:v,exec:y,execEndOfVideo:C,listen:k,unlisten:u,release:s,containersEventsCallState:r,getPreparedToExecActions:d}}function ln(n){let e=new Map;return{setCalled:({timestamp:s,id:l})=>{let h=e.get(s);h&&h[l]!==void 0&&(h[l]=!0)},setData:(s=[])=>{for(let l of s){let h=l.endTime??an,d=e.get(h);e.set(h,{...d,[l.id]:!1})}},resetCalled:s=>{let l=e.get(s);if(l)for(let h in l)l[h]=!1},isReady:s=>{let l=e.get(s);if(!l)return!0;let h=Object.values(l);return n?h.some(y=>y):!h.some(y=>!y)},release:()=>e.clear()}}function qe(n){return Object.values(n).flat().sort(e=>e.actionType===x.expect?-1:1)}var bi={videoContentHeight:0,videoContentWidth:0},vi=n=>{let{height:e,width:t}=n.info.intrinsicVideoSize$.getValue()||{};if(!(e&&t))return bi;let{clientHeight:i,clientWidth:r}=n.experimental.element$.getValue()||{};if(!(i&&r))return bi;let o=e/t,a=i/r,s,l;return a>o?(l=r,s=r*o):a<o?(l=i/o,s=i):(l=r,s=i),{videoContentWidth:l,videoContentHeight:s}};var cn=250;function yi(n){let e,t=new ResizeObserver(s=>{o(s),e=o.bind(null,s)});function i(s){let{parentElement:l,player:h,cssVarsManager:d}=n();if(!l||!h)return;let{videoContentWidth:y,videoContentHeight:C}=vi(h);d.setup({"--interactive-content-width":`${y}px`,"--interactive-content-height":`${C}px`,"--interactive-width":`${s[0].contentRect.width}px`,"--interactive-height":`${s[0].contentRect.height}px`})}function r(){let{parentElement:s}=n();s.removeAttribute("style")}let o=pe(s=>{let{fns:l=[]}=n();i(s);for(let h of l)h()},cn);function a(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:a}}var pn=n=>Math.floor(Math.random()*n),gi=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},Ei=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 Ii=n=>{let e=n.length,t=pn(e);return n[t]},Ci=1,Ti=n=>{let e=0;for(let i=0;i<n.length;++i)e+=n[i].weight??Ci;let t=Math.random()*e;e=0;for(let i=0;i<n.length-1;++i)if(e+=n[i].weight??Ci,e>=t)return n[i];return n[n.length-1]};var xi={shouldOpenNow:!0,isDetachContainer:!0},Ai="after-expect",wt=(n,e=!1)=>({...n,args:e?{...n.args,...xi}:{...xi,...n.args}}),Si=({globalEventEmitter:n,globalEvents:e,player:t,interactiveEvents:i})=>{let r={isExpect:!1},o=()=>{r.isExpect&&(r.isExpect=!1)},a=({action:p,controlType:c,controlId:m,containerId:f,branches:b=[],onEvent:g,isEOV:A=()=>!1,isDisabled:N=()=>!1})=>{let E=wt(p,A()),V={timestamp:1/0,priority:"control",initiator:m,actionType:E.type},P=N(),_=n.emit.bind(n,I.interactives,{subjectId:m,subjectType:c,subjectName:"control",type:P?R.actionChoiceCanceled:R.actionChoice,actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:f,...E.args}}),Q=()=>{e.interactiveActionChoice$.next({subjectId:m,subjectType:c,subjectName:"control",type:P?"action-choice-canceled":"action-choice",actionType:p.type,payload:{invokeImmediately:E.args.shouldOpenNow,containerId:f,...E.args}})};if(P){_(),Q();return}switch(E.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let B=b.find(q=>q.id===E.args.branchId);if(!B)return;g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?T({subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}}):i.add({...V,action:T.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{chapterId:B.chapterId,autoSelect:!1}})});return}case x.continuePlayback.trim().toLowerCase():{g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?k({subjectId:m,subjectName:"control",subjectType:c,action:p}):i.add({...V,action:k.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:p})});return}case x.openURI.trim().toLowerCase():{g(E.args.isDetachContainer,u.bind(null,{subjectId:m,subjectName:"control"})),_(),Q(),E.args.shouldOpenNow?v({subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{URI:p.args.uri}}):i.add({...V,action:v.bind(null,{subjectId:m,subjectName:"control",subjectType:c,action:E,payload:{URI:p.args.uri}})});return}default:{let B="Unexpected control event",q=new M(1,1,{message:B});d(q,B);return}}},s=({action:p,container:{id:c,endTime:m},branches:f=[],isEOV:b=!1,autoSelected:g=!1})=>{let A=wt(p,b),N={timestamp:!A.args.shouldOpenNow||b?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}}),V=()=>{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 x.setNextBranch.trim().toLowerCase():{let P=f.find(_=>_.id===A.args.branchId);if(!P)return;E(),V(),i.add({...N,action:T.bind(null,{subjectId:c,subjectName:"container",action:A,payload:{chapterId:P.chapterId,autoSelect:g}})});return}case x.setMaxWeightBranch.trim().toLowerCase():return;case x.setMinWeightBranch.trim().toLowerCase():return;case x.setRandomBranch.trim().toLowerCase():return;case x.setWeightlessRandomBranch.trim().toLowerCase():return;case x.continuePlayback.trim().toLowerCase():{E(),V(),i.add({...N,action:k.bind(null,{subjectId:c,subjectName:"container",action:A})});return}case x.openURI.trim().toLowerCase():{E(),V(),i.add({...N,action:v.bind(null,{subjectId:c,subjectName:"container",action:A,payload:{URI:p.args.uri}})});return}default:{let P="Unexpected container event",_=new M(1,1,{message:P});d(_,P);return}}};function l({container:p,branches:c,isEOV:m=!1}){let f=ht(p.events);if(f){let b=wt(f.action,m);n.emit(I.interactives,{subjectId:p.id,subjectName:"container",type:R.actionChoice,actionType:b.type,payload:{invokeImmediately:b.args.shouldOpenNow,...b.args}}),e.interactiveActionChoice$.next({subjectId:p.id,subjectName:"container",type:"action-choice",actionType:b.type,payload:{invokeImmediately:b.args.shouldOpenNow,...b.args}}),i.add({timestamp:m?1/0:p.endTime??1/0,priority:"container",initiator:p.id,actionType:x.expect,action:C.bind(null,{subjectId:p.id,subjectName:"container"})}),r.isExpect=!0}else for(let b of p.events??[])s({action:b.action,container:p,branches:c,isEOV:m})}let h=({chapterId:p,action:c,branches:m=[]})=>{let f=n.emit.bind(n,I.interactives,{subjectId:p,subjectName:"chapter",type:R.actionChoice,actionType:c.type,payload:c.args}),b=()=>{e.interactiveActionChoice$.next({subjectId:p,subjectName:"chapter",type:"action-choice",actionType:c.type,payload:c.args})};switch(c.type.trim().toLowerCase()){case x.setNextBranch.trim().toLowerCase():{let g=m.find(A=>A.id===c.args.branchId);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setWeightlessRandomBranch.trim().toLowerCase():{let g=Ii(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setRandomBranch.trim().toLowerCase():{let g=Ti(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setMaxWeightBranch.trim().toLowerCase():{let g=Ei(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.setMinWeightBranch.trim().toLowerCase():{let g=gi(m);return g?.chapterId?(f(),b(),T.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{chapterId:g.chapterId,autoSelect:!0}})):void 0}case x.continuePlayback.trim().toLowerCase():return f(),b(),k.bind(null,{subjectId:p,subjectName:"chapter",action:c});case x.openURI.trim().toLowerCase():return f(),b(),v.bind(null,{subjectId:p,subjectName:"chapter",action:c,payload:{URI:c.args.uri}});default:{let g="Unexpected chapter event",A=new M(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 y(p){let c=ht(p.events);if(c){if(D(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:x.expect,action:C.bind(null,{subjectId:p.id,subjectName:"chapter"})})}else p.events?.forEach(m=>{let f=h({chapterId:p.id,action:m.action,branches:p.branches});f&&i.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:m.action.type,action:f})})}let C=({subjectId:p,subjectName:c})=>{t.pause(),n.emit(I.interactives,{subjectId:p,subjectName:c,type:R.actionExecution,actionType:x.expect}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,type:"action-execution",actionType:x.expect})},u=({subjectId:p,subjectName:c})=>{t.info.isEnded$.getValue()?i.execEndOfVideo():t.play(),n.emit(I.interactives,{subjectId:p,subjectName:c,type:R.actionExecution,actionType:Ai}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,type:"action-execution",actionType:Ai})},k=({subjectId:p,subjectName:c,subjectType:m,action:f})=>{n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:f.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:f.type})},T=({subjectId:p,subjectName:c,subjectType:m,action:f,payload:b})=>{b.behaviour="change-chapter",n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:f.type,payload:b}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:f.type,payload:b})},v=({subjectId:p,subjectName:c,subjectType:m,action:f,payload:b})=>{if(!b.URI)return;let g=window.open(b.URI,"_blank","noopener,noreferrer");g&&(g.opener=null),n.emit(I.interactives,{subjectId:p,subjectName:c,subjectType:m,type:R.actionExecution,actionType:f.type}),e.interactiveActionExecution$.next({subjectId:p,subjectName:c,subjectType:m,type:"action-execution",actionType:f.type})};return{onControlEvent:a,onContainerEvent:s,onChapterEvent:h,onExpectEvent:C,expectEventHandler:u,setManifestChapterEvents:y,setManifestContainerEvents:l,stopExpect:o,state:r}};import{Subscription as fn,Subject as kt,ValueSubject as ve}from"@vkontakte/videoplayer-shared/evergreen";var Rt=(n,e)=>{let t={};return n.map(i=>{if(!t[i]){let r=e.chapters.find(a=>a.id===i);if(!r)return null;let o=e.media.videos.find(a=>r.videoId===a.id);if(!o)return null;t[i]=wi(o)}return t[i]}).filter(Boolean)},mn=n=>{for(let e of n.variants)if(dn(e)&&e.payload)return e.payload.id},dn=n=>!!(n.type==="custom"&&n.payload&&n.payload.type==="vk"),wi=n=>{let e=mn(n);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},un=(n,e)=>{for(let t of n.media.videos)if(e===wi(t)){for(let i of n.chapters)if(i.videoId===t.id)return i.id;return}},Ri=(n,e)=>n.reduce((t,i)=>{let r=un(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 ve([]),hasPrevChapter$:new ve(!1),prevChapter$:new ve(null),isInitialChapter$:new ve(!1),isGoBackLimited$:new ve(!1)};this.#i=null;this.#s=!1;this.#e=null;this.#p=null;this.events={inited$:new kt,destroyed$:new kt,error$:new kt};this.#n=null;this.#r=null;this.#t=null;this.#a=new fn;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(a=>{this.state.prevChapter$.next(a.at(-2)||null),this.state.hasPrevChapter$.next(a.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,a=Rt(o,i);if(this.#p=a,this.state.history$.next(o),!(!t||!this.#i||!this.#n))try{await this.#i.save(this.#n,a)}catch{let l=new M(1,5,"Unable to save interactive history");this.events.error$.next(l),this.#t?.emit(I.errors,l)}}async goBack(){if(!this.state||!this.#r){let i=new M(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 M(1,5,"Error while trying to fetch data");this.events.error$.next(o),this.#t?.emit(I.errors,o)}let i=Ri(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 Rt([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 Ye=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 Je=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 e=`1.0.62-dev.04ce2cd1.0`;import{fromEvent as t,Subscription as n}from"@vkontakte/videoplayer-shared/evergreen";class r{layout;cssVarsManager;constructor(e,t){this.layout=e,this.cssVarsManager=t}}class i extends r{cssVarsManager;constructor(e,t){super(e,t),this.cssVarsManager=t,this.cssVarsManager=t}setContainerLayout(e){e.style.position=`relative`}setControlLayout(e,t){let n=this.cssVarsManager.getPropValue(`--interactive-content-width`),r=this.cssVarsManager.getPropValue(`--interactive-content-height`),i=this.cssVarsManager.getPropValue(`--interactive-width`),a=this.cssVarsManager.getPropValue(`--interactive-height`);e.style.position=`absolute`,e.style.width=`calc(${n} * (${t.width} + 0.0002))`,e.style.height=`calc(${r} * ${t.height})`,e.style.left=`calc(${n} * ${t.x} + ((${i} - ${n}) / 2))`,e.style.top=`calc(${r} * ${t.y} + ((${a} - ${r}) / 2))`}}import{Subject as a}from"@vkontakte/videoplayer-shared/evergreen";function o(e){return`features`in e}class s{severity;category;data;constructor(e,t,...n){this.severity=e,this.category=t,this.data=n}toString(){return`Interactive SDK error ${JSON.stringify(this,null,` `)}`}}function c({emitter$:e,error:t,subjectId:n,message:r=``,severity:i=1,category:a=1}){let o=new s(i,a,{message:r,error:t,details:{id:n}});e.next(o)}class l{container;options;factories;controls;error$=new a;cssVarsManager;constructor(e,t,n){this.container=e,this.options=n,this.factories=new Map,this.controls=[],this.setControls(),this.cssVarsManager=t}featureIsEnabled(e){return!!(this.options&&this.options.features&&o(this.options)&&this.options.features[e])}onError(e=``,t){c({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 n=t.type.trim().toLowerCase(),r=this.factories.get(n);if(r){let n=r(t,this.options);if(n)return[...e,n]}return[...e]},[])||[]}}import{fromEvent as u,once as d}from"@vkontakte/videoplayer-shared/evergreen";var f=(e,t)=>Object.prototype.toString.call(e)===`[object ${t}]`,p=e=>f(e,`Object`),m=e=>f(e,`String`),h=e=>f(e,`Array`),g=e=>f(e,`Number`),_=e=>f(e,`Function`),v=e=>f(e,`Boolean`),y=e=>g(e)&&!isNaN(e),b=e=>p(e)&&Object.keys(e).length===0,x=e=>h(e)&&!e.length,S=(e,t)=>m(e)&&!!(t?e.trim():e).length;function C(e,t=1){let n=`0`,r=`0`,i=`0`;return e.length===4?(n=`0x`+e[1]+e[1],r=`0x`+e[2]+e[2],i=`0x`+e[3]+e[3]):e.length===7&&(n=`0x`+e[1]+e[2],r=`0x`+e[3]+e[4],i=`0x`+e[5]+e[6]),`rgba(${+n},${+r},${+i},${t})`}var ee=`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},te;(e=>{e.top=`flex-start`,e.bottom=`flex-end`,e.center=`center`})(te||={});var ne;(e=>{e.start=`flex-start`,e.end=`flex-end`,e.center=`center`})(ne||={});var re=({target:e,props:t})=>{e.style.alignItems=(t?.gravityVertical&&te[t.gravityVertical])??`center`,e.style.justifyContent=(t?.gravityHorizontal&&ne[t.gravityHorizontal])??`center`,e.style.textAlign=t?.alignment??`center`},ie=({target:e,props:t,fallback:n,dependsOn:r})=>{e.style.color=t?.text?.color??n.textColor,e.style.fontSize=`calc(${r.height} * ${t?.text?.size??n.textSize})`,e.textContent=t?.text?.value??n.textContent},ae=({target:e,props:t,fallback:n})=>{e.style.backgroundColor=C(t?.background?.color??n.backgroundColor,t?.background?.alpha??n.backgroundAlpha)},oe=({target:e,props:t,fallback:n,dependsOn:r,useRawValues:i=!1})=>{let a=i?n.borderWidthRawValue:`calc(${r.height} * ${t?.shape?.border?.width??n.borderWidth})`,o=i?n.roundCornersRawValue:`calc(${r.height} * ${t?.shape?.roundCorners??n.roundCorners})`;e.style.borderWidth=a,e.style.borderStyle=`solid`,e.style.borderColor=C(i?n.borderColor:t?.shape?.border?.color??n.borderColor,i?n.borderAlpha:t?.shape?.border?.alpha??n.borderAlpha),e.style.borderRadius=o},se=({target:e,isDark:t,baseDimension:n,fallback:r})=>{let i=C(r.shadowColorLight,r.shadowColorAlpha),a=C(r.shadowColorDark,r.shadowColorAlpha),o=`0px 0px ${`calc(${n} * 0.25)`} ${`calc(${n} * 0.11)`} ${t?a:i}`;e.style.boxShadow=o},ce=({target:e,layoutParams:t,fallback:n})=>{let r=t.angle??n.angle;r&&=r*-1,e.style.transform=`rotate(${r}rad)`};import{fromEvent as T,Subject as le,Subscription as ue}from"@vkontakte/videoplayer-shared/evergreen";var E=`interactive-control-tap`,D={common:E,animation:`${E}-animation`,visible:`${E}-visible`},de=60;class fe{element;controlRotateAngleRad;clickCancelCondition;circleDiameterPx;useDimensionsBasedSize;constructor({controlRotateAngleRad:e,clickCancelCondition:t,circleDiameterPx:n=de,useDimensionsBasedSize:r=!1}){let i=document.createElement(`div`);i.classList.add(D.common),this.controlRotateAngleRad=e,this.element=i,this.clickCancelCondition=t,this.circleDiameterPx=n,this.useDimensionsBasedSize=r}onElementClick=e=>{if(!e.target||!e.currentTarget||this.clickCancelCondition())return;let t=e.currentTarget.parentElement;if(!t)return;let n=t.getBoundingClientRect(),r={width:this.useDimensionsBasedSize?t.offsetWidth:this.circleDiameterPx,height:this.useDimensionsBasedSize?t.offsetHeight:this.circleDiameterPx},i=Math.min(r.width,r.height),a=n.left+n.width/2,o=n.top+n.height/2,s=pe(e.clientX-a,e.clientY-o,this.controlRotateAngleRad);this.element.style.width=i+`px`,this.element.style.left=s.x+n.width/2-i/2+`px`,this.element.style.top=s.y+n.height/2-i/2+`px`,this.element.classList.add(D.visible,D.animation)};onAnimationEnd=e=>{e.stopPropagation(),!(!e.target||!e.currentTarget)&&e.target===e.currentTarget&&this.element.classList.remove(D.visible,D.animation)}}function pe(e,t,n){return{x:e*Math.cos(n)-t*Math.sin(n),y:e*Math.sin(n)+t*Math.cos(n)}}function me(e){return`features`in e}var O=`interactive-control`,k={common:O,selected:`${O}-selected`,wrapper:`${O}-wrapper`,disabled:`${O}-disabled`,button:`${O}-button`,area:`${O}-area`,text:`${O}-text`,blinkAnim:`${O}-blink-anim`,blinkAnimButton:`${O}-blink-anim-button`,blinkAnimArea:`${O}-blink-anim-area`},he=40;import{isSupportedManifest as ge,ContainerTypes as _e,ControlTypes as A,EventActionTypes as j,EventTypes as ve,migrateManifestToLatestVersion as ye}from"@interactiveplatform/movika-manifest";var be={metadata:`Object`,chapters:`Array`},xe=e=>{if(!p(e))return!1;for(let t in be){let n=e[t];if(!n||!f(n,be[t]))return!1}return ge(e.metadata.version)};function Se(e){return e.type===A.Text}function Ce(e){return e.type===A.Button}function we(e){return e.type===A.Area}var Te={Choice:`Choice`,TextInput:`TextInput`},Ee={Button:`Button`,Area:`Area`,Text:`Text`},De={onClick:`onClick`,onSuspense:`onSuspense`},Oe={openURI:`openURI`,setNextBranch:`setNextBranch`,setWeightlessRandomBranch:`setWeightlessRandomBranch`,setRandomBranch:`setRandomBranch`,setMaxWeightBranch:`setMaxWeightBranch`,setMinWeightBranch:`setMinWeightBranch`,setDefaultBranch:`setDefaultBranch`,continuePlayback:`continuePlayback`,expect:`expect`},ke=e=>h(e)&&!x(e),M=e=>e.order===`end`,Ae=e=>h(e.containers)&&!x(e.containers)&&M(e),je=(e,t)=>{let n=e*1e3;return ke(t.controls)&&n<(t.startTime??0)},Me=(e,t)=>{let n=e*1e3;return ke(t.controls)&&n>=(t.startTime??0)&&n<=(t.endTime??1/0)},N=(e=[])=>e.some(e=>e.action.type===`expect`),Ne=(e=[])=>e.find(e=>e.action.type===`expect`),Pe=e=>e?.length===1,P=e=>Pe(e)&&Se(e[0]);function Fe(e=[],t=1/0,n=[]){return e.filter(({container:e})=>!n.includes(e.container.id)&&N(e.container.events)&&e.container.endTime===t&&!e.isRemoved&&!e.willRemoved)}function Ie({gameControllers:e=[],subjectName:t,subjectId:n,execFn:r}){for(let i of e)if(t===`container`&&i.container.container.id===n){r(i),Fe(e,i.container.container.endTime,[i.container.container.id]).forEach(e=>{r(e)});break}}function Le(e){for(let t of e.events)if(t.action.type===`openURI`)return!0;return!1}var Re=(e,t)=>{let n=N(e.events)&&!(e=>t.find(({container:t})=>t.container.id===e)?.container.isRemoved)(e.id),r=(t,n=!1,r=!1)=>{let i=r?`every`:`some`;return t.controls[i](r=>{let a=n?t.endTime===e.endTime:!0;return r.events?.[i](e=>e.action?.type===j.openURI)&&a})},i=e=>e.some(({container:e})=>r(e.container,!0,!1)&&!e.isRemoved),a=e=>e.every(({container:e})=>e.isRemoved||e.willRemoved?!0:r(e.container,!0,!0)),o=Fe(t,e.endTime,[e.id]).length,s=e=>e.controls.some(e=>e.events?.some(e=>e.action?.args?.shouldOpenNow)),c=n||o>0,l=i(t),u=r(e),d=a(t),f=n?!1:o>0,p=s(e);return{isExpectTime:c,hasOtherExpect:o>0,hasOpenURIEvent:l,hasOpenURIEventInCurrentContainer:u,isAllOpenURIEventsValid:d,isExpectEventForCurrentContainer:f,hasShouldOpenNowEvent:p}};class F{control;options;container=null;controlElement=null;subscriptions=new ue;error$=new le;controlTap;isInteracted=!1;isRemoved=!1;cssVarsManager=null;constructor(e,t=void 0){this.control=e,this.options=t}setCssVarsManager(e){this.cssVarsManager=e}onControlSelect=()=>{this.container?.isManifestContainerDisabled()||Le(this.control)||this.container?.element?.classList.add(`interactive-control-wrapper-selected`)};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(T(t,`transitionend`).subscribe(this.onTransitionEnd,e=>this.onError(`${F.name} remove view transition error`,e))).add(T(t,`transitioncancel`).subscribe(this.onTransitionEnd,e=>this.onError(`${F.name} remove view transition error`,e)));return}this.removeListeners(),t.remove(),this.isRemoved=!0}}onTransitionEnd=e=>{e.stopPropagation(),!(!e.target||!e.currentTarget)&&e.target===e.currentTarget&&this.removeView()};onError(e=``,t){c({emitter$:this.error$,error:t,message:e,subjectId:this.control.id})}addControlTap(e){this.featureIsEnabled(`controlsTapPlace`)&&this.container&&(this.controlTap=new fe({controlRotateAngleRad:this.control.layoutParams.angle??w.angle,clickCancelCondition:this.container.isManifestContainerDisabled,circleDiameterPx:this.isTouch()?he:void 0}),this.subscriptions.add(T(e,`click`).subscribe(this.controlTap.onElementClick,e=>this.onError(`Control click tap animation error`,e))).add(T(this.controlTap.element,`animationend`).subscribe(this.controlTap.onAnimationEnd,e=>this.onError(`Tap animationend error`,e))),this.container.element.append(this.controlTap.element))}createContainerElement(e){let t=document.createElement(`div`);t.classList.add(k.wrapper),e.setControlLayout(t,this.control.layoutParams),this.container={element:t,dimensions:(this.control.layoutParams.innerSizesDependOn??w.innerSizesDependOn)===`self`?{height:t.style.height,width:t.style.width}:{height:this.cssVarsManager?.getPropValue(`--interactive-content-height`)??0,width:this.cssVarsManager?.getPropValue(`--interactive-content-width`)??0},isManifestContainerDisabled:()=>e.isContainerDisabled?.()??!1}}createClickListener(e){return t=>{t.stopPropagation(),this.isInteracted=!0,e()}}featureIsEnabled(e){return!!(this.options&&me(this.options)&&this.options.features[e])}isTouch(){return!!(this.options&&me(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(T(this.container.element,`click`).subscribe(this.createClickListener(()=>e({action:t.action,controlId:this.control.id,controlType:this.control.type})),e=>this.onError(`Error happened on control interaction`,e)));break;default:break}})}removeListeners(){this.subscriptions.unsubscribe()}}var ze=`interactive-blink-anim-reference`,I={common:ze,animation:`${ze}-animation`,disabled:`${ze}-disabled`};class Be{_RAFId=0;_element=void 0;get element(){return this._element}create(){if(this._element)return;let e=document.createElement(`div`);e.classList.add(I.common,I.animation),this._element=e}restart(){this._element&&(this._element.classList.add(I.disabled),this.cleanupRAF(),this._RAFId=requestAnimationFrame(()=>{this._element&&(this._element.classList.remove(I.disabled),this.cleanupRAF())}))}cleanupRAF(){this._RAFId&&=(cancelAnimationFrame(this._RAFId),0)}destroy(){this.cleanupRAF(),this._element=void 0}}var Ve=`interactive-container`,L={common:Ve,hidden:`${Ve}-hidden`,disabled:`${Ve}-disabled`},He=(e,t)=>{if(e.type.trim().toLowerCase()===`area`)return new Ue(e,t)};class Ue extends F{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 n=document.createElement(`button`);n.type=`button`,n.classList.add(k.common,k.area),n.setAttribute(`data-testid`,`int_area`),ae({target:n,props:this.control.props,fallback:{...w,backgroundColor:`transparent`}}),ce({target:n,layoutParams:this.control.layoutParams,fallback:w}),this.addControlTap(n),this.subscriptions.add(u(this.container.element,`click`).pipe(d()).subscribe(this.onControlSelect,e=>this.onError(`Control click handler error`,e))),this.container.element.append(n),e.append(this.container.element),this.controlElement=n,this.updateShadowStyles(),this.registerBlinkAnimationEvents()}registerBlinkAnimationEvents(){if(!this.featureIsEnabled(`controlsExpectTimeBlinkAnimation`))return;let e=this.container?.element.parentElement;!e||!this.controlElement||(this.subscriptions.add(u(this.controlElement,`mouseleave`).subscribe(()=>{if(e.classList.contains(L.disabled))return;let t=e.parentElement;if(t){let e=t.querySelector(`.${I.common}`);e&&this.syncBlinkAnimation(e)}},e=>this.onError(`Error happened in mouseleave callback`,e))),this.subscriptions.add(u(this.controlElement,`mouseenter`).subscribe(()=>{e.classList.contains(L.disabled)||this.onBlinkHovering()},e=>this.onError(`Error happened in mouseenter callback`,e))).add(u(this.controlElement,`mouseleave`).subscribe(()=>{this.controlElement&&(this.controlElement.style.animation=``)},e=>this.onError(`Error happened in mouseleave callback`,e))))}disable(){this.controlElement&&this.controlElement.classList.add(k.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(k.disabled)}getElement(){return this.controlElement}updateShadowStyles(e){if(!(!this.container||!this.controlElement))if(v(e)){let t=Math.min(this.controlElement.offsetWidth,this.controlElement.offsetHeight)+`px`;se({target:this.controlElement,props:this.control.props,fallback:w,isDark:e,baseDimension:t}),oe({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 oe({target:this.controlElement,props:this.control.props,fallback:{...w,borderAlpha:0},dependsOn:this.container.dimensions})}toggleBlinkAnimation(e){this.controlElement?.classList.toggle(k.blinkAnim,e),this.controlElement?.classList.toggle(k.blinkAnimArea,e)}syncBlinkAnimation(e){this.controlElement&&(!this.controlElement.classList.contains(`${k.blinkAnimArea}`)||this.controlElement.classList.contains(k.selected)||this.controlElement.classList.contains(I.disabled)||(this.controlElement.classList.add(I.disabled),this.subscriptions.add(u(e,`animationiteration`).pipe(d()).subscribe(()=>{this.controlElement&&this.controlElement.classList.remove(I.disabled)},e=>this.onError(`Error happened in animationiteration callback`,e)))))}onBlinkHovering(){if(!this.controlElement||!this.controlElement.classList.contains(`${k.blinkAnimArea}`)||this.controlElement.classList.contains(k.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 R,once as We}from"@vkontakte/videoplayer-shared/evergreen";var Ge=e=>{let t=document.createElement(`span`);switch(e){case`Button`:case`button`:{let e=document.createElement(`div`);return Object.assign(e.style,{overflow:`hidden`,display:`flex`,justifyContent:`center`,alignItems:`center`}),e.append(t),Object.assign(t.style,{display:`inline-block`,whiteSpace:`pre`,textOverflow:`ellipsis`,maxWidth:`initial`,maxHeight:`100%`,wordBreak:`normal`}),e}default:return Object.assign(t.style,{display:`inline-block`,whiteSpace:`break-spaces`,overflow:`hidden`,textOverflow:`ellipsis`,maxWidth:`100%`,maxHeight:`100%`,wordBreak:`break-all`}),t}},z=Math.PI,Ke=2*z,B=z/2,qe=3*B,Je=[0,B,z,qe];function Ye(e){return e===B}function Xe(e){return e===z}function Ze(e){return e===qe}function Qe(e){return(e%Ke+Ke)%Ke}function $e(e){for(let t of Je)if(e===t)return t}function et(e){return $e(e)?null:[1,2,3,4][Math.floor(e/B)+1-1]}function tt(e){return e*180/Math.PI}var V=`interactive-control-fill-animation`,H={common:V,fillerWrapper:`${V}-filler-wrapper`,filler:`${V}-filler`,fillHeight:`${V}-fill-height`,fillWidth:`${V}-fill-width`,fromTop:`${V}-from-top`,fromBottom:`${V}-from-bottom`,fromLeft:`${V}-from-left`,fromRight:`${V}-from-right`};class nt{fillAnimationElement;fillAnimationFillerElement;fillAnimationFillerWrapperElement;startTime;endTime;shouldFillHeight;widthExpansionCoef=0;isDebug;fromLeft;useSkew;rotateAngle;constructor(e){let t=document.createElement(`div`);t.classList.add(H.common);let n=document.createElement(`div`);n.classList.add(H.fillerWrapper);let r=document.createElement(`div`);r.classList.add(H.filler),n.append(r),t.append(n);let i=Qe(e.rotateAngle),a=et(i),o=a!==null,s=a===2||!o&&Xe(i)||a===3,c=!o&&Ye(i),l=!o&&Ze(i),u=!s&&!c&&!l,d=c||l,f=o&&!d,p=f?i:0;t.style.borderRadius=e.borderRadius,n.style.transform=`skew(${p*-1}rad)`,d?(r.classList.add(H.fillHeight,c?H.fromTop:H.fromBottom),n.classList.add(H.fillHeight,c?H.fromTop:H.fromBottom)):(r.classList.add(H.fillWidth,u?H.fromLeft:H.fromRight),n.classList.add(H.fillWidth)),e.debug&&console.log(`[interactive ${nt.name}]`,{widthExpansionCoef:this.widthExpansionCoef,opts:e,shouldFillHeight:d,rotateAngleRad:i,rotateAngelDeg:tt(i),rotateAngleRaw:e.rotateAngle,fromRight:s,fromTop:c,fromBottom:l,fromLeft:u}),this.useSkew=f,this.fromLeft=u,this.rotateAngle=i,this.fillAnimationElement=t,this.fillAnimationFillerElement=r,this.fillAnimationFillerWrapperElement=n,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((e=>e<this.startTime||e>this.endTime)(e))return;let t=this.endTime-this.startTime,n=Math.min(Math.max((e-this.startTime)/t,0),1);this.shouldFillHeight?this.fillAnimationFillerElement.style.transform=`scaleY(${n})`:this.fillAnimationFillerElement.style.transform=`scaleX(${n})`}calcWidthExpansionCoef({rotateAngle:e,isSkewed:t=!1,initWidth:n,initHeight:r}){return t?(n+r*Math.abs(Math.tan(e)))/n-1:0}}var rt=(e,t)=>{if(e.type.trim().toLowerCase()===`button`)return new it(e,t)};class it extends F{startTime;endTime;controlFillAnimation;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 n=document.createElement(`button`);n.type=`button`,n.classList.add(k.common,k.button),n.setAttribute(`data-testid`,`int_bttn`),ce({target:n,layoutParams:this.control.layoutParams,fallback:w}),ae({target:n,props:this.control.props,fallback:w}),oe({target:n,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),re({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=Ge(this.control.type.trim().toLowerCase());ie({target:r.firstElementChild??r,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),this.addControlTap(n),this.startTime!==void 0&&this.endTime!==void 0&&this.featureIsEnabled(`controlsFillAnimation`)&&(this.controlFillAnimation=new nt({startTime:this.startTime,endTime:this.endTime,rotateAngle:this.control.layoutParams.angle??w.angle,borderRadius:n.style.borderRadius})),this.subscriptions.add(R(n,`click`).pipe(We()).subscribe(this.onControlSelect,e=>this.onError(`Control click handler error`,e))),n.append(r,this.controlFillAnimation?.fillAnimationElement??``),this.container.element.append(this.controlTap?.element??``,n),e.append(this.container.element),this.controlElement=n,this.registerBlinkAnimationEvents()}registerBlinkAnimationEvents(){if(!this.featureIsEnabled(`controlsExpectTimeBlinkAnimation`))return;let e=this.container?.element.parentElement;!e||!this.controlElement||(this.subscriptions.add(R(this.controlElement,`mouseleave`).subscribe(()=>{if(e.classList.contains(L.disabled))return;let t=e.parentElement;if(t){let e=t.querySelector(`.${I.common}`);e&&this.syncBlinkAnimation(e)}},e=>this.onError(`Error happened in mouseleave callback`,e))),this.subscriptions.add(R(this.controlElement,`mouseenter`).subscribe(()=>{e.classList.contains(L.disabled)||this.onBlinkHovering()},e=>this.onError(`Error happened in mouseenter callback`,e))).add(R(this.controlElement,`mouseleave`).subscribe(()=>{this.controlElement&&(this.controlElement.style.animation=``)},e=>this.onError(`Error happened in mouseleave callback`,e))))}disable(){this.controlElement&&this.controlElement.classList.add(k.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(k.disabled)}getElement(){return this.controlElement}toggleBlinkAnimation(e){this.controlElement?.classList.toggle(k.blinkAnim,e),this.controlElement?.classList.toggle(k.blinkAnimButton,e)}syncBlinkAnimation(e){this.controlElement&&(!this.controlElement.classList.contains(`${k.blinkAnimButton}`)||this.controlElement.classList.contains(k.selected)||this.controlElement.classList.contains(I.disabled)||(this.controlElement.classList.add(I.disabled),this.subscriptions.add(R(e,`animationiteration`).pipe(We()).subscribe(()=>{this.controlElement&&this.controlElement.classList.remove(I.disabled)},e=>this.onError(`Error happened in animationiteration callback`,e)))))}onBlinkHovering(){if(!this.controlElement||!this.controlElement.classList.contains(`${k.blinkAnimButton}`)||this.controlElement.classList.contains(k.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 at=(e,t)=>{if(e.type.trim().toLowerCase()===`text`)return new ot(e,t)};class ot extends F{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 n=document.createElement(`div`);n.classList.add(k.common,k.text),n.setAttribute(`data-testid`,`int_text`),ce({target:n,layoutParams:this.control.layoutParams,fallback:w}),re({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=Ge(this.control.type.trim().toLowerCase());ie({target:r.firstElementChild??r,props:this.control.props,fallback:w,dependsOn:this.container.dimensions}),n.append(r),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}getElement(){return this.controlElement}disable(){}enable(){}onProgress(){}onResize(){}updateShadowStyles(){}toggleBlinkAnimation(){}setShowTimeRange(){}updateFillAnimationDimensions(){}}var st=(e,t,n,r)=>{if(e.type.trim().toLowerCase()===`choice`)return new ct(e,t,n,r)};class ct extends l{rootElement;containerElement=null;layout;subscriptions=new n;isRemoved;isDisabled;willRemoved;cssVarsManager;constructor(e,t,n,r){super(e,n,r),this.rootElement=t,this.layout=new i(this.container.layout,n),this.cssVarsManager=n,this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory(`button`,rt),this.addControlFactory(`text`,at),this.addControlFactory(`area`,He)}createView({eventCallback:e,videoDurationMs:t}){let n=document.createElement(`div`);return n.classList.add(L.common,L.disabled),n.setAttribute(`data-subjectId`,this.container.id),requestAnimationFrame(()=>{n.classList.remove(L.disabled)}),this.layout.setContainerLayout(n),this.controls.forEach(r=>{r.setShowTimeRange(this.container.startTime,this.container.endTime??t),r.setCssVarsManager(this.cssVarsManager),r.createView({parentElement:n,callbacks:{setControlLayout:(e,t)=>this.layout.setControlLayout(e,t),isContainerDisabled:()=>this.isDisabled}}),r.setEvents(e),this.subscriptions.add(r.error$.subscribe(this.error$))}),this.rootElement.append(n),this.isRemoved=!1,this.willRemoved=!1,this.containerElement=n,this.updateControlsFillAnimationDimensions(),n}updateControlsFillAnimationDimensions(){for(let e of this.controls)e.updateFillAnimationDimensions()}hide(){let e=this.getElement();e&&e.classList.add(L.hidden)}show(){let e=this.getElement();e&&e.classList.remove(L.hidden)}enable(){let e=this.getElement();e&&(e.classList.remove(L.disabled),this.controls.forEach(e=>e.enable()),this.isDisabled=!1)}disable(){let e=this.getElement();e&&(e.classList.add(L.disabled),this.controls.forEach(e=>e.disable()),this.isDisabled=!0)}removeView(e=!1,n=!1){let r=this.getElement();if(r){if(e){if(this.willRemoved)return;this.willRemoved=!0,n&&r.classList.add(`interactive-container-before-remove-delay`),r.classList.add(`interactive-container-before-remove`),this.subscriptions.add(t(r,`transitionend`).subscribe(this.onTransitionEnd,e=>this.onError(`${ct.name} remove view transition error`,e))).add(t(r,`transitioncancel`).subscribe(this.onTransitionEnd,e=>this.onError(`${ct.name} remove view transition error`,e)));return}this.subscriptions.unsubscribe(),this.removeAllControls(),r.remove(),this.isRemoved=!0,this.willRemoved=!1,this.containerElement=null}}onTransitionEnd=e=>{e.stopPropagation(),!(!e.target||!e.currentTarget)&&e.target===e.currentTarget&&this.removeView()};removeAllControls(e=!1){this.controls.forEach(t=>t.removeView(e))}removeNonInteractedControls(e=!1){this.controls.forEach(t=>{t.isInteracted||t.removeView(e)})}isInteracted(){return this.controls.some(e=>e.isInteracted)}fakeRemove(){this.isRemoved||=!0}getElement(){return this.containerElement}onProgress(e,t){t&&this.controls.forEach(t=>{t.onProgress(e)})}onResize(e){e&&this.controls.forEach(e=>{e.onResize()})}updateControlsShadowStyles(e){this.controls.forEach(t=>t.updateShadowStyles(e))}toggleBlinkAnimation(e){this.controls.forEach(t=>t.toggleBlinkAnimation(e))}}import{combine as lt,InterfaceLanguage as ut,Observable as dt,once as ft,Subject as U,Subscription as W,ValueSubject as G,fromEvent as pt}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as K}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as mt}from"@vkontakte/videoplayer-shared/evergreen";function ht(e,t){let n;return(...r)=>{clearTimeout(n),n=setTimeout(()=>e(...r),t)}}var gt=`video_interactive`,_t=`videoint`,vt=250;class yt{isHidden;currentManifestId;currentChapterId;visitedChapterIds;onOpenPreviewClick;onError;lang;zoom;lastZoomInfo;isReady;ngEditor;ngEditorSize;graphWrapperElement;resizeObserver;manifest;constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:r,visitedChapters:i=[]}){this.isReady=!1,this.isHidden=!0,this.manifest=null,this.visitedChapterIds=new Set(i),this.onOpenPreviewClick=t,this.onError=n,this.lang=r??`ru`,this.zoom=.7,this.lastZoomInfo=null,this.currentManifestId=null,this.currentChapterId=null,this.ngEditor=null,this.ngEditorSize=null,this.graphWrapperElement=bt(e),this.resizeObserver=new ResizeObserver(ht(this.onResize,vt)),this.resizeObserver.observe(this.graphWrapperElement)}handleZoomChange=ht(e=>{this.lastZoomInfo=e},vt);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}};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]}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}};handleManifestChange=(e,t=[])=>{if(this.isReady=!1,!g(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.setVisitedChapters(Array.from(t)):(this.ngEditor.update(e),this.currentManifestId=this.manifest.metadata.id),this.isReady=!0)};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 mt(this.lang,gt,_t)}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:e,...t})=>{e===`openPreview`&&`chapterId`in t&&this.onOpenPreviewClick?.(t.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 bt(e){let t=document.createElement(`div`);return t.style.position=`absolute`,t.style.top=`0`,t.style.left=`0`,t.style.height=`100%`,t.style.width=`100%`,t.style.display=`none`,e.append(t),t}var xt=3e3;class St{_containers=[];_player=null;setPlayer=e=>{this._player=e};setContainers=e=>{this._containers=e};deleteContainer=e=>{this._containers=this._containers.filter(t=>t.id!==e)};getNextInteractiveTime=(e=xt)=>{if(!this._containers.length||this._player===null)return null;let t=-1,n=!1,r=Math.round(this._player.info.position$.getValue()*1e3);for(let i of this._containers){let a=i.startTime-e;if(a<=r&&(i.endTime&&r<=i.endTime||i.endTime===null)){n=!0;break}r<a&&(t=t===-1?a:Math.min(t,a))}return!n&&t!==-1?t:null}}class Ct{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 n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){let n=this.listeners[e]||[];for(let e=n.length;e>0;e--)if(n[e]===t){n.splice(e,1);break}return this}emit(e,...t){let n=this.listeners[e];return n?(n.forEach(e=>{e(...t)}),!0):!1}listenerCount(e){return this.rawListeners(e).length}rawListeners(e){return this.listeners[e]||[]}}class wt{raf;fn;fns=[];constructor(e){e&&(this.fn=e,this.addFn(e))}addFn=(e,t=!1)=>{_(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(t=>t!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{this.raf&&=(cancelAnimationFrame(this.raf),void 0)};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Tt{rootElement;isCssVarsSupported;rootElementProps={};constructor(e){this.rootElement=e,this.isCssVarsSupported=Tt.checkCssVarsSupport(e)}static checkCssVarsSupport(e){let t=`--test-key`,n=`test`;e.style.setProperty(t,n);let r=e.style.getPropertyValue(t)===n;return r&&e.style.removeProperty(t),r}getPropValue(e){return this.isCssVarsSupported?`var(${e})`:this.rootElementProps[e]??``}setup(e){if(this.rootElementProps={...this.rootElementProps,...e},this.isCssVarsSupported)for(let[t,n]of Object.entries(e))this.rootElement.style.setProperty(t,n)}cleanup(){for(let e in this.rootElementProps)this.rootElement.style.removeProperty(e);this.rootElementProps={}}setProp(e,t){this.rootElementProps[e]=t,this.isCssVarsSupported&&this.rootElement.style.setProperty(e,t)}}import{ValueSubject as Et}from"@vkontakte/videoplayer-shared/evergreen";class Dt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Ot(...this.loaders[e])(t)}}function Ot(...e){return async function(t){let n=[...e];for(;n.length>0;)t=await n.shift()(t);return t}}function q(e,t,n){return e?{...e,[t]:e[t]?[n,...e[t]]:[n]}:{[t]:[n]}}function kt({actions:e,errors:t,chapterId:n,...r}){if(n){let i=e.getManifest();if(i){let a=e.getChapter(i.chapters,n);if(a){let n=e.getMedia(i.media,a.videoId),o=e.getGraph(i.graph,a.id);return n?{...r,actions:e,errors:t,result:{chapter:a,media:n,graph:o}}:{...r,errors:q(t,kt.name,`Could not find media`),actions:e}}}}return{...r,errors:q(t,kt.name,`Could not find chapter`),actions:e}}var At=(e=``,t=``)=>{let n=e.split(`.`),r=t.split(`.`),i=0;for(let e=0;e<Math.max(n.length,r.length)&&!i;e++)i=n[e]>r[e]?1:n[e]<r[e]?-1:0;return i},jt=async e=>{try{let t={},n;if(m(e)){n=new URL(e).href;let r=await fetch(n);if(!r.ok)return{};t=await r.json()}else if(p(e))t=e;else return{};if(!xe(t))return{};let r=t.metadata.media;if(m(r)&&!(`media`in t))try{let e;n?e=new URL(r,n).href:(e=new URL(r).href,n=e);let i=await fetch(e);if(!i.ok)throw Error();t.metadata.media=await i.json()}catch{return Rt(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:n}}catch{return{}}};async function Mt(e){let{manifest:t,manifestURL:n}=await jt(e);if(!t)throw Error(`Failed on fetch`);let r=ye(t);return r.media=It(r.media,n),delete r.metadata.media,r}function Nt(e,t){if(t)return e.find(e=>e.id===t)}function Pt(e,t){if(e.edit?.chapters)return e.edit.chapters.find(e=>e.id===t);if(e.view?.chapters)return e.view.chapters.find(e=>e.id===t)}function Ft(e,t){return e.videos.find(e=>e.id===t)}function It(e,t){return{...e,videos:e.videos.map(e=>({...e,variants:e.variants.map(e=>{let n=`url`in e?e.url:``,r=Lt(n,t);return{...e,url:r||n}})}))}}function Lt(e=``,t){try{return new URL(e,t).href}catch{return``}}function Rt(e){return At(e,`3.2.0`)>=0}class zt extends Dt{manifest=null;chapter=null;media=null;graph=null;prevChapter$=new Et(null);onError;constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(e){this.release();let t=await this.exec(`manifestLoaders`,{actions:{addErrorMessage:q},result:null,errors:null,source:e});return t.errors&&this.errorHandler(t.errors),this.manifest=await Mt(t.result??e),this}async setInitial(){return this.setNext()}async setNext(e=this.manifest?.metadata.initChapterId){if(!e)return this;this.prevChapter$.next(this.chapter);let t=await this.exec(`chapterLoaders`,kt({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Pt,getChapter:Nt,getMedia:Ft,getByBranches:this.getByBranches.bind(this),addErrorMessage:q},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),t.result&&(this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph),this}errorHandler(e){this.onError(e),console.error(`Something went wrong with loaders`,{errors:e})}getInitial(){return this.getByChapterId(this.manifest?.metadata.initChapterId)||null}getByChapterId(e=this.manifest?.metadata.initChapterId){if(!e||!this.manifest)return null;let t=Nt(this.manifest.chapters,e);if(t){let e=Ft(this.manifest.media,t.videoId),n=Pt(this.manifest.graph,t.id);if(e)return{chapter:t,media:e,graph:n}}return null}getBranches(e=this.chapter?.id){if(e===this.chapter?.id)return this.getByBranches(this.chapter?.branches);{let t=Nt(this.manifest?.chapters||[],e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((e,t)=>{let n=this.getByChapterId(t.chapterId);return n&&e.push(n),e},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter?.id===this.manifest?.metadata.initChapterId}isEndChapter(){return this.chapter?M(this.chapter):!1}}import{Player as Bt}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as Vt,TracerFactory as Ht,ValueSubject as Ut}from"@vkontakte/videoplayer-shared/evergreen";var Wt=e=>{let t=e.variants.find(e=>e.payload?.type===`vk`);if(t&&t.payload){let[e,n]=t.payload.id.split(`_`);return[e,n]}return[]};function Gt(){let e=new Map;function t({listId:t=Math.random().toString(),itemId:n=Math.random().toString(),...r}){let i=e.get(t),a={...r};return i?i[n]=a:e.set(t,{[n]:a}),{listId:t,itemId:n,...r}}function n(e){e.player.destroy(),e.container.remove(),e.subscription.unsubscribe(),e.statistics?.oneStat.destroy(),e.statistics?.statSubscription.unsubscribe()}function r(t,r){let i=e.get(t);if(!i)throw Error(`Can't remove. Not find.`);if(r){let a=i[r];a&&n(a),delete i[r],Object.keys(i).length||e.delete(t)}else{for(let e of Object.values(i))n(e);e.delete(t)}}function i(){for(let t of e)r(t[0])}return{createPlayer:t,removePlayer:r,map:e,removeAll:i}}function Kt(e,t=[]){let n={},r,i=!t.length;for(let a of e.variants)if(!r&&`cover`in a&&(r=a.cover),`url`in a)switch(a.type.toLowerCase()){case`mp4`:(i||t.includes(`mp4`))&&(n.MPEG={...n.MPEG,[a.standard??`Invariant quality`]:a.url});break;case`mpeg`:(i||t.includes(`mpeg`))&&(n.MPEG={...n.MPEG,[a.standard??`Invariant quality`]:a.url});break;case`hls`:(i||t.includes(`hls`))&&(n={...n,HLS:{type:`url`,url:a.url}});break;case`dash`:(i||t.includes(`dash`))&&(n={...n,DASH_SEP:{compatibilityMode:!0,type:`url`,url:a.url}});break;default:break}return{sources:n,thumbUrl:r,title:e.title??``}}var J=(e,t)=>{let n=e.info.currentQuality$.getValue(),r=e.info.availableQualities$.getValue();n!==t&&r.includes(t)&&(e.setQuality(t),e.setAutoQuality(!1))},qt=2;function Jt(e){let t=Gt(),n=new Vt,r={},i=null,a=!1,o,s=new Ut(null);e&&c(e);function c(e){i=e}function l(e,n,o){if(!i)throw Error(`need to set interactive controller`);if(!i.options)return;let c=(t.map.get(e)??{})[n];if(c){r={chapterId:o,listId:e,itemId:n,...c};let l=r.player;r.subscription.add(l.info.currentQuality$.subscribe(e=>{let n=l.info.position$.getValue(),r=l.info.isAutoQualityEnabled$.getValue();if(!(!e||!n||r))for(let n of t.map)Object.values(n[1]).forEach(({player:t})=>{J(t,e)})})).add(l.events.started$.subscribe(()=>{u(n)})),c.container.remove(),i.setPlayer(c.player),a||=(i.init(),!0),s.next({player:r.player,config:r.config,statistics:r.statistics});return}throw Error(`Can't set. Not find.`)}async function u(e){if(!i)throw Error(`need to set interactive controller`);if(b(r)||e!==r.itemId)return;let t=i.getChapterBranches(),n=new Set;for(let e of t)n.has(e.media.id)||(await f({media:e.media,chapterId:e.chapter.id,setAsActive:!1,title:e.chapter.label}),n.add(e.media.id))}async function d({chapter:{id:e},manifestVideo:n}){if(b(r)||!i)return;let a=r.player.info.muted$.getValue(),o=r.player.info.currentQuality$.getValue(),s=r.player.info.isAutoQualityEnabled$.getValue(),c=r.player.info.volume$.getValue(),u=r.player.info.currentPlaybackRate$.getValue(),d=!s,p=!1;for(let s of t.map)if(s[0]===n.id&&!i.state.isReplay$.getValue()){let n=Object.keys(s[1]);for(let i of n)i===r.itemId?(n.length<qt||(p=!0),t.removePlayer(s[0],i)):(p=!0,l(s[0],i,e),d?J(r.player,o):r.player.setAutoQuality(!0),r.player.setVolume(c),r.player.setMuted(a),r.player.setPlaybackRate(u))}else t.removePlayer(s[0]);p||(await f({media:n,chapterId:e,setAsActive:!0,playbackRate:u}),d?J(r.player,o):r.player.setAutoQuality(!0),r.player.setVolume(c),r.player.setMuted(a))}async function f({media:e,chapterId:n,prefetch:a=!0,setAsActive:s=!0,autoplay:c=!1,preferredExt:u,title:d,playbackRate:f}){let p=Math.random().toString(),m=document.createElement(`div`);o.append(m);let h;if(i?.options?.vkVideoLoader){let t=Wt(e);t.length&&(h=await i.options.vkVideoLoader(...t))}let g={...i?.options?.coreConfig||void 0},_={container:m,sources:Kt(e,u).sources,...h?.videos?.[0],title:d,failoverHosts:h?.failoverHosts||[]},v=new Bt(g,Ht.createRootTracer());v.initVideo(_);let y=null;if(h?.videos&&i?.options.createOneStat){let e=h.videos[0],t=i.options.createOneStat(e),n=new Vt;t&&(n.add(t.attachTo(v)),y={oneStat:t,statSubscription:n})}let b=new Vt,x=r?.player?.info.isAutoQualityEnabled$.getValue();b.add(v.events.canplay$.subscribe(function(){x||J(v,r.player.info.currentQuality$.getValue()),f&&v.setPlaybackRate(f)}));let S=t.createPlayer({listId:e.id,itemId:p,player:v,container:m,sources:Kt(e,u).sources,config:_,subscription:b,statistics:y});return s&&l(e.id,S.itemId,n),c&&S.player.play(),a&&!c&&S.player.prepare(),{player:S.player,config:S.config,statistics:S.statistics}}function p(){m(),i=null,o.remove()}function m(){n.unsubscribe(),t.removeAll(),r={},a=!1}async function h(){if(!i)throw Error(`need to set interactive controller`);m(),o=document.createElement(`div`);let{media:e,chapter:t}=i.getCurrentChapter();e&&t?(n.add(i.events.chapterChanged$.subscribe(d)),await f({media:e,chapterId:t.id,title:t.label})):console.error(`not found`)}return{map:t.map,removePlayer:t.removePlayer,init:h,setInteractiveController:c,createPlayer:f,removeAll:p,getActivePlayer:function(){return r},activePlayerChanged:s}}var Y={graph:`graph`,interactives:`interactives`,chapterChanged:`chapter-changed`,playerChanged:`player-changed`,manifestChanged:`manifest-changed`,errors:`errors`,eachTick:`eachTick`,historyInited:`history-inited`,historyDestroyed:`history-destroyed`},Yt={visibility:`visibility`,watchAgainClicked:`watchAgainClicked`},X={actionChoiceCanceled:`action-choice-canceled`,actionChoice:`action-choice`,actionExecution:`action-execution`,visibility:`visibility`,containerRemoved:`container-removed`,rangeEnded:`range-ended`};import{Subscription as Xt}from"@vkontakte/videoplayer-shared/evergreen";function Zt(e){return function(...t){return e(...t.reverse())}}function Z(e,...t){return(...n)=>p(t[0])&&p(n[0])?e({...t[0],...n[0]}):e(...t,...n)}class Qt{container;branches;selectBranches;subscription;player;interactiveEvents;getContainerEventState;isPermanentText;interactiveTimeOpenUri;disabledControls$;onRemove;globalEventEmitter;gameState;isSelectedControlEvent;isSelectedContainerEvent;globalEvents;onError;disableTextControlContainerVisibilityEvents;features;constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:i,globalEvents:a,globalEventEmitter:o,getContainerEventState:s,permanentTextControls:c,interactiveTimeOpenUri:l,disabledControls$:u,onRemove:d,onError:f,disableTextControlContainerVisibilityEvents:p=!1,features:m}){this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new Xt,this.player=e,this.interactiveEvents=i,this.getContainerEventState=s;let h=P(t.container.controls);this.isPermanentText=c&&h,this.disableTextControlContainerVisibilityEvents=p&&h,this.interactiveTimeOpenUri=l,this.disabledControls$=u,this.onRemove=d,this.globalEventEmitter=o,this.gameState=0,this.globalEvents=a,this.onError=f,this.features=m,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(Y.interactives,{subjectId:this.container.container.id,subjectName:`container`,type:X.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(Y.interactives,{subjectId:this.container.container.id,subjectName:`container`,type:X.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))}hide=()=>{setTimeout(()=>{this.gameState!==4&&(N(this.container.container.events)&&this.gameState===3||this.selectBranches.state.isExpect||(this.gameState!==2&&this.container.hide?.(),this.emitContainerVisibilityEvent(!1)))})};show=()=>{if(!(this.gameState!==2||this.isSelectedControlEvent))if(this.container.getElement()){let{hasOpenURIEventInCurrentContainer:e}=this.getContainerEventState();if(this.container.show?.(),this.interactiveTimeOpenUri&&e||this.disableTextControlContainerVisibilityEvents)return;this.emitContainerVisibilityEvent(!0,!1)}else{let e={isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.emitContainerVisibilityEvent(!1)},onEvent:(e,t)=>{let{isExpectTime:n,hasOtherExpect:r,hasOpenURIEvent:i,hasOpenURIEventInCurrentContainer:a,isAllOpenURIEventsValid:o,hasShouldOpenNowEvent:s}=this.getContainerEventState(),c=this.interactiveTimeOpenUri&&!a,l=this.interactiveTimeOpenUri&&a;if((!this.interactiveTimeOpenUri||c)&&(this.isSelectedControlEvent=!0),e!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||c)){if(this.interactiveTimeOpenUri){let e=!r&&!o&&a;e&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:`container`,type:`container-fake-removed`,removeAllOpenURI:e})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&i&&this.gameState!==5){if(l){let e=((e,t,n,r)=>!e&&!t&&n||e&&!t&&n&&!r||e&&!t&&n&&r)(n,r,o,this.isSelectedContainerEvent);this.fakeRemoveView(e)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!n||!r||!s)&&(this.selectBranches.stopExpect(),t())}},isEOV:()=>this.gameState===4},t=Z(this.selectBranches.onControlEvent,e),n=(this.player?.info.duration$.getValue()??1/0)*1e3;this.container.createView({eventCallback:t,videoDurationMs:n}),this.disableTextControlContainerVisibilityEvents||this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};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(),n=this.interactiveTimeOpenUri?e||t:N(this.container.container.events)||e;(this.isSelectedControlEvent||!n)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.emitContainerVisibilityEvent(!1)}onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};whilePlaying=()=>{let e=this.player.experimental.element$.getValue(),t=e instanceof HTMLVideoElement;if(this.features.enableAvPlayerSupport&&(t||=e instanceof HTMLObjectElement&&e?.getAttribute(`type`)===`application/avplayer`),!(t&&e?.readyState)||this.isRemovedOrDestroyed()&&!this.isPermanentText)return;let n=this.player.getExactTime();if(je(n,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(Me(n,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let e=this.gameState;this.gameState=3,e===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:e}=this.getContainerEventState(),t=this.selectBranches.state.isExpect,n=this.interactiveTimeOpenUri&&e;if(n&&!t){let e=this.container.getElement();e&&(e.style.visibility!==`hidden`&&this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView())}!this.isPermanentText&&!n&&this.removeView()}let r=Me(n,this.container.container),i=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],a={subjectId:this.container.container.id,subjectName:`container`,range:i,currentTime:n,isInteractiveTime:r};this.container.onProgress(n*1e3,r),this.globalEventEmitter.emit(Y.eachTick,a),this.globalEvents.eachTick$.next(a)};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(Y.interactives,{subjectId:this.container.container.id,subjectName:`container`,type:X.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 $t=(e=[])=>e.reduce((e,t,n)=>{if(ke((t?.controls??[]).filter(e=>!Se(e)))){let r=[t.startTime??0,t.endTime??1/0],i={id:t.id,isRemoved:!1};if(!n)e.push({subjects:[i],range:r});else{let t=[],n=-1/0,a=1/0,o=[],s=[];for(let c=0;c<e.length;c++){let l=e[c];if(s.push(...l.subjects),l.range[0]<a&&(a=l.range[0]),l.range[1]>n&&(n=l.range[1]),r[0]>=l.range[0]&&r[1]<=l.range[1])return e[c].subjects.push(i),e;r[0]<l.range[0]&&r[1]>l.range[0]&&(t.push(c),o=o.concat(l.subjects)),r[0]>=l.range[0]&&r[0]<=l.range[1]&&(t.push(c),o=o.concat(l.subjects),r[0]=l.range[0]),r[1]>=l.range[0]&&r[1]<=l.range[1]&&(t.push(c),o=o.concat(l.subjects),r[1]=l.range[1])}if(s.push(i),r[0]<=a&&r[1]>=n)return[{subjects:s,range:r}];t.length&&t.reverse().forEach(t=>{e.splice(t,1)}),e.push({subjects:o.concat([i]),range:r})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function en(){let e={};function t(){for(let t in e)Object.prototype.hasOwnProperty.call(e,t)&&delete e[t]}function n(t){let n={};for(let r in e)+r<=t&&(n[r]=e[r]);return n}function r(t){let n={};for(let r in e)+r>=t&&(n[r]=e[r]);return n}function i({timestamp:t,priority:n,initiator:r}){if(y(t)){let i=e[t]??null;if(i&&n&&S(n,!0)){let e={},t=i[n];return t&&(e={...e,...t}),e=b(e)?null:e,e&&S(r,!0)?e[r]??null:e}return i}return null}function a({timestamp:t,priority:n,initiator:r}){if(y(t))if(e[t]){if(n&&S(n,!0))if(e[t][n]){if(r&&S(r,!0))if(e[t][n][r]){if(delete e[t][n][r],!b(e[t][n]))return!0}else return!1;if(delete e[t][n],!b(e[t]))return!0}else return!1;return delete e[t]}else return!1;return!1}function o({timestamp:t,priority:n,initiator:r,...i}){e[t]?.[n]?.[r]?e[t][n][r].push({...i}):e[t]?.[n]?e[t][n]={...e[t][n],[r]:[{...i}]}:e[t]?e[t]={...e[t],[n]:{[r]:[{...i}]}}:e[t]={[n]:{[r]:[{...i}]}}}return{map:e,remove:a,add:o,removeAll:t,get:i,getLte:n,getGte:r}}var tn=[j.expect,j.setNextBranch],nn=1/0;function rn(e,t){let n=e,r,i=an(t),a=en(),o,s=()=>{p(),_()},c=e=>{a.add.call(void 0,e),m()},l=(e=[])=>{for(let t of e)if(t.action(),tn.includes(t.actionType))break},u=(e=1/0)=>{let t=Q(a.get({timestamp:e,priority:`control`})??{}),n=Q(a.get({timestamp:e,priority:`container`})??{}),r=Q(a.get({timestamp:e,priority:`chapter`})??{});return[...t,...n,...r]},d=e=>{i.isReady(e)&&l(u(e))},f=()=>{l([...Q(a.get({timestamp:1/0,priority:`chapter`})??{})])},p=()=>{r&&=(o?.unsubscribe(),void 0)},m=()=>{r||(r=()=>setTimeout(()=>{d(1/0)}),o=n.events.ended$.subscribe(r))},h=e=>{p(),n=e},g=e=>{e.priority===`container`&&i.resetCalled(e.timestamp),a.remove(e)},_=()=>{i.release(),a.removeAll()};return{setPlayer:h,add:c,remove:g,exec:d,execEndOfVideo:f,listen:m,unlisten:p,release:s,containersEventsCallState:i,getPreparedToExecActions:u}}function an(e){let t=new Map;return{setCalled:({timestamp:e,id:n})=>{let r=t.get(e);r&&r[n]!==void 0&&(r[n]=!0)},setData:(e=[])=>{for(let n of e){let e=n.endTime??nn,r=t.get(e);t.set(e,{...r,[n.id]:!1})}},resetCalled:e=>{let n=t.get(e);if(n)for(let e in n)n[e]=!1},isReady:n=>{let r=t.get(n);if(!r)return!0;let i=Object.values(r);return e?i.some(e=>e):!i.some(e=>!e)},release:()=>t.clear()}}function Q(e){return Object.values(e).flat().sort(e=>e.actionType===j.expect?-1:1)}var on={videoContentHeight:0,videoContentWidth:0},sn=e=>{let{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return on;let{clientHeight:r,clientWidth:i}=e.experimental.element$.getValue()||{};if(!(r&&i))return on;let a=t/n,o=r/i,s,c;return o>a?(c=i,s=i*a):o<a?(c=r/a,s=r):(c=i,s=r),{videoContentWidth:c,videoContentHeight:s}},cn=250;function ln(e){let t,n=new ResizeObserver(e=>{a(e),t=a.bind(null,e)});function r(t){let{parentElement:n,player:r,cssVarsManager:i}=e();if(!n||!r)return;let{videoContentWidth:a,videoContentHeight:o}=sn(r);i.setup({"--interactive-content-width":`${a}px`,"--interactive-content-height":`${o}px`,"--interactive-width":`${t[0].contentRect.width}px`,"--interactive-height":`${t[0].contentRect.height}px`})}function i(){let{parentElement:t}=e();t.removeAttribute(`style`)}let a=ht(t=>{let{fns:n=[]}=e();r(t);for(let e of n)e()},cn);function o(){t=void 0,n.disconnect(),i()}return{resizeObserver:n,calc:()=>{t?.()},release:o}}var un=e=>Math.floor(Math.random()*e),dn=e=>{let t=e.length,n=1/0,r=null;for(;t--;){let i=e[t],a=i.weight??1;a<n&&(n=a,r=i)}return r},fn=e=>{let t=e.length,n=-1/0,r=null;for(;t--;){let i=e[t],a=i.weight??0;a>n&&(n=a,r=i)}return r},pn=e=>{let t=e.length;return e[un(t)]},mn=1,hn=e=>{let t=0;for(let n=0;n<e.length;++n)t+=e[n].weight??mn;let n=Math.random()*t;t=0;for(let r=0;r<e.length-1;++r)if(t+=e[r].weight??mn,t>=n)return e[r];return e[e.length-1]},gn={shouldOpenNow:!0,isDetachContainer:!0},_n=`after-expect`,vn=(e,t=!1)=>({...e,args:t?{...e.args,...gn}:{...gn,...e.args}}),yn=({globalEventEmitter:e,globalEvents:t,player:n,interactiveEvents:r})=>{let i={isExpect:!1},a=()=>{i.isExpect&&=!1},o=({action:n,controlType:i,controlId:a,containerId:o,branches:c=[],onEvent:l,isEOV:u=()=>!1,isDisabled:f=()=>!1})=>{let p=vn(n,u()),v={timestamp:1/0,priority:`control`,initiator:a,actionType:p.type},y=f(),b=e.emit.bind(e,Y.interactives,{subjectId:a,subjectType:i,subjectName:`control`,type:y?X.actionChoiceCanceled:X.actionChoice,actionType:n.type,payload:{invokeImmediately:p.args.shouldOpenNow,containerId:o,...p.args}}),x=()=>{t.interactiveActionChoice$.next({subjectId:a,subjectType:i,subjectName:`control`,type:y?`action-choice-canceled`:`action-choice`,actionType:n.type,payload:{invokeImmediately:p.args.shouldOpenNow,containerId:o,...p.args}})};if(y){b(),x();return}switch(p.type.trim().toLowerCase()){case j.setNextBranch.trim().toLowerCase():{let e=c.find(e=>e.id===p.args.branchId);if(!e)return;l(p.args.isDetachContainer,m.bind(null,{subjectId:a,subjectName:`control`})),b(),x(),p.args.shouldOpenNow?g({subjectId:a,subjectName:`control`,subjectType:i,action:p,payload:{chapterId:e.chapterId,autoSelect:!1}}):r.add({...v,action:g.bind(null,{subjectId:a,subjectName:`control`,subjectType:i,action:p,payload:{chapterId:e.chapterId,autoSelect:!1}})});return}case j.continuePlayback.trim().toLowerCase():l(p.args.isDetachContainer,m.bind(null,{subjectId:a,subjectName:`control`})),b(),x(),p.args.shouldOpenNow?h({subjectId:a,subjectName:`control`,subjectType:i,action:n}):r.add({...v,action:h.bind(null,{subjectId:a,subjectName:`control`,subjectType:i,action:n})});return;case j.openURI.trim().toLowerCase():l(p.args.isDetachContainer,m.bind(null,{subjectId:a,subjectName:`control`})),b(),x(),p.args.shouldOpenNow?_({subjectId:a,subjectName:`control`,subjectType:i,action:p,payload:{URI:n.args.uri}}):r.add({...v,action:_.bind(null,{subjectId:a,subjectName:`control`,subjectType:i,action:p,payload:{URI:n.args.uri}})});return;default:{let e=`Unexpected control event`;d(new s(1,1,{message:e}),e);return}}},c=({action:n,container:{id:i,endTime:a},branches:o=[],isEOV:c=!1,autoSelected:l=!1})=>{let u=vn(n,c),f={timestamp:!u.args.shouldOpenNow||c?1/0:a??1/0,priority:`container`,initiator:i,actionType:u.type},p=e.emit.bind(e,Y.interactives,{subjectId:i,subjectName:`container`,type:X.actionChoice,actionType:u.type,payload:{invokeImmediately:u.args.shouldOpenNow,...u.args}}),m=()=>{t.interactiveActionChoice$.next({subjectId:i,subjectName:`container`,type:`action-choice`,actionType:u.type,payload:{invokeImmediately:u.args.shouldOpenNow,...u.args}})};switch(u.type.trim().toLowerCase()){case j.setNextBranch.trim().toLowerCase():{let e=o.find(e=>e.id===u.args.branchId);if(!e)return;p(),m(),r.add({...f,action:g.bind(null,{subjectId:i,subjectName:`container`,action:u,payload:{chapterId:e.chapterId,autoSelect:l}})});return}case j.setMaxWeightBranch.trim().toLowerCase():return;case j.setMinWeightBranch.trim().toLowerCase():return;case j.setRandomBranch.trim().toLowerCase():return;case j.setWeightlessRandomBranch.trim().toLowerCase():return;case j.continuePlayback.trim().toLowerCase():p(),m(),r.add({...f,action:h.bind(null,{subjectId:i,subjectName:`container`,action:u})});return;case j.openURI.trim().toLowerCase():p(),m(),r.add({...f,action:_.bind(null,{subjectId:i,subjectName:`container`,action:u,payload:{URI:n.args.uri}})});return;default:{let e=`Unexpected container event`;d(new s(1,1,{message:e}),e);return}}};function l({container:n,branches:a,isEOV:o=!1}){let s=Ne(n.events);if(s){let a=vn(s.action,o);e.emit(Y.interactives,{subjectId:n.id,subjectName:`container`,type:X.actionChoice,actionType:a.type,payload:{invokeImmediately:a.args.shouldOpenNow,...a.args}}),t.interactiveActionChoice$.next({subjectId:n.id,subjectName:`container`,type:`action-choice`,actionType:a.type,payload:{invokeImmediately:a.args.shouldOpenNow,...a.args}}),r.add({timestamp:o?1/0:n.endTime??1/0,priority:`container`,initiator:n.id,actionType:j.expect,action:p.bind(null,{subjectId:n.id,subjectName:`container`})}),i.isExpect=!0}else for(let e of n.events??[])c({action:e.action,container:n,branches:a,isEOV:o})}let u=({chapterId:n,action:r,branches:i=[]})=>{let a=e.emit.bind(e,Y.interactives,{subjectId:n,subjectName:`chapter`,type:X.actionChoice,actionType:r.type,payload:r.args}),o=()=>{t.interactiveActionChoice$.next({subjectId:n,subjectName:`chapter`,type:`action-choice`,actionType:r.type,payload:r.args})};switch(r.type.trim().toLowerCase()){case j.setNextBranch.trim().toLowerCase():{let e=i.find(e=>e.id===r.args.branchId);return e?.chapterId?(a(),o(),g.bind(null,{subjectId:n,subjectName:`chapter`,action:r,payload:{chapterId:e.chapterId,autoSelect:!0}})):void 0}case j.setWeightlessRandomBranch.trim().toLowerCase():{let e=pn(i);return e?.chapterId?(a(),o(),g.bind(null,{subjectId:n,subjectName:`chapter`,action:r,payload:{chapterId:e.chapterId,autoSelect:!0}})):void 0}case j.setRandomBranch.trim().toLowerCase():{let e=hn(i);return e?.chapterId?(a(),o(),g.bind(null,{subjectId:n,subjectName:`chapter`,action:r,payload:{chapterId:e.chapterId,autoSelect:!0}})):void 0}case j.setMaxWeightBranch.trim().toLowerCase():{let e=fn(i);return e?.chapterId?(a(),o(),g.bind(null,{subjectId:n,subjectName:`chapter`,action:r,payload:{chapterId:e.chapterId,autoSelect:!0}})):void 0}case j.setMinWeightBranch.trim().toLowerCase():{let e=dn(i);return e?.chapterId?(a(),o(),g.bind(null,{subjectId:n,subjectName:`chapter`,action:r,payload:{chapterId:e.chapterId,autoSelect:!0}})):void 0}case j.continuePlayback.trim().toLowerCase():return a(),o(),h.bind(null,{subjectId:n,subjectName:`chapter`,action:r});case j.openURI.trim().toLowerCase():return a(),o(),_.bind(null,{subjectId:n,subjectName:`chapter`,action:r,payload:{URI:r.args.uri}});default:{let e=`Unexpected chapter event`;d(new s(1,1,{message:e}),e);return}}};function d(n,r){console.error(r),t.error$.next(n),e.emit(Y.errors,n)}function f(n){let i=Ne(n.events);if(i){if(M(n))return;e.emit(Y.interactives,{subjectId:n.id,subjectName:`chapter`,type:X.actionChoice,actionType:i.action.type,payload:i.action.args}),t.interactiveActionChoice$.next({subjectId:n.id,subjectName:`chapter`,type:`action-choice`,actionType:i.action.type,payload:i.action.args}),r.add({timestamp:1/0,priority:`chapter`,initiator:n.id,actionType:j.expect,action:p.bind(null,{subjectId:n.id,subjectName:`chapter`})})}else n.events?.forEach(e=>{let t=u({chapterId:n.id,action:e.action,branches:n.branches});t&&r.add({timestamp:1/0,priority:`chapter`,initiator:n.id,actionType:e.action.type,action:t})})}let p=({subjectId:r,subjectName:i})=>{n.pause(),e.emit(Y.interactives,{subjectId:r,subjectName:i,type:X.actionExecution,actionType:j.expect}),t.interactiveActionExecution$.next({subjectId:r,subjectName:i,type:`action-execution`,actionType:j.expect})},m=({subjectId:i,subjectName:a})=>{n.info.isEnded$.getValue()?r.execEndOfVideo():n.play(),e.emit(Y.interactives,{subjectId:i,subjectName:a,type:X.actionExecution,actionType:_n}),t.interactiveActionExecution$.next({subjectId:i,subjectName:a,type:`action-execution`,actionType:_n})},h=({subjectId:n,subjectName:r,subjectType:i,action:a})=>{e.emit(Y.interactives,{subjectId:n,subjectName:r,subjectType:i,type:X.actionExecution,actionType:a.type}),t.interactiveActionExecution$.next({subjectId:n,subjectName:r,subjectType:i,type:`action-execution`,actionType:a.type})},g=({subjectId:n,subjectName:r,subjectType:i,action:a,payload:o})=>{o.behaviour=`change-chapter`,e.emit(Y.interactives,{subjectId:n,subjectName:r,subjectType:i,type:X.actionExecution,actionType:a.type,payload:o}),t.interactiveActionExecution$.next({subjectId:n,subjectName:r,subjectType:i,type:`action-execution`,actionType:a.type,payload:o})},_=({subjectId:n,subjectName:r,subjectType:i,action:a,payload:o})=>{if(!o.URI)return;let s=window.open(o.URI,`_blank`,`noopener,noreferrer`);s&&(s.opener=null),e.emit(Y.interactives,{subjectId:n,subjectName:r,subjectType:i,type:X.actionExecution,actionType:a.type}),t.interactiveActionExecution$.next({subjectId:n,subjectName:r,subjectType:i,type:`action-execution`,actionType:a.type})};return{onControlEvent:o,onContainerEvent:c,onChapterEvent:u,onExpectEvent:p,expectEventHandler:m,setManifestChapterEvents:f,setManifestContainerEvents:l,stopExpect:a,state:i}};import{Subscription as bn,Subject as xn,ValueSubject as $}from"@vkontakte/videoplayer-shared/evergreen";var Sn=(e,t)=>{let n={};return e.map(e=>{if(!n[e]){let r=t.chapters.find(t=>t.id===e);if(!r)return null;let i=t.media.videos.find(e=>r.videoId===e.id);if(!i)return null;n[e]=Tn(i)}return n[e]}).filter(e=>e!==null)},Cn=e=>{for(let t of e.variants)if(wn(t)&&t.payload)return t.payload.id},wn=e=>!!(e.type===`custom`&&e.payload&&e.payload.type===`vk`),Tn=e=>{let t=Cn(e);if(!t)return null;let n=t.split(`_`).pop();return n?parseInt(n,10):null},En=(e,t)=>{for(let n of e.media.videos)if(t===Tn(n)){for(let t of e.chapters)if(t.videoId===n.id)return t.id;return}},Dn=(e,t)=>e.reduce((e,n)=>{let r=En(t,n);return r?[...e,r]:e},[]);class On{state={history$:new $([]),hasPrevChapter$:new $(!1),prevChapter$:new $(null),isInitialChapter$:new $(!1),isGoBackLimited$:new $(!1)};#api=null;#settings;#inited=!1;#manifest=null;#videoIds=null;events={inited$:new xn,destroyed$:new xn,error$:new xn};#rootVid=null;#interactiveController=null;#globalEventEmitter=null;#subscription=new bn;#isGoBackUpdate=!1;#goBackCounter=0;constructor({globalEventEmitter:e,videoId:t,interactiveController:n,historyApi:r,settings:i}){this.#rootVid=t,this.#globalEventEmitter=e,this.#interactiveController=n,this.#api=r,this.#settings=i,this.state.history$&&this.#subscription&&this.#subscription?.add(this.state.history$.subscribe(e=>{this.state.prevChapter$.next(e.at(-2)||null),this.state.hasPrevChapter$.next(e.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#manifest?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#goBackCounter===this.#settings.maxLength-1)}))}async setManifest(e){if(!this.#interactiveController||!this.#globalEventEmitter)return;this.#manifest=e,await this.getProjectHistory();let t=this.getInitialChapterId();await this.#interactiveController.setChapter({chapterId:t,pushToHistory:!1}),this.#inited||(this.#inited=!0,this.events.inited$.next({initChapterId:t}))}get inited(){return this.#inited}async updateHistory(e,t=!0){if(!this.#manifest)return;this.#isGoBackUpdate?(this.#isGoBackUpdate=!1,this.#goBackCounter++):this.#goBackCounter=0;let n=this.#manifest,r=e.length-this.#settings.maxLength,i=r>0?e.slice(r):e,a=Sn(i,n);if(this.#videoIds=a,this.state.history$.next(i),!(!t||!this.#api||!this.#rootVid))try{await this.#api.save(this.#rootVid,a)}catch{let e=new s(1,5,`Unable to save interactive history`);this.events.error$.next(e),this.#globalEventEmitter?.emit(Y.errors,e)}}async goBack(){if(!this.state||!this.#interactiveController){let e=new s(1,5,`Unable to save interactive history`);this.events.error$.next(e),this.#globalEventEmitter?.emit(Y.errors,e);return}this.#isGoBackUpdate=!0;let e=this.state.history$.getValue().slice(0,-1),t=e.pop();this.state.history$.next(e),await this.#interactiveController.setChapter({chapterId:t,playPrev:!0})}async getProjectHistory(){if(!this.#manifest||!this.#rootVid)return;let e=this.#manifest,t=[this.getInitialVideoId()];if(this.#api)try{let e=await this.#api.get(this.#rootVid);e.length&&(t=e)}catch{let e=new s(1,5,`Error while trying to fetch data`);this.events.error$.next(e),this.#globalEventEmitter?.emit(Y.errors,e)}let n=Dn(t,e);this.state.history$.next(n)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#settings.initChapterId||this.#manifest?.metadata.initChapterId}getInitialVideoId(){return this.#manifest?Sn([this.getInitialChapterId()],this.#manifest).pop():null}destroy(){this.#rootVid=null,this.#api=null,this.#interactiveController=null,this.#subscription?.unsubscribe(),this.#subscription=null,this.#inited=!1,this.#globalEventEmitter?.emit(Y.historyDestroyed),this.events.destroyed$.next(),this.#globalEventEmitter=null}}class kn{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){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,n=t.length;for(let e=3;e<n;e+=40)if(t[e]!==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 n=e.width+e.height;if(this._prevSizeId===n)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=n}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)}}class An{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement(`div`),this.rootElement.style.cssText=`
7
7
  position: absolute;
8
8
  top: 0;
9
9
  left: 0;
@@ -11,12 +11,12 @@ var Lt="1.0.61";import{fromEvent as si,Subscription as Gi}from"@vkontakte/videop
11
11
  height: var(--interactive-height);
12
12
  background-color: var(--black);
13
13
  visibility: hidden;
14
- `,this.lastFrameCanvas=new Ye,this.endOffsetMs=t,this._callbacks={onError:i},this.lastFrameCanvas.rootElement.style.cssText=`
14
+ `,this.lastFrameCanvas=new kn,this.endOffsetMs=t,this._callbacks={onError:n},this.lastFrameCanvas.rootElement.style.cssText=`
15
15
  position: absolute;
16
16
  top: 50%;
17
17
  left: 50%;
18
18
  transform: translate(-50%, -50%);
19
- `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);let t=getComputedStyle(this.rootElement),i={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(i,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}};function ki(n=0){return new Promise(e=>{setTimeout(()=>{e(0)},n)})}var Vi=`/* interactive-container */
19
+ `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility=`visible`}hide(){this.rootElement.style.visibility=`hidden`}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);let t=getComputedStyle(this.rootElement),n={width:parseInt(t.getPropertyValue(`--interactive-content-width`),10),height:parseInt(t.getPropertyValue(`--interactive-content-height`),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(e){this._onError(e)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return!!(this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs)}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=e=>{let t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)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()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}}function jn(e=0){return new Promise(t=>{setTimeout(()=>{t(0)},e)})}var Mn=`/* interactive-container */
20
20
  .interactive-container {
21
21
  opacity: 1;
22
22
  visibility: visible;
@@ -282,4 +282,5 @@ var Lt="1.0.61";import{fromEvent as si,Subscription as Gi}from"@vkontakte/videop
282
282
  .interactive-control-fill-animation-filler.interactive-control-fill-animation-from-bottom {
283
283
  transform-origin: bottom;
284
284
  }
285
- `;var Mi=n=>{let e=document.createElement("style");e.textContent=Vi,n.prepend(e)};import{clientChecker as gn}from"@vkontakte/videoplayer-core/evergreen";var Oi=Object.freeze({lang:yn.RU,loaders:{},graph:!1,initSeamless:!1,lastFrame:!1,permanentTextControls:!0,interactiveTimeOpenUri:!1,config:{historyMaxLength:100,noInteractionEventTimeout:3e4},isTouch:!1,disableTextControlContainerVisibilityEvents:!1,animationsFeatureToggles:{areaControlShadow:!1,controlsExpectTimeBlinkAnimation:!1,controlsTapPlace:!1,controlsFillAnimation:!1,controlsHideAnimation:!1},enableAvPlayerSupport:!1});function En(){let n=document.createElement("div");return n.classList.add("interactive-chapter"),n}var et=class{constructor(e){this.playerSubscriptions=new Vt;this.subscriptions=new Vt;this.globalEventEmitter=new We;this.animation=new Ge;this.seekToInteractiveController=new me;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=En();this.factories=new Map([["choice",Ue]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new Vt;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&&D(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(a=>a.id!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};if(this._options={...Oi,...e,config:{...Oi.config,...e.config}},this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation){this.blinkAnimationRef=new Fe,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 Je({parentElement:this._options.parentElement,onError:r=>{let o=new M(1,6,r);this.emitErrorEvent(o)}})),Mi(this._options.parentElement),this.subscriptions.add(Li(this.rootElement,"mousedown").subscribe(r=>r.stopPropagation())).add(Li(this.rootElement,"mouseup").subscribe(r=>r.stopPropagation())),this.manifestController=new ne(this._options.loaders,r=>{let o=new M(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.cssVarsManager=new ze(this._options?.parentElement),this.resizeManager=yi(()=>({player:this.player,cssVarsManager:this.cssVarsManager,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 M(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),(e.actionType==="setNextBranch"||!this._options.endChapterHistoryFix)&&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=At(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(Cn()).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(vn({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 l=e*1e3;r=!!t.find(({range:[d,y],subjects:C})=>d<l&&l<y&&C.some(u=>!u.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(),a=this.factories.get(r)?.(i,this.rootElement,this.cssVarsManager,{isTouch:this._options?.isTouch??!1,features:{controlsExpectTimeBlinkAnimation:this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation,controlsTapPlace:this._options.animationsFeatureToggles?.controlsTapPlace,controlsFillAnimation:this._options.animationsFeatureToggles?.controlsFillAnimation}});if(a&&this.selectBranches&&this.interactiveEvents&&this.player){let s=new Ze({player:this.player,container:a,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,disableTextControlContainerVisibilityEvents:this.options.disableTextControlContainerVisibilityEvents??!1,features:{controlsHideAnimation:this._options.animationsFeatureToggles?.controlsHideAnimation,enableAvPlayerSupport:this._options.enableAvPlayerSupport}});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&&D(i)&&Oe(i))??!1,o=this.manifestController.manifest?.metadata.initChapterId===e,a=this.historyController.state.history$.getValue();if(o||r&&t){this.historyController.updateHistory([e]);return}a.at(-1)!==e&&this.historyController.updateHistory([...a,e])}handleFakeRemoval(e,t){let{interactiveRanges$:i}=this.state,o=i.getValue().map(a=>{let s=a.subjects.some(h=>h.id===e),l=a.subjects.map(h=>t&&s||h.id===e?{...h,isRemoved:!0}:h);return{...a,subjects:l}});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._options.endChapterHistoryFix&&this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1),this.clearNoInteractionTimeout())}toggleBlinkAnimation(e){if(!this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation)return;let t=(i,r)=>{i.toggleBlinkAnimation(r)};$e({...e,gameControllers:this.gameControllers,execFn:be(St(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?$e({...e,gameControllers:this.gameControllers,execFn:be(St(t),!1)}):$e({...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=fi(this.player,this._options.interactiveTimeOpenUri),this.selectBranches=Si({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&&gn.browser.isSafari&&await ki(35);let r=!i&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:o,media:a,graph:s}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!o||!a)&&(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.state.isInteractiveTime$.next(!1),this.state.isInteractiveExpectation$.next(!1),this.lastFrame?.setCurrentChapter(o),this.events.chapterChanged$.next({chapter:o,manifestVideo:a}),this.globalEventEmitter.emit(I.chapterChanged,{chapter:o,media:a,graph:s}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new Pi(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 Pi(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===x.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&&Me(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 di(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 In={Container:J,createChoiceContainer:Ue,createAreaControl:Ne,createButtonControl:De,classnamesPrefix:Nt};var Na={version:Lt};export{ar as ContainerTypes,Pe as ControlTypes,M as CustomError,I as EVENT_NAMES,x as EventActionTypes,lr as EventTypes,et as Interactives,ne as ManifestController,Na as SDKInfo,Rt as chapterIdsToVKVideoIds,Ct as compareVersions,er as containerTypes,tr as controlTypes,nr as eventActionTypes,ir as eventTypes,un as getChapterIdByVkVideoId,wi as getVKVideoIdByMedia,mn as getVideoRawIdByMedia,fe as graphEventTypes,Oe as hasEndTemplate,R as interactivesEventTypes,Jn as isAreaControl,Yn as isButtonControl,D as isLastChapter,ie as isOneTextCtrlContainer,Me as isSupportedManifest,Ve as isTextControl,dn as isVKVariantItem,Wt as isValidManifest,Gt as migrateManifestToLatestVersion,In as utils,Ri as vkVideoIdsToChapterIds};
285
+ `,Nn=e=>{let t=document.createElement(`style`);t.textContent=Mn,e.prepend(t)};import{clientChecker as Pn}from"@vkontakte/videoplayer-core/evergreen";var Fn=Object.freeze({lang:ut.RU,loaders:{},graph:!1,initSeamless:!1,lastFrame:!1,permanentTextControls:!0,interactiveTimeOpenUri:!1,config:{historyMaxLength:100,noInteractionEventTimeout:3e4},isTouch:!1,disableTextControlContainerVisibilityEvents:!1,animationsFeatureToggles:{areaControlShadow:!1,controlsExpectTimeBlinkAnimation:!1,controlsTapPlace:!1,controlsFillAnimation:!1,controlsHideAnimation:!1},enableAvPlayerSupport:!1});function In(){let e=document.createElement(`div`);return e.classList.add(`interactive-chapter`),e}class Ln{playerSubscriptions=new W;subscriptions=new W;globalEventEmitter=new Ct;animation=new wt;seekToInteractiveController=new St;endedRanges=new Set;gameControllers=[];rootElement=In();factories=new Map([[`choice`,st]]);isFirstChapterFetched=!1;_options;manifestController;resizeManager;cssVarsManager;historyController;player=null;interactiveEvents=null;selectBranches=null;seamlessController=null;seamlessControllerSubs=new W;graph=null;lastFrame=null;noInteractionTimeout;blinkAnimationRef=null;appState=0;state={prevChapter$:new G(null),isInitialChapter$:new G(!1),isFirstChapter$:new G(!0),isEndChapter$:new G(!1),isInteractiveExpectation$:new G(!1),isReplay$:new G(!1),calledByInteractive$:new G(!1),lastChapterChangeWasInitiatedByInteractive$:new G(!1),disabledControls$:new G(!1),interactiveRanges$:new G([]),isInteractiveTime$:new G(!1),statistics$:new G(null),isSeekable$:new G(!1)};events={noInteraction$:new U,graphVisibilityChanged$:new U,watchAgainIsClicked$:new U,chapterChanged$:new U,playerChanged$:new U,error$:new U,eachTick$:new U,manifestChanged$:new U,interactiveRangeEnded$:new U,interactiveContainerRemoved$:new U,interactiveContainerFakeRemoved$:new U,interactiveActionExecution$:new U,interactiveActionChoice$:new U,interactiveVisibilityChanged$:new U};constructor(e){if(this._options={...Fn,...e,config:{...Fn.config,...e.config}},this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation){this.blinkAnimationRef=new Be,this.blinkAnimationRef.create();let e=this.blinkAnimationRef.element;e&&this.rootElement.append(e)}this._options.parentElement.append(this.rootElement),this.historyController=new On({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 An({parentElement:this._options.parentElement,onError:e=>{let t=new s(1,6,e);this.emitErrorEvent(t)}})),Nn(this._options.parentElement),this.subscriptions.add(pt(this.rootElement,`mousedown`).subscribe(e=>e.stopPropagation())).add(pt(this.rootElement,`mouseup`).subscribe(e=>e.stopPropagation())),this.manifestController=new zt(this._options.loaders,e=>{let t=new s(1,3,e);this.emitErrorEvent(t)});let t=[];this._options.lastFrame&&t.push(()=>{this.lastFrame?.updateCanvasDimensions(!0)}),t.push(()=>{let e=this.state.isInteractiveTime$.getValue();for(let t of this.gameControllers)t.onResize(e)}),this.cssVarsManager=new Tt(this._options?.parentElement),this.resizeManager=ln(()=>({player:this.player,cssVarsManager:this.cssVarsManager,parentElement:this._options.parentElement,fns:t})),this._options.graph&&(this.graph=new yt({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:e=>{this.setChapter({chapterId:e}),this.globalEventEmitter.emit(Y.graph,{type:Yt.watchAgainClicked,chapterId:e}),this.events.watchAgainIsClicked$.next(e)},onError:e=>{let t=new s(1,2,{message:e});this.emitErrorEvent(t)}})),this.initSubscriptions()}emitErrorEvent=e=>{this.events.error$.next(e),this.globalEventEmitter.emit(Y.errors,e)};clearHistoryIfEnded=()=>{let e=this.player?.info.isEnded$.getValue(),t=this.state.isInteractiveExpectation$.getValue(),{chapter:n}=this.getCurrentChapter();e&&n&&M(n)&&!t&&this.historyController.updateHistory([]),window.removeEventListener(`beforeunload`,this.clearHistoryIfEnded)};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),(e.actionType===`setNextBranch`||!this._options.endChapterHistoryFix)&&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:n})=>{e!==`action-choice`||t===`chapter`||`invokeImmediately`in n&&n.invokeImmediately||this.destroyGameControllers({removeTextControls:!1,withTransition:this._options.animationsFeatureToggles?.controlsHideAnimation})}))}async initSeamless(){this.seamlessController=Jt(this),this.seamlessControllerSubs.add(this.seamlessController.activePlayerChanged.subscribe(this.handleSeamlessPlayerChanged)),await this.seamlessController.init()}handleSeamlessPlayerChanged=e=>{if(!e)return;let{statistics:t,...n}=e;if(t){let{statSubscription:e,oneStat:n}=t;e.add(n.attachToInteractive(this.getStatEvents())),this.state.statistics$.next(t)}this.state.isReplay$.getValue()&&this.state.isReplay$.next(!1),this.events.playerChanged$.next(n),this.globalEventEmitter.emit(Y.playerChanged,n)};onPlaybackStarted=()=>{this.resizeManager?.calc(),this.animation.requestAnimation()};handlePositionChange(e){(!this.graph||this.graph.isHidden)&&this.checkIfSeekable();let t=e*1e3,n=this.getInteractiveRanges().reverse().find(({range:e})=>t>=e[1]);if(n){let e=n.range.join(`-`);this.endedRanges.has(e)||(this.endedRanges.add(e),this.globalEventEmitter.emit(Y.interactives,{type:X.rangeEnded,payload:n,visibility:!0}),this.events.interactiveRangeEnded$.next({type:`range-ended`,payload:n}))}}registerVideoEvents(){this.player&&(window.removeEventListener(`beforeunload`,this.clearHistoryIfEnded),this.playerSubscriptions.unsubscribe(),window.addEventListener(`beforeunload`,this.clearHistoryIfEnded),this.playerSubscriptions.add(this.player.events.started$.pipe(ft()).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(lt({position:this.player.info.position$,interactiveRanges:this.state.interactiveRanges$,isInteractiveExpectation:this.state.isInteractiveExpectation$}).subscribe(({position:e,interactiveRanges:t,isInteractiveExpectation:n})=>{let r;if(n)r=!0;else{let n=e*1e3;r=!!t.find(({range:[e,t],subjects:r})=>e<n&&n<t&&r.some(e=>!e.isRemoved)&&r.length)}r!==this.state.isInteractiveTime$.getValue()&&this.state.isInteractiveTime$.next(r);let i=!!this.noInteractionTimeout,a=this.player?.info.playbackState$.getValue()===`playing`||n;r&&!i&&a?this.noInteractionTimeout=window.setTimeout(()=>{this.events.noInteraction$.next()},this._options.config.noInteractionEventTimeout):i&&!a&&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)))}destroyGameControllers=({removeTextControls:e=!0,withTransition:t=!1}={})=>{for(let n of this.gameControllers)!e&&n.isPermanentText||(this.animation.removeFn(n.whilePlaying),n.destroy(t))};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(e=>e.container.container).filter(e=>!P(e.controls))),this._options.lastFrame&&this.animation.addFn(()=>{this.player&&this.lastFrame?.onEachTick(this.player.info.position$.getValue()*1e3)},!0),this.state.interactiveRanges$.next(this.getInteractiveRanges()),this.appState=2)}getGameControllers(e){let t=[];return e.containers.forEach(n=>{let r=n.type.trim().toLowerCase(),i=this.factories.get(r)?.(n,this.rootElement,this.cssVarsManager,{isTouch:this._options?.isTouch??!1,features:{controlsExpectTimeBlinkAnimation:this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation,controlsTapPlace:this._options.animationsFeatureToggles?.controlsTapPlace,controlsFillAnimation:this._options.animationsFeatureToggles?.controlsFillAnimation}});if(i&&this.selectBranches&&this.interactiveEvents&&this.player){let r=new Qt({player:this.player,container:i,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,getContainerEventState:()=>Re(n,this.gameControllers),permanentTextControls:this._options.permanentTextControls,interactiveTimeOpenUri:this._options.interactiveTimeOpenUri,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(n.id)},onError:this.emitErrorEvent,disableTextControlContainerVisibilityEvents:this.options.disableTextControlContainerVisibilityEvents??!1,features:{controlsHideAnimation:this._options.animationsFeatureToggles?.controlsHideAnimation,enableAvPlayerSupport:this._options.enableAvPlayerSupport}});this.animation.addFn(r.whilePlaying,!0),t.push(r)}}),t}checkIfSeekable(){if(this.state.isInteractiveExpectation$.getValue()){this.state.isSeekable$.next(!1);return}let e=this.state.isSeekable$.getValue(),t=!!this.seekToInteractiveController.getNextInteractiveTime();(t&&!e||!t&&e)&&this.state.isSeekable$.next(!e)}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(),n=this.state.prevChapter$.getValue(),r=(n&&M(n)&&Ae(n))??!1,i=this.manifestController.manifest?.metadata.initChapterId===e,a=this.historyController.state.history$.getValue();if(i||r&&t){this.historyController.updateHistory([e]);return}a.at(-1)!==e&&this.historyController.updateHistory([...a,e])}completeInteractiveRange=e=>{let{interactiveRanges$:t}=this.state,n=t.getValue().map(t=>({...t,subjects:t.subjects.filter(t=>t.id!==e)}));t.next(n)};handleFakeRemoval(e,t){let{interactiveRanges$:n}=this.state,r=n.getValue().map(n=>{let r=n.subjects.some(t=>t.id===e),i=n.subjects.map(n=>t&&r||n.id===e?{...n,isRemoved:!0}:n);return{...n,subjects:i}});n.next(r)}clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&=(clearTimeout(this.noInteractionTimeout),void 0)};reset(){this.appState===2&&(this.destroyGameControllers(),this.gameControllers=[],this.animation.release(),this.interactiveEvents?.release(),this.appState=1,this.state.isSeekable$.next(!1),this._options.endChapterHistoryFix&&this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1),this.clearNoInteractionTimeout())}toggleBlinkAnimation(e){if(!this._options.animationsFeatureToggles?.controlsExpectTimeBlinkAnimation)return;let t=(e,t)=>{e.toggleBlinkAnimation(t)};Ie({...e,gameControllers:this.gameControllers,execFn:Z(Zt(t),e.isExpect)}),e.isExpect&&this.blinkAnimationRef?.restart()}updateControlsShadowStyles(e){if(!this._options.animationsFeatureToggles?.areaControlShadow)return;let t=(e,t)=>{e.updateControlsShadowStyles(t)};e.isExpect?Ie({...e,gameControllers:this.gameControllers,execFn:Z(Zt(t),!1)}):Ie({...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(Y.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=rn(this.player,this._options.interactiveTimeOpenUri),this.selectBranches=yn({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:n=!1}={}){this.reset(),this.lastFrame&&this.isFirstChapterFetched&&(this.lastFrame.draw(),this.lastFrame.show()),this.lastFrame&&Pn.browser.isSafari&&await jn(35);let r=!n&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:i,media:a,graph:o}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!i||!a)&&(t&&this.pushChapterToHistory(i.id),this.state.isInitialChapter$.next(this.manifestController.isInitialChapter()),this.state.isEndChapter$.next(this.manifestController.isEndChapter()),this.graph&&this.graph.handleChapterChange(i),this.state.isInteractiveTime$.next(!1),this.state.isInteractiveExpectation$.next(!1),this.lastFrame?.setCurrentChapter(i),this.events.chapterChanged$.next({chapter:i,manifestVideo:a}),this.globalEventEmitter.emit(Y.chapterChanged,{chapter:i,media:a,graph:o}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new dt(e=>{this.subscriptions.add(this.events.graphVisibilityChanged$.subscribe(t=>{e.next(t?K.GRAPH_SHOW:K.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{e.next(K.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:n,subjectType:r})=>{t!==`action-choice`||n!==`control`||(r===`Button`&&e.next(K.NEXT_BUTTON),r===`Area`&&e.next(K.NEXT_AREA))}))}),nextMovie$:new dt(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(Y.graph,{type:Yt.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(e=>e.actionType===j.setNextBranch)}allControlsAreRemoved(e=!0){return!this.gameControllers.some(t=>{let n=e&&this._options.animationsFeatureToggles?.controlsHideAnimation?t.container.willRemoved:!0;return!t.container.isRemoved||!n})}isEndedExpectation(){return!this.player||!this.gameControllers?!1:this.player.info.position$.getValue()===this.player.info.duration$.getValue()&&this.gameControllers.some(e=>{let t=e.container.container;return!e.container.isRemoved&&!e.container.willRemoved&&t.endTime===null&&N(t.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&ge(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 $t(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 Rn={Container:l,createChoiceContainer:st,createAreaControl:He,createButtonControl:rt,classnamesPrefix:ee},zn={version:e};export{Dn as vkVideoIdsToChapterIds,Rn as utils,ye as migrateManifestToLatestVersion,xe as isValidManifest,wn as isVKVariantItem,Se as isTextControl,ge as isSupportedManifest,P as isOneTextCtrlContainer,M as isLastChapter,Ce as isButtonControl,we as isAreaControl,X as interactivesEventTypes,Ae as hasEndTemplate,Yt as graphEventTypes,Cn as getVideoRawIdByMedia,Tn as getVKVideoIdByMedia,En as getChapterIdByVkVideoId,De as eventTypes,Oe as eventActionTypes,Ee as controlTypes,Te as containerTypes,At as compareVersions,Sn as chapterIdsToVKVideoIds,zn as SDKInfo,zt as ManifestController,Ln as Interactives,ve as EventTypes,j as EventActionTypes,Y as EVENT_NAMES,s as CustomError,A as ControlTypes,_e as ContainerTypes};
286
+ //# sourceMappingURL=evergreen.esm.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.61",
3
+ "version": "1.0.62-dev.04ce2cd1.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.155",
60
- "@vkontakte/videoplayer-shared": "1.0.84",
61
- "@vkontakte/videoplayer-statistics": "1.0.101"
59
+ "@vkontakte/videoplayer-core": "2.0.156-dev.04ce2cd1.0",
60
+ "@vkontakte/videoplayer-shared": "1.0.85-dev.04ce2cd1.0",
61
+ "@vkontakte/videoplayer-statistics": "1.0.102-dev.04ce2cd1.0"
62
62
  }
63
63
  }
package/types/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- export { EVENT_NAMES, HistoryApi, Interactives, utils, graphEventTypes, interactivesEventTypes, isLastChapter, hasEndTemplate, isOneTextCtrlContainer, } from './modules/Interactives';
2
- export type { IInteractiveOptions, InteractiveRange, InteractiveProjectInfo, PlayerChangedData, VideoInfo } from './modules/Interactives';
3
- export { ManifestController } from './modules/ManifestController';
4
- export * from './manifest';
5
- export { compareVersions } from './utils/compareVersions';
6
- export { CustomError } from './utils/Error';
7
- export * from './utils/chapterHelpers';
1
+ export type { HistoryApi } from "./modules/Interactives";
2
+ export { EVENT_NAMES, Interactives, utils, graphEventTypes, interactivesEventTypes, isLastChapter, hasEndTemplate, isOneTextCtrlContainer } from "./modules/Interactives";
3
+ export type { IInteractiveOptions, InteractiveRange, InteractiveProjectInfo, PlayerChangedData, VideoInfo } from "./modules/Interactives";
4
+ export { ManifestController } from "./modules/ManifestController";
5
+ export * from "./manifest";
6
+ export { compareVersions } from "./utils/compareVersions";
7
+ export { CustomError } from "./utils/Error";
8
+ export * from "./utils/chapterHelpers";
8
9
  export declare const SDKInfo: {
9
- version: string;
10
+ version: string;
10
11
  };
@@ -1,3 +1,3 @@
1
- export type { ChapterContainer, ChapterContainer as Container, Chapter, Control, Manifest, ManifestVideo, ManifestVideoVariant, Media, Metadata, VideoId, CustomManifestVideoVariant, Extension, AnyManifest, AnyControl, GraphEditChapter, GraphViewChapter, ChapterBranch, Standard, ControlLayoutParams, ControlEvent, ContainerEvent, ChapterEvent, } from '@interactiveplatform/movika-manifest';
2
- export { isSupportedManifest, ContainerTypes, ControlTypes, EventActionTypes, EventTypes, migrateManifestToLatestVersion, compareVersions, } from '@interactiveplatform/movika-manifest';
3
- export * from './utils';
1
+ export type { ChapterContainer, ChapterContainer as Container, Chapter, Control, Manifest, ManifestVideo, ManifestVideoVariant, Media, Metadata, VideoId, CustomManifestVideoVariant, Extension, AnyManifest, AnyControl, GraphEditChapter, GraphViewChapter, ChapterBranch, Standard, ControlLayoutParams, ControlEvent, ContainerEvent, ChapterEvent } from "@interactiveplatform/movika-manifest";
2
+ export { isSupportedManifest, ContainerTypes, ControlTypes, EventActionTypes, EventTypes, migrateManifestToLatestVersion, compareVersions } from "@interactiveplatform/movika-manifest";
3
+ export * from "./utils";