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