@vkontakte/videoplayer-interactive 1.0.9-dev.fb906f6e.0 → 1.0.10-beta.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.9-dev.fb906f6e.0
3
- * Fri, 19 Apr 2024 13:13:53 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-9/doc/
2
+ * @vkontakte/videoplayer-interactive v1.0.10-beta.0
3
+ * Tue, 07 May 2024 23:36:26 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-10/doc/
5
5
  */
6
- import{loadVKLangPack as ie,ValueSubject as L,Subscription as et,Observable as yt,getCurrentBrowser as ne,CurrentClientBrowser as se,once as re}from"@vkontakte/videoplayer-shared/evergreen.esm.js";import{v4 as ae}from"uuid";import{Player as oe}from"@vkontakte/videoplayer-core/evergreen.esm.js";const ce="1.0.9-dev.fb906f6e.0";function Mt(i,t=1){let e="0",n="0",r="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+r},${t})`}const N="SDK_NAME",le="SDK_NAME-controls-container",_t=()=>document.querySelector(`.${le}`),he=.4,O={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},gt={top:"flex-start",bottom:"flex-end",center:"center"},vt={start:"flex-start",end:"flex-end",center:"center"},Ct={start:"left",end:"right",center:"center"},Pt=({target:i,props:t})=>{i.style.alignItems=gt[t?.text?.gravityVertical]??gt.center,i.style.justifyContent=vt[t?.text?.gravityHorizontal]??vt.center,i.style.textAlign=Ct[t?.text?.alignment]??Ct.start},kt=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.color=t?.text?.color??e.textColor,i.style.fontSize=`calc(${n.height} * ${t?.text?.size??e.textSize})`,i.textContent=t?.text?.value??e.textContent},Bt=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Mt(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Ft=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Mt(t?.shape?.border?.color??e.borderColor,t?.shape?.border?.alpha??e.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${t?.shape?.roundCorners??e.roundCorners})`},ct=({target:i,layoutParams:t,fallback:e})=>{i.style.transform=`rotate(${-t.angle}rad)`},nt="int",lt={AREA:`${nt}_area`,TEXT:`${nt}_text`,BUTTON:`${nt}_bttn`};class ht{constructor(t){this.control=t}createView(t){const e=document.createElement("div");e.classList.add(`${N}-control-container-${this.control.id}`),t(e,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??O.innerSizesDependOn)==="self"?{height:e.style.height,width:e.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:e,dependsOn:n}}setEvents(t,e){t&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":t.addEventListener("click",s=>{s.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const Dt=i=>{if(i.type.trim().toLowerCase()==="area")return new de(i)};class de extends ht{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");return s.classList.add(`${N}-${this.control.id}`),s.setAttribute("data-testid",lt.AREA),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",Bt({target:s,props:this.control.props,fallback:{...O,backgroundColor:"transparent"}}),Ft({target:s,props:this.control.props,fallback:{...O,borderAlpha:0},dependsOn:n}),ct({target:s,layoutParams:this.control.layoutParams,fallback:O}),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const Ht=i=>{if(i.type.trim().toLowerCase()==="button")return new ue(i)};class ue extends ht{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");s.type="button",s.classList.add(`${N}-${this.control.id}`),s.setAttribute("data-testid",lt.BUTTON),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",ct({target:s,layoutParams:this.control.layoutParams,fallback:O}),Bt({target:s,props:this.control.props,fallback:O}),Ft({target:s,props:this.control.props,fallback:O,dependsOn:n}),Pt({target:s,props:this.control.props}),kt({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const pe=i=>{if(i.type.trim().toLowerCase()==="text")return new fe(i)};class fe extends ht{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("div");s.classList.add(`${N}-${this.control.id}`),s.setAttribute("data-testid",lt.TEXT),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ct({target:s,layoutParams:this.control.layoutParams,fallback:O}),Pt({target:s,props:this.control.props}),kt({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){}enable(){}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class me{constructor(t){this.layout=t}}const ye=i=>{if(i.type.trim().toLowerCase()==="relative")return new Ut(i)};class Ut extends me{constructor(t){super(t)}setContainerLayout(t){t.style.position="relative"}setControlLayout(t,e){t.style.position="absolute",t.style.width=`calc(var(--interactive-content-width) * ${e.width})`,t.style.height=`calc(var(--interactive-content-height) * ${e.height})`,t.style.left=`calc(var(--interactive-content-width) * ${e.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,t.style.top=`calc(var(--interactive-content-height) * ${e.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Wt{constructor(t){this.container=t,this.factories=new Map,this.#r()}addControlFactory(t,e){this.factories.set(t.trim().toLowerCase(),e),this.#r()}removeControlFactory(t){this.factories.delete(t.trim().toLowerCase()),this.#r()}#r(){this.controls=this.#i()}#i(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...t,r(e)]:[...t]},[])}}const Gt=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new ge(i,t)};class ge extends Wt{constructor(t,e){super(t),this.rootElement=e??_t(),this.layout=new Ut(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Ht),this.addControlFactory("text",pe),this.addControlFactory("area",Dt)}createView(t){const e=document.createElement("div");return e.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const r=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(r,t)}),this.rootElement.append(e),this.isRemoved=!1,e}hide(){const t=this.getElement();t&&(t.style.visibility="hidden")}show(){const t=this.getElement();t&&(t.style.visibility="visible")}enable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.enable()),t.style.opacity=1,this.isDisabled=!1)}disable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.disable()),t.style.opacity=he,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function zt(i,t){let e;return(...n)=>{clearTimeout(e),e=setTimeout(()=>i(...n),t)}}const Q={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},W=(i,t)=>Object.prototype.toString.call(i)===`[object ${t}]`,dt=i=>W(i,Q.Object),at=i=>W(i,Q.String),ut=i=>W(i,Q.Array),Qt=i=>W(i,Q.Number),ve=i=>W(i,Q.Function),bt=i=>Qt(i)&&!isNaN(i),G=i=>dt(i)&&Object.keys(i).length===0,Xt=i=>ut(i)&&!i.length,q=(i,t)=>at(i)&&(t?i.trim():i).length,qt=window.navigator.userAgent.toLowerCase(),Ce=/mobi/i.test(qt);qt.indexOf("android")>-1;const be="video_interactive",Ee="videoint",Ie=250;class we{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=e,this.onError=n,this.lang=r??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=Se(t),this.resizeObserver=new ResizeObserver(zt(this.onResize,Ie)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=t=>{this.isReady&&(!t[0].contentRect.width||!t[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:t[0].contentRect.width,height:t[0].contentRect.height}))};getNextPoint(t=this.ngEditorSize){return[(this.lastZoomInfo.x-t.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-t.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=t=>{if(this.isReady){if(this.isHidden||this.hide(),!t?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(t.id),this.ngEditor.selectChapter(t.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=t.id,this.lastZoomInfo=void 0}};handleManifestChange=async(t,e=[])=>{if(!Qt(t.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await ie(this.lang,be,Ee)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:r}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new r(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:s,chapterId:o})=>{s==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",s=>{this.lastZoomInfo={...s}})}this.visitedChapterIds=new Set(e),t.metadata.id!==this.currentManifestId?(this.ngEditor.update(t),this.currentManifestId=t.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(t){this.visitedChapterIds=new Set([...this.visitedChapterIds,...t]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(t){this.ngEditor.updateVideosInfo(t)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function Se(i){const t=document.createElement("div");return t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.height="100%",t.style.width="100%",t.style.display="none",i.append(t),t}const J=(i="",t="")=>{i=i.split("."),t=t.split(".");let e=0;for(let n=0;n<Math.max(i.length,t.length)&&!e;n++)i[n]>t[n]?e=1:i[n]<t[n]?e=-1:e=0;return e},Te="3.1",Et={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},xe={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Re=i=>{const t=[];for(const e of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let g=[xe];switch(a){case"await":l?g=[]:s=[];break;case"default":{const y={type:"onSuspense",action:{type:Et.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?g=[y]:s=[y];break}case"random":case"weightlessRandom":case"max":case"min":{const y={type:"onSuspense",action:{type:Et[a],args:{}}};l?g=[y]:s=[y];break}}for(const y of c.controls)o.push({...c,controls:[{...y}],id:ae(),events:g})}t.push({...e,containers:o,events:s,branches:r})}return i.metadata.version=Te,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},Ae="3.2",Ve=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:Ae},media:t}}return i},je="3.3",$e=(i=[])=>({edit:{chapters:i},view:{}}),It={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Le=i=>{const t=[],e=[];for(const n of i.chapters){const{id:r,x:s,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:g,type:y,...I})=>({...I,type:g??y})),events:l.events?.length?l.events:[It]}));t.push({id:r,...a,containers:c,events:a.events?.length?a.events:[It]}),e.push({id:r,x:s,y:o})}return{...i,chapters:t,graph:$e(e),metadata:{...i.metadata,version:je}}},Ne=[{version:"3.0",migrate:Re},{version:"3.1",migrate:Ve},{version:"3.2",migrate:Le}],Oe=i=>Ne.reduce((t,e)=>J(t.metadata.version,e.version)?t:e.migrate(t),i),Me=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),w=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var F;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(F||(F={}));const wt={metadata:"Object",chapters:"Array"},_e="3.0.0",Pe="3.3.0",Kt=i=>{const t=J(i,_e);return t===-1?!1:t===0?!0:J(i,Pe)!==1},ke=i=>{if(!dt(i))return!1;for(const t in wt)if(!i[t]||!W(i[t],wt[t]))return!1;return Kt(i.metadata.version)},Zt=i=>i.type===Me.Text;class b{constructor(t,e,...n){this.severity=t,this.category=e,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class Yt{listeners={};addListener(t,e){return this.listeners[t]=this.listeners[t]||[],this.listeners[t].push(e),this}on(t,e){return this.addListener(t,e)}once(t,e){this.listeners[t]=this.listeners[t]||[];const n=()=>{e(),this.off(t,n)};return this.listeners[t].push(n),this}off(t,e){return this.removeListener(t,e)}reset(){this.listeners={}}removeListener(t,e){const n=this.listeners[t];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===e){n.splice(r,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(r=>{r(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class Be{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{ve(t)&&(this.fns.push(t),e&&this.updateFn())};removeFn=(t,e=!1)=>{this.fns=this.fns.filter(n=>n!==t),e&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(t=>t()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Fe{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return De(...this.loaders[t])(e)}}function De(...i){return async function(e){const n=[...i];for(;n.length>0;)e=await n.shift()(e);return e}}function tt(i,t,e){return i?{...i,[t]:i[t]?[e,...i[t]]:[e]}:{[t]:[e]}}function ot({actions:i,errors:t,chapterId:e,...n}){if(e){const r=i.getManifest(),s=i.getChapter(r.chapters,e);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:t,result:{chapter:s,media:o,graph:a}}:{...n,errors:tt(t,ot.name,"Could not find media"),actions:i}}}return{...n,errors:tt(t,ot.name,"Could not find chapter"),actions:i}}const He=async i=>{try{let t,e;if(dt(i))t=i;else if(at(i)){e=new URL(i).href;const r=await fetch(e);if(!r.ok)return{};t=await r.json()}else return{};if(!ke(t))return{};const n=t.metadata.media;if(at(n)&&!t.media)try{let r;e?r=new URL(n,e).href:(r=new URL(n).href,e=r);const s=await fetch(r);if(!s.ok)throw new Error;t.metadata.media=await s.json()}catch{return ze(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function Ue(i){const{manifest:t,manifestURL:e}=await He(i),n=Oe(t);return n.media=We(n.media,e),delete n.metadata.media,n}function st(i,t){return i.find(e=>e.id===t)}function St(i,t){return i.edit?.chapters?i.edit.chapters.find(e=>e.id===t):i.view?.chapters?i.view.chapters.find(e=>e.id===t):void 0}function Tt(i,t){return i.videos.find(e=>e.id===t)}function We(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const r=Ge(n.url,t);return{...n,url:r||n.url}})}))}}function Ge(i,t){try{return new URL(i,t).href}catch{return""}}function ze(i){return J(i,"3.2.0")>=0}const S=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),pt=i=>ut(i)&&!Xt(i),it=i=>i.order==="end",Qe=i=>ut(i.containers)&&!Xt(i.containers)&&it(i),Xe=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e<(t.startTime??0)},xt=(i,t)=>{const e=i*1e3;return pt(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)},z=i=>i.some(t=>t.action.type==="expect"),Rt=i=>i.find(t=>t.action.type==="expect"),qe=i=>i?.length===1,Jt=i=>qe(i)&&Zt(i[0]),Ke=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),Ze=(i=[])=>i.reduce((t,e,n)=>{const r=(e?.controls??[]).filter(s=>!Zt(s));if(pt(r)){const s=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:s});else{const a=[];let c=-1/0,l=1/0,g=[];const y=[];for(let I=0;I<t.length;I++){const C=t[I];if(y.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=s[0]&&C.range[1]>=s[1])return t[I].subjects.push(o),t;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(I),g=g.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(I),g=g.concat(C.subjects),s[1]=C.range[1])}if(y.push(o),s[0]<=l&&s[1]>=c)return[{subjects:y,range:s}];a.length&&a.reverse().forEach(I=>{t.splice(I,1)}),t.push({subjects:g.concat([o]),range:s})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),Ye=(i,t)=>z(i.events)?!1:t.some(({container:e})=>e.container.id!==i.id&&z(e.container.events)&&e.container.endTime===i.endTime&&!e.isRemoved);class Je extends Fe{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new L(null),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();const e=await this.exec("manifestLoaders",{actions:{addErrorMessage:tt},result:null,errors:null,source:t});e.errors&&this.errorHandler(e.errors);const n=await Ue(e.result??t);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(t=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const e=await this.exec("chapterLoaders",ot({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:St,getChapter:st,getMedia:Tt,getByBranches:this.getByBranches.bind(this),addErrorMessage:tt},result:null,errors:null,chapterId:t}));return e.errors&&this.errorHandler(e.errors),this.chapter=e.result.chapter,this.media=e.result.media,this.graph=e.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){const e=st(this.manifest.chapters,t);if(e){const n=Tt(this.manifest.media,e.videoId),r=St(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:r}}return null}getBranches(t=this.chapter.id){if(t===this.chapter.id)return this.getByBranches(this.chapter.branches);{const e=st(this.manifest.chapters,t);return this.getByBranches(e?.branches)}}getByBranches(t=[]){return t.reduce((e,n)=>{const r=this.getByChapterId(n.chapterId);return r&&e.push(r),e},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter.id===this.manifest.metadata.initChapterId}isEndChapter(){return it(this.chapter)}}const ti=i=>{const t=i.variants.find(e=>e.payload?.type==="vk");if(t&&"payload"in t){const[e,n]=t.payload.id.split("_");return[e,n]}return[]},f={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},At={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ei(){const i=new Map;function t({listId:r=Math.random().toString(),itemId:s=Math.random().toString(),...o}){const a=i.get(r),c={...o};return a?a[s]=c:i.set(r,{[s]:c}),{listId:r,itemId:s,...o}}function e(r,s){const o=i.get(r);if(o){if(s)return o[s]?.player.destroy(),o[s]?.container.remove(),o[s]?.subscription.unsubscribe(),delete o[s],Object.keys(o).length||i.delete(r),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(r),!0}else throw Error("Can't remove. Not find.")}function n(){for(const r of i)e(r[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function Vt(i,t=[]){let e={},n;const r=!t.length;for(const s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:s.url}});break;case"dash":(r||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:e,thumbUrl:n,title:i.title??""}}const K=(i,t)=>{const e=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();e!==t&&n.includes(t)&&(i.setQuality(t),i.setAutoQuality(!1))},Y={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ii=2;function ni(i){const t=ei();let e,n;const r=new Yt;let s={},o=!1,a=null,c=!1,l;i&&g(i);function g(d){a=d}function y(d,m,p){if(!a)throw Error("need to set interactive controller");const E=(t.map.get(d)??{})[m];if(E){s={chapterId:p,listId:d,itemId:m,...E};const R=s.player;n=R.info.currentQuality$.subscribe(v=>{if(!(!v||!R.info.position$.getValue())){e=v;for(const j of t.map)Object.values(j[1]).forEach(({player:$})=>{R.info.isAutoQualityEnabled$.getValue()||K($,v)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),r.emit(Y.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function I(d,m,p){if(!a)throw Error("need to set interactive controller");if(G(s)||d!==s.itemId)return;if(p>=0&&!o){const E=a.getChapterBranches();o=!0;const R=new Set;for(const v of E)R.has(v.media.id)||(await V({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),R.add(v.media.id))}}async function C({chapter:{id:d},media:m}){if(G(s))return;n?.unsubscribe();const p=s.player.info.muted$.getValue(),x=s.player.info.currentQuality$.getValue(),E=s.player.info.isAutoQualityEnabled$.getValue(),R=s.player.info.volume$.getValue(),v=s.player.info.currentPlaybackRate$.getValue(),j=!E;let $=!1;for(const A of t.map)if(A[0]===m.id){const k=Object.keys(A[1]);for(const M of k)M===s.itemId?(k.length<ii||($=!0),t.removePlayer(A[0],M)):($=!0,y(A[0],M,d),j?K(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(p),s.player.setPlaybackRate(v))}else t.removePlayer(A[0]);$||(await V({media:m,chapterId:d,setAsActive:!0,playbackRate:v}),j?K(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(p))}async function V({media:d,chapterId:m,prefetch:p=!0,setAsActive:x=!0,autoplay:E=!1,preferredExt:R,title:v,playbackRate:j}){const $=Math.random().toString(),A=document.createElement("div");l.append(A);const k=s?.player?.info.isAutoQualityEnabled$.getValue();let M;if(a?.options?.vkVideoLoader){const X=ti(d);X.length&&(M=await a.options.vkVideoLoader(...X))}const ft={container:A,...M?.videos?.[0]||{sources:Vt(d,R).sources},title:v},B=new oe;B.initVideo(ft);const ee=A.lastChild,mt=new et;mt.add(B.info.position$.subscribe(function(X){I($,B.info.duration$.getValue(),X)})).add(B.events.canplay$.subscribe(function(){k||K(B,e),j&&B.setPlaybackRate(j)})),ee&&(A.style.display="none",A.classList.add(m));const D=t.createPlayer({listId:d.id,itemId:$,player:B,container:A,sources:Vt(d,R).sources,config:ft,subscription:mt});return x&&y(d.id,D.itemId,m),E&&D.player.play(),p&&!E&&D.player.prepare(),r.emit(Y.playerCreated,D.player),{player:D.player,config:D.config}}function P(){u(),a=null}function u(){a?.off(f.chapterChanged,C),t.removeAll(),s={},c=!1,o=!1}async function h({container:d}){if(!a)throw Error("need to set interactive controller");u(),l=d;const{media:m,chapter:p}=a.getCurrentChapter();if(m){a.on(f.chapterChanged,C);const{player:x,config:E}=await V({media:m,chapterId:p.id,title:p.label});return r.emit(Y.initiated,{container:d,media:m,chapterId:p.id}),{player:x,config:E}}else console.error("not found")}return{...t,on:r.on.bind(r),off:r.off.bind(r),init:h,setInteractiveController:g,createPlayer:V,removeAll:P,getActivePlayer:function(){return s}}}const si=3e3,ri=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=si)=>{if(!i.length||t===null)return null;let a=-1,c=!1;const l=Math.round(t.info.position$.getValue()*1e3);for(const g of i){const y=g.startTime-o;if(y<=l&&(l<=g.endTime||g.endTime===null)){c=!0;break}l<y&&(a=a===-1?y:Math.min(a,y))}return!c&&a!==-1?a:null}}},H=ri();class ai{constructor({player:t,container:e,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l}){this.container=e,this.branches=n,this.selectBranches=r,this.subscription=new et,this.player=t,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&Jt(e.container.controls),this.disabledControls$=l,this.globalEventEmitter=o,this.gameState=S.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)),this.disabledControls$&&this.subscription.add(this.disabledControls$.subscribe(t=>{t?this.container.disable?.():this.container.enable?.()}))}hide=()=>{setTimeout(()=>{this.gameState!==S.end&&(z(this.container.container.events)&&this.gameState===S.afterInteractive||this.selectBranches.state.isExpect||(this.gameState===S.interactive?this.disabledControls$||this.container.disable?.():this.container.hide?.(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===S.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.disabledControls$||this.container.enable?.(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const e=Ke({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===S.end||this.gameState===S.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),H.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===S.end});this.container.createView(e),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0}),this.disabledControls$?.getValue()&&this.container.disable()}};selectContainerEvent(t=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:t?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:t}),!t&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const t=z(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!t)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=S.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[S.destroyed,S.removed].includes(this.gameState)&&!this.isPermanentText)return;const e=this.player.getExactTime();if(Xe(e,this.container.container))this.gameState!==S.beforeInteractive&&(this.gameState=S.beforeInteractive,this.onBeforeStartTime());else if(xt(e,this.container.container))this.gameState!==S.interactive&&(this.gameState=S.interactive,this.onStartTime());else if(this.gameState!==S.afterInteractive){const s=this.gameState;this.gameState=S.afterInteractive,s===S.interactive&&this.onEndTime()}else this.gameState!==S.destroyed&&this.removeView();const n=xt(e,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(e,n),this.globalEventEmitter.emit(f.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:e,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=S.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=S.removed}destroy(){this.reset(),this.removeView(),this.gameState=S.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),H.deleteContainer(this.container.container.id)}}function oi(){const i={};function t(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function e(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function r({timestamp:a,priority:c,initiator:l}){if(bt(a)){const g=i[a]??null;if(g&&q(c,!0)){let y={};const I=g[c];return I&&(y={...y,...I}),y=G(y)?null:y,y&&q(l,!0)?y[l]??null:y}return g}return null}function s({timestamp:a,priority:c,initiator:l}){if(bt(a))if(i[a]){if(q(c,!0))if(i[a][c]){if(q(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!G(i[a][c]))return!0}else return!1;if(delete i[a][c],!G(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...g}){i[a]?.[c]?.[l]?i[a][c][l].push({...g}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...g}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...g}]}}:i[a]={[c]:{[l]:[{...g}]}}}return{map:i,remove:s,add:o,removeAll:t,get:r,getLte:e,getGte:n}}const ci=[w.expect,w.setNextBranch],li=1/0;function jt(i){let t=i,e;const n=hi(),r=new oi;let s;const o=()=>{I(),u()},a=h=>{r.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),ci.includes(d.actionType))break},l=(h=1/0)=>{const d=Z(r.get({timestamp:h,priority:"control"})??{}),m=Z(r.get({timestamp:h,priority:"container"})??{}),p=Z(r.get({timestamp:h,priority:"chapter"})??{});return[...d,...m,...p]},g=h=>{n.isReady(h)&&c(l(h))},y=()=>{c([...Z(r.get({timestamp:1/0,priority:"chapter"})??{})])},I=()=>{e&&(s?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{g(1/0)}),s=t.events.ended$.subscribe(e))},V=h=>{I(),t=h},P=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),r.remove(h)},u=()=>{n.release(),r.removeAll()};return{setPlayer:V,add:a,remove:P,exec:g,execEndOfVideo:y,listen:C,unlisten:I,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function hi(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??li,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function Z(i){return Object.values(i).flat().sort(t=>t.actionType===w.expect?-1:1)}const di=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=t.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=r/s;let c,l;return a>o?(l=s,c=s*o):a<o?(l=r/o,c=r):(l=s,c=r),{videoContentWidth:l,videoContentHeight:c}},ui=250;function pi(i){let t=()=>{};const e=new ResizeObserver(a=>{s(a),t=s.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:g,videoContentHeight:y}=di(c,l);c.style.setProperty("--interactive-content-width",`${g}px`),c.style.setProperty("--interactive-content-height",`${y}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function r(){const{parentElement:a}=i();a.removeAttribute("style")}const s=zt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},ui);function o(){t=void 0,e.disconnect(),r()}return{resizeObserver:e,calc:()=>{t()},release:o}}class fi{constructor(){this.map={}}push(t,e){t in this.map?this.map[t].push(e):this.map[t]=[e]}get(t){const e=this.map[t];return e?e.slice():null}getAll(){const t=[];for(const e in this.map)t.push(...this.map[e]);return t}remove(t,e){t in this.map&&(this.map[t]=this.map[t].filter(n=>n!==e),this.map[t].length===0&&delete this.map[t])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const mi=i=>Math.floor(Math.random()*i),yi=i=>{let t=i.length,e=1/0,n=null;for(;t--;)i[t].weight<e&&(e=i[t].weight,n=i[t]);return n},gi=i=>{let t=i.length,e=-1/0,n=null;for(;t--;)i[t].weight>e&&(e=i[t].weight,n=i[t]);return n},vi=i=>{const t=i.length,e=mi(t);return i[e]},$t=1,Ci=i=>{let t=0;for(let n=0;n<i.length;++n)t+=i[n].weight??$t;const e=Math.random()*t;t=0;for(let n=0;n<i.length-1;++n)if(t+=i[n].weight??$t,t>=e)return i[n];return i[i.length-1]},Lt=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),rt=(i,t=!1)=>({...i,args:t?{...i.args,...Lt}:{...Lt,...i.args}}),Nt=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:m,branches:p=[],onEvent:x,isEOV:E=()=>!1,isDisabled:R=()=>!1})=>{const v=rt(u,E()),j={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},$=R(),A=i.emit.bind(i,f.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:$?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:m,...v.args}});if($){A();return}switch(v.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const k=p.find(M=>M.id===v.args.branchId);if(!k)return;x(v.args.isDetachContainer,I.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(e.add({...j,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,I.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...j,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case w.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,I.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?P({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...j,action:P.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:u,container:{id:h,endTime:d},branches:m=[],isEOV:p=!1,autoSelected:x=!1})=>{const E=rt(u,p),R={timestamp:!E.args.shouldOpenNow||p?1/0:d,priority:"container",initiator:h,actionType:E.type},v=i.emit.bind(i,f.interactives,{subjectId:h,subjectName:"container",type:T.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const j=m.find($=>$.id===E.args.branchId);if(!j)return;v(),e.add({...R,action:V.bind(null,{subjectId:h,subjectName:"container",action:E,payload:{chapterId:j.chapterId,autoSelect:x}})}),n?.();return}case w.setMaxWeightBranch.trim().toLowerCase():return;case w.setMinWeightBranch.trim().toLowerCase():return;case w.setRandomBranch.trim().toLowerCase():return;case w.setWeightlessRandomBranch.trim().toLowerCase():return;case w.continuePlayback.trim().toLowerCase():{v(),e.add({...R,action:C.bind(null,{subjectId:h,subjectName:"container",action:E})});return}case w.openURI.trim().toLowerCase():{v(),e.add({...R,action:P.bind(null,{subjectId:h,subjectName:"container",action:E,payload:{URI:u.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:u,branches:h,isEOV:d=!1}){const m=Rt(u.events);if(m){const p=rt(m.action,d);i.emit(f.interactives,{subjectId:u.id,subjectName:"container",type:T.actionChoice,actionType:p.type,payload:p.args}),e.add({timestamp:d?1/0:u.endTime,priority:"container",initiator:u.id,actionType:w.expect,action:y.bind(null,{subjectId:u.id,subjectName:"container"})}),r.isExpect=!0}else for(const p of u.events)a({action:p.action,container:u,branches:h,isEOV:d})}const l=({chapterId:u,action:h,branches:d=[]})=>{const m=i.emit.bind(i,f.interactives,{subjectId:u,subjectName:"chapter",type:T.actionChoice,actionType:h.type,payload:h.args});switch(h.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const p=d.find(x=>x.id===h.args.branchId);return p?.chapterId?(m(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const p=vi(d);return p?.chapterId?(m(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const p=Ci(d);return p?.chapterId?(m(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const p=gi(d);return p?.chapterId?(m(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const p=yi(d);return p?.chapterId?(m(),V.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return m(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case w.openURI.trim().toLowerCase():return m(),P.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{URI:h.args.uri}});default:console.error("Unexpected chapter event"),i.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function g(u){const h=Rt(u.events);if(h){if(it(u))return;i.emit(f.interactives,{subjectId:u.id,subjectName:"chapter",type:T.actionChoice,actionType:h.action.type,payload:h.action.args}),e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:w.expect,action:y.bind(null,{subjectId:u.id,subjectName:"chapter"})})}else u.events.forEach(d=>{const m=l({chapterId:u.id,action:d.action,branches:u.branches});m&&e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:d.action.type,action:m})})}const y=({subjectId:u,subjectName:h,action:d})=>{t.pause(),i.emit(f.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:d?.type??w.expect})},I=({subjectId:u,subjectName:h})=>{t.info.isEnded$.getValue()?e.execEndOfVideo():t.play(),i.emit(f.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:u,subjectName:h,subjectType:d,action:m})=>{i.emit(f.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:m.type})},V=({subjectId:u,subjectName:h,subjectType:d,action:m,payload:p})=>{p.behaviour="change-chapter",i.emit(f.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:m.type,payload:p})},P=({subjectId:u,subjectName:h,subjectType:d,action:m,payload:p})=>{if(!p.URI)return;const x=window.open(p.URI,"_blank","noopener,noreferrer");x&&(x.opener=null),i.emit(f.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:m.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:y,expectEventHandler:I,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:s,state:r}},Ot=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const r=t.chapters.find(o=>o.id===n);if(!r)return null;const s=t.media.videos.find(o=>r.videoId===o.id);if(!s)return null;e[n]=te(s)}return e[n]}).filter(Boolean)},bi=i=>{for(const t of i.variants)if(Ei(t)&&"payload"in t)return t.payload.id},Ei=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",te=i=>{const t=bi(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},Ii=(i,t)=>{for(const e of i.media.videos)if(t===te(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},wi=(i,t)=>i.reduce((e,n)=>{const r=Ii(t,n);return r?[...e,r]:e},[]);class Si{state={history$:new L([]),hasPrevChapter$:new L(!1),prevChapter$:new L(null),isInitialChapter$:new L(!1)};#r=null;#i=!1;#a=null;#o=null;#h=null;#n=null;#s=null;#d=new et;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:r}){this.#h=e,this.#s=t,this.#n=n,this.#r=r,this.state?.history$&&this.#d&&this.#d?.add(this.state?.history$.subscribe(s=>{this.state?.prevChapter$.next(s.at(-2)||null),this.state?.hasPrevChapter$.next(s.length>1),this.state?.isInitialChapter$.next(this.getInitialChapterId()===this.#a?.metadata?.initChapterId)}))}async setManifest(t){!this.#n||!this.#s||(this.#a=t,await this.getProjectHistory(),await this.#n.setChapter({chapterId:this.getInitialChapterId(),pushToHistory:!1}),this.#i||(this.#i=!0,this.#s.emit(f.historyInited,{initChapterId:this.getInitialChapterId()})))}get inited(){return this.#i}async updateHistory(t,e=!0){if(!this.#a||!this.#h)return;const n=this.#a,r=Ot(t,n);if(this.#o=r,this?.state?.history$.next(t),!(!e||!this.#r))try{await this.#r.save(this.#h,r)}catch{this.#s?.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.HISTORY,"Unable to save interactive history"))}}async getProjectHistory(){if(!this.#a||!this.#h)return;const t=this.#a;let e=[this.getInitialVideoId()];if(this.#r)try{const r=await this.#r.get(this.#h);r.length&&(e=r)}catch{this.#s?.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.HISTORY,"Error while trying to fetch data"))}const n=wi(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#a?.metadata.initChapterId}getInitialVideoId(){if(this.#a){const t=this.getInitialChapterId();return Ot([t],this.#a).pop()}return null}destroy(){this.state=null,this.#h=null,this.#r=null,this.#n=null,this.#d?.unsubscribe(),this.#d=null,this.#i=!1,this.#s?.emit(f.historyDestroyed),this.#s=null}}class U{constructor(t,e,n,r){this.target=t,this.type=e,this.listener=n,this.options=U.#r(t,r),this.target.addEventListener(e,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#r(t,e){if(e===void 0)return!1;if(typeof e=="boolean")return e;{const n=new Set(["passive","capture"]),r=Object.keys(e).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),U.#a(t)?e:e.capture||!1}}static#i=void 0;static#a(t){let e=U.#i;if(e===void 0){e=!1;try{const n={},r={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};t.addEventListener("test",s,n),t.removeEventListener("test",s,n)}catch{e=!1}U.#i=e}return e||!1}}class Ti{constructor(){this.bindingMap=new fi}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,r){if(!this.bindingMap)return;const s=new U(t,e,n,r);this.bindingMap.push(e,s)}listenOnce(t,e,n,r){const s=o=>{this.unlisten(t,e,s),n(o)};this.listen(t,e,s,r)}unlisten(t,e,n){if(!this.bindingMap)return;const r=this.bindingMap.get(e)||[];for(const s of r)s.target===t&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(e,s))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class xi{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const t=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!t)return!1;const e=t.data,n=e.length;for(let r=3;r<n;r+=40)if(e[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(t){this.canvasImgSrc=t}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(t,e=!1){const n=t.width+t.height;if(this._prevSizeId===n)return;let r;e&&(r=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&r&&this.restore(r),this._prevSizeId=n}async save(){const t=this.rootElement.toDataURL("image/jpeg",1),e=new Image;return e.crossOrigin="anonymous",e.src=t,await e.decode(),e}restore(t){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(t,0,0,this.rootElement.width,this.rootElement.height)}}class Ri{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:t,endOffsetMs:e=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
6
+ import{loadVKLangPack as ee,ValueSubject as $,Subscription as tt,Observable as mt,getCurrentBrowser as ie,CurrentClientBrowser as ne,once as se}from"@vkontakte/videoplayer-shared/evergreen.esm.js";import{v4 as re}from"uuid";import{Player as ae}from"@vkontakte/videoplayer-core/evergreen.esm.js";const oe="1.0.10-beta.0";function Ot(i,t=1){let e="0",n="0",r="0";return i.length===4?(e="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(e="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+e},${+n},${+r},${t})`}const N="SDK_NAME",ce="SDK_NAME-controls-container",Mt=()=>document.querySelector(`.${ce}`),le=.4,O={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},yt={top:"flex-start",bottom:"flex-end",center:"center"},gt={start:"flex-start",end:"flex-end",center:"center"},vt={start:"left",end:"right",center:"center"},_t=({target:i,props:t})=>{i.style.alignItems=yt[t?.text?.gravityVertical]??yt.center,i.style.justifyContent=gt[t?.text?.gravityHorizontal]??gt.center,i.style.textAlign=vt[t?.text?.alignment]??vt.start},kt=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.color=t?.text?.color??e.textColor,i.style.fontSize=`calc(${n.height} * ${t?.text?.size??e.textSize})`,i.textContent=t?.text?.value??e.textContent},Bt=({target:i,props:t,fallback:e})=>{i.style.backgroundColor=Ot(t?.background?.color??e.backgroundColor,t?.background?.alpha??e.backgroundAlpha)},Pt=({target:i,props:t,fallback:e,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${t?.shape?.border?.width??e.borderWidth}) solid ${Ot(t?.shape?.border?.color??e.borderColor,t?.shape?.border?.alpha??e.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${t?.shape?.roundCorners??e.roundCorners})`},ot=({target:i,layoutParams:t,fallback:e})=>{i.style.transform=`rotate(${-t.angle}rad)`},it="int",ct={AREA:`${it}_area`,TEXT:`${it}_text`,BUTTON:`${it}_bttn`};class lt{constructor(t){this.control=t}createView(t){const e=document.createElement("div");e.classList.add(`${N}-control-container-${this.control.id}`),t(e,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??O.innerSizesDependOn)==="self"?{height:e.style.height,width:e.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:e,dependsOn:n}}setEvents(t,e){t&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":t.addEventListener("click",s=>{s.stopPropagation(),e&&e({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const Ft=i=>{if(i.type.trim().toLowerCase()==="area")return new he(i)};class he extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");return s.classList.add(`${N}-${this.control.id}`),s.setAttribute("data-testid",ct.AREA),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",Bt({target:s,props:this.control.props,fallback:{...O,backgroundColor:"transparent"}}),Pt({target:s,props:this.control.props,fallback:{...O,borderAlpha:0},dependsOn:n}),ot({target:s,layoutParams:this.control.layoutParams,fallback:O}),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const Dt=i=>{if(i.type.trim().toLowerCase()==="button")return new de(i)};class de extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("button");s.type="button",s.classList.add(`${N}-${this.control.id}`),s.setAttribute("data-testid",ct.BUTTON),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.display="inline-block",o.style.whiteSpace="pre",o.style.overflow="hidden",o.style.textOverflow="ellipsis",ot({target:s,layoutParams:this.control.layoutParams,fallback:O}),Bt({target:s,props:this.control.props,fallback:O}),Pt({target:s,props:this.control.props,fallback:O,dependsOn:n}),_t({target:s,props:this.control.props}),kt({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){this.controlEl&&(this.controlEl.style.cursor="default")}enable(){this.controlEl&&(this.controlEl.style.cursor="pointer")}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const ue=i=>{if(i.type.trim().toLowerCase()==="text")return new pe(i)};class pe extends lt{constructor(t){super(t)}createView({parent:t,layoutFn:e}){const{dependsOn:n,controlContainerEl:r}=super.createView(e),s=document.createElement("div");s.classList.add(`${N}-${this.control.id}`),s.setAttribute("data-testid",ct.TEXT),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.fontFamily="inherit";const o=document.createElement("span");return o.style.whiteSpace="pre",ot({target:s,layoutParams:this.control.layoutParams,fallback:O}),_t({target:s,props:this.control.props}),kt({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),t.append(r),this.controlEl=s,r}disable(){}enable(){}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class fe{constructor(t){this.layout=t}}const me=i=>{if(i.type.trim().toLowerCase()==="relative")return new Ht(i)};class Ht extends fe{constructor(t){super(t)}setContainerLayout(t){t.style.position="relative"}setControlLayout(t,e){t.style.position="absolute",t.style.width=`calc(var(--interactive-content-width) * ${e.width})`,t.style.height=`calc(var(--interactive-content-height) * ${e.height})`,t.style.left=`calc(var(--interactive-content-width) * ${e.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,t.style.top=`calc(var(--interactive-content-height) * ${e.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class Gt{constructor(t){this.container=t,this.factories=new Map,this.#r()}addControlFactory(t,e){this.factories.set(t.trim().toLowerCase(),e),this.#r()}removeControlFactory(t){this.factories.delete(t.trim().toLowerCase()),this.#r()}#r(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((t,e)=>{const n=e.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...t,r(e)]:[...t]},[])}}const Ut=(i,t)=>{if(i.type.trim().toLowerCase()==="choice")return new ye(i,t)};class ye extends Gt{constructor(t,e){super(t),this.rootElement=e??Mt(),this.layout=new Ht(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Dt),this.addControlFactory("text",ue),this.addControlFactory("area",Ft)}createView(t){const e=document.createElement("div");return e.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(e),this.controls.forEach(n=>{const r=n.createView({parent:e,layoutFn:this.layout.setControlLayout});n.setEvents(r,t)}),this.rootElement.append(e),this.isRemoved=!1,e}hide(){const t=this.getElement();t&&(t.style.visibility="hidden")}show(){const t=this.getElement();t&&(t.style.visibility="visible")}enable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.enable()),t.style.opacity=1,this.isDisabled=!1)}disable(){const t=this.getElement();t&&(this.controls.forEach(e=>e.disable()),t.style.opacity=le,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function Wt(i,t){let e;return(...n)=>{clearTimeout(e),e=setTimeout(()=>i(...n),t)}}const z={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},G=(i,t)=>Object.prototype.toString.call(i)===`[object ${t}]`,ht=i=>G(i,z.Object),rt=i=>G(i,z.String),dt=i=>G(i,z.Array),zt=i=>G(i,z.Number),ge=i=>G(i,z.Function),Ct=i=>zt(i)&&!isNaN(i),U=i=>ht(i)&&Object.keys(i).length===0,Qt=i=>dt(i)&&!i.length,X=(i,t)=>rt(i)&&(t?i.trim():i).length,Xt=window.navigator.userAgent.toLowerCase(),ve=/mobi/i.test(Xt);Xt.indexOf("android")>-1;const Ce="video_interactive",be="videoint",Ee=250;class Ie{constructor(t){this.init(t)}init({root:t,onOpenPreviewClick:e,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=e,this.onError=n,this.lang=r??"ru",this.zoom=.7,this.isReady=!1,this.lastZoomInfo=void 0,this.ngEditorSize=void 0,this.ngEditor=void 0,this.graphWrapperElement=we(t),this.resizeObserver=new ResizeObserver(Wt(this.onResize,Ee)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=t=>{this.isReady&&(!t[0].contentRect.width||!t[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:t[0].contentRect.width,height:t[0].contentRect.height}))};getNextPoint(t=this.ngEditorSize){return[(this.lastZoomInfo.x-t.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-t.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=t=>{if(this.isReady){if(this.isHidden||this.hide(),!t?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(t.id),this.ngEditor.selectChapter(t.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=t.id,this.lastZoomInfo=void 0}};handleManifestChange=async(t,e=[])=>{if(!zt(t.graph.edit.chapters[0].x)){this.isReady=!1,this.onError?.("Can't show graph"),console.error("Can't show graph");return}if(this.lastZoomInfo=void 0,!this.ngEditor){let n;try{n=await ee(this.lang,Ce,be)}catch{console.log("Unable to load graph language pack")}const{GraphEditor:r}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new r(this.graphWrapperElement,{mode:"read",lang:this.lang,translation:n}),this.ngEditor.on("control",({name:s,chapterId:o})=>{s==="openPreview"&&this.onOpenPreviewClick(o)}),this.ngEditor.on("zoomEnd",s=>{this.lastZoomInfo={...s}})}this.visitedChapterIds=new Set(e),t.metadata.id!==this.currentManifestId?(this.ngEditor.update(t),this.currentManifestId=t.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(t){this.visitedChapterIds=new Set([...this.visitedChapterIds,...t]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(t){this.ngEditor.updateVideosInfo(t)}show(){!this.ngEditor||!this.isReady||(this.graphWrapperElement.style.display="block",this.lastZoomInfo||this.ngEditor.focusChapter(this.currentChapterId),this.isHidden=!1)}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}}function we(i){const t=document.createElement("div");return t.style.position="absolute",t.style.top="0",t.style.left="0",t.style.height="100%",t.style.width="100%",t.style.display="none",i.append(t),t}const Se=3e3,Te=()=>{let i=[],t=null;return{setPlayer:o=>{t=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Se)=>{if(!i.length||t===null)return null;let a=-1,c=!1;const l=Math.round(t.info.position$.getValue()*1e3);for(const g of i){const y=g.startTime-o;if(y<=l&&(l<=g.endTime||g.endTime===null)){c=!0;break}l<y&&(a=a===-1?y:Math.min(a,y))}return!c&&a!==-1?a:null}}},Y=(i="",t="")=>{i=i.split("."),t=t.split(".");let e=0;for(let n=0;n<Math.max(i.length,t.length)&&!e;n++)i[n]>t[n]?e=1:i[n]<t[n]?e=-1:e=0;return e},xe="3.1",bt={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Re={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ae=i=>{const t=[];for(const e of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of e.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of e.containers){const l=!!c.endTime;let g=[Re];switch(a){case"await":l?g=[]:s=[];break;case"default":{const y={type:"onSuspense",action:{type:bt.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?g=[y]:s=[y];break}case"random":case"weightlessRandom":case"max":case"min":{const y={type:"onSuspense",action:{type:bt[a],args:{}}};l?g=[y]:s=[y];break}}for(const y of c.controls)o.push({...c,controls:[{...y}],id:re(),events:g})}t.push({...e,containers:o,events:s,branches:r})}return i.metadata.version=xe,i.metadata.updated=new Date().toISOString(),{...i,chapters:t}},Le="3.2",Ve=i=>{if(!i.media){const{media:t,...e}=i.metadata;return{...i,metadata:{...e,version:Le},media:t}}return i},$e="3.3",je=(i=[])=>({edit:{chapters:i},view:{}}),Et={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Ne=i=>{const t=[],e=[];for(const n of i.chapters){const{id:r,x:s,y:o,...a}=n,c=a.containers.map(l=>({...l,controls:l.controls.map(({subtype:g,type:y,...I})=>({...I,type:g??y})),events:l.events?.length?l.events:[Et]}));t.push({id:r,...a,containers:c,events:a.events?.length?a.events:[Et]}),e.push({id:r,x:s,y:o})}return{...i,chapters:t,graph:je(e),metadata:{...i.metadata,version:$e}}},Oe=[{version:"3.0",migrate:Ae},{version:"3.1",migrate:Ve},{version:"3.2",migrate:Ne}],Me=i=>Oe.reduce((t,e)=>Y(t.metadata.version,e.version)?t:e.migrate(t),i),_e=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),w=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var F;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(F||(F={}));const It={metadata:"Object",chapters:"Array"},ke="3.0.0",Be="3.3.0",qt=i=>{const t=Y(i,ke);return t===-1?!1:t===0?!0:Y(i,Be)!==1},Pe=i=>{if(!ht(i))return!1;for(const t in It)if(!i[t]||!G(i[t],It[t]))return!1;return qt(i.metadata.version)},Kt=i=>i.type===_e.Text;class b{constructor(t,e,...n){this.severity=t,this.category=e,this.data=n}toString(){return`SDK_NAME ERROR ${JSON.stringify(this,null," ")}`}static Severity={RECOVERABLE:1,CRITICAL:2};static Category={VIDEO:0,INTERACTIVES:1,GRAPH:2,MANIFEST:3,LOADERS:4,HISTORY:5,SEAMLESS:6}}class Zt{listeners={};addListener(t,e){return this.listeners[t]=this.listeners[t]||[],this.listeners[t].push(e),this}on(t,e){return this.addListener(t,e)}once(t,e){this.listeners[t]=this.listeners[t]||[];const n=()=>{e(),this.off(t,n)};return this.listeners[t].push(n),this}off(t,e){return this.removeListener(t,e)}reset(){this.listeners={}}removeListener(t,e){const n=this.listeners[t];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===e){n.splice(r,1);break}return this}emit(t,...e){const n=this.listeners[t];return n?(n.forEach(r=>{r(...e)}),!0):!1}listenerCount(t){return(this.listeners[t]||[]).length}rawListeners(t){return this.listeners[t]}}class Fe{constructor(t){this.raf,this.fn,this.fns=[],this.addFn(t)}addFn=(t,e=!1)=>{ge(t)&&(this.fns.push(t),e&&this.updateFn())};removeFn=(t,e=!1)=>{this.fns=this.fns.filter(n=>n!==t),e&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(t=>t()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class De{loaders;constructor(t){this.loaders={chapterLoaders:t?.chapterLoaders??[],manifestLoaders:t?.manifestLoaders??[]}}async exec(t,e){return He(...this.loaders[t])(e)}}function He(...i){return async function(e){const n=[...i];for(;n.length>0;)e=await n.shift()(e);return e}}function J(i,t,e){return i?{...i,[t]:i[t]?[e,...i[t]]:[e]}:{[t]:[e]}}function at({actions:i,errors:t,chapterId:e,...n}){if(e){const r=i.getManifest(),s=i.getChapter(r.chapters,e);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:t,result:{chapter:s,media:o,graph:a}}:{...n,errors:J(t,at.name,"Could not find media"),actions:i}}}return{...n,errors:J(t,at.name,"Could not find chapter"),actions:i}}const Ge=async i=>{try{let t,e;if(ht(i))t=i;else if(rt(i)){e=new URL(i).href;const r=await fetch(e);if(!r.ok)return{};t=await r.json()}else return{};if(!Pe(t))return{};const n=t.metadata.media;if(rt(n)&&!t.media)try{let r;e?r=new URL(n,e).href:(r=new URL(n).href,e=r);const s=await fetch(r);if(!s.ok)throw new Error;t.metadata.media=await s.json()}catch{return Qe(t.metadata.version)?{manifest:t}:{}}return{manifest:t,manifestURL:e}}catch{return{}}};async function Ue(i){const{manifest:t,manifestURL:e}=await Ge(i),n=Me(t);return n.media=We(n.media,e),delete n.metadata.media,n}function nt(i,t){return i.find(e=>e.id===t)}function wt(i,t){return i.edit?.chapters?i.edit.chapters.find(e=>e.id===t):i.view?.chapters?i.view.chapters.find(e=>e.id===t):void 0}function St(i,t){return i.videos.find(e=>e.id===t)}function We(i,t){return{...i,videos:i.videos.map(e=>({...e,variants:e.variants.map(n=>{const r=ze(n.url,t);return{...n,url:r||n.url}})}))}}function ze(i,t){try{return new URL(i,t).href}catch{return""}}function Qe(i){return Y(i,"3.2.0")>=0}const S=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),ut=i=>dt(i)&&!Qt(i),et=i=>i.order==="end",Xe=i=>dt(i.containers)&&!Qt(i.containers)&&et(i),qe=(i,t)=>{const e=i*1e3;return ut(t.controls)&&e<(t.startTime??0)},Tt=(i,t)=>{const e=i*1e3;return ut(t.controls)&&e>=(t.startTime??0)&&e<=(t.endTime??1/0)},W=i=>i.some(t=>t.action.type==="expect"),xt=i=>i.find(t=>t.action.type==="expect"),Ke=i=>i?.length===1,Yt=i=>Ke(i)&&Kt(i[0]),Ze=({fn:i,type:t=1},...e)=>(...n)=>t?i(...n,...e):i({...n[t],...e[t]}),Ye=(i=[])=>i.reduce((t,e,n)=>{const r=(e?.controls??[]).filter(s=>!Kt(s));if(ut(r)){const s=[e.startTime??0,e.endTime??1/0],o=e.id;if(!n)t.push({subjects:[o],range:s});else{const a=[];let c=-1/0,l=1/0,g=[];const y=[];for(let I=0;I<t.length;I++){const C=t[I];if(y.push(...C.subjects),C.range[0]<l&&(l=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=s[0]&&C.range[1]>=s[1])return t[I].subjects.push(o),t;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(I),g=g.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(I),g=g.concat(C.subjects),s[1]=C.range[1])}if(y.push(o),s[0]<=l&&s[1]>=c)return[{subjects:y,range:s}];a.length&&a.reverse().forEach(I=>{t.splice(I,1)}),t.push({subjects:g.concat([o]),range:s})}}return t},[]).sort((t,e)=>t.range[0]-e.range[0]),Je=(i,t)=>W(i.events)?!1:t.some(({container:e})=>e.container.id!==i.id&&W(e.container.events)&&e.container.endTime===i.endTime&&!e.isRemoved);class ti extends De{constructor(t,e){super(t),this.onError=e,this.prevChapter$=new $(null),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();const e=await this.exec("manifestLoaders",{actions:{addErrorMessage:J},result:null,errors:null,source:t});e.errors&&this.errorHandler(e.errors);const n=await Ue(e.result??t);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(t=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const e=await this.exec("chapterLoaders",at({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:wt,getChapter:nt,getMedia:St,getByBranches:this.getByBranches.bind(this),addErrorMessage:J},result:null,errors:null,chapterId:t}));return e.errors&&this.errorHandler(e.errors),this.chapter=e.result.chapter,this.media=e.result.media,this.graph=e.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){const e=nt(this.manifest.chapters,t);if(e){const n=St(this.manifest.media,e.videoId),r=wt(this.manifest.graph,e.id);if(n)return{chapter:e,media:n,graph:r}}return null}getBranches(t=this.chapter.id){if(t===this.chapter.id)return this.getByBranches(this.chapter.branches);{const e=nt(this.manifest.chapters,t);return this.getByBranches(e?.branches)}}getByBranches(t=[]){return t.reduce((e,n)=>{const r=this.getByChapterId(n.chapterId);return r&&e.push(r),e},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter.id===this.manifest.metadata.initChapterId}isEndChapter(){return et(this.chapter)}}const ei=i=>{const t=i.variants.find(e=>e.payload?.type==="vk");if(t&&"payload"in t){const[e,n]=t.payload.id.split("_");return[e,n]}return[]},f={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},Rt={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function ii(){const i=new Map;function t({listId:r=Math.random().toString(),itemId:s=Math.random().toString(),...o}){const a=i.get(r),c={...o};return a?a[s]=c:i.set(r,{[s]:c}),{listId:r,itemId:s,...o}}function e(r,s){const o=i.get(r);if(o){if(s)return o[s]?.player.destroy(),o[s]?.container.remove(),o[s]?.subscription.unsubscribe(),delete o[s],Object.keys(o).length||i.delete(r),!0;for(const a of Object.values(o))a.player.destroy(),a.container.remove();return i.delete(r),!0}else throw Error("Can't remove. Not find.")}function n(){for(const r of i)e(r[0])}return{createPlayer:t,removePlayer:e,map:i,removeAll:n}}function At(i,t=[]){let e={},n;const r=!t.length;for(const s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||t.includes("mp4"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||t.includes("mpeg"))&&(e.MPEG={...e.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||t.includes("hls"))&&(e={...e,HLS:{type:"url",url:s.url}});break;case"dash":(r||t.includes("dash"))&&(e={...e,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:e,thumbUrl:n,title:i.title??""}}const q=(i,t)=>{const e=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();e!==t&&n.includes(t)&&(i.setQuality(t),i.setAutoQuality(!1))},Z={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ni=2;function si(i){const t=ii();let e,n;const r=new Zt;let s={},o=!1,a=null,c=!1,l;i&&g(i);function g(d){a=d}function y(d,m,p){if(!a)throw Error("need to set interactive controller");const E=(t.map.get(d)??{})[m];if(E){s={chapterId:p,listId:d,itemId:m,...E};const R=s.player;n=R.info.currentQuality$.subscribe(v=>{if(!(!v||!R.info.position$.getValue())){e=v;for(const V of t.map)Object.values(V[1]).forEach(({player:j})=>{R.info.isAutoQualityEnabled$.getValue()||q(j,v)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),r.emit(Z.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function I(d,m,p){if(!a)throw Error("need to set interactive controller");if(U(s)||d!==s.itemId)return;if(p>=0&&!o){const E=a.getChapterBranches();o=!0;const R=new Set;for(const v of E)R.has(v.media.id)||(await L({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),R.add(v.media.id))}}async function C({chapter:{id:d},media:m}){if(U(s))return;n?.unsubscribe();const p=s.player.info.muted$.getValue(),x=s.player.info.currentQuality$.getValue(),E=s.player.info.isAutoQualityEnabled$.getValue(),R=s.player.info.volume$.getValue(),v=s.player.info.currentPlaybackRate$.getValue(),V=!E;let j=!1;for(const A of t.map)if(A[0]===m.id){const B=Object.keys(A[1]);for(const M of B)M===s.itemId?(B.length<ni||(j=!0),t.removePlayer(A[0],M)):(j=!0,y(A[0],M,d),V?q(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(p),s.player.setPlaybackRate(v))}else t.removePlayer(A[0]);j||(await L({media:m,chapterId:d,setAsActive:!0,playbackRate:v}),V?q(s.player,x):s.player.setAutoQuality(!0),s.player.setVolume(R),s.player.setMuted(p))}async function L({media:d,chapterId:m,prefetch:p=!0,setAsActive:x=!0,autoplay:E=!1,preferredExt:R,title:v,playbackRate:V}){const j=Math.random().toString(),A=document.createElement("div");l.append(A);const B=s?.player?.info.isAutoQualityEnabled$.getValue();let M;if(a?.options?.vkVideoLoader){const Q=ei(d);Q.length&&(M=await a.options.vkVideoLoader(...Q))}const pt={container:A,...M?.videos?.[0]||{sources:At(d,R).sources},title:v},P=new ae;P.initVideo(pt);const te=A.lastChild,ft=new tt;ft.add(P.info.position$.subscribe(function(Q){I(j,P.info.duration$.getValue(),Q)})).add(P.events.canplay$.subscribe(function(){B||q(P,e),V&&P.setPlaybackRate(V)})),te&&(A.style.display="none",A.classList.add(m));const D=t.createPlayer({listId:d.id,itemId:j,player:P,container:A,sources:At(d,R).sources,config:pt,subscription:ft});return x&&y(d.id,D.itemId,m),E&&D.player.play(),p&&!E&&D.player.prepare(),r.emit(Z.playerCreated,D.player),{player:D.player,config:D.config}}function k(){u(),a=null}function u(){a?.off(f.chapterChanged,C),t.removeAll(),s={},c=!1,o=!1}async function h({container:d}){if(!a)throw Error("need to set interactive controller");u(),l=d;const{media:m,chapter:p}=a.getCurrentChapter();if(m){a.on(f.chapterChanged,C);const{player:x,config:E}=await L({media:m,chapterId:p.id,title:p.label});return r.emit(Z.initiated,{container:d,media:m,chapterId:p.id}),{player:x,config:E}}else console.error("not found")}return{...t,on:r.on.bind(r),off:r.off.bind(r),init:h,setInteractiveController:g,createPlayer:L,removeAll:k,getActivePlayer:function(){return s}}}class ri{constructor({player:t,container:e,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c,disabledControls$:l,onRemove:g}){this.container=e,this.branches=n,this.selectBranches=r,this.subscription=new tt,this.player=t,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&Yt(e.container.controls),this.disabledControls$=l,this.onRemove=g,this.globalEventEmitter=o,this.gameState=S.nothing,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(t=>{t?this.container.disable?.():this.container.enable?.()}))}hide=()=>{setTimeout(()=>{this.gameState!==S.end&&(W(this.container.container.events)&&this.gameState===S.afterInteractive||this.selectBranches.state.isExpect||(this.gameState!==S.interactive&&this.container.hide?.(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===S.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const e=Ze({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===S.end||this.gameState===S.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1}))},isEOV:()=>this.gameState===S.end});this.container.createView(e),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0}),this.disabledControls$.getValue()&&this.container.disable?.()}};selectContainerEvent(t=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:t?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:t}),!t&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const t=W(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!t)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=S.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[S.destroyed,S.removed].includes(this.gameState)&&!this.isPermanentText)return;const e=this.player.getExactTime();if(qe(e,this.container.container))this.gameState!==S.beforeInteractive&&(this.gameState=S.beforeInteractive,this.onBeforeStartTime());else if(Tt(e,this.container.container))this.gameState!==S.interactive&&(this.gameState=S.interactive,this.onStartTime());else if(this.gameState!==S.afterInteractive){const s=this.gameState;this.gameState=S.afterInteractive,s===S.interactive&&this.onEndTime()}else this.gameState!==S.destroyed&&!this.isPermanentText&&this.removeView();const n=Tt(e,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.globalEventEmitter.emit(f.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:e,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=S.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=S.removed,this.onRemove?.()}destroy(){this.reset(),this.removeView(),this.gameState=S.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id})}}function ai(){const i={};function t(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function e(a){const c={};for(const l in i)+l<=a&&(c[l]=i[l]);return c}function n(a){const c={};for(const l in i)+l>=a&&(c[l]=i[l]);return c}function r({timestamp:a,priority:c,initiator:l}){if(Ct(a)){const g=i[a]??null;if(g&&X(c,!0)){let y={};const I=g[c];return I&&(y={...y,...I}),y=U(y)?null:y,y&&X(l,!0)?y[l]??null:y}return g}return null}function s({timestamp:a,priority:c,initiator:l}){if(Ct(a))if(i[a]){if(X(c,!0))if(i[a][c]){if(X(l,!0))if(i[a][c][l]){if(delete i[a][c][l],!U(i[a][c]))return!0}else return!1;if(delete i[a][c],!U(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:l,...g}){i[a]?.[c]?.[l]?i[a][c][l].push({...g}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...g}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...g}]}}:i[a]={[c]:{[l]:[{...g}]}}}return{map:i,remove:s,add:o,removeAll:t,get:r,getLte:e,getGte:n}}const oi=[w.expect,w.setNextBranch],ci=1/0;function Lt(i){let t=i,e;const n=li(),r=new ai;let s;const o=()=>{I(),u()},a=h=>{r.add.call(void 0,h),C()},c=(h=[])=>{for(const d of h)if(d.action(),oi.includes(d.actionType))break},l=(h=1/0)=>{const d=K(r.get({timestamp:h,priority:"control"})??{}),m=K(r.get({timestamp:h,priority:"container"})??{}),p=K(r.get({timestamp:h,priority:"chapter"})??{});return[...d,...m,...p]},g=h=>{n.isReady(h)&&c(l(h))},y=()=>{c([...K(r.get({timestamp:1/0,priority:"chapter"})??{})])},I=()=>{e&&(s?.unsubscribe(),e=void 0)},C=()=>{e||(e=()=>setTimeout(()=>{g(1/0)}),s=t.events.ended$.subscribe(e))},L=h=>{I(),t=h},k=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),r.remove(h)},u=()=>{n.release(),r.removeAll()};return{setPlayer:L,add:a,remove:k,exec:g,execEndOfVideo:y,listen:C,unlisten:I,release:o,containersEventsCallState:n,getPreparedToExecActions:l}}function li(){const i=new Map;return{setCalled:({timestamp:o,id:a})=>{const c=i.get(o);c&&c[a]!==void 0&&(c[a]=!0)},setData:(o=[])=>{for(const a of o){const c=a.endTime??ci,l=i.get(c)??{};i.set(c,{...l,[a.id]:!1})}},resetCalled:o=>{const a=i.get(o);if(a)for(const c in a)a[c]=!1},isReady:o=>{const a=i.get(o);return a?!Object.values(a).some(c=>!c):!0},release:()=>i.clear()}}function K(i){return Object.values(i).flat().sort(t=>t.actionType===w.expect?-1:1)}const hi=(i,t)=>{const{height:e,width:n}=t.info.intrinsicVideoSize$.getValue()||{};if(!(e&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=t.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=e/n,a=r/s;let c,l;return a>o?(l=s,c=s*o):a<o?(l=r/o,c=r):(l=s,c=r),{videoContentWidth:l,videoContentHeight:c}},di=250;function ui(i){let t=()=>{};const e=new ResizeObserver(a=>{s(a),t=s.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:g,videoContentHeight:y}=hi(c,l);c.style.setProperty("--interactive-content-width",`${g}px`),c.style.setProperty("--interactive-content-height",`${y}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function r(){const{parentElement:a}=i();a.removeAttribute("style")}const s=Wt(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},di);function o(){t=void 0,e.disconnect(),r()}return{resizeObserver:e,calc:()=>{t()},release:o}}class pi{constructor(){this.map={}}push(t,e){t in this.map?this.map[t].push(e):this.map[t]=[e]}get(t){const e=this.map[t];return e?e.slice():null}getAll(){const t=[];for(const e in this.map)t.push(...this.map[e]);return t}remove(t,e){t in this.map&&(this.map[t]=this.map[t].filter(n=>n!==e),this.map[t].length===0&&delete this.map[t])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const fi=i=>Math.floor(Math.random()*i),mi=i=>{let t=i.length,e=1/0,n=null;for(;t--;)i[t].weight<e&&(e=i[t].weight,n=i[t]);return n},yi=i=>{let t=i.length,e=-1/0,n=null;for(;t--;)i[t].weight>e&&(e=i[t].weight,n=i[t]);return n},gi=i=>{const t=i.length,e=fi(t);return i[e]},Vt=1,vi=i=>{let t=0;for(let n=0;n<i.length;++n)t+=i[n].weight??Vt;const e=Math.random()*t;t=0;for(let n=0;n<i.length-1;++n)if(t+=i[n].weight??Vt,t>=e)return i[n];return i[i.length-1]},$t=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),st=(i,t=!1)=>({...i,args:t?{...i.args,...$t}:{...$t,...i.args}}),jt=({globalEventEmitter:i,player:t,interactiveEvents:e,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:u,controlType:h,controlId:d,containerId:m,branches:p=[],onEvent:x,isEOV:E=()=>!1,isDisabled:R=()=>!1})=>{const v=st(u,E()),V={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},j=R(),A=i.emit.bind(i,f.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:j?T.actionChoiceCanceled:T.actionChoice,actionType:u.type,payload:{containerId:m,...v.args}});if(j){A();return}switch(v.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const B=p.find(M=>M.id===v.args.branchId);if(!B)return;x(v.args.isDetachContainer,I.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?L({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:B.chapterId,autoSelect:!1}}):(e.add({...V,action:L.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{chapterId:B.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{x(v.args.isDetachContainer,I.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:h,action:u}):e.add({...V,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:u})});return}case w.openURI.trim().toLowerCase():{x(v.args.isDetachContainer,I.bind(null,{subjectId:d,subjectName:"control"})),A(),v.args.shouldOpenNow?k({subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}}):(e.add({...V,action:k.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:v,payload:{URI:u.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:u,container:{id:h,endTime:d},branches:m=[],isEOV:p=!1,autoSelected:x=!1})=>{const E=st(u,p),R={timestamp:!E.args.shouldOpenNow||p?1/0:d,priority:"container",initiator:h,actionType:E.type},v=i.emit.bind(i,f.interactives,{subjectId:h,subjectName:"container",type:T.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const V=m.find(j=>j.id===E.args.branchId);if(!V)return;v(),e.add({...R,action:L.bind(null,{subjectId:h,subjectName:"container",action:E,payload:{chapterId:V.chapterId,autoSelect:x}})}),n?.();return}case w.setMaxWeightBranch.trim().toLowerCase():return;case w.setMinWeightBranch.trim().toLowerCase():return;case w.setRandomBranch.trim().toLowerCase():return;case w.setWeightlessRandomBranch.trim().toLowerCase():return;case w.continuePlayback.trim().toLowerCase():{v(),e.add({...R,action:C.bind(null,{subjectId:h,subjectName:"container",action:E})});return}case w.openURI.trim().toLowerCase():{v(),e.add({...R,action:k.bind(null,{subjectId:h,subjectName:"container",action:E,payload:{URI:u.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:u,branches:h,isEOV:d=!1}){const m=xt(u.events);if(m){const p=st(m.action,d);i.emit(f.interactives,{subjectId:u.id,subjectName:"container",type:T.actionChoice,actionType:p.type,payload:p.args}),e.add({timestamp:d?1/0:u.endTime,priority:"container",initiator:u.id,actionType:w.expect,action:y.bind(null,{subjectId:u.id,subjectName:"container"})}),r.isExpect=!0}else for(const p of u.events)a({action:p.action,container:u,branches:h,isEOV:d})}const l=({chapterId:u,action:h,branches:d=[]})=>{const m=i.emit.bind(i,f.interactives,{subjectId:u,subjectName:"chapter",type:T.actionChoice,actionType:h.type,payload:h.args});switch(h.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const p=d.find(x=>x.id===h.args.branchId);return p?.chapterId?(m(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const p=gi(d);return p?.chapterId?(m(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const p=vi(d);return p?.chapterId?(m(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const p=yi(d);return p?.chapterId?(m(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const p=mi(d);return p?.chapterId?(m(),L.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return m(),C.bind(null,{subjectId:u,subjectName:"chapter",action:h});case w.openURI.trim().toLowerCase():return m(),k.bind(null,{subjectId:u,subjectName:"chapter",action:h,payload:{URI:h.args.uri}});default:console.error("Unexpected chapter event"),i.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function g(u){const h=xt(u.events);if(h){if(et(u))return;i.emit(f.interactives,{subjectId:u.id,subjectName:"chapter",type:T.actionChoice,actionType:h.action.type,payload:h.action.args}),e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:w.expect,action:y.bind(null,{subjectId:u.id,subjectName:"chapter"})})}else u.events.forEach(d=>{const m=l({chapterId:u.id,action:d.action,branches:u.branches});m&&e.add({timestamp:1/0,priority:"chapter",initiator:u.id,actionType:d.action.type,action:m})})}const y=({subjectId:u,subjectName:h,action:d})=>{t.pause(),i.emit(f.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:d?.type??w.expect})},I=({subjectId:u,subjectName:h})=>{t.info.isEnded$.getValue()?e.execEndOfVideo():t.play(),i.emit(f.interactives,{subjectId:u,subjectName:h,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:u,subjectName:h,subjectType:d,action:m})=>{i.emit(f.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:m.type})},L=({subjectId:u,subjectName:h,subjectType:d,action:m,payload:p})=>{p.behaviour="change-chapter",i.emit(f.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:m.type,payload:p})},k=({subjectId:u,subjectName:h,subjectType:d,action:m,payload:p})=>{if(!p.URI)return;const x=window.open(p.URI,"_blank","noopener,noreferrer");x&&(x.opener=null),i.emit(f.interactives,{subjectId:u,subjectName:h,subjectType:d,type:T.actionExecution,actionType:m.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:y,expectEventHandler:I,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:s,state:r}},Nt=(i,t)=>{const e={};return i.map(n=>{if(!e[n]){const r=t.chapters.find(o=>o.id===n);if(!r)return null;const s=t.media.videos.find(o=>r.videoId===o.id);if(!s)return null;e[n]=Jt(s)}return e[n]}).filter(Boolean)},Ci=i=>{for(const t of i.variants)if(bi(t)&&"payload"in t)return t.payload.id},bi=i=>i.type==="custom"&&"payload"in i&&i.payload.type==="vk",Jt=i=>{const t=Ci(i);if(!t)return null;const e=t.split("_").pop();return e?parseInt(e,10):null},Ei=(i,t)=>{for(const e of i.media.videos)if(t===Jt(e)){for(const n of i.chapters)if(n.videoId===e.id)return n.id;return}},Ii=(i,t)=>i.reduce((e,n)=>{const r=Ei(t,n);return r?[...e,r]:e},[]),wi=100;class Si{state={history$:new $([]),hasPrevChapter$:new $(!1),prevChapter$:new $(null),isInitialChapter$:new $(!1),isGoBackLimited$:new $(!1)};#r=null;#s;#h=!1;#i=null;#u=null;#n=null;#a=null;#o=null;#t=new tt;#d=!1;#p=0;constructor({globalEventEmitter:t,videoId:e,interactiveController:n,historyApi:r,historyParams:s}){this.#n=e,this.#o=t,this.#a=n,this.#r=r,this.#s={maxLength:s?.maxLength||wi},this.state?.history$&&this.#t&&this.#t?.add(this.state?.history$.subscribe(o=>{this.state?.prevChapter$.next(o.at(-2)||null),this.state?.hasPrevChapter$.next(o.length>1),this.state?.isInitialChapter$.next(this.getInitialChapterId()===this.#i?.metadata?.initChapterId),this.state?.isGoBackLimited$.next(this.#p===this.#s.maxLength-1)}))}async setManifest(t){!this.#a||!this.#o||(this.#i=t,await this.getProjectHistory(),await this.#a.setChapter({chapterId:this.getInitialChapterId(),pushToHistory:!1}),this.#h||(this.#h=!0,this.#o.emit(f.historyInited,{initChapterId:this.getInitialChapterId()})))}get inited(){return this.#h}async updateHistory(t,e=!0){if(!this.#i)return;this.#d?(this.#d=!1,this.#p++):this.#p=0;const n=this.#i,r=t.length-this.#s.maxLength,s=r>0?t.slice(r):t,o=Nt(s,n);if(this.#u=o,this?.state?.history$.next(s),!(!e||!this.#r||!this.#n))try{await this.#r.save(this.#n,o)}catch{this.#o?.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.HISTORY,"Unable to save interactive history"))}}async goBack(){if(!this.state||!this.#a)return this.#o?.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.HISTORY,"Cannot go back because HistoryController has not been initialized"));this.#d=!0;const t=this.state.history$.getValue().slice(0,-1),e=t.pop();this.state.history$.next(t),await this.#a.setChapter({chapterId:e})}async getProjectHistory(){if(!this.#i||!this.#n)return;const t=this.#i;let e=[this.getInitialVideoId()];if(this.#r)try{const r=await this.#r.get(this.#n);r.length&&(e=r)}catch{this.#o?.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.HISTORY,"Error while trying to fetch data"))}const n=Ii(e,t);this?.state?.history$.next(n)}getInitialChapterId(){return this.state?.history$.getValue()?.at(-1)||this.#i?.metadata.initChapterId}getInitialVideoId(){if(this.#i){const t=this.getInitialChapterId();return Nt([t],this.#i).pop()}return null}destroy(){this.state=null,this.#n=null,this.#r=null,this.#a=null,this.#t?.unsubscribe(),this.#t=null,this.#h=!1,this.#o?.emit(f.historyDestroyed),this.#o=null}}class H{constructor(t,e,n,r){this.target=t,this.type=e,this.listener=n,this.options=H.#r(t,r),this.target.addEventListener(e,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#r(t,e){if(e===void 0)return!1;if(typeof e=="boolean")return e;{const n=new Set(["passive","capture"]),r=Object.keys(e).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),H.#h(t)?e:e.capture||!1}}static#s=void 0;static#h(t){let e=H.#s;if(e===void 0){e=!1;try{const n={},r={get:()=>(e=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};t.addEventListener("test",s,n),t.removeEventListener("test",s,n)}catch{e=!1}H.#s=e}return e||!1}}class Ti{constructor(){this.bindingMap=new pi}release(){this.removeAll(),this.bindingMap=null}listen(t,e,n,r){if(!this.bindingMap)return;const s=new H(t,e,n,r);this.bindingMap.push(e,s)}listenOnce(t,e,n,r){const s=o=>{this.unlisten(t,e,s),n(o)};this.listen(t,e,s,r)}unlisten(t,e,n){if(!this.bindingMap)return;const r=this.bindingMap.get(e)||[];for(const s of r)s.target===t&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(e,s))}removeAll(){if(!this.bindingMap)return;const t=this.bindingMap.getAll();for(const e of t)e.unlisten();this.bindingMap.clear()}}class xi{rootElement;canvasImgSrc;_prevSizeId=0;constructor(){this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){const t=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!t)return!1;const e=t.data,n=e.length;for(let r=3;r<n;r+=40)if(e[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(t){this.canvasImgSrc=t}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(t,e=!1){const n=t.width+t.height;if(this._prevSizeId===n)return;let r;e&&(r=await this.save()),this.rootElement.width=t.width,this.rootElement.height=t.height,e&&r&&this.restore(r),this._prevSizeId=n}async save(){const t=this.rootElement.toDataURL("image/jpeg",1),e=new Image;return e.crossOrigin="anonymous",e.src=t,await e.decode(),e}restore(t){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(t,0,0,this.rootElement.width,this.rootElement.height)}}class Ri{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:t,endOffsetMs:e=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
7
7
  position: absolute;
8
8
  top: 0;
9
9
  left: 0;
@@ -16,8 +16,8 @@ import{loadVKLangPack as ie,ValueSubject as L,Subscription as et,Observable as y
16
16
  top: 50%;
17
17
  left: 50%;
18
18
  transform: translate(-50%, -50%);
19
- `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),t.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(t){this.currentVideoDurationMs=t}setVideoElement(t){this.lastFrameCanvas.setCanvasImageSource(t)}setCurrentChapter(t){this.currentChapter=t}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(t=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(t=!1);const e=getComputedStyle(this.rootElement),n={width:parseInt(e.getPropertyValue("--interactive-content-width"),10),height:parseInt(e.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,t)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(t){return this.currentVideoDurationMs&&t>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(t){if(this.currentChapter)return this.currentChapter.containers.some(e=>e.controls?.length&&t>=(e.startTime??0)&&t<=Math.min(e.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=t=>{const e=t??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(e);if(this.isContainerTime(e))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(t){this._callbacks?.onError?.(t)}}function Ai(i=0){return new Promise(t=>{setTimeout(()=>{t(0)},i)})}const Vi=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,historyApi:null,projectInfo:{},initSeamless:!1,lastFrame:!1,permanentTextControls:!0,disableControlsOnPause:!0}),_=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function ji(){const i=document.createElement("div");return i.style.cssText=`
19
+ `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),t.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(t){this.currentVideoDurationMs=t}setVideoElement(t){this.lastFrameCanvas.setCanvasImageSource(t)}setCurrentChapter(t){this.currentChapter=t}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(t=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(t=!1);const e=getComputedStyle(this.rootElement),n={width:parseInt(e.getPropertyValue("--interactive-content-width"),10),height:parseInt(e.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,t)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(t){return this.currentVideoDurationMs&&t>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(t){if(this.currentChapter)return this.currentChapter.containers.some(e=>e.controls?.length&&t>=(e.startTime??0)&&t<=Math.min(e.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=t=>{const e=t??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(e);if(this.isContainerTime(e))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(t){this._callbacks?.onError?.(t)}}function Ai(i=0){return new Promise(t=>{setTimeout(()=>{t(0)},i)})}const Li=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,historyApi:null,historyParams:null,projectInfo:{},initSeamless:!1,lastFrame:!1,permanentTextControls:!0}),_=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function Vi(){const i=document.createElement("div");return i.style.cssText=`
20
20
  position: absolute;
21
21
  top: 0;
22
22
  left: 0;
23
- `,i}class Oi{#r=null;#i=null;#a=null;#o=null;#h=null;#n=null;#s=null;#d=null;#e=null;#u=new L(!1);#m=new Set;#l=null;#y=null;#c=null;#t=null;state={prevChapter$:new L(null),isInitialChapter$:new L(!1),isEndChapter$:new L(!1),calledByInteractive$:new L(!1),lastChapterChangeWasInitiatedByInteractive$:new L(!1),disabledControls$:new L(!1)};constructor(t){this.options={...Vi,...t},this.#i=[],this.factories=new Map([["choice",Gt]]),this.rootElement=ji(),this.options.parentElement.append(this.rootElement),this.#t=new Yt,this.#h=new et,this.#a=new Ti,this.#o=new Si({interactiveController:this,globalEventEmitter:this.#t,videoId:this.options.projectInfo.videoId,historyApi:this.options.historyApi}),this.options.lastFrame&&(this.#c=new Ri({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:e=>this.#t.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.SEAMLESS,e))})),this.#a.listen(this.rootElement,"mousedown",e=>e.stopPropagation()),this.#a.listen(this.rootElement,"mouseup",e=>e.stopPropagation()),this.#e=new Je(this.options.loaders,e=>this.#t.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.MANIFEST,e))),this.#n=jt(this.options.player),this.#s=new Be,this.#d=Nt({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#t,removeControllers:this.#p}),this.#r=pi(()=>({player:this.options?.player,parentElement:this.options?.parentElement,fns:this.options?.lastFrame?[()=>{this.#c.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#l=new we({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:e=>{this.setChapter({chapterId:e}),this.#t.emit(f.graph,{type:At.watchAgainClicked,chapterId:e})},onError:e=>this.#t.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.LOADERS,{message:e}))})),this.#b(this.options.initSeamless),this.isFirstChapterFetched=!1,this.appState=_.created}emitPlayerChanged=t=>{this.#t.emit(f.playerChanged,t)};#b(t=!1){this.#t.on(f.historyInited,async({initChapterId:e,videosInfo:n=[]})=>{t&&await this.#E({initialChapter:e,videosInfo:n})}),this.#t.on(f.interactives,async e=>{if(e.type===T.actionExecution){if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){const{chapterId:n}=e.payload;this.setChapter({chapterId:n})}if(e.payload?.behaviour==="change-manifest"){const{manifestURL:n}=e.payload;this.setManifest(n)}}}),this.#t.on(f.manifestChanged,()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})}async#E({source:t,videosInfo:e=[]}){this.#y=ni(this);const n=document.createElement("div");this.#y.on(Y.activePlayerChanged,this.emitPlayerChanged);const{player:r,config:s}=await this.#y.init({source:t,initialChapter:this.#o.getInitialChapterId(),container:n});return this.updateGraphVideosInfo(e),{player:r,config:s}}getStatEvents(){return{click$:new yt(t=>{this.#t.on(f.graph,({type:e,visibility:n})=>{e==="visibility"&&t.next(n?F.OPEN_GRAPH:F.CLOSE_GRAPH),e==="watchAgainClicked"&&t.next(F.WATCH_AGAIN)}),this.#t.on(f.interactives,({type:e,subjectName:n,subjectType:r})=>{e!=="action-choice"||n!=="control"||(r==="Button"&&t.next(F.GO_NEXT_BUTTON),r==="Area"&&t.next(F.GO_NEXT_AREA))})}),nextMovie$:new yt(t=>{this.#t.on(f.playerChanged,({config:e})=>{e?.unitedVideoId&&t.next(e.unitedVideoId)})})}}setPlayer(t){this.#g(),this.options.player=t,H.setPlayer(this.options.player),this.#n?this.#n.setPlayer(this.options.player):this.#n=jt(this.options.player),this.#d=Nt({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#t,removeControllers:()=>this.#p(!1)}),this.appState===_.initiated&&(this.#v(),this.#f(this.#e.chapter))}async setManifest(t){this.#g(),this.isFirstChapterFetched=!1;const e=await this.#e.setManifest(t);return this.#l&&await this.#l.handleManifestChange(e.manifest),await this.#o.setManifest(e.manifest),this.#t.emit(f.manifestChanged,{manifest:e.manifest}),this.#f(this.#e.chapter),e.manifest}setVisitedChapters(t){Array.isArray(t)&&this.#l?.setVisitedChapters(t)}updateGraphVideosInfo(t){Array.isArray(t)&&this.#l?.updateVideosInfo(t)}async setChapter({chapterId:t,pushToHistory:e=!0}={}){this.#g(),this.#c&&this.isFirstChapterFetched&&(this.#c.draw(),this.#c.show()),ne().browser===se.Safari&&await Ai(35);const r=await(t?this.#e.setNext(t):this.#e.setInitial()),{chapter:s,media:o,graph:a}=r;return e&&this.#x(s.id),this.state.isInitialChapter$.next(this.#e.isInitialChapter()),this.state.isEndChapter$.next(this.#e.isEndChapter()),this.#l&&this.#l.handleChapterChange(a),this.#c?.setCurrentChapter(this.getCurrentChapter().chapter),this.#t.emit(f.chapterChanged,{chapter:s,media:o,graph:a}),this.#f(this.#e.chapter),this.#m=new Set,this.isFirstChapterFetched=!0,{chapter:s,media:o,graph:a}}toggleGraphView(t=!0){this.#l&&(t?(this.#l.show(),this.#u.next(!1)):(this.#l.hide(),this.#C()),this.#t.emit(f.graph,{type:At.visibility,visibility:t}))}init(){this.#e.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.appState===_.created&&(this.#r.resizeObserver.observe(this.options.fullscreenTargetElement),this.#v(),this.appState=_.initiated,this.#f(this.#e.chapter))}#g(){this.appState===_.ready&&(this.#p(),this.#i=[],this.#s.release(),this.#n?.release(),this.appState=_.initiated,this.#u.next(!1))}#R=()=>{this.#s.fns.forEach(n=>n());const t=this.options.player.info.position$.getValue()*1e3,e=(this.#e.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(t));for(const n of e){this.#n.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const r of n.controls)this.#n.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#i.find(r=>r.container.container.id===n.id).reset()}};#I=()=>{this.#r.calc(),this.#s.requestAnimation()};#w(t){(!this.#l||this.#l.isHidden)&&this.#C();const e=t*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>e>=s[1]);if(r){const s=r.range.join("-");this.#m.has(s)||(this.#m.add(s),this.#t.emit(f.interactives,{type:T.rangeEnded,payload:r,visibility:!0}))}}deadEndCheck(){return!(this.#n?.getPreparedToExecActions()??[]).some(n=>n.actionType===w.setNextBranch)}allControlsAreRemoved(){return!this.#i.some(e=>!e.container.isRemoved)}isEndedExpectation(){if(!this.options?.player||!this.#i)return!1;const t=this.options.player.info.position$.getValue(),e=this.options.player.info.duration$.getValue();return t===e&&this.#i.some(n=>{const r=n.container.container;return!r.isRemoved&&r.endTime===null&&z(r.events)})}#v(){this.#h.unsubscribe(),this.#h.add(this.options.player.events.started$.pipe(re()).subscribe(this.#I)).add(this.options.player.events.playing$.subscribe(this.#s.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#s.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#w.bind(this))).add(this.#e.prevChapter$.subscribe(t=>this.state.prevChapter$.next(t))),this.options.lastFrame&&this.#h.add(this.options.player.info.duration$.subscribe(t=>{this.#c.setVideoDuration(t*1e3)})).add(this.options.player.experimental.element$.subscribe(t=>{t&&this.#c.setVideoElement(t)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#c.reset(),setTimeout(()=>{this.#c.hide(),this.#c.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#c.onSeek))}#p=(t=!0)=>{this.#i.forEach(e=>{!t&&e.isPermanentText||(this.#s.removeFn(e.whilePlaying),e.destroy())})};#f(t){this.#e.chapter&&this.appState===_.initiated&&(this.#d.setManifestChapterEvents(t),this.#i=this.#S(t),this.#n.containersEventsCallState.setData(t.containers),H.setContainers(this.#i.map(e=>e.container.container).filter(e=>!Jt(e.controls))),this.options.lastFrame&&this.#s.addFn(()=>{this.#c.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.appState=_.ready)}#S(t){return t?.containers?.reduce((e,n)=>{const r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){const o=new ai({player:this.options.player,container:s(n,this.rootElement),branches:this.#e.chapter.branches,selectBranches:this.#d,interactiveEvents:this.#n,globalEventEmitter:this.#t,ignoreContainerEvent:()=>Ye(n,this.#i),permanentTextControls:this.options.permanentTextControls,disabledControls$:this.options.disableControlsOnPause?void 0:this.state.disabledControls$});return this.#s.addFn(o.whilePlaying,!0),[...e,o]}return[...e]},[])??[]}#C(){const t=this.#u.getValue(),e=!!H.getNextInteractiveTime();(e&&!t||!e&&t)&&this.#u.next(!t)}#T(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}#x(t){if(this.#T(),!this.#o.inited)return;const e=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),n=this.state.prevChapter$.getValue(),r=(n&&it(n)&&Qe(n))??!1,s=this.#e.manifest.metadata.initChapterId===t,o=this.#o.state.history$.getValue();if(s||r&&e){this.#o.updateHistory([t]);return}o.at(-1)!==t&&this.#o.updateHistory([...o,t])}playPrevChapter(){const t=[...this.#o.state.history$.getValue()];if(t.length>1){t.pop();const e=t.at(-1);this.#o.updateHistory(t),this.setChapter({chapterId:e})}}setDisabledControls(t){this.options.disableControlsOnPause?this.#t.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.INTERACTIVES,"To disable controls set disableControlsOnPause option to false")):this.state.disabledControls$.next(t)}isSupport(t=this.#e.manifest){return Kt(t.metadata.version)}getInitialVideoInfo(){return{videoId:this.#o.getInitialVideoId(),chapterId:this.#o.getInitialChapterId()}}getHistoryState(){return this.#o.state}getIsSeekable(){return this.#u}getInteractiveRanges(){return Ze(this.#e.chapter?.containers)}getNextInteractiveStartTime(t){return H.getNextInteractiveTime(t)}getChapterBranches(t){return this.#e.getBranches(t)}getCurrentChapter(){return this.#e.getCurrent()}getCurrentManifest(){return this.#e.manifest}addFactory(t,e){this.factories.set(t.trim().toLowerCase(),e)}removeFactory(t){this.factories.delete(t.trim().toLowerCase())}on(...t){return this.#t.on(...t),this}off(...t){return this.#t.off(...t),this}once(...t){return this.#t.once(...t),this}destroy(){this.#p(),this.#i=void 0,this.state=void 0,this.#l?.destroy(),this.#l=void 0,this.#r.release(),this.#r=void 0,this.#d=void 0,this.#s.release(),this.#s=void 0,this.#n.release(),this.#n=void 0,this.#e.release(),this.#d=void 0,this.#a.release(),this.#a=void 0,this.#h.unsubscribe(),this.#h=void 0,this.#t.reset(),this.#t=void 0,this.#c?.destroy(),this.#c=void 0,this.rootElement.remove(),this.rootElement=void 0,this.#o.destroy(),this.#o=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.appState=_.destroyed}}const Mi={Container:Wt,createChoiceContainer:Gt,createAreaControl:Dt,createButtonControl:Ht,createRelativeLayout:ye,getRootEl:_t,classnamesPrefix:N},_i={version:ce};export{b as CustomError,f as EVENT_NAMES,F as INTERACTIVE_CLICK_ACTIONS,Oi as Interactives,Je as ManifestController,_i as SDKInfo,Ot as chapterIdsToVKVideoIds,J as compareVersions,Ii as getChapterIdByVkVideoId,te as getVKVideoIdByMedia,bi as getVideoRawIdByMedia,At as graphEventTypes,Qe as hasEndTemplate,T as interactivesEventTypes,it as isLastChapter,Kt as isSupportedManifest,Ei as isVKVariantItem,Mi as utils,wi as vkVideoIdsToChapterIds};
23
+ `,i}class Oi{#r=null;#s=null;#h=null;#i=null;#u=null;#n=null;#a=null;#o=null;#t=null;#d=new $(!1);#p=new Set;#l=null;#g=null;#c=null;#e=null;#f=Te();state={prevChapter$:new $(null),isInitialChapter$:new $(!1),isEndChapter$:new $(!1),isInteractiveExpectation$:new $(!1),calledByInteractive$:new $(!1),lastChapterChangeWasInitiatedByInteractive$:new $(!1),disabledControls$:new $(!1)};constructor(t){this.options={...Li,...t},this.#s=[],this.factories=new Map([["choice",Ut]]),this.rootElement=Vi(),this.options.parentElement.append(this.rootElement),this.#e=new Zt,this.#u=new tt,this.#h=new Ti,this.#i=new Si({interactiveController:this,globalEventEmitter:this.#e,videoId:this.options.projectInfo?.videoId,historyApi:this.options.historyApi,historyParams:this.options.historyParams}),this.options.lastFrame&&(this.#c=new Ri({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:e=>this.#e.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.SEAMLESS,e))})),this.#h.listen(this.rootElement,"mousedown",e=>e.stopPropagation()),this.#h.listen(this.rootElement,"mouseup",e=>e.stopPropagation()),this.#t=new ti(this.options.loaders,e=>this.#e.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.MANIFEST,e))),this.#n=Lt(this.options.player),this.#a=new Fe,this.#o=jt({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#e,removeControllers:this.#m}),this.#r=ui(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#c.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#l=new Ie({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:e=>{this.setChapter({chapterId:e}),this.#e.emit(f.graph,{type:Rt.watchAgainClicked,chapterId:e})},onError:e=>this.#e.emit(f.errors,new b(b.Severity.RECOVERABLE,b.Category.LOADERS,{message:e}))})),this.#E(this.options.initSeamless),this.isFirstChapterFetched=!1,this.appState=_.created}emitPlayerChanged=t=>{setTimeout(()=>{this.#e.emit(f.playerChanged,t)})};#E(t=!1){this.#e.on(f.historyInited,async({initChapterId:e,videosInfo:n=[]})=>{t&&await this.#I({initialChapter:e,videosInfo:n})}),this.#e.on(f.interactives,async e=>{if(e.type===T.actionExecution){if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){const{chapterId:r}=e.payload;this.setChapter({chapterId:r})}if(e.payload?.behaviour==="change-manifest"){const{manifestURL:r}=e.payload;this.setManifest(r)}const n=e.type==="action-execution";n&&e.actionType==="expect"?this.state.isInteractiveExpectation$.next(!0):n&&e.actionType==="after-expect"&&this.state.isInteractiveExpectation$.next(!1)}}),this.#e.on(f.manifestChanged,()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})}async#I({source:t,videosInfo:e=[]}){this.#g=si(this);const n=document.createElement("div");this.#g.on(Z.activePlayerChanged,this.emitPlayerChanged);const{player:r,config:s}=await this.#g.init({source:t,initialChapter:this.#i.getInitialChapterId(),container:n});return this.updateGraphVideosInfo(e),{player:r,config:s}}getStatEvents(){return{click$:new mt(t=>{this.#e.on(f.graph,({type:e,visibility:n})=>{e==="visibility"&&t.next(n?F.OPEN_GRAPH:F.CLOSE_GRAPH),e==="watchAgainClicked"&&t.next(F.WATCH_AGAIN)}),this.#e.on(f.interactives,({type:e,subjectName:n,subjectType:r})=>{e!=="action-choice"||n!=="control"||(r==="Button"&&t.next(F.GO_NEXT_BUTTON),r==="Area"&&t.next(F.GO_NEXT_AREA))})}),nextMovie$:new mt(t=>{this.#e.on(f.playerChanged,({config:e})=>{e?.unitedVideoId&&t.next(e.unitedVideoId)})})}}setPlayer(t){this.#v(),this.options.player=t,this.#f.setPlayer(this.options.player),this.#n?this.#n.setPlayer(this.options.player):this.#n=Lt(this.options.player),this.#o=jt({player:this.options.player,interactiveEvents:this.#n,globalEventEmitter:this.#e,removeControllers:()=>this.#m(!1)}),this.appState===_.initiated&&(this.#C(),this.#y(this.#t.chapter))}async setManifest(t){this.#v(),this.isFirstChapterFetched=!1;const e=await this.#t.setManifest(t);return this.#l&&await this.#l.handleManifestChange(e.manifest),await this.#i.setManifest(e.manifest),this.#e.emit(f.manifestChanged,{manifest:e.manifest}),this.#y(this.#t.chapter),e.manifest}setVisitedChapters(t){Array.isArray(t)&&this.#l?.setVisitedChapters(t)}updateGraphVideosInfo(t){Array.isArray(t)&&this.#l?.updateVideosInfo(t)}async setChapter({chapterId:t,pushToHistory:e=!0}={}){this.#v(),this.#c&&this.isFirstChapterFetched&&(this.#c.draw(),this.#c.show()),ie().browser===ne.Safari&&await Ai(35);const r=await(t?this.#t.setNext(t):this.#t.setInitial()),{chapter:s,media:o,graph:a}=r;return e&&this.#R(s.id),this.state.isInitialChapter$.next(this.#t.isInitialChapter()),this.state.isEndChapter$.next(this.#t.isEndChapter()),this.#l&&this.#l.handleChapterChange(a),this.#c?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(f.chapterChanged,{chapter:s,media:o,graph:a}),this.#y(this.#t.chapter),this.#p=new Set,this.isFirstChapterFetched=!0,{chapter:s,media:o,graph:a}}toggleGraphView(t=!0){this.#l&&(t?(this.#l.show(),this.#d.next(!1)):(this.#l.hide(),this.#b()),this.#e.emit(f.graph,{type:Rt.visibility,visibility:t}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.appState===_.created&&(this.#r.resizeObserver.observe(this.options.fullscreenTargetElement),this.#C(),this.appState=_.initiated,this.#y(this.#t.chapter))}#v(){this.appState===_.ready&&(this.#m(),this.#s=[],this.#a.release(),this.#n?.release(),this.appState=_.initiated,this.#d.next(!1))}#A=()=>{this.#a.fns.forEach(n=>n());const t=this.options.player.info.position$.getValue()*1e3,e=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(t));for(const n of e){this.#n.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const r of n.controls)this.#n.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#s.find(r=>r.container.container.id===n.id).reset()}};#w=()=>{this.#r.calc(),this.#a.requestAnimation()};#S(t){(!this.#l||this.#l.isHidden)&&this.#b();const e=t*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>e>=s[1]);if(r){const s=r.range.join("-");this.#p.has(s)||(this.#p.add(s),this.#e.emit(f.interactives,{type:T.rangeEnded,payload:r,visibility:!0}))}}deadEndCheck(){return!(this.#n?.getPreparedToExecActions()??[]).some(n=>n.actionType===w.setNextBranch)}allControlsAreRemoved(){return!this.#s.some(e=>!e.container.isRemoved)}isEndedExpectation(){if(!this.options?.player||!this.#s)return!1;const t=this.options.player.info.position$.getValue(),e=this.options.player.info.duration$.getValue();return t===e&&this.#s.some(n=>{const r=n.container.container;return!r.isRemoved&&r.endTime===null&&W(r.events)})}#C(){this.#u.unsubscribe(),this.#u.add(this.options.player.events.started$.pipe(se()).subscribe(this.#w)).add(this.options.player.events.playing$.subscribe(this.#a.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#a.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#S.bind(this))).add(this.#t.prevChapter$.subscribe(t=>this.state.prevChapter$.next(t))),this.options.lastFrame&&this.#u.add(this.options.player.info.duration$.subscribe(t=>{this.#c.setVideoDuration(t*1e3)})).add(this.options.player.experimental.element$.subscribe(t=>{t&&this.#c.setVideoElement(t)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#c.reset(),setTimeout(()=>{this.#c.hide(),this.#c.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#c.onSeek))}#m=(t=!0)=>{this.#s.forEach(e=>{!t&&e.isPermanentText||(this.#a.removeFn(e.whilePlaying),e.destroy())})};#y(t){this.#t.chapter&&this.appState===_.initiated&&(this.#o.setManifestChapterEvents(t),this.#s=this.#T(t),this.#n.containersEventsCallState.setData(t.containers),this.#f.setContainers(this.#s.map(e=>e.container.container).filter(e=>!Yt(e.controls))),this.options.lastFrame&&this.#a.addFn(()=>{this.#c.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.appState=_.ready)}#T(t){return t?.containers?.reduce((e,n)=>{const r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){const o=new ri({player:this.options.player,container:s(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#o,interactiveEvents:this.#n,globalEventEmitter:this.#e,ignoreContainerEvent:()=>Je(n,this.#s),permanentTextControls:this.options.permanentTextControls,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.#f.deleteContainer(n.id)}});return this.#a.addFn(o.whilePlaying,!0),[...e,o]}return[...e]},[])??[]}#b(){if(this.state.isInteractiveExpectation$.getValue()){this.#d.next(!1);return}const e=this.#d.getValue(),n=!!this.#f.getNextInteractiveTime();(n&&!e||!n&&e)&&this.#d.next(!e)}#x(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}#R(t){if(this.#x(),!this.#i.inited)return;const e=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),n=this.state.prevChapter$.getValue(),r=(n&&et(n)&&Xe(n))??!1,s=this.#t.manifest.metadata.initChapterId===t,o=this.#i.state.history$.getValue();if(s||r&&e){this.#i.updateHistory([t]);return}o.at(-1)!==t&&this.#i.updateHistory([...o,t])}playPrevChapter(){this.#i?.goBack()}setDisabledControls(t){this.state.disabledControls$.next(t)}isSupport(t=this.#t.manifest){return qt(t.metadata.version)}getInitialVideoInfo(){return{videoId:this.#i.getInitialVideoId(),chapterId:this.#i.getInitialChapterId()}}getHistoryState(){return this.#i.state}getIsSeekable(){return this.#d}getInteractiveRanges(){return Ye(this.#t.chapter?.containers)}getNextInteractiveStartTime(t){return this.#f.getNextInteractiveTime(t)}getChapterBranches(t){return this.#t.getBranches(t)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(t,e){this.factories.set(t.trim().toLowerCase(),e)}removeFactory(t){this.factories.delete(t.trim().toLowerCase())}on(...t){return this.#e.on(...t),this}off(...t){return this.#e.off(...t),this}once(...t){return this.#e.once(...t),this}destroy(){this.#m(),this.#s=void 0,this.state=void 0,this.#l?.destroy(),this.#l=void 0,this.#r.release(),this.#r=void 0,this.#o=void 0,this.#a.release(),this.#a=void 0,this.#n.release(),this.#n=void 0,this.#t.release(),this.#o=void 0,this.#h.release(),this.#h=void 0,this.#u.unsubscribe(),this.#u=void 0,this.#e.reset(),this.#e=void 0,this.#c?.destroy(),this.#c=void 0,this.rootElement.remove(),this.rootElement=void 0,this.#i.destroy(),this.#i=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.appState=_.destroyed}}const Mi={Container:Gt,createChoiceContainer:Ut,createAreaControl:Ft,createButtonControl:Dt,createRelativeLayout:me,getRootEl:Mt,classnamesPrefix:N},_i={version:oe};export{b as CustomError,f as EVENT_NAMES,F as INTERACTIVE_CLICK_ACTIONS,Oi as Interactives,ti as ManifestController,_i as SDKInfo,Nt as chapterIdsToVKVideoIds,Y as compareVersions,Ei as getChapterIdByVkVideoId,Jt as getVKVideoIdByMedia,Ci as getVideoRawIdByMedia,Rt as graphEventTypes,Xe as hasEndTemplate,T as interactivesEventTypes,et as isLastChapter,qt as isSupportedManifest,bi as isVKVariantItem,Mi as utils,Ii as vkVideoIdsToChapterIds};
package/index.d.ts CHANGED
@@ -74,6 +74,7 @@ declare class Interactives {
74
74
  prevChapter$: ValueSubject<null>;
75
75
  isInitialChapter$: ValueSubject<boolean>;
76
76
  isEndChapter$: ValueSubject<boolean>;
77
+ isInteractiveExpectation$: ValueSubject<boolean>;
77
78
  calledByInteractive$: ValueSubject<boolean>;
78
79
  lastChapterChangeWasInitiatedByInteractive$: ValueSubject<boolean>;
79
80
  disabledControls$: ValueSubject<boolean>;
@@ -103,16 +104,19 @@ declare class Interactives {
103
104
  */
104
105
  setVisitedChapters(chapterIds: string[]): void;
105
106
  /**
106
- * @param {Object[]} videosInfo
107
- * @param {string} videosInfo[].id
108
- * @param {string} videosInfo[].cover
109
- * @param {string|undefined} videosInfo[].title
107
+ * @typedef {Object} VideosInfo
108
+ * @property {string} id
109
+ * @property {string} cover
110
+ * @property {string=} title
111
+ */
112
+ /**
113
+ * @param {Array<VideosInfo>} videosInfo
110
114
  */
111
115
  updateGraphVideosInfo(videosInfo: {
112
116
  id: string;
113
117
  cover: string;
114
- title: string | undefined;
115
- }): void;
118
+ title?: string | undefined;
119
+ }[]): void;
116
120
  /**
117
121
  * Set new chapter
118
122
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.9-dev.fb906f6e.0",
3
+ "version": "1.0.10-beta.0",
4
4
  "author": "vk.com",
5
5
  "description": "Movika interactive SDK",
6
6
  "homepage": "https://vk.com",
@@ -50,8 +50,8 @@
50
50
  ],
51
51
  "dependencies": {
52
52
  "@interactiveplatform/movika-graph-editor": "^1.11.0",
53
- "@vkontakte/videoplayer-core": "^2.0.99",
54
- "@vkontakte/videoplayer-shared": "^1.0.33",
53
+ "@vkontakte/videoplayer-core": "2.0.102-beta.0",
54
+ "@vkontakte/videoplayer-shared": "1.0.35-beta.0",
55
55
  "uuid": "^9.0.0"
56
56
  }
57
57
  }