@vkontakte/videoplayer-interactive 1.0.7-beta.0 → 1.0.7-dev.6643328a.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/es2015.cjs.js +3 -3
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +3 -3
- package/es2018.esm.js +3 -3
- package/esnext.cjs.js +3 -3
- package/esnext.esm.js +3 -3
- package/evergreen.esm.js +3 -3
- package/package.json +3 -3
package/esnext.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-interactive v1.0.7-
|
|
3
|
-
* Thu, 15 Feb 2024
|
|
2
|
+
* @vkontakte/videoplayer-interactive v1.0.7-dev.6643328a.0
|
|
3
|
+
* Thu, 15 Feb 2024 18:13:27 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-7/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{loadVKLangPack as st,ValueSubject as $,Subscription as re,Observable as me,getCurrentBrowser as rt,CurrentClientBrowser as at,once as ot}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as ct}from"uuid";import{Player as lt}from"@vkontakte/videoplayer-core/esnext.esm.js";const ht="1.0.7-beta.0";function Pe(i,e=1){let t="0",n="0",r="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+r},${e})`}const N="SDK_NAME",dt="SDK_NAME-controls-container",Ve=()=>document.querySelector(`.${dt}`),ut=.4,_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ye={top:"flex-start",bottom:"flex-end",center:"center"},ge={start:"flex-start",end:"flex-end",center:"center"},ve={start:"left",end:"right",center:"center"},ke=({target:i,props:e})=>{i.style.alignItems=ye[e?.text?.gravityVertical]??ye.center,i.style.justifyContent=ge[e?.text?.gravityHorizontal]??ge.center,i.style.textAlign=ve[e?.text?.alignment]??ve.start},Fe=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},$e=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Pe(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},Be=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Pe(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},ae=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class oe{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${N}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??_.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",s=>{s.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const De=i=>{if(i.type.trim().toLowerCase()==="area")return new pt(i)};class pt extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");return s.classList.add(`${N}-${this.control.id}`),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",$e({target:s,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),Be({target:s,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),ae({target:s,layoutParams:this.control.layoutParams,fallback:_}),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new ft(i)};class ft extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");s.type="button",s.classList.add(`${N}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:_}),$e({target:s,props:this.control.props,fallback:_}),Be({target:s,props:this.control.props,fallback:_,dependsOn:n}),ke({target:s,props:this.control.props}),Fe({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const mt=i=>{if(i.type.trim().toLowerCase()==="text")return new yt(i)};class yt extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("div");s.classList.add(`${N}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:_}),ke({target:s,props:this.control.props}),Fe({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class gt{constructor(e){this.layout=e}}const vt=i=>{if(i.type.trim().toLowerCase()==="relative")return new Ge(i)};class Ge extends gt{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class ze{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...e,r(t)]:[...e]},[])}}const Ue=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new bt(i,e)};class bt extends ze{constructor(e,t){super(e),this.rootElement=t??Ve(),this.layout=new Ge(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",We),this.addControlFactory("text",mt),this.addControlFactory("area",De)}createView(e){const t=document.createElement("div");return t.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const r=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(r,e)}),this.rootElement.append(t),this.isRemoved=!1,t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}enable(){const e=this.getElement();e&&(e.style.opacity=1,this.isDisabled=!1)}disable(){const e=this.getElement();e&&(e.style.opacity=ut,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function He(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const H={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ce=i=>z(i,H.Object),ne=i=>z(i,H.String),le=i=>z(i,H.Array),qe=i=>z(i,H.Number),Ct=i=>z(i,H.Function),be=i=>qe(i)&&!isNaN(i),U=i=>ce(i)&&Object.keys(i).length===0,he=i=>le(i)&&!i.length,Q=(i,e)=>ne(i)&&(e?i.trim():i).length,Qe=window.navigator.userAgent.toLowerCase(),Et=/mobi/i.test(Qe);Qe.indexOf("android")>-1;const wt="video_interactive",It="videoint",St=250;class Tt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=t,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=xt(e),this.resizeObserver=new ResizeObserver(He(this.onResize,St)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!qe(e.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 st(this.lang,wt,It)}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(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}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 xt(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const Y=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Rt="3.1",Ce={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},At={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Lt=i=>{const e=[];for(const t of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let f=[At];switch(a){case"await":l?f=[]:s=[];break;case"default":{const u={type:"onSuspense",action:{type:Ce.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[u]:s=[u];break}case"random":case"weightlessRandom":case"max":case"min":{const u={type:"onSuspense",action:{type:Ce[a],args:{}}};l?f=[u]:s=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:ct(),events:f})}e.push({...t,containers:o,events:s,branches:r})}return i.metadata.version=Rt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},jt="3.2",Ot=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:jt},media:e}}return i},Nt="3.3",_t=(i=[])=>({edit:{chapters:i},view:{}}),Ee={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Mt=i=>{const e=[],t=[];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:f,type:u,...b})=>({...b,type:f??u})),events:l.events?.length?l.events:[Ee]}));e.push({id:r,...a,containers:c,events:a.events?.length?a.events:[Ee]}),t.push({id:r,x:s,y:o})}return{...i,chapters:e,graph:_t(t),metadata:{...i.metadata,version:Nt}}},Pt=[{version:"3.0",migrate:Lt},{version:"3.1",migrate:Ot},{version:"3.2",migrate:Mt}],Vt=i=>Pt.reduce((e,t)=>Y(e.metadata.version,t.version)?e:t.migrate(e),i),kt=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 B;(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"})(B||(B={}));const we={metadata:"Object",chapters:"Array"},Ft="3.0.0",$t="3.3.0",Xe=i=>{const e=Y(i,Ft);return e===-1?!1:e===0?!0:Y(i,$t)!==1},Bt=i=>{if(!ce(i))return!1;for(const e in we)if(!i[e]||!z(i[e],we[e]))return!1;return Xe(i.metadata.version)},Ze=i=>i.type===kt.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,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 Ke{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===t){n.splice(r,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Dt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{Ct(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Wt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Gt(...this.loaders[e])(t)}}function Gt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function J(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function se({actions:i,errors:e,chapterId:t,...n}){if(t){const r=i.getManifest(),s=i.getChapter(r.chapters,t);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:e,result:{chapter:s,media:o,graph:a}}:{...n,errors:J(e,se.name,"Could not find media"),actions:i}}}return{...n,errors:J(e,se.name,"Could not find chapter"),actions:i}}class Ie{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,n){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:n})}removeEventListener(e,t){if(!(e in this.listeners))return;const n=this.listeners[e];for(let r=0,s=n.length;r<s;r++)if(n[r].callback===t){n.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const n=this.listeners[e.type].slice();for(let r=0,s=n.length;r<s;r++){const o=n[r];try{o.callback.call(this,e)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Ye extends Ie{constructor(){super(),this.listeners||Ie.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class zt{constructor(){Object.defineProperty(this,"signal",{value:new Ye,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let n=e;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(zt.prototype[Symbol.toStringTag]="AbortController",Ye.prototype[Symbol.toStringTag]="AbortSignal");function Je(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Ut(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Je({fetch:e,Request:t,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,f){let u;f&&f.signal&&(u=f.signal,delete f.signal);const b=new t(l,f);return u&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),b},s.prototype=t.prototype);const o=e;return{fetch:(c,l)=>{const f=s&&s.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(f){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(f.aborted)return Promise.reject(u);const b=new Promise((C,L)=>{f.addEventListener("abort",()=>L(u),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:s}}const de=Je({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),et=de?Ut({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Se=de?et.fetch:window.fetch;de?et.Request:window.Request;const Ht=async i=>{try{let e,t;if(ce(i))e=i;else if(ne(i)){t=new URL(i).href;const r=await Se(t);if(!r.ok)return{};e=await r.json()}else return{};if(!Bt(e))return{};const n=e.metadata.media;if(ne(n)&&!e.media)try{let r;t?r=new URL(n,t).href:(r=new URL(n).href,t=r);const s=await Se(r);if(!s.ok)throw new Error;e.metadata.media=await s.json()}catch{return Zt(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function qt(i){const{manifest:e,manifestURL:t}=await Ht(i),n=Vt(e);return n.media=Qt(n.media,t),delete n.metadata.media,n}function te(i,e){return i.find(t=>t.id===e)}function Te(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function xe(i,e){return i.videos.find(t=>t.id===e)}function Qt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const r=Xt(n.url,e);return{...n,url:r||n.url}})}))}}function Xt(i,e){try{return new URL(i,e).href}catch{return""}}function Zt(i){return Y(i,"3.2.0")>=0}class Kt extends Wt{constructor(e,t){super(e),this.onError=t,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(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:J},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await qt(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const t=await this.exec("chapterLoaders",se({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Te,getChapter:te,getMedia:xe,getByBranches:this.getByBranches.bind(this),addErrorMessage:J},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=te(this.manifest.chapters,e);if(t){const n=xe(this.manifest.media,t.videoId),r=Te(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:r}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=te(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const r=this.getByChapterId(n.chapterId);return r&&t.push(r),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Re={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function Yt(){const i=new Map;function e({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 t(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)t(r[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function Ae(i,e=[]){let t={},n;const r=!e.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||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:s.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:t,thumbUrl:n,title:i.title??""}}const X=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},Jt=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},K={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ei=2;function ti(i){const e=Yt();let t,n;const r=new Ke;let s={},o=!1,a=null,c=!1,l;i&&f(i);function f(d){a=d}function u(d,g,m){if(!a)throw Error("need to set interactive controller");const E=(e.map.get(d)??{})[g];if(E){s={chapterId:m,listId:d,itemId:g,...E};const x=s.player;n=x.info.currentQuality$.subscribe(v=>{if(!(!v||!x.info.position$.getValue())){t=v;for(const j of e.map)Object.values(j[1]).forEach(({player:O})=>{x.info.isAutoQualityEnabled$.getValue()||X(O,v)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),r.emit(K.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(U(s)||d!==s.itemId)return;if(m>=0&&!o){const E=a.getChapterBranches();o=!0;const x=new Set;for(const v of E)x.has(v.media.id)||(await L({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),x.add(v.media.id))}}async function C({chapter:{id:d},media:g}){if(U(s))return;n?.unsubscribe();const m=s.player.info.muted$.getValue(),S=s.player.info.currentQuality$.getValue(),E=s.player.info.isAutoQualityEnabled$.getValue(),x=s.player.info.volume$.getValue(),v=s.player.info.currentPlaybackRate$.getValue(),j=!E;let O=!1;for(const R of e.map)if(R[0]===g.id){const k=Object.keys(R[1]);for(const M of k)M===s.itemId?(k.length<ei||(O=!0),e.removePlayer(R[0],M)):(O=!0,u(R[0],M,d),j?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(m),s.player.setPlaybackRate(v))}else e.removePlayer(R[0]);O||(await L({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),j?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(m))}async function L({media:d,chapterId:g,prefetch:m=!0,setAsActive:S=!0,autoplay:E=!1,preferredExt:x,title:v,playbackRate:j}){const O=Math.random().toString(),R=document.createElement("div");l.append(R);const k=s?.player?.info.isAutoQualityEnabled$.getValue();let M;if(a?.options?.vkVideoLoader){const q=Jt(d);q.length&&(M=await a.options.vkVideoLoader(...q))}const pe={container:R,...M?.videos?.[0]||{sources:Ae(d,x).sources},title:v},F=new lt;F.initVideo(pe);const nt=R.lastChild,fe=new re;fe.add(F.info.position$.subscribe(function(q){b(O,F.info.duration$.getValue(),q)})).add(F.events.canplay$.subscribe(function(){k||X(F,t),j&&F.setPlaybackRate(j)})),nt&&(R.style.display="none",R.classList.add(g));const D=e.createPlayer({listId:d.id,itemId:O,player:F,container:R,sources:Ae(d,x).sources,config:pe,subscription:fe});return S&&u(d.id,D.itemId,g),E&&D.player.play(),m&&!E&&D.player.prepare(),r.emit(K.playerCreated,D.player),{player:D.player,config:D.config}}function V(){h(),a=null}function h(){a?.off(y.chapterChanged,C),e.removeAll(),s={},c=!1,o=!1}async function p({source:d,initialChapter:g,container:m}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=m;const{media:S,chapter:E}=await a.setChapter({chapterId:g});if(S){a.on(y.chapterChanged,C);const{player:x,config:v}=await L({media:S,chapterId:E.id,title:E.label});return r.emit(K.initiated,{container:m,media:S,chapterId:E.id}),{player:x,config:v}}else console.error("not found")}return{...e,on:r.on.bind(r),off:r.off.bind(r),init:p,setInteractiveController:f,createPlayer:L,removeAll:V,getActivePlayer:function(){return s}}}const ii=3e3,ni=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=ii)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const f of i){const u=f.startTime-o;if(u<=l&&(l<=f.endTime||f.endTime===null)){c=!0;break}l<u&&(a=a===-1?u:Math.min(a,u))}return!c&&a!==-1?a:null}}},W=ni(),I=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),ue=i=>le(i)&&!he(i),tt=i=>he(i.branches)||i.order==="end",si=i=>le(i.branches)&&!he(i.branches),ri=(i,e)=>{const t=i*1e3;return ue(e.controls)&&t<(e.startTime??0)},Le=(i,e)=>{const t=i*1e3;return ue(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ee=i=>i.some(e=>e.action.type==="expect"),je=i=>i.find(e=>e.action.type==="expect"),ai=i=>i?.length===1,it=i=>ai(i)&&Ze(i[0]),oi=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),ci=(i=[])=>i.reduce((e,t,n)=>{const r=(t?.controls??[]).filter(s=>!Ze(s));if(ue(r)){const s=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:s});else{const a=[];let c=-1/0,l=1/0,f=[];const u=[];for(let b=0;b<e.length;b++){const C=e[b];if(u.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 e[b].subjects.push(o),e;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[1]=C.range[1])}if(u.push(o),s[0]<=l&&s[1]>=c)return[{subjects:u,range:s}];a.length&&a.reverse().forEach(b=>{e.splice(b,1)}),e.push({subjects:f.concat([o]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),li=(i,e)=>ee(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ee(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class hi{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c}){this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new re,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&it(t.container.controls),this.globalEventEmitter=o,this.gameState=I.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))}hide=()=>{setTimeout(()=>{this.gameState!==I.end&&(ee(this.container.container.events)&&this.gameState===I.afterInteractive||this.selectBranches.state.isExpect||(this.gameState===I.interactive?this.container.disable?.():this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===I.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.container.enable?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const t=oi({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.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(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===I.end||this.gameState===I.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),W.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===I.end});this.container.createView(t),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ee(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=I.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[I.destroyed,I.removed].includes(this.gameState)&&!this.isPermanentText)return;const t=this.player.getExactTime();if(ri(t,this.container.container))this.gameState!==I.beforeInteractive&&(this.gameState=I.beforeInteractive,this.onBeforeStartTime());else if(Le(t,this.container.container))this.gameState!==I.interactive&&(this.gameState=I.interactive,this.onStartTime());else if(this.gameState!==I.afterInteractive){const s=this.gameState;this.gameState=I.afterInteractive,s===I.interactive&&this.onEndTime()}else this.gameState!==I.destroyed&&this.removeView();const n=Le(t,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=I.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=I.removed}destroy(){this.reset(),this.removeView(),this.gameState=I.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),W.deleteContainer(this.container.container.id)}}function di(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(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(be(a)){const f=i[a]??null;if(f&&Q(c,!0)){let u={};const b=f[c];return b&&(u={...u,...b}),u=U(u)?null:u,u&&Q(l,!0)?u[l]??null:u}return f}return null}function s({timestamp:a,priority:c,initiator:l}){if(be(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],!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,...f}){i[a]?.[c]?.[l]?i[a][c][l].push({...f}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...f}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...f}]}}:i[a]={[c]:{[l]:[{...f}]}}}return{map:i,remove:s,add:o,removeAll:e,get:r,getLte:t,getGte:n}}const ui=[w.expect,w.setNextBranch],pi=1/0;function Oe(i){let e=i,t;const n=fi(),r=new di;let s;const o=()=>{u(),V()},a=h=>{r.add.call(void 0,h),b()},c=(h=[])=>{for(const p of h)if(p.action(),ui.includes(p.actionType))break},l=h=>{if(!n.isReady(h))return;const p=Z(r.get({timestamp:h,priority:"control"})??{}),d=Z(r.get({timestamp:h,priority:"container"})??{}),g=Z(r.get({timestamp:h,priority:"chapter"})??{});c([...p,...d,...g])},f=()=>{c([...Z(r.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{t&&(s?.unsubscribe(),t=void 0)},b=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),s=e.events.ended$.subscribe(t))},C=h=>{u(),e=h},L=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),r.remove(h)},V=()=>{n.release(),r.removeAll()};return{setPlayer:C,add:a,remove:L,exec:l,execEndOfVideo:f,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function fi(){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??pi,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(e=>e.actionType===w.expect?-1:1)}const mi=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=e.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=t/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}},yi=250;function gi(i){let e=()=>{};const t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:u}=mi(c,l);c.style.setProperty("--interactive-content-width",`${f}px`),c.style.setProperty("--interactive-content-height",`${u}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=He(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},yi);function o(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e()},release:o}}class vi{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const bi=i=>Math.floor(Math.random()*i),Ci=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},Ei=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},wi=i=>{const e=i.length,t=bi(e);return i[t]},Ne=1,Ii=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Ne;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Ne,e>=t)return i[n];return i[i.length-1]},_e=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),ie=(i,e=!1)=>({...i,args:e?{...i.args,..._e}:{..._e,...i.args}}),Me=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:h,controlType:p,controlId:d,containerId:g,branches:m=[],onEvent:S,isEOV:E=()=>!1,isDisabled:x=()=>!1})=>{const v=ie(h,E()),j={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},O=x(),R=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:p,subjectName:"control",type:O?T.actionChoiceCanceled:T.actionChoice,actionType:h.type,payload:{containerId:g,...v.args}});if(O){R();return}switch(v.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const k=m.find(M=>M.id===v.args.branchId);if(!k)return;S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),R(),v.args.shouldOpenNow?L({subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(t.add({...j,action:L.bind(null,{subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),R(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:p,action:h}):t.add({...j,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:p,action:h})});return}case w.openURI.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),R(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{URI:h.args.uri}}):(t.add({...j,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:p,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:S=!1})=>{const E=ie(h,m),x={timestamp:!E.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:p,actionType:E.type},v=i.emit.bind(i,y.interactives,{subjectId:p,subjectName:"container",type:T.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const j=g.find(O=>O.id===E.args.branchId);if(!j)return;v(),t.add({...x,action:L.bind(null,{subjectId:p,subjectName:"container",action:E,payload:{chapterId:j.chapterId,autoSelect:S}})}),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(),t.add({...x,action:C.bind(null,{subjectId:p,subjectName:"container",action:E})});return}case w.openURI.trim().toLowerCase():{v(),t.add({...x,action:V.bind(null,{subjectId:p,subjectName:"container",action:E,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:p,isEOV:d=!1}){const g=je(h.events);if(g){const m=ie(g.action,d);i.emit(y.interactives,{subjectId:h.id,subjectName:"container",type:T.actionChoice,actionType:m.type,payload:m.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:w.expect,action:u.bind(null,{subjectId:h.id,subjectName:"container"})}),r.isExpect=!0}else for(const m of h.events)a({action:m.action,container:h,branches:p,isEOV:d})}const l=({chapterId:h,action:p,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"chapter",type:T.actionChoice,actionType:p.type,payload:p.args});switch(p.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const m=d.find(S=>S.id===p.args.branchId);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const m=wi(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const m=Ii(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const m=Ei(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const m=Ci(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:h,subjectName:"chapter",action:p});case w.openURI.trim().toLowerCase():return g(),V.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{URI:p.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function f(h){const p=je(h.events);if(p){if(tt(h))return;i.emit(y.interactives,{subjectId:h.id,subjectName:"chapter",type:T.actionChoice,actionType:p.action.type,payload:p.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:w.expect,action:u.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const g=l({chapterId:h.id,action:d.action,branches:h.branches});g&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:g})})}const u=({subjectId:h,subjectName:p,action:d})=>{e.pause(),i.emit(y.interactives,{subjectId:h,subjectName:p,type:T.actionExecution,actionType:d?.type??w.expect})},b=({subjectId:h,subjectName:p})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(y.interactives,{subjectId:h,subjectName:p,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:h,subjectName:p,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:h,subjectName:p,subjectType:d,type:T.actionExecution,actionType:g.type})},L=({subjectId:h,subjectName:p,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:h,subjectName:p,subjectType:d,type:T.actionExecution,actionType:g.type,payload:m})},V=({subjectId:h,subjectName:p,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const S=window.open(m.URI,"_blank","noopener,noreferrer");S&&(S.opener=null),i.emit(y.interactives,{subjectId:h,subjectName:p,subjectType:d,type:T.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:u,expectEventHandler:b,setManifestChapterEvents:f,setManifestContainerEvents:c,stopExpect:s,state:r}};class G{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=G.#a(e,r),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),r=Object.keys(t).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),G.#c(e)?t:t.capture||!1}}static#s=void 0;static#c(e){let t=G.#s;if(t===void 0){t=!1;try{const n={},r={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};e.addEventListener("test",s,n),e.removeEventListener("test",s,n)}catch{t=!1}G.#s=t}return t||!1}}class Si{constructor(){this.bindingMap=new vi}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;const s=new G(e,t,n,r);this.bindingMap.push(t,s)}listenOnce(e,t,n,r){const s=o=>{this.unlisten(e,t,s),n(o)};this.listen(e,t,s,r)}unlisten(e,t,n){if(!this.bindingMap)return;const r=this.bindingMap.get(t)||[];for(const s of r)s.target===e&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(t,s))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class Ti{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 e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let r=3;r<n;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class xi{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
6
|
+
import{loadVKLangPack as st,ValueSubject as $,Subscription as re,Observable as me,getCurrentBrowser as rt,CurrentClientBrowser as at,once as ot}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as ct}from"uuid";import{Player as lt}from"@vkontakte/videoplayer-core/esnext.esm.js";const ht="1.0.7-dev.6643328a.0";function Pe(i,e=1){let t="0",n="0",r="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+r},${e})`}const N="SDK_NAME",dt="SDK_NAME-controls-container",Ve=()=>document.querySelector(`.${dt}`),ut=.4,_={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ye={top:"flex-start",bottom:"flex-end",center:"center"},ge={start:"flex-start",end:"flex-end",center:"center"},ve={start:"left",end:"right",center:"center"},ke=({target:i,props:e})=>{i.style.alignItems=ye[e?.text?.gravityVertical]??ye.center,i.style.justifyContent=ge[e?.text?.gravityHorizontal]??ge.center,i.style.textAlign=ve[e?.text?.alignment]??ve.start},Fe=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},$e=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Pe(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},Be=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Pe(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},ae=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class oe{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${N}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??_.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",s=>{s.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${N}-control-container-${this.control.id}`)}}const De=i=>{if(i.type.trim().toLowerCase()==="area")return new pt(i)};class pt extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");return s.classList.add(`${N}-${this.control.id}`),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",$e({target:s,props:this.control.props,fallback:{..._,backgroundColor:"transparent"}}),Be({target:s,props:this.control.props,fallback:{..._,borderAlpha:0},dependsOn:n}),ae({target:s,layoutParams:this.control.layoutParams,fallback:_}),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const We=i=>{if(i.type.trim().toLowerCase()==="button")return new ft(i)};class ft extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");s.type="button",s.classList.add(`${N}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:_}),$e({target:s,props:this.control.props,fallback:_}),Be({target:s,props:this.control.props,fallback:_,dependsOn:n}),ke({target:s,props:this.control.props}),Fe({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}const mt=i=>{if(i.type.trim().toLowerCase()==="text")return new yt(i)};class yt extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("div");s.classList.add(`${N}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:_}),ke({target:s,props:this.control.props}),Fe({target:o,props:this.control.props,fallback:_,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${N}-${this.control.id}`)}}class gt{constructor(e){this.layout=e}}const vt=i=>{if(i.type.trim().toLowerCase()==="relative")return new Ge(i)};class Ge extends gt{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class ze{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...e,r(t)]:[...e]},[])}}const Ue=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new bt(i,e)};class bt extends ze{constructor(e,t){super(e),this.rootElement=t??Ve(),this.layout=new Ge(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",We),this.addControlFactory("text",mt),this.addControlFactory("area",De)}createView(e){const t=document.createElement("div");return t.classList.add(`${N}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const r=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(r,e)}),this.rootElement.append(t),this.isRemoved=!1,t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}enable(){const e=this.getElement();e&&(e.style.opacity=1,this.isDisabled=!1)}disable(){const e=this.getElement();e&&(e.style.opacity=ut,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${N}-${this.container.id}`)}}function He(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const H={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ce=i=>z(i,H.Object),ne=i=>z(i,H.String),le=i=>z(i,H.Array),qe=i=>z(i,H.Number),Ct=i=>z(i,H.Function),be=i=>qe(i)&&!isNaN(i),U=i=>ce(i)&&Object.keys(i).length===0,he=i=>le(i)&&!i.length,Q=(i,e)=>ne(i)&&(e?i.trim():i).length,Qe=window.navigator.userAgent.toLowerCase(),Et=/mobi/i.test(Qe);Qe.indexOf("android")>-1;const wt="video_interactive",It="videoint",St=250;class Tt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=t,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=xt(e),this.resizeObserver=new ResizeObserver(He(this.onResize,St)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!qe(e.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 st(this.lang,wt,It)}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(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}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 xt(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const Y=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Rt="3.1",Ce={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},At={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Lt=i=>{const e=[];for(const t of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const l=!!c.endTime;let f=[At];switch(a){case"await":l?f=[]:s=[];break;case"default":{const u={type:"onSuspense",action:{type:Ce.default,args:{branchId:n,shouldOpenNow:!l,isDetachContainer:!0}}};l?f=[u]:s=[u];break}case"random":case"weightlessRandom":case"max":case"min":{const u={type:"onSuspense",action:{type:Ce[a],args:{}}};l?f=[u]:s=[u];break}}for(const u of c.controls)o.push({...c,controls:[{...u}],id:ct(),events:f})}e.push({...t,containers:o,events:s,branches:r})}return i.metadata.version=Rt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},jt="3.2",Ot=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:jt},media:e}}return i},Nt="3.3",_t=(i=[])=>({edit:{chapters:i},view:{}}),Ee={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Mt=i=>{const e=[],t=[];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:f,type:u,...b})=>({...b,type:f??u})),events:l.events?.length?l.events:[Ee]}));e.push({id:r,...a,containers:c,events:a.events?.length?a.events:[Ee]}),t.push({id:r,x:s,y:o})}return{...i,chapters:e,graph:_t(t),metadata:{...i.metadata,version:Nt}}},Pt=[{version:"3.0",migrate:Lt},{version:"3.1",migrate:Ot},{version:"3.2",migrate:Mt}],Vt=i=>Pt.reduce((e,t)=>Y(e.metadata.version,t.version)?e:t.migrate(e),i),kt=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 B;(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"})(B||(B={}));const we={metadata:"Object",chapters:"Array"},Ft="3.0.0",$t="3.3.0",Xe=i=>{const e=Y(i,Ft);return e===-1?!1:e===0?!0:Y(i,$t)!==1},Bt=i=>{if(!ce(i))return!1;for(const e in we)if(!i[e]||!z(i[e],we[e]))return!1;return Xe(i.metadata.version)},Ze=i=>i.type===kt.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,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 Ke{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===t){n.splice(r,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class Dt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{Ct(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class Wt{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Gt(...this.loaders[e])(t)}}function Gt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function J(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function se({actions:i,errors:e,chapterId:t,...n}){if(t){const r=i.getManifest(),s=i.getChapter(r.chapters,t);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:e,result:{chapter:s,media:o,graph:a}}:{...n,errors:J(e,se.name,"Could not find media"),actions:i}}}return{...n,errors:J(e,se.name,"Could not find chapter"),actions:i}}class Ie{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,n){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:n})}removeEventListener(e,t){if(!(e in this.listeners))return;const n=this.listeners[e];for(let r=0,s=n.length;r<s;r++)if(n[r].callback===t){n.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const n=this.listeners[e.type].slice();for(let r=0,s=n.length;r<s;r++){const o=n[r];try{o.callback.call(this,e)}catch(a){Promise.resolve().then(()=>{throw a})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Ye extends Ie{constructor(){super(),this.listeners||Ie.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}class zt{constructor(){Object.defineProperty(this,"signal",{value:new Ye,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch{typeof document<"u"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let n=e;if(n===void 0)if(typeof document>"u")n=new Error("This operation was aborted"),n.name="AbortError";else try{n=new DOMException("signal is aborted without reason")}catch{n=new Error("This operation was aborted"),n.name="AbortError"}this.signal.reason=n,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}}typeof Symbol<"u"&&Symbol.toStringTag&&(zt.prototype[Symbol.toStringTag]="AbortController",Ye.prototype[Symbol.toStringTag]="AbortSignal");function Je(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function Ut(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Je({fetch:e,Request:t,AbortController:n,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:s};let s=t;(s&&!s.prototype.hasOwnProperty("signal")||r)&&(s=function(l,f){let u;f&&f.signal&&(u=f.signal,delete f.signal);const b=new t(l,f);return u&&Object.defineProperty(b,"signal",{writable:!1,enumerable:!1,configurable:!0,value:u}),b},s.prototype=t.prototype);const o=e;return{fetch:(c,l)=>{const f=s&&s.prototype.isPrototypeOf(c)?c.signal:l?l.signal:void 0;if(f){let u;try{u=new DOMException("Aborted","AbortError")}catch{u=new Error("Aborted"),u.name="AbortError"}if(f.aborted)return Promise.reject(u);const b=new Promise((C,L)=>{f.addEventListener("abort",()=>L(u),{once:!0})});return l&&l.signal&&delete l.signal,Promise.race([b,o(c,l)])}return o(c,l)},Request:s}}const de=Je({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),et=de?Ut({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Se=de?et.fetch:window.fetch;de?et.Request:window.Request;const Ht=async i=>{try{let e,t;if(ce(i))e=i;else if(ne(i)){t=new URL(i).href;const r=await Se(t);if(!r.ok)return{};e=await r.json()}else return{};if(!Bt(e))return{};const n=e.metadata.media;if(ne(n)&&!e.media)try{let r;t?r=new URL(n,t).href:(r=new URL(n).href,t=r);const s=await Se(r);if(!s.ok)throw new Error;e.metadata.media=await s.json()}catch{return Zt(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function qt(i){const{manifest:e,manifestURL:t}=await Ht(i),n=Vt(e);return n.media=Qt(n.media,t),delete n.metadata.media,n}function te(i,e){return i.find(t=>t.id===e)}function Te(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function xe(i,e){return i.videos.find(t=>t.id===e)}function Qt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const r=Xt(n.url,e);return{...n,url:r||n.url}})}))}}function Xt(i,e){try{return new URL(i,e).href}catch{return""}}function Zt(i){return Y(i,"3.2.0")>=0}class Kt extends Wt{constructor(e,t){super(e),this.onError=t,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(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:J},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await qt(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const t=await this.exec("chapterLoaders",se({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Te,getChapter:te,getMedia:xe,getByBranches:this.getByBranches.bind(this),addErrorMessage:J},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=te(this.manifest.chapters,e);if(t){const n=xe(this.manifest.media,t.videoId),r=Te(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:r}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=te(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const r=this.getByChapterId(n.chapterId);return r&&t.push(r),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Re={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function Yt(){const i=new Map;function e({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 t(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)t(r[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function Ae(i,e=[]){let t={},n;const r=!e.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||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:s.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:t,thumbUrl:n,title:i.title??""}}const X=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},Jt=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},K={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},ei=2;function ti(i){const e=Yt();let t,n;const r=new Ke;let s={},o=!1,a=null,c=!1,l;i&&f(i);function f(d){a=d}function u(d,g,m){if(!a)throw Error("need to set interactive controller");const E=(e.map.get(d)??{})[g];if(E){s={chapterId:m,listId:d,itemId:g,...E};const x=s.player;n=x.info.currentQuality$.subscribe(v=>{if(!(!v||!x.info.position$.getValue())){t=v;for(const j of e.map)Object.values(j[1]).forEach(({player:O})=>{x.info.isAutoQualityEnabled$.getValue()||X(O,v)})}}),E.container.remove(),o=!1,a.setPlayer(E.player),c||(a.init(),c=!0),r.emit(K.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function b(d,g,m){if(!a)throw Error("need to set interactive controller");if(U(s)||d!==s.itemId)return;if(m>=0&&!o){const E=a.getChapterBranches();o=!0;const x=new Set;for(const v of E)x.has(v.media.id)||(await L({media:v.media,chapterId:v.chapter.id,setAsActive:!1,title:v.chapter.label}),x.add(v.media.id))}}async function C({chapter:{id:d},media:g}){if(U(s))return;n?.unsubscribe();const m=s.player.info.muted$.getValue(),S=s.player.info.currentQuality$.getValue(),E=s.player.info.isAutoQualityEnabled$.getValue(),x=s.player.info.volume$.getValue(),v=s.player.info.currentPlaybackRate$.getValue(),j=!E;let O=!1;for(const R of e.map)if(R[0]===g.id){const k=Object.keys(R[1]);for(const M of k)M===s.itemId?(k.length<ei||(O=!0),e.removePlayer(R[0],M)):(O=!0,u(R[0],M,d),j?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(m),s.player.setPlaybackRate(v))}else e.removePlayer(R[0]);O||(await L({media:g,chapterId:d,setAsActive:!0,playbackRate:v}),j?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(m))}async function L({media:d,chapterId:g,prefetch:m=!0,setAsActive:S=!0,autoplay:E=!1,preferredExt:x,title:v,playbackRate:j}){const O=Math.random().toString(),R=document.createElement("div");l.append(R);const k=s?.player?.info.isAutoQualityEnabled$.getValue();let M;if(a?.options?.vkVideoLoader){const q=Jt(d);q.length&&(M=await a.options.vkVideoLoader(...q))}const pe={container:R,...M?.videos?.[0]||{sources:Ae(d,x).sources},title:v},F=new lt;F.initVideo(pe);const nt=R.lastChild,fe=new re;fe.add(F.info.position$.subscribe(function(q){b(O,F.info.duration$.getValue(),q)})).add(F.events.canplay$.subscribe(function(){k||X(F,t),j&&F.setPlaybackRate(j)})),nt&&(R.style.display="none",R.classList.add(g));const D=e.createPlayer({listId:d.id,itemId:O,player:F,container:R,sources:Ae(d,x).sources,config:pe,subscription:fe});return S&&u(d.id,D.itemId,g),E&&D.player.play(),m&&!E&&D.player.prepare(),r.emit(K.playerCreated,D.player),{player:D.player,config:D.config}}function V(){h(),a=null}function h(){a?.off(y.chapterChanged,C),e.removeAll(),s={},c=!1,o=!1}async function p({source:d,initialChapter:g,container:m}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),h(),l=m;const{media:S,chapter:E}=await a.setChapter({chapterId:g});if(S){a.on(y.chapterChanged,C);const{player:x,config:v}=await L({media:S,chapterId:E.id,title:E.label});return r.emit(K.initiated,{container:m,media:S,chapterId:E.id}),{player:x,config:v}}else console.error("not found")}return{...e,on:r.on.bind(r),off:r.off.bind(r),init:p,setInteractiveController:f,createPlayer:L,removeAll:V,getActivePlayer:function(){return s}}}const ii=3e3,ni=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=ii)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const l=e.info.position$.getValue()*1e3;for(const f of i){const u=f.startTime-o;if(u<=l&&(l<=f.endTime||f.endTime===null)){c=!0;break}l<u&&(a=a===-1?u:Math.min(a,u))}return!c&&a!==-1?a:null}}},W=ni(),I=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),ue=i=>le(i)&&!he(i),tt=i=>he(i.branches)||i.order==="end",si=i=>le(i.branches)&&!he(i.branches),ri=(i,e)=>{const t=i*1e3;return ue(e.controls)&&t<(e.startTime??0)},Le=(i,e)=>{const t=i*1e3;return ue(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ee=i=>i.some(e=>e.action.type==="expect"),je=i=>i.find(e=>e.action.type==="expect"),ai=i=>i?.length===1,it=i=>ai(i)&&Ze(i[0]),oi=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),ci=(i=[])=>i.reduce((e,t,n)=>{const r=(t?.controls??[]).filter(s=>!Ze(s));if(ue(r)){const s=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:s});else{const a=[];let c=-1/0,l=1/0,f=[];const u=[];for(let b=0;b<e.length;b++){const C=e[b];if(u.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 e[b].subjects.push(o),e;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(b),f=f.concat(C.subjects),s[1]=C.range[1])}if(u.push(o),s[0]<=l&&s[1]>=c)return[{subjects:u,range:s}];a.length&&a.reverse().forEach(b=>{e.splice(b,1)}),e.push({subjects:f.concat([o]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),li=(i,e)=>ee(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ee(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class hi{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c}){this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new re,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&it(t.container.controls),this.globalEventEmitter=o,this.gameState=I.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))}hide=()=>{setTimeout(()=>{this.gameState!==I.end&&(ee(this.container.container.events)&&this.gameState===I.afterInteractive||this.selectBranches.state.isExpect||(this.gameState===I.interactive?this.container.disable?.():this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===I.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.container.enable?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const t=oi({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.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(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===I.end||this.gameState===I.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),W.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===I.end});this.container.createView(t),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ee(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=I.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[I.destroyed,I.removed].includes(this.gameState)&&!this.isPermanentText)return;const t=this.player.getExactTime();if(ri(t,this.container.container))this.gameState!==I.beforeInteractive&&(this.gameState=I.beforeInteractive,this.onBeforeStartTime());else if(Le(t,this.container.container))this.gameState!==I.interactive&&(this.gameState=I.interactive,this.onStartTime());else if(this.gameState!==I.afterInteractive){const s=this.gameState;this.gameState=I.afterInteractive,s===I.interactive&&this.onEndTime()}else this.gameState!==I.destroyed&&this.removeView();const n=Le(t,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(y.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=I.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=I.removed}destroy(){this.reset(),this.removeView(),this.gameState=I.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),W.deleteContainer(this.container.container.id)}}function di(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(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(be(a)){const f=i[a]??null;if(f&&Q(c,!0)){let u={};const b=f[c];return b&&(u={...u,...b}),u=U(u)?null:u,u&&Q(l,!0)?u[l]??null:u}return f}return null}function s({timestamp:a,priority:c,initiator:l}){if(be(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],!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,...f}){i[a]?.[c]?.[l]?i[a][c][l].push({...f}):i[a]?.[c]?i[a][c]={...i[a][c],[l]:[{...f}]}:i[a]?i[a]={...i[a],[c]:{[l]:[{...f}]}}:i[a]={[c]:{[l]:[{...f}]}}}return{map:i,remove:s,add:o,removeAll:e,get:r,getLte:t,getGte:n}}const ui=[w.expect,w.setNextBranch],pi=1/0;function Oe(i){let e=i,t;const n=fi(),r=new di;let s;const o=()=>{u(),V()},a=h=>{r.add.call(void 0,h),b()},c=(h=[])=>{for(const p of h)if(p.action(),ui.includes(p.actionType))break},l=h=>{if(!n.isReady(h))return;const p=Z(r.get({timestamp:h,priority:"control"})??{}),d=Z(r.get({timestamp:h,priority:"container"})??{}),g=Z(r.get({timestamp:h,priority:"chapter"})??{});c([...p,...d,...g])},f=()=>{c([...Z(r.get({timestamp:1/0,priority:"chapter"})??{})])},u=()=>{t&&(s?.unsubscribe(),t=void 0)},b=()=>{t||(t=()=>setTimeout(()=>{l(1/0)}),s=e.events.ended$.subscribe(t))},C=h=>{u(),e=h},L=h=>{h.priority==="container"&&n.resetCalled(h.timestamp),r.remove(h)},V=()=>{n.release(),r.removeAll()};return{setPlayer:C,add:a,remove:L,exec:l,execEndOfVideo:f,listen:b,unlisten:u,release:o,containersEventsCallState:n}}function fi(){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??pi,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(e=>e.actionType===w.expect?-1:1)}const mi=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=e.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=t/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}},yi=250;function gi(i){let e=()=>{};const t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){const{parentElement:c,player:l}=i();if(c&&l){const{videoContentWidth:f,videoContentHeight:u}=mi(c,l);c.style.setProperty("--interactive-content-width",`${f}px`),c.style.setProperty("--interactive-content-height",`${u}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=He(a=>{const{fns:c=[]}=i();n(a);for(const l of c)l()},yi);function o(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e()},release:o}}class vi{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const bi=i=>Math.floor(Math.random()*i),Ci=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},Ei=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},wi=i=>{const e=i.length,t=bi(e);return i[t]},Ne=1,Ii=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Ne;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Ne,e>=t)return i[n];return i[i.length-1]},_e=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),ie=(i,e=!1)=>({...i,args:e?{...i.args,..._e}:{..._e,...i.args}}),Me=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:h,controlType:p,controlId:d,containerId:g,branches:m=[],onEvent:S,isEOV:E=()=>!1,isDisabled:x=()=>!1})=>{const v=ie(h,E()),j={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},O=x(),R=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:p,subjectName:"control",type:O?T.actionChoiceCanceled:T.actionChoice,actionType:h.type,payload:{containerId:g,...v.args}});if(O){R();return}switch(v.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const k=m.find(M=>M.id===v.args.branchId);if(!k)return;S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),R(),v.args.shouldOpenNow?L({subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}}):(t.add({...j,action:L.bind(null,{subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),R(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:p,action:h}):t.add({...j,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:p,action:h})});return}case w.openURI.trim().toLowerCase():{S(v.args.isDetachContainer,b.bind(null,{subjectId:d,subjectName:"control"})),R(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{URI:h.args.uri}}):(t.add({...j,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:p,action:v,payload:{URI:h.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:h,container:{id:p,endTime:d},branches:g=[],isEOV:m=!1,autoSelected:S=!1})=>{const E=ie(h,m),x={timestamp:!E.args.shouldOpenNow||m?1/0:d,priority:"container",initiator:p,actionType:E.type},v=i.emit.bind(i,y.interactives,{subjectId:p,subjectName:"container",type:T.actionChoice,actionType:E.type,payload:E.args});switch(E.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const j=g.find(O=>O.id===E.args.branchId);if(!j)return;v(),t.add({...x,action:L.bind(null,{subjectId:p,subjectName:"container",action:E,payload:{chapterId:j.chapterId,autoSelect:S}})}),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(),t.add({...x,action:C.bind(null,{subjectId:p,subjectName:"container",action:E})});return}case w.openURI.trim().toLowerCase():{v(),t.add({...x,action:V.bind(null,{subjectId:p,subjectName:"container",action:E,payload:{URI:h.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:h,branches:p,isEOV:d=!1}){const g=je(h.events);if(g){const m=ie(g.action,d);i.emit(y.interactives,{subjectId:h.id,subjectName:"container",type:T.actionChoice,actionType:m.type,payload:m.args}),t.add({timestamp:d?1/0:h.endTime,priority:"container",initiator:h.id,actionType:w.expect,action:u.bind(null,{subjectId:h.id,subjectName:"container"})}),r.isExpect=!0}else for(const m of h.events)a({action:m.action,container:h,branches:p,isEOV:d})}const l=({chapterId:h,action:p,branches:d=[]})=>{const g=i.emit.bind(i,y.interactives,{subjectId:h,subjectName:"chapter",type:T.actionChoice,actionType:p.type,payload:p.args});switch(p.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const m=d.find(S=>S.id===p.args.branchId);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const m=wi(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const m=Ii(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const m=Ei(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const m=Ci(d);return m?.chapterId?(g(),L.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{chapterId:m.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return g(),C.bind(null,{subjectId:h,subjectName:"chapter",action:p});case w.openURI.trim().toLowerCase():return g(),V.bind(null,{subjectId:h,subjectName:"chapter",action:p,payload:{URI:p.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function f(h){const p=je(h.events);if(p){if(tt(h))return;i.emit(y.interactives,{subjectId:h.id,subjectName:"chapter",type:T.actionChoice,actionType:p.action.type,payload:p.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:w.expect,action:u.bind(null,{subjectId:h.id,subjectName:"chapter"})})}else h.events.forEach(d=>{const g=l({chapterId:h.id,action:d.action,branches:h.branches});g&&t.add({timestamp:1/0,priority:"chapter",initiator:h.id,actionType:d.action.type,action:g})})}const u=({subjectId:h,subjectName:p,action:d})=>{e.pause(),i.emit(y.interactives,{subjectId:h,subjectName:p,type:T.actionExecution,actionType:d?.type??w.expect})},b=({subjectId:h,subjectName:p})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(y.interactives,{subjectId:h,subjectName:p,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:h,subjectName:p,subjectType:d,action:g})=>{i.emit(y.interactives,{subjectId:h,subjectName:p,subjectType:d,type:T.actionExecution,actionType:g.type})},L=({subjectId:h,subjectName:p,subjectType:d,action:g,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:h,subjectName:p,subjectType:d,type:T.actionExecution,actionType:g.type,payload:m})},V=({subjectId:h,subjectName:p,subjectType:d,action:g,payload:m})=>{if(!m.URI)return;const S=window.open(m.URI,"_blank","noopener,noreferrer");S&&(S.opener=null),i.emit(y.interactives,{subjectId:h,subjectName:p,subjectType:d,type:T.actionExecution,actionType:g.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:l,onExpectEvent:u,expectEventHandler:b,setManifestChapterEvents:f,setManifestContainerEvents:c,stopExpect:s,state:r}};class G{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=G.#a(e,r),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),r=Object.keys(t).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),G.#c(e)?t:t.capture||!1}}static#s=void 0;static#c(e){let t=G.#s;if(t===void 0){t=!1;try{const n={},r={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};e.addEventListener("test",s,n),e.removeEventListener("test",s,n)}catch{t=!1}G.#s=t}return t||!1}}class Si{constructor(){this.bindingMap=new vi}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;const s=new G(e,t,n,r);this.bindingMap.push(t,s)}listenOnce(e,t,n,r){const s=o=>{this.unlisten(e,t,s),n(o)};this.listen(e,t,s,r)}unlisten(e,t,n){if(!this.bindingMap)return;const r=this.bindingMap.get(t)||[];for(const s of r)s.target===e&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(t,s))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class Ti{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 e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let r=3;r<n;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class xi{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
7
7
|
position: absolute;
|
|
8
8
|
top: 0;
|
|
9
9
|
left: 0;
|
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-interactive v1.0.7-
|
|
3
|
-
* Thu, 15 Feb 2024
|
|
2
|
+
* @vkontakte/videoplayer-interactive v1.0.7-dev.6643328a.0
|
|
3
|
+
* Thu, 15 Feb 2024 18:13:27 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-7/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{loadVKLangPack as Ye,ValueSubject as F,Subscription as re,Observable as fe,getCurrentBrowser as Je,CurrentClientBrowser as et,once as tt}from"@vkontakte/videoplayer-shared/evergreen.esm.js";import{v4 as it}from"uuid";import{Player as nt}from"@vkontakte/videoplayer-core/evergreen.esm.js";const st="1.0.7-beta.0";function Me(i,e=1){let t="0",n="0",r="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+r},${e})`}const M="SDK_NAME",rt="SDK_NAME-controls-container",Oe=()=>document.querySelector(`.${rt}`),at=.4,O={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},me={top:"flex-start",bottom:"flex-end",center:"center"},ye={start:"flex-start",end:"flex-end",center:"center"},ge={start:"left",end:"right",center:"center"},Ve=({target:i,props:e})=>{i.style.alignItems=me[e?.text?.gravityVertical]??me.center,i.style.justifyContent=ye[e?.text?.gravityHorizontal]??ye.center,i.style.textAlign=ge[e?.text?.alignment]??ge.start},_e=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},$e=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Me(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},ke=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Me(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},ae=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class oe{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${M}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??O.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",s=>{s.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${M}-control-container-${this.control.id}`)}}const Pe=i=>{if(i.type.trim().toLowerCase()==="area")return new ot(i)};class ot extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");return s.classList.add(`${M}-${this.control.id}`),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",$e({target:s,props:this.control.props,fallback:{...O,backgroundColor:"transparent"}}),ke({target:s,props:this.control.props,fallback:{...O,borderAlpha:0},dependsOn:n}),ae({target:s,layoutParams:this.control.layoutParams,fallback:O}),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}const Fe=i=>{if(i.type.trim().toLowerCase()==="button")return new ct(i)};class ct extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");s.type="button",s.classList.add(`${M}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:O}),$e({target:s,props:this.control.props,fallback:O}),ke({target:s,props:this.control.props,fallback:O,dependsOn:n}),Ve({target:s,props:this.control.props}),_e({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}const lt=i=>{if(i.type.trim().toLowerCase()==="text")return new ht(i)};class ht extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("div");s.classList.add(`${M}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:O}),Ve({target:s,props:this.control.props}),_e({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}class dt{constructor(e){this.layout=e}}const ut=i=>{if(i.type.trim().toLowerCase()==="relative")return new Be(i)};class Be extends dt{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class De{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...e,r(t)]:[...e]},[])}}const We=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new pt(i,e)};class pt extends De{constructor(e,t){super(e),this.rootElement=t??Oe(),this.layout=new Be(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Fe),this.addControlFactory("text",lt),this.addControlFactory("area",Pe)}createView(e){const t=document.createElement("div");return t.classList.add(`${M}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const r=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(r,e)}),this.rootElement.append(t),this.isRemoved=!1,t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}enable(){const e=this.getElement();e&&(e.style.opacity=1,this.isDisabled=!1)}disable(){const e=this.getElement();e&&(e.style.opacity=at,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${M}-${this.container.id}`)}}function Ge(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const H={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ce=i=>z(i,H.Object),ne=i=>z(i,H.String),le=i=>z(i,H.Array),ze=i=>z(i,H.Number),ft=i=>z(i,H.Function),ve=i=>ze(i)&&!isNaN(i),U=i=>ce(i)&&Object.keys(i).length===0,he=i=>le(i)&&!i.length,q=(i,e)=>ne(i)&&(e?i.trim():i).length,Ue=window.navigator.userAgent.toLowerCase(),mt=/mobi/i.test(Ue);Ue.indexOf("android")>-1;const yt="video_interactive",gt="videoint",vt=250;class bt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=t,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=Ct(e),this.resizeObserver=new ResizeObserver(Ge(this.onResize,vt)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!ze(e.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 Ye(this.lang,yt,gt)}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(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}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 Ct(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const Y=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Et="3.1",be={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},wt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},It=i=>{const e=[];for(const t of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const h=!!c.endTime;let v=[wt];switch(a){case"await":h?v=[]:s=[];break;case"default":{const f={type:"onSuspense",action:{type:be.default,args:{branchId:n,shouldOpenNow:!h,isDetachContainer:!0}}};h?v=[f]:s=[f];break}case"random":case"weightlessRandom":case"max":case"min":{const f={type:"onSuspense",action:{type:be[a],args:{}}};h?v=[f]:s=[f];break}}for(const f of c.controls)o.push({...c,controls:[{...f}],id:it(),events:v})}e.push({...t,containers:o,events:s,branches:r})}return i.metadata.version=Et,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},St="3.2",Tt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:St},media:e}}return i},xt="3.3",Rt=(i=[])=>({edit:{chapters:i},view:{}}),Ce={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},At=i=>{const e=[],t=[];for(const n of i.chapters){const{id:r,x:s,y:o,...a}=n,c=a.containers.map(h=>({...h,controls:h.controls.map(({subtype:v,type:f,...E})=>({...E,type:v??f})),events:h.events?.length?h.events:[Ce]}));e.push({id:r,...a,containers:c,events:a.events?.length?a.events:[Ce]}),t.push({id:r,x:s,y:o})}return{...i,chapters:e,graph:Rt(t),metadata:{...i.metadata,version:xt}}},jt=[{version:"3.0",migrate:It},{version:"3.1",migrate:Tt},{version:"3.2",migrate:At}],Lt=i=>jt.reduce((e,t)=>Y(e.metadata.version,t.version)?e:t.migrate(e),i),Nt=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 B;(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"})(B||(B={}));const Ee={metadata:"Object",chapters:"Array"},Mt="3.0.0",Ot="3.3.0",He=i=>{const e=Y(i,Mt);return e===-1?!1:e===0?!0:Y(i,Ot)!==1},Vt=i=>{if(!ce(i))return!1;for(const e in Ee)if(!i[e]||!z(i[e],Ee[e]))return!1;return He(i.metadata.version)},Qe=i=>i.type===Nt.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,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 qe{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===t){n.splice(r,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class _t{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{ft(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class $t{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return kt(...this.loaders[e])(t)}}function kt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function J(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function se({actions:i,errors:e,chapterId:t,...n}){if(t){const r=i.getManifest(),s=i.getChapter(r.chapters,t);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:e,result:{chapter:s,media:o,graph:a}}:{...n,errors:J(e,se.name,"Could not find media"),actions:i}}}return{...n,errors:J(e,se.name,"Could not find chapter"),actions:i}}const Pt=async i=>{try{let e,t;if(ce(i))e=i;else if(ne(i)){t=new URL(i).href;const r=await fetch(t);if(!r.ok)return{};e=await r.json()}else return{};if(!Vt(e))return{};const n=e.metadata.media;if(ne(n)&&!e.media)try{let r;t?r=new URL(n,t).href:(r=new URL(n).href,t=r);const s=await fetch(r);if(!s.ok)throw new Error;e.metadata.media=await s.json()}catch{return Wt(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Ft(i){const{manifest:e,manifestURL:t}=await Pt(i),n=Lt(e);return n.media=Bt(n.media,t),delete n.metadata.media,n}function te(i,e){return i.find(t=>t.id===e)}function we(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Ie(i,e){return i.videos.find(t=>t.id===e)}function Bt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const r=Dt(n.url,e);return{...n,url:r||n.url}})}))}}function Dt(i,e){try{return new URL(i,e).href}catch{return""}}function Wt(i){return Y(i,"3.2.0")>=0}class Gt extends $t{constructor(e,t){super(e),this.onError=t,this.prevChapter$=new F(null),this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:J},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await Ft(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const t=await this.exec("chapterLoaders",se({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:we,getChapter:te,getMedia:Ie,getByBranches:this.getByBranches.bind(this),addErrorMessage:J},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=te(this.manifest.chapters,e);if(t){const n=Ie(this.manifest.media,t.videoId),r=we(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:r}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=te(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const r=this.getByChapterId(n.chapterId);return r&&t.push(r),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const m={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Se={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function zt(){const i=new Map;function e({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 t(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)t(r[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function Te(i,e=[]){let t={},n;const r=!e.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||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:s.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:t,thumbUrl:n,title:i.title??""}}const X=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},Ut=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},K={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},Ht=2;function Qt(i){const e=zt();let t,n;const r=new qe;let s={},o=!1,a=null,c=!1,h;i&&v(i);function v(d){a=d}function f(d,y,p){if(!a)throw Error("need to set interactive controller");const b=(e.map.get(d)??{})[y];if(b){s={chapterId:p,listId:d,itemId:y,...b};const x=s.player;n=x.info.currentQuality$.subscribe(g=>{if(!(!g||!x.info.position$.getValue())){t=g;for(const L of e.map)Object.values(L[1]).forEach(({player:N})=>{x.info.isAutoQualityEnabled$.getValue()||X(N,g)})}}),b.container.remove(),o=!1,a.setPlayer(b.player),c||(a.init(),c=!0),r.emit(K.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function E(d,y,p){if(!a)throw Error("need to set interactive controller");if(U(s)||d!==s.itemId)return;if(p>=0&&!o){const b=a.getChapterBranches();o=!0;const x=new Set;for(const g of b)x.has(g.media.id)||(await j({media:g.media,chapterId:g.chapter.id,setAsActive:!1,title:g.chapter.label}),x.add(g.media.id))}}async function C({chapter:{id:d},media:y}){if(U(s))return;n?.unsubscribe();const p=s.player.info.muted$.getValue(),S=s.player.info.currentQuality$.getValue(),b=s.player.info.isAutoQualityEnabled$.getValue(),x=s.player.info.volume$.getValue(),g=s.player.info.currentPlaybackRate$.getValue(),L=!b;let N=!1;for(const R of e.map)if(R[0]===y.id){const k=Object.keys(R[1]);for(const V of k)V===s.itemId?(k.length<Ht||(N=!0),e.removePlayer(R[0],V)):(N=!0,f(R[0],V,d),L?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(p),s.player.setPlaybackRate(g))}else e.removePlayer(R[0]);N||(await j({media:y,chapterId:d,setAsActive:!0,playbackRate:g}),L?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(p))}async function j({media:d,chapterId:y,prefetch:p=!0,setAsActive:S=!0,autoplay:b=!1,preferredExt:x,title:g,playbackRate:L}){const N=Math.random().toString(),R=document.createElement("div");h.append(R);const k=s?.player?.info.isAutoQualityEnabled$.getValue();let V;if(a?.options?.vkVideoLoader){const Q=Ut(d);Q.length&&(V=await a.options.vkVideoLoader(...Q))}const ue={container:R,...V?.videos?.[0]||{sources:Te(d,x).sources},title:g},P=new nt;P.initVideo(ue);const Ke=R.lastChild,pe=new re;pe.add(P.info.position$.subscribe(function(Q){E(N,P.info.duration$.getValue(),Q)})).add(P.events.canplay$.subscribe(function(){k||X(P,t),L&&P.setPlaybackRate(L)})),Ke&&(R.style.display="none",R.classList.add(y));const D=e.createPlayer({listId:d.id,itemId:N,player:P,container:R,sources:Te(d,x).sources,config:ue,subscription:pe});return S&&f(d.id,D.itemId,y),b&&D.player.play(),p&&!b&&D.player.prepare(),r.emit(K.playerCreated,D.player),{player:D.player,config:D.config}}function $(){l(),a=null}function l(){a?.off(m.chapterChanged,C),e.removeAll(),s={},c=!1,o=!1}async function u({source:d,initialChapter:y,container:p}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),l(),h=p;const{media:S,chapter:b}=await a.setChapter({chapterId:y});if(S){a.on(m.chapterChanged,C);const{player:x,config:g}=await j({media:S,chapterId:b.id,title:b.label});return r.emit(K.initiated,{container:p,media:S,chapterId:b.id}),{player:x,config:g}}else console.error("not found")}return{...e,on:r.on.bind(r),off:r.off.bind(r),init:u,setInteractiveController:v,createPlayer:j,removeAll:$,getActivePlayer:function(){return s}}}const qt=3e3,Xt=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=qt)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const h=e.info.position$.getValue()*1e3;for(const v of i){const f=v.startTime-o;if(f<=h&&(h<=v.endTime||v.endTime===null)){c=!0;break}h<f&&(a=a===-1?f:Math.min(a,f))}return!c&&a!==-1?a:null}}},W=Xt(),I=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),de=i=>le(i)&&!he(i),Xe=i=>he(i.branches)||i.order==="end",Zt=i=>le(i.branches)&&!he(i.branches),Kt=(i,e)=>{const t=i*1e3;return de(e.controls)&&t<(e.startTime??0)},xe=(i,e)=>{const t=i*1e3;return de(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ee=i=>i.some(e=>e.action.type==="expect"),Re=i=>i.find(e=>e.action.type==="expect"),Yt=i=>i?.length===1,Ze=i=>Yt(i)&&Qe(i[0]),Jt=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),ei=(i=[])=>i.reduce((e,t,n)=>{const r=(t?.controls??[]).filter(s=>!Qe(s));if(de(r)){const s=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:s});else{const a=[];let c=-1/0,h=1/0,v=[];const f=[];for(let E=0;E<e.length;E++){const C=e[E];if(f.push(...C.subjects),C.range[0]<h&&(h=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=s[0]&&C.range[1]>=s[1])return e[E].subjects.push(o),e;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(E),v=v.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(E),v=v.concat(C.subjects),s[1]=C.range[1])}if(f.push(o),s[0]<=h&&s[1]>=c)return[{subjects:f,range:s}];a.length&&a.reverse().forEach(E=>{e.splice(E,1)}),e.push({subjects:v.concat([o]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),ti=(i,e)=>ee(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ee(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class ii{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c}){this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new re,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&Ze(t.container.controls),this.globalEventEmitter=o,this.gameState=I.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))}hide=()=>{setTimeout(()=>{this.gameState!==I.end&&(ee(this.container.container.events)&&this.gameState===I.afterInteractive||this.selectBranches.state.isExpect||(this.gameState===I.interactive?this.container.disable?.():this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===I.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.container.enable?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const t=Jt({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(m.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(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===I.end||this.gameState===I.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),W.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===I.end});this.container.createView(t),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ee(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=I.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[I.destroyed,I.removed].includes(this.gameState)&&!this.isPermanentText)return;const t=this.player.getExactTime();if(Kt(t,this.container.container))this.gameState!==I.beforeInteractive&&(this.gameState=I.beforeInteractive,this.onBeforeStartTime());else if(xe(t,this.container.container))this.gameState!==I.interactive&&(this.gameState=I.interactive,this.onStartTime());else if(this.gameState!==I.afterInteractive){const s=this.gameState;this.gameState=I.afterInteractive,s===I.interactive&&this.onEndTime()}else this.gameState!==I.destroyed&&this.removeView();const n=xe(t,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(m.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=I.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=I.removed}destroy(){this.reset(),this.removeView(),this.gameState=I.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),W.deleteContainer(this.container.container.id)}}function ni(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const h in i)+h<=a&&(c[h]=i[h]);return c}function n(a){const c={};for(const h in i)+h>=a&&(c[h]=i[h]);return c}function r({timestamp:a,priority:c,initiator:h}){if(ve(a)){const v=i[a]??null;if(v&&q(c,!0)){let f={};const E=v[c];return E&&(f={...f,...E}),f=U(f)?null:f,f&&q(h,!0)?f[h]??null:f}return v}return null}function s({timestamp:a,priority:c,initiator:h}){if(ve(a))if(i[a]){if(q(c,!0))if(i[a][c]){if(q(h,!0))if(i[a][c][h]){if(delete i[a][c][h],!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:h,...v}){i[a]?.[c]?.[h]?i[a][c][h].push({...v}):i[a]?.[c]?i[a][c]={...i[a][c],[h]:[{...v}]}:i[a]?i[a]={...i[a],[c]:{[h]:[{...v}]}}:i[a]={[c]:{[h]:[{...v}]}}}return{map:i,remove:s,add:o,removeAll:e,get:r,getLte:t,getGte:n}}const si=[w.expect,w.setNextBranch],ri=1/0;function Ae(i){let e=i,t;const n=ai(),r=new ni;let s;const o=()=>{f(),$()},a=l=>{r.add.call(void 0,l),E()},c=(l=[])=>{for(const u of l)if(u.action(),si.includes(u.actionType))break},h=l=>{if(!n.isReady(l))return;const u=Z(r.get({timestamp:l,priority:"control"})??{}),d=Z(r.get({timestamp:l,priority:"container"})??{}),y=Z(r.get({timestamp:l,priority:"chapter"})??{});c([...u,...d,...y])},v=()=>{c([...Z(r.get({timestamp:1/0,priority:"chapter"})??{})])},f=()=>{t&&(s?.unsubscribe(),t=void 0)},E=()=>{t||(t=()=>setTimeout(()=>{h(1/0)}),s=e.events.ended$.subscribe(t))},C=l=>{f(),e=l},j=l=>{l.priority==="container"&&n.resetCalled(l.timestamp),r.remove(l)},$=()=>{n.release(),r.removeAll()};return{setPlayer:C,add:a,remove:j,exec:h,execEndOfVideo:v,listen:E,unlisten:f,release:o,containersEventsCallState:n}}function ai(){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??ri,h=i.get(c)??{};i.set(c,{...h,[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(e=>e.actionType===w.expect?-1:1)}const oi=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=e.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=r/s;let c,h;return a>o?(h=s,c=s*o):a<o?(h=r/o,c=r):(h=s,c=r),{videoContentWidth:h,videoContentHeight:c}},ci=250;function li(i){let e=()=>{};const t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){const{parentElement:c,player:h}=i();if(c&&h){const{videoContentWidth:v,videoContentHeight:f}=oi(c,h);c.style.setProperty("--interactive-content-width",`${v}px`),c.style.setProperty("--interactive-content-height",`${f}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=Ge(a=>{const{fns:c=[]}=i();n(a);for(const h of c)h()},ci);function o(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e()},release:o}}class hi{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const di=i=>Math.floor(Math.random()*i),ui=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},pi=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},fi=i=>{const e=i.length,t=di(e);return i[t]},je=1,mi=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??je;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??je,e>=t)return i[n];return i[i.length-1]},Le=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),ie=(i,e=!1)=>({...i,args:e?{...i.args,...Le}:{...Le,...i.args}}),Ne=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:l,controlType:u,controlId:d,containerId:y,branches:p=[],onEvent:S,isEOV:b=()=>!1,isDisabled:x=()=>!1})=>{const g=ie(l,b()),L={timestamp:1/0,priority:"control",initiator:d,actionType:g.type},N=x(),R=i.emit.bind(i,m.interactives,{subjectId:d,subjectType:u,subjectName:"control",type:N?T.actionChoiceCanceled:T.actionChoice,actionType:l.type,payload:{containerId:y,...g.args}});if(N){R();return}switch(g.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const k=p.find(V=>V.id===g.args.branchId);if(!k)return;S(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),R(),g.args.shouldOpenNow?j({subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{chapterId:k.chapterId,autoSelect:!1}}):(t.add({...L,action:j.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{S(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),R(),g.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:u,action:l}):t.add({...L,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:l})});return}case w.openURI.trim().toLowerCase():{S(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),R(),g.args.shouldOpenNow?$({subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{URI:l.args.uri}}):(t.add({...L,action:$.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{URI:l.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(m.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:l,container:{id:u,endTime:d},branches:y=[],isEOV:p=!1,autoSelected:S=!1})=>{const b=ie(l,p),x={timestamp:!b.args.shouldOpenNow||p?1/0:d,priority:"container",initiator:u,actionType:b.type},g=i.emit.bind(i,m.interactives,{subjectId:u,subjectName:"container",type:T.actionChoice,actionType:b.type,payload:b.args});switch(b.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const L=y.find(N=>N.id===b.args.branchId);if(!L)return;g(),t.add({...x,action:j.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{chapterId:L.chapterId,autoSelect:S}})}),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():{g(),t.add({...x,action:C.bind(null,{subjectId:u,subjectName:"container",action:b})});return}case w.openURI.trim().toLowerCase():{g(),t.add({...x,action:$.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{URI:l.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(m.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:l,branches:u,isEOV:d=!1}){const y=Re(l.events);if(y){const p=ie(y.action,d);i.emit(m.interactives,{subjectId:l.id,subjectName:"container",type:T.actionChoice,actionType:p.type,payload:p.args}),t.add({timestamp:d?1/0:l.endTime,priority:"container",initiator:l.id,actionType:w.expect,action:f.bind(null,{subjectId:l.id,subjectName:"container"})}),r.isExpect=!0}else for(const p of l.events)a({action:p.action,container:l,branches:u,isEOV:d})}const h=({chapterId:l,action:u,branches:d=[]})=>{const y=i.emit.bind(i,m.interactives,{subjectId:l,subjectName:"chapter",type:T.actionChoice,actionType:u.type,payload:u.args});switch(u.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const p=d.find(S=>S.id===u.args.branchId);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const p=fi(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const p=mi(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const p=pi(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const p=ui(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return y(),C.bind(null,{subjectId:l,subjectName:"chapter",action:u});case w.openURI.trim().toLowerCase():return y(),$.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{URI:u.args.uri}});default:console.error("Unexpected chapter event"),i.emit(m.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function v(l){const u=Re(l.events);if(u){if(Xe(l))return;i.emit(m.interactives,{subjectId:l.id,subjectName:"chapter",type:T.actionChoice,actionType:u.action.type,payload:u.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:w.expect,action:f.bind(null,{subjectId:l.id,subjectName:"chapter"})})}else l.events.forEach(d=>{const y=h({chapterId:l.id,action:d.action,branches:l.branches});y&&t.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:d.action.type,action:y})})}const f=({subjectId:l,subjectName:u,action:d})=>{e.pause(),i.emit(m.interactives,{subjectId:l,subjectName:u,type:T.actionExecution,actionType:d?.type??w.expect})},E=({subjectId:l,subjectName:u})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(m.interactives,{subjectId:l,subjectName:u,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:l,subjectName:u,subjectType:d,action:y})=>{i.emit(m.interactives,{subjectId:l,subjectName:u,subjectType:d,type:T.actionExecution,actionType:y.type})},j=({subjectId:l,subjectName:u,subjectType:d,action:y,payload:p})=>{p.behaviour="change-chapter",i.emit(m.interactives,{subjectId:l,subjectName:u,subjectType:d,type:T.actionExecution,actionType:y.type,payload:p})},$=({subjectId:l,subjectName:u,subjectType:d,action:y,payload:p})=>{if(!p.URI)return;const S=window.open(p.URI,"_blank","noopener,noreferrer");S&&(S.opener=null),i.emit(m.interactives,{subjectId:l,subjectName:u,subjectType:d,type:T.actionExecution,actionType:y.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:h,onExpectEvent:f,expectEventHandler:E,setManifestChapterEvents:v,setManifestContainerEvents:c,stopExpect:s,state:r}};class G{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=G.#a(e,r),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),r=Object.keys(t).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),G.#c(e)?t:t.capture||!1}}static#s=void 0;static#c(e){let t=G.#s;if(t===void 0){t=!1;try{const n={},r={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};e.addEventListener("test",s,n),e.removeEventListener("test",s,n)}catch{t=!1}G.#s=t}return t||!1}}class yi{constructor(){this.bindingMap=new hi}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;const s=new G(e,t,n,r);this.bindingMap.push(t,s)}listenOnce(e,t,n,r){const s=o=>{this.unlisten(e,t,s),n(o)};this.listen(e,t,s,r)}unlisten(e,t,n){if(!this.bindingMap)return;const r=this.bindingMap.get(t)||[];for(const s of r)s.target===e&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(t,s))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class gi{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 e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let r=3;r<n;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class vi{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
6
|
+
import{loadVKLangPack as Ye,ValueSubject as F,Subscription as re,Observable as fe,getCurrentBrowser as Je,CurrentClientBrowser as et,once as tt}from"@vkontakte/videoplayer-shared/evergreen.esm.js";import{v4 as it}from"uuid";import{Player as nt}from"@vkontakte/videoplayer-core/evergreen.esm.js";const st="1.0.7-dev.6643328a.0";function Me(i,e=1){let t="0",n="0",r="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+r},${e})`}const M="SDK_NAME",rt="SDK_NAME-controls-container",Oe=()=>document.querySelector(`.${rt}`),at=.4,O={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},me={top:"flex-start",bottom:"flex-end",center:"center"},ye={start:"flex-start",end:"flex-end",center:"center"},ge={start:"left",end:"right",center:"center"},Ve=({target:i,props:e})=>{i.style.alignItems=me[e?.text?.gravityVertical]??me.center,i.style.justifyContent=ye[e?.text?.gravityHorizontal]??ye.center,i.style.textAlign=ge[e?.text?.alignment]??ge.start},_e=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},$e=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Me(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},ke=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Me(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},ae=({target:i,layoutParams:e,fallback:t})=>{i.style.transform=`rotate(${-e.angle}rad)`};class oe{constructor(e){this.control=e}createView(e){const t=document.createElement("div");t.classList.add(`${M}-control-container-${this.control.id}`),e(t,this.control.layoutParams);const n=(this.control.layoutParams.innerSizesDependOn??O.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};return{controlContainerEl:t,dependsOn:n}}setEvents(e,t){e&&this.control.events.forEach(n=>{switch(n.type.trim().toLowerCase()){case"onclick":e.addEventListener("click",s=>{s.stopPropagation(),t&&t({action:n.action,controlId:this.control.id,controlType:this.control.type})});break}})}getElement(){return document.querySelector(`.${M}-control-container-${this.control.id}`)}}const Pe=i=>{if(i.type.trim().toLowerCase()==="area")return new ot(i)};class ot extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");return s.classList.add(`${M}-${this.control.id}`),s.style.display="flex",s.style.width="100%",s.style.height="100%",s.style.cursor="pointer",s.type="button",$e({target:s,props:this.control.props,fallback:{...O,backgroundColor:"transparent"}}),ke({target:s,props:this.control.props,fallback:{...O,borderAlpha:0},dependsOn:n}),ae({target:s,layoutParams:this.control.layoutParams,fallback:O}),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}const Fe=i=>{if(i.type.trim().toLowerCase()==="button")return new ct(i)};class ct extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("button");s.type="button",s.classList.add(`${M}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:O}),$e({target:s,props:this.control.props,fallback:O}),ke({target:s,props:this.control.props,fallback:O,dependsOn:n}),Ve({target:s,props:this.control.props}),_e({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}const lt=i=>{if(i.type.trim().toLowerCase()==="text")return new ht(i)};class ht extends oe{constructor(e){super(e)}createView({parent:e,layoutFn:t}){const{dependsOn:n,controlContainerEl:r}=super.createView(t),s=document.createElement("div");s.classList.add(`${M}-${this.control.id}`),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",ae({target:s,layoutParams:this.control.layoutParams,fallback:O}),Ve({target:s,props:this.control.props}),_e({target:o,props:this.control.props,fallback:O,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}class dt{constructor(e){this.layout=e}}const ut=i=>{if(i.type.trim().toLowerCase()==="relative")return new Be(i)};class Be extends dt{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}}class De{constructor(e){this.container=e,this.factories=new Map,this.#a()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.#a()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.#a()}#a(){this.controls=this.#s()}#s(){return this.container.controls?.reduce((e,t)=>{const n=t.type.trim().toLowerCase(),r=this.factories.get(n);return r?[...e,r(t)]:[...e]},[])}}const We=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new pt(i,e)};class pt extends De{constructor(e,t){super(e),this.rootElement=t??Oe(),this.layout=new Be(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Fe),this.addControlFactory("text",lt),this.addControlFactory("area",Pe)}createView(e){const t=document.createElement("div");return t.classList.add(`${M}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{const r=n.createView({parent:t,layoutFn:this.layout.setControlLayout});n.setEvents(r,e)}),this.rootElement.append(t),this.isRemoved=!1,t}hide(){const e=this.getElement();e&&(e.style.visibility="hidden")}show(){const e=this.getElement();e&&(e.style.visibility="visible")}enable(){const e=this.getElement();e&&(e.style.opacity=1,this.isDisabled=!1)}disable(){const e=this.getElement();e&&(e.style.opacity=at,this.isDisabled=!0)}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${M}-${this.container.id}`)}}function Ge(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const H={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ce=i=>z(i,H.Object),ne=i=>z(i,H.String),le=i=>z(i,H.Array),ze=i=>z(i,H.Number),ft=i=>z(i,H.Function),ve=i=>ze(i)&&!isNaN(i),U=i=>ce(i)&&Object.keys(i).length===0,he=i=>le(i)&&!i.length,q=(i,e)=>ne(i)&&(e?i.trim():i).length,Ue=window.navigator.userAgent.toLowerCase(),mt=/mobi/i.test(Ue);Ue.indexOf("android")>-1;const yt="video_interactive",gt="videoint",vt=250;class bt{constructor(e){this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:r,visitedChapters:s=[]}){this.isHidden=!0,this.currentManifestId=void 0,this.currentChapterId=void 0,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=t,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=Ct(e),this.resizeObserver=new ResizeObserver(Ge(this.onResize,vt)),this.resizeObserver.observe(this.graphWrapperElement)}onResize=e=>{this.isReady&&(!e[0].contentRect.width||!e[0].contentRect.height||(this.lastZoomInfo&&this.ngEditor.zoomTo(this.getNextPoint()),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}))};getNextPoint(e=this.ngEditorSize){return[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}handleChapterChange=e=>{if(this.isReady){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor.selectChapter(e.id),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=void 0}};handleManifestChange=async(e,t=[])=>{if(!ze(e.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 Ye(this.lang,yt,gt)}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(t),e.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=e.metadata.id):this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.isReady=!0};setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor.updateVideosInfo(e)}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 Ct(i){const e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}const Y=(i="",e="")=>{i=i.split("."),e=e.split(".");let t=0;for(let n=0;n<Math.max(i.length,e.length)&&!t;n++)i[n]>e[n]?t=1:i[n]<e[n]?t=-1:t=0;return t},Et="3.1",be={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},wt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},It=i=>{const e=[];for(const t of i.chapters){let n;const r=[];for(const{isDefault:a,...c}of t.branches)a&&(n=c.id),r.push(c);let s=[];const o=[];for(const{fallbackStrategy:a,...c}of t.containers){const h=!!c.endTime;let v=[wt];switch(a){case"await":h?v=[]:s=[];break;case"default":{const f={type:"onSuspense",action:{type:be.default,args:{branchId:n,shouldOpenNow:!h,isDetachContainer:!0}}};h?v=[f]:s=[f];break}case"random":case"weightlessRandom":case"max":case"min":{const f={type:"onSuspense",action:{type:be[a],args:{}}};h?v=[f]:s=[f];break}}for(const f of c.controls)o.push({...c,controls:[{...f}],id:it(),events:v})}e.push({...t,containers:o,events:s,branches:r})}return i.metadata.version=Et,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},St="3.2",Tt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:St},media:e}}return i},xt="3.3",Rt=(i=[])=>({edit:{chapters:i},view:{}}),Ce={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},At=i=>{const e=[],t=[];for(const n of i.chapters){const{id:r,x:s,y:o,...a}=n,c=a.containers.map(h=>({...h,controls:h.controls.map(({subtype:v,type:f,...E})=>({...E,type:v??f})),events:h.events?.length?h.events:[Ce]}));e.push({id:r,...a,containers:c,events:a.events?.length?a.events:[Ce]}),t.push({id:r,x:s,y:o})}return{...i,chapters:e,graph:Rt(t),metadata:{...i.metadata,version:xt}}},jt=[{version:"3.0",migrate:It},{version:"3.1",migrate:Tt},{version:"3.2",migrate:At}],Lt=i=>jt.reduce((e,t)=>Y(e.metadata.version,t.version)?e:t.migrate(e),i),Nt=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 B;(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"})(B||(B={}));const Ee={metadata:"Object",chapters:"Array"},Mt="3.0.0",Ot="3.3.0",He=i=>{const e=Y(i,Mt);return e===-1?!1:e===0?!0:Y(i,Ot)!==1},Vt=i=>{if(!ce(i))return!1;for(const e in Ee)if(!i[e]||!z(i[e],Ee[e]))return!1;return He(i.metadata.version)},Qe=i=>i.type===Nt.Text;class A{constructor(e,t,...n){this.severity=e,this.category=t,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 qe{listeners={};addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];const n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){const n=this.listeners[e];if(!n)return this;for(let r=n.length;r>0;r--)if(n[r]===t){n.splice(r,1);break}return this}emit(e,...t){const n=this.listeners[e];return n?(n.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return(this.listeners[e]||[]).length}rawListeners(e){return this.listeners[e]}}class _t{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{ft(e)&&(this.fns.push(e),t&&this.updateFn())};removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};requestAnimation=()=>{this.raf||this.forceRequestAnimation()};cancelAnimation=()=>{cancelAnimationFrame(this.raf),this.raf=void 0};release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}}class $t{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return kt(...this.loaders[e])(t)}}function kt(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function J(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function se({actions:i,errors:e,chapterId:t,...n}){if(t){const r=i.getManifest(),s=i.getChapter(r.chapters,t);if(s){const o=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return o?{...n,actions:i,errors:e,result:{chapter:s,media:o,graph:a}}:{...n,errors:J(e,se.name,"Could not find media"),actions:i}}}return{...n,errors:J(e,se.name,"Could not find chapter"),actions:i}}const Pt=async i=>{try{let e,t;if(ce(i))e=i;else if(ne(i)){t=new URL(i).href;const r=await fetch(t);if(!r.ok)return{};e=await r.json()}else return{};if(!Vt(e))return{};const n=e.metadata.media;if(ne(n)&&!e.media)try{let r;t?r=new URL(n,t).href:(r=new URL(n).href,t=r);const s=await fetch(r);if(!s.ok)throw new Error;e.metadata.media=await s.json()}catch{return Wt(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Ft(i){const{manifest:e,manifestURL:t}=await Pt(i),n=Lt(e);return n.media=Bt(n.media,t),delete n.metadata.media,n}function te(i,e){return i.find(t=>t.id===e)}function we(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function Ie(i,e){return i.videos.find(t=>t.id===e)}function Bt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const r=Dt(n.url,e);return{...n,url:r||n.url}})}))}}function Dt(i,e){try{return new URL(i,e).href}catch{return""}}function Wt(i){return Y(i,"3.2.0")>=0}class Gt extends $t{constructor(e,t){super(e),this.onError=t,this.prevChapter$=new F(null),this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:J},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await Ft(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){this.prevChapter$.next(this.chapter);const t=await this.exec("chapterLoaders",se({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:we,getChapter:te,getMedia:Ie,getByBranches:this.getByBranches.bind(this),addErrorMessage:J},result:null,errors:null,chapterId:e}));return t.errors&&this.errorHandler(t.errors),this.chapter=t.result.chapter,this.media=t.result.media,this.graph=t.result.graph,this}errorHandler(e){this.onError(e),console.error("Something went wrong with loaders",{errors:e})}getInitial(){return this.getByChapterId(this.manifest.metadata.initChapterId)||null}getByChapterId(e=this.manifest.metadata.initChapterId){const t=te(this.manifest.chapters,e);if(t){const n=Ie(this.manifest.media,t.videoId),r=we(this.manifest.graph,t.id);if(n)return{chapter:t,media:n,graph:r}}return null}getBranches(e=this.chapter.id){if(e===this.chapter.id)return this.getByBranches(this.chapter.branches);{const t=te(this.manifest.chapters,e);return this.getByBranches(t?.branches)}}getByBranches(e=[]){return e.reduce((t,n)=>{const r=this.getByChapterId(n.chapterId);return r&&t.push(r),t},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}}const m={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyChanged:"history-changed"},Se={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},T={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function zt(){const i=new Map;function e({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 t(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)t(r[0])}return{createPlayer:e,removePlayer:t,map:i,removeAll:n}}function Te(i,e=[]){let t={},n;const r=!e.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||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:s.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break}return{sources:t,thumbUrl:n,title:i.title??""}}const X=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},Ut=i=>{const e=i.variants.find(t=>t.payload?.type==="vk");if(e&&"payload"in e){const[t,n]=e.payload.id.split("_");return[t,n]}return[]},K={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},Ht=2;function Qt(i){const e=zt();let t,n;const r=new qe;let s={},o=!1,a=null,c=!1,h;i&&v(i);function v(d){a=d}function f(d,y,p){if(!a)throw Error("need to set interactive controller");const b=(e.map.get(d)??{})[y];if(b){s={chapterId:p,listId:d,itemId:y,...b};const x=s.player;n=x.info.currentQuality$.subscribe(g=>{if(!(!g||!x.info.position$.getValue())){t=g;for(const L of e.map)Object.values(L[1]).forEach(({player:N})=>{x.info.isAutoQualityEnabled$.getValue()||X(N,g)})}}),b.container.remove(),o=!1,a.setPlayer(b.player),c||(a.init(),c=!0),r.emit(K.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function E(d,y,p){if(!a)throw Error("need to set interactive controller");if(U(s)||d!==s.itemId)return;if(p>=0&&!o){const b=a.getChapterBranches();o=!0;const x=new Set;for(const g of b)x.has(g.media.id)||(await j({media:g.media,chapterId:g.chapter.id,setAsActive:!1,title:g.chapter.label}),x.add(g.media.id))}}async function C({chapter:{id:d},media:y}){if(U(s))return;n?.unsubscribe();const p=s.player.info.muted$.getValue(),S=s.player.info.currentQuality$.getValue(),b=s.player.info.isAutoQualityEnabled$.getValue(),x=s.player.info.volume$.getValue(),g=s.player.info.currentPlaybackRate$.getValue(),L=!b;let N=!1;for(const R of e.map)if(R[0]===y.id){const k=Object.keys(R[1]);for(const V of k)V===s.itemId?(k.length<Ht||(N=!0),e.removePlayer(R[0],V)):(N=!0,f(R[0],V,d),L?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(p),s.player.setPlaybackRate(g))}else e.removePlayer(R[0]);N||(await j({media:y,chapterId:d,setAsActive:!0,playbackRate:g}),L?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(x),s.player.setMuted(p))}async function j({media:d,chapterId:y,prefetch:p=!0,setAsActive:S=!0,autoplay:b=!1,preferredExt:x,title:g,playbackRate:L}){const N=Math.random().toString(),R=document.createElement("div");h.append(R);const k=s?.player?.info.isAutoQualityEnabled$.getValue();let V;if(a?.options?.vkVideoLoader){const Q=Ut(d);Q.length&&(V=await a.options.vkVideoLoader(...Q))}const ue={container:R,...V?.videos?.[0]||{sources:Te(d,x).sources},title:g},P=new nt;P.initVideo(ue);const Ke=R.lastChild,pe=new re;pe.add(P.info.position$.subscribe(function(Q){E(N,P.info.duration$.getValue(),Q)})).add(P.events.canplay$.subscribe(function(){k||X(P,t),L&&P.setPlaybackRate(L)})),Ke&&(R.style.display="none",R.classList.add(y));const D=e.createPlayer({listId:d.id,itemId:N,player:P,container:R,sources:Te(d,x).sources,config:ue,subscription:pe});return S&&f(d.id,D.itemId,y),b&&D.player.play(),p&&!b&&D.player.prepare(),r.emit(K.playerCreated,D.player),{player:D.player,config:D.config}}function $(){l(),a=null}function l(){a?.off(m.chapterChanged,C),e.removeAll(),s={},c=!1,o=!1}async function u({source:d,initialChapter:y,container:p}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),l(),h=p;const{media:S,chapter:b}=await a.setChapter({chapterId:y});if(S){a.on(m.chapterChanged,C);const{player:x,config:g}=await j({media:S,chapterId:b.id,title:b.label});return r.emit(K.initiated,{container:p,media:S,chapterId:b.id}),{player:x,config:g}}else console.error("not found")}return{...e,on:r.on.bind(r),off:r.off.bind(r),init:u,setInteractiveController:v,createPlayer:j,removeAll:$,getActivePlayer:function(){return s}}}const qt=3e3,Xt=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=qt)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const h=e.info.position$.getValue()*1e3;for(const v of i){const f=v.startTime-o;if(f<=h&&(h<=v.endTime||v.endTime===null)){c=!0;break}h<f&&(a=a===-1?f:Math.min(a,f))}return!c&&a!==-1?a:null}}},W=Xt(),I=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),de=i=>le(i)&&!he(i),Xe=i=>he(i.branches)||i.order==="end",Zt=i=>le(i.branches)&&!he(i.branches),Kt=(i,e)=>{const t=i*1e3;return de(e.controls)&&t<(e.startTime??0)},xe=(i,e)=>{const t=i*1e3;return de(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},ee=i=>i.some(e=>e.action.type==="expect"),Re=i=>i.find(e=>e.action.type==="expect"),Yt=i=>i?.length===1,Ze=i=>Yt(i)&&Qe(i[0]),Jt=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),ei=(i=[])=>i.reduce((e,t,n)=>{const r=(t?.controls??[]).filter(s=>!Qe(s));if(de(r)){const s=[t.startTime??0,t.endTime??1/0],o=t.id;if(!n)e.push({subjects:[o],range:s});else{const a=[];let c=-1/0,h=1/0,v=[];const f=[];for(let E=0;E<e.length;E++){const C=e[E];if(f.push(...C.subjects),C.range[0]<h&&(h=C.range[0]),C.range[1]>c&&(c=C.range[1]),C.range[0]<=s[0]&&C.range[1]>=s[1])return e[E].subjects.push(o),e;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(E),v=v.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(E),v=v.concat(C.subjects),s[1]=C.range[1])}if(f.push(o),s[0]<=h&&s[1]>=c)return[{subjects:f,range:s}];a.length&&a.reverse().forEach(E=>{e.splice(E,1)}),e.push({subjects:v.concat([o]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),ti=(i,e)=>ee(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&ee(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class ii{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEventEmitter:o,ignoreContainerEvent:a,permanentTextControls:c}){this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new re,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=a,this.isPermanentText=c&&Ze(t.container.controls),this.globalEventEmitter=o,this.gameState=I.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))}hide=()=>{setTimeout(()=>{this.gameState!==I.end&&(ee(this.container.container.events)&&this.gameState===I.afterInteractive||this.selectBranches.state.isExpect||(this.gameState===I.interactive?this.container.disable?.():this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})))})};show=()=>{if(this.gameState===I.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.container.enable?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!1});else{const t=Jt({fn:this.selectBranches.onControlEvent,type:0},{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(m.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(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),(this.gameState===I.end||this.gameState===I.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})),W.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===I.end});this.container.createView(t),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!0,isFirst:!0})}};selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);const e=ee(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=I.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[I.destroyed,I.removed].includes(this.gameState)&&!this.isPermanentText)return;const t=this.player.getExactTime();if(Kt(t,this.container.container))this.gameState!==I.beforeInteractive&&(this.gameState=I.beforeInteractive,this.onBeforeStartTime());else if(xe(t,this.container.container))this.gameState!==I.interactive&&(this.gameState=I.interactive,this.onStartTime());else if(this.gameState!==I.afterInteractive){const s=this.gameState;this.gameState=I.afterInteractive,s===I.interactive&&this.onEndTime()}else this.gameState!==I.destroyed&&this.removeView();const n=xe(t,this.container.container),r=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[];this.container.onProgress?.(t,n),this.globalEventEmitter.emit(m.eachTick,{subjectId:this.container.container.id,subjectName:"container",range:r,currentTime:t,isInteractiveTime:n})};reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=I.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:T.containerRemoved,visibility:!1}),this.gameState=I.removed}destroy(){this.reset(),this.removeView(),this.gameState=I.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),W.deleteContainer(this.container.container.id)}}function ni(){const i={};function e(){for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a];return!0}function t(a){const c={};for(const h in i)+h<=a&&(c[h]=i[h]);return c}function n(a){const c={};for(const h in i)+h>=a&&(c[h]=i[h]);return c}function r({timestamp:a,priority:c,initiator:h}){if(ve(a)){const v=i[a]??null;if(v&&q(c,!0)){let f={};const E=v[c];return E&&(f={...f,...E}),f=U(f)?null:f,f&&q(h,!0)?f[h]??null:f}return v}return null}function s({timestamp:a,priority:c,initiator:h}){if(ve(a))if(i[a]){if(q(c,!0))if(i[a][c]){if(q(h,!0))if(i[a][c][h]){if(delete i[a][c][h],!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:h,...v}){i[a]?.[c]?.[h]?i[a][c][h].push({...v}):i[a]?.[c]?i[a][c]={...i[a][c],[h]:[{...v}]}:i[a]?i[a]={...i[a],[c]:{[h]:[{...v}]}}:i[a]={[c]:{[h]:[{...v}]}}}return{map:i,remove:s,add:o,removeAll:e,get:r,getLte:t,getGte:n}}const si=[w.expect,w.setNextBranch],ri=1/0;function Ae(i){let e=i,t;const n=ai(),r=new ni;let s;const o=()=>{f(),$()},a=l=>{r.add.call(void 0,l),E()},c=(l=[])=>{for(const u of l)if(u.action(),si.includes(u.actionType))break},h=l=>{if(!n.isReady(l))return;const u=Z(r.get({timestamp:l,priority:"control"})??{}),d=Z(r.get({timestamp:l,priority:"container"})??{}),y=Z(r.get({timestamp:l,priority:"chapter"})??{});c([...u,...d,...y])},v=()=>{c([...Z(r.get({timestamp:1/0,priority:"chapter"})??{})])},f=()=>{t&&(s?.unsubscribe(),t=void 0)},E=()=>{t||(t=()=>setTimeout(()=>{h(1/0)}),s=e.events.ended$.subscribe(t))},C=l=>{f(),e=l},j=l=>{l.priority==="container"&&n.resetCalled(l.timestamp),r.remove(l)},$=()=>{n.release(),r.removeAll()};return{setPlayer:C,add:a,remove:j,exec:h,execEndOfVideo:v,listen:E,unlisten:f,release:o,containersEventsCallState:n}}function ai(){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??ri,h=i.get(c)??{};i.set(c,{...h,[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(e=>e.actionType===w.expect?-1:1)}const oi=(i,e)=>{const{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return{videoContentHeight:0,videoContentWidth:0};const{clientHeight:r,clientWidth:s}=e.experimental.element$.value||{};if(!(r&&s))return{videoContentHeight:0,videoContentWidth:0};const o=t/n,a=r/s;let c,h;return a>o?(h=s,c=s*o):a<o?(h=r/o,c=r):(h=s,c=r),{videoContentWidth:h,videoContentHeight:c}},ci=250;function li(i){let e=()=>{};const t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){const{parentElement:c,player:h}=i();if(c&&h){const{videoContentWidth:v,videoContentHeight:f}=oi(c,h);c.style.setProperty("--interactive-content-width",`${v}px`),c.style.setProperty("--interactive-content-height",`${f}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=Ge(a=>{const{fns:c=[]}=i();n(a);for(const h of c)h()},ci);function o(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e()},release:o}}class hi{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){const t=this.map[e];return t?t.slice():null}getAll(){const e=[];for(const t in this.map)e.push(...this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}size(){return Object.keys(this.map).length}keys(){return Object.keys(this.map)}}const di=i=>Math.floor(Math.random()*i),ui=i=>{let e=i.length,t=1/0,n=null;for(;e--;)i[e].weight<t&&(t=i[e].weight,n=i[e]);return n},pi=i=>{let e=i.length,t=-1/0,n=null;for(;e--;)i[e].weight>t&&(t=i[e].weight,n=i[e]);return n},fi=i=>{const e=i.length,t=di(e);return i[t]},je=1,mi=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??je;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??je,e>=t)return i[n];return i[i.length-1]},Le=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),ie=(i,e=!1)=>({...i,args:e?{...i.args,...Le}:{...Le,...i.args}}),Ne=({globalEventEmitter:i,player:e,interactiveEvents:t,removeControllers:n})=>{const r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},o=({action:l,controlType:u,controlId:d,containerId:y,branches:p=[],onEvent:S,isEOV:b=()=>!1,isDisabled:x=()=>!1})=>{const g=ie(l,b()),L={timestamp:1/0,priority:"control",initiator:d,actionType:g.type},N=x(),R=i.emit.bind(i,m.interactives,{subjectId:d,subjectType:u,subjectName:"control",type:N?T.actionChoiceCanceled:T.actionChoice,actionType:l.type,payload:{containerId:y,...g.args}});if(N){R();return}switch(g.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const k=p.find(V=>V.id===g.args.branchId);if(!k)return;S(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),R(),g.args.shouldOpenNow?j({subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{chapterId:k.chapterId,autoSelect:!1}}):(t.add({...L,action:j.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{chapterId:k.chapterId,autoSelect:!1}})}),n?.());return}case w.continuePlayback.trim().toLowerCase():{S(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),R(),g.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:u,action:l}):t.add({...L,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:l})});return}case w.openURI.trim().toLowerCase():{S(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),R(),g.args.shouldOpenNow?$({subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{URI:l.args.uri}}):(t.add({...L,action:$.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:g,payload:{URI:l.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(m.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:l,container:{id:u,endTime:d},branches:y=[],isEOV:p=!1,autoSelected:S=!1})=>{const b=ie(l,p),x={timestamp:!b.args.shouldOpenNow||p?1/0:d,priority:"container",initiator:u,actionType:b.type},g=i.emit.bind(i,m.interactives,{subjectId:u,subjectName:"container",type:T.actionChoice,actionType:b.type,payload:b.args});switch(b.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const L=y.find(N=>N.id===b.args.branchId);if(!L)return;g(),t.add({...x,action:j.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{chapterId:L.chapterId,autoSelect:S}})}),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():{g(),t.add({...x,action:C.bind(null,{subjectId:u,subjectName:"container",action:b})});return}case w.openURI.trim().toLowerCase():{g(),t.add({...x,action:$.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{URI:l.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(m.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:l,branches:u,isEOV:d=!1}){const y=Re(l.events);if(y){const p=ie(y.action,d);i.emit(m.interactives,{subjectId:l.id,subjectName:"container",type:T.actionChoice,actionType:p.type,payload:p.args}),t.add({timestamp:d?1/0:l.endTime,priority:"container",initiator:l.id,actionType:w.expect,action:f.bind(null,{subjectId:l.id,subjectName:"container"})}),r.isExpect=!0}else for(const p of l.events)a({action:p.action,container:l,branches:u,isEOV:d})}const h=({chapterId:l,action:u,branches:d=[]})=>{const y=i.emit.bind(i,m.interactives,{subjectId:l,subjectName:"chapter",type:T.actionChoice,actionType:u.type,payload:u.args});switch(u.type.trim().toLowerCase()){case w.setNextBranch.trim().toLowerCase():{const p=d.find(S=>S.id===u.args.branchId);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setWeightlessRandomBranch.trim().toLowerCase():{const p=fi(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setRandomBranch.trim().toLowerCase():{const p=mi(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMaxWeightBranch.trim().toLowerCase():{const p=pi(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.setMinWeightBranch.trim().toLowerCase():{const p=ui(d);return p?.chapterId?(y(),j.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case w.continuePlayback.trim().toLowerCase():return y(),C.bind(null,{subjectId:l,subjectName:"chapter",action:u});case w.openURI.trim().toLowerCase():return y(),$.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{URI:u.args.uri}});default:console.error("Unexpected chapter event"),i.emit(m.errors,new A(A.Severity.RECOVERABLE,A.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function v(l){const u=Re(l.events);if(u){if(Xe(l))return;i.emit(m.interactives,{subjectId:l.id,subjectName:"chapter",type:T.actionChoice,actionType:u.action.type,payload:u.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:w.expect,action:f.bind(null,{subjectId:l.id,subjectName:"chapter"})})}else l.events.forEach(d=>{const y=h({chapterId:l.id,action:d.action,branches:l.branches});y&&t.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:d.action.type,action:y})})}const f=({subjectId:l,subjectName:u,action:d})=>{e.pause(),i.emit(m.interactives,{subjectId:l,subjectName:u,type:T.actionExecution,actionType:d?.type??w.expect})},E=({subjectId:l,subjectName:u})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(m.interactives,{subjectId:l,subjectName:u,type:T.actionExecution,actionType:"after-expect"})},C=({subjectId:l,subjectName:u,subjectType:d,action:y})=>{i.emit(m.interactives,{subjectId:l,subjectName:u,subjectType:d,type:T.actionExecution,actionType:y.type})},j=({subjectId:l,subjectName:u,subjectType:d,action:y,payload:p})=>{p.behaviour="change-chapter",i.emit(m.interactives,{subjectId:l,subjectName:u,subjectType:d,type:T.actionExecution,actionType:y.type,payload:p})},$=({subjectId:l,subjectName:u,subjectType:d,action:y,payload:p})=>{if(!p.URI)return;const S=window.open(p.URI,"_blank","noopener,noreferrer");S&&(S.opener=null),i.emit(m.interactives,{subjectId:l,subjectName:u,subjectType:d,type:T.actionExecution,actionType:y.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:h,onExpectEvent:f,expectEventHandler:E,setManifestChapterEvents:v,setManifestContainerEvents:c,stopExpect:s,state:r}};class G{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=G.#a(e,r),this.target.addEventListener(t,n,this.options)}unlisten(){this.target.removeEventListener(this.type,this.listener,this.options),this.target=null,this.listener=null,this.options=!1}static#a(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{const n=new Set(["passive","capture"]),r=Object.keys(t).filter(o=>!n.has(o));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),G.#c(e)?t:t.capture||!1}}static#s=void 0;static#c(e){let t=G.#s;if(t===void 0){t=!1;try{const n={},r={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);const s=()=>{};e.addEventListener("test",s,n),e.removeEventListener("test",s,n)}catch{t=!1}G.#s=t}return t||!1}}class yi{constructor(){this.bindingMap=new hi}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;const s=new G(e,t,n,r);this.bindingMap.push(t,s)}listenOnce(e,t,n,r){const s=o=>{this.unlisten(e,t,s),n(o)};this.listen(e,t,s,r)}unlisten(e,t,n){if(!this.bindingMap)return;const r=this.bindingMap.get(t)||[];for(const s of r)s.target===e&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(t,s))}removeAll(){if(!this.bindingMap)return;const e=this.bindingMap.getAll();for(const t of e)t.unlisten();this.bindingMap.clear()}}class gi{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 e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;const t=e.data,n=t.length;for(let r=3;r<n;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){const n=e.width+e.height;if(this._prevSizeId===n)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=n}async save(){const e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}}class vi{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
7
7
|
position: absolute;
|
|
8
8
|
top: 0;
|
|
9
9
|
left: 0;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vkontakte/videoplayer-interactive",
|
|
3
|
-
"version": "1.0.7-
|
|
3
|
+
"version": "1.0.7-dev.6643328a.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.98-
|
|
54
|
-
"@vkontakte/videoplayer-shared": "1.0.32-
|
|
53
|
+
"@vkontakte/videoplayer-core": "2.0.98-dev.a3af0042.0",
|
|
54
|
+
"@vkontakte/videoplayer-shared": "1.0.32-dev.1023506c.0",
|
|
55
55
|
"uuid": "^9.0.0"
|
|
56
56
|
}
|
|
57
57
|
}
|