@vkontakte/videoplayer-interactive 1.0.19-dev.c3a364e7.0 → 1.0.19-dev.d432d6cd.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 (65) hide show
  1. package/es2015.cjs.js +6 -6
  2. package/es2015.esm.js +6 -6
  3. package/es2018.cjs.js +6 -6
  4. package/es2018.esm.js +6 -6
  5. package/esnext.cjs.js +6 -6
  6. package/esnext.esm.js +6 -6
  7. package/evergreen.esm.js +6 -6
  8. package/package.json +5 -5
  9. package/types/index.d.ts +3 -4
  10. package/types/manifest/index.d.ts +3 -0
  11. package/types/manifest/utils.d.ts +11 -0
  12. package/types/modules/Graph/Graph.d.ts +16 -12
  13. package/types/modules/Interactives/Interactives.d.ts +99 -83
  14. package/types/modules/Interactives/Layout.d.ts +11 -7
  15. package/types/modules/Interactives/controls/AreaControl.d.ts +2 -11
  16. package/types/modules/Interactives/controls/ButtonControl.d.ts +2 -11
  17. package/types/modules/Interactives/controls/Control.d.ts +20 -12
  18. package/types/modules/Interactives/controls/TextControl.d.ts +2 -11
  19. package/types/modules/Interactives/controls/index.d.ts +4 -3
  20. package/types/modules/Interactives/controls/types.d.ts +24 -0
  21. package/types/modules/Interactives/index.d.ts +4 -4
  22. package/types/modules/Interactives/types.d.ts +38 -7
  23. package/types/modules/Interactives/utils/GameController.d.ts +35 -16
  24. package/types/modules/Interactives/utils/GroupsStack.d.ts +31 -21
  25. package/types/modules/Interactives/utils/HistoryController.d.ts +8 -8
  26. package/types/modules/Interactives/utils/InteractiveEvents.d.ts +16 -10
  27. package/types/modules/Interactives/utils/ResizeManager.d.ts +8 -1
  28. package/types/modules/Interactives/utils/SelectBranches.d.ts +15 -51
  29. package/types/modules/Interactives/utils/SelectBranches.types.d.ts +73 -0
  30. package/types/modules/Interactives/utils/events.d.ts +8 -0
  31. package/types/modules/Interactives/utils/fallbackStrategies.d.ts +23 -6
  32. package/types/modules/Interactives/utils/gameUtils.d.ts +28 -26
  33. package/types/modules/Interactives/utils/getInteractiveRanges.d.ts +4 -4
  34. package/types/modules/Interactives/utils/renderingUtils.d.ts +64 -59
  35. package/types/modules/Loaders/vkVideoLoader/types.d.ts +2 -2
  36. package/types/modules/Loaders/vkVideoLoader/utils.d.ts +1 -1
  37. package/types/modules/ManifestController/Loadable.d.ts +4 -7
  38. package/types/modules/ManifestController/ManifestController.d.ts +11 -12
  39. package/types/modules/ManifestController/utils.d.ts +6 -6
  40. package/types/modules/SeamlessController/SeamlessController.d.ts +10 -12
  41. package/types/modules/SeamlessController/utils.d.ts +2 -2
  42. package/types/modules/SeekToInteractiveController/SeekToInteractiveController.d.ts +2 -2
  43. package/types/utils/EventManager.d.ts +3 -3
  44. package/types/utils/LastFrame.d.ts +1 -1
  45. package/types/utils/Raf.d.ts +1 -1
  46. package/types/utils/chapterHelpers.d.ts +1 -1
  47. package/types/utils/extractVkMovieId.d.ts +2 -2
  48. package/types/modules/Interactives/controls/constants.d.ts +0 -5
  49. package/types/movika.core/manifest/index.d.ts +0 -19
  50. package/types/movika.core/manifest/manifest_3_2/chapter.d.ts +0 -62
  51. package/types/movika.core/manifest/manifest_3_2/control.d.ts +0 -67
  52. package/types/movika.core/manifest/manifest_3_2/manifest.d.ts +0 -50
  53. package/types/movika.core/manifest/manifest_3_2/template.d.ts +0 -34
  54. package/types/movika.core/manifest/manifest_3_3/chapter.d.ts +0 -70
  55. package/types/movika.core/manifest/manifest_3_3/control.d.ts +0 -66
  56. package/types/movika.core/manifest/manifest_3_3/graph.d.ts +0 -73
  57. package/types/movika.core/manifest/manifest_3_3/manifest.d.ts +0 -52
  58. package/types/movika.core/manifest/manifest_3_3/template.d.ts +0 -34
  59. package/types/movika.core/manifest/migrations/index.d.ts +0 -1
  60. package/types/movika.core/manifest/migrations/migrateManifestToLatestVersion.d.ts +0 -1
  61. package/types/movika.core/manifest/migrations/migrate_from_3_0_to_3_1.d.ts +0 -21
  62. package/types/movika.core/manifest/migrations/migrate_from_3_1_to_3_2.d.ts +0 -2
  63. package/types/movika.core/manifest/migrations/migrate_from_3_2_to_3_3.d.ts +0 -8
  64. package/types/movika.core/manifest/types.d.ts +0 -29
  65. package/types/movika.core/manifest/utils.d.ts +0 -5
package/evergreen.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.19-dev.c3a364e7.0
3
- * Tue, 17 Sep 2024 11:13:16 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.19-dev.d432d6cd.0
3
+ * Tue, 01 Oct 2024 14:51:14 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-19/doc/
5
5
  */
6
- var pe="1.0.19-dev.c3a364e7.0";function Ht(i,t=1){let e="0",n="0",r="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+r},${t})`}var M="SDK_NAME",Je="SDK_NAME-controls-container",pt=()=>document.querySelector(`.${Je}`),me=.4,L={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},de={top:"flex-start",bottom:"flex-end",center:"center"},ue={start:"flex-start",end:"flex-end",center:"center"},fe={start:"left",end:"right",center:"center"},dt=({target:i,props:t})=>{i.style.alignItems=de[t?.text?.gravityVertical]??de.center,i.style.justifyContent=ue[t?.text?.gravityHorizontal]??ue.center,i.style.textAlign=fe[t?.text?.alignment]??fe.start},ut=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.color=t?.text?.color??e.textColor,i.style.fontSize=`calc(${n.height} * ${t?.text?.size??e.textSize})`,i.textContent=t?.text?.value??e.textContent},ft=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Ht(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},mt=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Ht(t?.shape?.border?.color??e.borderColor,t?.shape?.border?.alpha??e.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${t?.shape?.roundCorners??e.roundCorners})`},W=({target:i,layoutParams:t,fallback:e})=>{i.style.transform=`rotate(${-t.angle}rad)`};var Dt="int",Q={AREA:`${Dt}_area`,TEXT:`${Dt}_text`,BUTTON:`${Dt}_bttn`};var P=class{constructor(t){this.control=t}createView(t){let e=document.createElement("div");e.classList.add(`${M}-control-container-${this.control.id}`),t(e,this.control.layoutParams);let n=(this.control.layoutParams.innerSizesDependOn??L.innerSizesDependOn)==="self"?{height:e.style.height,width:e.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:e,dependsOn:n}}setEvents(t,e){t&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":t.addEventListener("click",s=>{s.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break;default:break}})}getElement(){return document.querySelector(`.${M}-control-container-${this.control.id}`)}};var yt=i=>{if(i.type.trim().toLowerCase()==="area")return new Gt(i)},Gt=class extends P{constructor(t){super(t)}createView({parent:t,layoutFn:e}){let{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");return s.classList.add(`${M}-${this.control.id}`),s.setAttribute("data-testid",Q.AREA),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",ft({target:s,props:this.control.props,fallback:{...L,backgroundColor:"transparent"}}),mt({target:s,props:this.control.props,fallback:{...L,borderAlpha:0},dependsOn:n}),W({target:s,layoutParams:this.control.layoutParams,fallback:L}),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}};var gt=()=>{let i=document.createElement("span");return i.style.display="inline-block",i.style.whiteSpace="pre",i.style.overflow="hidden",i.style.textOverflow="ellipsis",i.style.maxWidth="100%",i.style.maxHeight="100%",i};var vt=i=>{if(i.type.trim().toLowerCase()==="button")return new zt(i)},zt=class extends P{constructor(t){super(t)}createView({parent:t,layoutFn:e}){let{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");s.type="button",s.classList.add(`${M}-${this.control.id}`),s.setAttribute("data-testid",Q.BUTTON),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.style.fontFamily="inherit";let o=gt();return W({target:s,layoutParams:this.control.layoutParams,fallback:L}),ft({target:s,props:this.control.props,fallback:L}),mt({target:s,props:this.control.props,fallback:L,dependsOn:n}),dt({target:s,props:this.control.props}),ut({target:o,props:this.control.props,fallback:L,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}};var ye=i=>{if(i.type.trim().toLowerCase()==="text")return new Ut(i)},Ut=class extends P{constructor(t){super(t)}createView({parent:t,layoutFn:e}){let{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("div");s.classList.add(`${M}-${this.control.id}`),s.setAttribute("data-testid",Q.TEXT),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.fontFamily="inherit";let o=gt();return W({target:s,layoutParams:this.control.layoutParams,fallback:L}),dt({target:s,props:this.control.props}),ut({target:o,props:this.control.props,fallback:L,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){}enable(){}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}};var Wt=class{constructor(t){this.layout=t}},ge=i=>{if(i.type.trim().toLowerCase()==="relative")return new X(i)},X=class extends Wt{constructor(t){super(t)}setContainerLayout(t){t.style.position="relative"}setControlLayout(t,e){t.style.position="absolute",t.style.width=`calc(var(--interactive-content-width) * ${e.width})`,t.style.height=`calc(var(--interactive-content-height) * ${e.height})`,t.style.left=`calc(var(--interactive-content-width) * ${e.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,t.style.top=`calc(var(--interactive-content-height) * ${e.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}};var K=class{constructor(t){this.container=t,this.factories=new Map,this.#a()}addControlFactory(t,e){this.factories.set(t.trim().toLowerCase(),e),this.#a()}removeControlFactory(t){this.factories.delete(t.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#r()}#r(){return this.container.controls?.reduce((t,e)=>{let n=e.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...t,r(e)]:[...t]},[])}};var bt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new Qt(i,t)},Qt=class extends K{constructor(t,e){super(t),this.rootElement=e??pt(),this.layout=new X(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",vt),this.addControlFactory("text",ye),this.addControlFactory("area",yt)}createView(t){let e=document.createElement("div");return e.classList.add(`${M}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{let r=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(r,t)}),this.rootElement.append(e),this.isRemoved=!1,e}hide(){let t=this.getElement();t&&(t.style.visibility="hidden")}show(){let t=this.getElement();t&&(t.style.visibility="visible")}enable(){let t=this.getElement();t&&(this.controls.forEach(e=>e.enable()),t.style.opacity=1,this.isDisabled=!1)}disable(){let t=this.getElement();t&&(this.controls.forEach(e=>e.disable()),t.style.opacity=me,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${M}-${this.container.id}`)}};import{Subject as ki,ValueSubject as N,Observable as Ze,once as Ni,Subscription as Oi,clientChecker as ji,combine as $i}from"@vkontakte/videoplayer-shared";import{InteractiveInterfaceClick as ct}from"@vkontakte/videoplayer-statistics";import{loadVKLangPack as ti}from"@vkontakte/videoplayer-shared";function Ct(i,t){let e;return(...n)=>{clearTimeout(e),e=setTimeout(()=>i(...n),t)}}var D=(i,t)=>Object.prototype.toString.call(i)===`[object ${t}]`,Y=i=>D(i,"Object"),Et=i=>D(i,"String"),It=i=>D(i,"Array"),xt=i=>D(i,"Number"),ve=i=>D(i,"Function");var Kt=i=>xt(i)&&!isNaN(i);var G=i=>Y(i)&&Object.keys(i).length===0,qt=i=>It(i)&&!i.length;var J=(i,t)=>Et(i)&&(t?i.trim():i).length;var be="video_interactive",Ce="videoint";var ei=250,tt=class{constructor(t){this.onResize=t=>{this.isReady&&(!t[0].contentRect.width||!t[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor?.zoomTo(this.getNextPoint()),this.ngEditorSize={width:t[0].contentRect.width,height:t[0].contentRect.height}))};this.handleChapterChange=t=>{if(this.isReady){if(this.isHidden||this.hide(),!t?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(t.id),this.ngEditor?.selectChapter(t.id),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=t.id,this.lastZoomInfo=null}};this.handleManifestChange=async(t,e=[])=>{if(!xt(t.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=null,!this.ngEditor){let n;try{n=await ti(this.lang,be,Ce)}catch{console.log("Unable to load graph language pack")}let{GraphEditor:r}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new r(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:s,...o})=>{s==="openPreview"&&"chapterId"in o&&this.onOpenPreviewClick?.(o.chapterId)}),this.ngEditor.on("zoom",s=>{this.lastZoomInfo={...s}})}this.visitedChapterIds=new Set(e),t.metadata.id!==this.currentManifestId?(this.ngEditor.update(t),this.currentManifestId=t.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:r,visitedChapters:s=[]}){this.isReady=!1,this.isHidden=!0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=e,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=ii(t),this.resizeObserver=new ResizeObserver(Ct(this.onResize,ei)),this.resizeObserver.observe(this.graphWrapperElement)}getNextPoint(t=this.ngEditorSize){return!this.lastZoomInfo||!t?[0,0]:[(this.lastZoomInfo.x-t.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-t.height/2)/this.lastZoomInfo.value*-1]}setVisitedChapters(t){this.visitedChapterIds=new Set([...this.visitedChapterIds,...t]),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(t){this.ngEditor?.updateVideosInfo(t)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",!this.lastZoomInfo&&this.currentChapterId&&this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}};function ii(i){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",i.append(t),t}var et=class{constructor(){this._containers=[];this._player=null;this.setPlayer=t=>{this._player=t};this.setContainers=t=>{this._containers=t};this.deleteContainer=t=>{this._containers=this._containers.filter(e=>e.id!==t)};this.getNextInteractiveTime=(t=3e3)=>{if(!this._containers.length||this._player===null)return null;let e=-1,n=!1,r=Math.round(this._player.info.position$.getValue()*1e3);for(let s of this._containers){let o=s.startTime-t;if(o<=r&&(s.endTime&&r<=s.endTime||s.endTime===null)){n=!0;break}r<o&&(e=e===-1?o:Math.min(e,o))}return!n&&e!==-1?e:null}}};var B=(i="",t="")=>{let e=i.split("."),n=t.split("."),r=0;for(let s=0;s<Math.max(e.length,n.length)&&!r;s++)e[s]>n[s]?r=1:e[s]<n[s]?r=-1:r=0;return r};import{v4 as ni}from"uuid";var ri="3.1",Ee={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},si={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ie=i=>{let t=[];for(let e of i.chapters){let n,r=[];for(let{isDefault:a,...c}of e.branches)a&&(n=c.id),r.push(c);let s=[],o=[];for(let{fallbackStrategy:a,...c}of e.containers){let h=!!c.endTime,y=[si];switch(a){case"await":h?y=[]:s=[];break;case"default":{let g={type:"onSuspense",action:{type:Ee.default,args:{branchId:n,shouldOpenNow:!h,isDetachContainer:!0}}};h?y=[g]:s=[g];break}case"random":case"weightlessRandom":case"max":case"min":{let g={type:"onSuspense",action:{type:Ee[a],args:{}}};h?y=[g]:s=[g];break}}for(let g of c.controls)o.push({...c,controls:[{...g}],id:ni(),events:y})}t.push({...e,containers:o,events:s,branches:r})}return i.metadata.version=ri,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}};var ai="3.2",xe=i=>{if(!i.media){let{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:ai},media:t}}return i};var oi="3.3",ci=(i=[])=>({edit:{chapters:i},view:{}}),Te={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Se=i=>{let t=[],e=[];for(let n of i.chapters){let{id:r,x:s,y:o,...a}=n,c=a.containers.map(h=>({...h,controls:h.controls.map(({subtype:y,type:g,...E})=>({...E,type:y??g})),events:h.events?.length?h.events:[Te]}));t.push({id:r,...a,containers:c,events:a.events?.length?a.events:[Te]}),e.push({id:r,x:s,y:o})}return{...i,chapters:t,graph:ci(e),metadata:{...i.metadata,version:oi}}};var li=[{version:"3.0",migrate:Ie},{version:"3.1",migrate:xe},{version:"3.2",migrate:Se}],Zt=i=>li.reduce((t,e)=>B(t.metadata.version,e.version)?t:e.migrate(t),i);var Zn=Object.freeze({Choice:"Choice",TextInput:"TextInput"}),we=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),Xn=Object.freeze({onClick:"onClick",onSuspense:"onSuspense"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var _e={metadata:"Object",chapters:"Array"},hi="3.0.0",pi="3.3.0",Tt=i=>{let t=B(i,hi);return t===-1?!1:t===0?!0:B(i,pi)!==1},Ve=i=>{if(!Y(i))return!1;for(let t in _e)if(!i[t]||!D(i[t],_e[t]))return!1;return Tt(i.metadata.version)},St=i=>i.type===we.Text;var R=class{constructor(t,e,...n){this.severity=t;this.category=e;this.data=n}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var q=class{constructor(){this.listeners={}}addListener(t,e){return this.listeners[t]=this.listeners[t]||[],this.listeners[t].push(e),this}on(t,e){return this.addListener(t,e)}once(t,e){this.listeners[t]=this.listeners[t]||[];let n=()=>{e(),this.off(t,n)};return this.listeners[t].push(n),this}off(t,e){return this.removeListener(t,e)}reset(){this.listeners={}}removeListener(t,e){let n=this.listeners[t]||[];for(let r=n.length;r>0;r--)if(n[r]===e){n.splice(r,1);break}return this}emit(t,...e){let n=this.listeners[t];return n?(n.forEach(r=>{r(...e)}),!0):!1}listenerCount(t){return this.rawListeners(t).length}rawListeners(t){return this.listeners[t]||[]}};var wt=class{constructor(t){this.fns=[];this.addFn=(t,e=!1)=>{ve(t)&&(this.fns.push(t),e&&this.updateFn())};this.removeFn=(t,e=!1)=>{this.fns=this.fns.filter(n=>n!==t),e&&this.updateFn()};this.updateFn=()=>{this.fn=()=>{this.fns.forEach(t=>t()),this.raf&&this.forceRequestAnimation()}};this.forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};this.requestAnimation=()=>{this.raf||this.forceRequestAnimation()};this.cancelAnimation=()=>{this.raf&&(cancelAnimationFrame(this.raf),this.raf=void 0)};this.fn=t,this.addFn(t)}release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}};import{ValueSubject as vi}from"@vkontakte/videoplayer-shared";var _t=class{constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return di(...this.loaders[t])(e)}};function di(...i){return async function(e){let n=[...i];for(;n.length>0;)e=await n.shift()(e);return e}}function it(i,t,e){return i?{...i,[t]:i[t]?[e,...i[t]]:[e]}:{[t]:[e]}}function Vt({actions:i,errors:t,chapterId:e,...n}){if(e){let r=i.getManifest(),s=i.getChapter(r.chapters,e);if(s){let o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:t,result:{chapter:s,media:o,graph:a}}:{...n,errors:it(t,Vt.name,"Could not find media"),actions:i}}}return{...n,errors:it(t,Vt.name,"Could not find chapter"),actions:i}}var ui=async i=>{try{let t={},e;if(Et(i)){e=new URL(i).href;let r=await fetch(e);if(!r.ok)return{};t=await r.json()}else if(Y(i))t=i;else return{};if(!Ve(t))return{};let n=t.metadata.media;if(Et(n)&&!t.media)try{let r;e?r=new URL(n,e).href:(r=new URL(n).href,e=r);let s=await fetch(r);if(!s.ok)throw new Error;t.metadata.media=await s.json()}catch{return yi(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function Me(i){let{manifest:t,manifestURL:e}=await ui(i),n=Zt(t);return n.media=fi(n.media,e),delete n.metadata.media,n}function Mt(i,t){if(t)return i.find(e=>e.id===t)}function Xt(i,t){return i.edit?.chapters?i.edit.chapters.find(e=>e.id===t):i.view?.chapters?i.view.chapters.find(e=>e.id===t):void 0}function Yt(i,t){return i.videos.find(e=>e.id===t)}function fi(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{let r="url"in n?n.url:"",s=mi(r,t);return{...n,url:s||r}})}))}}function mi(i="",t){try{return new URL(i,t).href}catch{return""}}function yi(i){return B(i,"3.2.0")>=0}var x=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),Rt=i=>It(i)&&!qt(i),j=i=>i.order==="end",At=i=>It(i.containers)&&!qt(i.containers)&&j(i),Re=(i,t)=>{let e=i*1e3;return Rt(t.controls)&&e<(t.startTime??0)},Jt=(i,t)=>{let e=i*1e3;return Rt(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)};var z=i=>i.some(t=>t.action.type==="expect"),te=i=>i.find(t=>t.action.type==="expect"),gi=i=>i?.length===1,Lt=i=>gi(i)&&St(i[0]);var Ae=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),Le=(i,t)=>z(i.events)?!1:t.some(({container:e})=>e.container.id!==i.id&&z(e.container.events)&&e.container.endTime===i.endTime&&!e.isRemoved);var Z=class extends _t{constructor(e,n){super(e);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new vi(null);this.onError=n,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 n=await this.exec("manifestLoaders",{actions:{addErrorMessage:it},result:null,errors:null,source:e});return n.errors&&this.errorHandler(n.errors),this.manifest=await Me(n.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 n=await this.exec("chapterLoaders",Vt({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Xt,getChapter:Mt,getMedia:Yt,getByBranches:this.getByBranches.bind(this),addErrorMessage:it},result:null,errors:null,chapterId:e}));return n.errors&&this.errorHandler(n.errors),this.chapter=n.result.chapter,this.media=n.result.media,this.graph=n.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 n=Mt(this.manifest.chapters,e);if(n){let r=Yt(this.manifest.media,n.videoId),s=Xt(this.manifest.graph,n.id);if(r)return{chapter:n,media:r,graph:s}}return null}getBranches(e=this.chapter?.id){if(e===this.chapter?.id)return this.getByBranches(this.chapter?.branches);{let n=Mt(this.manifest?.chapters||[],e);return this.getByBranches(n?.branches)}}getByBranches(e=[]){return e.reduce((n,r)=>{let s=this.getByChapterId(r.chapterId);return s&&n.push(s),n},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter?.id===this.manifest?.metadata.initChapterId}isEndChapter(){return j(this.chapter)}};import{Player as bi}from"@vkontakte/videoplayer-core";import{Subscription as Ne,Tracer as Ci}from"@vkontakte/videoplayer-shared";var ke=i=>{let t=i.variants.find(e=>e.payload?.type==="vk");if(t&&"payload"in t){let[e,n]=t.payload.id.split("_");return[e,n]}return[]};var d={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},nt={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},C={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ee(){let i=new Map;function t({listId:s=Math.random().toString(),itemId:o=Math.random().toString(),...a}){let c=i.get(s),h={...a};return c?c[o]=h:i.set(s,{[o]:h}),{listId:s,itemId:o,...a}}function e(s){s.player.destroy(),s.container.remove(),s.subscription.unsubscribe(),s.statistics?.oneStat.destroy(),s.statistics?.statSubscription.unsubscribe()}function n(s,o){let a=i.get(s);if(!a)throw Error("Can't remove. Not find.");if(o){let c=a[o];c&&e(c),delete a[o],Object.keys(a).length||i.delete(s)}else{for(let c of Object.values(a))e(c);i.delete(s)}}function r(){for(let s of i)n(s[0])}return{createPlayer:t,removePlayer:n,map:i,removeAll:r}}function ie(i,t=[]){let e={},n,r=!t.length;for(let s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:s.url}});break;case"dash":(r||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break;default:break}return{sources:e,thumbUrl:n,title:i.title??""}}var rt=(i,t)=>{let e=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();e!==t&&n.includes(t)&&(i.setQuality(t),i.setAutoQuality(!1))};var kt={activePlayerChanged:"sc-active-player-changed",playerCreated:"sc-player-created"},Ei=2;function ne(i){let t=ee(),e=new q,n={},r=null,s=!1,o;i&&a(i);function a(T){r=T}function c(T,S,p){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let u=(t.map.get(T)??{})[S];if(u){n={chapterId:p,listId:T,itemId:S,...u};let m=n.player;n.subscription.add(m.info.currentQuality$.subscribe(f=>{let _=m.info.position$.getValue(),w=m.info.isAutoQualityEnabled$.getValue();if(!(!f||!_||w))for(let V of t.map)Object.values(V[1]).forEach(({player:b})=>{rt(b,f)})})).add(m.events.started$.subscribe(()=>{h(S)})),u.container.remove(),r.setPlayer(u.player),s||(r.init(),s=!0),e.emit(kt.activePlayerChanged,{player:n.player,config:n.config,statistics:n.statistics});return}throw Error("Can't set. Not find.")}async function h(T){if(!r)throw Error("need to set interactive controller");if(G(n)||T!==n.itemId)return;let S=r.getChapterBranches(),p=new Set;for(let l of S)p.has(l.media.id)||(await g({media:l.media,chapterId:l.chapter.id,setAsActive:!1,title:l.chapter.label}),p.add(l.media.id))}async function y({chapter:{id:T},media:S}){if(G(n))return;let p=n.player.info.muted$.getValue(),l=n.player.info.currentQuality$.getValue(),u=n.player.info.isAutoQualityEnabled$.getValue(),m=n.player.info.volume$.getValue(),f=n.player.info.currentPlaybackRate$.getValue(),_=!u,w=!1;for(let V of t.map)if(V[0]===S.id){let b=Object.keys(V[1]);for(let A of b)A===n.itemId?(b.length<Ei||(w=!0),t.removePlayer(V[0],A)):(w=!0,c(V[0],A,T),_?rt(n.player,l):n.player.setAutoQuality(!0),n.player.setVolume(m),n.player.setMuted(p),n.player.setPlaybackRate(f))}else t.removePlayer(V[0]);w||(await g({media:S,chapterId:T,setAsActive:!0,playbackRate:f}),_?rt(n.player,l):n.player.setAutoQuality(!0),n.player.setVolume(m),n.player.setMuted(p))}async function g({media:T,chapterId:S,prefetch:p=!0,setAsActive:l=!0,autoplay:u=!1,preferredExt:m,title:f,playbackRate:_}){let w=Math.random().toString(),V=document.createElement("div");o.append(V);let b;if(r?.options?.vkVideoLoader){let ht=ke(T);ht.length&&(b=await r.options.vkVideoLoader(...ht))}let A=r?.options?.coreConfig||{},U={...A,configName:[...A.configName??[],"interactive"]},F={container:V,...b?.videos?.[0]||{sources:ie(T,m).sources},title:f,failoverHosts:b?.failoverHosts||[]},O=new bi(U,Ci.createRootTracer());O.initVideo(F);let lt=null;if(r?.options.createOneStat){let ht=b.videos[0],le=r.options.createOneStat(ht),he=new Ne;he.add(le.attachTo(O)),lt={oneStat:le,statSubscription:he}}let ce=new Ne,Ye=n?.player?.info.isAutoQualityEnabled$.getValue();ce.add(O.events.canplay$.subscribe(function(){Ye||rt(O,n.player.info.currentQuality$.getValue()),_&&O.setPlaybackRate(_)}));let H=t.createPlayer({listId:T.id,itemId:w,player:O,container:V,sources:ie(T,m).sources,config:F,subscription:ce,statistics:lt});return l&&c(T.id,H.itemId,S),u&&H.player.play(),p&&!u&&H.player.prepare(),e.emit(kt.playerCreated,H.player),{player:H.player,config:H.config,statistics:H.statistics}}function E(){v(),r=null,o.remove()}function v(){r?.off(d.chapterChanged,y),t.removeAll(),n={},s=!1}async function k(){if(!r)throw Error("need to set interactive controller");v(),o=document.createElement("div");let{media:T,chapter:S}=r.getCurrentChapter();T?(r.on(d.chapterChanged,y),await g({media:T,chapterId:S.id,title:S.label})):console.error("not found")}return{...t,on:e.on.bind(e),off:e.off.bind(e),init:k,setInteractiveController:a,createPlayer:g,removeAll:E,getActivePlayer:function(){return n}}}import{Subscription as Ii}from"@vkontakte/videoplayer-shared";var Nt=class{constructor({player:t,container:e,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:h,onRemove:y}){this.container=e,this.branches=n,this.selectBranches=r,this.subscription=new Ii,this.player=t,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&Lt(e.container.controls),this.disabledControls$=h,this.onRemove=y,this.globalEventEmitter=o,this.gameState=x.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(t=>{t?this.container.disable?.():this.container.enable?.()}))}hide=()=>{setTimeout(()=>{this.gameState!==x.end&&(z(this.container.container.events)&&this.gameState===x.afterInteractive||this.selectBranches.state.isExpect||(this.gameState!==x.interactive&&this.container.hide?.(),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.visibility,visibility:!1})))})};show=()=>{if(this.gameState===x.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.visibility,visibility:!0,isFirst:!1});else{let e=Ae({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.visibility,visibility:!1})},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.visibility,visibility:!1})),(this.gameState===x.end||this.gameState===x.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.visibility,visibility:!1}))},isEOV:()=>this.gameState===x.end});this.container.createView(e),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.visibility,visibility:!0,isFirst:!0}),this.disabledControls$.getValue()&&this.container.disable?.()}};selectContainerEvent(t=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:t?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:t}),!t&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);let t=z(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!t)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=x.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[x.destroyed,x.removed].includes(this.gameState)&&!this.isPermanentText)return;let e=this.player.getExactTime();if(Re(e,this.container.container))this.gameState!==x.beforeInteractive&&(this.gameState=x.beforeInteractive,this.onBeforeStartTime());else if(Jt(e,this.container.container))this.gameState!==x.interactive&&(this.gameState=x.interactive,this.onStartTime());else if(this.gameState!==x.afterInteractive){let s=this.gameState;this.gameState=x.afterInteractive,s===x.interactive&&this.onEndTime()}else this.gameState!==x.destroyed&&!this.isPermanentText&&this.removeView();let n=Jt(e,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.globalEventEmitter.emit(d.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:e,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=x.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(d.interactives,{subjectId:this.container.container.id,subjectName:"container",type:C.containerRemoved,visibility:!1}),this.gameState=x.removed,this.onRemove?.()}destroy(){this.reset(),this.removeView(),this.gameState=x.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}};var Oe=(i=[])=>i.reduce((t,e,n)=>{let r=(e?.controls??[]).filter(s=>!St(s));if(Rt(r)){let s=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:s});else{let a=[],c=-1/0,h=1/0,y=[],g=[];for(let E=0;E<t.length;E++){let v=t[E];if(g.push(...v.subjects),v.range[0]<h&&(h=v.range[0]),v.range[1]>c&&(c=v.range[1]),s[0]>=v.range[0]&&s[1]<=v.range[1])return t[E].subjects.push(o),t;s[0]<v.range[0]&&s[1]>v.range[0]&&(a.push(E),y=y.concat(v.subjects)),s[0]>=v.range[0]&&s[0]<=v.range[1]&&(a.push(E),y=y.concat(v.subjects),s[0]=v.range[0]),s[1]>=v.range[0]&&s[1]<=v.range[1]&&(a.push(E),y=y.concat(v.subjects),s[1]=v.range[1])}if(g.push(o),s[0]<=h&&s[1]>=c)return[{subjects:g,range:s}];a.length&&a.reverse().forEach(E=>{t.splice(E,1)}),t.push({subjects:y.concat([o]),range:s})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]);function je(){let i={};function t(){for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function e(a){let c={};for(let h in i)+h<=a&&(c[h]=i[h]);return c}function n(a){let c={};for(let h in i)+h>=a&&(c[h]=i[h]);return c}function r({timestamp:a,priority:c,initiator:h}){if(Kt(a)){let y=i[a]??null;if(y&&J(c,!0)){let g={},E=y[c];return E&&(g={...g,...E}),g=G(g)?null:g,g&&J(h,!0)?g[h]??null:g}return y}return null}function s({timestamp:a,priority:c,initiator:h}){if(Kt(a))if(i[a]){if(J(c,!0))if(i[a][c]){if(J(h,!0))if(i[a][c][h]){if(delete i[a][c][h],!G(i[a][c]))return!0}else return!1;if(delete i[a][c],!G(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:h,...y}){i[a]?.[c]?.[h]?i[a][c][h].push({...y}):i[a]?.[c]?i[a][c]={...i[a][c],[h]:[{...y}]}:i[a]?i[a]={...i[a],[c]:{[h]:[{...y}]}}:i[a]={[c]:{[h]:[{...y}]}}}return{map:i,remove:s,add:o,removeAll:t,get:r,getLte:e,getGte:n}}var xi=[I.expect,I.setNextBranch],Ti=1/0;function re(i){let t=i,e,n=Si(),r=new je,s,o=()=>{E(),p()},a=l=>{r.add.call(void 0,l),k()},c=(l=[])=>{for(let u of l)if(u.action(),xi.includes(u.actionType))break},h=(l=1/0)=>{let u=Ot(r.get({timestamp:l,priority:"control"})??{}),m=Ot(r.get({timestamp:l,priority:"container"})??{}),f=Ot(r.get({timestamp:l,priority:"chapter"})??{});return[...u,...m,...f]},y=l=>{n.isReady(l)&&c(h(l))},g=()=>{c([...Ot(r.get({timestamp:1/0,priority:"chapter"})??{})])},E=()=>{e&&(s?.unsubscribe(),e=void 0)},v=l=>{},k=()=>{e||(e=()=>setTimeout(()=>{y(1/0)}),s=t.events.ended$.subscribe(e))},T=l=>{E(),t=l},S=l=>{l.priority==="container"&&n.resetCalled(l.timestamp),r.remove(l)},p=()=>{n.release(),r.removeAll()};return{setPlayer:T,add:a,remove:S,exec:y,execEndOfVideo:g,listen:k,unlisten:E,release:o,containersEventsCallState:n,getPreparedToExecActions:h}}function Si(){let i=new Map;return{setCalled:({timestamp:o,id:a})=>{let c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(let a of o){let c=a.endTime??Ti,h=i.get(c)??{};i.set(c,{...h,[a.id]:!1})}},resetCalled:o=>{let a=i.get(o);if(a)for(let c in a)a[c]=!1},isReady:o=>{let a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function Ot(i){return Object.values(i).flat().sort(t=>t.actionType===I.expect?-1:1)}var $e={videoContentHeight:0,videoContentWidth:0},Pe=(i,t)=>{let{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return $e;let{clientHeight:r,clientWidth:s}=t.experimental.element$.getValue()||{};if(!(r&&s))return $e;let o=e/n,a=r/s,c,h;return a>o?(h=s,c=s*o):a<o?(h=r/o,c=r):(h=s,c=r),{videoContentWidth:h,videoContentHeight:c}};var wi=250;function Be(i){let t=()=>{},e=new ResizeObserver(a=>{s(a),t=s.bind(null,a)});function n(a){let{parentElement:c,player:h}=i();if(c&&h){let{videoContentWidth:y,videoContentHeight:g}=Pe(c,h);c.style.setProperty("--interactive-content-width",`${y}px`),c.style.setProperty("--interactive-content-height",`${g}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function r(){let{parentElement:a}=i();a.removeAttribute("style")}let s=Ct(a=>{let{fns:c=[]}=i();n(a);for(let h of c)h()},wi);function o(){t=void 0,e.disconnect(),r()}return{resizeObserver:e,calc:()=>{t()},release:o}}var st=class{constructor(){this.map={}}push(t,e){t in this.map?this.map[t].push(e):this.map[t]=[e]}get(t){let e=this.map[t];return e?e.slice():null}getAll(){let t=[];for(let e in this.map)t.concat(this.map[e]);return t}remove(t,e){t in this.map&&(this.map[t]=this.map[t].filter(n=>n!==e),this.map[t].length===0&&delete this.map[t])}clear(){this.map={}}keys(){return Object.keys(this.map)}size(){return this.keys().length}};var _i=i=>Math.floor(Math.random()*i),Fe=i=>{let t=i.length,e=1/0,n=null;for(;t--;)i[t].weight<e&&(e=i[t].weight,n=i[t]);return n},He=i=>{let t=i.length,e=-1/0,n=null;for(;t--;)i[t].weight>e&&(e=i[t].weight,n=i[t]);return n};var De=i=>{let t=i.length,e=_i(t);return i[e]};var Ge=i=>{let t=0;for(let n=0;n<i.length;++n)t+=i[n].weight??1;let e=Math.random()*t;t=0;for(let n=0;n<i.length-1;++n)if(t+=i[n].weight??1,t>=e)return i[n];return i[i.length-1]};var ze=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0});var se=(i,t=!1)=>({...i,args:t?{...i.args,...ze}:{...ze,...i.args}}),ae=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{let r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:p,controlType:l,controlId:u,containerId:m,branches:f=[],onEvent:_,isEOV:w=()=>!1,isDisabled:V=()=>!1})=>{let b=se(p,w()),A={timestamp:1/0,priority:"control",initiator:u,actionType:b.type},U=V(),F=i.emit.bind(i,d.interactives,{subjectId:u,subjectType:l,subjectName:"control",type:U?C.actionChoiceCanceled:C.actionChoice,actionType:p.type,payload:{containerId:m,...b.args}});if(U){F();return}switch(b.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let O=f.find(lt=>lt.id===b.args.branchId);if(!O)return;_(b.args.isDetachContainer,E.bind(null,{subjectId:u,subjectName:"control"})),F(),b.args.shouldOpenNow?k({subjectId:u,subjectName:"control",subjectType:l,action:b,payload:{chapterId:O.chapterId,autoSelect:!1}}):(e.add({...A,action:k.bind(null,{subjectId:u,subjectName:"control",subjectType:l,action:b,payload:{chapterId:O.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{_(b.args.isDetachContainer,E.bind(null,{subjectId:u,subjectName:"control"})),F(),b.args.shouldOpenNow?v({subjectId:u,subjectName:"control",subjectType:l,action:p}):e.add({...A,action:v.bind(null,{subjectId:u,subjectName:"control",subjectType:l,action:p})});return}case I.openURI.trim().toLowerCase():{_(b.args.isDetachContainer,E.bind(null,{subjectId:u,subjectName:"control"})),F(),b.args.shouldOpenNow?S({subjectId:u,subjectName:"control",subjectType:l,action:b,payload:{URI:p.args.uri}}):(e.add({...A,action:S.bind(null,{subjectId:u,subjectName:"control",subjectType:l,action:b,payload:{URI:p.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(d.errors,new R(1,1,{message:"Unexpected control event"}));return}},a=({action:p,container:{id:l,endTime:u},branches:m=[],isEOV:f=!1,autoSelected:_=!1})=>{let w=se(p,f),V={timestamp:!w.args.shouldOpenNow||f?1/0:u,priority:"container",initiator:l,actionType:w.type},b=i.emit.bind(i,d.interactives,{subjectId:l,subjectName:"container",type:C.actionChoice,actionType:w.type,payload:w.args});switch(w.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let A=m.find(U=>U.id===w.args.branchId);if(!A)return;b(),e.add({...V,action:k.bind(null,{subjectId:l,subjectName:"container",action:w,payload:{chapterId:A.chapterId,autoSelect:_}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{b(),e.add({...V,action:v.bind(null,{subjectId:l,subjectName:"container",action:w})});return}case I.openURI.trim().toLowerCase():{b(),e.add({...V,action:S.bind(null,{subjectId:l,subjectName:"container",action:w,payload:{URI:p.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(d.errors,new R(1,1,{message:"Unexpected container event"}));return}};function c({container:p,branches:l,isEOV:u=!1}){let m=te(p.events);if(m){let f=se(m.action,u);i.emit(d.interactives,{subjectId:p.id,subjectName:"container",type:C.actionChoice,actionType:f.type,payload:f.args}),e.add({timestamp:u?1/0:p.endTime,priority:"container",initiator:p.id,actionType:I.expect,action:g.bind(null,{subjectId:p.id,subjectName:"container"})}),r.isExpect=!0}else for(let f of p.events)a({action:f.action,container:p,branches:l,isEOV:u})}let h=({chapterId:p,action:l,branches:u=[]})=>{let m=i.emit.bind(i,d.interactives,{subjectId:p,subjectName:"chapter",type:C.actionChoice,actionType:l.type,payload:l.args});switch(l.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let f=u.find(_=>_.id===l.args.branchId);return f?.chapterId?(m(),k.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{let f=De(u);return f?.chapterId?(m(),k.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{let f=Ge(u);return f?.chapterId?(m(),k.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{let f=He(u);return f?.chapterId?(m(),k.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{let f=Fe(u);return f?.chapterId?(m(),k.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return m(),v.bind(null,{subjectId:p,subjectName:"chapter",action:l});case I.openURI.trim().toLowerCase():return m(),S.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{URI:l.args.uri}});default:console.error("Unexpected chapter event"),i.emit(d.errors,new R(1,1,{message:"Unexpected chapter event"}));return}};function y(p){let l=te(p.events);if(l){if(j(p))return;i.emit(d.interactives,{subjectId:p.id,subjectName:"chapter",type:C.actionChoice,actionType:l.action.type,payload:l.action.args}),e.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:I.expect,action:g.bind(null,{subjectId:p.id,subjectName:"chapter"})})}else p.events.forEach(u=>{let m=h({chapterId:p.id,action:u.action,branches:p.branches});m&&e.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:u.action.type,action:m})})}let g=({subjectId:p,subjectName:l,action:u})=>{t.pause(),i.emit(d.interactives,{subjectId:p,subjectName:l,type:C.actionExecution,actionType:u?.type??I.expect})},E=({subjectId:p,subjectName:l})=>{t.info.isEnded$.getValue()?e.execEndOfVideo():t.play(),i.emit(d.interactives,{subjectId:p,subjectName:l,type:C.actionExecution,actionType:"after-expect"})},v=({subjectId:p,subjectName:l,subjectType:u,action:m})=>{i.emit(d.interactives,{subjectId:p,subjectName:l,subjectType:u,type:C.actionExecution,actionType:m.type})},k=({subjectId:p,subjectName:l,subjectType:u,action:m,payload:f})=>{f.behaviour="change-chapter",i.emit(d.interactives,{subjectId:p,subjectName:l,subjectType:u,type:C.actionExecution,actionType:m.type,payload:f})},T=({subjectId:p,subjectName:l,subjectType:u,action:m,payload:f})=>{f.behaviour="change-manifest",i.emit(d.interactives,{subjectId:p,subjectName:l,subjectType:u,type:C.actionExecution,actionType:m.type,payload:f})},S=({subjectId:p,subjectName:l,subjectType:u,action:m,payload:f})=>{if(!f.URI)return;let _=window.open(f.URI,"_blank","noopener,noreferrer");_&&(_.opener=null),i.emit(d.interactives,{subjectId:p,subjectName:l,subjectType:u,type:C.actionExecution,actionType:m.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:h,onExpectEvent:g,expectEventHandler:E,setManifestChapterEvents:y,setManifestContainerEvents:c,stopExpect:s,state:r}};import{Subscription as Li,ValueSubject as at}from"@vkontakte/videoplayer-shared";var oe=(i,t)=>{let e={};return i.map(n=>{if(!e[n]){let r=t.chapters.find(o=>o.id===n);if(!r)return null;let s=t.media.videos.find(o=>r.videoId===o.id);if(!s)return null;e[n]=Qe(s)}return e[n]}).filter(Boolean)},Mi=i=>{for(let t of i.variants)if(Ri(t)&&"payload"in t)return t.payload.id},Ri=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",Qe=i=>{let t=Mi(i);if(!t)return null;let e=t.split("_").pop();return e?parseInt(e,10):null},Ai=(i,t)=>{for(let e of i.media.videos)if(t===Qe(e)){for(let n of i.chapters)if(n.videoId===e.id)return n.id;return}},Ke=(i,t)=>i.reduce((e,n)=>{let r=Ai(t,n);return r?[...e,r]:e},[]);var ot=class{constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:r,settings:s}){this.state={history$:new at([]),hasPrevChapter$:new at(!1),prevChapter$:new at(null),isInitialChapter$:new at(!1),isGoBackLimited$:new at(!1)};this.#a=null;this.#h=!1;this.#i=null;this.#d=null;this.#n=null;this.#s=null;this.#o=null;this.#t=new Li;this.#p=!1;this.#u=0;this.#n=e,this.#o=t,this.#s=n,this.#a=r,this.#r=s,this.state?.history$&&this.#t&&this.#t?.add(this.state?.history$.subscribe(o=>{this.state?.prevChapter$.next(o.at(-2)||null),this.state?.hasPrevChapter$.next(o.length>1),this.state?.isInitialChapter$.next(this.getInitialChapterId()===this.#i?.metadata?.initChapterId),this.state?.isGoBackLimited$.next(this.#u===this.#r.maxLength-1)}))}#a;#r;#h;#i;#d;#n;#s;#o;#t;#p;#u;async setManifest(t){!this.#s||!this.#o||(this.#i=t,await this.getProjectHistory(),await this.#s.setChapter({chapterId:this.getInitialChapterId(),pushToHistory:!1}),this.#h||(this.#h=!0,this.#o.emit(d.historyInited,{initChapterId:this.getInitialChapterId()})))}get inited(){return this.#h}async updateHistory(t,e=!0){if(!this.#i)return;this.#p?(this.#p=!1,this.#u++):this.#u=0;let n=this.#i,r=t.length-this.#r.maxLength,s=r>0?t.slice(r):t,o=oe(s,n);if(this.#d=o,this?.state?.history$.next(s),!(!e||!this.#a||!this.#n))try{await this.#a.save(this.#n,o)}catch{this.#o?.emit(d.errors,new R(1,5,"Unable to save interactive history"))}}async goBack(){if(!this.state||!this.#s)return this.#o?.emit(d.errors,new R(1,5,"Cannot go back because HistoryController has not been initialized"));this.#p=!0;let t=this.state.history$.getValue().slice(0,-1),e=t.pop();this.state.history$.next(t),await this.#s.setChapter({chapterId:e})}async getProjectHistory(){if(!this.#i||!this.#n)return;let t=this.#i,e=[this.getInitialVideoId()];if(this.#a)try{let r=await this.#a.get(this.#n);r.length&&(e=r)}catch{this.#o?.emit(d.errors,new R(1,5,"Error while trying to fetch data"))}let n=Ke(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#r.initChapterId||this.#i?.metadata.initChapterId}getInitialVideoId(){if(this.#i){let t=this.getInitialChapterId();return oe([t],this.#i).pop()}return null}destroy(){this.state=null,this.#n=null,this.#a=null,this.#s=null,this.#t?.unsubscribe(),this.#t=null,this.#h=!1,this.#o?.emit(d.historyDestroyed),this.#o=null}};var jt=class i{constructor(t,e,n,r){this.target=t,this.type=e,this.listener=n,this.options=i._convertOptions(t,r),this.target.addEventListener(e,n,this.options)}unlisten(){this.type&&this.listener&&this.options&&this.target?.removeEventListener(this.type,this.listener,this.options),this.target=null,this.type=null,this.listener=null,this.options=!1}static _convertOptions(t,e){if(e===void 0)return!1;if(typeof e=="boolean")return e;{let n=new Set(["passive","capture"]),r=Object.keys(e).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),i._doesSupportObject(t)?e:e.capture||!1}}static{this._supportsObject=void 0}static _doesSupportObject(t){let e=i._supportsObject;if(e===void 0){e=!1;try{let n={},r={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);let s=()=>{};t.addEventListener("test",s,n),t.removeEventListener("test",s,n)}catch{e=!1}i._supportsObject=e}return e||!1}};var $t=class{constructor(){this.bindingMap=new st}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,r){if(!this.bindingMap)return;let s=new jt(t,e,n,r);this.bindingMap.push(e,s)}listenOnce(t,e,n,r){let s=o=>{this.unlisten(t,e,s),n(o)};this.listen(t,e,s,r)}unlisten(t,e,n){if(!this.bindingMap)return;let r=this.bindingMap.get(e)||[];for(let s of r)s.target===t&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(e,s))}removeAll(){if(!this.bindingMap)return;let t=this.bindingMap.getAll();for(let e of t)e.unlisten();this.bindingMap.clear()}};var Pt=class{constructor(){this._prevSizeId=0;this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){let t=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!t)return!1;let e=t.data,n=e.length;for(let r=3;r<n;r+=40)if(e[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(t){this.canvasImgSrc=t}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(t,e=!1){let n=t.width+t.height;if(this._prevSizeId===n)return;let r;e&&(r=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&r&&this.restore(r),this._prevSizeId=n}async save(){let t=this.rootElement.toDataURL("image/jpeg",1),e=new Image;return e.crossOrigin="anonymous",e.src=t,await e.decode(),e}restore(t){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(t,0,0,this.rootElement.width,this.rootElement.height)}};var Bt=class{constructor({parentElement:t,endOffsetMs:e=250,onError:n}){this.currentVideoDurationMs=1/0;this._containerTimeFrameShouldReceived=!1;this._endTimeFrameReceived=!1;this._shouldCallSkip=!1;this.onEachTick=t=>{let e=t??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(e);if(this.isContainerTime(e))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()}};this.onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
6
+ var ot="1.0.19-dev.d432d6cd.0";function Be(i,e=1){let t="0",n="0",r="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+r},${e})`}var P="interactive",Kt="interactive-controls-container",oe=()=>document.querySelector(`.${Kt}`),lt=.4,V={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ct=(n=>(n.top="flex-start",n.bottom="flex-end",n.center="center",n))(ct||{}),pt=(n=>(n.start="flex-start",n.end="flex-end",n.center="center",n))(pt||{}),ht=(n=>(n.start="left",n.end="right",n.center="center",n))(ht||{}),le=({target:i,props:e})=>{i.style.alignItems=(e.text?.gravityVertical&&ct[e.text.gravityVertical])??"center",i.style.justifyContent=(e.text?.gravityHorizontal&&pt[e.text.gravityHorizontal])??"center",i.style.textAlign=(e.text?.alignment&&ht[e.text.alignment])??"left"},ce=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},pe=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Be(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},he=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Be(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},z=({target:i,layoutParams:e,fallback:t})=>{let n=e.angle??t.angle;n=n&&n*-1,i.style.transform=`rotate(${n}rad)`};var j=class{constructor(e){this.control=e;this.container=null;this.controlElement=null;this.clickListener=null}createContainerElement(e){let t=document.createElement("div");t.classList.add(`${P}-control-container-${this.control.id}`),e(t,this.control.layoutParams);let n=(this.control.layoutParams.innerSizesDependOn??V.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};this.container={element:t,dimensions:n}}createClickListener(e){return t=>{t.stopPropagation(),e()}}setEvents(e){!this.container||!this.control.events||this.control.events.forEach(t=>{switch(t.type.trim().toLowerCase()){case"onclick":this.clickListener=this.createClickListener(()=>e({action:t.action,controlId:this.control.id,controlType:this.control.type})),this.container?.element.addEventListener("click",this.clickListener);break;default:break}})}removeListeners(){this.container?.element&&this.clickListener&&this.container?.element.removeEventListener("click",this.clickListener)}};var _e="int",$=(n=>(n.AREA=`${_e}_area`,n.TEXT=`${_e}_text`,n.BUTTON=`${_e}_bttn`,n))($||{});var de=i=>{if(i.type.trim().toLowerCase()==="area")return new He(i)},He=class extends j{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("button");n.type="button",n.classList.add(`${P}-${this.control.id}`),n.setAttribute("data-testid",$.AREA),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",pe({target:n,props:this.control.props,fallback:{...V,backgroundColor:"transparent"}}),he({target:n,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:this.container.dimensions}),z({target:n,layoutParams:this.control.layoutParams,fallback:V}),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}disable(){this.controlElement&&(this.controlElement.style.cursor="default")}enable(){this.controlElement&&(this.controlElement.style.cursor="pointer")}getElement(){return this.controlElement}};var ue=()=>{let i=document.createElement("span");return i.style.display="inline-block",i.style.whiteSpace="pre",i.style.overflow="hidden",i.style.textOverflow="ellipsis",i.style.maxWidth="100%",i.style.maxHeight="100%",i};var me=i=>{if(i.type.trim().toLowerCase()==="button")return new De(i)},De=class extends j{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("button");n.type="button",n.classList.add(`${P}-${this.control.id}`),n.setAttribute("data-testid",$.BUTTON),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",n.style.fontFamily="inherit",z({target:n,layoutParams:this.control.layoutParams,fallback:V}),pe({target:n,props:this.control.props,fallback:V}),he({target:n,props:this.control.props,fallback:V,dependsOn:this.container.dimensions}),le({target:n,props:this.control.props});let r=ue();ce({target:r,props:this.control.props,fallback:V,dependsOn:this.container.dimensions}),n.append(r),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}disable(){this.controlElement&&(this.controlElement.style.cursor="default")}enable(){this.controlElement&&(this.controlElement.style.cursor="pointer")}getElement(){return this.controlElement}};var dt=i=>{if(i.type.trim().toLowerCase()==="text")return new Ge(i)},Ge=class extends j{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("div");n.classList.add(`${P}-${this.control.id}`),n.setAttribute("data-testid",$.TEXT),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.fontFamily="inherit",z({target:n,layoutParams:this.control.layoutParams,fallback:V}),le({target:n,props:this.control.props});let r=ue();ce({target:r,props:this.control.props,fallback:V,dependsOn:this.container.dimensions}),n.append(r),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}disable(){}enable(){}getElement(){return this.controlElement}};var ze=class{constructor(e){this.layout=e}},fe=class extends ze{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}};var U=class{constructor(e){this.container=e,this.factories=new Map,this.#e()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#e()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#e()}#e(){this.controls=this.#n()}#n(){return this.container.controls?.reduce((e,t)=>{let n=t.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...e,r(t)]:[...e]},[])}};var ye=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new Ue(i,e)},Ue=class extends U{constructor(e,t){super(e),this.rootElement=t??oe(),this.layout=new fe(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",me),this.addControlFactory("text",dt),this.addControlFactory("area",de)}createView(e){let t=document.createElement("div");return t.classList.add(`${P}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{n.createView({parentElement:t,layoutCallback:this.layout.setControlLayout}),n.setEvents(e)}),this.rootElement.append(t),this.isRemoved=!1,t}hide(){let e=this.getElement();e&&(e.style.visibility="hidden")}show(){let e=this.getElement();e&&(e.style.visibility="visible")}enable(){let e=this.getElement();e&&(this.controls.forEach(t=>t.enable()),e.style.opacity=1,this.isDisabled=!1)}disable(){let e=this.getElement();e&&(this.controls.forEach(t=>t.disable()),e.style.opacity=lt,this.isDisabled=!0)}removeView(){this.isRemoved||(this.controls.forEach(e=>e.removeListeners()),this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${P}-${this.container.id}`)}};import{clientChecker as bi,combine as Ci,InterfaceLanguage as Ei,Observable as zt,once as Ii,Subject as rt,Subscription as Ut,ValueSubject as L}from"@vkontakte/videoplayer-shared";import{InteractiveInterfaceClick as re}from"@vkontakte/videoplayer-statistics";import{loadVKLangPack as Zt}from"@vkontakte/videoplayer-shared";function Q(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}var B=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,K=i=>B(i,"Object"),ge=i=>B(i,"String"),ve=i=>B(i,"Array"),be=i=>B(i,"Number"),ut=i=>B(i,"Function");var We=i=>be(i)&&!isNaN(i);var _=i=>K(i)&&Object.keys(i).length===0,Qe=i=>ve(i)&&!i.length;var Z=(i,e)=>ge(i)&&(e?i.trim():i).length;var mt="video_interactive",ft="videoint";var yt=250,q=class{constructor(e){this.handleZoomChange=Q(e=>{this.lastZoomInfo=e},yt);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),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?.("Id is not found"),console.error("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,!be(e.graph.edit.chapters[0].x)){this.onError?.("Can't show graph"),console.error("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:n,lang:r,visitedChapters:s=[]}){this.isReady=!1,this.isHidden=!0,this.manifest=null,this.visitedChapterIds=new Set(s),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=qt(e),this.resizeObserver=new ResizeObserver(Q(this.onResize,yt)),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 Zt(this.lang,mt,ft)}catch{console.log("Unable to load graph language pack")}let{GraphEditor:t}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new t(this.graphWrapperElement,{mode:"read",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:n,...r})=>{n==="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 qt(i){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",i.append(e),e}var X=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,n=!1,r=Math.round(this._player.info.position$.getValue()*1e3);for(let s of this._containers){let c=s.startTime-e;if(c<=r&&(s.endTime&&r<=s.endTime||s.endTime===null)){n=!0;break}r<c&&(t=t===-1?c:Math.min(t,c))}return!n&&t!==-1?t:null}}};import{isSupportedManifest as Ee,ControlTypes as Ie,EventActionTypes as E,migrateManifestToLatestVersion as bt,compareVersions as Pn}from"@interactiveplatform/movika-graph-editor";var gt={metadata:"Object",chapters:"Array"},vt=i=>{if(!K(i))return!1;for(let e in gt)if(!i[e]||!B(i[e],gt[e]))return!1;return Ee(i.metadata.version)},Ce=i=>i.type===Ie.Text,An=i=>i.type===Ie.Button,Mn=i=>i.type===Ie.Area;var M=class{constructor(e,t,...n){this.severity=e;this.category=t;this.data=n}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var xe=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 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 r=n.length;r>0;r--)if(n[r]===t){n.splice(r,1);break}return this}emit(e,...t){let n=this.listeners[e];return n?(n.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return this.rawListeners(e).length}rawListeners(e){return this.listeners[e]||[]}};var Te=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{ut(e)&&(this.fns.push(e),t&&this.updateFn())};this.removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};this.updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};this.forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};this.requestAnimation=()=>{this.raf||this.forceRequestAnimation()};this.cancelAnimation=()=>{this.raf&&(cancelAnimationFrame(this.raf),this.raf=void 0)};e&&(this.fn=e,this.addFn(e))}release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}};import{ValueSubject as ni}from"@vkontakte/videoplayer-shared";var Se=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Xt(...this.loaders[e])(t)}};function Xt(...i){return async function(t){let n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function Y(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function we({actions:i,errors:e,chapterId:t,...n}){if(t){let r=i.getManifest(),s=i.getChapter(r.chapters,t);if(s){let c=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return c?{...n,actions:i,errors:e,result:{chapter:s,media:c,graph:a}}:{...n,errors:Y(e,we.name,"Could not find media"),actions:i}}}return{...n,errors:Y(e,we.name,"Could not find chapter"),actions:i}}var Ke=(i="",e="")=>{let t=i.split("."),n=e.split("."),r=0;for(let s=0;s<Math.max(t.length,n.length)&&!r;s++)t[s]>n[s]?r=1:t[s]<n[s]?r=-1:r=0;return r};var Yt=async i=>{try{let e={},t;if(ge(i)){t=new URL(i).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(K(i))e=i;else return{};if(!vt(e))return{};let n=e.metadata.media;if(ge(n)&&!("media"in e))try{let r;t?r=new URL(n,t).href:(r=new URL(n).href,t=r);let s=await fetch(r);if(!s.ok)throw new Error;e.metadata.media=await s.json()}catch{return ti(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Ct(i){let{manifest:e,manifestURL:t}=await Yt(i);if(!e)throw new Error("Failed on fetch");let n=bt(e);return n.media=Jt(n.media,t),delete n.metadata.media,n}function Ae(i,e){if(e)return i.find(t=>t.id===e)}function Ze(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function qe(i,e){return i.videos.find(t=>t.id===e)}function Jt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{let r="url"in n?n.url:"",s=ei(r,e);return{...n,url:s||r}})}))}}function ei(i="",e){try{return new URL(i,e).href}catch{return""}}function ti(i){return Ke(i,"3.2.0")>=0}var Me=i=>ve(i)&&!Qe(i),F=i=>i.order==="end",ke=i=>ve(i.containers)&&!Qe(i.containers)&&F(i),Et=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t<(e.startTime??0)},Xe=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var H=(i=[])=>i.some(e=>e.action.type==="expect"),Ye=(i=[])=>i.find(e=>e.action.type==="expect"),ii=i=>i?.length===1,Ve=i=>ii(i)&&Ce(i[0]);function It(i,...e){return t=>typeof e[0]=="object"&&typeof t=="object"?i({...e[0],...t}):i(...e,...t)}var xt=(i,e)=>H(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&H(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);var W=class extends Se{constructor(t,n){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new ni(null);this.onError=n,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 n=await this.exec("manifestLoaders",{actions:{addErrorMessage:Y},result:null,errors:null,source:t});return n.errors&&this.errorHandler(n.errors),this.manifest=await Ct(n.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 n=await this.exec("chapterLoaders",we({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Ze,getChapter:Ae,getMedia:qe,getByBranches:this.getByBranches.bind(this),addErrorMessage:Y},result:null,errors:null,chapterId:t}));return n.errors&&this.errorHandler(n.errors),this.chapter=n.result.chapter,this.media=n.result.media,this.graph=n.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 n=Ae(this.manifest.chapters,t);if(n){let r=qe(this.manifest.media,n.videoId),s=Ze(this.manifest.graph,n.id);if(r)return{chapter:n,media:r,graph:s}}return null}getBranches(t=this.chapter?.id){if(t===this.chapter?.id)return this.getByBranches(this.chapter?.branches);{let n=Ae(this.manifest?.chapters||[],t);return this.getByBranches(n?.branches)}}getByBranches(t=[]){return t.reduce((n,r)=>{let s=this.getByChapterId(r.chapterId);return s&&n.push(s),n},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter?.id===this.manifest?.metadata.initChapterId}isEndChapter(){return this.chapter?F(this.chapter):!1}};import{Player as ri}from"@vkontakte/videoplayer-core";import{Subscription as St,Tracer as si,ValueSubject as ai}from"@vkontakte/videoplayer-shared";var Tt=i=>{let e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){let[t,n]=e.payload.id.split("_");return[t,n]}return[]};function Je(){let i=new Map;function e({listId:s=Math.random().toString(),itemId:c=Math.random().toString(),...a}){let o=i.get(s),d={...a};return o?o[c]=d:i.set(s,{[c]:d}),{listId:s,itemId:c,...a}}function t(s){s.player.destroy(),s.container.remove(),s.subscription.unsubscribe(),s.statistics?.oneStat.destroy(),s.statistics?.statSubscription.unsubscribe()}function n(s,c){let a=i.get(s);if(!a)throw Error("Can't remove. Not find.");if(c){let o=a[c];o&&t(o),delete a[c],Object.keys(a).length||i.delete(s)}else{for(let o of Object.values(a))t(o);i.delete(s)}}function r(){for(let s of i)n(s[0])}return{createPlayer:e,removePlayer:n,map:i,removeAll:r}}function et(i,e=[]){let t={},n,r=!e.length;for(let s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:s.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break;default:break}return{sources:t,thumbUrl:n,title:i.title??""}}var J=(i,e)=>{let t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))};var oi=2;function tt(i){let e=Je(),t={},n=null,r=!1,s,c=new ai(null);i&&a(i);function a(x){n=x}function o(x,T,p){if(!n)throw Error("need to set interactive controller");if(!n.options)return;let u=(e.map.get(x)??{})[T];if(u){t={chapterId:p,listId:x,itemId:T,...u};let f=t.player;t.subscription.add(f.info.currentQuality$.subscribe(m=>{let w=f.info.position$.getValue(),S=f.info.isAutoQualityEnabled$.getValue();if(!(!m||!w||S))for(let A of e.map)Object.values(A[1]).forEach(({player:g})=>{J(g,m)})})).add(f.events.started$.subscribe(()=>{d(T)})),u.container.remove(),n.setPlayer(u.player),r||(n.init(),r=!0),c.next({player:t.player,config:t.config,statistics:t.statistics});return}throw Error("Can't set. Not find.")}async function d(x){if(!n)throw Error("need to set interactive controller");if(_(t)||x!==t.itemId)return;let T=n.getChapterBranches(),p=new Set;for(let l of T)p.has(l.media.id)||(await C({media:l.media,chapterId:l.chapter.id,setAsActive:!1,title:l.chapter.label}),p.add(l.media.id))}async function y({chapter:{id:x},media:T}){if(_(t))return;let p=t.player.info.muted$.getValue(),l=t.player.info.currentQuality$.getValue(),u=t.player.info.isAutoQualityEnabled$.getValue(),f=t.player.info.volume$.getValue(),m=t.player.info.currentPlaybackRate$.getValue(),w=!u,S=!1;for(let A of e.map)if(A[0]===T.id){let g=Object.keys(A[1]);for(let k of g)k===t.itemId?(g.length<oi||(S=!0),e.removePlayer(A[0],k)):(S=!0,o(A[0],k,x),w?J(t.player,l):t.player.setAutoQuality(!0),t.player.setVolume(f),t.player.setMuted(p),t.player.setPlaybackRate(m))}else e.removePlayer(A[0]);S||(await C({media:T,chapterId:x,setAsActive:!0,playbackRate:m}),w?J(t.player,l):t.player.setAutoQuality(!0),t.player.setVolume(f),t.player.setMuted(p))}async function C({media:x,chapterId:T,prefetch:p=!0,setAsActive:l=!0,autoplay:u=!1,preferredExt:f,title:m,playbackRate:w}){let S=Math.random().toString(),A=document.createElement("div");s.append(A);let g;if(n?.options?.vkVideoLoader){let ae=Tt(x);ae.length&&(g=await n.options.vkVideoLoader(...ae))}let k=n?.options?.coreConfig||void 0,D={...k,configName:[...k?.configName??[],"interactive"]},O={container:A,...g?.videos?.[0]||{sources:et(x,f).sources},title:m,failoverHosts:g?.failoverHosts||[]},N=new ri(D,si.createRootTracer());N.initVideo(O);let se=null;if(g?.videos&&n?.options.createOneStat){let ae=g.videos[0],$e=n.options.createOneStat(ae),at=new St;$e&&(at.add($e.attachTo(N)),se={oneStat:$e,statSubscription:at})}let st=new St,Qt=t?.player?.info.isAutoQualityEnabled$.getValue();st.add(N.events.canplay$.subscribe(function(){Qt||J(N,t.player.info.currentQuality$.getValue()),w&&N.setPlaybackRate(w)}));let G=e.createPlayer({listId:x.id,itemId:S,player:N,container:A,sources:et(x,f).sources,config:O,subscription:st,statistics:se});return l&&o(x.id,G.itemId,T),u&&G.player.play(),p&&!u&&G.player.prepare(),{player:G.player,config:G.config,statistics:G.statistics}}function I(){v(),n=null,s.remove()}function v(){n?.off(h.chapterChanged,y),e.removeAll(),t={},r=!1}async function R(){if(!n)throw Error("need to set interactive controller");v(),s=document.createElement("div");let{media:x,chapter:T}=n.getCurrentChapter();x&&T?(n.on(h.chapterChanged,y),await C({media:x,chapterId:T.id,title:T.label})):console.error("not found")}return{...e,init:R,setInteractiveController:a,createPlayer:C,removeAll:I,getActivePlayer:function(){return t},activePlayerChanged:c}}var h={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},ee={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},b={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as li}from"@vkontakte/videoplayer-shared";var Re=class{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:c,ignoreContainerEvent:a,permanentTextControls:o,disabledControls$:d,onRemove:y}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(H(this.container.container.events)&&this.gameState===3||this.selectBranches.state.isExpect||(this.gameState!==2&&this.container.hide?.(),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.visibility,visibility:!1})))})};this.show=()=>{if(this.gameState===2&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.visibility,visibility:!0,isFirst:!1});else{let t=It(this.selectBranches.onControlEvent,{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.visibility,visibility:!1})},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.visibility,visibility:!1})),(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.visibility,visibility:!1}))},isEOV:()=>this.gameState===4});this.container.createView(t),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.visibility,visibility:!0,isFirst:!0}),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let e=this.player.experimental.element$.getValue(),n=e instanceof HTMLVideoElement?e.readyState:void 0,r=[6,5];if(!n||r.includes(this.gameState)&&!this.isPermanentText)return;let s=this.player.getExactTime();if(Et(s,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(Xe(s,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let o=this.gameState;this.gameState=3,o===2&&this.onEndTime()}else this.isPermanentText||this.removeView();let c=Xe(s,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.globalEventEmitter.emit(h.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:a,currentTime:s,isInteractiveTime:c})};this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new li,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=o&&Ve(t.container.controls),this.disabledControls$=d,this.onRemove=y,this.globalEventEmitter=c,this.gameState=0,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}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?.()}))}selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||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 e=H(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.visibility,visibility:!1})}reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=1}removeView(){this.container.removeView(),this.globalEventEmitter.emit(h.interactives,{subjectId:this.container.container.id,subjectName:"container",type:b.containerRemoved,visibility:!1}),this.gameState=5,this.onRemove?.()}destroy(){this.reset(),this.removeView(),this.gameState=6,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}};var wt=(i=[])=>i.reduce((e,t,n)=>{let r=(t?.controls??[]).filter(s=>!Ce(s));if(Me(r)){let s=[t.startTime??0,t.endTime??1/0],c=t.id;if(!n)e.push({subjects:[c],range:s});else{let a=[],o=-1/0,d=1/0,y=[],C=[];for(let I=0;I<e.length;I++){let v=e[I];if(C.push(...v.subjects),v.range[0]<d&&(d=v.range[0]),v.range[1]>o&&(o=v.range[1]),s[0]>=v.range[0]&&s[1]<=v.range[1])return e[I].subjects.push(c),e;s[0]<v.range[0]&&s[1]>v.range[0]&&(a.push(I),y=y.concat(v.subjects)),s[0]>=v.range[0]&&s[0]<=v.range[1]&&(a.push(I),y=y.concat(v.subjects),s[0]=v.range[0]),s[1]>=v.range[0]&&s[1]<=v.range[1]&&(a.push(I),y=y.concat(v.subjects),s[1]=v.range[1])}if(C.push(c),s[0]<=d&&s[1]>=o)return[{subjects:C,range:s}];a.length&&a.reverse().forEach(I=>{e.splice(I,1)}),e.push({subjects:y.concat([c]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function At(){let i={};function e(){for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a]}function t(a){let o={};for(let d in i)+d<=a&&(o[d]=i[d]);return o}function n(a){let o={};for(let d in i)+d>=a&&(o[d]=i[d]);return o}function r({timestamp:a,priority:o,initiator:d}){if(We(a)){let y=i[a]??null;if(y&&o&&Z(o,!0)){let C={},I=y[o];return I&&(C={...C,...I}),C=_(C)?null:C,C&&Z(d,!0)?C[d]??null:C}return y}return null}function s({timestamp:a,priority:o,initiator:d}){if(We(a))if(i[a]){if(o&&Z(o,!0))if(i[a][o]){if(d&&Z(d,!0))if(i[a][o][d]){if(delete i[a][o][d],!_(i[a][o]))return!0}else return!1;if(delete i[a][o],!_(i[a]))return!0}else return!1;return delete i[a]}else return!1;return!1}function c({timestamp:a,priority:o,initiator:d,...y}){i[a]?.[o]?.[d]?i[a][o][d].push({...y}):i[a]?.[o]?i[a][o]={...i[a][o],[d]:[{...y}]}:i[a]?i[a]={...i[a],[o]:{[d]:[{...y}]}}:i[a]={[o]:{[d]:[{...y}]}}}return{map:i,remove:s,add:c,removeAll:e,get:r,getLte:t,getGte:n}}var ci=[E.expect,E.setNextBranch],pi=1/0;function Mt(i){let e=i,t,n=hi(),r=At(),s,c=()=>{I(),p()},a=l=>{r.add.call(void 0,l),R()},o=(l=[])=>{for(let u of l)if(u.action(),ci.includes(u.actionType))break},d=(l=1/0)=>{let u=Pe(r.get({timestamp:l,priority:"control"})??{}),f=Pe(r.get({timestamp:l,priority:"container"})??{}),m=Pe(r.get({timestamp:l,priority:"chapter"})??{});return[...u,...f,...m]},y=l=>{n.isReady(l)&&o(d(l))},C=()=>{o([...Pe(r.get({timestamp:1/0,priority:"chapter"})??{})])},I=()=>{t&&(s?.unsubscribe(),t=void 0)},v=l=>{},R=()=>{t||(t=()=>setTimeout(()=>{y(1/0)}),s=e.events.ended$.subscribe(t))},x=l=>{I(),e=l},T=l=>{l.priority==="container"&&n.resetCalled(l.timestamp),r.remove(l)},p=()=>{n.release(),r.removeAll()};return{setPlayer:x,add:a,remove:T,exec:y,execEndOfVideo:C,listen:R,unlisten:I,release:c,containersEventsCallState:n,getPreparedToExecActions:d}}function hi(){let i=new Map;return{setCalled:({timestamp:c,id:a})=>{let o=i.get(c);o&&o[a]!==void 0&&(o[a]=!0)},setData:(c=[])=>{for(let a of c){let o=a.endTime??pi,d=i.get(o)??{};i.set(o,{...d,[a.id]:!1})}},resetCalled:c=>{let a=i.get(c);if(a)for(let o in a)a[o]=!1},isReady:c=>{let a=i.get(c);return a?!Object.values(a).some(o=>!o):!0},release:()=>i.clear()}}function Pe(i){return Object.values(i).flat().sort(e=>e.actionType===E.expect?-1:1)}var kt={videoContentHeight:0,videoContentWidth:0},Vt=(i,e)=>{let{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return kt;let{clientHeight:r,clientWidth:s}=e.experimental.element$.getValue()||{};if(!(r&&s))return kt;let c=t/n,a=r/s,o,d;return a>c?(d=s,o=s*c):a<c?(d=r/c,o=r):(d=s,o=r),{videoContentWidth:d,videoContentHeight:o}};var di=250;function Rt(i){let e=()=>{},t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){let{parentElement:o,player:d}=i();if(o&&d){let{videoContentWidth:y,videoContentHeight:C}=Vt(o,d);o.style.setProperty("--interactive-content-width",`${y}px`),o.style.setProperty("--interactive-content-height",`${C}px`),o.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),o.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function r(){let{parentElement:a}=i();a.removeAttribute("style")}let s=Q(a=>{let{fns:o=[]}=i();n(a);for(let d of o)d()},di);function c(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:c}}var te=class{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){let t=this.map[e];return t?t.slice():null}getAll(){let e=[];for(let t in this.map)e.concat(this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}keys(){return Object.keys(this.map)}size(){return this.keys().length}};var ui=i=>Math.floor(Math.random()*i),Lt=i=>{let e=i.length,t=1/0,n=null;for(;e--;){let r=i[e],s=r.weight??1;s<t&&(t=s,n=r)}return n},Nt=i=>{let e=i.length,t=-1/0,n=null;for(;e--;){let r=i[e],s=r.weight??0;s>t&&(t=s,n=r)}return n};var Ft=i=>{let e=i.length,t=ui(e);return i[t]},Pt=1,jt=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Pt;let t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Pt,e>=t)return i[n];return i[i.length-1]};var Ot={shouldOpenNow:!0,isDetachContainer:!0};var it=(i,e=!1)=>({...i,args:e?{...i.args,...Ot}:{...Ot,...i.args}}),_t=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{let r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},c=({action:p,controlType:l,controlId:u,containerId:f,branches:m=[],onEvent:w,isEOV:S=()=>!1,isDisabled:A=()=>!1})=>{let g=it(p,S()),k={timestamp:1/0,priority:"control",initiator:u,actionType:g.type},D=A(),O=i.emit.bind(i,h.interactives,{subjectId:u,subjectType:l,subjectName:"control",type:D?b.actionChoiceCanceled:b.actionChoice,actionType:p.type,payload:{containerId:f,...g.args}});if(D){O();return}switch(g.type.trim().toLowerCase()){case E.setNextBranch.trim().toLowerCase():{let N=m.find(se=>se.id===g.args.branchId);if(!N)return;w(g.args.isDetachContainer,I.bind(null,{subjectId:u,subjectName:"control"})),O(),g.args.shouldOpenNow?R({subjectId:u,subjectName:"control",subjectType:l,action:g,payload:{chapterId:N.chapterId,autoSelect:!1}}):(t.add({...k,action:R.bind(null,{subjectId:u,subjectName:"control",subjectType:l,action:g,payload:{chapterId:N.chapterId,autoSelect:!1}})}),n?.());return}case E.continuePlayback.trim().toLowerCase():{w(g.args.isDetachContainer,I.bind(null,{subjectId:u,subjectName:"control"})),O(),g.args.shouldOpenNow?v({subjectId:u,subjectName:"control",subjectType:l,action:p}):t.add({...k,action:v.bind(null,{subjectId:u,subjectName:"control",subjectType:l,action:p})});return}case E.openURI.trim().toLowerCase():{w(g.args.isDetachContainer,I.bind(null,{subjectId:u,subjectName:"control"})),O(),g.args.shouldOpenNow?T({subjectId:u,subjectName:"control",subjectType:l,action:g,payload:{URI:p.args.uri}}):(t.add({...k,action:T.bind(null,{subjectId:u,subjectName:"control",subjectType:l,action:g,payload:{URI:p.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(h.errors,new M(1,1,{message:"Unexpected control event"}));return}},a=({action:p,container:{id:l,endTime:u},branches:f=[],isEOV:m=!1,autoSelected:w=!1})=>{let S=it(p,m),A={timestamp:!S.args.shouldOpenNow||m?1/0:u??1/0,priority:"container",initiator:l,actionType:S.type},g=i.emit.bind(i,h.interactives,{subjectId:l,subjectName:"container",type:b.actionChoice,actionType:S.type,payload:S.args});switch(S.type.trim().toLowerCase()){case E.setNextBranch.trim().toLowerCase():{let k=f.find(D=>D.id===S.args.branchId);if(!k)return;g(),t.add({...A,action:R.bind(null,{subjectId:l,subjectName:"container",action:S,payload:{chapterId:k.chapterId,autoSelect:w}})}),n?.();return}case E.setMaxWeightBranch.trim().toLowerCase():return;case E.setMinWeightBranch.trim().toLowerCase():return;case E.setRandomBranch.trim().toLowerCase():return;case E.setWeightlessRandomBranch.trim().toLowerCase():return;case E.continuePlayback.trim().toLowerCase():{g(),t.add({...A,action:v.bind(null,{subjectId:l,subjectName:"container",action:S})});return}case E.openURI.trim().toLowerCase():{g(),t.add({...A,action:T.bind(null,{subjectId:l,subjectName:"container",action:S,payload:{URI:p.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(h.errors,new M(1,1,{message:"Unexpected container event"}));return}};function o({container:p,branches:l,isEOV:u=!1}){let f=Ye(p.events);if(f){let m=it(f.action,u);i.emit(h.interactives,{subjectId:p.id,subjectName:"container",type:b.actionChoice,actionType:m.type,payload:m.args}),t.add({timestamp:u?1/0:p.endTime??1/0,priority:"container",initiator:p.id,actionType:E.expect,action:C.bind(null,{subjectId:p.id,subjectName:"container"})}),r.isExpect=!0}else for(let m of p.events??[])a({action:m.action,container:p,branches:l,isEOV:u})}let d=({chapterId:p,action:l,branches:u=[]})=>{let f=i.emit.bind(i,h.interactives,{subjectId:p,subjectName:"chapter",type:b.actionChoice,actionType:l.type,payload:l.args});switch(l.type.trim().toLowerCase()){case E.setNextBranch.trim().toLowerCase():{let m=u.find(w=>w.id===l.args.branchId);return m?.chapterId?(f(),R.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case E.setWeightlessRandomBranch.trim().toLowerCase():{let m=Ft(u);return m?.chapterId?(f(),R.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case E.setRandomBranch.trim().toLowerCase():{let m=jt(u);return m?.chapterId?(f(),R.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case E.setMaxWeightBranch.trim().toLowerCase():{let m=Nt(u);return m?.chapterId?(f(),R.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case E.setMinWeightBranch.trim().toLowerCase():{let m=Lt(u);return m?.chapterId?(f(),R.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case E.continuePlayback.trim().toLowerCase():return f(),v.bind(null,{subjectId:p,subjectName:"chapter",action:l});case E.openURI.trim().toLowerCase():return f(),T.bind(null,{subjectId:p,subjectName:"chapter",action:l,payload:{URI:l.args.uri}});default:console.error("Unexpected chapter event"),i.emit(h.errors,new M(1,1,{message:"Unexpected chapter event"}));return}};function y(p){let l=Ye(p.events);if(l){if(F(p))return;i.emit(h.interactives,{subjectId:p.id,subjectName:"chapter",type:b.actionChoice,actionType:l.action.type,payload:l.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:E.expect,action:C.bind(null,{subjectId:p.id,subjectName:"chapter"})})}else p.events?.forEach(u=>{let f=d({chapterId:p.id,action:u.action,branches:p.branches});f&&t.add({timestamp:1/0,priority:"chapter",initiator:p.id,actionType:u.action.type,action:f})})}let C=({subjectId:p,subjectName:l})=>{e.pause(),i.emit(h.interactives,{subjectId:p,subjectName:l,type:b.actionExecution,actionType:E.expect})},I=({subjectId:p,subjectName:l})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(h.interactives,{subjectId:p,subjectName:l,type:b.actionExecution,actionType:"after-expect"})},v=({subjectId:p,subjectName:l,subjectType:u,action:f})=>{i.emit(h.interactives,{subjectId:p,subjectName:l,subjectType:u,type:b.actionExecution,actionType:f.type})},R=({subjectId:p,subjectName:l,subjectType:u,action:f,payload:m})=>{m.behaviour="change-chapter",i.emit(h.interactives,{subjectId:p,subjectName:l,subjectType:u,type:b.actionExecution,actionType:f.type,payload:m})},x=({subjectId:p,subjectName:l,subjectType:u,action:f,payload:m})=>{m.behaviour="change-manifest",i.emit(h.interactives,{subjectId:p,subjectName:l,subjectType:u,type:b.actionExecution,actionType:f.type,payload:m})},T=({subjectId:p,subjectName:l,subjectType:u,action:f,payload:m})=>{if(!m.URI)return;let w=window.open(m.URI,"_blank","noopener,noreferrer");w&&(w.opener=null),i.emit(h.interactives,{subjectId:p,subjectName:l,subjectType:u,type:b.actionExecution,actionType:f.type})};return{onControlEvent:c,onContainerEvent:a,onChapterEvent:d,onExpectEvent:C,expectEventHandler:I,setManifestChapterEvents:y,setManifestContainerEvents:o,stopExpect:s,state:r}};import{Subscription as vi,ValueSubject as ie}from"@vkontakte/videoplayer-shared";var nt=(i,e)=>{let t={};return i.map(n=>{if(!t[n]){let r=e.chapters.find(c=>c.id===n);if(!r)return null;let s=e.media.videos.find(c=>r.videoId===c.id);if(!s)return null;t[n]=Ht(s)}return t[n]}).filter(Boolean)},fi=i=>{for(let e of i.variants)if(yi(e)&&"payload"in e)return e.payload.id},yi=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",Ht=i=>{let e=fi(i);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},gi=(i,e)=>{for(let t of i.media.videos)if(e===Ht(t)){for(let n of i.chapters)if(n.videoId===t.id)return n.id;return}},Dt=(i,e)=>i.reduce((t,n)=>{let r=gi(e,n);return r?[...t,r]:t},[]);var ne=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:n,historyApi:r,settings:s}){this.state={history$:new ie([]),hasPrevChapter$:new ie(!1),prevChapter$:new ie(null),isInitialChapter$:new ie(!1),isGoBackLimited$:new ie(!1)};this.#e=null;this.#a=!1;this.#t=null;this.#p=null;this.#r=null;this.#s=null;this.#i=null;this.#o=new vi;this.#l=!1;this.#c=0;this.#r=t,this.#i=e,this.#s=n,this.#e=r,this.#n=s,this.state.history$&&this.#o&&this.#o?.add(this.state.history$.subscribe(c=>{this.state.prevChapter$.next(c.at(-2)||null),this.state.hasPrevChapter$.next(c.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#t?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#c===this.#n.maxLength-1)}))}#e;#n;#a;#t;#p;#r;#s;#i;#o;#l;#c;async setManifest(e){!this.#s||!this.#i||(this.#t=e,await this.getProjectHistory(),await this.#s.setChapter({chapterId:this.getInitialChapterId(),pushToHistory:!1}),this.#a||(this.#a=!0,this.#i.emit(h.historyInited,{initChapterId:this.getInitialChapterId()})))}get inited(){return this.#a}async updateHistory(e,t=!0){if(!this.#t)return;this.#l?(this.#l=!1,this.#c++):this.#c=0;let n=this.#t,r=e.length-this.#n.maxLength,s=r>0?e.slice(r):e,c=nt(s,n);if(this.#p=c,this.state.history$.next(s),!(!t||!this.#e||!this.#r))try{await this.#e.save(this.#r,c)}catch{this.#i?.emit(h.errors,new M(1,5,"Unable to save interactive history"))}}async goBack(){if(!this.state||!this.#s)return this.#i?.emit(h.errors,new M(1,5,"Cannot go back because HistoryController has not been initialized"));this.#l=!0;let e=this.state.history$.getValue().slice(0,-1),t=e.pop();this.state.history$.next(e),await this.#s.setChapter({chapterId:t,playPrev:!0})}async getProjectHistory(){if(!this.#t||!this.#r)return;let e=this.#t,t=[this.getInitialVideoId()];if(this.#e)try{let r=await this.#e.get(this.#r);r.length&&(t=r)}catch{this.#i?.emit(h.errors,new M(1,5,"Error while trying to fetch data"))}let n=Dt(t,e);this.state.history$.next(n)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#n.initChapterId||this.#t?.metadata.initChapterId}getInitialVideoId(){if(this.#t){let e=this.getInitialChapterId();return nt([e],this.#t).pop()}return null}destroy(){this.#r=null,this.#e=null,this.#s=null,this.#o?.unsubscribe(),this.#o=null,this.#a=!1,this.#i?.emit(h.historyDestroyed),this.#i=null}};var Le=class i{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=i._convertOptions(e,r),this.target.addEventListener(t,n,this.options)}unlisten(){this.type&&this.listener&&this.options&&this.target?.removeEventListener(this.type,this.listener,this.options),this.target=null,this.type=null,this.listener=null,this.options=!1}static _convertOptions(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{let n=new Set(["passive","capture"]),r=Object.keys(t).filter(c=>!n.has(c));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),i._doesSupportObject(e)?t:t.capture||!1}}static{this._supportsObject=void 0}static _doesSupportObject(e){let t=i._supportsObject;if(t===void 0){t=!1;try{let n={},r={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);let s=()=>{};e.addEventListener("test",s,n),e.removeEventListener("test",s,n)}catch{t=!1}i._supportsObject=t}return t||!1}};var Ne=class{constructor(){this.bindingMap=new te}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;let s=new Le(e,t,n,r);this.bindingMap.push(t,s)}listenOnce(e,t,n,r){let s=c=>{this.unlisten(e,t,s),n(c)};this.listen(e,t,s,r)}unlisten(e,t,n){if(!this.bindingMap)return;let r=this.bindingMap.get(t)||[];for(let s of r)s.target===e&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(t,s))}removeAll(){if(!this.bindingMap)return;let e=this.bindingMap.getAll();for(let t of e)t.unlisten();this.bindingMap.clear()}};var Fe=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,n=t.length;for(let r=3;r<n;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 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)}};var je=class{constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.currentVideoDurationMs=1/0;this._containerTimeFrameShouldReceived=!1;this._endTimeFrameReceived=!1;this._shouldCallSkip=!1;this.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()}};this.onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
7
7
  position: absolute;
8
8
  top: 0;
9
9
  left: 0;
@@ -11,13 +11,13 @@ var pe="1.0.19-dev.c3a364e7.0";function Ht(i,t=1){let e="0",n="0",r="0";return i
11
11
  height: var(--interactive-height);
12
12
  background-color: var(--black);
13
13
  visibility: hidden;
14
- `,this.lastFrameCanvas=new Pt,this.endOffsetMs=e,this._callbacks={onError:n},this.lastFrameCanvas.rootElement.style.cssText=`
14
+ `,this.lastFrameCanvas=new Fe,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),t.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(t){this.currentVideoDurationMs=t}setVideoElement(t){this.lastFrameCanvas.setCanvasImageSource(t)}setCurrentChapter(t){this.currentChapter=t}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(t=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(t=!1);let e=getComputedStyle(this.rootElement),n={width:parseInt(e.getPropertyValue("--interactive-content-width"),10),height:parseInt(e.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,t)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(t){return this.currentVideoDurationMs&&t>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(t){if(this.currentChapter)return this.currentChapter.containers.some(e=>e.controls?.length&&t>=(e.startTime??0)&&t<=Math.min(e.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(t){this._callbacks?.onError?.(t)}};function qe(i=0){return new Promise(t=>{setTimeout(()=>{t(0)},i)})}var Xe=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,historyApi:null,historyParams:null,projectInfo:{},initSeamless:!1,lastFrame:!1,permanentTextControls:!0,config:{historyMaxLength:100,noInteractionEventTimeout:3e4}}),$=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function Pi(){let i=document.createElement("div");return i.style.cssText=`
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(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 Gt(i=0){return new Promise(e=>{setTimeout(()=>{e(0)},i)})}var Wt=Object.freeze({lang:Ei.RU,loaders:{},graph:!1,initSeamless:!1,lastFrame:!1,permanentTextControls:!0,config:{historyMaxLength:100,noInteractionEventTimeout:3e4}});function xi(){let i=document.createElement("div");return i.style.cssText=`
20
20
  position: absolute;
21
21
  top: 0;
22
22
  left: 0;
23
- `,i}var Ft=class{#a=null;#r=null;#h=null;#i=null;#d=null;#n=null;#s=null;#o=null;#t=null;#p=new N(!1);#u=new Set;#l=null;#f=null;#c=null;#e=null;#m=new et;#y=null;state={prevChapter$:new N(null),isInitialChapter$:new N(!1),isFirstChapter$:new N(!0),isEndChapter$:new N(!1),isInteractiveExpectation$:new N(!1),calledByInteractive$:new N(!1),lastChapterChangeWasInitiatedByInteractive$:new N(!1),disabledControls$:new N(!1),interactiveRanges$:new N([]),isInteractiveTime$:new N(!1),statistics$:new N(null)};events={noInteraction$:new ki};constructor(t){this.options={...Xe,...t,config:{...Xe.config,...t.config}},this.#r=[],this.factories=new Map([["choice",bt]]),this.rootElement=Pi(),this.options.parentElement.append(this.rootElement),this.#e=new q,this.#d=new Oi,this.#h=new $t,this.#i=new ot({interactiveController:this,globalEventEmitter:this.#e,videoId:this.options.projectInfo?.videoId,historyApi:this.options.historyApi,settings:{maxLength:this.options.config.historyMaxLength,initChapterId:this.options.initChapterId}}),this.options.lastFrame&&(this.#c=new Bt({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:e=>this.#e.emit(d.errors,new R(1,6,e))})),this.#h.listen(this.rootElement,"mousedown",e=>e.stopPropagation()),this.#h.listen(this.rootElement,"mouseup",e=>e.stopPropagation()),this.#t=new Z(this.options.loaders,e=>this.#e.emit(d.errors,new R(1,3,e))),this.#n=re(this.options.player),this.#s=new wt,this.#o=ae({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#e,removeControllers:this.#g}),this.#a=Be(()=>({player:this.options?.player,parentElement:this.options?.parentElement,fns:this.options?.lastFrame?[()=>{this.#c.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#l=new tt({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:e=>{this.setChapter({chapterId:e}),this.#e.emit(d.graph,{type:nt.watchAgainClicked,chapterId:e})},onError:e=>this.#e.emit(d.errors,new R(1,4,{message:e}))})),this.#x(),this.isFirstChapterFetched=!1,this.appState=$.created}clearHistoryIfEnded=()=>{let t=this.options.player?.info.isEnded$.getValue(),e=this.state.isInteractiveExpectation$.getValue(),{chapter:n}=this.getCurrentChapter();t&&j(n)&&!e&&this.#i.updateHistory([]),window.removeEventListener("beforeunload",this.clearHistoryIfEnded)};#x(){this.#e.on(d.historyInited,async({videosInfo:t=[]})=>{this.options.initSeamless&&(await this.#S(),this.updateGraphVideosInfo(t))}),this.#e.on(d.interactives,async t=>{if(t.type===C.actionExecution){if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),t.payload?.behaviour==="change-chapter"){let{chapterId:n}=t.payload;this.setChapter({chapterId:n}),this.state.isFirstChapter$.getValue()&&this.state.isFirstChapter$.next(!1)}if(t.payload?.behaviour==="change-manifest"){let{manifestURL:n}=t.payload;this.setManifest(n)}let e=t.type==="action-execution";e&&t.actionType==="expect"?this.state.isInteractiveExpectation$.next(!0):e&&t.actionType==="after-expect"&&this.state.isInteractiveExpectation$.next(!1)}t.type===C.containerRemoved&&this.#A(t.subjectId)}),this.#e.on(d.manifestChanged,()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})}#T=({statistics:t,...e})=>{if(t){let{statSubscription:n,oneStat:r}=t;n.add(r.attachToInteractive(this.getStatEvents())),this.state.statistics$.next(t)}this.#e.emit(d.playerChanged,e)};async#S(){this.#f=ne(this),this.#f.on(kt.activePlayerChanged,this.#T),this.#f.init()}getStatEvents(){return{click$:new Ze(t=>{this.#e.on(d.graph,({type:e,visibility:n})=>{e==="visibility"&&t.next(n?ct.GRAPH_SHOW:ct.GRAPH_HIDE),e==="watchAgainClicked"&&t.next(ct.WATCH_AGAIN)}),this.#e.on(d.interactives,({type:e,subjectName:n,subjectType:r})=>{e!=="action-choice"||n!=="control"||(r==="Button"&&t.next(ct.NEXT_BUTTON),r==="Area"&&t.next(ct.NEXT_AREA))})}),nextMovie$:new Ze(t=>{this.#e.on(d.playerChanged,({config:e})=>{e?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&t.next(e.unitedVideoId)})})}}setPlayer(t){this.#b(),this.options.player=t,this.#m.setPlayer(this.options.player),this.#n?this.#n.setPlayer(this.options.player):this.#n=re(this.options.player),this.#o=ae({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#e,removeControllers:()=>this.#g(!1)}),this.appState===$.initiated&&(this.#C(),this.#v(this.#t.chapter))}async setManifest(t){this.#b(),this.isFirstChapterFetched=!1;let e=await this.#t.setManifest(t);return this.#l&&await this.#l.handleManifestChange(e.manifest),await this.#i.setManifest(e.manifest),this.#e.emit(d.manifestChanged,{manifest:e.manifest}),this.#v(this.#t.chapter),e.manifest}setVisitedChapters(t){Array.isArray(t)&&this.#l?.setVisitedChapters(t)}updateGraphVideosInfo(t){Array.isArray(t)&&this.#l?.updateVideosInfo(t)}async setChapter({chapterId:t,pushToHistory:e=!0}={}){this.#b(),this.#c&&this.isFirstChapterFetched&&(this.#c.draw(),this.#c.show()),ji.isSafari&&await qe(35);let n=this.state.isEndChapter$.getValue()&&this.getCurrentManifest().metadata.initChapterId===t,{chapter:r,media:s,graph:o}=await(t?this.#t.setNext(t):this.#t.setInitial());return(!t||n)&&this.state.isFirstChapter$.next(!0),e&&this.#R(r.id),this.state.isInitialChapter$.next(this.#t.isInitialChapter()),this.state.isEndChapter$.next(this.#t.isEndChapter()),this.#l&&this.#l.handleChapterChange(o),this.#c?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(d.chapterChanged,{chapter:r,media:s,graph:o}),this.#v(this.#t.chapter),this.#u=new Set,this.isFirstChapterFetched=!0,{chapter:r,media:s,graph:o}}toggleGraphView(t=!0){this.#l&&(t?(this.#l.show(),this.#p.next(!1)):(this.#l.hide(),this.#E()),this.#e.emit(d.graph,{type:nt.visibility,visibility:t}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.appState===$.created&&(this.#a.resizeObserver.observe(this.options.fullscreenTargetElement),this.#C(),this.appState=$.initiated,this.#v(this.#t.chapter))}#b(){this.appState===$.ready&&(this.#g(),this.#r=[],this.#s.release(),this.#n?.release(),this.appState=$.initiated,this.#p.next(!1),this.#I())}#L=()=>{this.#s.fns.forEach(n=>n());let t=this.options.player.info.position$.getValue()*1e3,e=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(t));for(let n of e){this.#n.remove({timestamp:1/0,priority:"container",initiator:n.id});for(let r of n.controls)this.#n.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#r.find(r=>r.container.container.id===n.id).reset()}};#w=()=>{this.#a.calc(),this.#s.requestAnimation()};#_(t){(!this.#l||this.#l.isHidden)&&this.#E();let e=t*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>e>=s[1]);if(r){let s=r.range.join("-");this.#u.has(s)||(this.#u.add(s),this.#e.emit(d.interactives,{type:C.rangeEnded,payload:r,visibility:!0}))}}deadEndCheck(){return!(this.#n?.getPreparedToExecActions()??[]).some(n=>n.actionType===I.setNextBranch)}allControlsAreRemoved(){return!this.#r.some(e=>!e.container.isRemoved)}isEndedExpectation(){if(!this.options?.player||!this.#r)return!1;let t=this.options.player.info.position$.getValue(),e=this.options.player.info.duration$.getValue();return t===e&&this.#r.some(n=>{let r=n.container.container;return!r.isRemoved&&r.endTime===null&&z(r.events)})}#C(){window.removeEventListener("beforeunload",this.clearHistoryIfEnded),this.#d.unsubscribe(),window.addEventListener("beforeunload",this.clearHistoryIfEnded),this.#d.add(this.options.player.events.started$.pipe(Ni()).subscribe(this.#w)).add(this.options.player.events.playing$.subscribe(this.#s.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#s.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#_.bind(this))).add(this.#t.prevChapter$.subscribe(t=>this.state.prevChapter$.next(t))).add($i({position:this.options.player.info.position$,interactiveRanges:this.state.interactiveRanges$,isInteractiveExpectation:this.state.isInteractiveExpectation$}).subscribe(({position:t,interactiveRanges:e,isInteractiveExpectation:n})=>{let r;if(n)r=!0;else{let c=t*1e3;r=!!e?.find(({range:[y,g],subjects:E})=>y<c&&c<g&&E.length)}r!==this.state.isInteractiveTime$.getValue()&&this.state.isInteractiveTime$.next(r);let s=this.#y!==null,a=this.options.player.info.playbackState$.getValue()==="playing"||n;r&&!s&&a?this.#y=setTimeout(()=>{this.events.noInteraction$.next()},this.options.config.noInteractionEventTimeout):s&&!a&&this.#I()})),this.options.lastFrame&&this.#d.add(this.options.player.info.duration$.subscribe(t=>{this.#c.setVideoDuration(t*1e3)})).add(this.options.player.experimental.element$.subscribe(t=>{t&&this.#c.setVideoElement(t)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#c.reset(),setTimeout(()=>{this.#c.hide(),this.#c.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#c.onSeek))}#g=(t=!0)=>{this.#r.forEach(e=>{!t&&e.isPermanentText||(this.#s.removeFn(e.whilePlaying),e.destroy())})};#v(t){this.#t.chapter&&this.appState===$.initiated&&(this.#o.setManifestChapterEvents(t),this.#r=this.#V(t),this.#n.containersEventsCallState.setData(t.containers),this.#m.setContainers(this.#r.map(e=>e.container.container).filter(e=>!Lt(e.controls))),this.options.lastFrame&&this.#s.addFn(()=>{this.#c.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.state.interactiveRanges$.next(this.getInteractiveRanges()),this.appState=$.ready)}#V(t){return t?.containers?.reduce((e,n)=>{let r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){let o=new Nt({player:this.options.player,container:s(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#o,interactiveEvents:this.#n,globalEventEmitter:this.#e,ignoreContainerEvent:()=>Le(n,this.#r),permanentTextControls:this.options.permanentTextControls,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.#m.deleteContainer(n.id)}});return this.#s.addFn(o.whilePlaying,!0),[...e,o]}return[...e]},[])??[]}#E(){if(this.state.isInteractiveExpectation$.getValue()){this.#p.next(!1);return}let e=this.#p.getValue(),n=!!this.#m.getNextInteractiveTime();(n&&!e||!n&&e)&&this.#p.next(!e)}#M(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}#R(t){if(this.#M(),!this.#i.inited)return;let e=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),n=this.state.prevChapter$.getValue(),r=(n&&j(n)&&At(n))??!1,s=this.#t.manifest.metadata.initChapterId===t,o=this.#i.state.history$.getValue();if(s||r&&e){this.#i.updateHistory([t]);return}o.at(-1)!==t&&this.#i.updateHistory([...o,t])}#A=t=>{let{interactiveRanges$:e}=this.state,r=e.getValue().map(s=>({...s,subjects:s.subjects.filter(o=>o!==t)}));e.next(r)};#I=()=>{this.#y&&(clearTimeout(this.#y),this.#y=null)};playPrevChapter(){this.#i?.goBack()}setDisabledControls(t){this.state.disabledControls$.next(t)}isSupport(t=this.#t.manifest){return Tt(t.metadata.version)}getInitialVideoInfo(){return{videoId:this.#i.getInitialVideoId(),chapterId:this.#i.getInitialChapterId()}}getHistoryState(){return this.#i.state}getIsSeekable(){return this.#p}getInteractiveRanges(){return Oe(this.#t.chapter?.containers)}getNextInteractiveStartTime(t){return this.#m.getNextInteractiveTime(t)}getChapterBranches(t){return this.#t.getBranches(t)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(t,e){this.factories.set(t.trim().toLowerCase(),e)}removeFactory(t){this.factories.delete(t.trim().toLowerCase())}on(...t){return this.#e.on(...t),this}off(...t){return this.#e.off(...t),this}once(...t){return this.#e.once(...t),this}destroy(){this.clearHistoryIfEnded(),this.#g(),this.#r=void 0,this.state=void 0,this.#l?.destroy(),this.#l=void 0,this.#f?.removeAll(),this.#f=void 0,this.#a.release(),this.#a=void 0,this.#o=void 0,this.#s.release(),this.#s=void 0,this.#n.release(),this.#n=void 0,this.#t.release(),this.#o=void 0,this.#h.release(),this.#h=void 0,this.#d.unsubscribe(),this.#d=void 0,this.#e.reset(),this.#e=void 0,this.#c?.destroy(),this.#c=void 0,this.rootElement.remove(),this.rootElement=void 0,this.#i.destroy(),this.#i=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.appState=$.destroyed}};var Bi={Container:K,createChoiceContainer:bt,createAreaControl:yt,createButtonControl:vt,createRelativeLayout:ge,getRootEl:pt,classnamesPrefix:M};var la={version:pe};export{R as CustomError,d as EVENT_NAMES,Ft as Interactives,Z as ManifestController,la as SDKInfo,oe as chapterIdsToVKVideoIds,B as compareVersions,Ai as getChapterIdByVkVideoId,Qe as getVKVideoIdByMedia,Mi as getVideoRawIdByMedia,nt as graphEventTypes,At as hasEndTemplate,C as interactivesEventTypes,j as isLastChapter,Tt as isSupportedManifest,Ri as isVKVariantItem,Bi as utils,Ke as vkVideoIdsToChapterIds};
23
+ `,i}var Oe=class{constructor(e){this.subscription=new Ut;this.globalEventEmitter=new xe;this.animation=new Te;this.eventManager=new Ne;this.seekToInteractiveController=new X;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=xi();this.factories=new Map([["choice",ye]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new Ut;this.graph=null;this.lastFrame=null;this.appState=0;this.state={prevChapter$:new L(null),isInitialChapter$:new L(!1),isFirstChapter$:new L(!0),isEndChapter$:new L(!1),isInteractiveExpectation$:new L(!1),calledByInteractive$:new L(!1),lastChapterChangeWasInitiatedByInteractive$:new L(!1),disabledControls$:new L(!1),interactiveRanges$:new L([]),isInteractiveTime$:new L(!1),statistics$:new L(null),isSeekable$:new L(!1)};this.events={noInteraction$:new rt,graphVisibilityChanged$:new rt,watchAgainIsClicked$:new rt};this.clearHistoryIfEnded=()=>{let e=this.player?.info.isEnded$.getValue(),t=this.state.isInteractiveExpectation$.getValue(),{chapter:n}=this.getCurrentChapter();e&&n&&F(n)&&!t&&this.historyController.updateHistory([]),window.removeEventListener("beforeunload",this.clearHistoryIfEnded)};this.handleSeamlessPlayerChanged=e=>{if(!e)return;let{statistics:t,...n}=e;if(t){let{statSubscription:r,oneStat:s}=t;r.add(s.attachToInteractive(this.getStatEvents())),this.state.statistics$.next(t)}this.globalEventEmitter.emit(h.playerChanged,n)};this.onPlaybackStarted=()=>{this.resizeManager?.calc(),this.animation.requestAnimation()};this.removeControllers=(e=!0)=>{this.gameControllers.forEach(t=>{!e&&t.isPermanentText||(this.animation.removeFn(t.whilePlaying),t.destroy())})};this.completeInteractiveRange=e=>{let{interactiveRanges$:t}=this.state,r=t.getValue().map(s=>({...s,subjects:s.subjects.filter(c=>c!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};this._options={...Wt,...e,config:{...Wt.config,...e.config}},this._options.parentElement.append(this.rootElement),this.historyController=new ne({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:t=>this.globalEventEmitter.emit(h.errors,new M(1,6,t))})),this.eventManager.listen(this.rootElement,"mousedown",t=>t.stopPropagation()),this.eventManager.listen(this.rootElement,"mouseup",t=>t.stopPropagation()),this.manifestController=new W(this._options.loaders,t=>this.globalEventEmitter.emit(h.errors,new M(1,3,t))),this.resizeManager=Rt(()=>({player:this.player,parentElement:this._options?.parentElement,fns:this._options?.lastFrame?[()=>{this.lastFrame?.updateCanvasDimensions(!0)}]:[]})),this._options.graph&&(this.graph=new q({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.globalEventEmitter.emit(h.graph,{type:ee.watchAgainClicked,chapterId:t}),this.events.watchAgainIsClicked$.next(t)},onError:t=>this.globalEventEmitter.emit(h.errors,new M(1,4,{message:t}))})),this.initSubscriptions()}initSubscriptions(){this.globalEventEmitter.on(h.historyInited,async({videosInfo:e=[]})=>{this._options.initSeamless&&(await this.initSeamless(),this.updateGraphVideosInfo(e))}),this.globalEventEmitter.on(h.interactives,async e=>{if(e.type===b.actionExecution){if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){let{chapterId:n}=e.payload;this.setChapter({chapterId:n}),this.state.isFirstChapter$.getValue()&&this.state.isFirstChapter$.next(!1)}if(e.payload?.behaviour==="change-manifest"){let{manifestURL:n}=e.payload;this.setManifest(n)}let t=e.type==="action-execution";t&&e.actionType==="expect"?this.state.isInteractiveExpectation$.next(!0):t&&e.actionType==="after-expect"&&this.state.isInteractiveExpectation$.next(!1)}e.type===b.containerRemoved&&this.completeInteractiveRange(e.subjectId)}),this.globalEventEmitter.on(h.manifestChanged,()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})}async initSeamless(){this.seamlessController=tt(this),this.seamlessControllerSubs.add(this.seamlessController.activePlayerChanged.subscribe(this.handleSeamlessPlayerChanged)),await this.seamlessController.init()}handlePositionChange(e){(!this.graph||this.graph.isHidden)&&this.checkIfSeekable();let t=e*1e3,r=this.getInteractiveRanges().reverse().find(({range:s})=>t>=s[1]);if(r){let s=r.range.join("-");this.endedRanges.has(s)||(this.endedRanges.add(s),this.globalEventEmitter.emit(h.interactives,{type:b.rangeEnded,payload:r,visibility:!0}))}}registerVideoEvents(){this.player&&(window.removeEventListener("beforeunload",this.clearHistoryIfEnded),this.subscription.unsubscribe(),window.addEventListener("beforeunload",this.clearHistoryIfEnded),this.subscription.add(this.player.events.started$.pipe(Ii()).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(Ci({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 o=e*1e3;r=!!t.find(({range:[y,C],subjects:I})=>y<o&&o<C&&I.length)}r!==this.state.isInteractiveTime$.getValue()&&this.state.isInteractiveTime$.next(r);let s=!!this.noInteractionTimeout,a=this.player?.info.playbackState$.getValue()==="playing"||n;r&&!s&&a?this.noInteractionTimeout=window.setTimeout(()=>{this.events.noInteraction$.next()},this._options.config.noInteractionEventTimeout):s&&!a&&this.clearNoInteractionTimeout()})),this._options.lastFrame&&this.subscription.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.filterGameControllers(e),this.interactiveEvents?.containersEventsCallState.setData(e.containers),this.seekToInteractiveController.setContainers(this.gameControllers.map(t=>t.container.container).filter(t=>!Ve(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)}filterGameControllers(e){let t=[];return e.containers.forEach(n=>{let r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){let c=new Re({player:this.player,container:s(n,this.rootElement),branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEventEmitter:this.globalEventEmitter,ignoreContainerEvent:()=>xt(n,this.gameControllers),permanentTextControls:this._options.permanentTextControls,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(n.id)}});this.animation.addFn(c.whilePlaying,!0),t.push(c)}}),t}checkIfSeekable(){if(this.state.isInteractiveExpectation$.getValue()){this.state.isSeekable$.next(!1);return}let t=this.state.isSeekable$.getValue(),n=!!this.seekToInteractiveController.getNextInteractiveTime();(n&&!t||!n&&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(),n=this.state.prevChapter$.getValue(),r=(n&&F(n)&&ke(n))??!1,s=this.manifestController.manifest?.metadata.initChapterId===e,c=this.historyController.state.history$.getValue();if(s||r&&t){this.historyController.updateHistory([e]);return}c.at(-1)!==e&&this.historyController.updateHistory([...c,e])}reset(){this.appState===2&&(this.removeControllers(),this.gameControllers=[],this.animation.release(),this.interactiveEvents?.release(),this.appState=1,this.state.isSeekable$.next(!1),this.clearNoInteractionTimeout())}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.globalEventEmitter.emit(h.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=Mt(this.player),this.selectBranches=_t({player:this.player,interactiveEvents:this.interactiveEvents,globalEventEmitter:this.globalEventEmitter,removeControllers:()=>this.removeControllers(!1)}),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()),bi.isSafari&&await Gt(35);let r=!n&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e,{chapter:s,media:c,graph:a}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),s&&(t&&this.pushChapterToHistory(s.id),this.state.isInitialChapter$.next(this.manifestController.isInitialChapter()),this.state.isEndChapter$.next(this.manifestController.isEndChapter()),this.graph&&this.graph.handleChapterChange(s),this.lastFrame?.setCurrentChapter(s),this.globalEventEmitter.emit(h.chapterChanged,{chapter:s,media:c,graph:a}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new zt(e=>{this.globalEventEmitter.on(h.graph,({type:t,visibility:n})=>{t==="visibility"&&e.next(n?re.GRAPH_SHOW:re.GRAPH_HIDE),t==="watchAgainClicked"&&e.next(re.WATCH_AGAIN)}),this.globalEventEmitter.on(h.interactives,({type:t,subjectName:n,subjectType:r})=>{t!=="action-choice"||n!=="control"||(r==="Button"&&e.next(re.NEXT_BUTTON),r==="Area"&&e.next(re.NEXT_AREA))})}),nextMovie$:new zt(e=>{this.globalEventEmitter.on(h.playerChanged,({config:t})=>{t?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&e.next(t.unitedVideoId)})})}}toggleGraphView(e=!0){this.graph&&(e?(this.graph.show(),this.state.isSeekable$.next(!1)):(this.graph.hide(),this.checkIfSeekable()),this.globalEventEmitter.emit(h.graph,{type:ee.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(n=>n.actionType===E.setNextBranch)}allControlsAreRemoved(){return!this.gameControllers.some(t=>!t.container.isRemoved)}isEndedExpectation(){if(!this.player||!this.gameControllers)return!1;let e=this.player.info.position$.getValue(),t=this.player.info.duration$.getValue();return e===t&&this.gameControllers.some(n=>{let r=n.container.container;return!n.container.isRemoved&&r.endTime===null&&H(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&Ee(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 wt(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.removeControllers(),this.gameControllers=[],this.graph?.destroy(),this.seamlessControllerSubs.unsubscribe(),this.seamlessController?.removeAll(),this.resizeManager?.release(),this.animation.release(),this.interactiveEvents?.release(),this.manifestController.release(),this.eventManager.release(),this.subscription.unsubscribe(),this.globalEventEmitter.reset(),this.lastFrame?.destroy(),this.rootElement.remove(),this.historyController.destroy(),this.isFirstChapterFetched=!1,this.appState=3}};var Ti={Container:U,createChoiceContainer:ye,createAreaControl:de,createButtonControl:me,getRootEl:oe,classnamesPrefix:P};var Fs={version:ot};export{Ie as ControlTypes,M as CustomError,h as EVENT_NAMES,E as EventActionTypes,Oe as Interactives,W as ManifestController,Fs as SDKInfo,nt as chapterIdsToVKVideoIds,Ke as compareVersions,gi as getChapterIdByVkVideoId,Ht as getVKVideoIdByMedia,fi as getVideoRawIdByMedia,ee as graphEventTypes,ke as hasEndTemplate,b as interactivesEventTypes,Mn as isAreaControl,An as isButtonControl,F as isLastChapter,Ee as isSupportedManifest,Ce as isTextControl,yi as isVKVariantItem,vt as isValidManifest,bt as migrateManifestToLatestVersion,Ti as utils,Dt as vkVideoIdsToChapterIds};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.19-dev.c3a364e7.0",
3
+ "version": "1.0.19-dev.d432d6cd.0",
4
4
  "author": "vk.com",
5
5
  "description": "Movika interactive SDK",
6
6
  "homepage": "https://vk.com",
@@ -49,10 +49,10 @@
49
49
  "**/*.d.ts"
50
50
  ],
51
51
  "dependencies": {
52
- "@interactiveplatform/movika-graph-editor": "^1.11.0",
53
- "@vkontakte/videoplayer-core": "^2.0.110",
54
- "@vkontakte/videoplayer-shared": "^1.0.42",
55
- "@vkontakte/videoplayer-statistics": "^1.0.57",
52
+ "@interactiveplatform/movika-graph-editor": "^1.23.2-dev.0",
53
+ "@vkontakte/videoplayer-core": "2.0.111-dev.91072aa3.0",
54
+ "@vkontakte/videoplayer-shared": "1.0.43-dev.cf4d6598.0",
55
+ "@vkontakte/videoplayer-statistics": "1.0.58-dev.dbe794fb.0",
56
56
  "uuid": "^9.0.0"
57
57
  }
58
58
  }
package/types/index.d.ts CHANGED
@@ -1,8 +1,7 @@
1
- export { EVENT_NAMES, Interactives, utils, graphEventTypes, interactivesEventTypes, isLastChapter, hasEndTemplate, } from './modules/Interactives';
2
- export type { InteractiveRange, VideoInfo } from './modules/Interactives';
1
+ export { EVENT_NAMES, Interactives, utils, graphEventTypes, interactivesEventTypes, isLastChapter, hasEndTemplate, InteractiveProjectInfo, } from './modules/Interactives';
2
+ export type { InteractiveRange } from './modules/Interactives';
3
3
  export { ManifestController } from './modules/ManifestController';
4
- export type { Container, Chapter, Manifest, ManifestVideo, ManifestVideoVariant, Media, Metadata } from './movika.core/manifest';
5
- export { isSupportedManifest } from './movika.core/manifest';
4
+ export * from './manifest';
6
5
  export { compareVersions } from './utils/compareVersions';
7
6
  export { CustomError } from './utils/Error';
8
7
  export * from './utils/chapterHelpers';
@@ -0,0 +1,3 @@
1
+ export type { ChapterContainer, ChapterContainer as Container, Chapter, Control, Manifest, ManifestVideo, ManifestVideoVariant, Media, Metadata, VideoInfo, VideoId, CustomManifestVideoVariant, Extension, AnyManifest, AnyControl, GraphEditChapter, GraphViewChapter, ChapterBranch, Standard, ControlLayoutParams, ControlEvent, ContainerEvent, ChapterEvent, } from '@interactiveplatform/movika-graph-editor';
2
+ export { isSupportedManifest, ControlTypes, EventActionTypes, migrateManifestToLatestVersion, compareVersions, } from '@interactiveplatform/movika-graph-editor';
3
+ export * from './utils';
@@ -0,0 +1,11 @@
1
+ import { EventActionTypes, type AnyManifest, type AnyControl } from '../manifest';
2
+ /**
3
+ * checks manifest object validity
4
+ * @param manifest - manifest to check
5
+ * @returns true is valid, false is invalid
6
+ */
7
+ export declare const isValidManifest: (manifest: AnyManifest) => boolean;
8
+ export declare const isTextControl: (controlItem: AnyControl) => boolean;
9
+ export declare const isButtonControl: (controlItem: AnyControl) => boolean;
10
+ export declare const isAreaControl: (controlItem: AnyControl) => boolean;
11
+ export type EventActionKeys = keyof typeof EventActionTypes;
@@ -1,13 +1,18 @@
1
1
  import { type InterfaceLanguage } from '@vkontakte/videoplayer-shared';
2
2
  import type { GraphEditor } from '@interactiveplatform/movika-graph-editor';
3
- import type { Chapter, LatestManifest as Manifest } from '../../movika.core/manifest';
3
+ import type { Chapter, Manifest, VideoInfo } from '../../manifest';
4
4
  interface GraphOptions {
5
- lang: InterfaceLanguage;
6
- root: HTMLDivElement;
5
+ lang: InterfaceLanguage | string;
6
+ root: HTMLElement;
7
7
  onError: (msg: string) => void;
8
8
  onOpenPreviewClick: (chapterId: string) => void;
9
9
  visitedChapters?: string[];
10
10
  }
11
+ type Coordinates = Nullable<{
12
+ x: number;
13
+ y: number;
14
+ value: number;
15
+ }>;
11
16
  export declare class Graph {
12
17
  isHidden: boolean;
13
18
  currentManifestId: Nullable<string>;
@@ -17,11 +22,7 @@ export declare class Graph {
17
22
  onError: GraphOptions['onError'];
18
23
  lang: GraphOptions['lang'];
19
24
  zoom: number;
20
- lastZoomInfo: Nullable<{
21
- x: number;
22
- y: number;
23
- value: number;
24
- }>;
25
+ lastZoomInfo: Coordinates;
25
26
  isReady: boolean;
26
27
  ngEditor: Nullable<GraphEditor>;
27
28
  ngEditorSize: Nullable<{
@@ -30,18 +31,21 @@ export declare class Graph {
30
31
  }>;
31
32
  graphWrapperElement: HTMLDivElement;
32
33
  resizeObserver: ResizeObserver;
34
+ private manifest;
33
35
  constructor(options: GraphOptions);
34
36
  init({ root, onOpenPreviewClick, onError, lang, visitedChapters }: GraphOptions): void;
37
+ private handleZoomChange;
35
38
  onResize: (entries: ResizeObserverEntry[]) => void;
36
39
  getNextPoint(ngEditorSize?: Nullable<{
37
40
  width: number;
38
41
  height: number;
39
- }>): [number, number];
42
+ }>): Nullable<[number, number]>;
40
43
  handleChapterChange: (chapter: Chapter) => void;
41
- handleManifestChange: (manifest: Manifest, visitedChapters?: string[]) => Promise<void>;
44
+ handleManifestChange: (manifest: Manifest, visitedChapters?: string[]) => void;
42
45
  setVisitedChapters(chapterIds: string[]): void;
43
- updateVideosInfo(videosInfo: any): void;
44
- show(): void;
46
+ updateVideosInfo(videosInfo: VideoInfo[]): void;
47
+ show(): Promise<void>;
48
+ private initNgEditor;
45
49
  hide(): void;
46
50
  destroy(): void;
47
51
  }