@vkontakte/videoplayer-interactive 1.0.30-dev.9aa27113.0 → 1.0.30-dev.b736679d.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 +233 -5
- package/es2015.esm.js +234 -6
- package/es2018.cjs.js +234 -6
- package/es2018.esm.js +233 -5
- package/esnext.cjs.js +234 -6
- package/esnext.esm.js +234 -6
- package/evergreen.esm.js +234 -6
- package/package.json +4 -4
- package/types/modules/Interactives/Interactives.d.ts +19 -8
- package/types/modules/Interactives/Layout.d.ts +4 -0
- package/types/modules/Interactives/containers/ChoiceContainer.d.ts +16 -6
- package/types/modules/Interactives/containers/Container.d.ts +9 -6
- package/types/modules/Interactives/controls/AreaControl.d.ts +22 -2
- package/types/modules/Interactives/controls/ButtonControl.d.ts +27 -2
- package/types/modules/Interactives/controls/Control.d.ts +22 -9
- package/types/modules/Interactives/controls/types.d.ts +21 -7
- package/types/modules/Interactives/index.d.ts +69 -4
- package/types/modules/Interactives/styles.d.ts +1 -0
- package/types/modules/Interactives/types.d.ts +12 -4
- package/types/modules/Interactives/utils/BlinkAnimationReference.d.ts +2 -0
- package/types/modules/Interactives/utils/FillAnimation.d.ts +30 -0
- package/types/modules/Interactives/utils/GameController.d.ts +14 -6
- package/types/modules/Interactives/utils/InteractiveEvents.d.ts +2 -2
- package/types/modules/Interactives/utils/SelectBranches.d.ts +2 -1
- package/types/modules/Interactives/utils/SelectBranches.types.d.ts +1 -0
- package/types/modules/Interactives/utils/TapElement.d.ts +10 -0
- package/types/modules/Interactives/utils/events.types.d.ts +3 -1
- package/types/modules/Interactives/utils/renderingUtils.d.ts +15 -3
- package/types/utils/AverageColor/FrameAverageColor.d.ts +19 -0
- package/types/utils/AverageColor/helpers.d.ts +17 -0
- package/types/utils/AverageColor/index.d.ts +2 -0
- package/types/utils/getVideoContentSize.d.ts +1 -1
- package/types/utils/Binding.d.ts +0 -34
- package/types/utils/EventManager.d.ts +0 -13
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-interactive v1.0.30-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-interactive v1.0.30-dev.b736679d.0
|
|
3
|
+
* Sat, 01 Feb 2025 17:10:24 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-30/doc/
|
|
5
5
|
*/
|
|
6
|
-
var ut="1.0.30-dev.9aa27113.0";function Ge(i,e=1){let t="0",n="0",r="0";return i.length===4?(t="0x"+i[1]+i[1],n="0x"+i[2]+i[2],r="0x"+i[3]+i[3]):i.length===7&&(t="0x"+i[1]+i[2],n="0x"+i[3]+i[4],r="0x"+i[5]+i[6]),`rgba(${+t},${+n},${+r},${e})`}var P="interactive",Yt="interactive-controls-container",he=()=>document.querySelector(`.${Yt}`),dt=.4,k={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},mt=(n=>(n.top="flex-start",n.bottom="flex-end",n.center="center",n))(mt||{}),ft=(n=>(n.start="flex-start",n.end="flex-end",n.center="center",n))(ft||{}),yt=(n=>(n.start="left",n.end="right",n.center="center",n))(yt||{}),ue=({target:i,props:e})=>{i.style.alignItems=(e?.gravityVertical&&mt[e.gravityVertical])??"center",i.style.justifyContent=(e?.gravityHorizontal&&ft[e.gravityHorizontal])??"center",i.style.textAlign=(e?.alignment&&yt[e.alignment])??"left"},de=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.color=e?.text?.color??t.textColor,i.style.fontSize=`calc(${n.height} * ${e?.text?.size??t.textSize})`,i.textContent=e?.text?.value??t.textContent},me=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Ge(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},fe=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Ge(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},X=({target:i,layoutParams:e,fallback:t})=>{let n=e.angle??t.angle;n=n&&n*-1,i.style.transform=`rotate(${n}rad)`};var H=class{constructor(e){this.control=e;this.container=null;this.controlElement=null;this.clickListener=null}createContainerElement(e){let t=document.createElement("div");t.classList.add(`${P}-control-container-${this.control.id}`),e(t,this.control.layoutParams);let n=(this.control.layoutParams.innerSizesDependOn??k.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};this.container={element:t,dimensions:n}}createClickListener(e){return t=>{t.stopPropagation(),e()}}setEvents(e){!this.container||!this.control.events||this.control.events.forEach(t=>{switch(t.type.trim().toLowerCase()){case"onclick":this.clickListener=this.createClickListener(()=>e({action:t.action,controlId:this.control.id,controlType:this.control.type})),this.container?.element.addEventListener("click",this.clickListener);break;default:break}})}removeListeners(){this.container?.element&&this.clickListener&&this.container?.element.removeEventListener("click",this.clickListener)}};var Ue="int",U=(n=>(n.AREA=`${Ue}_area`,n.TEXT=`${Ue}_text`,n.BUTTON=`${Ue}_bttn`,n))(U||{});var ye=i=>{if(i.type.trim().toLowerCase()==="area")return new ze(i)},ze=class extends H{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("button");n.type="button",n.classList.add(`${P}-${this.control.id}`),n.setAttribute("data-testid",U.AREA),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",me({target:n,props:this.control.props,fallback:{...k,backgroundColor:"transparent"}}),fe({target:n,props:this.control.props,fallback:{...k,borderAlpha:0},dependsOn:this.container.dimensions}),X({target:n,layoutParams:this.control.layoutParams,fallback:k}),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}disable(){this.controlElement&&(this.controlElement.style.cursor="default")}enable(){this.controlElement&&(this.controlElement.style.cursor="pointer")}getElement(){return this.controlElement}};var ve=()=>{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 ge=i=>{if(i.type.trim().toLowerCase()==="button")return new We(i)},We=class extends H{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("button");n.type="button",n.classList.add(`${P}-${this.control.id}`),n.setAttribute("data-testid",U.BUTTON),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",n.style.fontFamily="inherit",X({target:n,layoutParams:this.control.layoutParams,fallback:k}),me({target:n,props:this.control.props,fallback:k}),fe({target:n,props:this.control.props,fallback:k,dependsOn:this.container.dimensions}),ue({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ve();de({target:r,props:this.control.props,fallback:k,dependsOn:this.container.dimensions}),n.append(r),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}disable(){this.controlElement&&(this.controlElement.style.cursor="default")}enable(){this.controlElement&&(this.controlElement.style.cursor="pointer")}getElement(){return this.controlElement}};var vt=i=>{if(i.type.trim().toLowerCase()==="text")return new Qe(i)},Qe=class extends H{constructor(e){super(e)}createView({parentElement:e,layoutCallback:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("div");n.classList.add(`${P}-${this.control.id}`),n.setAttribute("data-testid",U.TEXT),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.fontFamily="inherit",X({target:n,layoutParams:this.control.layoutParams,fallback:k}),ue({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ve();de({target:r,props:this.control.props,fallback:k,dependsOn:this.container.dimensions}),n.append(r),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}disable(){}enable(){}getElement(){return this.controlElement}};var Ke=class{constructor(e){this.layout=e}},Ce=class extends Ke{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}};var Z=class{constructor(e){this.container=e,this.factories=new Map,this.controls=[],this.setControls()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.setControls()}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.setControls()}setControls(){this.controls=this.chooseControls()}chooseControls(){return this.container.controls?.reduce((e,t)=>{let n=t.type.trim().toLowerCase(),r=this.factories.get(n);if(r){let s=r(t);if(s)return[...e,s]}return[...e]},[])||[]}};var be=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new Xe(i,e)},Xe=class extends Z{constructor(e,t){super(e),this.rootElement=t??he(),this.layout=new Ce(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",ge),this.addControlFactory("text",vt),this.addControlFactory("area",ye)}createView(e){let t=document.createElement("div");return t.classList.add(`${P}-${this.container.id}`),this.layout.setContainerLayout(t),this.controls.forEach(n=>{n.createView({parentElement:t,layoutCallback:this.layout.setControlLayout}),n.setEvents(e)}),this.rootElement.append(t),this.isRemoved=!1,t}hide(){let e=this.getElement();e&&(e.style.visibility="hidden")}show(){let e=this.getElement();e&&(e.style.visibility="visible")}enable(){let e=this.getElement();e&&(this.controls.forEach(t=>t.enable()),e.style.opacity="1",this.isDisabled=!1)}disable(){let e=this.getElement();e&&(this.controls.forEach(t=>t.disable()),e.style.opacity=`${dt}`,this.isDisabled=!0)}removeView(){this.isRemoved||(this.controls.forEach(e=>e.removeListeners()),this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${P}-${this.container.id}`)}};import{clientChecker as xn,combine as Sn,InterfaceLanguage as wn,Observable as Zt,once as An,Subject as $,Subscription as pt,ValueSubject as L}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as pe}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as Jt}from"@vkontakte/videoplayer-shared/evergreen";function J(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}var z=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,ee=i=>z(i,"Object"),Ee=i=>z(i,"String"),Ie=i=>z(i,"Array"),Te=i=>z(i,"Number"),gt=i=>z(i,"Function");var Ze=i=>Te(i)&&!isNaN(i);var W=i=>ee(i)&&Object.keys(i).length===0,qe=i=>Ie(i)&&!i.length;var te=(i,e)=>Ee(i)&&(e?i.trim():i).length;var Ct="video_interactive",bt="videoint";var Et=250,ne=class{constructor(e){this.handleZoomChange=J(e=>{this.lastZoomInfo=e},Et);this.onResize=e=>{if(!this.isReady||this.isHidden||!e[0].contentRect.width||!e[0].contentRect.height)return;let t=this.getNextPoint();t&&this.ngEditor?.zoomTo(t),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}};this.handleChapterChange=e=>{if(this.manifest){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor?.selectChapter(e.id),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=null}};this.handleManifestChange=(e,t=[])=>{if(this.isReady=!1,!Te(e.graph.edit.chapters[0].x)){this.onError?.("Can't show graph"),console.error("Can't show graph");return}this.lastZoomInfo=null,this.manifest=e,this.visitedChapterIds=new Set(t),this.ngEditor&&(this.manifest.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=this.manifest.metadata.id):this.ngEditor.setVisitedChapters(Array.from(t)),this.isReady=!0)};this.init(e)}init({root:e,onOpenPreviewClick:t,onError:n,lang:r,visitedChapters:s=[]}){this.isReady=!1,this.isHidden=!0,this.manifest=null,this.visitedChapterIds=new Set(s),this.onOpenPreviewClick=t,this.onError=n,this.lang=r??"ru",this.zoom=.7,this.lastZoomInfo=null,this.currentManifestId=null,this.currentChapterId=null,this.ngEditor=null,this.ngEditorSize=null,this.graphWrapperElement=en(e),this.resizeObserver=new ResizeObserver(J(this.onResize,Et)),this.resizeObserver.observe(this.graphWrapperElement)}getNextPoint(e=this.ngEditorSize){return!this.lastZoomInfo||!e?null:[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor?.updateVideosInfo(e)}async show(){this.manifest&&(this.ngEditor||await this.initNgEditor(),this.graphWrapperElement.style.display="block",!this.lastZoomInfo&&this.currentChapterId&&this.ngEditor?.focusChapter(this.currentChapterId),this.isHidden=!1)}async initNgEditor(){if(!this.manifest)return;let e;try{e=await Jt(this.lang,Ct,bt)}catch{console.log("Unable to load graph language pack")}let{GraphEditor:t}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new t(this.graphWrapperElement,{mode:"read",lang:this.lang==="ru"?"ru":"en",translation:e}),this.currentManifestId=this.manifest.metadata.id,this.ngEditor.update(this.manifest),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId&&this.ngEditor.selectChapter(this.currentChapterId),this.ngEditor.on("control",({name:n,...r})=>{n==="openPreview"&&"chapterId"in r&&this.onOpenPreviewClick?.(r.chapterId)}),this.ngEditor.on("zoom",this.handleZoomChange),this.isReady=!0}hide(){this.graphWrapperElement.style.display="none",this.isHidden=!0}destroy(){this.hide(),this.manifest=null,this.resizeObserver.disconnect(),this.ngEditor?.setVisitedChapters([]),this.onOpenPreviewClick=void 0,this.ngEditor?.dispose(),this.graphWrapperElement.remove(),this.isReady=!1}};function en(i){let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",i.append(e),e}var ie=class{constructor(){this._containers=[];this._player=null;this.setPlayer=e=>{this._player=e};this.setContainers=e=>{this._containers=e};this.deleteContainer=e=>{this._containers=this._containers.filter(t=>t.id!==e)};this.getNextInteractiveTime=(e=3e3)=>{if(!this._containers.length||this._player===null)return null;let t=-1,n=!1,r=Math.round(this._player.info.position$.getValue()*1e3);for(let s of this._containers){let c=s.startTime-e;if(c<=r&&(s.endTime&&r<=s.endTime||s.endTime===null)){n=!0;break}r<c&&(t=t===-1?c:Math.min(t,c))}return!n&&t!==-1?t:null}}};import{isSupportedManifest as Se,ContainerTypes as _i,ControlTypes as we,EventActionTypes as I,EventTypes as Hi,migrateManifestToLatestVersion as xt,compareVersions as Di}from"@interactiveplatform/movika-manifest";var It={metadata:"Object",chapters:"Array"},Tt=i=>{if(!ee(i))return!1;for(let e in It)if(!i[e]||!z(i[e],It[e]))return!1;return Se(i.metadata.version)},xe=i=>i.type===we.Text,Vi=i=>i.type===we.Button,Pi=i=>i.type===we.Area,$i={Choice:"Choice",TextInput:"TextInput"},Li={Button:"Button",Area:"Area",Text:"Text"},Ni={onClick:"onClick",onSuspense:"onSuspense"},Oi={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var M=class{constructor(e,t,...n){this.severity=e;this.category=t;this.data=n}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var Ae=class{constructor(){this.listeners={}}addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];let n=()=>{t(),this.off(e,n)};return this.listeners[e].push(n),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){let n=this.listeners[e]||[];for(let r=n.length;r>0;r--)if(n[r]===t){n.splice(r,1);break}return this}emit(e,...t){let n=this.listeners[e];return n?(n.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return this.rawListeners(e).length}rawListeners(e){return this.listeners[e]||[]}};var Re=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{gt(e)&&(this.fns.push(e),t&&this.updateFn())};this.removeFn=(e,t=!1)=>{this.fns=this.fns.filter(n=>n!==e),t&&this.updateFn()};this.updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};this.forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};this.requestAnimation=()=>{this.raf||this.forceRequestAnimation()};this.cancelAnimation=()=>{this.raf&&(cancelAnimationFrame(this.raf),this.raf=void 0)};e&&(this.fn=e,this.addFn(e))}release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}};import{ValueSubject as ln}from"@vkontakte/videoplayer-shared/evergreen";var Me=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return tn(...this.loaders[e])(t)}};function tn(...i){return async function(t){let n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function re(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function ke({actions:i,errors:e,chapterId:t,...n}){if(t){let r=i.getManifest(),s=i.getChapter(r.chapters,t);if(s){let c=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return c?{...n,actions:i,errors:e,result:{chapter:s,media:c,graph:a}}:{...n,errors:re(e,ke.name,"Could not find media"),actions:i}}}return{...n,errors:re(e,ke.name,"Could not find chapter"),actions:i}}var Ye=(i="",e="")=>{let t=i.split("."),n=e.split("."),r=0;for(let s=0;s<Math.max(t.length,n.length)&&!r;s++)t[s]>n[s]?r=1:t[s]<n[s]?r=-1:r=0;return r};var nn=async i=>{try{let e={},t;if(Ee(i)){t=new URL(i).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(ee(i))e=i;else return{};if(!Tt(e))return{};let n=e.metadata.media;if(Ee(n)&&!("media"in e))try{let r;t?r=new URL(n,t).href:(r=new URL(n).href,t=r);let s=await fetch(r);if(!s.ok)throw new Error;e.metadata.media=await s.json()}catch{return an(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function St(i){let{manifest:e,manifestURL:t}=await nn(i);if(!e)throw new Error("Failed on fetch");let n=xt(e);return n.media=rn(n.media,t),delete n.metadata.media,n}function Ve(i,e){if(e)return i.find(t=>t.id===e)}function Je(i,e){return i.edit?.chapters?i.edit.chapters.find(t=>t.id===e):i.view?.chapters?i.view.chapters.find(t=>t.id===e):void 0}function et(i,e){return i.videos.find(t=>t.id===e)}function rn(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{let r="url"in n?n.url:"",s=sn(r,e);return{...n,url:s||r}})}))}}function sn(i="",e){try{return new URL(i,e).href}catch{return""}}function an(i){return Ye(i,"3.2.0")>=0}var Pe=i=>Ie(i)&&!qe(i),F=i=>i.order==="end",$e=i=>Ie(i.containers)&&!qe(i.containers)&&F(i),wt=(i,e)=>{let t=i*1e3;return Pe(e.controls)&&t<(e.startTime??0)},tt=(i,e)=>{let t=i*1e3;return Pe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var Q=(i=[])=>i.some(e=>e.action.type==="expect"),nt=(i=[])=>i.find(e=>e.action.type==="expect"),on=i=>i?.length===1,q=i=>on(i)&&xe(i[0]);function At(i,...e){return t=>typeof e[0]=="object"&&typeof t=="object"?i({...e[0],...t}):i(...e,...t)}var Rt=(i,e)=>Q(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&Q(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);var Y=class extends Me{constructor(t,n){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new ln(null);this.onError=n,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(t){this.release();let n=await this.exec("manifestLoaders",{actions:{addErrorMessage:re},result:null,errors:null,source:t});return n.errors&&this.errorHandler(n.errors),this.manifest=await St(n.result??t),this}async setInitial(){return this.setNext()}async setNext(t=this.manifest?.metadata.initChapterId){if(!t)return this;this.prevChapter$.next(this.chapter);let n=await this.exec("chapterLoaders",ke({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Je,getChapter:Ve,getMedia:et,getByBranches:this.getByBranches.bind(this),addErrorMessage:re},result:null,errors:null,chapterId:t}));return n.errors&&this.errorHandler(n.errors),this.chapter=n.result.chapter,this.media=n.result.media,this.graph=n.result.graph,this}errorHandler(t){this.onError(t),console.error("Something went wrong with loaders",{errors:t})}getInitial(){return this.getByChapterId(this.manifest?.metadata.initChapterId)||null}getByChapterId(t=this.manifest?.metadata.initChapterId){if(!t||!this.manifest)return null;let n=Ve(this.manifest.chapters,t);if(n){let r=et(this.manifest.media,n.videoId),s=Je(this.manifest.graph,n.id);if(r)return{chapter:n,media:r,graph:s}}return null}getBranches(t=this.chapter?.id){if(t===this.chapter?.id)return this.getByBranches(this.chapter?.branches);{let n=Ve(this.manifest?.chapters||[],t);return this.getByBranches(n?.branches)}}getByBranches(t=[]){return t.reduce((n,r)=>{let s=this.getByChapterId(r.chapterId);return s&&n.push(s),n},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter?.id===this.manifest?.metadata.initChapterId}isEndChapter(){return this.chapter?F(this.chapter):!1}};import{Player as cn}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as st,Tracer as pn,ValueSubject as hn}from"@vkontakte/videoplayer-shared/evergreen";var Mt=i=>{let e=i.variants.find(t=>t.payload?.type==="vk");if(e&&e.payload){let[t,n]=e.payload.id.split("_");return[t,n]}return[]};function it(){let i=new Map;function e({listId:s=Math.random().toString(),itemId:c=Math.random().toString(),...a}){let o=i.get(s),h={...a};return o?o[c]=h:i.set(s,{[c]:h}),{listId:s,itemId:c,...a}}function t(s){s.player.destroy(),s.container.remove(),s.subscription.unsubscribe(),s.statistics?.oneStat.destroy(),s.statistics?.statSubscription.unsubscribe()}function n(s,c){let a=i.get(s);if(!a)throw Error("Can't remove. Not find.");if(c){let o=a[c];o&&t(o),delete a[c],Object.keys(a).length||i.delete(s)}else{for(let o of Object.values(a))t(o);i.delete(s)}}function r(){for(let s of i)n(s[0])}return{createPlayer:e,removePlayer:n,map:i,removeAll:r}}function rt(i,e=[]){let t={},n,r=!e.length;for(let s of i.variants)if(!n&&"cover"in s&&(n=s.cover),"url"in s)switch(s.type.toLowerCase()){case"mp4":(r||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[s.standard??"Invariant quality"]:s.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:s.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:s.url}});break;default:break}return{sources:t,thumbUrl:n,title:i.title??""}}var se=(i,e)=>{let t=i.info.currentQuality$.getValue(),n=i.info.availableQualities$.getValue();t!==e&&n.includes(e)&&(i.setQuality(e),i.setAutoQuality(!1))};var un=2;function at(i){let e=it(),t=new st,n={},r=null,s=!1,c,a=new hn(null);i&&o(i);function o(C){r=C}function h(C,R,y){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let p=(e.map.get(C)??{})[R];if(p){n={chapterId:y,listId:C,itemId:R,...p};let u=n.player;n.subscription.add(u.info.currentQuality$.subscribe(d=>{let m=u.info.position$.getValue(),A=u.info.isAutoQualityEnabled$.getValue();if(!(!d||!m||A))for(let E of e.map)Object.values(E[1]).forEach(({player:v})=>{se(v,d)})})).add(u.events.started$.subscribe(()=>{g(R)})),p.container.remove(),r.setPlayer(p.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 g(C){if(!r)throw Error("need to set interactive controller");if(W(n)||C!==n.itemId)return;let R=r.getChapterBranches(),y=new Set;for(let l of R)y.has(l.media.id)||(await S({media:l.media,chapterId:l.chapter.id,setAsActive:!1,title:l.chapter.label}),y.add(l.media.id))}async function T({chapter:{id:C},manifestVideo:R}){if(W(n)||!r)return;let y=n.player.info.muted$.getValue(),l=n.player.info.currentQuality$.getValue(),p=n.player.info.isAutoQualityEnabled$.getValue(),u=n.player.info.volume$.getValue(),d=n.player.info.currentPlaybackRate$.getValue(),m=!p,A=!1;for(let E of e.map)if(E[0]===R.id&&!r.state.isReplay$.getValue()){let v=Object.keys(E[1]);for(let b of v)b===n.itemId?(v.length<un||(A=!0),e.removePlayer(E[0],b)):(A=!0,h(E[0],b,C),m?se(n.player,l):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(y),n.player.setPlaybackRate(d))}else e.removePlayer(E[0]);A||(await S({media:R,chapterId:C,setAsActive:!0,playbackRate:d}),m?se(n.player,l):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(y))}async function S({media:C,chapterId:R,prefetch:y=!0,setAsActive:l=!0,autoplay:p=!1,preferredExt:u,title:d,playbackRate:m}){let A=Math.random().toString(),E=document.createElement("div");c.append(E);let v;if(r?.options?.vkVideoLoader){let K=Mt(C);K.length&&(v=await r.options.vkVideoLoader(...K))}let b=r?.options?.coreConfig||void 0,B={...b,configName:[...b?.configName??[],"interactive"]},_={container:E,...v?.videos?.[0]||{sources:rt(C,u).sources},title:d,failoverHosts:v?.failoverHosts||[]},V=new cn(B,pn.createRootTracer());V.initVideo(_);let O=null;if(v?.videos&&r?.options.createOneStat){let K=v.videos[0],De=r.options.createOneStat(K),ht=new st;De&&(ht.add(De.attachTo(V)),O={oneStat:De,statSubscription:ht})}let G=new st,He=n?.player?.info.isAutoQualityEnabled$.getValue();G.add(V.events.canplay$.subscribe(function(){He||se(V,n.player.info.currentQuality$.getValue()),m&&V.setPlaybackRate(m)}));let j=e.createPlayer({listId:C.id,itemId:A,player:V,container:E,sources:rt(C,u).sources,config:_,subscription:G,statistics:O});return l&&h(C.id,j.itemId,R),p&&j.player.play(),y&&!p&&j.player.prepare(),{player:j.player,config:j.config,statistics:j.statistics}}function x(){N(),r=null,c.remove()}function N(){t.unsubscribe(),e.removeAll(),n={},s=!1}async function D(){if(!r)throw Error("need to set interactive controller");N(),c=document.createElement("div");let{media:C,chapter:R}=r.getCurrentChapter();C&&R?(t.add(r.events.chapterChanged$.subscribe(T)),await S({media:C,chapterId:R.id,title:R.label})):console.error("not found")}return{...e,init:D,setInteractiveController:o,createPlayer:S,removeAll:x,getActivePlayer:function(){return n},activePlayerChanged:a}}var f={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},ae={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},w={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as dn}from"@vkontakte/videoplayer-shared/evergreen";var Le=class{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEvents:c,globalEventEmitter:a,ignoreContainerEvent:o,permanentTextControls:h,disabledControls$:g,onRemove:T}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(Q(this.container.container.events)&&this.gameState===3||this.selectBranches.state.isExpect||(this.gameState!==2&&this.container.hide?.(),this.emitContainerVisibilityEvent(!1)))})};this.show=()=>{if(this.gameState===2&&!this.isSelectedControlEvent)if(this.container.getElement())this.container.show?.(),this.emitContainerVisibilityEvent(!0,!1);else{let t=At(this.selectBranches.onControlEvent,{isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.emitContainerVisibilityEvent(!1)},onEvent:(n,r)=>{this.isSelectedControlEvent=!0,n!==!1&&(this.removeView(),this.emitContainerVisibilityEvent(!1)),(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),r(),this.removeView(),this.emitContainerVisibilityEvent(!1))},isEOV:()=>this.gameState===4});this.container.createView(t),this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let e=this.player.experimental.element$.getValue(),n=e instanceof HTMLVideoElement?e.readyState:void 0,r=[6,5];if(!n||r.includes(this.gameState)&&!this.isPermanentText)return;let s=this.player.getExactTime();if(wt(s,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(tt(s,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let h=this.gameState;this.gameState=3,h===2&&this.onEndTime()}else this.isPermanentText||this.removeView();let c=tt(s,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],o={subjectId:this.container.container.id,subjectName:"container",range:a,currentTime:s,isInteractiveTime:c};this.globalEventEmitter.emit(f.eachTick,o),this.globalEvents.eachTick$.next(o)};this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new dn,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=o,this.isPermanentText=h&&q(t.container.controls),this.disabledControls$=g,this.onRemove=T,this.globalEventEmitter=a,this.gameState=0,this.globalEvents=c,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:e,isFirst:t}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e,isFirst:t})):(this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:!1}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e}))}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(e=>{e?this.container.disable?.():this.container.enable?.()}))}selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime??1/0))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);let e=Q(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.emitContainerVisibilityEvent(!1)}reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=1}removeView(){this.container.removeView(),this.globalEventEmitter.emit(f.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.containerRemoved,visibility:!1}),this.globalEvents.interactiveContainerRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-removed"}),this.gameState=5,this.onRemove?.()}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 Vt=(i=[])=>i.reduce((e,t,n)=>{let r=(t?.controls??[]).filter(s=>!xe(s));if(Pe(r)){let s=[t.startTime??0,t.endTime??1/0],c=t.id;if(!n)e.push({subjects:[c],range:s});else{let a=[],o=-1/0,h=1/0,g=[],T=[];for(let S=0;S<e.length;S++){let x=e[S];if(T.push(...x.subjects),x.range[0]<h&&(h=x.range[0]),x.range[1]>o&&(o=x.range[1]),s[0]>=x.range[0]&&s[1]<=x.range[1])return e[S].subjects.push(c),e;s[0]<x.range[0]&&s[1]>x.range[0]&&(a.push(S),g=g.concat(x.subjects)),s[0]>=x.range[0]&&s[0]<=x.range[1]&&(a.push(S),g=g.concat(x.subjects),s[0]=x.range[0]),s[1]>=x.range[0]&&s[1]<=x.range[1]&&(a.push(S),g=g.concat(x.subjects),s[1]=x.range[1])}if(T.push(c),s[0]<=h&&s[1]>=o)return[{subjects:T,range:s}];a.length&&a.reverse().forEach(S=>{e.splice(S,1)}),e.push({subjects:g.concat([c]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function Pt(){let i={};function e(){for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a]}function t(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(Ze(a)){let g=i[a]??null;if(g&&o&&te(o,!0)){let T={},S=g[o];return S&&(T={...T,...S}),T=W(T)?null:T,T&&te(h,!0)?T[h]??null:T}return g}return null}function s({timestamp:a,priority:o,initiator:h}){if(Ze(a))if(i[a]){if(o&&te(o,!0))if(i[a][o]){if(h&&te(h,!0))if(i[a][o][h]){if(delete i[a][o][h],!W(i[a][o]))return!0}else return!1;if(delete i[a][o],!W(i[a]))return!0}else return!1;return delete i[a]}else return!1;return!1}function c({timestamp:a,priority:o,initiator:h,...g}){i[a]?.[o]?.[h]?i[a][o][h].push({...g}):i[a]?.[o]?i[a][o]={...i[a][o],[h]:[{...g}]}:i[a]?i[a]={...i[a],[o]:{[h]:[{...g}]}}:i[a]={[o]:{[h]:[{...g}]}}}return{map:i,remove:s,add:c,removeAll:e,get:r,getLte:t,getGte:n}}var mn=[I.expect,I.setNextBranch],fn=1/0;function $t(i){let e=i,t,n=yn(),r=Pt(),s,c=()=>{S(),R()},a=y=>{r.add.call(void 0,y),N()},o=(y=[])=>{for(let l of y)if(l.action(),mn.includes(l.actionType))break},h=(y=1/0)=>{let l=Ne(r.get({timestamp:y,priority:"control"})??{}),p=Ne(r.get({timestamp:y,priority:"container"})??{}),u=Ne(r.get({timestamp:y,priority:"chapter"})??{});return[...l,...p,...u]},g=y=>{n.isReady(y)&&o(h(y))},T=()=>{o([...Ne(r.get({timestamp:1/0,priority:"chapter"})??{})])},S=()=>{t&&(s?.unsubscribe(),t=void 0)},x=y=>{},N=()=>{t||(t=()=>setTimeout(()=>{g(1/0)}),s=e.events.ended$.subscribe(t))},D=y=>{S(),e=y},C=y=>{y.priority==="container"&&n.resetCalled(y.timestamp),r.remove(y)},R=()=>{n.release(),r.removeAll()};return{setPlayer:D,add:a,remove:C,exec:g,execEndOfVideo:T,listen:N,unlisten:S,release:c,containersEventsCallState:n,getPreparedToExecActions:h}}function yn(){let i=new Map;return{setCalled:({timestamp:c,id:a})=>{let o=i.get(c);o&&o[a]!==void 0&&(o[a]=!0)},setData:(c=[])=>{for(let a of c){let o=a.endTime??fn,h=i.get(o)??{};i.set(o,{...h,[a.id]:!1})}},resetCalled:c=>{let a=i.get(c);if(a)for(let o in a)a[o]=!1},isReady:c=>{let a=i.get(c);return a?!Object.values(a).some(o=>!o):!0},release:()=>i.clear()}}function Ne(i){return Object.values(i).flat().sort(e=>e.actionType===I.expect?-1:1)}var Lt={videoContentHeight:0,videoContentWidth:0},Nt=(i,e)=>{let{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return Lt;let{clientHeight:r,clientWidth:s}=e.experimental.element$.getValue()||{};if(!(r&&s))return Lt;let c=t/n,a=r/s,o,h;return a>c?(h=s,o=s*c):a<c?(h=r/c,o=r):(h=s,o=r),{videoContentWidth:h,videoContentHeight:o}};var vn=250;function Ot(i){let e=()=>{},t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){let{parentElement:o,player:h}=i();if(o&&h){let{videoContentWidth:g,videoContentHeight:T}=Nt(o,h);o.style.setProperty("--interactive-content-width",`${g}px`),o.style.setProperty("--interactive-content-height",`${T}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=J(a=>{let{fns:o=[]}=i();n(a);for(let h of o)h()},vn);function c(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:c}}var oe=class{constructor(){this.map={}}push(e,t){e in this.map?this.map[e].push(t):this.map[e]=[t]}get(e){let t=this.map[e];return t?t.slice():null}getAll(){let e=[];for(let t in this.map)e.concat(this.map[t]);return e}remove(e,t){e in this.map&&(this.map[e]=this.map[e].filter(n=>n!==t),this.map[e].length===0&&delete this.map[e])}clear(){this.map={}}keys(){return Object.keys(this.map)}size(){return this.keys().length}};var gn=i=>Math.floor(Math.random()*i),Ft=i=>{let e=i.length,t=1/0,n=null;for(;e--;){let r=i[e],s=r.weight??1;s<t&&(t=s,n=r)}return n},Bt=i=>{let e=i.length,t=-1/0,n=null;for(;e--;){let r=i[e],s=r.weight??0;s>t&&(t=s,n=r)}return n};var _t=i=>{let e=i.length,t=gn(e);return i[t]},jt=1,Ht=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??jt;let t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??jt,e>=t)return i[n];return i[i.length-1]};var Dt={shouldOpenNow:!0,isDetachContainer:!0},Gt="after-expect";var ot=(i,e=!1)=>({...i,args:e?{...i.args,...Dt}:{...Dt,...i.args}}),Wt=({globalEventEmitter:i,globalEvents:e,player:t,interactiveEvents:n,removeControllers:r})=>{let s={isExpect:!1},c=()=>{s.isExpect&&(s.isExpect=!1)},a=({action:l,controlType:p,controlId:u,containerId:d,branches:m=[],onEvent:A,isEOV:E=()=>!1,isDisabled:v=()=>!1})=>{let b=ot(l,E()),B={timestamp:1/0,priority:"control",initiator:u,actionType:b.type},_=v(),V=i.emit.bind(i,f.interactives,{subjectId:u,subjectType:p,subjectName:"control",type:_?w.actionChoiceCanceled:w.actionChoice,actionType:l.type,payload:{containerId:d,...b.args}}),O=()=>{e.interactiveActionChoice$.next({subjectId:u,subjectType:p,subjectName:"control",type:_?"action-choice-canceled":"action-choice",actionType:l.type,payload:{containerId:d,...b.args}})};if(_){V(),O();return}switch(b.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let j=m.find(K=>K.id===b.args.branchId);if(!j)return;A(b.args.isDetachContainer,N.bind(null,{subjectId:u,subjectName:"control"})),V(),O(),b.args.shouldOpenNow?C({subjectId:u,subjectName:"control",subjectType:p,action:b,payload:{chapterId:j.chapterId,autoSelect:!1}}):(n.add({...B,action:C.bind(null,{subjectId:u,subjectName:"control",subjectType:p,action:b,payload:{chapterId:j.chapterId,autoSelect:!1}})}),r?.());return}case I.continuePlayback.trim().toLowerCase():{A(b.args.isDetachContainer,N.bind(null,{subjectId:u,subjectName:"control"})),V(),O(),b.args.shouldOpenNow?D({subjectId:u,subjectName:"control",subjectType:p,action:l}):n.add({...B,action:D.bind(null,{subjectId:u,subjectName:"control",subjectType:p,action:l})});return}case I.openURI.trim().toLowerCase():{A(b.args.isDetachContainer,N.bind(null,{subjectId:u,subjectName:"control"})),V(),O(),b.args.shouldOpenNow?y({subjectId:u,subjectName:"control",subjectType:p,action:b,payload:{URI:l.args.uri}}):(n.add({...B,action:y.bind(null,{subjectId:u,subjectName:"control",subjectType:p,action:b,payload:{URI:l.args.uri}})}),r?.());return}default:let G="Unexpected control event",He=new M(1,1,{message:G});T(He,G);return}},o=({action:l,container:{id:p,endTime:u},branches:d=[],isEOV:m=!1,autoSelected:A=!1})=>{let E=ot(l,m),v={timestamp:!E.args.shouldOpenNow||m?1/0:u??1/0,priority:"container",initiator:p,actionType:E.type},b=i.emit.bind(i,f.interactives,{subjectId:p,subjectName:"container",type:w.actionChoice,actionType:E.type,payload:E.args}),B=()=>{e.interactiveActionChoice$.next({subjectId:p,subjectName:"container",type:"action-choice",actionType:E.type,payload:E.args})};switch(E.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let O=d.find(G=>G.id===E.args.branchId);if(!O)return;b(),B(),n.add({...v,action:C.bind(null,{subjectId:p,subjectName:"container",action:E,payload:{chapterId:O.chapterId,autoSelect:A}})}),r?.();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():{b(),B(),n.add({...v,action:D.bind(null,{subjectId:p,subjectName:"container",action:E})});return}case I.openURI.trim().toLowerCase():{b(),B(),n.add({...v,action:y.bind(null,{subjectId:p,subjectName:"container",action:E,payload:{URI:l.args.uri}})}),r?.();return}default:let _="Unexpected container event",V=new M(1,1,{message:_});T(V,_);return}};function h({container:l,branches:p,isEOV:u=!1}){let d=nt(l.events);if(d){let m=ot(d.action,u);i.emit(f.interactives,{subjectId:l.id,subjectName:"container",type:w.actionChoice,actionType:m.type,payload:m.args}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"container",type:"action-choice",actionType:m.type,payload:m.args}),n.add({timestamp:u?1/0:l.endTime??1/0,priority:"container",initiator:l.id,actionType:I.expect,action:x.bind(null,{subjectId:l.id,subjectName:"container"})}),s.isExpect=!0}else for(let m of l.events??[])o({action:m.action,container:l,branches:p,isEOV:u})}let g=({chapterId:l,action:p,branches:u=[]})=>{let d=i.emit.bind(i,f.interactives,{subjectId:l,subjectName:"chapter",type:w.actionChoice,actionType:p.type,payload:p.args}),m=()=>{e.interactiveActionChoice$.next({subjectId:l,subjectName:"chapter",type:"action-choice",actionType:p.type,payload:p.args})};switch(p.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let v=u.find(b=>b.id===p.args.branchId);return v?.chapterId?(d(),m(),C.bind(null,{subjectId:l,subjectName:"chapter",action:p,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{let v=_t(u);return v?.chapterId?(d(),m(),C.bind(null,{subjectId:l,subjectName:"chapter",action:p,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{let v=Ht(u);return v?.chapterId?(d(),m(),C.bind(null,{subjectId:l,subjectName:"chapter",action:p,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{let v=Bt(u);return v?.chapterId?(d(),m(),C.bind(null,{subjectId:l,subjectName:"chapter",action:p,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{let v=Ft(u);return v?.chapterId?(d(),m(),C.bind(null,{subjectId:l,subjectName:"chapter",action:p,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return d(),m(),D.bind(null,{subjectId:l,subjectName:"chapter",action:p});case I.openURI.trim().toLowerCase():return d(),m(),y.bind(null,{subjectId:l,subjectName:"chapter",action:p,payload:{URI:p.args.uri}});default:let A="Unexpected chapter event",E=new M(1,1,{message:A});T(E,A);return}};function T(l,p){console.error(p),e.error$.next(l),i.emit(f.errors,l)}function S(l){let p=nt(l.events);if(p){if(F(l))return;i.emit(f.interactives,{subjectId:l.id,subjectName:"chapter",type:w.actionChoice,actionType:p.action.type,payload:p.action.args}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"chapter",type:"action-choice",actionType:p.action.type,payload:p.action.args}),n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:I.expect,action:x.bind(null,{subjectId:l.id,subjectName:"chapter"})})}else l.events?.forEach(u=>{let d=g({chapterId:l.id,action:u.action,branches:l.branches});d&&n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:u.action.type,action:d})})}let x=({subjectId:l,subjectName:p})=>{t.pause(),i.emit(f.interactives,{subjectId:l,subjectName:p,type:w.actionExecution,actionType:I.expect}),e.interactiveActionExecution$.next({subjectId:l,subjectName:p,type:"action-execution",actionType:I.expect})},N=({subjectId:l,subjectName:p})=>{t.info.isEnded$.getValue()?n.execEndOfVideo():t.play(),i.emit(f.interactives,{subjectId:l,subjectName:p,type:w.actionExecution,actionType:Gt}),e.interactiveActionExecution$.next({subjectId:l,subjectName:p,type:"action-execution",actionType:Gt})},D=({subjectId:l,subjectName:p,subjectType:u,action:d})=>{i.emit(f.interactives,{subjectId:l,subjectName:p,subjectType:u,type:w.actionExecution,actionType:d.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:p,subjectType:u,type:"action-execution",actionType:d.type})},C=({subjectId:l,subjectName:p,subjectType:u,action:d,payload:m})=>{m.behaviour="change-chapter",i.emit(f.interactives,{subjectId:l,subjectName:p,subjectType:u,type:w.actionExecution,actionType:d.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:p,subjectType:u,type:"action-execution",actionType:d.type,payload:m})},R=({subjectId:l,subjectName:p,subjectType:u,action:d,payload:m})=>{m.behaviour="change-manifest",i.emit(f.interactives,{subjectId:l,subjectName:p,subjectType:u,type:w.actionExecution,actionType:d.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:p,subjectType:u,type:"action-execution",actionType:d.type,payload:m})},y=({subjectId:l,subjectName:p,subjectType:u,action:d,payload:m})=>{if(!m.URI)return;let A=window.open(m.URI,"_blank","noopener,noreferrer");A&&(A.opener=null),i.emit(f.interactives,{subjectId:l,subjectName:p,subjectType:u,type:w.actionExecution,actionType:d.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:p,subjectType:u,type:"action-execution",actionType:d.type})};return{onControlEvent:a,onContainerEvent:o,onChapterEvent:g,onExpectEvent:x,expectEventHandler:N,setManifestChapterEvents:S,setManifestContainerEvents:h,stopExpect:c,state:s}};import{Subscription as Tn,Subject as ct,ValueSubject as le}from"@vkontakte/videoplayer-shared/evergreen";var lt=(i,e)=>{let t={};return i.map(n=>{if(!t[n]){let r=e.chapters.find(c=>c.id===n);if(!r)return null;let s=e.media.videos.find(c=>r.videoId===c.id);if(!s)return null;t[n]=Qt(s)}return t[n]}).filter(Boolean)},bn=i=>{for(let e of i.variants)if(En(e)&&e.payload)return e.payload.id},En=i=>!!(i.type==="custom"&&i.payload&&i.payload.type==="vk"),Qt=i=>{let e=bn(i);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},In=(i,e)=>{for(let t of i.media.videos)if(e===Qt(t)){for(let n of i.chapters)if(n.videoId===t.id)return n.id;return}},Kt=(i,e)=>i.reduce((t,n)=>{let r=In(e,n);return r?[...t,r]:t},[]);var ce=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:n,historyApi:r,settings:s}){this.state={history$:new le([]),hasPrevChapter$:new le(!1),prevChapter$:new le(null),isInitialChapter$:new le(!1),isGoBackLimited$:new le(!1)};this.#n=null;this.#a=!1;this.#e=null;this.#p=null;this.events={inited$:new ct,destroyed$:new ct,error$:new ct};this.#i=null;this.#r=null;this.#t=null;this.#o=new Tn;this.#l=!1;this.#c=0;this.#i=t,this.#t=e,this.#r=n,this.#n=r,this.#s=s,this.state.history$&&this.#o&&this.#o?.add(this.state.history$.subscribe(c=>{this.state.prevChapter$.next(c.at(-2)||null),this.state.hasPrevChapter$.next(c.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#e?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#c===this.#s.maxLength-1)}))}#n;#s;#a;#e;#p;#i;#r;#t;#o;#l;#c;async setManifest(e){if(!this.#r||!this.#t)return;this.#e=e,await this.getProjectHistory();let t=this.getInitialChapterId();await this.#r.setChapter({chapterId:t,pushToHistory:!1}),this.#a||(this.#a=!0,this.events.inited$.next({initChapterId:t}))}get inited(){return this.#a}async updateHistory(e,t=!0){if(!this.#e)return;this.#l?(this.#l=!1,this.#c++):this.#c=0;let n=this.#e,r=e.length-this.#s.maxLength,s=r>0?e.slice(r):e,c=lt(s,n);if(this.#p=c,this.state.history$.next(s),!(!t||!this.#n||!this.#i))try{await this.#n.save(this.#i,c)}catch{let o=new M(1,5,"Unable to save interactive history");this.events.error$.next(o),this.#t?.emit(f.errors,o)}}async goBack(){if(!this.state||!this.#r){let n=new M(1,5,"Unable to save interactive history");return this.events.error$.next(n),this.#t?.emit(f.errors,n)}this.#l=!0;let e=this.state.history$.getValue().slice(0,-1),t=e.pop();this.state.history$.next(e),await this.#r.setChapter({chapterId:t,playPrev:!0})}async getProjectHistory(){if(!this.#e||!this.#i)return;let e=this.#e,t=[this.getInitialVideoId()];if(this.#n)try{let r=await this.#n.get(this.#i);r.length&&(t=r)}catch{let s=new M(1,5,"Error while trying to fetch data");this.events.error$.next(s),this.#t?.emit(f.errors,s)}let n=Kt(t,e);this.state.history$.next(n)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#s.initChapterId||this.#e?.metadata.initChapterId}getInitialVideoId(){if(this.#e){let e=this.getInitialChapterId();return lt([e],this.#e).pop()}return null}destroy(){this.#i=null,this.#n=null,this.#r=null,this.#o?.unsubscribe(),this.#o=null,this.#a=!1,this.#t?.emit(f.historyDestroyed),this.events.destroyed$.next(),this.#t=null}};var Oe=class i{constructor(e,t,n,r){this.target=e,this.type=t,this.listener=n,this.options=i._convertOptions(e,r),this.target.addEventListener(t,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(e,t){if(t===void 0)return!1;if(typeof t=="boolean")return t;{let n=new Set(["passive","capture"]),r=Object.keys(t).filter(c=>!n.has(c));return r.length===0&&console.warn("Unsupported flag(s) to addEventListener: "+r.join(",")),i._doesSupportObject(e)?t:t.capture||!1}}static{this._supportsObject=void 0}static _doesSupportObject(e){let t=i._supportsObject;if(t===void 0){t=!1;try{let n={},r={get:()=>(t=!0,!1)};Object.defineProperty(n,"passive",r),Object.defineProperty(n,"capture",r);let s=()=>{};e.addEventListener("test",s,n),e.removeEventListener("test",s,n)}catch{t=!1}i._supportsObject=t}return t||!1}};var je=class{constructor(){this.bindingMap=new oe}release(){this.removeAll(),this.bindingMap=null}listen(e,t,n,r){if(!this.bindingMap)return;let s=new Oe(e,t,n,r);this.bindingMap.push(t,s)}listenOnce(e,t,n,r){let s=c=>{this.unlisten(e,t,s),n(c)};this.listen(e,t,s,r)}unlisten(e,t,n){if(!this.bindingMap)return;let r=this.bindingMap.get(t)||[];for(let s of r)s.target===e&&(n===s.listener||!n)&&(s.unlisten(),this.bindingMap.remove(t,s))}removeAll(){if(!this.bindingMap)return;let e=this.bindingMap.getAll();for(let t of e)t.unlisten();this.bindingMap.clear()}};var Fe=class{constructor(){this._prevSizeId=0;this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){let e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;let t=e.data,n=t.length;for(let r=3;r<n;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){let n=e.width+e.height;if(this._prevSizeId===n)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=n}async save(){let e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}};var Be=class{constructor({parentElement:e,endOffsetMs:t=250,onError:n}){this.currentVideoDurationMs=1/0;this._containerTimeFrameShouldReceived=!1;this._endTimeFrameReceived=!1;this._shouldCallSkip=!1;this.onEachTick=e=>{let t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,n=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(n)this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1,this._endTimeFrameReceived||(this.draw(),this._endTimeFrameReceived=!0,this.show());else{if(this._shouldCallSkip){this._shouldCallSkip=!1;return}this.reset()}};this.onSeek=()=>{this.onEachTick(),!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived&&(this.hide(),this.lastFrameCanvas.clear())};this.rootElement=document.createElement("div"),this.rootElement.style.cssText=`
|
|
6
|
+
var ft="1.0.30-dev.b736679d.0";function ee(n,e=1){let t="0",i="0",r="0";return n.length===4?(t="0x"+n[1]+n[1],i="0x"+n[2]+n[2],r="0x"+n[3]+n[3]):n.length===7&&(t="0x"+n[1]+n[2],i="0x"+n[3]+n[4],r="0x"+n[5]+n[6]),`rgba(${+t},${+i},${+r},${e})`}function te(n){for(;n>Math.PI;)n-=2*Math.PI;for(;n<=-Math.PI;)n+=2*Math.PI;return n}function pi(n){return n*180/Math.PI}var ye=class{constructor(e){this.widthExpansionCoef=0;let t=document.createElement("div");t.classList.add("interactive-fillAnimationElement");let i=document.createElement("div");i.classList.add("interactive-fillAnimationElement-filler-wrapper");let r=document.createElement("div");r.classList.add("interactive-fillAnimationElement-filler"),i.append(r),t.append(i);let o=te(e.rotateAngle),a=o>Math.PI/2&&o<=Math.PI||o<0&&o<-Math.PI/2,s=o===Math.PI/2,l=o===-Math.PI/2,p=!a&&!s&&!l,u=s||l,b=!!(o%Math.PI/2)&&!u,y=b?o:0;t.style.borderRadius=e.borderRadius,i.style.transform=`skew(${y*-1}rad)`,u?(r.classList.add("fillHeight",s?"fromTop":"fromBottom"),i.classList.add("fillHeight",s?"fromTop":"fromBottom")):(r.classList.add("fillWidth",p?"fromLeft":"fromRight"),i.classList.add("fillWidth")),e.debug&&console.log({widthExpansionCoef:this.widthExpansionCoef,opts:e,shouldFillHeight:u,rotateAngleRad:o,rotateAngelDeg:pi(o),rotateAngleRaw:e.rotateAngle,fromRight:a,fromTop:s,fromBottom:l,fromLeft:p}),this.useSkew=b,this.fromLeft=p,this.rotateAngle=o,this.fillAnimationElement=t,this.fillAnimationFillerElement=r,this.fillAnimationFillerWrapperElement=i,this.startTime=e.startTime,this.endTime=e.endTime,this.shouldFillHeight=u,this.isDebug=e.debug??!1}updateDimension(e){this.fillAnimationElement.style.top=`${e.borderWidth*-1}px`,this.fillAnimationElement.style.left=`${e.borderWidth*-1}px`,this.fillAnimationElement.style.width=`${e.width}px`,this.fillAnimationElement.style.height=`${e.height}px`;let t=this.calcWidthExpansionCoef({rotateAngle:this.rotateAngle,isSkewed:this.useSkew,initWidth:e.width,initHeight:e.height});!this.shouldFillHeight&&(this.fillAnimationFillerWrapperElement.style.width=100*t+100+"%",this.fillAnimationFillerWrapperElement.style[`${this.fromLeft?"left":"right"}`]=`calc((${t} * 100%) / 2 * -1)`),this.widthExpansionCoef=t}updateAnimation(e){if((o=>o<this.startTime||o>this.endTime)(e))return;let i=this.endTime-this.startTime,r=Math.min(Math.max((e-this.startTime)/i,0),1);this.shouldFillHeight?this.fillAnimationFillerElement.style.transform=`scaleY(${r})`:this.fillAnimationFillerElement.style.transform=`scaleX(${r})`}calcWidthExpansionCoef({rotateAngle:e,isSkewed:t=!1,initWidth:i,initHeight:r}){return t?(i+r*Math.abs(Math.tan(e)))/i-1:0}};var R="interactive";var S={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderWidthRawValue:"1px",roundCornersRawValue:"0",borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0,shadowColorLight:"#fff",shadowColorDark:"#000",shadowColorAlpha:.24},yt=(i=>(i.top="flex-start",i.bottom="flex-end",i.center="center",i))(yt||{}),vt=(i=>(i.start="flex-start",i.end="flex-end",i.center="center",i))(vt||{}),Ct=(i=>(i.start="left",i.end="right",i.center="center",i))(Ct||{}),ve=({target:n,props:e})=>{n.style.alignItems=(e?.gravityVertical&&yt[e.gravityVertical])??"center",n.style.justifyContent=(e?.gravityHorizontal&&vt[e.gravityHorizontal])??"center",n.style.textAlign=(e?.alignment&&Ct[e.alignment])??"left"},Ce=({target:n,props:e,fallback:t,dependsOn:i})=>{n.style.color=e?.text?.color??t.textColor,n.style.fontSize=`calc(${i.height} * ${e?.text?.size??t.textSize})`,n.textContent=e?.text?.value??t.textContent},ge=({target:n,props:e,fallback:t})=>{n.style.backgroundColor=ee(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},ie=({target:n,props:e,fallback:t,dependsOn:i,useRawValues:r=!1})=>{let o=r?t.borderWidthRawValue:`calc(${i.height} * ${e?.shape?.border?.width??t.borderWidth})`,a=r?t.roundCornersRawValue:`calc(${i.height} * ${e?.shape?.roundCorners??t.roundCorners})`;n.style.borderWidth=o,n.style.borderStyle="solid",n.style.borderColor=ee(r?t.borderColor:e?.shape?.border?.color??t.borderColor,r?t.borderAlpha:e?.shape?.border?.alpha??t.borderAlpha),n.style.borderRadius=a},gt=({target:n,frameToneIsDark:e,baseDimension:t,fallback:i})=>{let a=ee(i.shadowColorLight,i.shadowColorAlpha),s=ee(i.shadowColorDark,i.shadowColorAlpha),l=`calc(${t} * ${.25})`,p=`calc(${t} * ${.11})`,u=`0px 0px ${l} ${p} ${e?a:s}`;n.style.boxShadow=u},K=({target:n,layoutParams:e,fallback:t})=>{let i=te(e.angle??t.angle);i=i&&i*-1,n.style.transform=`rotate(${i}rad)`};var Ge="int",z=(i=>(i.AREA=`${Ge}_area`,i.TEXT=`${Ge}_text`,i.BUTTON=`${Ge}_bttn`,i))(z||{});function be(n){return"features"in n}var _=class{constructor(e,t){this.control=e;this.options=t;this.container=null;this.controlElement=null;this.clickListener=null;this.isInteracted=!1;this.isRemoved=!1}createContainerElement(e){let t=document.createElement("div");t.classList.add(`${R}-control-container-${this.control.id}`),e.setControlLayout(t,this.control.layoutParams);let i=(this.control.layoutParams.innerSizesDependOn??S.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"},r=()=>e.isContainerDisabled?.()??!1;this.container={element:t,dimensions:i,getComputedDimensions:e.getComputedDimensions,isManifestContainerDisabled:r}}createClickListener(e){return t=>{t.stopPropagation(),this.isInteracted=!0,e()}}featureIsEnabled(e){return this.options&&be(this.options)&&this.options.features[e]}setEvents(e){!this.container||!this.control.events||this.control.events.forEach(t=>{switch(t.type.trim().toLowerCase()){case"onclick":this.clickListener=this.createClickListener(()=>e({action:t.action,controlId:this.control.id,controlType:this.control.type})),this.container?.element.addEventListener("click",this.clickListener);break;default:break}})}removeListeners(){this.container?.element&&this.clickListener&&this.container?.element.removeEventListener("click",this.clickListener)}};var bt=!1,Et=60,X=class{constructor(e,t){this.onElementClick=e=>{if(!e.currentTarget||this.clickCancelCondition())return;let t=e.currentTarget.parentElement;if(!t)return;let i=t.getBoundingClientRect(),r={width:bt?t.offsetWidth:Et,height:bt?t.offsetHeight:Et},o=Math.min(r.width,r.height),a=i.left+i.width/2,s=i.top+i.height/2,l=e.clientX-a,p=e.clientY-s,u=di(l,p,te(this.controlRotateAngleRad));this.element.style.width=o+"px",this.element.style.left=u.x+i.width/2-o/2+"px",this.element.style.top=u.y+i.height/2-o/2+"px",this.element.classList.add("interactive-tap-visible","interactive-tap-animation")};let i=document.createElement("div");i.classList.add("interactive-tap"),this.controlRotateAngleRad=e,this.element=i,this.clickCancelCondition=t}};function di(n,e,t){return{x:n*Math.cos(t)-e*Math.sin(t),y:n*Math.sin(t)+e*Math.cos(t)}}var Ee=(n,e)=>{if(n.type.trim().toLowerCase()==="area")return new Ue(n,e)},Ue=class extends _{constructor(t,i){super(t,i);this.onControlSelect=()=>{this.container&&this.container.isManifestContainerDisabled()||this.controlElement?.classList.add("interactive-control-selected")};this.onTransitionEnd=t=>{t.stopPropagation(),!(!t.target||!t.currentTarget)&&t.target===t.currentTarget&&(t.currentTarget.removeEventListener("transitionend",this.onTransitionEnd),this.removeView())}}createView({parentElement:t,callbacks:i}){if(super.createContainerElement(i),!this.container)return;let r=document.createElement("button");if(r.type="button",r.classList.add(`${R}-${this.control.id}`,`${R}-control`,`${R}-control-area`),r.setAttribute("data-testid",z.AREA),this.controlElement=r,ge({target:r,props:this.control.props,fallback:{...S,backgroundColor:"transparent"}}),this.updateShadowStyles(),K({target:r,layoutParams:this.control.layoutParams,fallback:S}),this.featureIsEnabled("tapPlaceShow")){let o=this.control.layoutParams.angle??S.angle;this.tapElement=new X(o,this.container.isManifestContainerDisabled),r.addEventListener("click",this.tapElement.onElementClick),this.container.element.append(this.tapElement.element)}r.addEventListener("click",this.onControlSelect,{once:!0}),this.container.element.append(r),t.append(this.container.element)}updateShadowStyles(t=!1){if(!(!this.container||!this.controlElement))if(t){let i=getComputedStyle(this.controlElement),r=i.getPropertyValue("--interactive-frame-tone");if(!r)return;let o=Math.min(Number.parseFloat(i.height),Number.parseFloat(i.width))+"px",a=r==="dark";gt({target:this.controlElement,props:this.control.props,fallback:S,frameToneIsDark:a,baseDimension:o}),ie({target:this.controlElement,props:this.control.props,fallback:{...S,borderColor:a?"#fff":"#000",borderAlpha:1,borderWidthRawValue:"0.1px",roundCornersRawValue:`calc(${this.container.dimensions.height} * ${this.control.props?.shape?.roundCorners??S.roundCorners})`},dependsOn:this.container.dimensions,useRawValues:!0})}else ie({target:this.controlElement,props:this.control.props,fallback:{...S,borderAlpha:0},dependsOn:this.container.dimensions})}disable(){this.controlElement&&(this.controlElement.style.cursor="default")}enable(){this.controlElement&&(this.controlElement.style.cursor="pointer")}setShowTimeRange(){}onProgress(){}onResize(){}removeView(t=!1){let i=this.getElement();if(i){if(t){if(i.classList.contains("interactive-control-before-remove"))return;i.classList.add("interactive-control-before-remove"),i.addEventListener("transitionend",this.onTransitionEnd);return}this.removeListeners(),i.remove(),this.isRemoved=!0}}removeListeners(){super.removeListeners(),this.controlElement?.removeEventListener("click",this.onControlSelect),this.getElement()?.removeEventListener("transitionend",this.onTransitionEnd),!(!this.tapElement||!this.featureIsEnabled("tapPlaceShow"))&&this.controlElement?.removeEventListener("click",this.tapElement.onElementClick)}getElement(){return this.controlElement}toggleCTAAnimation(t){this.controlElement?.classList.toggle("interactive-control-cta-area",t)}};var Ie=()=>{let n=document.createElement("span");return n.style.display="inline-block",n.style.whiteSpace="pre",n.style.overflow="hidden",n.style.textOverflow="ellipsis",n.style.maxWidth="100%",n.style.maxHeight="100%",n};var Te=(n,e)=>{if(n.type.trim().toLowerCase()==="button")return new Qe(n,e)},Qe=class extends _{constructor(t,i){super(t,i);this.onControlSelect=()=>{this.container&&this.container.isManifestContainerDisabled()||this.controlElement?.classList.add("interactive-control-selected")};this.onTransitionEnd=t=>{t.stopPropagation(),!(!t.target||!t.currentTarget)&&t.target===t.currentTarget&&(t.currentTarget.removeEventListener("transitionend",this.onTransitionEnd),this.removeView())}}createView({parentElement:t,callbacks:i}){if(super.createContainerElement(i),!this.container)return;let r=document.createElement("button");r.type="button",r.classList.add(`${R}-${this.control.id}`,`${R}-control`,`${R}-control-button`),r.setAttribute("data-testid",z.BUTTON),K({target:r,layoutParams:this.control.layoutParams,fallback:S}),ge({target:r,props:this.control.props,fallback:S}),ie({target:r,props:this.control.props,fallback:S,dependsOn:this.container.dimensions}),ve({target:r,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let o=Ie();if(Ce({target:o,props:this.control.props,fallback:S,dependsOn:this.container.dimensions}),this.startTime!==void 0&&this.endTime!==void 0&&this.featureIsEnabled("buttonControlInteractiveTimeTimer")&&(this.fillAnimation=new ye({startTime:this.startTime,endTime:this.endTime,rotateAngle:this.control.layoutParams.angle??S.angle,borderRadius:r.style.borderRadius})),this.featureIsEnabled("tapPlaceShow")){let a=this.control.layoutParams.angle??S.angle;this.tapElement=new X(a,this.container.isManifestContainerDisabled),r.addEventListener("click",this.tapElement.onElementClick),this.container.element.append(this.tapElement.element)}r.addEventListener("click",this.onControlSelect,{once:!0}),r.append(o,this.fillAnimation?.fillAnimationElement??""),this.container.element.append(r),t.append(this.container.element),this.controlElement=r,requestAnimationFrame(()=>{this.fillAnimation&&this.updateFillAnimationDimension()})}disable(){this.controlElement&&(this.controlElement.style.cursor="default")}enable(){this.controlElement&&(this.controlElement.style.cursor="pointer")}setShowTimeRange(t,i){this.startTime=t,this.endTime=i}onProgress(t){this.fillAnimation?.updateAnimation(t)}updateFillAnimationDimension(){if(!this.container||!this.controlElement)return;let t=getComputedStyle(this.controlElement),i={width:parseFloat(t.width),height:parseFloat(t.height),borderWidth:parseFloat(t.borderWidth)||0};this.fillAnimation?.updateDimension(i)}onResize(){this.updateFillAnimationDimension()}getElement(){return this.controlElement}removeView(t=!1){let i=this.getElement();if(i){if(t){if(i.classList.contains("interactive-control-before-remove"))return;i.classList.add("interactive-control-before-remove"),i.addEventListener("transitionend",this.onTransitionEnd);return}this.removeListeners(),i.remove(),this.isRemoved=!0}}removeListeners(){super.removeListeners(),this.controlElement?.removeEventListener("click",this.onControlSelect),this.getElement()?.removeEventListener("transitionend",this.onTransitionEnd),!(!this.tapElement||!this.featureIsEnabled("tapPlaceShow"))&&this.controlElement?.removeEventListener("click",this.tapElement.onElementClick)}toggleCTAAnimation(t){this.controlElement?.classList.toggle("interactive-control-cta-button",t)}updateShadowStyles(){}};var It=n=>{if(n.type.trim().toLowerCase()==="text")return new qe(n)},qe=class extends _{constructor(t){super(t);this.onTransitionEnd=t=>{t.stopPropagation(),!(!t.target||!t.currentTarget)&&t.target===t.currentTarget&&(t.currentTarget.removeEventListener("transitionend",this.onTransitionEnd),this.removeView())}}createView({parentElement:t,callbacks:i}){if(super.createContainerElement(i),!this.container)return;let r=document.createElement("div");r.classList.add(`${R}-${this.control.id}`,`${R}-control`,`${R}-control-text`),r.setAttribute("data-testid",z.TEXT),K({target:r,layoutParams:this.control.layoutParams,fallback:S}),ve({target:r,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let o=Ie();Ce({target:o,props:this.control.props,fallback:S,dependsOn:this.container.dimensions}),r.append(o),this.container.element.append(r),t.append(this.container.element),this.controlElement=r}disable(){}enable(){}setShowTimeRange(){}onProgress(){}onResize(){}toggleCTAAnimation(){}updateShadowStyles(){}removeView(t=!1){let i=this.getElement();if(i){if(t){if(i.classList.contains("interactive-control-before-remove"))return;i.classList.add("interactive-control-before-remove"),i.addEventListener("transitionend",this.onTransitionEnd);return}this.removeListeners(),i.remove(),this.isRemoved=!0}}removeListeners(){super.removeListeners(),this.getElement()?.removeEventListener("transitionend",this.onTransitionEnd)}getElement(){return this.controlElement}};var Ke=class{constructor(e){this.layout=e}},xe=class extends Ke{constructor(e){super(e)}setContainerLayout(e){e.style.position="relative"}setControlLayout(e,t){e.style.position="absolute",e.style.width=`calc(var(--interactive-content-width) * ${t.width})`,e.style.height=`calc(var(--interactive-content-height) * ${t.height})`,e.style.left=`calc(var(--interactive-content-width) * ${t.x} + ((var(--interactive-width) - var(--interactive-content-width)) / 2))`,e.style.top=`calc(var(--interactive-content-height) * ${t.y} + ((var(--interactive-height) - var(--interactive-content-height)) / 2))`}getComputedDimensions(e,t){let i=window.getComputedStyle(e),r=parseFloat(i.getPropertyValue("--interactive-content-width")),o=parseFloat(i.getPropertyValue("--interactive-content-height"));return{width:r*t.width,height:o*t.height}}};var Z=class{constructor(e,t){this.container=e,this.options=t,this.factories=new Map,this.controls=[],this.setControls()}addControlFactory(e,t){this.factories.set(e.trim().toLowerCase(),t),this.setControls()}featureIsEnabled(e){return this.options&&be(this.options)&&this.options.features[e]}removeControlFactory(e){this.factories.delete(e.trim().toLowerCase()),this.setControls()}setControls(){this.controls=this.chooseControls()}chooseControls(){return this.container.controls?.reduce((e,t)=>{let i=t.type.trim().toLowerCase(),r=this.factories.get(i);if(r){let o=r(t,this.options);if(o)return[...e,o]}return[...e]},[])||[]}};import{isSupportedManifest as ke,ContainerTypes as Un,ControlTypes as U,EventActionTypes as I,EventTypes as Qn,migrateManifestToLatestVersion as wt,compareVersions as qn}from"@interactiveplatform/movika-manifest";var W=(n,e)=>Object.prototype.toString.call(n)===`[object ${e}]`,ne=n=>W(n,"Object"),Ae=n=>W(n,"String"),we=n=>W(n,"Array"),Se=n=>W(n,"Number"),Tt=n=>W(n,"Function");var Xe=n=>Se(n)&&!isNaN(n);var G=n=>ne(n)&&Object.keys(n).length===0,Ze=n=>we(n)&&!n.length;var re=(n,e)=>Ae(n)&&(e?n.trim():n).length;var xt={metadata:"Object",chapters:"Array"},At=n=>{if(!ne(n))return!1;for(let e in xt)if(!n[e]||!W(n[e],xt[e]))return!1;return ke(n.metadata.version)},Re=n=>n.type===U.Text,Nn=n=>n.type===U.Button,jn=n=>n.type===U.Area,Bn={Choice:"Choice",TextInput:"TextInput"},Dn={Button:"Button",Area:"Area",Text:"Text"},_n={onClick:"onClick",onSuspense:"onSuspense"},Hn={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var Me=(n,e,t)=>{if(n.type.trim().toLowerCase()==="choice")return new Ye(n,e,t)},Ye=class extends Z{constructor(t,i,r){super(t,r);this.onTransitionEnd=t=>{t.stopPropagation(),!(!t.target||!t.currentTarget)&&t.target===t.currentTarget&&(t.currentTarget.removeEventListener("transitionend",this.onTransitionEnd),this.removeView())};this.rootElement=i,this.layout=new xe(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.willRemoved=!1,this.addControlFactory("button",Te),this.addControlFactory("text",It),this.addControlFactory("area",Ee)}createView({eventCallback:t,videoDurationMs:i}){let r=document.createElement("div");return this.featureIsEnabled("controlsShowAnimation")?(r.classList.add("interactive-container-before-show"),requestAnimationFrame(()=>{r.classList.remove("interactive-container-before-show"),r.classList.add("interactive-container")})):r.classList.add("interactive-container"),r.classList.add(`${R}-${this.container.id}`),this.layout.setContainerLayout(r),this.controls.forEach(o=>{if(o.setShowTimeRange(this.container.startTime,this.container.endTime??i),o.createView({parentElement:r,callbacks:{setControlLayout:this.layout.setControlLayout,getComputedDimensions:()=>this.layout.getComputedDimensions(this.rootElement,o.control.layoutParams),isContainerDisabled:()=>this.isDisabled}}),o.setEvents(t),this.featureIsEnabled("controlsCTAAnimation")){let a=o.control.type;(a===U.Button||a===U.Area)&&o.controlElement?.addEventListener("mouseleave",()=>{o.controlElement&&this.setupControlsBlinkAnimSync(o.controlElement,a)})}}),this.rootElement.append(r),this.isRemoved=!1,this.willRemoved=!1,r}onProgress(t,i){i&&this.controls.forEach(r=>{r.onProgress(t)})}onResize(){this.controls.forEach(t=>{t.onResize()})}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(i=>i.enable()),t.classList.remove("interactive-container-disabled"),this.isDisabled=!1)}disable(){let t=this.getElement();t&&(this.controls.forEach(i=>i.disable()),t.classList.add("interactive-container-disabled"),this.isDisabled=!0)}removeView(t=!1,i=!1){let r=this.getElement();if(r){if(t){if(this.willRemoved)return;this.willRemoved=!0,i&&r.classList.add("interactive-container-before-remove-delay"),r.classList.add("interactive-container-before-remove"),r.addEventListener("transitionend",this.onTransitionEnd);return}this.removeAllControls(),r.remove(),this.isRemoved=!0,this.willRemoved=!1}}removeAllControls(t=!1){this.controls.forEach(i=>i.removeView(t))}removeNonInteractedControls(t=!1){this.controls.forEach(i=>{i.isInteracted||i.removeView(t)})}isInteracted(){return this.controls.some(t=>t.isInteracted)}getElement(){return this.rootElement.querySelector(`.${R}-${this.container.id}`)}toggleCTAAnimation(t){this.controls.forEach(i=>i.toggleCTAAnimation(t))}updateControlsShadowStyles(t){this.controls.forEach(i=>i.updateShadowStyles(t))}setupControlsBlinkAnimSync(t,i){if(!t.classList.contains(`interactive-control-cta-${i.toLowerCase()}`)||t.classList.contains("interactive-control-selected")||t.classList.contains("interactive-blink-reference-disable-animation"))return;let r=this.rootElement.querySelector(".interactive-blink-reference-animation");r&&(t.classList.add("interactive-blink-reference-disable-animation"),r.addEventListener("animationiteration",()=>{t.classList.remove("interactive-blink-reference-disable-animation")},{once:!0}))}};import{clientChecker as Hi,combine as zi,InterfaceLanguage as Wi,Observable as ai,once as Gi,Subject as L,Subscription as He,ValueSubject as $,fromEvent as li}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as me}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as ui}from"@vkontakte/videoplayer-shared/evergreen";function oe(n,e){let t;return(...i)=>{clearTimeout(t),t=setTimeout(()=>n(...i),e)}}var St="video_interactive",Rt="videoint";var kt=250,se=class{constructor(e){this.handleZoomChange=oe(e=>{this.lastZoomInfo=e},kt);this.onResize=e=>{if(!this.isReady||this.isHidden||!e[0].contentRect.width||!e[0].contentRect.height)return;let t=this.getNextPoint();t&&this.ngEditor?.zoomTo(t),this.ngEditorSize={width:e[0].contentRect.width,height:e[0].contentRect.height}};this.handleChapterChange=e=>{if(this.manifest){if(this.isHidden||this.hide(),!e?.id){this.onError?.("Id is not found"),console.error("Id is not found");return}this.visitedChapterIds.add(e.id),this.ngEditor?.selectChapter(e.id),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId=e.id,this.lastZoomInfo=null}};this.handleManifestChange=(e,t=[])=>{if(this.isReady=!1,!Se(e.graph.edit.chapters[0].x)){this.onError?.("Can't show graph"),console.error("Can't show graph");return}this.lastZoomInfo=null,this.manifest=e,this.visitedChapterIds=new Set(t),this.ngEditor&&(this.manifest.metadata.id!==this.currentManifestId?(this.ngEditor.update(e),this.currentManifestId=this.manifest.metadata.id):this.ngEditor.setVisitedChapters(Array.from(t)),this.isReady=!0)};this.init(e)}init({root:e,onOpenPreviewClick:t,onError:i,lang:r,visitedChapters:o=[]}){this.isReady=!1,this.isHidden=!0,this.manifest=null,this.visitedChapterIds=new Set(o),this.onOpenPreviewClick=t,this.onError=i,this.lang=r??"ru",this.zoom=.7,this.lastZoomInfo=null,this.currentManifestId=null,this.currentChapterId=null,this.ngEditor=null,this.ngEditorSize=null,this.graphWrapperElement=mi(e),this.resizeObserver=new ResizeObserver(oe(this.onResize,kt)),this.resizeObserver.observe(this.graphWrapperElement)}getNextPoint(e=this.ngEditorSize){return!this.lastZoomInfo||!e?null:[(this.lastZoomInfo.x-e.width/2)/this.lastZoomInfo.value*-1,(this.lastZoomInfo.y-e.height/2)/this.lastZoomInfo.value*-1]}setVisitedChapters(e){this.visitedChapterIds=new Set([...this.visitedChapterIds,...e]),this.ngEditor?.setVisitedChapters(Array.from(this.visitedChapterIds))}updateVideosInfo(e){this.ngEditor?.updateVideosInfo(e)}async show(){this.manifest&&(this.ngEditor||await this.initNgEditor(),this.graphWrapperElement.style.display="block",!this.lastZoomInfo&&this.currentChapterId&&this.ngEditor?.focusChapter(this.currentChapterId),this.isHidden=!1)}async initNgEditor(){if(!this.manifest)return;let e;try{e=await ui(this.lang,St,Rt)}catch{console.log("Unable to load graph language pack")}let{GraphEditor:t}=await import("@interactiveplatform/movika-graph-editor");this.ngEditor=new t(this.graphWrapperElement,{mode:"read",lang:this.lang==="ru"?"ru":"en",translation:e}),this.currentManifestId=this.manifest.metadata.id,this.ngEditor.update(this.manifest),this.ngEditor.setVisitedChapters(Array.from(this.visitedChapterIds)),this.currentChapterId&&this.ngEditor.selectChapter(this.currentChapterId),this.ngEditor.on("control",({name:i,...r})=>{i==="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 mi(n){let e=document.createElement("div");return e.style.position="absolute",e.style.top="0",e.style.left="0",e.style.height="100%",e.style.width="100%",e.style.display="none",n.append(e),e}var ae=class{constructor(){this._containers=[];this._player=null;this.setPlayer=e=>{this._player=e};this.setContainers=e=>{this._containers=e};this.deleteContainer=e=>{this._containers=this._containers.filter(t=>t.id!==e)};this.getNextInteractiveTime=(e=3e3)=>{if(!this._containers.length||this._player===null)return null;let t=-1,i=!1,r=Math.round(this._player.info.position$.getValue()*1e3);for(let o of this._containers){let a=o.startTime-e;if(a<=r&&(o.endTime&&r<=o.endTime||o.endTime===null)){i=!0;break}r<a&&(t=t===-1?a:Math.min(t,a))}return!i&&t!==-1?t:null}}};var P=class{constructor(e,t,...i){this.severity=e;this.category=t;this.data=i}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var Ve=class{constructor(){this.listeners={}}addListener(e,t){return this.listeners[e]=this.listeners[e]||[],this.listeners[e].push(t),this}on(e,t){return this.addListener(e,t)}once(e,t){this.listeners[e]=this.listeners[e]||[];let i=()=>{t(),this.off(e,i)};return this.listeners[e].push(i),this}off(e,t){return this.removeListener(e,t)}reset(){this.listeners={}}removeListener(e,t){let i=this.listeners[e]||[];for(let r=i.length;r>0;r--)if(i[r]===t){i.splice(r,1);break}return this}emit(e,...t){let i=this.listeners[e];return i?(i.forEach(r=>{r(...t)}),!0):!1}listenerCount(e){return this.rawListeners(e).length}rawListeners(e){return this.listeners[e]||[]}};var Pe=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{Tt(e)&&(this.fns.push(e),t&&this.updateFn())};this.removeFn=(e,t=!1)=>{this.fns=this.fns.filter(i=>i!==e),t&&this.updateFn()};this.updateFn=()=>{this.fn=()=>{this.fns.forEach(e=>e()),this.raf&&this.forceRequestAnimation()}};this.forceRequestAnimation=()=>{this.fn&&(this.raf=requestAnimationFrame(this.fn))};this.requestAnimation=()=>{this.raf||this.forceRequestAnimation()};this.cancelAnimation=()=>{this.raf&&(cancelAnimationFrame(this.raf),this.raf=void 0)};e&&(this.fn=e,this.addFn(e))}release(){this.cancelAnimation(),this.fn=void 0,this.fns=[]}};import{ValueSubject as Ei}from"@vkontakte/videoplayer-shared/evergreen";var Le=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return fi(...this.loaders[e])(t)}};function fi(...n){return async function(t){let i=[...n];for(;i.length>0;)t=await i.shift()(t);return t}}function le(n,e,t){return n?{...n,[e]:n[e]?[t,...n[e]]:[t]}:{[e]:[t]}}function $e({actions:n,errors:e,chapterId:t,...i}){if(t){let r=n.getManifest();if(r){let o=n.getChapter(r.chapters,t);if(o){let a=n.getMedia(r.media,o.videoId),s=n.getGraph(r.graph,o.id);return a?{...i,actions:n,errors:e,result:{chapter:o,media:a,graph:s}}:{...i,errors:le(e,$e.name,"Could not find media"),actions:n}}}}return{...i,errors:le(e,$e.name,"Could not find chapter"),actions:n}}var Je=(n="",e="")=>{let t=n.split("."),i=e.split("."),r=0;for(let o=0;o<Math.max(t.length,i.length)&&!r;o++)t[o]>i[o]?r=1:t[o]<i[o]?r=-1:r=0;return r};var yi=async n=>{try{let e={},t;if(Ae(n)){t=new URL(n).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(ne(n))e=n;else return{};if(!At(e))return{};let i=e.metadata.media;if(Ae(i)&&!("media"in e))try{let r;t?r=new URL(i,t).href:(r=new URL(i).href,t=r);let o=await fetch(r);if(!o.ok)throw new Error;e.metadata.media=await o.json()}catch{return gi(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Mt(n){let{manifest:e,manifestURL:t}=await yi(n);if(!e)throw new Error("Failed on fetch");let i=wt(e);return i.media=vi(i.media,t),delete i.metadata.media,i}function Fe(n,e){if(e)return n.find(t=>t.id===e)}function et(n,e){return n.edit?.chapters?n.edit.chapters.find(t=>t.id===e):n.view?.chapters?n.view.chapters.find(t=>t.id===e):void 0}function tt(n,e){return n.videos.find(t=>t.id===e)}function vi(n,e){return{...n,videos:n.videos.map(t=>({...t,variants:t.variants.map(i=>{let r="url"in i?i.url:"",o=Ci(r,e);return{...i,url:o||r}})}))}}function Ci(n="",e){try{return new URL(n,e).href}catch{return""}}function gi(n){return Je(n,"3.2.0")>=0}var Oe=n=>we(n)&&!Ze(n),B=n=>n.order==="end",Ne=n=>we(n.containers)&&!Ze(n.containers)&&B(n),Vt=(n,e)=>{let t=n*1e3;return Oe(e.controls)&&t<(e.startTime??0)},it=(n,e)=>{let t=n*1e3;return Oe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var H=(n=[])=>n.some(e=>e.action.type==="expect"),nt=(n=[])=>n.find(e=>e.action.type==="expect"),bi=n=>n?.length===1,Y=n=>bi(n)&&Re(n[0]);function Pt(n,...e){return t=>typeof e[0]=="object"&&typeof t=="object"?n({...e[0],...t}):n(...e,...t)}var Lt=(n,e)=>H(n.events)?!1:e.some(({container:t})=>t.container.id!==n.id&&H(t.container.events)&&t.container.endTime===n.endTime&&!t.isRemoved&&!t.willRemoved);var J=class extends Le{constructor(t,i){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new Ei(null);this.onError=i,this.release()}release(){return this.manifest=null,this.chapter=null,this.media=null,this.graph=null,this.prevChapter$.next(null),this}async setManifest(t){this.release();let i=await this.exec("manifestLoaders",{actions:{addErrorMessage:le},result:null,errors:null,source:t});return i.errors&&this.errorHandler(i.errors),this.manifest=await Mt(i.result??t),this}async setInitial(){return this.setNext()}async setNext(t=this.manifest?.metadata.initChapterId){if(!t)return this;this.prevChapter$.next(this.chapter);let i=await this.exec("chapterLoaders",$e({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:et,getChapter:Fe,getMedia:tt,getByBranches:this.getByBranches.bind(this),addErrorMessage:le},result:null,errors:null,chapterId:t}));return i.errors&&this.errorHandler(i.errors),i.result&&(this.chapter=i.result.chapter,this.media=i.result.media,this.graph=i.result.graph),this}errorHandler(t){this.onError(t),console.error("Something went wrong with loaders",{errors:t})}getInitial(){return this.getByChapterId(this.manifest?.metadata.initChapterId)||null}getByChapterId(t=this.manifest?.metadata.initChapterId){if(!t||!this.manifest)return null;let i=Fe(this.manifest.chapters,t);if(i){let r=tt(this.manifest.media,i.videoId),o=et(this.manifest.graph,i.id);if(r)return{chapter:i,media:r,graph:o}}return null}getBranches(t=this.chapter?.id){if(t===this.chapter?.id)return this.getByBranches(this.chapter?.branches);{let i=Fe(this.manifest?.chapters||[],t);return this.getByBranches(i?.branches)}}getByBranches(t=[]){return t.reduce((i,r)=>{let o=this.getByChapterId(r.chapterId);return o&&i.push(o),i},[])}getCurrent(){return{chapter:this.chapter,media:this.media,graph:this.graph}}isInitialChapter(){return this.chapter?.id===this.manifest?.metadata.initChapterId}isEndChapter(){return this.chapter?B(this.chapter):!1}};import{Player as Ii}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as st,Tracer as Ti,ValueSubject as xi}from"@vkontakte/videoplayer-shared/evergreen";var $t=n=>{let e=n.variants.find(t=>t.payload?.type==="vk");if(e&&e.payload){let[t,i]=e.payload.id.split("_");return[t,i]}return[]};function rt(){let n=new Map;function e({listId:o=Math.random().toString(),itemId:a=Math.random().toString(),...s}){let l=n.get(o),p={...s};return l?l[a]=p:n.set(o,{[a]:p}),{listId:o,itemId:a,...s}}function t(o){o.player.destroy(),o.container.remove(),o.subscription.unsubscribe(),o.statistics?.oneStat.destroy(),o.statistics?.statSubscription.unsubscribe()}function i(o,a){let s=n.get(o);if(!s)throw Error("Can't remove. Not find.");if(a){let l=s[a];l&&t(l),delete s[a],Object.keys(s).length||n.delete(o)}else{for(let l of Object.values(s))t(l);n.delete(o)}}function r(){for(let o of n)i(o[0])}return{createPlayer:e,removePlayer:i,map:n,removeAll:r}}function ot(n,e=[]){let t={},i,r=!e.length;for(let o of n.variants)if(!i&&"cover"in o&&(i=o.cover),"url"in o)switch(o.type.toLowerCase()){case"mp4":(r||e.includes("mp4"))&&(t.MPEG={...t.MPEG,[o.standard??"Invariant quality"]:o.url});break;case"mpeg":(r||e.includes("mpeg"))&&(t.MPEG={...t.MPEG,[o.standard??"Invariant quality"]:o.url});break;case"hls":(r||e.includes("hls"))&&(t={...t,HLS:{type:"url",url:o.url}});break;case"dash":(r||e.includes("dash"))&&(t={...t,DASH_SEP:{compatibilityMode:!0,type:"url",url:o.url}});break;default:break}return{sources:t,thumbUrl:i,title:n.title??""}}var ce=(n,e)=>{let t=n.info.currentQuality$.getValue(),i=n.info.availableQualities$.getValue();t!==e&&i.includes(e)&&(n.setQuality(e),n.setAutoQuality(!1))};var Ai=2;function at(n){let e=rt(),t=new st,i={},r=null,o=!1,a,s=new xi(null);n&&l(n);function l(x){r=x}function p(x,A,c){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let d=(e.map.get(x)??{})[A];if(d){i={chapterId:c,listId:x,itemId:A,...d};let m=i.player;i.subscription.add(m.info.currentQuality$.subscribe(f=>{let v=m.info.position$.getValue(),T=m.info.isAutoQualityEnabled$.getValue();if(!(!f||!v||T))for(let k of e.map)Object.values(k[1]).forEach(({player:g})=>{ce(g,f)})})).add(m.events.started$.subscribe(()=>{u(A)})),d.container.remove(),r.setPlayer(d.player),o||(r.init(),o=!0),s.next({player:i.player,config:i.config,statistics:i.statistics});return}throw Error("Can't set. Not find.")}async function u(x){if(!r)throw Error("need to set interactive controller");if(G(i)||x!==i.itemId)return;let A=r.getChapterBranches(),c=new Set;for(let h of A)c.has(h.media.id)||(await y({media:h.media,chapterId:h.chapter.id,setAsActive:!1,title:h.chapter.label}),c.add(h.media.id))}async function b({chapter:{id:x},manifestVideo:A}){if(G(i)||!r)return;let c=i.player.info.muted$.getValue(),h=i.player.info.currentQuality$.getValue(),d=i.player.info.isAutoQualityEnabled$.getValue(),m=i.player.info.volume$.getValue(),f=i.player.info.currentPlaybackRate$.getValue(),v=!d,T=!1;for(let k of e.map)if(k[0]===A.id&&!r.state.isReplay$.getValue()){let g=Object.keys(k[1]);for(let V of g)V===i.itemId?(g.length<Ai||(T=!0),e.removePlayer(k[0],V)):(T=!0,p(k[0],V,x),v?ce(i.player,h):i.player.setAutoQuality(!0),i.player.setVolume(m),i.player.setMuted(c),i.player.setPlaybackRate(f))}else e.removePlayer(k[0]);T||(await y({media:A,chapterId:x,setAsActive:!0,playbackRate:f}),v?ce(i.player,h):i.player.setAutoQuality(!0),i.player.setVolume(m),i.player.setMuted(c))}async function y({media:x,chapterId:A,prefetch:c=!0,setAsActive:h=!0,autoplay:d=!1,preferredExt:m,title:f,playbackRate:v}){let T=Math.random().toString(),k=document.createElement("div");a.append(k);let g;if(r?.options?.vkVideoLoader){let fe=$t(x);fe.length&&(g=await r.options.vkVideoLoader(...fe))}let V=r?.options?.coreConfig||void 0,O={...V,configName:[...V?.configName??[],"interactive"]},N={container:k,...g?.videos?.[0]||{sources:ot(x,m).sources},title:f,failoverHosts:g?.failoverHosts||[]},j=new Ii(O,Ti.createRootTracer());j.initVideo(N);let D=null;if(g?.videos&&r?.options.createOneStat){let fe=g.videos[0],We=r.options.createOneStat(fe),mt=new st;We&&(mt.add(We.attachTo(j)),D={oneStat:We,statSubscription:mt})}let Q=new st,hi=i?.player?.info.isAutoQualityEnabled$.getValue();Q.add(j.events.canplay$.subscribe(function(){hi||ce(j,i.player.info.currentQuality$.getValue()),v&&j.setPlaybackRate(v)}));let q=e.createPlayer({listId:x.id,itemId:T,player:j,container:k,sources:ot(x,m).sources,config:N,subscription:Q,statistics:D});return h&&p(x.id,q.itemId,A),d&&q.player.play(),c&&!d&&q.player.prepare(),{player:q.player,config:q.config,statistics:q.statistics}}function E(){M(),r=null,a.remove()}function M(){t.unsubscribe(),e.removeAll(),i={},o=!1}async function F(){if(!r)throw Error("need to set interactive controller");M(),a=document.createElement("div");let{media:x,chapter:A}=r.getCurrentChapter();x&&A?(t.add(r.events.chapterChanged$.subscribe(b)),await y({media:x,chapterId:A.id,title:A.label})):console.error("not found")}return{...e,init:F,setInteractiveController:l,createPlayer:y,removeAll:E,getActivePlayer:function(){return i},activePlayerChanged:s}}var C={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},he={visibility:"visibility",watchAgainClicked:"watchAgainClicked"},w={actionChoiceCanceled:"action-choice-canceled",actionChoice:"action-choice",actionExecution:"action-execution",visibility:"visibility",containerRemoved:"container-removed",rangeEnded:"range-ended"};import{Subscription as wi}from"@vkontakte/videoplayer-shared/evergreen";var je=class{constructor({player:e,container:t,branches:i,selectBranches:r,interactiveEvents:o,globalEvents:a,globalEventEmitter:s,ignoreContainerEvent:l,permanentTextControls:p,disabledControls$:u,onRemove:b,features: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.emitContainerVisibilityEvent(!1)))})};this.show=()=>{if(this.gameState!==2||this.container.isInteracted())return;if(this.container.getElement())this.container.show?.(),this.emitContainerVisibilityEvent(!0,!1);else{let t={isDisabled:()=>this.container.isDisabled,branches:this.branches,containerId:this.container.container.id,onDetachContainer:()=>{this.removeView(),this.emitContainerVisibilityEvent(!1)},onEvent:(o,a)=>{this.isSelectedControlEvent=!0,o!==!1&&(this.removeView(),this.emitContainerVisibilityEvent(!1)),(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),a(),this.removeView(),this.emitContainerVisibilityEvent(!1))},isEOV:()=>this.gameState===4},i=Pt(this.selectBranches.onControlEvent,t),r=(this.player?.info.duration$.getValue()??1/0)*1e3;this.container.createView({eventCallback:i,videoDurationMs:r}),this.emitContainerVisibilityEvent(!0,!0),this.disabledControls$.getValue()&&this.container.disable?.()}};this.onEndOfVideo=()=>{this.gameState=4,this.selectContainerEvent(!0)};this.whilePlaying=()=>{let e=this.player.experimental.element$.getValue();if(!(e instanceof HTMLVideoElement?e.readyState:void 0)||this.isRemovedOrDestroyed()&&!this.isPermanentText)return;let r=this.player.getExactTime();if(Vt(r,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(it(r,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let l=this.gameState;this.gameState=3,l===2&&this.onEndTime()}else this.isPermanentText||this.removeView();let o=it(r,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],s={subjectId:this.container.container.id,subjectName:"container",range:a,currentTime:r,isInteractiveTime:o};this.globalEventEmitter.emit(C.eachTick,s),this.globalEvents.eachTick$.next(s),this.container?.onProgress(r*1e3,o)};this.container=t,this.branches=i,this.selectBranches=r,this.subscription=new wi,this.player=e,this.interactiveEvents=o,this.ignoreContainerEvent=l,this.isPermanentText=p&&Y(t.container.controls),this.disabledControls$=u,this.onRemove=b,this.globalEventEmitter=s,this.gameState=0,this.globalEvents=a,this.features=y,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(C.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:e,isFirst:t}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e,isFirst:t})):(this.globalEventEmitter.emit(C.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.visibility,visibility:!1}),this.globalEvents.interactiveVisibilityChanged$.next({subjectId:this.container.container.id,subjectName:"container",type:"visibility",visibility:e}))}registerEvents(){this.subscription.add(this.player.events.playing$.subscribe(this.show)).add(this.player.events.paused$.subscribe(this.hide)).add(this.player.events.ended$.subscribe(this.onEndOfVideo)).add(this.disabledControls$.subscribe(e=>{e?this.container.disable?.():this.container.enable?.()}))}selectContainerEvent(e=!1){this.interactiveEvents.containersEventsCallState.setCalled({timestamp:e?1/0:this.container.container.endTime??1/0,id:this.container.container.id}),!(this.isSelectedControlEvent||this.isSelectedContainerEvent)&&(this.isSelectedContainerEvent=!0,this.ignoreContainerEvent()||this.selectBranches.setManifestContainerEvents({container:this.container.container,branches:this.branches,isEOV:e}),!e&&this.interactiveEvents.exec(this.container.container.endTime??1/0))}onStartTime(){this.show()}onEndTime(){this.selectContainerEvent(!1);let e=H(this.container.container.events)||this.ignoreContainerEvent();(this.isSelectedControlEvent||!e)&&this.removeView()}onBeforeStartTime(){this.container.hide?.(),this.emitContainerVisibilityEvent(!1)}reset(){this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.gameState=1}isInteracted(){return this.container.isInteracted()}isRemovedOrDestroyed(e=!0){let t=e?this.container.willRemoved:!1;return this.gameState===5||t||this.gameState===6}removeView(e=this.features.controlsHideAnimation){if(e){if(this.isRemovedOrDestroyed())return;this.container.removeNonInteractedControls(!0),this.container.removeView(!0,!0)}else this.container.removeView();this.globalEventEmitter.emit(C.interactives,{subjectId:this.container.container.id,subjectName:"container",type:w.containerRemoved,visibility:!1}),this.globalEvents.interactiveContainerRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-removed"}),this.gameState=5,this.onRemove?.()}toggleControlsCTAAnimation(e){this.container.toggleCTAAnimation(e)}updateControlsShadowStyles(e){this.container.updateControlsShadowStyles(e)}destroy(){this.reset(),this.removeView(!1),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 Ot=(n=[])=>n.reduce((e,t,i)=>{let r=(t?.controls??[]).filter(o=>!Re(o));if(Oe(r)){let o=[t.startTime??0,t.endTime??1/0],a=t.id;if(!i)e.push({subjects:[a],range:o});else{let s=[],l=-1/0,p=1/0,u=[],b=[];for(let y=0;y<e.length;y++){let E=e[y];if(b.push(...E.subjects),E.range[0]<p&&(p=E.range[0]),E.range[1]>l&&(l=E.range[1]),o[0]>=E.range[0]&&o[1]<=E.range[1])return e[y].subjects.push(a),e;o[0]<E.range[0]&&o[1]>E.range[0]&&(s.push(y),u=u.concat(E.subjects)),o[0]>=E.range[0]&&o[0]<=E.range[1]&&(s.push(y),u=u.concat(E.subjects),o[0]=E.range[0]),o[1]>=E.range[0]&&o[1]<=E.range[1]&&(s.push(y),u=u.concat(E.subjects),o[1]=E.range[1])}if(b.push(a),o[0]<=p&&o[1]>=l)return[{subjects:b,range:o}];s.length&&s.reverse().forEach(y=>{e.splice(y,1)}),e.push({subjects:u.concat([a]),range:o})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function Nt(){let n={};function e(){for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&delete n[s]}function t(s){let l={};for(let p in n)+p<=s&&(l[p]=n[p]);return l}function i(s){let l={};for(let p in n)+p>=s&&(l[p]=n[p]);return l}function r({timestamp:s,priority:l,initiator:p}){if(Xe(s)){let u=n[s]??null;if(u&&l&&re(l,!0)){let b={},y=u[l];return y&&(b={...b,...y}),b=G(b)?null:b,b&&re(p,!0)?b[p]??null:b}return u}return null}function o({timestamp:s,priority:l,initiator:p}){if(Xe(s))if(n[s]){if(l&&re(l,!0))if(n[s][l]){if(p&&re(p,!0))if(n[s][l][p]){if(delete n[s][l][p],!G(n[s][l]))return!0}else return!1;if(delete n[s][l],!G(n[s]))return!0}else return!1;return delete n[s]}else return!1;return!1}function a({timestamp:s,priority:l,initiator:p,...u}){n[s]?.[l]?.[p]?n[s][l][p].push({...u}):n[s]?.[l]?n[s][l]={...n[s][l],[p]:[{...u}]}:n[s]?n[s]={...n[s],[l]:{[p]:[{...u}]}}:n[s]={[l]:{[p]:[{...u}]}}}return{map:n,remove:o,add:a,removeAll:e,get:r,getLte:t,getGte:i}}var Si=[I.expect,I.setNextBranch],Ri=1/0;function jt(n){let e=n,t,i=ki(),r=Nt(),o,a=()=>{y(),A()},s=c=>{r.add.call(void 0,c),M()},l=(c=[])=>{for(let h of c)if(h.action(),Si.includes(h.actionType))break},p=(c=1/0)=>{let h=Be(r.get({timestamp:c,priority:"control"})??{}),d=Be(r.get({timestamp:c,priority:"container"})??{}),m=Be(r.get({timestamp:c,priority:"chapter"})??{});return[...h,...d,...m]},u=c=>{i.isReady(c)&&l(p(c))},b=()=>{l([...Be(r.get({timestamp:1/0,priority:"chapter"})??{})])},y=()=>{t&&(o?.unsubscribe(),t=void 0)},E=c=>{},M=()=>{t||(t=()=>setTimeout(()=>{u(1/0)}),o=e.events.ended$.subscribe(t))},F=c=>{y(),e=c},x=c=>{c.priority==="container"&&i.resetCalled(c.timestamp),r.remove(c)},A=()=>{i.release(),r.removeAll()};return{setPlayer:F,add:s,remove:x,exec:u,execEndOfVideo:b,listen:M,unlisten:y,release:a,containersEventsCallState:i,getPreparedToExecActions:p}}function ki(){let n=new Map;return{setCalled:({timestamp:a,id:s})=>{let l=n.get(a);l&&l[s]!==void 0&&(l[s]=!0)},setData:(a=[])=>{for(let s of a){let l=s.endTime??Ri,p=n.get(l);n.set(l,{...p,[s.id]:!1})}},resetCalled:a=>{let s=n.get(a);if(s)for(let l in s)s[l]=!1},isReady:a=>{let s=n.get(a);return s?!Object.values(s).some(l=>!l):!0},release:()=>n.clear()}}function Be(n){return Object.values(n).flat().sort(e=>e.actionType===I.expect?-1:1)}var Bt={videoContentHeight:0,videoContentWidth:0},Dt=n=>{let{height:e,width:t}=n.info.intrinsicVideoSize$.getValue()||{};if(!(e&&t))return Bt;let{clientHeight:i,clientWidth:r}=n.experimental.element$.getValue()||{};if(!(i&&r))return Bt;let o=e/t,a=i/r,s,l;return a>o?(l=r,s=r*o):a<o?(l=i/o,s=i):(l=r,s=i),{videoContentWidth:l,videoContentHeight:s}};var Mi=250;function _t(n){let e=()=>{},t=new ResizeObserver(s=>{o(s),e=o.bind(null,s)});function i(s){let{parentElement:l,player:p}=n();if(l&&p){let{videoContentWidth:u,videoContentHeight:b}=Dt(p);l.style.setProperty("--interactive-content-width",`${Math.ceil(u)}px`),l.style.setProperty("--interactive-content-height",`${Math.ceil(b)}px`),l.style.setProperty("--interactive-width",`${Math.ceil(s[0].contentRect.width)}px`),l.style.setProperty("--interactive-height",`${Math.ceil(s[0].contentRect.height)}px`)}}function r(){let{parentElement:s}=n();s.removeAttribute("style")}let o=oe(s=>{let{fns:l=[]}=n();i(s);for(let p of l)p()},Mi);function a(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:a}}var Vi=n=>Math.floor(Math.random()*n),zt=n=>{let e=n.length,t=1/0,i=null;for(;e--;){let r=n[e],o=r.weight??1;o<t&&(t=o,i=r)}return i},Wt=n=>{let e=n.length,t=-1/0,i=null;for(;e--;){let r=n[e],o=r.weight??0;o>t&&(t=o,i=r)}return i};var Gt=n=>{let e=n.length,t=Vi(e);return n[t]},Ht=1,Ut=n=>{let e=0;for(let i=0;i<n.length;++i)e+=n[i].weight??Ht;let t=Math.random()*e;e=0;for(let i=0;i<n.length-1;++i)if(e+=n[i].weight??Ht,e>=t)return n[i];return n[n.length-1]};var Qt={shouldOpenNow:!0,isDetachContainer:!0},qt="after-expect";var lt=(n,e=!1)=>({...n,args:e?{...n.args,...Qt}:{...Qt,...n.args}}),Zt=({globalEventEmitter:n,globalEvents:e,player:t,interactiveEvents:i})=>{let r={isExpect:!1},o=()=>{r.isExpect&&(r.isExpect=!1)},a=({action:c,controlType:h,controlId:d,containerId:m,branches:f=[],onEvent:v,isEOV:T=()=>!1,isDisabled:k=()=>!1})=>{let g=lt(c,T()),V={timestamp:1/0,priority:"control",initiator:d,actionType:g.type},O=k(),N=n.emit.bind(n,C.interactives,{subjectId:d,subjectType:h,subjectName:"control",type:O?w.actionChoiceCanceled:w.actionChoice,actionType:c.type,payload:{invokeImmediately:g.args.shouldOpenNow,containerId:m,...g.args}}),j=()=>{e.interactiveActionChoice$.next({subjectId:d,subjectType:h,subjectName:"control",type:O?"action-choice-canceled":"action-choice",actionType:c.type,payload:{invokeImmediately:g.args.shouldOpenNow,containerId:m,...g.args}})};if(O){N(),j();return}switch(g.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let D=f.find(Q=>Q.id===g.args.branchId);if(!D)return;v(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),N(),j(),g.args.shouldOpenNow?F({subjectId:d,subjectName:"control",subjectType:h,action:g,payload:{chapterId:D.chapterId,autoSelect:!1}}):i.add({...V,action:F.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:g,payload:{chapterId:D.chapterId,autoSelect:!1}})});return}case I.continuePlayback.trim().toLowerCase():{v(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),N(),j(),g.args.shouldOpenNow?M({subjectId:d,subjectName:"control",subjectType:h,action:c}):i.add({...V,action:M.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:c})});return}case I.openURI.trim().toLowerCase():{v(g.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),N(),j(),g.args.shouldOpenNow?A({subjectId:d,subjectName:"control",subjectType:h,action:g,payload:{URI:c.args.uri}}):i.add({...V,action:A.bind(null,{subjectId:d,subjectName:"control",subjectType:h,action:g,payload:{URI:c.args.uri}})});return}default:{let D="Unexpected control event",Q=new P(1,1,{message:D});u(Q,D);return}}},s=({action:c,container:{id:h,endTime:d},branches:m=[],isEOV:f=!1,autoSelected:v=!1})=>{let T=lt(c,f),k={timestamp:!T.args.shouldOpenNow||f?1/0:d??1/0,priority:"container",initiator:h,actionType:T.type},g=n.emit.bind(n,C.interactives,{subjectId:h,subjectName:"container",type:w.actionChoice,actionType:T.type,payload:{invokeImmediately:T.args.shouldOpenNow,...T.args}}),V=()=>{e.interactiveActionChoice$.next({subjectId:h,subjectName:"container",type:"action-choice",actionType:T.type,payload:{invokeImmediately:T.args.shouldOpenNow,...T.args}})};switch(T.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let O=m.find(N=>N.id===T.args.branchId);if(!O)return;g(),V(),i.add({...k,action:F.bind(null,{subjectId:h,subjectName:"container",action:T,payload:{chapterId:O.chapterId,autoSelect:v}})});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():{g(),V(),i.add({...k,action:M.bind(null,{subjectId:h,subjectName:"container",action:T})});return}case I.openURI.trim().toLowerCase():{g(),V(),i.add({...k,action:A.bind(null,{subjectId:h,subjectName:"container",action:T,payload:{URI:c.args.uri}})});return}default:{let O="Unexpected container event",N=new P(1,1,{message:O});u(N,O);return}}};function l({container:c,branches:h,isEOV:d=!1}){let m=nt(c.events);if(m){let f=lt(m.action,d);n.emit(C.interactives,{subjectId:c.id,subjectName:"container",type:w.actionChoice,actionType:f.type,payload:{invokeImmediately:f.args.shouldOpenNow,...f.args}}),e.interactiveActionChoice$.next({subjectId:c.id,subjectName:"container",type:"action-choice",actionType:f.type,payload:{invokeImmediately:f.args.shouldOpenNow,...f.args}}),i.add({timestamp:d?1/0:c.endTime??1/0,priority:"container",initiator:c.id,actionType:I.expect,action:y.bind(null,{subjectId:c.id,subjectName:"container"})}),r.isExpect=!0}else for(let f of c.events??[])s({action:f.action,container:c,branches:h,isEOV:d})}let p=({chapterId:c,action:h,branches:d=[]})=>{let m=n.emit.bind(n,C.interactives,{subjectId:c,subjectName:"chapter",type:w.actionChoice,actionType:h.type,payload:h.args}),f=()=>{e.interactiveActionChoice$.next({subjectId:c,subjectName:"chapter",type:"action-choice",actionType:h.type,payload:h.args})};switch(h.type.trim().toLowerCase()){case I.setNextBranch.trim().toLowerCase():{let v=d.find(T=>T.id===h.args.branchId);return v?.chapterId?(m(),f(),F.bind(null,{subjectId:c,subjectName:"chapter",action:h,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setWeightlessRandomBranch.trim().toLowerCase():{let v=Gt(d);return v?.chapterId?(m(),f(),F.bind(null,{subjectId:c,subjectName:"chapter",action:h,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setRandomBranch.trim().toLowerCase():{let v=Ut(d);return v?.chapterId?(m(),f(),F.bind(null,{subjectId:c,subjectName:"chapter",action:h,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setMaxWeightBranch.trim().toLowerCase():{let v=Wt(d);return v?.chapterId?(m(),f(),F.bind(null,{subjectId:c,subjectName:"chapter",action:h,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.setMinWeightBranch.trim().toLowerCase():{let v=zt(d);return v?.chapterId?(m(),f(),F.bind(null,{subjectId:c,subjectName:"chapter",action:h,payload:{chapterId:v.chapterId,autoSelect:!0}})):void 0}case I.continuePlayback.trim().toLowerCase():return m(),f(),M.bind(null,{subjectId:c,subjectName:"chapter",action:h});case I.openURI.trim().toLowerCase():return m(),f(),A.bind(null,{subjectId:c,subjectName:"chapter",action:h,payload:{URI:h.args.uri}});default:{let v="Unexpected chapter event",T=new P(1,1,{message:v});u(T,v);return}}};function u(c,h){console.error(h),e.error$.next(c),n.emit(C.errors,c)}function b(c){let h=nt(c.events);if(h){if(B(c))return;n.emit(C.interactives,{subjectId:c.id,subjectName:"chapter",type:w.actionChoice,actionType:h.action.type,payload:h.action.args}),e.interactiveActionChoice$.next({subjectId:c.id,subjectName:"chapter",type:"action-choice",actionType:h.action.type,payload:h.action.args}),i.add({timestamp:1/0,priority:"chapter",initiator:c.id,actionType:I.expect,action:y.bind(null,{subjectId:c.id,subjectName:"chapter"})})}else c.events?.forEach(d=>{let m=p({chapterId:c.id,action:d.action,branches:c.branches});m&&i.add({timestamp:1/0,priority:"chapter",initiator:c.id,actionType:d.action.type,action:m})})}let y=({subjectId:c,subjectName:h})=>{t.pause(),n.emit(C.interactives,{subjectId:c,subjectName:h,type:w.actionExecution,actionType:I.expect}),e.interactiveActionExecution$.next({subjectId:c,subjectName:h,type:"action-execution",actionType:I.expect})},E=({subjectId:c,subjectName:h})=>{t.info.isEnded$.getValue()?i.execEndOfVideo():t.play(),n.emit(C.interactives,{subjectId:c,subjectName:h,type:w.actionExecution,actionType:qt}),e.interactiveActionExecution$.next({subjectId:c,subjectName:h,type:"action-execution",actionType:qt})},M=({subjectId:c,subjectName:h,subjectType:d,action:m})=>{n.emit(C.interactives,{subjectId:c,subjectName:h,subjectType:d,type:w.actionExecution,actionType:m.type}),e.interactiveActionExecution$.next({subjectId:c,subjectName:h,subjectType:d,type:"action-execution",actionType:m.type})},F=({subjectId:c,subjectName:h,subjectType:d,action:m,payload:f})=>{f.behaviour="change-chapter",n.emit(C.interactives,{subjectId:c,subjectName:h,subjectType:d,type:w.actionExecution,actionType:m.type,payload:f}),e.interactiveActionExecution$.next({subjectId:c,subjectName:h,subjectType:d,type:"action-execution",actionType:m.type,payload:f})},x=({subjectId:c,subjectName:h,subjectType:d,action:m,payload:f})=>{f.behaviour="change-manifest",n.emit(C.interactives,{subjectId:c,subjectName:h,subjectType:d,type:w.actionExecution,actionType:m.type,payload:f}),e.interactiveActionExecution$.next({subjectId:c,subjectName:h,subjectType:d,type:"action-execution",actionType:m.type,payload:f})},A=({subjectId:c,subjectName:h,subjectType:d,action:m,payload:f})=>{if(!f.URI)return;let v=window.open(f.URI,"_blank","noopener,noreferrer");v&&(v.opener=null),n.emit(C.interactives,{subjectId:c,subjectName:h,subjectType:d,type:w.actionExecution,actionType:m.type}),e.interactiveActionExecution$.next({subjectId:c,subjectName:h,subjectType:d,type:"action-execution",actionType:m.type})};return{onControlEvent:a,onContainerEvent:s,onChapterEvent:p,onExpectEvent:y,expectEventHandler:E,setManifestChapterEvents:b,setManifestContainerEvents:l,stopExpect:o,state:r}};import{Subscription as Oi,Subject as ht,ValueSubject as pe}from"@vkontakte/videoplayer-shared/evergreen";var ct=(n,e)=>{let t={};return n.map(i=>{if(!t[i]){let r=e.chapters.find(a=>a.id===i);if(!r)return null;let o=e.media.videos.find(a=>r.videoId===a.id);if(!o)return null;t[i]=Yt(o)}return t[i]}).filter(Boolean)},Li=n=>{for(let e of n.variants)if($i(e)&&e.payload)return e.payload.id},$i=n=>!!(n.type==="custom"&&n.payload&&n.payload.type==="vk"),Yt=n=>{let e=Li(n);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},Fi=(n,e)=>{for(let t of n.media.videos)if(e===Yt(t)){for(let i of n.chapters)if(i.videoId===t.id)return i.id;return}},Jt=(n,e)=>n.reduce((t,i)=>{let r=Fi(e,i);return r?[...t,r]:t},[]);var de=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:i,historyApi:r,settings:o}){this.state={history$:new pe([]),hasPrevChapter$:new pe(!1),prevChapter$:new pe(null),isInitialChapter$:new pe(!1),isGoBackLimited$:new pe(!1)};this.#i=null;this.#s=!1;this.#e=null;this.#h=null;this.events={inited$:new ht,destroyed$:new ht,error$:new ht};this.#n=null;this.#r=null;this.#t=null;this.#a=new Oi;this.#l=!1;this.#c=0;this.#n=t,this.#t=e,this.#r=i,this.#i=r,this.#o=o,this.state.history$&&this.#a&&this.#a?.add(this.state.history$.subscribe(a=>{this.state.prevChapter$.next(a.at(-2)||null),this.state.hasPrevChapter$.next(a.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#e?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#c===this.#o.maxLength-1)}))}#i;#o;#s;#e;#h;#n;#r;#t;#a;#l;#c;async setManifest(e){if(!this.#r||!this.#t)return;this.#e=e,await this.getProjectHistory();let t=this.getInitialChapterId();await this.#r.setChapter({chapterId:t,pushToHistory:!1}),this.#s||(this.#s=!0,this.events.inited$.next({initChapterId:t}))}get inited(){return this.#s}async updateHistory(e,t=!0){if(!this.#e)return;this.#l?(this.#l=!1,this.#c++):this.#c=0;let i=this.#e,r=e.length-this.#o.maxLength,o=r>0?e.slice(r):e,a=ct(o,i);if(this.#h=a,this.state.history$.next(o),!(!t||!this.#i||!this.#n))try{await this.#i.save(this.#n,a)}catch{let l=new P(1,5,"Unable to save interactive history");this.events.error$.next(l),this.#t?.emit(C.errors,l)}}async goBack(){if(!this.state||!this.#r){let i=new P(1,5,"Unable to save interactive history");return this.events.error$.next(i),this.#t?.emit(C.errors,i)}this.#l=!0;let e=this.state.history$.getValue().slice(0,-1),t=e.pop();this.state.history$.next(e),await this.#r.setChapter({chapterId:t,playPrev:!0})}async getProjectHistory(){if(!this.#e||!this.#n)return;let e=this.#e,t=[this.getInitialVideoId()];if(this.#i)try{let r=await this.#i.get(this.#n);r.length&&(t=r)}catch{let o=new P(1,5,"Error while trying to fetch data");this.events.error$.next(o),this.#t?.emit(C.errors,o)}let i=Jt(t,e);this.state.history$.next(i)}getInitialChapterId(){return this.state.history$.getValue()?.at(-1)||this.#o.initChapterId||this.#e?.metadata.initChapterId}getInitialVideoId(){if(this.#e){let e=this.getInitialChapterId();return ct([e],this.#e).pop()}return null}destroy(){this.#n=null,this.#i=null,this.#r=null,this.#a?.unsubscribe(),this.#a=null,this.#s=!1,this.#t?.emit(C.historyDestroyed),this.events.destroyed$.next(),this.#t=null}};var De=class{constructor(){this._prevSizeId=0;this.rootElement=document.createElement("canvas")}clear(){this.rootElement.getContext("2d")?.clearRect(0,0,this.rootElement.width,this.rootElement.height)}isImageDrawn(){let e=this.rootElement.getContext("2d")?.getImageData(0,0,this.rootElement.width,this.rootElement.height);if(!e)return!1;let t=e.data,i=t.length;for(let r=3;r<i;r+=40)if(t[r]!==0)return!0;return!1}destroy(){this.rootElement.remove()}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}setCanvasImageSource(e){this.canvasImgSrc=e}draw(){this.canvasImgSrc&&this.rootElement.getContext("2d")?.drawImage(this.canvasImgSrc,0,0,this.rootElement.width,this.rootElement.height)}async updateCanvasDimensions(e,t=!1){let i=e.width+e.height;if(this._prevSizeId===i)return;let r;t&&(r=await this.save()),this.rootElement.width=e.width,this.rootElement.height=e.height,t&&r&&this.restore(r),this._prevSizeId=i}async save(){let e=this.rootElement.toDataURL("image/jpeg",1),t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}restore(e){this.rootElement&&this.rootElement.getContext("2d")?.drawImage(e,0,0,this.rootElement.width,this.rootElement.height)}};var _e=class{constructor({parentElement:e,endOffsetMs:t=250,onError:i}){this.currentVideoDurationMs=1/0;this._containerTimeFrameShouldReceived=!1;this._endTimeFrameReceived=!1;this._shouldCallSkip=!1;this.onEachTick=e=>{let t=e??this.lastFrameCanvas.canvasImgSrc.currentTime*1e3,i=this.isChapterEndTime(t);if(this.isContainerTime(t))this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!0,this._shouldCallSkip=!0;else if(i)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,241 @@ var ut="1.0.30-dev.9aa27113.0";function Ge(i,e=1){let t="0",n="0",r="0";return i
|
|
|
11
11
|
height: var(--interactive-height);
|
|
12
12
|
background-color: var(--black);
|
|
13
13
|
visibility: hidden;
|
|
14
|
-
`,this.lastFrameCanvas=new
|
|
14
|
+
`,this.lastFrameCanvas=new De,this.endOffsetMs=t,this._callbacks={onError:i},this.lastFrameCanvas.rootElement.style.cssText=`
|
|
15
15
|
position: absolute;
|
|
16
16
|
top: 50%;
|
|
17
17
|
left: 50%;
|
|
18
18
|
transform: translate(-50%, -50%);
|
|
19
|
-
`,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);let t=getComputedStyle(this.rootElement),
|
|
19
|
+
`,this.rootElement.prepend(this.lastFrameCanvas.rootElement),e.prepend(this.rootElement)}destroy(){this.hide(),this.reset(),this._callbacks=void 0,this.lastFrameCanvas.destroy(),this.rootElement.remove()}setVideoDuration(e){this.currentVideoDurationMs=e}setVideoElement(e){this.lastFrameCanvas.setCanvasImageSource(e)}setCurrentChapter(e){this.currentChapter=e}show(){this.rootElement.style.visibility="visible"}hide(){this.rootElement.style.visibility="hidden"}async updateCanvasDimensions(e=!1){this._containerTimeFrameShouldReceived||this._endTimeFrameReceived||(e=!1);let t=getComputedStyle(this.rootElement),i={width:parseFloat(t.getPropertyValue("--interactive-content-width")),height:parseFloat(t.getPropertyValue("--interactive-content-height"))};try{this.lastFrameCanvas.updateCanvasDimensions(i,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}};function ei(n=0){return new Promise(e=>{setTimeout(()=>{e(0)},n)})}var Ni=`
|
|
20
|
+
.interactive-fillAnimationElement {
|
|
20
21
|
position: absolute;
|
|
22
|
+
overflow: hidden;
|
|
23
|
+
z-index: -1;
|
|
24
|
+
pointer-events: none;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
.interactive-fillAnimationElement-filler-wrapper {
|
|
28
|
+
position: absolute;
|
|
29
|
+
width: 100%;
|
|
30
|
+
height: 100%;
|
|
31
|
+
transform-origin: center;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
.interactive-fillAnimationElement-filler-wrapper.fillWidth {
|
|
35
|
+
top: 0;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
.interactive-fillAnimationElement-filler-wrapper.fillHeight {
|
|
39
|
+
left: 0;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
.interactive-fillAnimationElement-filler-wrapper.fromRight {
|
|
43
|
+
right: 0;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
.interactive-fillAnimationElement-filler-wrapper.fromLeft {
|
|
47
|
+
left: 0;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
.interactive-fillAnimationElement-filler-wrapper.fromTop {
|
|
51
|
+
top: 0;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
.interactive-fillAnimationElement-filler-wrapper.fromBottom {
|
|
55
|
+
bottom: 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
.interactive-fillAnimationElement-filler {
|
|
59
|
+
width: 100%;
|
|
60
|
+
height: 100%;
|
|
61
|
+
background-color: rgba(173, 211, 255, 0.32);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
.interactive-fillAnimationElement-filler.fillWidth {
|
|
65
|
+
transform: scaleX(0);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
.interactive-fillAnimationElement-filler.fillHeight {
|
|
69
|
+
transform: scaleY(0);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
.interactive-fillAnimationElement-filler.fromRight {
|
|
73
|
+
transform-origin: right;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
.interactive-fillAnimationElement-filler.fromLeft {
|
|
77
|
+
transform-origin: left;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
.interactive-fillAnimationElement-filler.fromTop {
|
|
81
|
+
transform-origin: top;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
.interactive-fillAnimationElement-filler.fromBottom {
|
|
85
|
+
transform-origin: bottom;
|
|
86
|
+
}
|
|
87
|
+
`,ji=`
|
|
88
|
+
${Ni}
|
|
89
|
+
|
|
90
|
+
.interactive-control {
|
|
91
|
+
display: flex;
|
|
92
|
+
width: 100%;
|
|
93
|
+
height: 100%;
|
|
94
|
+
font-family: inherit;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
.interactive-control-button {
|
|
98
|
+
cursor: pointer;
|
|
99
|
+
position: relative;
|
|
100
|
+
isolation: isolate;
|
|
101
|
+
transition: opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
|
|
102
|
+
opacity: 1;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
.interactive-container:not(.interactive-container-disabled) .interactive-control-button:not(.interactive-control-selected):hover,
|
|
106
|
+
.interactive-container:not(.interactive-container-disabled) .interactive-control-button:not(.interactive-control-selected):focus-visible {
|
|
107
|
+
transition: opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
|
|
108
|
+
opacity: 0.8;
|
|
109
|
+
animation: none;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
.interactive-control-button.interactive-control-selected {
|
|
113
|
+
transition: opacity 100ms ease-in-out;
|
|
114
|
+
opacity: 0.5;
|
|
115
|
+
pointer-events: none;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
.interactive-control-area {
|
|
119
|
+
cursor: pointer;
|
|
120
|
+
opacity: 1;
|
|
121
|
+
box-shadow: none;
|
|
122
|
+
transition: border-color 100ms ease-in-out, box-shadow 100ms ease-in-out, opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
.interactive-container:not(.interactive-container-disabled) .interactive-control-area:not(.interactive-control-selected):hover,
|
|
126
|
+
.interactive-container:not(.interactive-container-disabled) .interactive-control-area:not(.interactive-control-selected):focus-visible {
|
|
127
|
+
transition: opacity 400ms cubic-bezier(0.4, 0, 0.2, 1);
|
|
128
|
+
opacity: 0;
|
|
129
|
+
animation: none;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
.interactive-control-area.interactive-control-selected {
|
|
133
|
+
transition: opacity 100ms ease-in-out;
|
|
134
|
+
opacity: 0;
|
|
135
|
+
pointer-events: none;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
.interactive-container.interactive-container-disabled .interactive-control-button,
|
|
139
|
+
.interactive-container.interactive-container-disabled .interactive-control-area {
|
|
140
|
+
animation: none;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
.interactive-container.interactive-container-before-remove-delay {
|
|
144
|
+
transition-delay: 300ms;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
.interactive-control-before-remove,
|
|
148
|
+
.interactive-container.interactive-container-before-remove {
|
|
149
|
+
transition-property: opacity;
|
|
150
|
+
transition-duration: 100ms;
|
|
151
|
+
transition-timing-function: ease-in-out;
|
|
152
|
+
opacity: 0;
|
|
153
|
+
pointer-events: none;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
.interactive-tap {
|
|
157
|
+
position: absolute;
|
|
158
|
+
aspect-ratio: 1;
|
|
159
|
+
background-color: rgba(255, 255, 255, 0.08);
|
|
160
|
+
border: 1px solid #fff;
|
|
161
|
+
border-radius: 50%;
|
|
162
|
+
transition: opacity 100ms ease-in-out;
|
|
163
|
+
opacity: 0;
|
|
164
|
+
pointer-events: none;
|
|
165
|
+
z-index: 1;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
.interactive-tap-animation {
|
|
169
|
+
animation-duration: 300ms;
|
|
170
|
+
animation-iteration-count: 1;
|
|
171
|
+
animation-timing-function: ease;
|
|
172
|
+
animation-name: bounce;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
@keyframes bounce {
|
|
176
|
+
0%, 100% {
|
|
177
|
+
transform: scale(1);
|
|
178
|
+
}
|
|
179
|
+
50% {
|
|
180
|
+
transform: scale(0.3);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
.interactive-container:not(.interactive-container-disabled) .interactive-tap-visible {
|
|
185
|
+
opacity: 1;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
.interactive-control-cta-area {
|
|
189
|
+
animation-duration: 2001ms;
|
|
190
|
+
animation-iteration-count: infinite;
|
|
191
|
+
animation-timing-function: cubic-bezier(0.3, 0.3, 0.3, 1);
|
|
192
|
+
animation-name: blinking-1;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
@keyframes blinking-1 {
|
|
196
|
+
0%, 100% {
|
|
197
|
+
opacity: 1;
|
|
198
|
+
}
|
|
199
|
+
50% {
|
|
200
|
+
opacity: 0;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
.interactive-control-cta-button {
|
|
205
|
+
animation-duration: 2001ms;
|
|
206
|
+
animation-iteration-count: infinite;
|
|
207
|
+
animation-timing-function: cubic-bezier(0.3, 0.3, 0.3, 1);
|
|
208
|
+
animation-name: blinking-2;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
@keyframes blinking-2 {
|
|
212
|
+
0%, 100% {
|
|
213
|
+
opacity: 1;
|
|
214
|
+
}
|
|
215
|
+
50% {
|
|
216
|
+
opacity: 0.8;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
.interactive-container {
|
|
221
|
+
opacity: 1;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
.interactive-container * {
|
|
225
|
+
box-sizing: border-box;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
.interactive-container-before-show {
|
|
229
|
+
transition: opacity 100ms ease-in-out;
|
|
230
|
+
opacity: 0.5;
|
|
231
|
+
pointer-events: none;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
.interactive-container-disabled {
|
|
235
|
+
transition: opacity 100ms ease-in-out;
|
|
236
|
+
opacity: 0.5;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
.interactive-blink-reference-animation {
|
|
240
|
+
position: absolute;
|
|
241
|
+
height: 0;
|
|
242
|
+
width: 0;
|
|
21
243
|
top: 0;
|
|
22
244
|
left: 0;
|
|
23
|
-
`,i}var _e=class{constructor(e){this.subscription=new pt;this.globalEventEmitter=new Ae;this.eventsSubs=new pt;this.animation=new Re;this.eventManager=new je;this.seekToInteractiveController=new ie;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=Rn();this.factories=new Map([["choice",be]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new pt;this.graph=null;this.lastFrame=null;this.appState=0;this.state={prevChapter$:new L(null),isInitialChapter$:new L(!1),isFirstChapter$:new L(!0),isEndChapter$:new L(!1),isInteractiveExpectation$:new L(!1),isReplay$:new L(!1),calledByInteractive$:new L(!1),lastChapterChangeWasInitiatedByInteractive$:new L(!1),disabledControls$:new L(!1),interactiveRanges$:new L([]),isInteractiveTime$:new L(!1),statistics$:new L(null),isSeekable$:new L(!1)};this.events={noInteraction$:new $,graphVisibilityChanged$:new $,watchAgainIsClicked$:new $,chapterChanged$:new $,playerChanged$:new $,error$:new $,eachTick$:new $,manifestChanged$:new $,interactiveRangeEnded$:new $,interactiveContainerRemoved$:new $,interactiveActionExecution$:new $,interactiveActionChoice$:new $,interactiveVisibilityChanged$:new $};this.emitErrorEvent=e=>{this.events.error$.next(e),this.globalEventEmitter.emit(f.errors,e)};this.clearHistoryIfEnded=()=>{let e=this.player?.info.isEnded$.getValue(),t=this.state.isInteractiveExpectation$.getValue(),{chapter:n}=this.getCurrentChapter();e&&n&&F(n)&&!t&&this.historyController.updateHistory([]),window.removeEventListener("beforeunload",this.clearHistoryIfEnded)};this.handleSeamlessPlayerChanged=e=>{if(!e)return;let{statistics:t,...n}=e;if(t){let{statSubscription:r,oneStat:s}=t;r.add(s.attachToInteractive(this.getStatEvents())),this.state.statistics$.next(t)}this.state.isReplay$.getValue()&&this.state.isReplay$.next(!1),this.events.playerChanged$.next(n),this.globalEventEmitter.emit(f.playerChanged,n)};this.onPlaybackStarted=()=>{this.resizeManager?.calc(),this.animation.requestAnimation()};this.removeControllers=(e=!0)=>{this.gameControllers.forEach(t=>{!e&&t.isPermanentText||(this.animation.removeFn(t.whilePlaying),t.destroy())})};this.completeInteractiveRange=e=>{let{interactiveRanges$:t}=this.state,r=t.getValue().map(s=>({...s,subjects:s.subjects.filter(c=>c!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};this._options={...qt,...e,config:{...qt.config,...e.config}},this._options.parentElement.append(this.rootElement),this.historyController=new ce({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 Be({parentElement:this._options.parentElement,onError:t=>{let n=new M(1,6,t);this.emitErrorEvent(n)}})),this.eventManager.listen(this.rootElement,"mousedown",t=>t.stopPropagation()),this.eventManager.listen(this.rootElement,"mouseup",t=>t.stopPropagation()),this.manifestController=new Y(this._options.loaders,t=>{let n=new M(1,3,t);this.emitErrorEvent(n)}),this.resizeManager=Ot(()=>({player:this.player,parentElement:this._options?.parentElement,fns:this._options?.lastFrame?[()=>{this.lastFrame?.updateCanvasDimensions(!0)}]:[]})),this._options.graph&&(this.graph=new ne({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.globalEventEmitter.emit(f.graph,{type:ae.watchAgainClicked,chapterId:t}),this.events.watchAgainIsClicked$.next(t)},onError:t=>{let n=new M(1,4,{message:t});this.emitErrorEvent(n)}})),this.initSubscriptions()}initSubscriptions(){this.subscription.add(this.historyController.events.inited$.subscribe(async({videosInfo:e=[]})=>{this._options.initSeamless&&(await this.initSeamless(),this.updateGraphVideosInfo(e))})),this.eventsSubs.add(this.events.interactiveContainerRemoved$.subscribe(({subjectId:e})=>{this.completeInteractiveRange(e)})).add(this.events.interactiveActionExecution$.subscribe(e=>{if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){let{chapterId:t}=e.payload;this.setChapter({chapterId:t}),this.state.isFirstChapter$.getValue()&&this.state.isFirstChapter$.next(!1)}else if(e.payload?.behaviour==="change-manifest"){let{manifestURL:t}=e.payload;t&&this.setManifest(t)}e.actionType==="expect"?this.state.isInteractiveExpectation$.next(!0):e.actionType==="after-expect"&&this.state.isInteractiveExpectation$.next(!1)})),this.eventsSubs.add(this.events.manifestChanged$.subscribe(()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}))}async initSeamless(){this.seamlessController=at(this),this.seamlessControllerSubs.add(this.seamlessController.activePlayerChanged.subscribe(this.handleSeamlessPlayerChanged)),await this.seamlessController.init()}handlePositionChange(e){(!this.graph||this.graph.isHidden)&&this.checkIfSeekable();let t=e*1e3,r=this.getInteractiveRanges().reverse().find(({range:s})=>t>=s[1]);if(r){let s=r.range.join("-");this.endedRanges.has(s)||(this.endedRanges.add(s),this.globalEventEmitter.emit(f.interactives,{type:w.rangeEnded,payload:r,visibility:!0}),this.events.interactiveRangeEnded$.next({type:"range-ended",payload:r}))}}registerVideoEvents(){this.player&&(window.removeEventListener("beforeunload",this.clearHistoryIfEnded),this.subscription.unsubscribe(),window.addEventListener("beforeunload",this.clearHistoryIfEnded),this.subscription.add(this.player.events.started$.pipe(An()).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(e=>this.state.prevChapter$.next(e))).add(Sn({position:this.player.info.position$,interactiveRanges:this.state.interactiveRanges$,isInteractiveExpectation:this.state.isInteractiveExpectation$}).subscribe(({position:e,interactiveRanges:t,isInteractiveExpectation:n})=>{let r;if(n)r=!0;else{let o=e*1e3;r=!!t.find(({range:[g,T],subjects:S})=>g<o&&o<T&&S.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.subscription.add(this.historyController.events.error$.subscribe(this.events.error$)),this._options.lastFrame&&this.subscription.add(this.player.info.duration$.subscribe(e=>{this.lastFrame?.setVideoDuration(e*1e3)})).add(this.player.experimental.element$.subscribe(e=>{e&&this.lastFrame?.setVideoElement(e)})).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 e=this.manifestController.chapter;e&&this.appState===1&&(this.selectBranches?.setManifestChapterEvents(e),this.gameControllers=this.filterGameControllers(e),this.interactiveEvents?.containersEventsCallState.setData(e.containers),this.seekToInteractiveController.setContainers(this.gameControllers.map(t=>t.container.container).filter(t=>!q(t.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(e){let t=[];return e.containers.forEach(n=>{let r=n.type.trim().toLowerCase(),c=this.factories.get(r)?.(n,this.rootElement);if(c&&this.selectBranches&&this.interactiveEvents&&this.player){let a=new Le({player:this.player,container:c,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,ignoreContainerEvent:()=>Rt(n,this.gameControllers),permanentTextControls:this._options.permanentTextControls,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(n.id)}});this.animation.addFn(a.whilePlaying,!0),t.push(a)}}),t}checkIfSeekable(){if(this.state.isInteractiveExpectation$.getValue()){this.state.isSeekable$.next(!1);return}let t=this.state.isSeekable$.getValue(),n=!!this.seekToInteractiveController.getNextInteractiveTime();(n&&!t||!n&&t)&&this.state.isSeekable$.next(!t)}updateLastEventInfo(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}pushChapterToHistory(e){if(this.updateLastEventInfo(),!this.historyController.inited)return;let t=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),n=this.state.prevChapter$.getValue(),r=(n&&F(n)&&$e(n))??!1,s=this.manifestController.manifest?.metadata.initChapterId===e,c=this.historyController.state.history$.getValue();if(s||r&&t){this.historyController.updateHistory([e]);return}c.at(-1)!==e&&this.historyController.updateHistory([...c,e])}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(e){this.reset(),this.isFirstChapterFetched=!1;let t=await this.manifestController.setManifest(e);if(t.manifest)return this.graph&&this.graph.handleManifestChange(t.manifest),await this.historyController.setManifest(t.manifest),this.events.manifestChanged$.next(t.manifest),this.globalEventEmitter.emit(f.manifestChanged,{manifest:t.manifest}),this.setGameControllers(),t.manifest}setPlayer(e){this.reset(),this.player=e,this.seekToInteractiveController.setPlayer(this.player),this.interactiveEvents?this.interactiveEvents.setPlayer(this.player):this.interactiveEvents=$t(this.player),this.selectBranches=Wt({player:this.player,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,removeControllers:()=>this.removeControllers(!1)}),this.appState===1&&(this.registerVideoEvents(),this.setGameControllers())}async setChapter({chapterId:e,pushToHistory:t=!0,playPrev:n=!1}={}){this.reset(),this.lastFrame&&this.isFirstChapterFetched&&(this.lastFrame.draw(),this.lastFrame.show()),xn.isSafari&&await Xt(35);let r=!n&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:s,media:c,graph:a}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!s||!c)&&(t&&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:c}),this.globalEventEmitter.emit(f.chapterChanged,{chapter:s,media:c,graph:a}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new Zt(e=>{this.eventsSubs.add(this.events.graphVisibilityChanged$.subscribe(t=>{e.next(t?pe.GRAPH_SHOW:pe.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{e.next(pe.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:n,subjectType:r})=>{t!=="action-choice"||n!=="control"||(r==="Button"&&e.next(pe.NEXT_BUTTON),r==="Area"&&e.next(pe.NEXT_AREA))}))}),nextMovie$:new Zt(e=>{this.events.playerChanged$.subscribe(({config:t})=>{t?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&e.next(t.unitedVideoId)})})}}toggleGraphView(e=!0){this.graph&&(e?(this.graph.show(),this.state.isSeekable$.next(!1)):(this.graph.hide(),this.checkIfSeekable()),this.globalEventEmitter.emit(f.graph,{type:ae.visibility,visibility:e}),this.events.graphVisibilityChanged$.next(e))}setVisitedChapters(e){Array.isArray(e)&&this.graph?.setVisitedChapters(e)}updateGraphVideosInfo(e){Array.isArray(e)&&this.graph?.updateVideosInfo(e)}deadEndCheck(){return!(this.interactiveEvents?.getPreparedToExecActions()||[]).some(n=>n.actionType===I.setNextBranch)}allControlsAreRemoved(){return!this.gameControllers.some(t=>!t.container.isRemoved)}isEndedExpectation(){if(!this.player||!this.gameControllers)return!1;let e=this.player.info.position$.getValue(),t=this.player.info.duration$.getValue();return e===t&&this.gameControllers.some(n=>{let r=n.container.container;return!n.container.isRemoved&&r.endTime===null&&Q(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&Se(e.metadata.version)}getInitialVideoInfo(){return{videoId:this.historyController.getInitialVideoId(),chapterId:this.historyController.getInitialChapterId()}}getHistoryState(){return this.historyController.state}getIsSeekable(){return this.state.isSeekable$}getInteractiveRanges(){return Vt(this.manifestController.chapter?.containers)}getNextInteractiveStartTime(e){return this.seekToInteractiveController.getNextInteractiveTime(e)}getChapterBranches(e){return this.manifestController.getBranches(e)}getCurrentChapter(){return this.manifestController.getCurrent()}getCurrentManifest(){return this.manifestController.manifest}on(e,t){return this.globalEventEmitter.on(e,t),this}off(e,t){return this.globalEventEmitter.off(e,t),this}once(e,t){return this.globalEventEmitter.once(e,t),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.eventsSubs.unsubscribe(),this.globalEventEmitter.reset(),this.lastFrame?.destroy(),this.rootElement.remove(),this.historyController.destroy(),this.isFirstChapterFetched=!1,this.appState=3}};var Mn={Container:Z,createChoiceContainer:be,createAreaControl:ye,createButtonControl:ge,getRootEl:he,classnamesPrefix:P};var Us={version:ut};export{_i as ContainerTypes,we as ControlTypes,M as CustomError,f as EVENT_NAMES,I as EventActionTypes,Hi as EventTypes,_e as Interactives,Y as ManifestController,Us as SDKInfo,lt as chapterIdsToVKVideoIds,Ye as compareVersions,$i as containerTypes,Li as controlTypes,Oi as eventActionTypes,Ni as eventTypes,In as getChapterIdByVkVideoId,Qt as getVKVideoIdByMedia,bn as getVideoRawIdByMedia,ae as graphEventTypes,$e as hasEndTemplate,w as interactivesEventTypes,Pi as isAreaControl,Vi as isButtonControl,F as isLastChapter,q as isOneTextCtrlContainer,Se as isSupportedManifest,xe as isTextControl,En as isVKVariantItem,Tt as isValidManifest,xt as migrateManifestToLatestVersion,Mn as utils,Kt as vkVideoIdsToChapterIds};
|
|
245
|
+
pointer-events: none;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
.interactive-blink-reference-disable-animation {
|
|
249
|
+
animation: none;
|
|
250
|
+
}
|
|
251
|
+
`,ti=n=>{let e=document.createElement("style");e.textContent=ji,n.prepend(e)};var Bi=typeof window>"u",Di=typeof OffscreenCanvas<"u";function ii(){return Bi?Di?new OffscreenCanvas(1,1):null:document.createElement("canvas")}function ni(n){return(n[0]*299+n[1]*587+n[2]*114)/1e3<128}var pt=[0,0,0,0],ri=1,_i="AverageColor: ";function dt(n){return Error(_i+n)}function ut(n){let e=window.getComputedStyle(n),t=parseFloat(e.getPropertyValue("--interactive-content-width"))||0,i=parseFloat(e.getPropertyValue("--interactive-content-height"))||0;return{width:t,height:i}}var ue=class{constructor(){this.canvas=null;this.ctx=null}getColorAsync(e,t){let i=this.getColor(e,t);return i.error?Promise.reject(i.error):Promise.resolve(i)}getColor(e,t){let i={...t,step:t.step||ri,defaultColor:t.defaultColor??pt,debug:t.debug??!1};if(!this.canvas&&(this.canvas=ii(),!this.canvas))return this.prepareResult(i.defaultColor,dt("Failed to create canvas"));if(!this.ctx){if(this.ctx=this.canvas.getContext("2d",{willReadFrequently:!0}),!this.ctx)return this.prepareResult(i.defaultColor,dt("Failed to create context of the canvas"));this.ctx.imageSmoothingEnabled=!1}this.canvas.width=i.width,this.canvas.height=i.height;try{this.ctx.clearRect(0,0,i.width,i.height),this.ctx.drawImage(e,0,0,i.width,i.height);let r=this.ctx.getImageData(0,0,i.width,i.height).data,o=this.getColorFromArray(r,i);return this.prepareResult(o)}catch(r){return i.debug&&console.error(r),this.prepareResult(i.defaultColor,new Error("Failed on getting average color"))}}getColorFromArray(e,t){let r=e.length;if(r<4)return pt;let o=r-r%4,a=t.step*4;return this.sqrtAlgorithm(e,o,{defaultColor:t.defaultColor,step:a})}sqrtAlgorithm(e,t,i){let r=0,o=0,a=0,s=0,l=0,p=i.step;for(let u=0;u<t;u+=p){let b=e[u],y=e[u+1],E=e[u+2],M=e[u+3];r+=b*b*M,o+=y*y*M,a+=E*E*M,s+=M,l++}return s?[Math.round(Math.sqrt(r/s)),Math.round(Math.sqrt(o/s)),Math.round(Math.sqrt(a/s)),Math.round(s/l)]:i.defaultColor}prepareResult(e,t){let i=[e[0],e[1],e[2],e[3]/255],r=ni(e);return{rgba:"rgba("+i.join(",")+")",isDark:r,error:t}}destroy(){this.canvas&&(this.canvas.width=1,this.canvas.height=1,this.canvas=null),this.ctx=null}};var oi=()=>{let n=document.createElement("div");return n.classList.add("interactive-blink-reference-animation","interactive-control-cta-button"),n},si=n=>{n.classList.add("interactive-blink-reference-disable-animation"),requestAnimationFrame(()=>{n.classList.remove("interactive-blink-reference-disable-animation")})};var ci=Object.freeze({lang:Wi.RU,loaders:{},graph:!1,initSeamless:!1,lastFrame:!1,permanentTextControls:!0,config:{historyMaxLength:100,noInteractionEventTimeout:3e4},buttonControlInteractiveTimeTimer:!0,areaControlFrameBasedShadow:!0,tapPlaceShow:!0,controlsCTAAnimation:!0,controlsShowAnimation:!0,controlsHideAnimation:!0});function Ui(){let n=document.createElement("div");return n.classList.add("interactive-chapter"),n}var ze=class{constructor(e){this.playerSubscriptions=new He;this.subscriptions=new He;this.globalEventEmitter=new Ve;this.eventsSubs=new He;this.animation=new Pe;this.seekToInteractiveController=new ae;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=Ui();this.factories=new Map([["choice",Me]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new He;this.graph=null;this.lastFrame=null;this.frameAverageColor=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 L,graphVisibilityChanged$:new L,watchAgainIsClicked$:new L,chapterChanged$:new L,playerChanged$:new L,error$:new L,eachTick$:new L,manifestChanged$:new L,interactiveRangeEnded$:new L,interactiveContainerRemoved$:new L,interactiveActionExecution$:new L,interactiveActionChoice$:new L,interactiveVisibilityChanged$:new L};this.emitErrorEvent=e=>{this.events.error$.next(e),this.globalEventEmitter.emit(C.errors,e)};this.clearHistoryIfEnded=()=>{let e=this.player?.info.isEnded$.getValue(),t=this.state.isInteractiveExpectation$.getValue(),{chapter:i}=this.getCurrentChapter();e&&i&&B(i)&&!t&&this.historyController.updateHistory([]),window.removeEventListener("beforeunload",this.clearHistoryIfEnded)};this.handleSeamlessPlayerChanged=e=>{if(!e)return;let{statistics:t,...i}=e;if(t){let{statSubscription:r,oneStat:o}=t;r.add(o.attachToInteractive(this.getStatEvents())),this.state.statistics$.next(t)}this.state.isReplay$.getValue()&&this.state.isReplay$.next(!1),this.events.playerChanged$.next(i),this.globalEventEmitter.emit(C.playerChanged,i)};this.onPlaybackStarted=()=>{this.resizeManager?.calc(),this.animation.requestAnimation()};this.removeGameControllersViews=({includeTextControls:e=!0}={})=>{for(let t of this.gameControllers)!e&&t.isPermanentText||(this.animation.removeFn(t.whilePlaying),t.removeView())};this.destroyGameControllers=({includeTextControls:e=!0}={})=>{for(let t of this.gameControllers)!e&&t.isPermanentText||(this.animation.removeFn(t.whilePlaying),t.destroy())};this.completeInteractiveRange=e=>{let{interactiveRanges$:t}=this.state,r=t.getValue().map(o=>({...o,subjects:o.subjects.filter(a=>a!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};this._options={...ci,...e,config:{...ci.config,...e.config}},this._options.controlsCTAAnimation&&this.rootElement.append(oi()),this._options.parentElement.append(this.rootElement),this.historyController=new de({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 _e({parentElement:this._options.parentElement,onError:i=>{let r=new P(1,6,i);this.emitErrorEvent(r)}})),ti(this._options.parentElement),this.subscriptions.add(li(this.rootElement,"mousedown").subscribe(i=>i.stopPropagation())).add(li(this.rootElement,"mouseup").subscribe(i=>i.stopPropagation())),this.manifestController=new J(this._options.loaders,i=>{let r=new P(1,3,i);this.emitErrorEvent(r)});let t=[];this._options.lastFrame&&t.push(()=>{this.lastFrame?.updateCanvasDimensions(!0)}),this._options.buttonControlInteractiveTimeTimer&&t.push(()=>{if(this.state.isInteractiveTime$.getValue())for(let i of this.gameControllers)i.container.onResize()}),this.resizeManager=_t(()=>({player:this.player,parentElement:this._options.parentElement,fns:t})),this._options.graph&&(this.graph=new se({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:i=>{this.setChapter({chapterId:i}),this.globalEventEmitter.emit(C.graph,{type:he.watchAgainClicked,chapterId:i}),this.events.watchAgainIsClicked$.next(i)},onError:i=>{let r=new P(1,4,{message:i});this.emitErrorEvent(r)}})),this._options.areaControlFrameBasedShadow&&(this.frameAverageColor=new ue),this.initSubscriptions()}async getVideoFrameAverageColorInfo(){if(!this.frameAverageColor||!this.player)return;let e=this.player.experimental.element$.getValue();if(!e||!e.readyState)return;let t=ut(this.rootElement);if(!(!t.width||!t.height))try{return await this.frameAverageColor.getColorAsync(e,{width:t.width,height:t.height})}catch(i){return console.error(i),{error:"Getting video frame average color failed"}}}initSubscriptions(){this.playerSubscriptions.add(this.historyController.events.inited$.subscribe(async({videosInfo:e=[]})=>{this._options.initSeamless&&(await this.initSeamless(),this.updateGraphVideosInfo(e))})),this.subscriptions.add(this.events.interactiveContainerRemoved$.subscribe(({subjectId:e})=>{this.completeInteractiveRange(e)})).add(this.events.interactiveActionExecution$.subscribe(e=>{if(this.state.calledByInteractive$.next(!0),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!0),e.payload?.behaviour==="change-chapter"){let{chapterId:t}=e.payload;this.setChapter({chapterId:t}),this.state.isFirstChapter$.getValue()&&this.state.isFirstChapter$.next(!1)}else if(e.payload?.behaviour==="change-manifest"){let{manifestURL:t}=e.payload;t&&this.setManifest(t)}e.actionType==="expect"?(this.state.isInteractiveExpectation$.next(!0),this.toggleControlsCTAAnimation({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!0}),this.updateControlsShadowStyles({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!0})):e.actionType==="after-expect"&&(this.state.isInteractiveExpectation$.next(!1),this.toggleControlsCTAAnimation({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!1}),this.updateControlsShadowStyles({subjectName:e.subjectName,subjectId:e.subjectId,isExpect:!1}))})).add(this.events.manifestChanged$.subscribe(()=>{this.state.calledByInteractive$.next(!1),this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)})).add(this.events.interactiveActionChoice$.subscribe(({type:e,subjectName:t,payload:i})=>{e!=="action-choice"||t==="chapter"||"invokeImmediately"in i&&i.invokeImmediately||this.removeGameControllersViews({includeTextControls:!1})}))}getGameControllerContainersWithExpect(e,t=[]){return this.gameControllers.filter(({container:i})=>!t.includes(i.container.id)&&H(i.container.events)&&i.container.endTime===e&&!i.isRemoved&&!i.willRemoved)}execForAllExpectContainers({subjectName:e,subjectId:t,isExpect:i,execFnName:r}){for(let o of this.gameControllers)if(e==="container"&&o.container.container.id===t){o[r](i),this.getGameControllerContainersWithExpect(o.container.container.endTime,[o.container.container.id]).forEach(s=>{s[r](i)});break}}updateControlsShadowStyles({isExpect:e,...t}){this._options.areaControlFrameBasedShadow&&(e?this.getVideoFrameAverageColorInfo().then(i=>{i&&!i.error&&"isDark"in i&&(this._options.parentElement.style.setProperty("--interactive-frame-tone",`${i.isDark?"dark":"light"}`),this.execForAllExpectContainers({...t,isExpect:e,execFnName:"updateControlsShadowStyles"}))}):this.execForAllExpectContainers({...t,isExpect:e,execFnName:"updateControlsShadowStyles"}))}toggleControlsCTAAnimation(e){if(this._options.controlsCTAAnimation){if(e.isExpect){let i=this.rootElement.querySelector(".interactive-blink-reference-animation");i&&si(i)}this.execForAllExpectContainers({...e,execFnName:"toggleControlsCTAAnimation"})}}async initSeamless(){this.seamlessController=at(this),this.seamlessControllerSubs.add(this.seamlessController.activePlayerChanged.subscribe(this.handleSeamlessPlayerChanged)),await this.seamlessController.init()}handlePositionChange(e){(!this.graph||this.graph.isHidden)&&this.checkIfSeekable();let t=e*1e3,r=this.getInteractiveRanges().reverse().find(({range:o})=>t>=o[1]);if(r){let o=r.range.join("-");this.endedRanges.has(o)||(this.endedRanges.add(o),this.globalEventEmitter.emit(C.interactives,{type:w.rangeEnded,payload:r,visibility:!0}),this.events.interactiveRangeEnded$.next({type:"range-ended",payload:r}))}}registerVideoEvents(){this.player&&(window.removeEventListener("beforeunload",this.clearHistoryIfEnded),this.playerSubscriptions.unsubscribe(),window.addEventListener("beforeunload",this.clearHistoryIfEnded),this.playerSubscriptions.add(this.player.events.started$.pipe(Gi()).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(e=>this.state.prevChapter$.next(e))).add(zi({position:this.player.info.position$,interactiveRanges:this.state.interactiveRanges$,isInteractiveExpectation:this.state.isInteractiveExpectation$}).subscribe(({position:e,interactiveRanges:t,isInteractiveExpectation:i})=>{let r;if(i)r=!0;else{let l=e*1e3;r=!!t.find(({range:[u,b],subjects:y})=>u<l&&l<b&&y.length)}r!==this.state.isInteractiveTime$.getValue()&&this.state.isInteractiveTime$.next(r);let o=!!this.noInteractionTimeout,s=this.player?.info.playbackState$.getValue()==="playing"||i;r&&!o&&s?this.noInteractionTimeout=window.setTimeout(()=>{this.events.noInteraction$.next()},this._options.config.noInteractionEventTimeout):o&&!s&&this.clearNoInteractionTimeout()})),this.playerSubscriptions.add(this.historyController.events.error$.subscribe(this.events.error$)),this._options.lastFrame&&this.playerSubscriptions.add(this.player.info.duration$.subscribe(e=>{this.lastFrame?.setVideoDuration(e*1e3)})).add(this.player.experimental.element$.subscribe(e=>{e&&this.lastFrame?.setVideoElement(e)})).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 e=this.manifestController.chapter;e&&this.appState===1&&(this.selectBranches?.setManifestChapterEvents(e),this.gameControllers=this.addGameControllers(e),this.interactiveEvents?.containersEventsCallState.setData(e.containers),this.seekToInteractiveController.setContainers(this.gameControllers.map(t=>t.container.container).filter(t=>!Y(t.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)}addGameControllers(e){let t=[];return e.containers.forEach(i=>{let r=i.type.trim().toLowerCase(),a=this.factories.get(r)?.(i,this.rootElement,{features:{buttonControlInteractiveTimeTimer:this._options.buttonControlInteractiveTimeTimer,areaControlFrameBasedShadow:this._options.areaControlFrameBasedShadow,tapPlaceShow:this._options.tapPlaceShow,controlsShowAnimation:this._options.controlsShowAnimation,controlsCTAAnimation:this._options.controlsCTAAnimation}});if(a&&this.selectBranches&&this.interactiveEvents&&this.player){let s=new je({player:this.player,container:a,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,ignoreContainerEvent:()=>Lt(i,this.gameControllers),permanentTextControls:this._options.permanentTextControls,disabledControls$:this.state.disabledControls$,onRemove:()=>{this.seekToInteractiveController.deleteContainer(i.id)},features:{controlsHideAnimation:this._options.controlsHideAnimation}});this.animation.addFn(s.whilePlaying,!0),t.push(s)}}),t}checkIfSeekable(){if(this.state.isInteractiveExpectation$.getValue()){this.state.isSeekable$.next(!1);return}let t=this.state.isSeekable$.getValue(),i=!!this.seekToInteractiveController.getNextInteractiveTime();(i&&!t||!i&&t)&&this.state.isSeekable$.next(!t)}updateLastEventInfo(){this.state.calledByInteractive$.getValue()?this.state.calledByInteractive$.next(!1):this.state.lastChapterChangeWasInitiatedByInteractive$.next(!1)}pushChapterToHistory(e){if(this.updateLastEventInfo(),!this.historyController.inited)return;let t=this.state.lastChapterChangeWasInitiatedByInteractive$.getValue(),i=this.state.prevChapter$.getValue(),r=(i&&B(i)&&Ne(i))??!1,o=this.manifestController.manifest?.metadata.initChapterId===e,a=this.historyController.state.history$.getValue();if(o||r&&t){this.historyController.updateHistory([e]);return}a.at(-1)!==e&&this.historyController.updateHistory([...a,e])}reset(){this.appState===2&&(this.destroyGameControllers({includeTextControls:!0}),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(e){this.reset(),this.isFirstChapterFetched=!1;let t=await this.manifestController.setManifest(e);if(t.manifest)return this.graph&&this.graph.handleManifestChange(t.manifest),await this.historyController.setManifest(t.manifest),this.events.manifestChanged$.next(t.manifest),this.globalEventEmitter.emit(C.manifestChanged,{manifest:t.manifest}),this.setGameControllers(),t.manifest}setPlayer(e){this.reset(),this.player=e,this.seekToInteractiveController.setPlayer(this.player),this.interactiveEvents?this.interactiveEvents.setPlayer(this.player):this.interactiveEvents=jt(this.player),this.selectBranches=Zt({player:this.player,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter}),this.appState===1&&(this.registerVideoEvents(),this.setGameControllers())}async setChapter({chapterId:e,pushToHistory:t=!0,playPrev:i=!1}={}){this.reset(),this.lastFrame&&this.isFirstChapterFetched&&(this.lastFrame.draw(),this.lastFrame.show()),this.lastFrame&&Hi.isSafari&&await ei(35);let r=!i&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:o,media:a,graph:s}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!o||!a)&&(t&&this.pushChapterToHistory(o.id),this.state.isInitialChapter$.next(this.manifestController.isInitialChapter()),this.state.isEndChapter$.next(this.manifestController.isEndChapter()),this.graph&&this.graph.handleChapterChange(o),this.lastFrame?.setCurrentChapter(o),this.events.chapterChanged$.next({chapter:o,manifestVideo:a}),this.globalEventEmitter.emit(C.chapterChanged,{chapter:o,media:a,graph:s}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new ai(e=>{this.subscriptions.add(this.events.graphVisibilityChanged$.subscribe(t=>{e.next(t?me.GRAPH_SHOW:me.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{e.next(me.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:i,subjectType:r})=>{t!=="action-choice"||i!=="control"||(r==="Button"&&e.next(me.NEXT_BUTTON),r==="Area"&&e.next(me.NEXT_AREA))}))}),nextMovie$:new ai(e=>{this.events.playerChanged$.subscribe(({config:t})=>{t?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&e.next(t.unitedVideoId)})})}}toggleGraphView(e=!0){this.graph&&(e?(this.graph.show(),this.state.isSeekable$.next(!1)):(this.graph.hide(),this.checkIfSeekable()),this.globalEventEmitter.emit(C.graph,{type:he.visibility,visibility:e}),this.events.graphVisibilityChanged$.next(e))}setVisitedChapters(e){Array.isArray(e)&&this.graph?.setVisitedChapters(e)}updateGraphVideosInfo(e){Array.isArray(e)&&this.graph?.updateVideosInfo(e)}deadEndCheck(){return!(this.interactiveEvents?.getPreparedToExecActions()||[]).some(i=>i.actionType===I.setNextBranch)}allControlsAreRemoved(e=!0){return!this.gameControllers.some(i=>{let r=e&&this._options.controlsHideAnimation?i.container.willRemoved:!0;return!i.container.isRemoved||!r})}isEndedExpectation(){if(!this.player)return!1;let e=this.player.info.position$.getValue(),t=this.player.info.duration$.getValue();return e===t&&this.gameControllers.some(i=>{let r=i.container.container;return!i.container.isRemoved&&!i.container.willRemoved&&r.endTime===null&&H(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&ke(e.metadata.version)}getInitialVideoInfo(){return{videoId:this.historyController.getInitialVideoId(),chapterId:this.historyController.getInitialChapterId()}}getHistoryState(){return this.historyController.state}getIsSeekable(){return this.state.isSeekable$}getInteractiveRanges(){return Ot(this.manifestController.chapter?.containers)}getNextInteractiveStartTime(e){return this.seekToInteractiveController.getNextInteractiveTime(e)}getChapterBranches(e){return this.manifestController.getBranches(e)}getCurrentChapter(){return this.manifestController.getCurrent()}getCurrentManifest(){return this.manifestController.manifest}on(e,t){return this.globalEventEmitter.on(e,t),this}off(e,t){return this.globalEventEmitter.off(e,t),this}once(e,t){return this.globalEventEmitter.once(e,t),this}destroy(){this.clearHistoryIfEnded(),this.destroyGameControllers(),this.gameControllers=[],this.frameAverageColor?.destroy(),this.graph?.destroy(),this.seamlessControllerSubs.unsubscribe(),this.seamlessController?.removeAll(),this.resizeManager?.release(),this.animation.release(),this.interactiveEvents?.release(),this.manifestController.release(),this.playerSubscriptions.unsubscribe(),this.subscriptions.unsubscribe(),this.globalEventEmitter.reset(),this.lastFrame?.destroy(),this.rootElement.remove(),this.historyController.destroy(),this.isFirstChapterFetched=!1,this.appState=3}};var Qi={Container:Z,createChoiceContainer:Me,createAreaControl:Ee,createButtonControl:Te,classnamesPrefix:R};var Rs={version:ft};export{Un as ContainerTypes,U as ControlTypes,P as CustomError,C as EVENT_NAMES,I as EventActionTypes,Qn as EventTypes,ze as Interactives,J as ManifestController,Rs as SDKInfo,ct as chapterIdsToVKVideoIds,Je as compareVersions,Bn as containerTypes,Dn as controlTypes,Hn as eventActionTypes,_n as eventTypes,Fi as getChapterIdByVkVideoId,Yt as getVKVideoIdByMedia,Li as getVideoRawIdByMedia,he as graphEventTypes,Ne as hasEndTemplate,w as interactivesEventTypes,jn as isAreaControl,Nn as isButtonControl,B as isLastChapter,Y as isOneTextCtrlContainer,ke as isSupportedManifest,Re as isTextControl,$i as isVKVariantItem,At as isValidManifest,wt as migrateManifestToLatestVersion,Qi as utils,Jt as vkVideoIdsToChapterIds};
|