@vkontakte/videoplayer-interactive 1.0.7-dev.200de7b.0 → 1.0.7-dev.6e70b297.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/evergreen.esm.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-interactive v1.0.7-dev.200de7b.0
3
- * Wed, 24 Jan 2024 08:12:47 GMT
2
+ * @vkontakte/videoplayer-interactive v1.0.7-dev.6e70b297.0
3
+ * Wed, 07 Feb 2024 10:02:44 GMT
4
4
  * https://st.mycdn.me/static/vkontakte-videoplayer/1-0-7/doc/
5
5
  */
6
- import{loadVKLangPack as Ze,Subscription as re,ValueSubject as ee,Observable as ue,getCurrentBrowser as Ke,CurrentClientBrowser as Ye,once as Je}from"@vkontakte/videoplayer-shared/esnext.esm.js";import{v4 as et}from"uuid";import{Player as tt}from"@vkontakte/videoplayer-core/esnext.esm.js";const it="1.0.7-dev.200de7b.0";function Ne(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",nt="SDK_NAME-controls-container",Le=()=>document.querySelector(`.${nt}`),O={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},pe={top:"flex-start",bottom:"flex-end",center:"center"},fe={start:"flex-start",end:"flex-end",center:"center"},me={start:"left",end:"right",center:"center"},Me=({target:i,props:e})=>{i.style.alignItems=pe[e?.text?.gravityVertical]??pe.center,i.style.justifyContent=fe[e?.text?.gravityHorizontal]??fe.center,i.style.textAlign=me[e?.text?.alignment]??me.start},Oe=({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=Ne(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},Ve=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Ne(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 ke=i=>{if(i.type.trim().toLowerCase()==="area")return new st(i)};class st 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"}}),Ve({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 Pe=i=>{if(i.type.trim().toLowerCase()==="button")return new rt(i)};class rt 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}),Ve({target:s,props:this.control.props,fallback:O,dependsOn:n}),Me({target:s,props:this.control.props}),Oe({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 at=i=>{if(i.type.trim().toLowerCase()==="text")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("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}),Me({target:s,props:this.control.props}),Oe({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 ct{constructor(e){this.layout=e}}const lt=i=>{if(i.type.trim().toLowerCase()==="relative")return new Fe(i)};class Fe extends ct{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 $e{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 Be=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new ht(i,e)};class ht extends $e{constructor(e,t){super(e),this.rootElement=t??Le(),this.layout=new Fe(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",Pe),this.addControlFactory("text",at),this.addControlFactory("area",ke)}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")}removeView(){this.isRemoved||(this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${M}-${this.container.id}`)}}function De(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}const U={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},G=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ce=i=>G(i,U.Object),ne=i=>G(i,U.String),Ge=i=>G(i,U.Array),ze=i=>G(i,U.Number),dt=i=>G(i,U.Function),ye=i=>ze(i)&&!isNaN(i),z=i=>ce(i)&&Object.keys(i).length===0,Ue=i=>Ge(i)&&!i.length,Q=(i,e)=>ne(i)&&(e?i.trim():i).length,We=window.navigator.userAgent.toLowerCase(),ut=/mobi/i.test(We);We.indexOf("android")>-1;const pt="video_interactive",ft="videoint",mt=250;class yt{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=gt(e),this.resizeObserver=new ResizeObserver(De(this.onResize,mt)),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 Ze(this.lang,pt,ft)}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 gt(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 K=(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},vt="3.1",ge={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},bt={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Et=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 g=[bt];switch(a){case"await":h?g=[]:s=[];break;case"default":{const f={type:"onSuspense",action:{type:ge.default,args:{branchId:n,shouldOpenNow:!h,isDetachContainer:!0}}};h?g=[f]:s=[f];break}case"random":case"weightlessRandom":case"max":case"min":{const f={type:"onSuspense",action:{type:ge[a],args:{}}};h?g=[f]:s=[f];break}}for(const f of c.controls)o.push({...c,controls:[{...f}],id:et(),events:g})}e.push({...t,containers:o,events:s,branches:r})}return i.metadata.version=vt,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},Ct="3.2",wt=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:Ct},media:e}}return i},St="3.3",It=(i=[])=>({edit:{chapters:i},view:{}}),ve={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Tt=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:g,type:f,...w})=>({...w,type:g??f})),events:h.events?.length?h.events:[ve]}));e.push({id:r,...a,containers:c,events:a.events?.length?a.events:[ve]}),t.push({id:r,x:s,y:o})}return{...i,chapters:e,graph:It(t),metadata:{...i.metadata,version:St}}},xt=[{version:"3.0",migrate:Et},{version:"3.1",migrate:wt},{version:"3.2",migrate:Tt}],Rt=i=>xt.reduce((e,t)=>K(e.metadata.version,t.version)?e:t.migrate(e),i),At=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),S=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var F;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(F||(F={}));const be={metadata:"Object",chapters:"Array"},jt="3.0.0",Nt="3.3.0",He=i=>{const e=K(i,jt);return e===-1?!1:e===0?!0:K(i,Nt)!==1},Lt=i=>{if(!ce(i))return!1;for(const e in be)if(!i[e]||!G(i[e],be[e]))return!1;return He(i.metadata.version)},Qe=i=>i.type===At.Text;class R{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 Mt{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{dt(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 Ot{loaders;constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return _t(...this.loaders[e])(t)}}function _t(...i){return async function(t){const n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function Y(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function 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:Y(e,se.name,"Could not find media"),actions:i}}}return{...n,errors:Y(e,se.name,"Could not find chapter"),actions:i}}const Vt=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(!Lt(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 $t(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function kt(i){const{manifest:e,manifestURL:t}=await Vt(i),n=Rt(e);return n.media=Pt(n.media,t),delete n.metadata.media,n}function te(i,e){return i.find(t=>t.id===e)}function Ee(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 Ce(i,e){return i.videos.find(t=>t.id===e)}function Pt(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const r=Ft(n.url,e);return{...n,url:r||n.url}})}))}}function Ft(i,e){try{return new URL(i,e).href}catch{return""}}function $t(i){return K(i,"3.2.0")>=0}class Bt extends Ot{constructor(e,t){super(e),this.onError=t,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this}async setManifest(e){this.release();const t=await this.exec("manifestLoaders",{actions:{addErrorMessage:Y},result:null,errors:null,source:e});t.errors&&this.errorHandler(t.errors);const n=await kt(t.result??e);return this.manifest=n,this}async setInitial(){return this.setNext()}async setNext(e=this.manifest.metadata.initChapterId){const t=await this.exec("chapterLoaders",se({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Ee,getChapter:te,getMedia:Ce,getByBranches:this.getByBranches.bind(this),addErrorMessage:Y},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=Ce(this.manifest.media,t.videoId),r=Ee(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"},we={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},x={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function Dt(){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 Se(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 q=(i,e)=>{const t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))},Gt=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[]},Z={activePlayerChanged:"sc-active-player-changed",initiated:"sc-initiated",playerCreated:"sc-player-created"},zt=2;function Ut(i){const e=Dt();let t,n;const r=new qe;let s={},o=!1,a=null,c=!1,h;i&&g(i);function g(d){a=d}function f(d,m,p){if(!a)throw Error("need to set interactive controller");const b=(e.map.get(d)??{})[m];if(b){s={chapterId:p,listId:d,itemId:m,...b};const v=s.player;n=v.info.currentQuality$.subscribe(C=>{if(!(!C||!v.info.position$.getValue())){t=C;for(const N of e.map)Object.values(N[1]).forEach(({player:L})=>{v.info.isAutoQualityEnabled$.getValue()||q(L,C)})}}),b.container.remove(),o=!1,a.setPlayer(b.player),c||(a.init(),c=!0),r.emit(Z.activePlayerChanged,{player:s.player,config:s.config});return}throw Error("Can't set. Not find.")}async function w(d,m,p){if(!a)throw Error("need to set interactive controller");if(z(s)||d!==s.itemId)return;if(p>=0&&!o){const b=a.getChapterBranches();o=!0;const v=new Set;for(const C of b)v.has(C.media.id)||(await A({media:C.media,chapterId:C.chapter.id,setAsActive:!1,title:C.chapter.label}),v.add(C.media.id))}}async function E({chapter:{id:d},media:m}){if(z(s))return;n?.unsubscribe();const p=s.player.info.muted$.getValue(),I=s.player.info.currentQuality$.getValue(),b=s.player.info.isAutoQualityEnabled$.getValue(),v=s.player.info.volume$.getValue(),C=s.player.info.currentPlaybackRate$.getValue(),N=!b;let L=!1;for(const j of e.map)if(j[0]===m.id){const W=Object.keys(j[1]);for(const k of W)k===s.itemId?(W.length<zt||(L=!0),e.removePlayer(j[0],k)):(L=!0,f(j[0],k,d),N?q(s.player,I):s.player.setAutoQuality(!0),s.player.setVolume(v),s.player.setMuted(p),s.player.setPlaybackRate(C))}else e.removePlayer(j[0]);L||(await A({media:m,chapterId:d,setAsActive:!0,playbackRate:C}),N?q(s.player,I):s.player.setAutoQuality(!0),s.player.setVolume(v),s.player.setMuted(p))}async function A({media:d,chapterId:m,prefetch:p=!0,setAsActive:I=!0,autoplay:b=!1,preferredExt:v,title:C,playbackRate:N}){const L=Math.random().toString(),j=document.createElement("div");h.append(j);const W=s?.player?.info.isAutoQualityEnabled$.getValue();let k;if(a?.options?.vkVideoLoader){const H=Gt(d);H.length&&(k=await a.options.vkVideoLoader(...H))}const he={container:j,...k?.videos?.[0]||{sources:Se(d,v).sources},title:C},P=new tt;P.initVideo(he);const Xe=j.lastChild,de=new re;de.add(P.info.position$.subscribe(function(H){w(L,P.info.duration$.getValue(),H)})).add(P.events.canplay$.subscribe(function(){W||q(P,t),N&&P.setPlaybackRate(N)})),Xe&&(j.style.display="none",j.classList.add(m));const $=e.createPlayer({listId:d.id,itemId:L,player:P,container:j,sources:Se(d,v).sources,config:he,subscription:de});return I&&f(d.id,$.itemId,m),b&&$.player.play(),p&&!b&&$.player.prepare(),r.emit(Z.playerCreated,$.player),{player:$.player,config:$.config}}function V(){l(),a=null}function l(){a?.off(y.chapterChanged,E),e.removeAll(),s={},c=!1,o=!1}async function u({source:d,initialChapter:m,container:p}){if(!a)throw Error("need to set interactive controller");await a.setManifest(d),l(),h=p;const{media:I,chapter:b}=await a.setChapter({chapterId:m});if(I){a.on(y.chapterChanged,E);const{player:v,config:C}=await A({media:I,chapterId:b.id,title:b.label});return r.emit(Z.initiated,{container:p,media:I,chapterId:b.id}),{player:v,config:C}}else console.error("not found")}return{...e,on:r.on.bind(r),off:r.off.bind(r),init:u,setInteractiveController:g,createPlayer:A,removeAll:V,getActivePlayer:function(){return s}}}const Wt=3e3,Ht=()=>{let i=[],e=null;return{setPlayer:o=>{e=o},setContainers:o=>{i=o},deleteContainer:o=>{i=i.filter(a=>a.id!==o)},getNextInteractiveTime:(o=Wt)=>{if(!i.length||e===null)return null;let a=-1,c=!1;const h=e.info.position$.getValue()*1e3;for(const g of i){const f=g.startTime-o;if(f<=h&&(h<=g.endTime||g.endTime===null)){c=!0;break}h<f&&(a=a===-1?f:Math.min(a,f))}return!c&&a!==-1?a:null}}},B=Ht(),T=Object.freeze({nothing:0,beforeInteractive:1,interactive:2,afterInteractive:3,end:4,removed:5,destroyed:6}),le=i=>Ge(i)&&!Ue(i),Qt=i=>Ue(i.branches)||i.order==="end",qt=(i,e)=>{const t=i*1e3;return le(e.controls)&&t<(e.startTime??0)},Ie=(i,e)=>{const t=i*1e3;return le(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)},J=i=>i.some(e=>e.action.type==="expect"),Te=i=>i.find(e=>e.action.type==="expect"),Xt=i=>i?.length===1,Zt=i=>Xt(i)&&Qe(i[0]),Kt=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),Yt=(i=[])=>i.reduce((e,t,n)=>{const r=(t?.controls??[]).filter(s=>!Qe(s));if(le(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,g=[];const f=[];for(let w=0;w<e.length;w++){const E=e[w];if(f.push(...E.subjects),E.range[0]<h&&(h=E.range[0]),E.range[1]>c&&(c=E.range[1]),E.range[0]<=s[0]&&E.range[1]>=s[1])return e[w].subjects.push(o),e;s[0]>=E.range[0]&&s[0]<=E.range[1]&&(a.push(w),g=g.concat(E.subjects),s[0]=E.range[0]),s[1]>=E.range[0]&&s[1]<=E.range[1]&&(a.push(w),g=g.concat(E.subjects),s[1]=E.range[1])}if(f.push(o),s[0]<=h&&s[1]>=c)return[{subjects:f,range:s}];a.length&&a.reverse().forEach(w=>{e.splice(w,1)}),e.push({subjects:g.concat([o]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),Jt=(i,e)=>J(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&J(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);class ei{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&&Zt(t.container.controls),this.globalEventEmitter=o,this.gameState=T.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!==T.end&&(J(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!0,isFirst:!1});else{const t=Kt({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.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:x.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})),B.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.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=J(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:x.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState)&&!this.isPermanentText)return;const t=this.player.getExactTime();if(qt(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(Ie(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const s=this.gameState;this.gameState=T.afterInteractive,s===T.interactive&&this.onEndTime()}else this.gameState!==T.destroyed&&this.removeView();const n=Ie(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=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(y.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),B.deleteContainer(this.container.container.id)}}function ti(){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(ye(a)){const g=i[a]??null;if(g&&Q(c,!0)){let f={};const w=g[c];return w&&(f={...f,...w}),f=z(f)?null:f,f&&Q(h,!0)?f[h]??null:f}return g}return null}function s({timestamp:a,priority:c,initiator:h}){if(ye(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],!z(i[a][c]))return!0}else return!1;if(delete i[a][c],!z(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:h,...g}){i[a]?.[c]?.[h]?i[a][c][h].push({...g}):i[a]?.[c]?i[a][c]={...i[a][c],[h]:[{...g}]}:i[a]?i[a]={...i[a],[c]:{[h]:[{...g}]}}:i[a]={[c]:{[h]:[{...g}]}}}return{map:i,remove:s,add:o,removeAll:e,get:r,getLte:t,getGte:n}}const ii=[S.expect,S.setNextBranch],ni=1/0;function xe(i){let e=i,t;const n=si(),r=new ti;let s;const o=()=>{f(),V()},a=l=>{r.add.call(void 0,l),w()},c=(l=[])=>{for(const u of l)if(u.action(),ii.includes(u.actionType))break},h=l=>{if(!n.isReady(l))return;const u=X(r.get({timestamp:l,priority:"control"})??{}),d=X(r.get({timestamp:l,priority:"container"})??{}),m=X(r.get({timestamp:l,priority:"chapter"})??{});c([...u,...d,...m])},g=()=>{c([...X(r.get({timestamp:1/0,priority:"chapter"})??{})])},f=()=>{t&&(s?.unsubscribe(),t=void 0)},w=()=>{t||(t=()=>setTimeout(()=>{h(1/0)}),s=e.events.ended$.subscribe(t))},E=l=>{f(),e=l},A=l=>{l.priority==="container"&&n.resetCalled(l.timestamp),r.remove(l)},V=()=>{n.release(),r.removeAll()};return{setPlayer:E,add:a,remove:A,exec:h,execEndOfVideo:g,listen:w,unlisten:f,release:o,containersEventsCallState:n}}function si(){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??ni,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 X(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}const ri=(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}},ai=250;function oi(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:g,videoContentHeight:f}=ri(c,h);c.style.setProperty("--interactive-content-width",`${g}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=De(a=>{const{fns:c=[]}=i();n(a);for(const h of c)h()},ai);function o(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e()},release:o}}class ci{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 li=i=>Math.floor(Math.random()*i),hi=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},di=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},ui=i=>{const e=i.length,t=li(e);return i[t]},Re=1,pi=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Re;const t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Re,e>=t)return i[n];return i[i.length-1]},Ae=Object.freeze({shouldOpenNow:!0,isDetachContainer:!0}),ie=(i,e=!1)=>({...i,args:e?{...i.args,...Ae}:{...Ae,...i.args}}),je=({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:m,branches:p=[],onEvent:I,isEOV:b=()=>!1})=>{const v=ie(l,b()),C={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},N=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:u,subjectName:"control",type:x.actionChoice,actionType:l.type,payload:{containerId:m,...v.args}});switch(v.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const L=p.find(j=>j.id===v.args.branchId);if(!L)return;I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?A({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:L.chapterId,autoSelect:!1}}):(t.add({...C,action:A.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:L.chapterId,autoSelect:!1}})}),n?.());return}case S.continuePlayback.trim().toLowerCase():{I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?E({subjectId:d,subjectName:"control",subjectType:u,action:l}):t.add({...C,action:E.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:l})});return}case S.openURI.trim().toLowerCase():{I(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),N(),v.args.shouldOpenNow?V({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:l.args.uri}}):(t.add({...C,action:V.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:l.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(y.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected control event"}));return}},a=({action:l,container:{id:u,endTime:d},branches:m=[],isEOV:p=!1,autoSelected:I=!1})=>{const b=ie(l,p),v={timestamp:!b.args.shouldOpenNow||p?1/0:d,priority:"container",initiator:u,actionType:b.type},C=i.emit.bind(i,y.interactives,{subjectId:u,subjectName:"container",type:x.actionChoice,actionType:b.type,payload:b.args});switch(b.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const N=m.find(L=>L.id===b.args.branchId);if(!N)return;C(),t.add({...v,action:A.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{chapterId:N.chapterId,autoSelect:I}})}),n?.();return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{C(),t.add({...v,action:E.bind(null,{subjectId:u,subjectName:"container",action:b})});return}case S.openURI.trim().toLowerCase():{C(),t.add({...v,action:V.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{URI:l.args.uri}})}),n?.();return}default:console.error("Unexpected container event"),i.emit(y.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected container event"}));return}};function c({container:l,branches:u,isEOV:d=!1}){const m=Te(l.events);if(m){const p=ie(m.action,d);i.emit(y.interactives,{subjectId:l.id,subjectName:"container",type:x.actionChoice,actionType:p.type,payload:p.args}),t.add({timestamp:d?1/0:l.endTime,priority:"container",initiator:l.id,actionType:S.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 m=i.emit.bind(i,y.interactives,{subjectId:l,subjectName:"chapter",type:x.actionChoice,actionType:u.type,payload:u.args});switch(u.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{const p=d.find(I=>I.id===u.args.branchId);return p?.chapterId?(m(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{const p=ui(d);return p?.chapterId?(m(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{const p=pi(d);return p?.chapterId?(m(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{const p=di(d);return p?.chapterId?(m(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{const p=hi(d);return p?.chapterId?(m(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return m(),E.bind(null,{subjectId:l,subjectName:"chapter",action:u});case S.openURI.trim().toLowerCase():return m(),V.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{URI:u.args.uri}});default:console.error("Unexpected chapter event"),i.emit(y.errors,new R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function g(l){const u=Te(l.events);if(u){if(Qt(l))return;i.emit(y.interactives,{subjectId:l.id,subjectName:"chapter",type:x.actionChoice,actionType:u.action.type,payload:u.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:S.expect,action:f.bind(null,{subjectId:l.id,subjectName:"chapter"})})}else l.events.forEach(d=>{const m=h({chapterId:l.id,action:d.action,branches:l.branches});m&&t.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:d.action.type,action:m})})}const f=({subjectId:l,subjectName:u,action:d})=>{e.pause(),i.emit(y.interactives,{subjectId:l,subjectName:u,type:x.actionExecution,actionType:d?.type??S.expect})},w=({subjectId:l,subjectName:u})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(y.interactives,{subjectId:l,subjectName:u,type:x.actionExecution,actionType:"after-expect"})},E=({subjectId:l,subjectName:u,subjectType:d,action:m})=>{i.emit(y.interactives,{subjectId:l,subjectName:u,subjectType:d,type:x.actionExecution,actionType:m.type})},A=({subjectId:l,subjectName:u,subjectType:d,action:m,payload:p})=>{p.behaviour="change-chapter",i.emit(y.interactives,{subjectId:l,subjectName:u,subjectType:d,type:x.actionExecution,actionType:m.type,payload:p})},V=({subjectId:l,subjectName:u,subjectType:d,action:m,payload:p})=>{if(!p.URI)return;const I=window.open(p.URI,"_blank","noopener,noreferrer");I&&(I.opener=null),i.emit(y.interactives,{subjectId:l,subjectName:u,subjectType:d,type:x.actionExecution,actionType:m.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:h,onExpectEvent:f,expectEventHandler:w,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:s,state:r}};class D{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=D.#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(",")),D.#c(e)?t:t.capture||!1}}static#s=void 0;static#c(e){let t=D.#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}D.#s=t}return t||!1}}class fi{constructor(){this.bindingMap=new ci}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;const s=new D(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 mi{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 yi{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 P,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.6e70b297.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",Ve=()=>document.querySelector(`.${rt}`),V={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"},Oe=({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??V.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 at(i)};class at 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:{...V,backgroundColor:"transparent"}}),ke({target:s,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:n}),ae({target:s,layoutParams:this.control.layoutParams,fallback:V}),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 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");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:V}),$e({target:s,props:this.control.props,fallback:V}),ke({target:s,props:this.control.props,fallback:V,dependsOn:n}),Oe({target:s,props:this.control.props}),_e({target:o,props:this.control.props,fallback:V,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}const ct=i=>{if(i.type.trim().toLowerCase()==="text")return new lt(i)};class lt 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:V}),Oe({target:s,props:this.control.props}),_e({target:o,props:this.control.props,fallback:V,dependsOn:n}),s.append(o),r.append(s),e.append(r),r}getElement(){return document.querySelector(`.${M}-${this.control.id}`)}}class ht{constructor(e){this.layout=e}}const dt=i=>{if(i.type.trim().toLowerCase()==="relative")return new Be(i)};class Be extends ht{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 ut(i,e)};class ut extends De{constructor(e,t){super(e),this.rootElement=t??Ve(),this.layout=new Be(this.container.layout),this.isRemoved=!1,this.addControlFactory("button",Fe),this.addControlFactory("text",ct),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")}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 U={Object:"Object",String:"String",Array:"Array",Number:"Number",Function:"Function",Boolean:"Boolean"},G=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ce=i=>G(i,U.Object),ne=i=>G(i,U.String),le=i=>G(i,U.Array),ze=i=>G(i,U.Number),pt=i=>G(i,U.Function),ve=i=>ze(i)&&!isNaN(i),z=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(),ft=/mobi/i.test(Ue);Ue.indexOf("android")>-1;const mt="video_interactive",yt="videoint",gt=250;class vt{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=bt(e),this.resizeObserver=new ResizeObserver(Ge(this.onResize,gt)),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,mt,yt)}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 bt(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},Ct="3.1",be={default:"setNextBranch",random:"setRandomBranch",weightlessRandom:"setWeightlessRandomBranch",max:"setMaxWeightBranch",min:"setMinWeightBranch"},Et={type:"onSuspense",action:{type:"continuePlayback",args:{shouldOpenNow:!0,isDetachContainer:!0}}},wt=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 g=[Et];switch(a){case"await":h?g=[]:s=[];break;case"default":{const f={type:"onSuspense",action:{type:be.default,args:{branchId:n,shouldOpenNow:!h,isDetachContainer:!0}}};h?g=[f]:s=[f];break}case"random":case"weightlessRandom":case"max":case"min":{const f={type:"onSuspense",action:{type:be[a],args:{}}};h?g=[f]:s=[f];break}}for(const f of c.controls)o.push({...c,controls:[{...f}],id:it(),events:g})}e.push({...t,containers:o,events:s,branches:r})}return i.metadata.version=Ct,i.metadata.updated=new Date().toISOString(),{...i,chapters:e}},It="3.2",St=i=>{if(!i.media){const{media:e,...t}=i.metadata;return{...i,metadata:{...t,version:It},media:e}}return i},Tt="3.3",xt=(i=[])=>({edit:{chapters:i},view:{}}),Ce={type:"onSuspense",action:{type:"expect",args:{shouldOpenNow:!0,isDetachContainer:!0}}},Rt=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:g,type:f,...w})=>({...w,type:g??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:xt(t),metadata:{...i.metadata,version:Tt}}},At=[{version:"3.0",migrate:wt},{version:"3.1",migrate:St},{version:"3.2",migrate:Rt}],jt=i=>At.reduce((e,t)=>Y(e.metadata.version,t.version)?e:t.migrate(e),i),Lt=Object.freeze({Button:"Button",Area:"Area",Text:"Text"}),I=Object.freeze({openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"});var F;(function(i){i.GO_NEXT_BUTTON="GO_NEXT_BUTTON",i.GO_NEXT_AREA="GO_NEXT_AREA",i.WATCH_AGAIN="WATCH_AGAIN",i.OPEN_GRAPH="OPEN_GRAPH",i.CLOSE_GRAPH="CLOSE_GRAPH"})(F||(F={}));const Ee={metadata:"Object",chapters:"Array"},Nt="3.0.0",Mt="3.3.0",He=i=>{const e=Y(i,Nt);return e===-1?!1:e===0?!0:Y(i,Mt)!==1},Vt=i=>{if(!ce(i))return!1;for(const e in Ee)if(!i[e]||!G(i[e],Ee[e]))return!1;return He(i.metadata.version)},Qe=i=>i.type===Lt.Text;class R{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 Ot{constructor(e){this.raf,this.fn,this.fns=[],this.addFn(e)}addFn=(e,t=!1)=>{pt(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 $t(...this.loaders[e])(t)}}function $t(...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 kt=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 Dt(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Pt(i){const{manifest:e,manifestURL:t}=await kt(i),n=jt(e);return n.media=Ft(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 Ft(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{const r=Bt(n.url,e);return{...n,url:r||n.url}})}))}}function Bt(i,e){try{return new URL(i,e).href}catch{return""}}function Dt(i){return Y(i,"3.2.0")>=0}class Wt extends _t{constructor(e,t){super(e),this.onError=t,this.prevChapter$=new P(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 Pt(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"},x={actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};function Gt(){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))},zt=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"},Ut=2;function Ht(i){const e=Gt();let t,n;const r=new qe;let s={},o=!1,a=null,c=!1,h;i&&g(i);function g(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 v=s.player;n=v.info.currentQuality$.subscribe(E=>{if(!(!E||!v.info.position$.getValue())){t=E;for(const L of e.map)Object.values(L[1]).forEach(({player:N})=>{v.info.isAutoQualityEnabled$.getValue()||X(N,E)})}}),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 w(d,y,p){if(!a)throw Error("need to set interactive controller");if(z(s)||d!==s.itemId)return;if(p>=0&&!o){const b=a.getChapterBranches();o=!0;const v=new Set;for(const E of b)v.has(E.media.id)||(await A({media:E.media,chapterId:E.chapter.id,setAsActive:!1,title:E.chapter.label}),v.add(E.media.id))}}async function C({chapter:{id:d},media:y}){if(z(s))return;n?.unsubscribe();const p=s.player.info.muted$.getValue(),S=s.player.info.currentQuality$.getValue(),b=s.player.info.isAutoQualityEnabled$.getValue(),v=s.player.info.volume$.getValue(),E=s.player.info.currentPlaybackRate$.getValue(),L=!b;let N=!1;for(const j of e.map)if(j[0]===y.id){const H=Object.keys(j[1]);for(const $ of H)$===s.itemId?(H.length<Ut||(N=!0),e.removePlayer(j[0],$)):(N=!0,f(j[0],$,d),L?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(v),s.player.setMuted(p),s.player.setPlaybackRate(E))}else e.removePlayer(j[0]);N||(await A({media:y,chapterId:d,setAsActive:!0,playbackRate:E}),L?X(s.player,S):s.player.setAutoQuality(!0),s.player.setVolume(v),s.player.setMuted(p))}async function A({media:d,chapterId:y,prefetch:p=!0,setAsActive:S=!0,autoplay:b=!1,preferredExt:v,title:E,playbackRate:L}){const N=Math.random().toString(),j=document.createElement("div");h.append(j);const H=s?.player?.info.isAutoQualityEnabled$.getValue();let $;if(a?.options?.vkVideoLoader){const Q=zt(d);Q.length&&($=await a.options.vkVideoLoader(...Q))}const ue={container:j,...$?.videos?.[0]||{sources:Te(d,v).sources},title:E},k=new nt;k.initVideo(ue);const Ke=j.lastChild,pe=new re;pe.add(k.info.position$.subscribe(function(Q){w(N,k.info.duration$.getValue(),Q)})).add(k.events.canplay$.subscribe(function(){H||X(k,t),L&&k.setPlaybackRate(L)})),Ke&&(j.style.display="none",j.classList.add(y));const B=e.createPlayer({listId:d.id,itemId:N,player:k,container:j,sources:Te(d,v).sources,config:ue,subscription:pe});return S&&f(d.id,B.itemId,y),b&&B.player.play(),p&&!b&&B.player.prepare(),r.emit(K.playerCreated,B.player),{player:B.player,config:B.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:v,config:E}=await A({media:S,chapterId:b.id,title:b.label});return r.emit(K.initiated,{container:p,media:S,chapterId:b.id}),{player:v,config:E}}else console.error("not found")}return{...e,on:r.on.bind(r),off:r.off.bind(r),init:u,setInteractiveController:g,createPlayer:A,removeAll:_,getActivePlayer:function(){return s}}}const Qt=3e3,qt=()=>{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 g of i){const f=g.startTime-o;if(f<=h&&(h<=g.endTime||g.endTime===null)){c=!0;break}h<f&&(a=a===-1?f:Math.min(a,f))}return!c&&a!==-1?a:null}}},D=qt(),T=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",Xt=i=>le(i.branches)&&!he(i.branches),Zt=(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"),Kt=i=>i?.length===1,Ze=i=>Kt(i)&&Qe(i[0]),Yt=({fn:i,type:e=1},...t)=>(...n)=>e?i(...n,...t):i({...n[e],...t[e]}),Jt=(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,g=[];const f=[];for(let w=0;w<e.length;w++){const C=e[w];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[w].subjects.push(o),e;s[0]>=C.range[0]&&s[0]<=C.range[1]&&(a.push(w),g=g.concat(C.subjects),s[0]=C.range[0]),s[1]>=C.range[0]&&s[1]<=C.range[1]&&(a.push(w),g=g.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(w=>{e.splice(w,1)}),e.push({subjects:g.concat([o]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]),ei=(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 ti{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=T.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!==T.end&&(ee(this.container.container.events)&&this.gameState===T.afterInteractive||this.selectBranches.state.isExpect||(this.container.hide?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})))})};show=()=>{if(this.gameState===T.interactive&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!0,isFirst:!1});else{const t=Yt({fn:this.selectBranches.onControlEvent,type:0},{branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.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:x.visibility,visibility:!1})),(this.gameState===T.end||this.gameState===T.afterInteractive||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.visibility,visibility:!1})),D.deleteContainer(this.container.container.id)},isEOV:()=>this.gameState===T.end});this.container.createView(t),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.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:x.visibility,visibility:!1})}onEndOfVideo=()=>{this.gameState=T.end,this.selectContainerEvent(!0)};whilePlaying=()=>{if(this.player.experimental.element$.getValue()?.readyState<1||[T.destroyed,T.removed].includes(this.gameState)&&!this.isPermanentText)return;const t=this.player.getExactTime();if(Zt(t,this.container.container))this.gameState!==T.beforeInteractive&&(this.gameState=T.beforeInteractive,this.onBeforeStartTime());else if(xe(t,this.container.container))this.gameState!==T.interactive&&(this.gameState=T.interactive,this.onStartTime());else if(this.gameState!==T.afterInteractive){const s=this.gameState;this.gameState=T.afterInteractive,s===T.interactive&&this.onEndTime()}else this.gameState!==T.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=T.beforeInteractive}removeView(){this.container.removeView(),this.globalEventEmitter.emit(m.interactives,{subjectId:this.container.container.id,subjectName:"container",type:x.containerRemoved,visibility:!1}),this.gameState=T.removed}destroy(){this.reset(),this.removeView(),this.gameState=T.destroyed,this.subscription.unsubscribe(),this.branches=[],this.interactiveEvents.containersEventsCallState.setCalled({timestamp:this.container.container.endTime??1/0,id:this.container.container.id}),D.deleteContainer(this.container.container.id)}}function ii(){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 g=i[a]??null;if(g&&q(c,!0)){let f={};const w=g[c];return w&&(f={...f,...w}),f=z(f)?null:f,f&&q(h,!0)?f[h]??null:f}return g}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],!z(i[a][c]))return!0}else return!1;if(delete i[a][c],!z(i[a]))return!0}else return!1;return delete i[a]}else return!1}function o({timestamp:a,priority:c,initiator:h,...g}){i[a]?.[c]?.[h]?i[a][c][h].push({...g}):i[a]?.[c]?i[a][c]={...i[a][c],[h]:[{...g}]}:i[a]?i[a]={...i[a],[c]:{[h]:[{...g}]}}:i[a]={[c]:{[h]:[{...g}]}}}return{map:i,remove:s,add:o,removeAll:e,get:r,getLte:t,getGte:n}}const ni=[I.expect,I.setNextBranch],si=1/0;function Ae(i){let e=i,t;const n=ri(),r=new ii;let s;const o=()=>{f(),_()},a=l=>{r.add.call(void 0,l),w()},c=(l=[])=>{for(const u of l)if(u.action(),ni.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])},g=()=>{c([...Z(r.get({timestamp:1/0,priority:"chapter"})??{})])},f=()=>{t&&(s?.unsubscribe(),t=void 0)},w=()=>{t||(t=()=>setTimeout(()=>{h(1/0)}),s=e.events.ended$.subscribe(t))},C=l=>{f(),e=l},A=l=>{l.priority==="container"&&n.resetCalled(l.timestamp),r.remove(l)},_=()=>{n.release(),r.removeAll()};return{setPlayer:C,add:a,remove:A,exec:h,execEndOfVideo:g,listen:w,unlisten:f,release:o,containersEventsCallState:n}}function ri(){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??si,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===I.expect?-1:1)}const ai=(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}},oi=250;function ci(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:g,videoContentHeight:f}=ai(c,h);c.style.setProperty("--interactive-content-width",`${g}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()},oi);function o(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e()},release:o}}class li{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 hi=i=>Math.floor(Math.random()*i),di=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},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=>{const e=i.length,t=hi(e);return i[t]},je=1,fi=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})=>{const v=ie(l,b()),E={timestamp:1/0,priority:"control",initiator:d,actionType:v.type},L=i.emit.bind(i,m.interactives,{subjectId:d,subjectType:u,subjectName:"control",type:x.actionChoice,actionType:l.type,payload:{containerId:y,...v.args}});switch(v.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const N=p.find(j=>j.id===v.args.branchId);if(!N)return;S(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?A({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}}):(t.add({...E,action:A.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{chapterId:N.chapterId,autoSelect:!1}})}),n?.());return}case I.continuePlayback.trim().toLowerCase():{S(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?C({subjectId:d,subjectName:"control",subjectType:u,action:l}):t.add({...E,action:C.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:l})});return}case I.openURI.trim().toLowerCase():{S(v.args.isDetachContainer,w.bind(null,{subjectId:d,subjectName:"control"})),L(),v.args.shouldOpenNow?_({subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:l.args.uri}}):(t.add({...E,action:_.bind(null,{subjectId:d,subjectName:"control",subjectType:u,action:v,payload:{URI:l.args.uri}})}),n?.());return}default:console.error("Unexpected control event"),i.emit(m.errors,new R(R.Severity.RECOVERABLE,R.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),v={timestamp:!b.args.shouldOpenNow||p?1/0:d,priority:"container",initiator:u,actionType:b.type},E=i.emit.bind(i,m.interactives,{subjectId:u,subjectName:"container",type:x.actionChoice,actionType:b.type,payload:b.args});switch(b.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const L=y.find(N=>N.id===b.args.branchId);if(!L)return;E(),t.add({...v,action:A.bind(null,{subjectId:u,subjectName:"container",action:b,payload:{chapterId:L.chapterId,autoSelect:S}})}),n?.();return}case I.setMaxWeightBranch.trim().toLowerCase():return;case I.setMinWeightBranch.trim().toLowerCase():return;case I.setRandomBranch.trim().toLowerCase():return;case I.setWeightlessRandomBranch.trim().toLowerCase():return;case I.continuePlayback.trim().toLowerCase():{E(),t.add({...v,action:C.bind(null,{subjectId:u,subjectName:"container",action:b})});return}case I.openURI.trim().toLowerCase():{E(),t.add({...v,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 R(R.Severity.RECOVERABLE,R.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:x.actionChoice,actionType:p.type,payload:p.args}),t.add({timestamp:d?1/0:l.endTime,priority:"container",initiator:l.id,actionType:I.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:x.actionChoice,actionType:u.type,payload:u.args});switch(u.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{const p=d.find(S=>S.id===u.args.branchId);return p?.chapterId?(y(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{const p=pi(d);return p?.chapterId?(y(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{const p=fi(d);return p?.chapterId?(y(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{const p=ui(d);return p?.chapterId?(y(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{const p=di(d);return p?.chapterId?(y(),A.bind(null,{subjectId:l,subjectName:"chapter",action:u,payload:{chapterId:p.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return y(),C.bind(null,{subjectId:l,subjectName:"chapter",action:u});case I.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 R(R.Severity.RECOVERABLE,R.Category.INTERACTIVES,{message:"Unexpected chapter event"}));return}};function g(l){const u=Re(l.events);if(u){if(Xe(l))return;i.emit(m.interactives,{subjectId:l.id,subjectName:"chapter",type:x.actionChoice,actionType:u.action.type,payload:u.action.args}),t.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:I.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:x.actionExecution,actionType:d?.type??I.expect})},w=({subjectId:l,subjectName:u})=>{e.info.isEnded$.getValue()?t.execEndOfVideo():e.play(),i.emit(m.interactives,{subjectId:l,subjectName:u,type:x.actionExecution,actionType:"after-expect"})},C=({subjectId:l,subjectName:u,subjectType:d,action:y})=>{i.emit(m.interactives,{subjectId:l,subjectName:u,subjectType:d,type:x.actionExecution,actionType:y.type})},A=({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:x.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:x.actionExecution,actionType:y.type})};return{onControlEvent:o,onContainerEvent:a,onChapterEvent:h,onExpectEvent:f,expectEventHandler:w,setManifestChapterEvents:g,setManifestContainerEvents:c,stopExpect:s,state:r}};class W{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=W.#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(",")),W.#c(e)?t:t.capture||!1}}static#s=void 0;static#c(e){let t=W.#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}W.#s=t}return t||!1}}class mi{constructor(){this.bindingMap=new li}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;const s=new W(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 yi{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 gi{lastFrameCanvas;endOffsetMs;currentChapter;currentVideoDurationMs=1/0;rootElement;_containerTimeFrameShouldReceived=!1;_endTimeFrameReceived=!1;_shouldCallSkip=!1;_callbacks;constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
7
7
  position: absolute;
8
8
  top: 0;
9
9
  left: 0;
@@ -11,13 +11,13 @@ import{loadVKLangPack as Ze,Subscription as re,ValueSubject as ee,Observable as
11
11
  height: var(--interactive-height);
12
12
  background-color: var(--black);
13
13
  visibility: hidden;
14
- `,this.lastFrameCanvas=new mi,this.endOffsetMs=t,this._callbacks={onError:n},this.lastFrameCanvas.rootElement.style.cssText=`
14
+ `,this.lastFrameCanvas=new yi,this.endOffsetMs=t,this._callbacks={onError:n},this.lastFrameCanvas.rootElement.style.cssText=`
15
15
  position: absolute;
16
16
  top: 50%;
17
17
  left: 50%;
18
18
  transform: translate(-50%, -50%);
19
- `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);const t=getComputedStyle(this.rootElement),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=e=>{const t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}}function gi(i=0){return new Promise(e=>{setTimeout(()=>{e(0)},i)})}const vi=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,lastFrame:!1,permanentTextControls:!0}),_=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function bi(){const i=document.createElement("div");return i.style.cssText=`
19
+ `,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);const t=getComputedStyle(this.rootElement),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}onEachTick=e=>{const t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}}function vi(i=0){return new Promise(e=>{setTimeout(()=>{e(0)},i)})}const bi=Object.freeze({parentElement:null,fullscreenTargetElement:null,lang:"ru",loaders:{},graph:!1,lastFrame:!1,permanentTextControls:!0}),O=Object.freeze({created:0,initiated:1,ready:2,destroyed:3});function Ci(){const i=document.createElement("div");return i.style.cssText=`
20
20
  position: absolute;
21
21
  top: 0;
22
22
  left: 0;
23
- `,i}class Si{#a=null;#s=null;#c=null;#l=null;#r=null;#o=null;#h=null;#t=null;#d=new ee(!1);#f=new Set;#n=null;#m=null;#i=null;#e=null;state={history$:new ee([]),hasPrevChapter$:new ee(!1)};constructor(e){this.options={...vi,...e},this.#s=[],this.factories=new Map([["choice",Be]]),this.rootElement=bi(),this.options.parentElement.append(this.rootElement),this.#e=new qe,this.#l=new re,this.#c=new fi,this.options.lastFrame&&(this.#i=new yi({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:t=>this.#e.emit(y.errors,new R(R.Severity.RECOVERABLE,R.Category.SEAMLESS,t))})),this.#c.listen(this.rootElement,"mousedown",t=>t.stopPropagation()),this.#c.listen(this.rootElement,"mouseup",t=>t.stopPropagation()),this.#t=new Bt(this.options.loaders,t=>this.#e.emit(y.errors,new R(R.Severity.RECOVERABLE,R.Category.MANIFEST,t))),this.#r=xe(this.options.player),this.#o=new Mt,this.#h=je({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#u}),this.#a=oi(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#i.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#n=new yt({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.#e.emit(y.graph,{type:we.watchAgainClicked,chapterId:t})},onError:t=>this.#e.emit(y.errors,new R(R.Severity.RECOVERABLE,R.Category.LOADERS,{message:t}))})),this.#e.on(y.interactives,t=>{if(t.type===x.actionExecution){if(t.payload?.behaviour==="change-chapter"){const{chapterId:n}=t.payload;this.setChapter({chapterId:n})}if(t.payload?.behaviour==="change-manifest"){const{manifestURL:n}=t.payload;this.setManifest(n)}}}),this.isFirstChapterFetched=!1,this.appState=_.created}emitPlayerChanged=e=>{this.#e.emit(y.playerChanged,e)};async initSeamless({source:e,initialChapter:t,visitedChapters:n=[],videosInfo:r}){this.#m=Ut(this);const s=document.createElement("div");this.#m.on(Z.activePlayerChanged,this.emitPlayerChanged);const{player:o,config:a}=await this.#m.init({source:e,initialChapter:t,container:s});return this.setVisitedChapters(n),this.updateGraphVideosInfo(r),{player:o,config:a}}getStatEvents(){return{click$:new ue(e=>{this.#e.on(y.graph,({type:t,visibility:n})=>{t==="visibility"&&e.next(n?F.OPEN_GRAPH:F.CLOSE_GRAPH),t==="watchAgainClicked"&&e.next(F.WATCH_AGAIN)}),this.#e.on(y.interactives,({type:t,subjectName:n,subjectType:r})=>{t!=="action-choice"||n!=="control"||(r==="Button"&&e.next(F.GO_NEXT_BUTTON),r==="Area"&&e.next(F.GO_NEXT_AREA))})}),nextMovie$:new ue(e=>{this.#e.on(y.playerChanged,({config:t})=>{t?.unitedVideoId&&e.next(t.unitedVideoId)})})}}setPlayer(e){this.#y(),this.options.player=e,B.setPlayer(this.options.player),this.#r?this.#r.setPlayer(this.options.player):this.#r=xe(this.options.player),this.#h=je({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:()=>this.#u(!1)}),this.appState===_.initiated&&(this.#g(),this.#p(this.#t.chapter))}async setManifest(e){this.#y(),this.isFirstChapterFetched=!1;const t=await this.#t.setManifest(e);return this.#n&&await this.#n.handleManifestChange(t.manifest),this.#e.emit(y.manifestChanged,{manifest:t.manifest}),this.#p(this.#t.chapter),t.manifest}setVisitedChapters(e){Array.isArray(e)&&(this.state.history$.next(e),this.#n?.setVisitedChapters(e))}updateGraphVideosInfo(e){Array.isArray(e)&&this.#n?.updateVideosInfo(e)}async setChapter({chapterId:e}={}){this.#y(),this.#i&&this.isFirstChapterFetched&&(this.#i.draw(),this.#i.show()),Ke().browser===Ye.Safari&&await gi(35);const n=await(e?this.#t.setNext(e):this.#t.setInitial()),{chapter:r,media:s,graph:o}=n;return this.#w(r.id),this.#n&&this.#n.handleChapterChange(o),this.#i?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(y.chapterChanged,{chapter:r,media:s,graph:o}),this.#p(this.#t.chapter),this.#f=new Set,this.isFirstChapterFetched=!0,{chapter:r,media:s,graph:o}}toggleGraphView(e=!0){this.#n&&(e?(this.#n.show(),this.#d.next(!1)):(this.#n.hide(),this.#v()),this.#e.emit(y.graph,{type:we.visibility,visibility:e}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.appState===_.created&&(this.#a.resizeObserver.observe(this.options.fullscreenTargetElement),this.#g(),this.appState=_.initiated,this.#p(this.#t.chapter))}#y(){this.appState===_.ready&&(this.#u(),this.#s=[],this.#o.release(),this.#r?.release(),this.appState=_.initiated,this.#d.next(!1))}#S=()=>{this.#o.fns.forEach(n=>n());const e=this.options.player.info.position$.getValue()*1e3,t=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(e));for(const n of t){this.#r.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const r of n.controls)this.#r.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#s.find(r=>r.container.container.id===n.id).reset()}};#b=()=>{this.#a.calc(),this.#o.requestAnimation()};#E(e){(!this.#n||this.#n.isHidden)&&this.#v();const t=e*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>t>=s[1]);if(r){const s=r.range.join("-");this.#f.has(s)||(this.#f.add(s),this.#e.emit(y.interactives,{type:x.rangeEnded,payload:r,visibility:!0}))}}#g(){this.#l.unsubscribe(),this.#l.add(this.options.player.events.started$.pipe(Je()).subscribe(this.#b)).add(this.options.player.events.playing$.subscribe(this.#o.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#o.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#E.bind(this))).add(this.state.history$.subscribe(e=>{this.state.hasPrevChapter$.next(e.length>1)})),this.options.lastFrame&&this.#l.add(this.options.player.info.duration$.subscribe(e=>{this.#i.setVideoDuration(e*1e3)})).add(this.options.player.experimental.element$.subscribe(e=>{e&&this.#i.setVideoElement(e)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#i.reset(),setTimeout(()=>{this.#i.hide(),this.#i.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#i.onSeek))}#u=(e=!0)=>{this.#s.forEach(t=>{!e&&t.isPermanentText||(this.#o.removeFn(t.whilePlaying),t.destroy())})};#p(e){this.#t.chapter&&this.appState===_.initiated&&(this.#h.setManifestChapterEvents(e),this.#s=this.#C(e),this.#r.containersEventsCallState.setData(e.containers),B.setContainers(this.#s.map(t=>t.container.container)),this.options.lastFrame&&this.#o.addFn(()=>{this.#i.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.appState=_.ready)}#C(e){return e?.containers?.reduce((t,n)=>{const r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){const o=new ei({player:this.options.player,container:s(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#h,interactiveEvents:this.#r,globalEventEmitter:this.#e,ignoreContainerEvent:()=>Jt(n,this.#s),permanentTextControls:this.options.permanentTextControls});return this.#o.addFn(o.whilePlaying,!0),[...t,o]}return[...t]},[])??[]}#v(){const e=this.#d.getValue(),t=!!B.getNextInteractiveTime();(t&&!e||!t&&e)&&this.#d.next(!e)}#w(e){if(this.#t.manifest.metadata.initChapterId===e){this.state.history$.next([e]);return}const t=this.state.history$.getValue();t.at(-1)!==e&&this.state.history$.next([...t,e])}playPrevChapter(){const e=this.state.history$.getValue();if(e.length>1){e.pop();const t=e.at(-1);this.state.history$.next(e),this.setChapter({chapterId:t})}}isSupport(e=this.#t.manifest){return He(e.metadata.version)}getIsSeekable(){return this.#d}getInteractiveRanges(){return Yt(this.#t.chapter?.containers)}getNextInteractiveStartTime(e){return B.getNextInteractiveTime(e)}getChapterBranches(e){return this.#t.getBranches(e)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(e,t){this.factories.set(e.trim().toLowerCase(),t)}removeFactory(e){this.factories.delete(e.trim().toLowerCase())}on(...e){return this.#e.on(...e),this}off(...e){return this.#e.off(...e),this}once(...e){return this.#e.once(...e),this}destroy(){this.#u(),this.#s=void 0,this.state=void 0,this.#n?.destroy(),this.#n=void 0,this.#a.release(),this.#a=void 0,this.#h=void 0,this.#o.release(),this.#o=void 0,this.#r.release(),this.#r=void 0,this.#t.release(),this.#h=void 0,this.#c.release(),this.#c=void 0,this.#l.unsubscribe(),this.#l=void 0,this.#e.reset(),this.#e=void 0,this.#i?.destroy(),this.#i=void 0,this.rootElement.remove(),this.rootElement=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.appState=_.destroyed}}const Ii={Container:$e,createChoiceContainer:Be,createAreaControl:ke,createButtonControl:Pe,createRelativeLayout:lt,getRootEl:Le,classnamesPrefix:M},Ti={version:it};export{R as CustomError,y as EVENT_NAMES,F as INTERACTIVE_CLICK_ACTIONS,Si as Interactives,Bt as ManifestController,Ti as SDKInfo,K as compareVersions,He as isSupportedManifest,Ii as utils};
23
+ `,i}class Si{#a=null;#s=null;#c=null;#l=null;#r=null;#o=null;#h=null;#t=null;#d=new P(!1);#f=new Set;#n=null;#m=null;#i=null;#e=null;state={history$:new P([]),hasPrevChapter$:new P(!1),prevChapter$:new P(null),calledByInteractive$:new P(!1),lastChapterChangeWasInitiatedByInteractive$:new P(!1)};constructor(e){this.options={...bi,...e},this.#s=[],this.factories=new Map([["choice",We]]),this.rootElement=Ci(),this.options.parentElement.append(this.rootElement),this.#e=new qe,this.#l=new re,this.#c=new mi,this.options.lastFrame&&(this.#i=new gi({parentElement:this.options.parentElement,interactivesRootElement:this.rootElement,onError:t=>this.#e.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.SEAMLESS,t))})),this.#c.listen(this.rootElement,"mousedown",t=>t.stopPropagation()),this.#c.listen(this.rootElement,"mouseup",t=>t.stopPropagation()),this.#t=new Wt(this.options.loaders,t=>this.#e.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.MANIFEST,t))),this.#r=Ae(this.options.player),this.#o=new Ot,this.#h=Ne({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:this.#u}),this.#a=ci(()=>({player:this.options?.player,parentElement:this.options.parentElement,fns:this.options.lastFrame?[()=>{this.#i.updateCanvasDimensions(!0)}]:[]})),this.options.graph&&(this.#n=new vt({root:this.options.parentElement,lang:this.options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.#e.emit(m.graph,{type:Se.watchAgainClicked,chapterId:t})},onError:t=>this.#e.emit(m.errors,new R(R.Severity.RECOVERABLE,R.Category.LOADERS,{message:t}))})),this.#e.on(m.interactives,t=>{if(t.type===x.actionExecution){if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),t.payload?.behaviour==="change-chapter"){const{chapterId:n}=t.payload;this.setChapter({chapterId:n})}if(t.payload?.behaviour==="change-manifest"){const{manifestURL:n}=t.payload;this.setManifest(n)}}}),this.#e.on(m.manifestChanged,()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}),this.isFirstChapterFetched=!1,this.appState=O.created}emitPlayerChanged=e=>{this.#e.emit(m.playerChanged,e)};async initSeamless({source:e,initialChapter:t,visitedChapters:n=[],videosInfo:r}){this.#m=Ht(this);const s=document.createElement("div");this.#m.on(K.activePlayerChanged,this.emitPlayerChanged);const{player:o,config:a}=await this.#m.init({source:e,initialChapter:t,container:s});return this.setVisitedChapters(n),this.updateGraphVideosInfo(r),{player:o,config:a}}getStatEvents(){return{click$:new fe(e=>{this.#e.on(m.graph,({type:t,visibility:n})=>{t==="visibility"&&e.next(n?F.OPEN_GRAPH:F.CLOSE_GRAPH),t==="watchAgainClicked"&&e.next(F.WATCH_AGAIN)}),this.#e.on(m.interactives,({type:t,subjectName:n,subjectType:r})=>{t!=="action-choice"||n!=="control"||(r==="Button"&&e.next(F.GO_NEXT_BUTTON),r==="Area"&&e.next(F.GO_NEXT_AREA))})}),nextMovie$:new fe(e=>{this.#e.on(m.playerChanged,({config:t})=>{t?.unitedVideoId&&e.next(t.unitedVideoId)})})}}setPlayer(e){this.#y(),this.options.player=e,D.setPlayer(this.options.player),this.#r?this.#r.setPlayer(this.options.player):this.#r=Ae(this.options.player),this.#h=Ne({player:this.options.player,interactiveEvents:this.#r,globalEventEmitter:this.#e,removeControllers:()=>this.#u(!1)}),this.appState===O.initiated&&(this.#g(),this.#p(this.#t.chapter))}async setManifest(e){this.#y(),this.isFirstChapterFetched=!1;const t=await this.#t.setManifest(e);return this.#n&&await this.#n.handleManifestChange(t.manifest),this.#e.emit(m.manifestChanged,{manifest:t.manifest}),this.#p(this.#t.chapter),t.manifest}setVisitedChapters(e){Array.isArray(e)&&(this.state.history$.next(e),this.#n?.setVisitedChapters(e))}updateGraphVideosInfo(e){Array.isArray(e)&&this.#n?.updateVideosInfo(e)}async setChapter({chapterId:e}={}){this.#y(),this.#i&&this.isFirstChapterFetched&&(this.#i.draw(),this.#i.show()),Je().browser===et.Safari&&await vi(35);const n=await(e?this.#t.setNext(e):this.#t.setInitial()),{chapter:r,media:s,graph:o}=n;return this.#I(r.id),this.#n&&this.#n.handleChapterChange(o),this.#i?.setCurrentChapter(this.getCurrentChapter().chapter),this.#e.emit(m.chapterChanged,{chapter:r,media:s,graph:o}),this.#p(this.#t.chapter),this.#f=new Set,this.isFirstChapterFetched=!0,{chapter:r,media:s,graph:o}}toggleGraphView(e=!0){this.#n&&(e?(this.#n.show(),this.#d.next(!1)):(this.#n.hide(),this.#v()),this.#e.emit(m.graph,{type:Se.visibility,visibility:e}))}init(){this.#t.chapter&&this.options.parentElement&&this.options.player&&this.options.fullscreenTargetElement&&this.appState===O.created&&(this.#a.resizeObserver.observe(this.options.fullscreenTargetElement),this.#g(),this.appState=O.initiated,this.#p(this.#t.chapter))}#y(){this.appState===O.ready&&(this.#u(),this.#s=[],this.#o.release(),this.#r?.release(),this.appState=O.initiated,this.#d.next(!1))}#S=()=>{this.#o.fns.forEach(n=>n());const e=this.options.player.info.position$.getValue()*1e3,t=(this.#t.chapter.containers||[]).filter(n=>n.startTime>=Math.floor(e));for(const n of t){this.#r.remove({timestamp:1/0,priority:"container",initiator:n.id});for(const r of n.controls)this.#r.remove({timestamp:1/0,priority:"control",initiator:r.id});this.#s.find(r=>r.container.container.id===n.id).reset()}};#b=()=>{this.#a.calc(),this.#o.requestAnimation()};#C(e){(!this.#n||this.#n.isHidden)&&this.#v();const t=e*1e3,r=this.getInteractiveRanges().findLast(({range:s})=>t>=s[1]);if(r){const s=r.range.join("-");this.#f.has(s)||(this.#f.add(s),this.#e.emit(m.interactives,{type:x.rangeEnded,payload:r,visibility:!0}))}}#g(){this.#l.unsubscribe(),this.#l.add(this.options.player.events.started$.pipe(tt()).subscribe(this.#b)).add(this.options.player.events.playing$.subscribe(this.#o.requestAnimation)).add(this.options.player.events.willPause$.subscribe(this.#o.cancelAnimation)).add(this.options.player.info.position$.subscribe(this.#C.bind(this))).add(this.state.history$.subscribe(e=>{this.state.hasPrevChapter$.next(e.length>1)})).add(this.#t.prevChapter$.subscribe(e=>this.state.prevChapter$.next(e))),this.options.lastFrame&&this.#l.add(this.options.player.info.duration$.subscribe(e=>{this.#i.setVideoDuration(e*1e3)})).add(this.options.player.experimental.element$.subscribe(e=>{e&&this.#i.setVideoElement(e)})).add(this.options.player.events.firstFrame$.subscribe(()=>{this.#i.reset(),setTimeout(()=>{this.#i.hide(),this.#i.lastFrameCanvas.clear()},50)})).add(this.options.player.events.seeked$.subscribe(this.#i.onSeek))}#u=(e=!0)=>{this.#s.forEach(t=>{!e&&t.isPermanentText||(this.#o.removeFn(t.whilePlaying),t.destroy())})};#p(e){this.#t.chapter&&this.appState===O.initiated&&(this.#h.setManifestChapterEvents(e),this.#s=this.#E(e),this.#r.containersEventsCallState.setData(e.containers),D.setContainers(this.#s.map(t=>t.container.container).filter(t=>!Ze(t.controls))),this.options.lastFrame&&this.#o.addFn(()=>{this.#i.onEachTick(this.options.player.info.position$.getValue()*1e3)},!0),this.appState=O.ready)}#E(e){return e?.containers?.reduce((t,n)=>{const r=n.type.trim().toLowerCase(),s=this.factories.get(r);if(s){const o=new ti({player:this.options.player,container:s(n,this.rootElement),branches:this.#t.chapter.branches,selectBranches:this.#h,interactiveEvents:this.#r,globalEventEmitter:this.#e,ignoreContainerEvent:()=>ei(n,this.#s),permanentTextControls:this.options.permanentTextControls});return this.#o.addFn(o.whilePlaying,!0),[...t,o]}return[...t]},[])??[]}#v(){const e=this.#d.getValue(),t=!!D.getNextInteractiveTime();(t&&!e||!t&&e)&&this.#d.next(!e)}#w(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}#I(e){this.#w();const t=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),n=this.state.prevChapter$.getValue(),r=(n&&Xe(n)&&Xt(n))??!1;if(this.#t.manifest.metadata.initChapterId===e||r&&t){this.state.history$.next([e]);return}const o=this.state.history$.getValue();o.at(-1)!==e&&this.state.history$.next([...o,e])}playPrevChapter(){const e=this.state.history$.getValue();if(e.length>1){e.pop();const t=e.at(-1);this.state.history$.next(e),this.setChapter({chapterId:t})}}isSupport(e=this.#t.manifest){return He(e.metadata.version)}getIsSeekable(){return this.#d}getInteractiveRanges(){return Jt(this.#t.chapter?.containers)}getNextInteractiveStartTime(e){return D.getNextInteractiveTime(e)}getChapterBranches(e){return this.#t.getBranches(e)}getCurrentChapter(){return this.#t.getCurrent()}getCurrentManifest(){return this.#t.manifest}addFactory(e,t){this.factories.set(e.trim().toLowerCase(),t)}removeFactory(e){this.factories.delete(e.trim().toLowerCase())}on(...e){return this.#e.on(...e),this}off(...e){return this.#e.off(...e),this}once(...e){return this.#e.once(...e),this}destroy(){this.#u(),this.#s=void 0,this.state=void 0,this.#n?.destroy(),this.#n=void 0,this.#a.release(),this.#a=void 0,this.#h=void 0,this.#o.release(),this.#o=void 0,this.#r.release(),this.#r=void 0,this.#t.release(),this.#h=void 0,this.#c.release(),this.#c=void 0,this.#l.unsubscribe(),this.#l=void 0,this.#e.reset(),this.#e=void 0,this.#i?.destroy(),this.#i=void 0,this.rootElement.remove(),this.rootElement=void 0,this.factories=void 0,this.options=void 0,this.isFirstChapterFetched=!1,this.appState=O.destroyed}}const Ti={Container:De,createChoiceContainer:We,createAreaControl:Pe,createButtonControl:Fe,createRelativeLayout:dt,getRootEl:Ve,classnamesPrefix:M},xi={version:st};export{R as CustomError,m as EVENT_NAMES,F as INTERACTIVE_CLICK_ACTIONS,Si as Interactives,Wt as ManifestController,xi as SDKInfo,Y as compareVersions,He as isSupportedManifest,Ti as utils};
package/index.d.ts CHANGED
@@ -64,6 +64,9 @@ declare class Interactives {
64
64
  state: {
65
65
  history$: ValueSubject<never[]>;
66
66
  hasPrevChapter$: ValueSubject<boolean>;
67
+ prevChapter$: ValueSubject<null>;
68
+ calledByInteractive$: ValueSubject<boolean>;
69
+ lastChapterChangeWasInitiatedByInteractive$: ValueSubject<boolean>;
67
70
  };
68
71
  options: any;
69
72
  factories: Map<string, (container: any, rootElement: any) => ChoiceContainer | undefined>;
@@ -202,6 +205,7 @@ declare class Loadable implements ILoadable {
202
205
  declare class ManifestController extends Loadable {
203
206
  constructor(loaders: any, onError: any);
204
207
  onError: any;
208
+ prevChapter$: ValueSubject<null>;
205
209
  release(): this;
206
210
  manifest: any;
207
211
  chapter: any;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vkontakte/videoplayer-interactive",
3
- "version": "1.0.7-dev.200de7b.0",
3
+ "version": "1.0.7-dev.6e70b297.0",
4
4
  "author": "vk.com",
5
5
  "description": "Movika interactive SDK",
6
6
  "homepage": "https://vk.com",
@@ -41,20 +41,17 @@
41
41
  "./es2018.esm.js": "./es2018.esm.js",
42
42
  "./es2018.cjs.js": "./es2018.cjs.js",
43
43
  "./es2015.esm.js": "./es2015.esm.js",
44
- "./es2015.cjs.js": "./es2015.cjs.js",
45
- "./es2015.umd.js": "./es2015.umd.js",
46
- "./es5.umd.js": "./es5.umd.js"
44
+ "./es2015.cjs.js": "./es2015.cjs.js"
47
45
  },
48
46
  "files": [
49
47
  "*.cjs.js",
50
48
  "*.esm.js",
51
- "**/*.d.ts",
52
- "*.umd.js"
49
+ "**/*.d.ts"
53
50
  ],
54
51
  "dependencies": {
55
52
  "@interactiveplatform/movika-graph-editor": "^1.11.0",
56
- "@vkontakte/videoplayer-core": "^2.0.97",
57
- "@vkontakte/videoplayer-shared": "1.0.32-dev.5a93139a.0",
53
+ "@vkontakte/videoplayer-core": "2.0.98-dev.1707cd0.0",
54
+ "@vkontakte/videoplayer-shared": "1.0.32-dev.7bf5a18e.0",
58
55
  "uuid": "^9.0.0"
59
56
  }
60
57
  }