@vkontakte/videoplayer-interactive 1.0.31-dev.684e92f5.0 → 1.0.31-dev.aa15be9d.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/evergreen.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.31-dev.684e92f5.0
3
- * Tue, 11 Feb 2025 09:26:19 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.31-dev.aa15be9d.0
3
+ * Tue, 11 Feb 2025 10:19:27 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-31/doc/
5
5
  */
6
- var ct="1.0.31-dev.684e92f5.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 O="interactive",qt="interactive-controls-container",pe=()=>document.querySelector(`.${qt}`),lt=.4,P={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},pt=(n=>(n.top="flex-start",n.bottom="flex-end",n.center="center",n))(pt||{}),ht=(n=>(n.start="flex-start",n.end="flex-end",n.center="center",n))(ht||{}),dt=(n=>(n.start="left",n.end="right",n.center="center",n))(dt||{}),he=({target:i,props:e})=>{i.style.alignItems=(e?.gravityVertical&&pt[e.gravityVertical])??"center",i.style.justifyContent=(e?.gravityHorizontal&&ht[e.gravityHorizontal])??"center",i.style.textAlign=(e?.alignment&&dt[e.alignment])??"center"},de=({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},ue=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Be(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},me=({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})`},Q=({target:i,layoutParams:e,fallback:t})=>{let n=e.angle??t.angle;n=n&&n*-1,i.style.transform=`rotate(${n}rad)`};var H=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(`${O}-control-container-${this.control.id}`),e(t,this.control.layoutParams);let n=(this.control.layoutParams.innerSizesDependOn??P.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",D=(n=>(n.AREA=`${_e}_area`,n.TEXT=`${_e}_text`,n.BUTTON=`${_e}_bttn`,n))(D||{});var fe=i=>{if(i.type.trim().toLowerCase()==="area")return new He(i)},He=class extends H{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(`${O}-${this.control.id}`),n.setAttribute("data-testid",D.AREA),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",ue({target:n,props:this.control.props,fallback:{...P,backgroundColor:"transparent"}}),me({target:n,props:this.control.props,fallback:{...P,borderAlpha:0},dependsOn:this.container.dimensions}),Q({target:n,layoutParams:this.control.layoutParams,fallback:P}),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 ye=i=>{let e=document.createElement("span");switch(i){case"Button":case"button":{let t=document.createElement("div"),n={overflow:"hidden",display:"flex",justifyContent:"center",alignItems:"center"};Object.assign(t.style,n),t.append(e);let r={display:"inline-block",whiteSpace:"pre",textOverflow:"ellipsis",maxWidth:"initial",maxHeight:"100%",wordBreak:"normal"};return Object.assign(e.style,r),t}default:{let t={display:"inline-block",whiteSpace:"break-spaces",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",maxHeight:"100%",wordBreak:"break-all"};return Object.assign(e.style,t),e}}};var ve=i=>{if(i.type.trim().toLowerCase()==="button")return new De(i)},De=class extends H{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(`${O}-${this.control.id}`),n.setAttribute("data-testid",D.BUTTON),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",n.style.fontFamily="inherit",Q({target:n,layoutParams:this.control.layoutParams,fallback:P}),ue({target:n,props:this.control.props,fallback:P}),me({target:n,props:this.control.props,fallback:P,dependsOn:this.container.dimensions}),he({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ye(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;de({target:s,props:this.control.props,fallback:P,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 ut=i=>{if(i.type.trim().toLowerCase()==="text")return new Ue(i)},Ue=class extends H{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("div");n.classList.add(`${O}-${this.control.id}`),n.setAttribute("data-testid",D.TEXT),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.fontFamily="inherit",Q({target:n,layoutParams:this.control.layoutParams,fallback:P}),he({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ye(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;de({target:s,props:this.control.props,fallback:P,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 Ge=class{constructor(e){this.layout=e}},Ce=class extends Ge{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 X=class{constructor(e){this.container=e,this.factories=new Map,this.controls=[],this.setControls()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.setControls()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.setControls()}setControls(){this.controls=this.chooseControls()}chooseControls(){return this.container.controls?.reduce((e,t)=>{let n=t.type.trim().toLowerCase(),r=this.factories.get(n);if(r){let s=r(t);if(s)return[...e,s]}return[...e]},[])||[]}};var ge=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new ze(i,e)},ze=class extends X{constructor(e,t){super(e),this.rootElement=t??pe(),this.layout=new Ce(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",ve),this.addControlFactory("text",ut),this.addControlFactory("area",fe)}createView(e){let t=document.createElement("div");return t.classList.add(`${O}-${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(e=!1){(!this.isRemoved||e)&&(this.controls.forEach(t=>t.removeListeners()),this.getElement()?.remove(),this.isRemoved=!0)}fakeRemove(){this.isRemoved||(this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${O}-${this.container.id}`)}};import{clientChecker as Tn,combine as xn,InterfaceLanguage as Sn,Observable as Kt,once as An,Subject as $,Subscription as at,ValueSubject as N,fromEvent as Qt}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as ce}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as Yt}from"@vkontakte/videoplayer-shared/evergreen";function Y(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}var U=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,J=i=>U(i,"Object"),be=i=>U(i,"String"),Ee=i=>U(i,"Array"),Ie=i=>U(i,"Number"),mt=i=>U(i,"Function");var We=i=>Ie(i)&&!isNaN(i);var G=i=>J(i)&&Object.keys(i).length===0,Ke=i=>Ee(i)&&!i.length;var ee=(i,e)=>be(i)&&(e?i.trim():i).length;var ft="video_interactive",yt="videoint";var vt=250,te=class{constructor(e){this.handleZoomChange=Y(e=>{this.lastZoomInfo=e},vt);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,!Ie(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=Jt(e),this.resizeObserver=new ResizeObserver(Y(this.onResize,vt)),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 Yt(this.lang,ft,yt)}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 Jt(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 ne=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 h=s.startTime-e;if(h<=r&&(s.endTime&&r<=s.endTime||s.endTime===null)){n=!0;break}r<h&&(t=t===-1?h:Math.min(t,h))}return!n&&t!==-1?t:null}}};import{isSupportedManifest as xe,ContainerTypes as Fi,ControlTypes as Se,EventActionTypes as S,EventTypes as Bi,migrateManifestToLatestVersion as Et,compareVersions as _i}from"@interactiveplatform/movika-manifest";var Ct={metadata:"Object",chapters:"Array"},gt=i=>{if(!J(i))return!1;for(let e in Ct)if(!i[e]||!U(i[e],Ct[e]))return!1;return xe(i.metadata.version)},Te=i=>i.type===Se.Text,Vi=i=>i.type===Se.Button,Mi=i=>i.type===Se.Area,Pi={Choice:"Choice",TextInput:"TextInput"},$i={Button:"Button",Area:"Area",Text:"Text"},Oi={onClick:"onClick",onSuspense:"onSuspense"},bt={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var V=class{constructor(e,t,...n){this.severity=e;this.category=t;this.data=n}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var Ae=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 we=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{mt(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 on}from"@vkontakte/videoplayer-shared/evergreen";var Re=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return en(...this.loaders[e])(t)}};function en(...i){return async function(t){let n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function ie(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function ke({actions:i,errors:e,chapterId:t,...n}){if(t){let r=i.getManifest();if(r){let s=i.getChapter(r.chapters,t);if(s){let h=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return h?{...n,actions:i,errors:e,result:{chapter:s,media:h,graph:a}}:{...n,errors:ie(e,ke.name,"Could not find media"),actions:i}}}}return{...n,errors:ie(e,ke.name,"Could not find chapter"),actions:i}}var Qe=(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 tn=async i=>{try{let e={},t;if(be(i)){t=new URL(i).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(J(i))e=i;else return{};if(!gt(e))return{};let n=e.metadata.media;if(be(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 sn(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function It(i){let{manifest:e,manifestURL:t}=await tn(i);if(!e)throw new Error("Failed on fetch");let n=Et(e);return n.media=nn(n.media,t),delete n.metadata.media,n}function Ve(i,e){if(e)return i.find(t=>t.id===e)}function Xe(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 Ze(i,e){return i.videos.find(t=>t.id===e)}function nn(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{let r="url"in n?n.url:"",s=rn(r,e);return{...n,url:s||r}})}))}}function rn(i="",e){try{return new URL(i,e).href}catch{return""}}function sn(i){return Qe(i,"3.2.0")>=0}var Me=i=>Ee(i)&&!Ke(i),B=i=>i.order==="end",Pe=i=>Ee(i.containers)&&!Ke(i.containers)&&B(i),Tt=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t<(e.startTime??0)},qe=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var z=(i=[])=>i.some(e=>e.action.type==="expect"),Ye=(i=[])=>i.find(e=>e.action.type==="expect"),an=i=>i?.length===1,Z=i=>an(i)&&Te(i[0]);function xt(i,...e){return t=>typeof e[0]=="object"&&typeof t=="object"?i({...e[0],...t}):i(...e,...t)}var St=(i,e)=>{let t=T=>e.find(({container:x})=>x.container.id===T)?.container.isRemoved,n=z(i.events)&&!t(i.id),r=(T,C=!1,x=!1)=>{let l=x?"every":"some";return T.controls[l](o=>{let d=C?T.endTime===i.endTime:!0;return o.events?.[l](u=>u.action?.type===bt.openURI)&&d})},s=T=>T.some(({container:C})=>r(C.container,!0,!1)&&!C.isRemoved),h=T=>T.every(({container:C})=>C.isRemoved?!0:r(C.container,!0,!0)),a=e.filter(({container:T})=>T.container.id!==i.id&&z(T.container.events)&&T.container.endTime===i.endTime&&!T.isRemoved).length,c=T=>T.controls.some(C=>C.events?.some(x=>x.action?.args?.shouldOpenNow)),p=n||a>0,f=s(e),g=r(i),y=h(e),v=n?!1:a>0,M=c(i);return{isExpectTime:p,hasOtherExpect:a>0,hasOpenURIEvent:f,hasOpenURIEventInCurrentContainer:g,isAllOpenURIEventsValid:y,isExpectEventForCurrentContainer:v,hasShouldOpenNowEvent:M}};var q=class extends Re{constructor(t,n){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new on(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:ie},result:null,errors:null,source:t});return n.errors&&this.errorHandler(n.errors),this.manifest=await It(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",ke({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Xe,getChapter:Ve,getMedia:Ze,getByBranches:this.getByBranches.bind(this),addErrorMessage:ie},result:null,errors:null,chapterId:t}));return n.errors&&this.errorHandler(n.errors),n.result&&(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=Ve(this.manifest.chapters,t);if(n){let r=Ze(this.manifest.media,n.videoId),s=Xe(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=Ve(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?B(this.chapter):!1}};import{Player as cn}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as tt,Tracer as ln,ValueSubject as pn}from"@vkontakte/videoplayer-shared/evergreen";var At=i=>{let e=i.variants.find(t=>t.payload?.type==="vk");if(e&&e.payload){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:h=Math.random().toString(),...a}){let c=i.get(s),p={...a};return c?c[h]=p:i.set(s,{[h]:p}),{listId:s,itemId:h,...a}}function t(s){s.player.destroy(),s.container.remove(),s.subscription.unsubscribe(),s.statistics?.oneStat.destroy(),s.statistics?.statSubscription.unsubscribe()}function n(s,h){let a=i.get(s);if(!a)throw Error("Can't remove. Not find.");if(h){let c=a[h];c&&t(c),delete a[h],Object.keys(a).length||i.delete(s)}else{for(let c of Object.values(a))t(c);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 re=(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 hn=2;function nt(i){let e=Je(),t=new tt,n={},r=null,s=!1,h,a=new pn(null);i&&c(i);function c(C){r=C}function p(C,x,l){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let d=(e.map.get(C)??{})[x];if(d){n={chapterId:l,listId:C,itemId:x,...d};let u=n.player;n.subscription.add(u.info.currentQuality$.subscribe(m=>{let b=u.info.position$.getValue(),A=u.info.isAutoQualityEnabled$.getValue();if(!(!m||!b||A))for(let R of e.map)Object.values(R[1]).forEach(({player:I})=>{re(I,m)})})).add(u.events.started$.subscribe(()=>{f(x)})),d.container.remove(),r.setPlayer(d.player),s||(r.init(),s=!0),a.next({player:n.player,config:n.config,statistics:n.statistics});return}throw Error("Can't set. Not find.")}async function f(C){if(!r)throw Error("need to set interactive controller");if(G(n)||C!==n.itemId)return;let x=r.getChapterBranches(),l=new Set;for(let o of x)l.has(o.media.id)||(await y({media:o.media,chapterId:o.chapter.id,setAsActive:!1,title:o.chapter.label}),l.add(o.media.id))}async function g({chapter:{id:C},manifestVideo:x}){if(G(n)||!r)return;let l=n.player.info.muted$.getValue(),o=n.player.info.currentQuality$.getValue(),d=n.player.info.isAutoQualityEnabled$.getValue(),u=n.player.info.volume$.getValue(),m=n.player.info.currentPlaybackRate$.getValue(),b=!d,A=!1;for(let R of e.map)if(R[0]===x.id&&!r.state.isReplay$.getValue()){let I=Object.keys(R[1]);for(let k of I)k===n.itemId?(I.length<hn||(A=!0),e.removePlayer(R[0],k)):(A=!0,p(R[0],k,C),b?re(n.player,o):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(l),n.player.setPlaybackRate(m))}else e.removePlayer(R[0]);A||(await y({media:x,chapterId:C,setAsActive:!0,playbackRate:m}),b?re(n.player,o):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(l))}async function y({media:C,chapterId:x,prefetch:l=!0,setAsActive:o=!0,autoplay:d=!1,preferredExt:u,title:m,playbackRate:b}){let A=Math.random().toString(),R=document.createElement("div");h.append(R);let I;if(r?.options?.vkVideoLoader){let le=At(C);le.length&&(I=await r.options.vkVideoLoader(...le))}let k=r?.options?.coreConfig||void 0,L={...k,configName:[...k?.configName??[],"interactive"]},j={container:R,...I?.videos?.[0]||{sources:et(C,u).sources},title:m,failoverHosts:I?.failoverHosts||[]},F=new cn(L,ln.createRootTracer());F.initVideo(j);let _=null;if(I?.videos&&r?.options.createOneStat){let le=I.videos[0],Fe=r.options.createOneStat(le),ot=new tt;Fe&&(ot.add(Fe.attachTo(F)),_={oneStat:Fe,statSubscription:ot})}let W=new tt,Zt=n?.player?.info.isAutoQualityEnabled$.getValue();W.add(F.events.canplay$.subscribe(function(){Zt||re(F,n.player.info.currentQuality$.getValue()),b&&F.setPlaybackRate(b)}));let K=e.createPlayer({listId:C.id,itemId:A,player:F,container:R,sources:et(C,u).sources,config:j,subscription:W,statistics:_});return o&&p(C.id,K.itemId,x),d&&K.player.play(),l&&!d&&K.player.prepare(),{player:K.player,config:K.config,statistics:K.statistics}}function v(){M(),r=null,h.remove()}function M(){t.unsubscribe(),e.removeAll(),n={},s=!1}async function T(){if(!r)throw Error("need to set interactive controller");M(),h=document.createElement("div");let{media:C,chapter:x}=r.getCurrentChapter();C&&x?(t.add(r.events.chapterChanged$.subscribe(g)),await y({media:C,chapterId:x.id,title:x.label})):console.error("not found")}return{...e,init:T,setInteractiveController:c,createPlayer:y,removeAll:v,getActivePlayer:function(){return n},activePlayerChanged:a}}var E={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},se={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},w={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as dn}from"@vkontakte/videoplayer-shared/evergreen";var $e=class{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEvents:h,globalEventEmitter:a,getContainerEventState:c,permanentTextControls:p,interactiveTimeOpenUri:f,disabledControls$:g,onRemove:y}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(z(this.container.container.events)&&this.gameState===3||this.selectBranches.state.isExpect||(this.gameState!==2&&this.container.hide?.(),this.emitContainerVisibilityEvent(!1)))})};this.show=()=>{if(this.gameState!==2||this.isSelectedControlEvent)return;if(this.container.getElement()){let{hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState();if(this.container.show?.(),this.interactiveTimeOpenUri&&t)return;this.emitContainerVisibilityEvent(!0,!1)}else{let t={isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.emitContainerVisibilityEvent(!1)},onEvent:(r,s)=>{let{isExpectTime:h,hasOtherExpect:a,hasOpenURIEvent:c,hasOpenURIEventInCurrentContainer:p,isAllOpenURIEventsValid:f,hasShouldOpenNowEvent:g}=this.getContainerEventState(),y=this.interactiveTimeOpenUri&&!p,v=this.interactiveTimeOpenUri&&p;if((!this.interactiveTimeOpenUri||y)&&(this.isSelectedControlEvent=!0),r!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||y)){if(this.interactiveTimeOpenUri){let M=!a&&!f&&p;M&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:M})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&c&&this.gameState!==5){if(v){let T=((C,x,l,o)=>!C&&!x&&l||C&&!x&&l&&!o||C&&!x&&l&&o)(h,a,f,this.isSelectedContainerEvent);this.fakeRemoveView(T)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!h||!a||!g)&&(this.selectBranches.stopExpect(),s())}},isEOV:()=>this.gameState===4},n=xt(this.selectBranches.onControlEvent,t);this.container.createView(n),this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let e=this.player.experimental.element$.getValue(),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(Tt(s,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(qe(s,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let p=this.gameState;this.gameState=3,p===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:p}=this.getContainerEventState(),f=this.selectBranches.state.isExpect;if(this.interactiveTimeOpenUri&&p&&!f){let y=this.container.getElement();if(y){if(y.style.visibility==="hidden")return;this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView();return}}this.isPermanentText||this.removeView()}let h=qe(s,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],c={subjectId:this.container.container.id,subjectName:"container",range:a,currentTime:s,isInteractiveTime:h};this.globalEventEmitter.emit(E.eachTick,c),this.globalEvents.eachTick$.next(c)};this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new dn,this.player=e,this.interactiveEvents=s,this.getContainerEventState=c,this.isPermanentText=p&&Z(t.container.controls),this.interactiveTimeOpenUri=f,this.disabledControls$=g,this.onRemove=y,this.globalEventEmitter=a,this.gameState=0,this.globalEvents=h,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(E.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:e,isFirst:t}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e,isFirst:t})):(this.globalEventEmitter.emit(E.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:!1}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e}))}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(e=>{e?this.container.disable?.():this.container.enable?.()}))}selectContainerEvent(e=!1){let{isExpectEventForCurrentContainer:t}=this.getContainerEventState();this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime??1/0,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,t||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime??1/0))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);let{isExpectTime:e,hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState(),n=this.interactiveTimeOpenUri?e||t:z(this.container.container.events)||e;(this.isSelectedControlEvent||!n)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.emitContainerVisibilityEvent(!1)}reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=1}removeView(e=!1){this.container.removeView(e),this.globalEventEmitter.emit(E.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.containerRemoved,visibility:!1}),this.globalEvents.interactiveContainerRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-removed"}),this.gameState=5,this.onRemove?.()}fakeRemoveView(e=!1){this.container.isRemoved||this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:e}),this.container.fakeRemove()}destroy(){this.reset(),this.removeView(!0),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 Rt=(i=[])=>i.reduce((e,t,n)=>{let r=(t?.controls??[]).filter(s=>!Te(s));if(Me(r)){let s=[t.startTime??0,t.endTime??1/0],h={id:t.id,isRemoved:!1};if(!n)e.push({subjects:[h],range:s});else{let a=[],c=-1/0,p=1/0,f=[],g=[];for(let y=0;y<e.length;y++){let v=e[y];if(g.push(...v.subjects),v.range[0]<p&&(p=v.range[0]),v.range[1]>c&&(c=v.range[1]),s[0]>=v.range[0]&&s[1]<=v.range[1])return e[y].subjects.push(h),e;s[0]<v.range[0]&&s[1]>v.range[0]&&(a.push(y),f=f.concat(v.subjects)),s[0]>=v.range[0]&&s[0]<=v.range[1]&&(a.push(y),f=f.concat(v.subjects),s[0]=v.range[0]),s[1]>=v.range[0]&&s[1]<=v.range[1]&&(a.push(y),f=f.concat(v.subjects),s[1]=v.range[1])}if(g.push(h),s[0]<=p&&s[1]>=c)return[{subjects:g,range:s}];a.length&&a.reverse().forEach(y=>{e.splice(y,1)}),e.push({subjects:f.concat([h]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function kt(){let i={};function e(){for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a]}function t(a){let c={};for(let p in i)+p<=a&&(c[p]=i[p]);return c}function n(a){let c={};for(let p in i)+p>=a&&(c[p]=i[p]);return c}function r({timestamp:a,priority:c,initiator:p}){if(We(a)){let f=i[a]??null;if(f&&c&&ee(c,!0)){let g={},y=f[c];return y&&(g={...g,...y}),g=G(g)?null:g,g&&ee(p,!0)?g[p]??null:g}return f}return null}function s({timestamp:a,priority:c,initiator:p}){if(We(a))if(i[a]){if(c&&ee(c,!0))if(i[a][c]){if(p&&ee(p,!0))if(i[a][c][p]){if(delete i[a][c][p],!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;return!1}function h({timestamp:a,priority:c,initiator:p,...f}){i[a]?.[c]?.[p]?i[a][c][p].push({...f}):i[a]?.[c]?i[a][c]={...i[a][c],[p]:[{...f}]}:i[a]?i[a]={...i[a],[c]:{[p]:[{...f}]}}:i[a]={[c]:{[p]:[{...f}]}}}return{map:i,remove:s,add:h,removeAll:e,get:r,getLte:t,getGte:n}}var un=[S.expect,S.setNextBranch],mn=1/0;function Vt(i,e){let t=i,n,r=fn(e),s=kt(),h,a=()=>{v(),l()},c=o=>{s.add.call(void 0,o),T()},p=(o=[])=>{for(let d of o)if(d.action(),un.includes(d.actionType))break},f=(o=1/0)=>{let d=Oe(s.get({timestamp:o,priority:"control"})??{}),u=Oe(s.get({timestamp:o,priority:"container"})??{}),m=Oe(s.get({timestamp:o,priority:"chapter"})??{});return[...d,...u,...m]},g=o=>{r.isReady(o)&&p(f(o))},y=()=>{p([...Oe(s.get({timestamp:1/0,priority:"chapter"})??{})])},v=()=>{n&&(h?.unsubscribe(),n=void 0)},M=o=>{},T=()=>{n||(n=()=>setTimeout(()=>{g(1/0)}),h=t.events.ended$.subscribe(n))},C=o=>{v(),t=o},x=o=>{o.priority==="container"&&r.resetCalled(o.timestamp),s.remove(o)},l=()=>{r.release(),s.removeAll()};return{setPlayer:C,add:c,remove:x,exec:g,execEndOfVideo:y,listen:T,unlisten:v,release:a,containersEventsCallState:r,getPreparedToExecActions:f}}function fn(i){let e=new Map;return{setCalled:({timestamp:a,id:c})=>{let p=e.get(a);p&&p[c]!==void 0&&(p[c]=!0)},setData:(a=[])=>{for(let c of a){let p=c.endTime??mn,f=e.get(p);e.set(p,{...f,[c.id]:!1})}},resetCalled:a=>{let c=e.get(a);if(c)for(let p in c)c[p]=!1},isReady:a=>{let c=e.get(a);if(!c)return!0;let p=Object.values(c);return i?p.some(g=>g):!p.some(g=>!g)},release:()=>e.clear()}}function Oe(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}var Mt={videoContentHeight:0,videoContentWidth:0},Pt=(i,e)=>{let{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return Mt;let{clientHeight:r,clientWidth:s}=e.experimental.element$.getValue()||{};if(!(r&&s))return Mt;let h=t/n,a=r/s,c,p;return a>h?(p=s,c=s*h):a<h?(p=r/h,c=r):(p=s,c=r),{videoContentWidth:p,videoContentHeight:c}};var yn=250;function $t(i){let e=()=>{},t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){let{parentElement:c,player:p}=i();if(c&&p){let{videoContentWidth:f,videoContentHeight:g}=Pt(c,p);c.style.setProperty("--interactive-content-width",`${f}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=Y(a=>{let{fns:c=[]}=i();n(a);for(let p of c)p()},yn);function h(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:h}}var vn=i=>Math.floor(Math.random()*i),Nt=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},Lt=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 jt=i=>{let e=i.length,t=vn(e);return i[t]},Ot=1,Ft=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Ot;let t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Ot,e>=t)return i[n];return i[i.length-1]};var Bt={shouldOpenNow:!0,isDetachContainer:!0},_t="after-expect";var it=(i,e=!1)=>({...i,args:e?{...i.args,...Bt}:{...Bt,...i.args}}),Ut=({globalEventEmitter:i,globalEvents:e,player:t,interactiveEvents:n})=>{let r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},h=({action:l,controlType:o,controlId:d,containerId:u,branches:m=[],onEvent:b,isEOV:A=()=>!1,isDisabled:R=()=>!1})=>{let I=it(l,A()),k={timestamp:1/0,priority:"control",initiator:d,actionType:I.type},L=R(),j=i.emit.bind(i,E.interactives,{subjectId:d,subjectType:o,subjectName:"control",type:L?w.actionChoiceCanceled:w.actionChoice,actionType:l.type,payload:{invokeImmediately:I.args.shouldOpenNow,containerId:u,...I.args}}),F=()=>{e.interactiveActionChoice$.next({subjectId:d,subjectType:o,subjectName:"control",type:L?"action-choice-canceled":"action-choice",actionType:l.type,payload:{invokeImmediately:I.args.shouldOpenNow,containerId:u,...I.args}})};if(L){j(),F();return}switch(I.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let _=m.find(W=>W.id===I.args.branchId);if(!_)return;b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),j(),F(),I.args.shouldOpenNow?T({subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{chapterId:_.chapterId,autoSelect:!1}}):n.add({...k,action:T.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{chapterId:_.chapterId,autoSelect:!1}})});return}case S.continuePlayback.trim().toLowerCase():{b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),j(),F(),I.args.shouldOpenNow?M({subjectId:d,subjectName:"control",subjectType:o,action:l}):n.add({...k,action:M.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:l})});return}case S.openURI.trim().toLowerCase():{b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),j(),F(),I.args.shouldOpenNow?x({subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{URI:l.args.uri}}):n.add({...k,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{URI:l.args.uri}})});return}default:{let _="Unexpected control event",W=new V(1,1,{message:_});f(W,_);return}}},a=({action:l,container:{id:o,endTime:d},branches:u=[],isEOV:m=!1,autoSelected:b=!1})=>{let A=it(l,m),R={timestamp:!A.args.shouldOpenNow||m?1/0:d??1/0,priority:"container",initiator:o,actionType:A.type},I=i.emit.bind(i,E.interactives,{subjectId:o,subjectName:"container",type:w.actionChoice,actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}}),k=()=>{e.interactiveActionChoice$.next({subjectId:o,subjectName:"container",type:"action-choice",actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}})};switch(A.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let L=u.find(j=>j.id===A.args.branchId);if(!L)return;I(),k(),n.add({...R,action:T.bind(null,{subjectId:o,subjectName:"container",action:A,payload:{chapterId:L.chapterId,autoSelect:b}})});return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{I(),k(),n.add({...R,action:M.bind(null,{subjectId:o,subjectName:"container",action:A})});return}case S.openURI.trim().toLowerCase():{I(),k(),n.add({...R,action:x.bind(null,{subjectId:o,subjectName:"container",action:A,payload:{URI:l.args.uri}})});return}default:{let L="Unexpected container event",j=new V(1,1,{message:L});f(j,L);return}}};function c({container:l,branches:o,isEOV:d=!1}){let u=Ye(l.events);if(u){let m=it(u.action,d);i.emit(E.interactives,{subjectId:l.id,subjectName:"container",type:w.actionChoice,actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"container",type:"action-choice",actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),n.add({timestamp:d?1/0:l.endTime??1/0,priority:"container",initiator:l.id,actionType:S.expect,action:y.bind(null,{subjectId:l.id,subjectName:"container"})}),r.isExpect=!0}else for(let m of l.events??[])a({action:m.action,container:l,branches:o,isEOV:d})}let p=({chapterId:l,action:o,branches:d=[]})=>{let u=i.emit.bind(i,E.interactives,{subjectId:l,subjectName:"chapter",type:w.actionChoice,actionType:o.type,payload:o.args}),m=()=>{e.interactiveActionChoice$.next({subjectId:l,subjectName:"chapter",type:"action-choice",actionType:o.type,payload:o.args})};switch(o.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let b=d.find(A=>A.id===o.args.branchId);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{let b=jt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{let b=Ft(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{let b=Lt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{let b=Nt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return u(),m(),M.bind(null,{subjectId:l,subjectName:"chapter",action:o});case S.openURI.trim().toLowerCase():return u(),m(),x.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{URI:o.args.uri}});default:{let b="Unexpected chapter event",A=new V(1,1,{message:b});f(A,b);return}}};function f(l,o){console.error(o),e.error$.next(l),i.emit(E.errors,l)}function g(l){let o=Ye(l.events);if(o){if(B(l))return;i.emit(E.interactives,{subjectId:l.id,subjectName:"chapter",type:w.actionChoice,actionType:o.action.type,payload:o.action.args}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"chapter",type:"action-choice",actionType:o.action.type,payload:o.action.args}),n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:S.expect,action:y.bind(null,{subjectId:l.id,subjectName:"chapter"})})}else l.events?.forEach(d=>{let u=p({chapterId:l.id,action:d.action,branches:l.branches});u&&n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:d.action.type,action:u})})}let y=({subjectId:l,subjectName:o})=>{t.pause(),i.emit(E.interactives,{subjectId:l,subjectName:o,type:w.actionExecution,actionType:S.expect}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,type:"action-execution",actionType:S.expect})},v=({subjectId:l,subjectName:o})=>{t.info.isEnded$.getValue()?n.execEndOfVideo():t.play(),i.emit(E.interactives,{subjectId:l,subjectName:o,type:w.actionExecution,actionType:_t}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,type:"action-execution",actionType:_t})},M=({subjectId:l,subjectName:o,subjectType:d,action:u})=>{i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type})},T=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{m.behaviour="change-chapter",i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},C=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{m.behaviour="change-manifest",i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},x=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{if(!m.URI)return;let b=window.open(m.URI,"_blank","noopener,noreferrer");b&&(b.opener=null),i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type})};return{onControlEvent:h,onContainerEvent:a,onChapterEvent:p,onExpectEvent:y,expectEventHandler:v,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:s,state:r}};import{Subscription as In,Subject as st,ValueSubject as ae}from"@vkontakte/videoplayer-shared/evergreen";var rt=(i,e)=>{let t={};return i.map(n=>{if(!t[n]){let r=e.chapters.find(h=>h.id===n);if(!r)return null;let s=e.media.videos.find(h=>r.videoId===h.id);if(!s)return null;t[n]=Gt(s)}return t[n]}).filter(Boolean)},gn=i=>{for(let e of i.variants)if(bn(e)&&e.payload)return e.payload.id},bn=i=>!!(i.type==="custom"&&i.payload&&i.payload.type==="vk"),Gt=i=>{let e=gn(i);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},En=(i,e)=>{for(let t of i.media.videos)if(e===Gt(t)){for(let n of i.chapters)if(n.videoId===t.id)return n.id;return}},zt=(i,e)=>i.reduce((t,n)=>{let r=En(e,n);return r?[...t,r]:t},[]);var oe=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:n,historyApi:r,settings:s}){this.state={history$:new ae([]),hasPrevChapter$:new ae(!1),prevChapter$:new ae(null),isInitialChapter$:new ae(!1),isGoBackLimited$:new ae(!1)};this.#n=null;this.#a=!1;this.#e=null;this.#p=null;this.events={inited$:new st,destroyed$:new st,error$:new st};this.#i=null;this.#r=null;this.#t=null;this.#o=new In;this.#c=!1;this.#l=0;this.#i=t,this.#t=e,this.#r=n,this.#n=r,this.#s=s,this.state.history$&&this.#o&&this.#o?.add(this.state.history$.subscribe(h=>{this.state.prevChapter$.next(h.at(-2)||null),this.state.hasPrevChapter$.next(h.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#e?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#l===this.#s.maxLength-1)}))}#n;#s;#a;#e;#p;#i;#r;#t;#o;#c;#l;async setManifest(e){if(!this.#r||!this.#t)return;this.#e=e,await this.getProjectHistory();let t=this.getInitialChapterId();await this.#r.setChapter({chapterId:t,pushToHistory:!1}),this.#a||(this.#a=!0,this.events.inited$.next({initChapterId:t}))}get inited(){return this.#a}async updateHistory(e,t=!0){if(!this.#e)return;this.#c?(this.#c=!1,this.#l++):this.#l=0;let n=this.#e,r=e.length-this.#s.maxLength,s=r>0?e.slice(r):e,h=rt(s,n);if(this.#p=h,this.state.history$.next(s),!(!t||!this.#n||!this.#i))try{await this.#n.save(this.#i,h)}catch{let c=new V(1,5,"Unable to save interactive history");this.events.error$.next(c),this.#t?.emit(E.errors,c)}}async goBack(){if(!this.state||!this.#r){let n=new V(1,5,"Unable to save interactive history");return this.events.error$.next(n),this.#t?.emit(E.errors,n)}this.#c=!0;let e=this.state.history$.getValue().slice(0,-1),t=e.pop();this.state.history$.next(e),await this.#r.setChapter({chapterId:t,playPrev:!0})}async getProjectHistory(){if(!this.#e||!this.#i)return;let e=this.#e,t=[this.getInitialVideoId()];if(this.#n)try{let r=await this.#n.get(this.#i);r.length&&(t=r)}catch{let s=new V(1,5,"Error while trying to fetch data");this.events.error$.next(s),this.#t?.emit(E.errors,s)}let n=zt(t,e);this.state.history$.next(n)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#s.initChapterId||this.#e?.metadata.initChapterId}getInitialVideoId(){if(this.#e){let e=this.getInitialChapterId();return rt([e],this.#e).pop()}return null}destroy(){this.#i=null,this.#n=null,this.#r=null,this.#o?.unsubscribe(),this.#o=null,this.#a=!1,this.#t?.emit(E.historyDestroyed),this.events.destroyed$.next(),this.#t=null}};var Ne=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 Le=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=`
6
+ var ct="1.0.31-dev.aa15be9d.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 O="interactive",qt="interactive-controls-container",pe=()=>document.querySelector(`.${qt}`),lt=.4,P={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},pt=(n=>(n.top="flex-start",n.bottom="flex-end",n.center="center",n))(pt||{}),ht=(n=>(n.start="flex-start",n.end="flex-end",n.center="center",n))(ht||{}),dt=(n=>(n.start="left",n.end="right",n.center="center",n))(dt||{}),he=({target:i,props:e})=>{i.style.alignItems=(e?.gravityVertical&&pt[e.gravityVertical])??"center",i.style.justifyContent=(e?.gravityHorizontal&&ht[e.gravityHorizontal])??"center",i.style.textAlign=(e?.alignment&&dt[e.alignment])??"center"},de=({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},ue=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Be(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},me=({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})`},Q=({target:i,layoutParams:e,fallback:t})=>{let n=e.angle??t.angle;n=n&&n*-1,i.style.transform=`rotate(${n}rad)`};var H=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(`${O}-control-container-${this.control.id}`),e(t,this.control.layoutParams);let n=(this.control.layoutParams.innerSizesDependOn??P.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",D=(n=>(n.AREA=`${_e}_area`,n.TEXT=`${_e}_text`,n.BUTTON=`${_e}_bttn`,n))(D||{});var fe=i=>{if(i.type.trim().toLowerCase()==="area")return new He(i)},He=class extends H{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(`${O}-${this.control.id}`),n.setAttribute("data-testid",D.AREA),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",ue({target:n,props:this.control.props,fallback:{...P,backgroundColor:"transparent"}}),me({target:n,props:this.control.props,fallback:{...P,borderAlpha:0},dependsOn:this.container.dimensions}),Q({target:n,layoutParams:this.control.layoutParams,fallback:P}),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 ye=i=>{let e=document.createElement("span");switch(i){case"Button":case"button":{let t=document.createElement("div"),n={overflow:"hidden",display:"flex",justifyContent:"center",alignItems:"center"};Object.assign(t.style,n),t.append(e);let r={display:"inline-block",whiteSpace:"pre",textOverflow:"ellipsis",maxWidth:"initial",maxHeight:"100%",wordBreak:"normal"};return Object.assign(e.style,r),t}default:{let t={display:"inline-block",whiteSpace:"break-spaces",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",maxHeight:"100%",wordBreak:"break-all"};return Object.assign(e.style,t),e}}};var ve=i=>{if(i.type.trim().toLowerCase()==="button")return new De(i)},De=class extends H{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(`${O}-${this.control.id}`),n.setAttribute("data-testid",D.BUTTON),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",n.style.fontFamily="inherit",Q({target:n,layoutParams:this.control.layoutParams,fallback:P}),ue({target:n,props:this.control.props,fallback:P}),me({target:n,props:this.control.props,fallback:P,dependsOn:this.container.dimensions}),he({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ye(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;de({target:s,props:this.control.props,fallback:P,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 ut=i=>{if(i.type.trim().toLowerCase()==="text")return new Ue(i)},Ue=class extends H{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("div");n.classList.add(`${O}-${this.control.id}`),n.setAttribute("data-testid",D.TEXT),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.fontFamily="inherit",Q({target:n,layoutParams:this.control.layoutParams,fallback:P}),he({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ye(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;de({target:s,props:this.control.props,fallback:P,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 Ge=class{constructor(e){this.layout=e}},Ce=class extends Ge{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 X=class{constructor(e){this.container=e,this.factories=new Map,this.controls=[],this.setControls()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.setControls()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.setControls()}setControls(){this.controls=this.chooseControls()}chooseControls(){return this.container.controls?.reduce((e,t)=>{let n=t.type.trim().toLowerCase(),r=this.factories.get(n);if(r){let s=r(t);if(s)return[...e,s]}return[...e]},[])||[]}};var ge=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new ze(i,e)},ze=class extends X{constructor(e,t){super(e),this.rootElement=t??pe(),this.layout=new Ce(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",ve),this.addControlFactory("text",ut),this.addControlFactory("area",fe)}createView(e){let t=document.createElement("div");return t.classList.add(`${O}-${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(e=!1){(!this.isRemoved||e)&&(this.controls.forEach(t=>t.removeListeners()),this.getElement()?.remove(),this.isRemoved=!0)}fakeRemove(){this.isRemoved||(this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${O}-${this.container.id}`)}};import{clientChecker as Tn,combine as xn,InterfaceLanguage as Sn,Observable as Kt,once as An,Subject as $,Subscription as at,ValueSubject as N,fromEvent as Qt}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as ce}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as Yt}from"@vkontakte/videoplayer-shared/evergreen";function Y(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}var U=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,J=i=>U(i,"Object"),be=i=>U(i,"String"),Ee=i=>U(i,"Array"),Ie=i=>U(i,"Number"),mt=i=>U(i,"Function");var We=i=>Ie(i)&&!isNaN(i);var G=i=>J(i)&&Object.keys(i).length===0,Ke=i=>Ee(i)&&!i.length;var ee=(i,e)=>be(i)&&(e?i.trim():i).length;var ft="video_interactive",yt="videoint";var vt=250,te=class{constructor(e){this.handleZoomChange=Y(e=>{this.lastZoomInfo=e},vt);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,!Ie(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=Jt(e),this.resizeObserver=new ResizeObserver(Y(this.onResize,vt)),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 Yt(this.lang,ft,yt)}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 Jt(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 ne=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 h=s.startTime-e;if(h<=r&&(s.endTime&&r<=s.endTime||s.endTime===null)){n=!0;break}r<h&&(t=t===-1?h:Math.min(t,h))}return!n&&t!==-1?t:null}}};import{isSupportedManifest as xe,ContainerTypes as Fi,ControlTypes as Se,EventActionTypes as S,EventTypes as Bi,migrateManifestToLatestVersion as Et,compareVersions as _i}from"@interactiveplatform/movika-manifest";var Ct={metadata:"Object",chapters:"Array"},gt=i=>{if(!J(i))return!1;for(let e in Ct)if(!i[e]||!U(i[e],Ct[e]))return!1;return xe(i.metadata.version)},Te=i=>i.type===Se.Text,Vi=i=>i.type===Se.Button,Mi=i=>i.type===Se.Area,Pi={Choice:"Choice",TextInput:"TextInput"},$i={Button:"Button",Area:"Area",Text:"Text"},Oi={onClick:"onClick",onSuspense:"onSuspense"},bt={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var V=class{constructor(e,t,...n){this.severity=e;this.category=t;this.data=n}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var Ae=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 we=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{mt(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 on}from"@vkontakte/videoplayer-shared/evergreen";var Re=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return en(...this.loaders[e])(t)}};function en(...i){return async function(t){let n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function ie(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function ke({actions:i,errors:e,chapterId:t,...n}){if(t){let r=i.getManifest();if(r){let s=i.getChapter(r.chapters,t);if(s){let h=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return h?{...n,actions:i,errors:e,result:{chapter:s,media:h,graph:a}}:{...n,errors:ie(e,ke.name,"Could not find media"),actions:i}}}}return{...n,errors:ie(e,ke.name,"Could not find chapter"),actions:i}}var Qe=(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 tn=async i=>{try{let e={},t;if(be(i)){t=new URL(i).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(J(i))e=i;else return{};if(!gt(e))return{};let n=e.metadata.media;if(be(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 sn(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function It(i){let{manifest:e,manifestURL:t}=await tn(i);if(!e)throw new Error("Failed on fetch");let n=Et(e);return n.media=nn(n.media,t),delete n.metadata.media,n}function Ve(i,e){if(e)return i.find(t=>t.id===e)}function Xe(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 Ze(i,e){return i.videos.find(t=>t.id===e)}function nn(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{let r="url"in n?n.url:"",s=rn(r,e);return{...n,url:s||r}})}))}}function rn(i="",e){try{return new URL(i,e).href}catch{return""}}function sn(i){return Qe(i,"3.2.0")>=0}var Me=i=>Ee(i)&&!Ke(i),B=i=>i.order==="end",Pe=i=>Ee(i.containers)&&!Ke(i.containers)&&B(i),Tt=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t<(e.startTime??0)},qe=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var z=(i=[])=>i.some(e=>e.action.type==="expect"),Ye=(i=[])=>i.find(e=>e.action.type==="expect"),an=i=>i?.length===1,Z=i=>an(i)&&Te(i[0]);function xt(i,...e){return t=>typeof e[0]=="object"&&typeof t=="object"?i({...e[0],...t}):i(...e,...t)}var St=(i,e)=>{let t=T=>e.find(({container:x})=>x.container.id===T)?.container.isRemoved,n=z(i.events)&&!t(i.id),r=(T,C=!1,x=!1)=>{let l=x?"every":"some";return T.controls[l](o=>{let d=C?T.endTime===i.endTime:!0;return o.events?.[l](u=>u.action?.type===bt.openURI)&&d})},s=T=>T.some(({container:C})=>r(C.container,!0,!1)&&!C.isRemoved),h=T=>T.every(({container:C})=>C.isRemoved?!0:r(C.container,!0,!0)),a=e.filter(({container:T})=>T.container.id!==i.id&&z(T.container.events)&&T.container.endTime===i.endTime&&!T.isRemoved).length,c=T=>T.controls.some(C=>C.events?.some(x=>x.action?.args?.shouldOpenNow)),p=n||a>0,f=s(e),g=r(i),y=h(e),v=n?!1:a>0,M=c(i);return{isExpectTime:p,hasOtherExpect:a>0,hasOpenURIEvent:f,hasOpenURIEventInCurrentContainer:g,isAllOpenURIEventsValid:y,isExpectEventForCurrentContainer:v,hasShouldOpenNowEvent:M}};var q=class extends Re{constructor(t,n){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new on(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:ie},result:null,errors:null,source:t});return n.errors&&this.errorHandler(n.errors),this.manifest=await It(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",ke({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Xe,getChapter:Ve,getMedia:Ze,getByBranches:this.getByBranches.bind(this),addErrorMessage:ie},result:null,errors:null,chapterId:t}));return n.errors&&this.errorHandler(n.errors),n.result&&(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=Ve(this.manifest.chapters,t);if(n){let r=Ze(this.manifest.media,n.videoId),s=Xe(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=Ve(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?B(this.chapter):!1}};import{Player as cn}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as tt,Tracer as ln,ValueSubject as pn}from"@vkontakte/videoplayer-shared/evergreen";var At=i=>{let e=i.variants.find(t=>t.payload?.type==="vk");if(e&&e.payload){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:h=Math.random().toString(),...a}){let c=i.get(s),p={...a};return c?c[h]=p:i.set(s,{[h]:p}),{listId:s,itemId:h,...a}}function t(s){s.player.destroy(),s.container.remove(),s.subscription.unsubscribe(),s.statistics?.oneStat.destroy(),s.statistics?.statSubscription.unsubscribe()}function n(s,h){let a=i.get(s);if(!a)throw Error("Can't remove. Not find.");if(h){let c=a[h];c&&t(c),delete a[h],Object.keys(a).length||i.delete(s)}else{for(let c of Object.values(a))t(c);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 re=(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 hn=2;function nt(i){let e=Je(),t=new tt,n={},r=null,s=!1,h,a=new pn(null);i&&c(i);function c(C){r=C}function p(C,x,l){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let d=(e.map.get(C)??{})[x];if(d){n={chapterId:l,listId:C,itemId:x,...d};let u=n.player;n.subscription.add(u.info.currentQuality$.subscribe(m=>{let b=u.info.position$.getValue(),A=u.info.isAutoQualityEnabled$.getValue();if(!(!m||!b||A))for(let R of e.map)Object.values(R[1]).forEach(({player:I})=>{re(I,m)})})).add(u.events.started$.subscribe(()=>{f(x)})),d.container.remove(),r.setPlayer(d.player),s||(r.init(),s=!0),a.next({player:n.player,config:n.config,statistics:n.statistics});return}throw Error("Can't set. Not find.")}async function f(C){if(!r)throw Error("need to set interactive controller");if(G(n)||C!==n.itemId)return;let x=r.getChapterBranches(),l=new Set;for(let o of x)l.has(o.media.id)||(await y({media:o.media,chapterId:o.chapter.id,setAsActive:!1,title:o.chapter.label}),l.add(o.media.id))}async function g({chapter:{id:C},manifestVideo:x}){if(G(n)||!r)return;let l=n.player.info.muted$.getValue(),o=n.player.info.currentQuality$.getValue(),d=n.player.info.isAutoQualityEnabled$.getValue(),u=n.player.info.volume$.getValue(),m=n.player.info.currentPlaybackRate$.getValue(),b=!d,A=!1;for(let R of e.map)if(R[0]===x.id&&!r.state.isReplay$.getValue()){let I=Object.keys(R[1]);for(let k of I)k===n.itemId?(I.length<hn||(A=!0),e.removePlayer(R[0],k)):(A=!0,p(R[0],k,C),b?re(n.player,o):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(l),n.player.setPlaybackRate(m))}else e.removePlayer(R[0]);A||(await y({media:x,chapterId:C,setAsActive:!0,playbackRate:m}),b?re(n.player,o):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(l))}async function y({media:C,chapterId:x,prefetch:l=!0,setAsActive:o=!0,autoplay:d=!1,preferredExt:u,title:m,playbackRate:b}){let A=Math.random().toString(),R=document.createElement("div");h.append(R);let I;if(r?.options?.vkVideoLoader){let le=At(C);le.length&&(I=await r.options.vkVideoLoader(...le))}let k=r?.options?.coreConfig||void 0,L={...k,configName:[...k?.configName??[],"interactive"]},j={container:R,...I?.videos?.[0]||{sources:et(C,u).sources},title:m,failoverHosts:I?.failoverHosts||[]},F=new cn(L,ln.createRootTracer());F.initVideo(j);let _=null;if(I?.videos&&r?.options.createOneStat){let le=I.videos[0],Fe=r.options.createOneStat(le),ot=new tt;Fe&&(ot.add(Fe.attachTo(F)),_={oneStat:Fe,statSubscription:ot})}let W=new tt,Zt=n?.player?.info.isAutoQualityEnabled$.getValue();W.add(F.events.canplay$.subscribe(function(){Zt||re(F,n.player.info.currentQuality$.getValue()),b&&F.setPlaybackRate(b)}));let K=e.createPlayer({listId:C.id,itemId:A,player:F,container:R,sources:et(C,u).sources,config:j,subscription:W,statistics:_});return o&&p(C.id,K.itemId,x),d&&K.player.play(),l&&!d&&K.player.prepare(),{player:K.player,config:K.config,statistics:K.statistics}}function v(){M(),r=null,h.remove()}function M(){t.unsubscribe(),e.removeAll(),n={},s=!1}async function T(){if(!r)throw Error("need to set interactive controller");M(),h=document.createElement("div");let{media:C,chapter:x}=r.getCurrentChapter();C&&x?(t.add(r.events.chapterChanged$.subscribe(g)),await y({media:C,chapterId:x.id,title:x.label})):console.error("not found")}return{...e,init:T,setInteractiveController:c,createPlayer:y,removeAll:v,getActivePlayer:function(){return n},activePlayerChanged:a}}var E={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},se={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},w={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as dn}from"@vkontakte/videoplayer-shared/evergreen";var $e=class{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEvents:h,globalEventEmitter:a,getContainerEventState:c,permanentTextControls:p,interactiveTimeOpenUri:f,disabledControls$:g,onRemove:y}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(z(this.container.container.events)&&this.gameState===3||this.selectBranches.state.isExpect||(this.gameState!==2&&this.container.hide?.(),this.emitContainerVisibilityEvent(!1)))})};this.show=()=>{if(this.gameState!==2||this.isSelectedControlEvent)return;if(this.container.getElement()){let{hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState();if(this.container.show?.(),this.interactiveTimeOpenUri&&t)return;this.emitContainerVisibilityEvent(!0,!1)}else{let t={isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.emitContainerVisibilityEvent(!1)},onEvent:(r,s)=>{let{isExpectTime:h,hasOtherExpect:a,hasOpenURIEvent:c,hasOpenURIEventInCurrentContainer:p,isAllOpenURIEventsValid:f,hasShouldOpenNowEvent:g}=this.getContainerEventState(),y=this.interactiveTimeOpenUri&&!p,v=this.interactiveTimeOpenUri&&p;if((!this.interactiveTimeOpenUri||y)&&(this.isSelectedControlEvent=!0),r!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||y)){if(this.interactiveTimeOpenUri){let M=!a&&!f&&p;M&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:M})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&c&&this.gameState!==5){if(v){let T=((C,x,l,o)=>!C&&!x&&l||C&&!x&&l&&!o||C&&!x&&l&&o)(h,a,f,this.isSelectedContainerEvent);this.fakeRemoveView(T)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!h||!a||!g)&&(this.selectBranches.stopExpect(),s())}},isEOV:()=>this.gameState===4},n=xt(this.selectBranches.onControlEvent,t);this.container.createView(n),this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let e=this.player.experimental.element$.getValue(),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(Tt(s,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(qe(s,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let p=this.gameState;this.gameState=3,p===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:p}=this.getContainerEventState(),f=this.selectBranches.state.isExpect;if(this.interactiveTimeOpenUri&&p&&!f){let y=this.container.getElement();if(y){if(y.style.visibility==="hidden")return;this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView();return}}this.isPermanentText||this.removeView()}let h=qe(s,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],c={subjectId:this.container.container.id,subjectName:"container",range:a,currentTime:s,isInteractiveTime:h};this.globalEventEmitter.emit(E.eachTick,c),this.globalEvents.eachTick$.next(c)};this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new dn,this.player=e,this.interactiveEvents=s,this.getContainerEventState=c,this.isPermanentText=p&&Z(t.container.controls),this.interactiveTimeOpenUri=f,this.disabledControls$=g,this.onRemove=y,this.globalEventEmitter=a,this.gameState=0,this.globalEvents=h,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(E.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:e,isFirst:t}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e,isFirst:t})):(this.globalEventEmitter.emit(E.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:!1}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e}))}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(e=>{e?this.container.disable?.():this.container.enable?.()}))}selectContainerEvent(e=!1){let{isExpectEventForCurrentContainer:t}=this.getContainerEventState();this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime??1/0,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,t||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime??1/0))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);let{isExpectTime:e,hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState(),n=this.interactiveTimeOpenUri?e||t:z(this.container.container.events)||e;(this.isSelectedControlEvent||!n)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.emitContainerVisibilityEvent(!1)}reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=1}removeView(e=!1){this.container.removeView(e),this.globalEventEmitter.emit(E.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.containerRemoved,visibility:!1}),this.globalEvents.interactiveContainerRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-removed"}),this.gameState=5,this.onRemove?.()}fakeRemoveView(e=!1){this.container.isRemoved||this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:e}),this.container.fakeRemove()}destroy(){this.reset(),this.removeView(!0),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 Rt=(i=[])=>i.reduce((e,t,n)=>{let r=(t?.controls??[]).filter(s=>!Te(s));if(Me(r)){let s=[t.startTime??0,t.endTime??1/0],h={id:t.id,isRemoved:!1};if(!n)e.push({subjects:[h],range:s});else{let a=[],c=-1/0,p=1/0,f=[],g=[];for(let y=0;y<e.length;y++){let v=e[y];if(g.push(...v.subjects),v.range[0]<p&&(p=v.range[0]),v.range[1]>c&&(c=v.range[1]),s[0]>=v.range[0]&&s[1]<=v.range[1])return e[y].subjects.push(h),e;s[0]<v.range[0]&&s[1]>v.range[0]&&(a.push(y),f=f.concat(v.subjects)),s[0]>=v.range[0]&&s[0]<=v.range[1]&&(a.push(y),f=f.concat(v.subjects),s[0]=v.range[0]),s[1]>=v.range[0]&&s[1]<=v.range[1]&&(a.push(y),f=f.concat(v.subjects),s[1]=v.range[1])}if(g.push(h),s[0]<=p&&s[1]>=c)return[{subjects:g,range:s}];a.length&&a.reverse().forEach(y=>{e.splice(y,1)}),e.push({subjects:f.concat([h]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function kt(){let i={};function e(){for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a]}function t(a){let c={};for(let p in i)+p<=a&&(c[p]=i[p]);return c}function n(a){let c={};for(let p in i)+p>=a&&(c[p]=i[p]);return c}function r({timestamp:a,priority:c,initiator:p}){if(We(a)){let f=i[a]??null;if(f&&c&&ee(c,!0)){let g={},y=f[c];return y&&(g={...g,...y}),g=G(g)?null:g,g&&ee(p,!0)?g[p]??null:g}return f}return null}function s({timestamp:a,priority:c,initiator:p}){if(We(a))if(i[a]){if(c&&ee(c,!0))if(i[a][c]){if(p&&ee(p,!0))if(i[a][c][p]){if(delete i[a][c][p],!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;return!1}function h({timestamp:a,priority:c,initiator:p,...f}){i[a]?.[c]?.[p]?i[a][c][p].push({...f}):i[a]?.[c]?i[a][c]={...i[a][c],[p]:[{...f}]}:i[a]?i[a]={...i[a],[c]:{[p]:[{...f}]}}:i[a]={[c]:{[p]:[{...f}]}}}return{map:i,remove:s,add:h,removeAll:e,get:r,getLte:t,getGte:n}}var un=[S.expect,S.setNextBranch],mn=1/0;function Vt(i,e){let t=i,n,r=fn(e),s=kt(),h,a=()=>{v(),l()},c=o=>{s.add.call(void 0,o),T()},p=(o=[])=>{for(let d of o)if(d.action(),un.includes(d.actionType))break},f=(o=1/0)=>{let d=Oe(s.get({timestamp:o,priority:"control"})??{}),u=Oe(s.get({timestamp:o,priority:"container"})??{}),m=Oe(s.get({timestamp:o,priority:"chapter"})??{});return[...d,...u,...m]},g=o=>{r.isReady(o)&&p(f(o))},y=()=>{p([...Oe(s.get({timestamp:1/0,priority:"chapter"})??{})])},v=()=>{n&&(h?.unsubscribe(),n=void 0)},M=o=>{},T=()=>{n||(n=()=>setTimeout(()=>{g(1/0)}),h=t.events.ended$.subscribe(n))},C=o=>{v(),t=o},x=o=>{o.priority==="container"&&r.resetCalled(o.timestamp),s.remove(o)},l=()=>{r.release(),s.removeAll()};return{setPlayer:C,add:c,remove:x,exec:g,execEndOfVideo:y,listen:T,unlisten:v,release:a,containersEventsCallState:r,getPreparedToExecActions:f}}function fn(i){let e=new Map;return{setCalled:({timestamp:a,id:c})=>{let p=e.get(a);p&&p[c]!==void 0&&(p[c]=!0)},setData:(a=[])=>{for(let c of a){let p=c.endTime??mn,f=e.get(p);e.set(p,{...f,[c.id]:!1})}},resetCalled:a=>{let c=e.get(a);if(c)for(let p in c)c[p]=!1},isReady:a=>{let c=e.get(a);if(!c)return!0;let p=Object.values(c);return i?p.some(g=>g):!p.some(g=>!g)},release:()=>e.clear()}}function Oe(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}var Mt={videoContentHeight:0,videoContentWidth:0},Pt=(i,e)=>{let{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return Mt;let{clientHeight:r,clientWidth:s}=e.experimental.element$.getValue()||{};if(!(r&&s))return Mt;let h=t/n,a=r/s,c,p;return a>h?(p=s,c=s*h):a<h?(p=r/h,c=r):(p=s,c=r),{videoContentWidth:p,videoContentHeight:c}};var yn=250;function $t(i){let e=()=>{},t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){let{parentElement:c,player:p}=i();if(c&&p){let{videoContentWidth:f,videoContentHeight:g}=Pt(c,p);c.style.setProperty("--interactive-content-width",`${f}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=Y(a=>{let{fns:c=[]}=i();n(a);for(let p of c)p()},yn);function h(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:h}}var vn=i=>Math.floor(Math.random()*i),Nt=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},Lt=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 jt=i=>{let e=i.length,t=vn(e);return i[t]},Ot=1,Ft=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Ot;let t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Ot,e>=t)return i[n];return i[i.length-1]};var Bt={shouldOpenNow:!0,isDetachContainer:!0},_t="after-expect";var it=(i,e=!1)=>({...i,args:e?{...i.args,...Bt}:{...Bt,...i.args}}),Ut=({globalEventEmitter:i,globalEvents:e,player:t,interactiveEvents:n})=>{let r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},h=({action:l,controlType:o,controlId:d,containerId:u,branches:m=[],onEvent:b,isEOV:A=()=>!1,isDisabled:R=()=>!1})=>{let I=it(l,A()),k={timestamp:1/0,priority:"control",initiator:d,actionType:I.type},L=R(),j=i.emit.bind(i,E.interactives,{subjectId:d,subjectType:o,subjectName:"control",type:L?w.actionChoiceCanceled:w.actionChoice,actionType:l.type,payload:{invokeImmediately:I.args.shouldOpenNow,containerId:u,...I.args}}),F=()=>{e.interactiveActionChoice$.next({subjectId:d,subjectType:o,subjectName:"control",type:L?"action-choice-canceled":"action-choice",actionType:l.type,payload:{invokeImmediately:I.args.shouldOpenNow,containerId:u,...I.args}})};if(L){j(),F();return}switch(I.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let _=m.find(W=>W.id===I.args.branchId);if(!_)return;b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),j(),F(),I.args.shouldOpenNow?T({subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{chapterId:_.chapterId,autoSelect:!1}}):n.add({...k,action:T.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{chapterId:_.chapterId,autoSelect:!1}})});return}case S.continuePlayback.trim().toLowerCase():{b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),j(),F(),I.args.shouldOpenNow?M({subjectId:d,subjectName:"control",subjectType:o,action:l}):n.add({...k,action:M.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:l})});return}case S.openURI.trim().toLowerCase():{b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),j(),F(),I.args.shouldOpenNow?x({subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{URI:l.args.uri}}):n.add({...k,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{URI:l.args.uri}})});return}default:{let _="Unexpected control event",W=new V(1,1,{message:_});f(W,_);return}}},a=({action:l,container:{id:o,endTime:d},branches:u=[],isEOV:m=!1,autoSelected:b=!1})=>{let A=it(l,m),R={timestamp:!A.args.shouldOpenNow||m?1/0:d??1/0,priority:"container",initiator:o,actionType:A.type},I=i.emit.bind(i,E.interactives,{subjectId:o,subjectName:"container",type:w.actionChoice,actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}}),k=()=>{e.interactiveActionChoice$.next({subjectId:o,subjectName:"container",type:"action-choice",actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}})};switch(A.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let L=u.find(j=>j.id===A.args.branchId);if(!L)return;I(),k(),n.add({...R,action:T.bind(null,{subjectId:o,subjectName:"container",action:A,payload:{chapterId:L.chapterId,autoSelect:b}})});return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{I(),k(),n.add({...R,action:M.bind(null,{subjectId:o,subjectName:"container",action:A})});return}case S.openURI.trim().toLowerCase():{I(),k(),n.add({...R,action:x.bind(null,{subjectId:o,subjectName:"container",action:A,payload:{URI:l.args.uri}})});return}default:{let L="Unexpected container event",j=new V(1,1,{message:L});f(j,L);return}}};function c({container:l,branches:o,isEOV:d=!1}){let u=Ye(l.events);if(u){let m=it(u.action,d);i.emit(E.interactives,{subjectId:l.id,subjectName:"container",type:w.actionChoice,actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"container",type:"action-choice",actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),n.add({timestamp:d?1/0:l.endTime??1/0,priority:"container",initiator:l.id,actionType:S.expect,action:y.bind(null,{subjectId:l.id,subjectName:"container"})}),r.isExpect=!0}else for(let m of l.events??[])a({action:m.action,container:l,branches:o,isEOV:d})}let p=({chapterId:l,action:o,branches:d=[]})=>{let u=i.emit.bind(i,E.interactives,{subjectId:l,subjectName:"chapter",type:w.actionChoice,actionType:o.type,payload:o.args}),m=()=>{e.interactiveActionChoice$.next({subjectId:l,subjectName:"chapter",type:"action-choice",actionType:o.type,payload:o.args})};switch(o.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let b=d.find(A=>A.id===o.args.branchId);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{let b=jt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{let b=Ft(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{let b=Lt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{let b=Nt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return u(),m(),M.bind(null,{subjectId:l,subjectName:"chapter",action:o});case S.openURI.trim().toLowerCase():return u(),m(),x.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{URI:o.args.uri}});default:{let b="Unexpected chapter event",A=new V(1,1,{message:b});f(A,b);return}}};function f(l,o){console.error(o),e.error$.next(l),i.emit(E.errors,l)}function g(l){let o=Ye(l.events);if(o){if(B(l))return;i.emit(E.interactives,{subjectId:l.id,subjectName:"chapter",type:w.actionChoice,actionType:o.action.type,payload:o.action.args}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"chapter",type:"action-choice",actionType:o.action.type,payload:o.action.args}),n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:S.expect,action:y.bind(null,{subjectId:l.id,subjectName:"chapter"})})}else l.events?.forEach(d=>{let u=p({chapterId:l.id,action:d.action,branches:l.branches});u&&n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:d.action.type,action:u})})}let y=({subjectId:l,subjectName:o})=>{t.pause(),i.emit(E.interactives,{subjectId:l,subjectName:o,type:w.actionExecution,actionType:S.expect}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,type:"action-execution",actionType:S.expect})},v=({subjectId:l,subjectName:o})=>{t.info.isEnded$.getValue()?n.execEndOfVideo():t.play(),i.emit(E.interactives,{subjectId:l,subjectName:o,type:w.actionExecution,actionType:_t}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,type:"action-execution",actionType:_t})},M=({subjectId:l,subjectName:o,subjectType:d,action:u})=>{i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type})},T=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{m.behaviour="change-chapter",i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},C=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{m.behaviour="change-manifest",i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},x=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{if(!m.URI)return;let b=window.open(m.URI,"_blank","noopener,noreferrer");b&&(b.opener=null),i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type})};return{onControlEvent:h,onContainerEvent:a,onChapterEvent:p,onExpectEvent:y,expectEventHandler:v,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:s,state:r}};import{Subscription as In,Subject as st,ValueSubject as ae}from"@vkontakte/videoplayer-shared/evergreen";var rt=(i,e)=>{let t={};return i.map(n=>{if(!t[n]){let r=e.chapters.find(h=>h.id===n);if(!r)return null;let s=e.media.videos.find(h=>r.videoId===h.id);if(!s)return null;t[n]=Gt(s)}return t[n]}).filter(Boolean)},gn=i=>{for(let e of i.variants)if(bn(e)&&e.payload)return e.payload.id},bn=i=>!!(i.type==="custom"&&i.payload&&i.payload.type==="vk"),Gt=i=>{let e=gn(i);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},En=(i,e)=>{for(let t of i.media.videos)if(e===Gt(t)){for(let n of i.chapters)if(n.videoId===t.id)return n.id;return}},zt=(i,e)=>i.reduce((t,n)=>{let r=En(e,n);return r?[...t,r]:t},[]);var oe=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:n,historyApi:r,settings:s}){this.state={history$:new ae([]),hasPrevChapter$:new ae(!1),prevChapter$:new ae(null),isInitialChapter$:new ae(!1),isGoBackLimited$:new ae(!1)};this.#n=null;this.#a=!1;this.#e=null;this.#p=null;this.events={inited$:new st,destroyed$:new st,error$:new st};this.#i=null;this.#r=null;this.#t=null;this.#o=new In;this.#c=!1;this.#l=0;this.#i=t,this.#t=e,this.#r=n,this.#n=r,this.#s=s,this.state.history$&&this.#o&&this.#o?.add(this.state.history$.subscribe(h=>{this.state.prevChapter$.next(h.at(-2)||null),this.state.hasPrevChapter$.next(h.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#e?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#l===this.#s.maxLength-1)}))}#n;#s;#a;#e;#p;#i;#r;#t;#o;#c;#l;async setManifest(e){if(!this.#r||!this.#t)return;this.#e=e,await this.getProjectHistory();let t=this.getInitialChapterId();await this.#r.setChapter({chapterId:t,pushToHistory:!1}),this.#a||(this.#a=!0,this.events.inited$.next({initChapterId:t}))}get inited(){return this.#a}async updateHistory(e,t=!0){if(!this.#e)return;this.#c?(this.#c=!1,this.#l++):this.#l=0;let n=this.#e,r=e.length-this.#s.maxLength,s=r>0?e.slice(r):e,h=rt(s,n);if(this.#p=h,this.state.history$.next(s),!(!t||!this.#n||!this.#i))try{await this.#n.save(this.#i,h)}catch{let c=new V(1,5,"Unable to save interactive history");this.events.error$.next(c),this.#t?.emit(E.errors,c)}}async goBack(){if(!this.state||!this.#r){let n=new V(1,5,"Unable to save interactive history");return this.events.error$.next(n),this.#t?.emit(E.errors,n)}this.#c=!0;let e=this.state.history$.getValue().slice(0,-1),t=e.pop();this.state.history$.next(e),await this.#r.setChapter({chapterId:t,playPrev:!0})}async getProjectHistory(){if(!this.#e||!this.#i)return;let e=this.#e,t=[this.getInitialVideoId()];if(this.#n)try{let r=await this.#n.get(this.#i);r.length&&(t=r)}catch{let s=new V(1,5,"Error while trying to fetch data");this.events.error$.next(s),this.#t?.emit(E.errors,s)}let n=zt(t,e);this.state.history$.next(n)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#s.initChapterId||this.#e?.metadata.initChapterId}getInitialVideoId(){if(this.#e){let e=this.getInitialChapterId();return rt([e],this.#e).pop()}return null}destroy(){this.#i=null,this.#n=null,this.#r=null,this.#o?.unsubscribe(),this.#o=null,this.#a=!1,this.#t?.emit(E.historyDestroyed),this.events.destroyed$.next(),this.#t=null}};var Ne=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 Le=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;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.31-dev.684e92f5.0",
3
+ "version": "1.0.31-dev.aa15be9d.0",
4
4
  "author": "vk.com",
5
5
  "description": "Movika interactive SDK",
6
6
  "homepage": "https://vk.com",
@@ -51,8 +51,8 @@
51
51
  "dependencies": {
52
52
  "@interactiveplatform/movika-graph-editor": "1.11.0",
53
53
  "@interactiveplatform/movika-manifest": "^1.0.0",
54
- "@vkontakte/videoplayer-core": "^2.0.125",
55
- "@vkontakte/videoplayer-shared": "^1.0.53",
56
- "@vkontakte/videoplayer-statistics": "^1.0.70"
54
+ "@vkontakte/videoplayer-core": "2.0.126-dev.aef633ec.0",
55
+ "@vkontakte/videoplayer-shared": "1.0.54-dev.fdbc2eec.0",
56
+ "@vkontakte/videoplayer-statistics": "1.0.71-dev.8ef11ac0.0"
57
57
  }
58
58
  }