@vkontakte/videoplayer-interactive 1.0.32-dev.162375f7.0 → 1.0.32-dev.ae886eaa.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 +43 -6
- package/es2015.esm.js +43 -6
- package/es2018.cjs.js +43 -6
- package/es2018.esm.js +43 -6
- package/esnext.cjs.js +43 -6
- package/esnext.esm.js +43 -6
- package/evergreen.esm.js +42 -5
- package/package.json +4 -4
- package/types/modules/Interactives/Interactives.d.ts +11 -0
- package/types/modules/Interactives/containers/ChoiceContainer.d.ts +8 -6
- package/types/modules/Interactives/containers/Container.d.ts +7 -5
- package/types/modules/Interactives/containers/index.d.ts +2 -0
- package/types/modules/Interactives/containers/types.d.ts +9 -0
- package/types/modules/Interactives/containers/utils.d.ts +6 -0
- package/types/modules/Interactives/controls/AreaControl.d.ts +11 -2
- package/types/modules/Interactives/controls/ButtonControl.d.ts +11 -2
- package/types/modules/Interactives/controls/Control.d.ts +12 -9
- package/types/modules/Interactives/controls/TextControl.d.ts +11 -2
- package/types/modules/Interactives/controls/index.d.ts +4 -2
- package/types/modules/Interactives/controls/types.d.ts +17 -8
- package/types/modules/Interactives/controls/utils.d.ts +9 -0
- package/types/modules/Interactives/index.d.ts +39 -4
- package/types/modules/Interactives/styles.d.ts +1 -0
- package/types/modules/Interactives/types.d.ts +14 -2
- package/types/modules/Interactives/utils/GameController.d.ts +8 -4
- package/types/modules/Interactives/utils/InteractiveEvents.d.ts +1 -1
- package/types/modules/Interactives/utils/events.d.ts +3 -1
- package/types/modules/Interactives/utils/events.types.d.ts +3 -0
- package/types/modules/Interactives/utils/gameUtils.d.ts +2 -1
- package/types/modules/Interactives/utils/getInteractiveRanges.d.ts +5 -1
- package/types/modules/Interactives/utils/renderingUtils.d.ts +0 -3
package/evergreen.esm.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-interactive v1.0.32-dev.
|
|
3
|
-
* Thu,
|
|
2
|
+
* @vkontakte/videoplayer-interactive v1.0.32-dev.ae886eaa.0
|
|
3
|
+
* Thu, 27 Feb 2025 14:36:21 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/1-0-32/doc/
|
|
5
5
|
*/
|
|
6
|
-
var lt="1.0.32-dev.162375f7.0";function Fe(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 M="interactive",Zt="interactive-controls-container",pe=()=>document.querySelector(`.${Zt}`),ct=.4,V={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},pt=(n=>(n.top="flex-start",n.bottom="flex-end",n.center="center",n))(pt||{}),ht=(n=>(n.start="flex-start",n.end="flex-end",n.center="center",n))(ht||{}),dt=(n=>(n.start="left",n.end="right",n.center="center",n))(dt||{}),he=({target:i,props:e})=>{i.style.alignItems=(e?.gravityVertical&&pt[e.gravityVertical])??"center",i.style.justifyContent=(e?.gravityHorizontal&&ht[e.gravityHorizontal])??"center",i.style.textAlign=(e?.alignment&&dt[e.alignment])??"center"},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},ue=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=Fe(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},me=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${Fe(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},K=({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(`${M}-control-container-${this.control.id}`),e(t,this.control.layoutParams);let n=(this.control.layoutParams.innerSizesDependOn??V.innerSizesDependOn)==="self"?{height:t.style.height,width:t.style.width}:{height:"var(--interactive-content-height)",width:"var(--interactive-content-width)"};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 _e="int",D=(n=>(n.AREA=`${_e}_area`,n.TEXT=`${_e}_text`,n.BUTTON=`${_e}_bttn`,n))(D||{});var fe=i=>{if(i.type.trim().toLowerCase()==="area")return new He(i)},He=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(`${M}-${this.control.id}`),n.setAttribute("data-testid",D.AREA),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",ue({target:n,props:this.control.props,fallback:{...V,backgroundColor:"transparent"}}),me({target:n,props:this.control.props,fallback:{...V,borderAlpha:0},dependsOn:this.container.dimensions}),K({target:n,layoutParams:this.control.layoutParams,fallback:V}),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 ye=i=>{let e=document.createElement("span");switch(i){case"Button":case"button":{let t=document.createElement("div"),n={overflow:"hidden",display:"flex",justifyContent:"center",alignItems:"center"};Object.assign(t.style,n),t.append(e);let r={display:"inline-block",whiteSpace:"pre",textOverflow:"ellipsis",maxWidth:"initial",maxHeight:"100%",wordBreak:"normal"};return Object.assign(e.style,r),t}default:{let t={display:"inline-block",whiteSpace:"break-spaces",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",maxHeight:"100%",wordBreak:"break-all"};return Object.assign(e.style,t),e}}};var Ce=i=>{if(i.type.trim().toLowerCase()==="button")return new De(i)},De=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(`${M}-${this.control.id}`),n.setAttribute("data-testid",D.BUTTON),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.cursor="pointer",n.style.fontFamily="inherit",K({target:n,layoutParams:this.control.layoutParams,fallback:V}),ue({target:n,props:this.control.props,fallback:V}),me({target:n,props:this.control.props,fallback:V,dependsOn:this.container.dimensions}),he({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ye(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;de({target:s,props:this.control.props,fallback:V,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 ut=i=>{if(i.type.trim().toLowerCase()==="text")return new Ge(i)},Ge=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(`${M}-${this.control.id}`),n.setAttribute("data-testid",D.TEXT),n.style.display="flex",n.style.width="100%",n.style.height="100%",n.style.fontFamily="inherit",K({target:n,layoutParams:this.control.layoutParams,fallback:V}),he({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ye(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;de({target:s,props:this.control.props,fallback:V,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 Ue=class{constructor(e){this.layout=e}},ve=class extends Ue{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 X=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 ge=(i,e)=>{if(i.type.trim().toLowerCase()==="choice")return new ze(i,e)},ze=class extends X{constructor(e,t){super(e),this.rootElement=t??pe(),this.layout=new ve(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",Ce),this.addControlFactory("text",ut),this.addControlFactory("area",fe)}createView(e){let t=document.createElement("div");return t.classList.add(`${M}-${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=`${ct}`,this.isDisabled=!0)}removeView(){this.isRemoved||(this.controls.forEach(e=>e.removeListeners()),this.getElement()?.remove(),this.isRemoved=!0)}getElement(){return this.rootElement.querySelector(`.${M}-${this.container.id}`)}};import{clientChecker as In,combine as Tn,InterfaceLanguage as xn,Observable as Wt,once as Sn,Subject as P,Subscription as at,ValueSubject as $,fromEvent as Qt}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as le}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as qt}from"@vkontakte/videoplayer-shared/evergreen";function Y(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}var G=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,J=i=>G(i,"Object"),be=i=>G(i,"String"),Ee=i=>G(i,"Array"),Ie=i=>G(i,"Number"),mt=i=>G(i,"Function");var We=i=>Ie(i)&&!isNaN(i);var U=i=>J(i)&&Object.keys(i).length===0,Qe=i=>Ee(i)&&!i.length;var ee=(i,e)=>be(i)&&(e?i.trim():i).length;var ft="video_interactive",yt="videoint";var Ct=250,te=class{constructor(e){this.handleZoomChange=Y(e=>{this.lastZoomInfo=e},Ct);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?.("Chapter 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,!Ie(e.graph.edit.chapters[0].x)){this.onError?.("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=Yt(e),this.resizeObserver=new ResizeObserver(Y(this.onResize,Ct)),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 qt(this.lang,ft,yt)}catch{this.onError?.("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 Yt(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 ne=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 p=s.startTime-e;if(p<=r&&(s.endTime&&r<=s.endTime||s.endTime===null)){n=!0;break}r<p&&(t=t===-1?p:Math.min(t,p))}return!n&&t!==-1?t:null}}};import{isSupportedManifest as xe,ContainerTypes as Bi,ControlTypes as Se,EventActionTypes as g,EventTypes as Fi,migrateManifestToLatestVersion as bt,compareVersions as _i}from"@interactiveplatform/movika-manifest";var vt={metadata:"Object",chapters:"Array"},gt=i=>{if(!J(i))return!1;for(let e in vt)if(!i[e]||!G(i[e],vt[e]))return!1;return xe(i.metadata.version)},Te=i=>i.type===Se.Text,Ri=i=>i.type===Se.Button,Vi=i=>i.type===Se.Area,Mi={Choice:"Choice",TextInput:"TextInput"},Pi={Button:"Button",Area:"Area",Text:"Text"},$i={onClick:"onClick",onSuspense:"onSuspense"},Ni={openURI:"openURI",setNextBranch:"setNextBranch",setWeightlessRandomBranch:"setWeightlessRandomBranch",setRandomBranch:"setRandomBranch",setMaxWeightBranch:"setMaxWeightBranch",setMinWeightBranch:"setMinWeightBranch",setDefaultBranch:"setDefaultBranch",continuePlayback:"continuePlayback",expect:"expect"};var R=class{constructor(e,t,...n){this.severity=e;this.category=t;this.data=n}toString(){return`Interactive SDK error ${JSON.stringify(this,null," ")}`}};var we=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 Ae=class{constructor(e){this.fns=[];this.addFn=(e,t=!1)=>{mt(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 an}from"@vkontakte/videoplayer-shared/evergreen";var ke=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return Jt(...this.loaders[e])(t)}};function Jt(...i){return async function(t){let n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function ie(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function Re({actions:i,errors:e,chapterId:t,...n}){if(t){let r=i.getManifest();if(r){let s=i.getChapter(r.chapters,t);if(s){let p=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return p?{...n,actions:i,errors:e,result:{chapter:s,media:p,graph:a}}:{...n,errors:ie(e,Re.name,"Could not find media"),actions:i}}}}return{...n,errors:ie(e,Re.name,"Could not find chapter"),actions:i}}var Ke=(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 en=async i=>{try{let e={},t;if(be(i)){t=new URL(i).href;let r=await fetch(t);if(!r.ok)return{};e=await r.json()}else if(J(i))e=i;else return{};if(!gt(e))return{};let n=e.metadata.media;if(be(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 rn(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function Et(i){let{manifest:e,manifestURL:t}=await en(i);if(!e)throw new Error("Failed on fetch");let n=bt(e);return n.media=tn(n.media,t),delete n.metadata.media,n}function Ve(i,e){if(e)return i.find(t=>t.id===e)}function Xe(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 Ze(i,e){return i.videos.find(t=>t.id===e)}function tn(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{let r="url"in n?n.url:"",s=nn(r,e);return{...n,url:s||r}})}))}}function nn(i="",e){try{return new URL(i,e).href}catch{return""}}function rn(i){return Ke(i,"3.2.0")>=0}var Me=i=>Ee(i)&&!Qe(i),F=i=>i.order==="end",Pe=i=>Ee(i.containers)&&!Qe(i.containers)&&F(i),It=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t<(e.startTime??0)},qe=(i,e)=>{let t=i*1e3;return Me(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var z=(i=[])=>i.some(e=>e.action.type==="expect"),Ye=(i=[])=>i.find(e=>e.action.type==="expect"),sn=i=>i?.length===1,Z=i=>sn(i)&&Te(i[0]);function Tt(i,...e){return t=>typeof e[0]=="object"&&typeof t=="object"?i({...e[0],...t}):i(...e,...t)}var xt=(i,e)=>z(i.events)?!1:e.some(({container:t})=>t.container.id!==i.id&&z(t.container.events)&&t.container.endTime===i.endTime&&!t.isRemoved);var q=class extends ke{constructor(t,n){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new an(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:ie},result:null,errors:null,source:t});return n.errors&&this.errorHandler(n.errors),this.manifest=await Et(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",Re({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:Xe,getChapter:Ve,getMedia:Ze,getByBranches:this.getByBranches.bind(this),addErrorMessage:ie},result:null,errors:null,chapterId:t}));return n.errors&&this.errorHandler(n.errors),n.result&&(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=Ze(this.manifest.media,n.videoId),s=Xe(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 on}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as tt,Tracer as ln,ValueSubject as cn}from"@vkontakte/videoplayer-shared/evergreen";var St=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 Je(){let i=new Map;function e({listId:s=Math.random().toString(),itemId:p=Math.random().toString(),...a}){let l=i.get(s),h={...a};return l?l[p]=h:i.set(s,{[p]:h}),{listId:s,itemId:p,...a}}function t(s){s.player.destroy(),s.container.remove(),s.subscription.unsubscribe(),s.statistics?.oneStat.destroy(),s.statistics?.statSubscription.unsubscribe()}function n(s,p){let a=i.get(s);if(!a)throw Error("Can't remove. Not find.");if(p){let l=a[p];l&&t(l),delete a[p],Object.keys(a).length||i.delete(s)}else{for(let l of Object.values(a))t(l);i.delete(s)}}function r(){for(let s of i)n(s[0])}return{createPlayer:e,removePlayer:n,map:i,removeAll:r}}function et(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 re=(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 pn=2;function nt(i){let e=Je(),t=new tt,n={},r=null,s=!1,p,a=new cn(null);i&&l(i);function l(x){r=x}function h(x,S,o){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let d=(e.map.get(x)??{})[S];if(d){n={chapterId:o,listId:x,itemId:S,...d};let u=n.player;n.subscription.add(u.info.currentQuality$.subscribe(m=>{let f=u.info.position$.getValue(),I=u.info.isAutoQualityEnabled$.getValue();if(!(!m||!f||I))for(let A of e.map)Object.values(A[1]).forEach(({player:C})=>{re(C,m)})})).add(u.events.started$.subscribe(()=>{v(S)})),d.container.remove(),r.setPlayer(d.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 v(x){if(!r)throw Error("need to set interactive controller");if(U(n)||x!==n.itemId)return;let S=r.getChapterBranches(),o=new Set;for(let c of S)o.has(c.media.id)||(await b({media:c.media,chapterId:c.chapter.id,setAsActive:!1,title:c.chapter.label}),o.add(c.media.id))}async function T({chapter:{id:x},manifestVideo:S}){if(U(n)||!r)return;let o=n.player.info.muted$.getValue(),c=n.player.info.currentQuality$.getValue(),d=n.player.info.isAutoQualityEnabled$.getValue(),u=n.player.info.volume$.getValue(),m=n.player.info.currentPlaybackRate$.getValue(),f=!d,I=!1;for(let A of e.map)if(A[0]===S.id&&!r.state.isReplay$.getValue()){let C=Object.keys(A[1]);for(let k of C)k===n.itemId?(C.length<pn||(I=!0),e.removePlayer(A[0],k)):(I=!0,h(A[0],k,x),f?re(n.player,c):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(o),n.player.setPlaybackRate(m))}else e.removePlayer(A[0]);I||(await b({media:S,chapterId:x,setAsActive:!0,playbackRate:m}),f?re(n.player,c):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(o))}async function b({media:x,chapterId:S,prefetch:o=!0,setAsActive:c=!0,autoplay:d=!1,preferredExt:u,title:m,playbackRate:f}){let I=Math.random().toString(),A=document.createElement("div");p.append(A);let C;if(r?.options?.vkVideoLoader){let ce=St(x);ce.length&&(C=await r.options.vkVideoLoader(...ce))}let k=r?.options?.coreConfig||void 0,L={...k,configName:[...k?.configName??[],"interactive"]},O={container:A,...C?.videos?.[0]||{sources:et(x,u).sources},title:m,failoverHosts:C?.failoverHosts||[]},j=new on(L,ln.createRootTracer());j.initVideo(O);let _=null;if(C?.videos&&r?.options.createOneStat){let ce=C.videos[0],Be=r.options.createOneStat(ce),ot=new tt;Be&&(ot.add(Be.attachTo(j)),_={oneStat:Be,statSubscription:ot})}let W=new tt,Xt=n?.player?.info.isAutoQualityEnabled$.getValue();W.add(j.events.canplay$.subscribe(function(){Xt||re(j,n.player.info.currentQuality$.getValue()),f&&j.setPlaybackRate(f)}));let Q=e.createPlayer({listId:x.id,itemId:I,player:j,container:A,sources:et(x,u).sources,config:O,subscription:W,statistics:_});return c&&h(x.id,Q.itemId,S),d&&Q.player.play(),o&&!d&&Q.player.prepare(),{player:Q.player,config:Q.config,statistics:Q.statistics}}function E(){B(),r=null,p.remove()}function B(){t.unsubscribe(),e.removeAll(),n={},s=!1}async function N(){if(!r)throw Error("need to set interactive controller");B(),p=document.createElement("div");let{media:x,chapter:S}=r.getCurrentChapter();x&&S?(t.add(r.events.chapterChanged$.subscribe(T)),await b({media:x,chapterId:S.id,title:S.label})):console.error("not found")}return{...e,init:N,setInteractiveController:l,createPlayer:b,removeAll:E,getActivePlayer:function(){return n},activePlayerChanged:a}}var y={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},se={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 hn}from"@vkontakte/videoplayer-shared/evergreen";var $e=class{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEvents:p,globalEventEmitter:a,ignoreContainerEvent:l,permanentTextControls:h,disabledControls$:v,onRemove:T}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(z(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)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:(r,s)=>{this.isSelectedControlEvent=!0,r!==!1&&(this.removeView(),this.emitContainerVisibilityEvent(!1)),(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect)&&(this.selectBranches.stopExpect(),s(),this.removeView(),this.emitContainerVisibilityEvent(!1))},isEOV:()=>this.gameState===4},n=Tt(this.selectBranches.onControlEvent,t);this.container.createView(n),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(It(s,this.container.container))this.gameState!==1&&(this.gameState=1,this.onBeforeStartTime());else if(qe(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 p=qe(s,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],l={subjectId:this.container.container.id,subjectName:"container",range:a,currentTime:s,isInteractiveTime:p};this.globalEventEmitter.emit(y.eachTick,l),this.globalEvents.eachTick$.next(l)};this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new hn,this.player=e,this.interactiveEvents=s,this.ignoreContainerEvent=l,this.isPermanentText=h&&Z(t.container.controls),this.disabledControls$=v,this.onRemove=T,this.globalEventEmitter=a,this.gameState=0,this.globalEvents=p,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(y.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(y.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=z(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(y.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 At=(i=[])=>i.reduce((e,t,n)=>{let r=(t?.controls??[]).filter(s=>!Te(s));if(Me(r)){let s=[t.startTime??0,t.endTime??1/0],p=t.id;if(!n)e.push({subjects:[p],range:s});else{let a=[],l=-1/0,h=1/0,v=[],T=[];for(let b=0;b<e.length;b++){let E=e[b];if(T.push(...E.subjects),E.range[0]<h&&(h=E.range[0]),E.range[1]>l&&(l=E.range[1]),s[0]>=E.range[0]&&s[1]<=E.range[1])return e[b].subjects.push(p),e;s[0]<E.range[0]&&s[1]>E.range[0]&&(a.push(b),v=v.concat(E.subjects)),s[0]>=E.range[0]&&s[0]<=E.range[1]&&(a.push(b),v=v.concat(E.subjects),s[0]=E.range[0]),s[1]>=E.range[0]&&s[1]<=E.range[1]&&(a.push(b),v=v.concat(E.subjects),s[1]=E.range[1])}if(T.push(p),s[0]<=h&&s[1]>=l)return[{subjects:T,range:s}];a.length&&a.reverse().forEach(b=>{e.splice(b,1)}),e.push({subjects:v.concat([p]),range:s})}}return e},[]).sort((e,t)=>e.range[0]-t.range[0]);function kt(){let i={};function e(){for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&delete i[a]}function t(a){let l={};for(let h in i)+h<=a&&(l[h]=i[h]);return l}function n(a){let l={};for(let h in i)+h>=a&&(l[h]=i[h]);return l}function r({timestamp:a,priority:l,initiator:h}){if(We(a)){let v=i[a]??null;if(v&&l&&ee(l,!0)){let T={},b=v[l];return b&&(T={...T,...b}),T=U(T)?null:T,T&&ee(h,!0)?T[h]??null:T}return v}return null}function s({timestamp:a,priority:l,initiator:h}){if(We(a))if(i[a]){if(l&&ee(l,!0))if(i[a][l]){if(h&&ee(h,!0))if(i[a][l][h]){if(delete i[a][l][h],!U(i[a][l]))return!0}else return!1;if(delete i[a][l],!U(i[a]))return!0}else return!1;return delete i[a]}else return!1;return!1}function p({timestamp:a,priority:l,initiator:h,...v}){i[a]?.[l]?.[h]?i[a][l][h].push({...v}):i[a]?.[l]?i[a][l]={...i[a][l],[h]:[{...v}]}:i[a]?i[a]={...i[a],[l]:{[h]:[{...v}]}}:i[a]={[l]:{[h]:[{...v}]}}}return{map:i,remove:s,add:p,removeAll:e,get:r,getLte:t,getGte:n}}var dn=[g.expect,g.setNextBranch],un=1/0;function Rt(i){let e=i,t,n=mn(),r=kt(),s,p=()=>{b(),S()},a=o=>{r.add.call(void 0,o),B()},l=(o=[])=>{for(let c of o)if(c.action(),dn.includes(c.actionType))break},h=(o=1/0)=>{let c=Ne(r.get({timestamp:o,priority:"control"})??{}),d=Ne(r.get({timestamp:o,priority:"container"})??{}),u=Ne(r.get({timestamp:o,priority:"chapter"})??{});return[...c,...d,...u]},v=o=>{n.isReady(o)&&l(h(o))},T=()=>{l([...Ne(r.get({timestamp:1/0,priority:"chapter"})??{})])},b=()=>{t&&(s?.unsubscribe(),t=void 0)},E=o=>{},B=()=>{t||(t=()=>setTimeout(()=>{v(1/0)}),s=e.events.ended$.subscribe(t))},N=o=>{b(),e=o},x=o=>{o.priority==="container"&&n.resetCalled(o.timestamp),r.remove(o)},S=()=>{n.release(),r.removeAll()};return{setPlayer:N,add:a,remove:x,exec:v,execEndOfVideo:T,listen:B,unlisten:b,release:p,containersEventsCallState:n,getPreparedToExecActions:h}}function mn(){let i=new Map;return{setCalled:({timestamp:p,id:a})=>{let l=i.get(p);l&&l[a]!==void 0&&(l[a]=!0)},setData:(p=[])=>{for(let a of p){let l=a.endTime??un,h=i.get(l);i.set(l,{...h,[a.id]:!1})}},resetCalled:p=>{let a=i.get(p);if(a)for(let l in a)a[l]=!1},isReady:p=>{let a=i.get(p);return a?!Object.values(a).some(l=>!l):!0},release:()=>i.clear()}}function Ne(i){return Object.values(i).flat().sort(e=>e.actionType===g.expect?-1:1)}var Vt={videoContentHeight:0,videoContentWidth:0},Mt=(i,e)=>{let{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return Vt;let{clientHeight:r,clientWidth:s}=e.experimental.element$.getValue()||{};if(!(r&&s))return Vt;let p=t/n,a=r/s,l,h;return a>p?(h=s,l=s*p):a<p?(h=r/p,l=r):(h=s,l=r),{videoContentWidth:h,videoContentHeight:l}};var fn=250;function Pt(i){let e=()=>{},t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){let{parentElement:l,player:h}=i();if(l&&h){let{videoContentWidth:v,videoContentHeight:T}=Mt(l,h);l.style.setProperty("--interactive-content-width",`${v}px`),l.style.setProperty("--interactive-content-height",`${T}px`),l.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),l.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function r(){let{parentElement:a}=i();a.removeAttribute("style")}let s=Y(a=>{let{fns:l=[]}=i();n(a);for(let h of l)h()},fn);function p(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:p}}var yn=i=>Math.floor(Math.random()*i),Nt=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},Lt=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 Ot=i=>{let e=i.length,t=yn(e);return i[t]},$t=1,jt=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??$t;let t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??$t,e>=t)return i[n];return i[i.length-1]};var Bt={shouldOpenNow:!0,isDetachContainer:!0},Ft="after-expect";var it=(i,e=!1)=>({...i,args:e?{...i.args,...Bt}:{...Bt,...i.args}}),Dt=({globalEventEmitter:i,globalEvents:e,player:t,interactiveEvents:n})=>{let r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},p=({action:o,controlType:c,controlId:d,containerId:u,branches:m=[],onEvent:f,isEOV:I=()=>!1,isDisabled:A=()=>!1})=>{let C=it(o,I()),k={timestamp:1/0,priority:"control",initiator:d,actionType:C.type},L=A(),O=i.emit.bind(i,y.interactives,{subjectId:d,subjectType:c,subjectName:"control",type:L?w.actionChoiceCanceled:w.actionChoice,actionType:o.type,payload:{invokeImmediately:C.args.shouldOpenNow,containerId:u,...C.args}}),j=()=>{e.interactiveActionChoice$.next({subjectId:d,subjectType:c,subjectName:"control",type:L?"action-choice-canceled":"action-choice",actionType:o.type,payload:{invokeImmediately:C.args.shouldOpenNow,containerId:u,...C.args}})};if(L){O(),j();return}switch(C.type.trim().toLowerCase()){case g.setNextBranch.trim().toLowerCase():{let _=m.find(W=>W.id===C.args.branchId);if(!_)return;f(C.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),O(),j(),C.args.shouldOpenNow?N({subjectId:d,subjectName:"control",subjectType:c,action:C,payload:{chapterId:_.chapterId,autoSelect:!1}}):n.add({...k,action:N.bind(null,{subjectId:d,subjectName:"control",subjectType:c,action:C,payload:{chapterId:_.chapterId,autoSelect:!1}})});return}case g.continuePlayback.trim().toLowerCase():{f(C.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),O(),j(),C.args.shouldOpenNow?B({subjectId:d,subjectName:"control",subjectType:c,action:o}):n.add({...k,action:B.bind(null,{subjectId:d,subjectName:"control",subjectType:c,action:o})});return}case g.openURI.trim().toLowerCase():{f(C.args.isDetachContainer,E.bind(null,{subjectId:d,subjectName:"control"})),O(),j(),C.args.shouldOpenNow?S({subjectId:d,subjectName:"control",subjectType:c,action:C,payload:{URI:o.args.uri}}):n.add({...k,action:S.bind(null,{subjectId:d,subjectName:"control",subjectType:c,action:C,payload:{URI:o.args.uri}})});return}default:{let _="Unexpected control event",W=new R(1,1,{message:_});v(W,_);return}}},a=({action:o,container:{id:c,endTime:d},branches:u=[],isEOV:m=!1,autoSelected:f=!1})=>{let I=it(o,m),A={timestamp:!I.args.shouldOpenNow||m?1/0:d??1/0,priority:"container",initiator:c,actionType:I.type},C=i.emit.bind(i,y.interactives,{subjectId:c,subjectName:"container",type:w.actionChoice,actionType:I.type,payload:{invokeImmediately:I.args.shouldOpenNow,...I.args}}),k=()=>{e.interactiveActionChoice$.next({subjectId:c,subjectName:"container",type:"action-choice",actionType:I.type,payload:{invokeImmediately:I.args.shouldOpenNow,...I.args}})};switch(I.type.trim().toLowerCase()){case g.setNextBranch.trim().toLowerCase():{let L=u.find(O=>O.id===I.args.branchId);if(!L)return;C(),k(),n.add({...A,action:N.bind(null,{subjectId:c,subjectName:"container",action:I,payload:{chapterId:L.chapterId,autoSelect:f}})});return}case g.setMaxWeightBranch.trim().toLowerCase():return;case g.setMinWeightBranch.trim().toLowerCase():return;case g.setRandomBranch.trim().toLowerCase():return;case g.setWeightlessRandomBranch.trim().toLowerCase():return;case g.continuePlayback.trim().toLowerCase():{C(),k(),n.add({...A,action:B.bind(null,{subjectId:c,subjectName:"container",action:I})});return}case g.openURI.trim().toLowerCase():{C(),k(),n.add({...A,action:S.bind(null,{subjectId:c,subjectName:"container",action:I,payload:{URI:o.args.uri}})});return}default:{let L="Unexpected container event",O=new R(1,1,{message:L});v(O,L);return}}};function l({container:o,branches:c,isEOV:d=!1}){let u=Ye(o.events);if(u){let m=it(u.action,d);i.emit(y.interactives,{subjectId:o.id,subjectName:"container",type:w.actionChoice,actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),e.interactiveActionChoice$.next({subjectId:o.id,subjectName:"container",type:"action-choice",actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),n.add({timestamp:d?1/0:o.endTime??1/0,priority:"container",initiator:o.id,actionType:g.expect,action:b.bind(null,{subjectId:o.id,subjectName:"container"})}),r.isExpect=!0}else for(let m of o.events??[])a({action:m.action,container:o,branches:c,isEOV:d})}let h=({chapterId:o,action:c,branches:d=[]})=>{let u=i.emit.bind(i,y.interactives,{subjectId:o,subjectName:"chapter",type:w.actionChoice,actionType:c.type,payload:c.args}),m=()=>{e.interactiveActionChoice$.next({subjectId:o,subjectName:"chapter",type:"action-choice",actionType:c.type,payload:c.args})};switch(c.type.trim().toLowerCase()){case g.setNextBranch.trim().toLowerCase():{let f=d.find(I=>I.id===c.args.branchId);return f?.chapterId?(u(),m(),N.bind(null,{subjectId:o,subjectName:"chapter",action:c,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case g.setWeightlessRandomBranch.trim().toLowerCase():{let f=Ot(d);return f?.chapterId?(u(),m(),N.bind(null,{subjectId:o,subjectName:"chapter",action:c,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case g.setRandomBranch.trim().toLowerCase():{let f=jt(d);return f?.chapterId?(u(),m(),N.bind(null,{subjectId:o,subjectName:"chapter",action:c,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case g.setMaxWeightBranch.trim().toLowerCase():{let f=Lt(d);return f?.chapterId?(u(),m(),N.bind(null,{subjectId:o,subjectName:"chapter",action:c,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case g.setMinWeightBranch.trim().toLowerCase():{let f=Nt(d);return f?.chapterId?(u(),m(),N.bind(null,{subjectId:o,subjectName:"chapter",action:c,payload:{chapterId:f.chapterId,autoSelect:!0}})):void 0}case g.continuePlayback.trim().toLowerCase():return u(),m(),B.bind(null,{subjectId:o,subjectName:"chapter",action:c});case g.openURI.trim().toLowerCase():return u(),m(),S.bind(null,{subjectId:o,subjectName:"chapter",action:c,payload:{URI:c.args.uri}});default:{let f="Unexpected chapter event",I=new R(1,1,{message:f});v(I,f);return}}};function v(o,c){console.error(c),e.error$.next(o),i.emit(y.errors,o)}function T(o){let c=Ye(o.events);if(c){if(F(o))return;i.emit(y.interactives,{subjectId:o.id,subjectName:"chapter",type:w.actionChoice,actionType:c.action.type,payload:c.action.args}),e.interactiveActionChoice$.next({subjectId:o.id,subjectName:"chapter",type:"action-choice",actionType:c.action.type,payload:c.action.args}),n.add({timestamp:1/0,priority:"chapter",initiator:o.id,actionType:g.expect,action:b.bind(null,{subjectId:o.id,subjectName:"chapter"})})}else o.events?.forEach(d=>{let u=h({chapterId:o.id,action:d.action,branches:o.branches});u&&n.add({timestamp:1/0,priority:"chapter",initiator:o.id,actionType:d.action.type,action:u})})}let b=({subjectId:o,subjectName:c})=>{t.pause(),i.emit(y.interactives,{subjectId:o,subjectName:c,type:w.actionExecution,actionType:g.expect}),e.interactiveActionExecution$.next({subjectId:o,subjectName:c,type:"action-execution",actionType:g.expect})},E=({subjectId:o,subjectName:c})=>{t.info.isEnded$.getValue()?n.execEndOfVideo():t.play(),i.emit(y.interactives,{subjectId:o,subjectName:c,type:w.actionExecution,actionType:Ft}),e.interactiveActionExecution$.next({subjectId:o,subjectName:c,type:"action-execution",actionType:Ft})},B=({subjectId:o,subjectName:c,subjectType:d,action:u})=>{i.emit(y.interactives,{subjectId:o,subjectName:c,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:o,subjectName:c,subjectType:d,type:"action-execution",actionType:u.type})},N=({subjectId:o,subjectName:c,subjectType:d,action:u,payload:m})=>{m.behaviour="change-chapter",i.emit(y.interactives,{subjectId:o,subjectName:c,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:o,subjectName:c,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},x=({subjectId:o,subjectName:c,subjectType:d,action:u,payload:m})=>{m.behaviour="change-manifest",i.emit(y.interactives,{subjectId:o,subjectName:c,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:o,subjectName:c,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},S=({subjectId:o,subjectName:c,subjectType:d,action:u,payload:m})=>{if(!m.URI)return;let f=window.open(m.URI,"_blank","noopener,noreferrer");f&&(f.opener=null),i.emit(y.interactives,{subjectId:o,subjectName:c,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:o,subjectName:c,subjectType:d,type:"action-execution",actionType:u.type})};return{onControlEvent:p,onContainerEvent:a,onChapterEvent:h,onExpectEvent:b,expectEventHandler:E,setManifestChapterEvents:T,setManifestContainerEvents:l,stopExpect:s,state:r}};import{Subscription as En,Subject as st,ValueSubject as ae}from"@vkontakte/videoplayer-shared/evergreen";var rt=(i,e)=>{let t={};return i.map(n=>{if(!t[n]){let r=e.chapters.find(p=>p.id===n);if(!r)return null;let s=e.media.videos.find(p=>r.videoId===p.id);if(!s)return null;t[n]=Gt(s)}return t[n]}).filter(Boolean)},vn=i=>{for(let e of i.variants)if(gn(e)&&e.payload)return e.payload.id},gn=i=>!!(i.type==="custom"&&i.payload&&i.payload.type==="vk"),Gt=i=>{let e=vn(i);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},bn=(i,e)=>{for(let t of i.media.videos)if(e===Gt(t)){for(let n of i.chapters)if(n.videoId===t.id)return n.id;return}},Ut=(i,e)=>i.reduce((t,n)=>{let r=bn(e,n);return r?[...t,r]:t},[]);var oe=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:n,historyApi:r,settings:s}){this.state={history$:new ae([]),hasPrevChapter$:new ae(!1),prevChapter$:new ae(null),isInitialChapter$:new ae(!1),isGoBackLimited$:new ae(!1)};this.#n=null;this.#a=!1;this.#e=null;this.#p=null;this.events={inited$:new st,destroyed$:new st,error$:new st};this.#i=null;this.#r=null;this.#t=null;this.#o=new En;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(p=>{this.state.prevChapter$.next(p.at(-2)||null),this.state.hasPrevChapter$.next(p.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,p=rt(s,n);if(this.#p=p,this.state.history$.next(s),!(!t||!this.#n||!this.#i))try{await this.#n.save(this.#i,p)}catch{let l=new R(1,5,"Unable to save interactive history");this.events.error$.next(l),this.#t?.emit(y.errors,l)}}async goBack(){if(!this.state||!this.#r){let n=new R(1,5,"Unable to save interactive history");return this.events.error$.next(n),this.#t?.emit(y.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 R(1,5,"Error while trying to fetch data");this.events.error$.next(s),this.#t?.emit(y.errors,s)}let n=Ut(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 rt([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(y.historyDestroyed),this.events.destroyed$.next(),this.#t=null}};var Le=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 Oe=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 pt="1.0.32-dev.ae886eaa.0";var _e=class{constructor(e){this.layout=e}},de=class extends _e{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))`}};function ht(i){return"features"in i}var X=class{constructor(e,t){this.container=e,this.options=t,this.factories=new Map,this.controls=[],this.setControls()}featureIsEnabled(e){return this.options&&ht(this.options)&&this.options.features[e]}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,this.options);if(s)return[...e,s]}return[...e]},[])||[]}};function He(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 dt="interactive",P={textColor:"#000",textSize:.4,textContent:"",roundCorners:0,borderWidth:0,borderColor:"#000",borderAlpha:1,backgroundColor:"#fff",backgroundAlpha:1,innerSizesDependOn:"self",angle:0},ut=(n=>(n.top="flex-start",n.bottom="flex-end",n.center="center",n))(ut||{}),mt=(n=>(n.start="flex-start",n.end="flex-end",n.center="center",n))(mt||{}),ft=(n=>(n.start="left",n.end="right",n.center="center",n))(ft||{}),ue=({target:i,props:e})=>{i.style.alignItems=(e?.gravityVertical&&ut[e.gravityVertical])??"center",i.style.justifyContent=(e?.gravityHorizontal&&mt[e.gravityHorizontal])??"center",i.style.textAlign=(e?.alignment&&ft[e.alignment])??"center"},me=({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},fe=({target:i,props:e,fallback:t})=>{i.style.backgroundColor=He(e?.background?.color??t.backgroundColor,e?.background?.alpha??t.backgroundAlpha)},ye=({target:i,props:e,fallback:t,dependsOn:n})=>{i.style.border=`calc(${n.height} * ${e?.shape?.border?.width??t.borderWidth}) solid ${He(e?.shape?.border?.color??t.borderColor,e?.shape?.border?.alpha??t.borderAlpha)}`,i.style.borderRadius=`calc(${n.height} * ${e?.shape?.roundCorners??t.roundCorners})`},Z=({target:i,layoutParams:e,fallback:t})=>{let n=e.angle??t.angle;n=n&&n*-1,i.style.transform=`rotate(${n}rad)`};var De="int",U=(n=>(n.AREA=`${De}_area`,n.TEXT=`${De}_text`,n.BUTTON=`${De}_bttn`,n))(U||{});function yt(i){return"features"in i}var q="interactive-control",R={common:q,wrapper:`${q}-wrapper`,disabled:`${q}-disabled`,button:`${q}-button`,area:`${q}-area`,text:`${q}-text`};var D=class{constructor(e,t){this.control=e;this.options=t;this.container=null;this.controlElement=null;this.clickListener=null}createContainerElement(e){let t=document.createElement("div");t.classList.add(R.wrapper),e.setControlLayout(t,this.control.layoutParams);let n=(this.control.layoutParams.innerSizesDependOn??P.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()}}featureIsEnabled(e){return this.options&&yt(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 Ce=(i,e)=>{if(i.type.trim().toLowerCase()==="area")return new Ue(i,e)},Ue=class extends D{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("button");n.type="button",n.classList.add(R.common,R.area),n.setAttribute("data-testid",U.AREA),fe({target:n,props:this.control.props,fallback:{...P,backgroundColor:"transparent"}}),ye({target:n,props:this.control.props,fallback:{...P,borderAlpha:0},dependsOn:this.container.dimensions}),Z({target:n,layoutParams:this.control.layoutParams,fallback:P}),this.container.element.append(n),e.append(this.container.element),this.controlElement=n}disable(){this.controlElement&&this.controlElement.classList.add(R.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(R.disabled)}getElement(){return this.controlElement}};var ve=i=>{let e=document.createElement("span");switch(i){case"Button":case"button":{let t=document.createElement("div"),n={overflow:"hidden",display:"flex",justifyContent:"center",alignItems:"center"};Object.assign(t.style,n),t.append(e);let r={display:"inline-block",whiteSpace:"pre",textOverflow:"ellipsis",maxWidth:"initial",maxHeight:"100%",wordBreak:"normal"};return Object.assign(e.style,r),t}default:{let t={display:"inline-block",whiteSpace:"break-spaces",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",maxHeight:"100%",wordBreak:"break-all"};return Object.assign(e.style,t),e}}};var ge=(i,e)=>{if(i.type.trim().toLowerCase()==="button")return new Ge(i,e)},Ge=class extends D{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("button");n.type="button",n.classList.add(R.common,R.button),n.setAttribute("data-testid",U.BUTTON),Z({target:n,layoutParams:this.control.layoutParams,fallback:P}),fe({target:n,props:this.control.props,fallback:P}),ye({target:n,props:this.control.props,fallback:P,dependsOn:this.container.dimensions}),ue({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ve(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;me({target:s,props:this.control.props,fallback:P,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.classList.add(R.disabled)}enable(){this.controlElement&&this.controlElement.classList.remove(R.disabled)}getElement(){return this.controlElement}};var Ct=(i,e)=>{if(i.type.trim().toLowerCase()==="text")return new ze(i,e)},ze=class extends D{constructor(e,t){super(e,t)}createView({parentElement:e,callbacks:t}){if(super.createContainerElement(t),!this.container)return;let n=document.createElement("div");n.classList.add(R.common,R.text),n.setAttribute("data-testid",U.TEXT),Z({target:n,layoutParams:this.control.layoutParams,fallback:P}),ue({target:n,props:{...this.control.props.text,alignment:this.control.layoutParams.alignment}});let r=ve(this.control.type.trim().toLowerCase()),s=r.firstElementChild??r;me({target:s,props:this.control.props,fallback:P,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 We="interactive-container",L={common:We,hidden:`${We}-hidden`,disabled:`${We}-disabled`};var be=(i,e,t)=>{if(i.type.trim().toLowerCase()==="choice")return new Ke(i,e,t)},Ke=class extends X{constructor(t,n,r){super(t,r);this.containerElement=null;this.rootElement=n,this.layout=new de(this.container.layout),this.isRemoved=!1,this.isDisabled=!1,this.addControlFactory("button",ge),this.addControlFactory("text",Ct),this.addControlFactory("area",Ce)}createView({eventCallback:t}){let n=document.createElement("div");return n.classList.add(L.common,L.disabled),requestAnimationFrame(()=>{n.classList.remove(L.disabled)}),this.layout.setContainerLayout(n),this.controls.forEach(r=>{r.createView({parentElement:n,callbacks:{setControlLayout:this.layout.setControlLayout}}),r.setEvents(t)}),this.rootElement.append(n),this.isRemoved=!1,this.containerElement=n,n}hide(){let t=this.getElement();t&&t.classList.add(L.hidden)}show(){let t=this.getElement();t&&t.classList.remove(L.hidden)}enable(){let t=this.getElement();t&&(t.classList.remove(L.disabled),this.controls.forEach(n=>n.enable()),this.isDisabled=!1)}disable(){let t=this.getElement();t&&(t.classList.add(L.disabled),this.controls.forEach(n=>n.disable()),this.isDisabled=!0)}removeView(){let t=this.getElement();t&&(this.controls.forEach(n=>n.removeListeners()),t.remove(),this.isRemoved=!0,this.containerElement=null)}fakeRemove(){this.isRemoved||(this.isRemoved=!0)}getElement(){return this.containerElement}};import{combine as kn,InterfaceLanguage as Vn,Observable as Yt,once as Mn,Subject as N,Subscription as ct,ValueSubject as $,fromEvent as Jt}from"@vkontakte/videoplayer-shared/evergreen";import{InteractiveInterfaceClick as pe}from"@vkontakte/videoplayer-statistics/evergreen";import{loadVKLangPack as nn}from"@vkontakte/videoplayer-shared/evergreen";function ee(i,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>i(...n),e)}}var G=(i,e)=>Object.prototype.toString.call(i)===`[object ${e}]`,te=i=>G(i,"Object"),Ee=i=>G(i,"String"),Ie=i=>G(i,"Array"),Te=i=>G(i,"Number"),vt=i=>G(i,"Function");var Qe=i=>Te(i)&&!isNaN(i);var z=i=>te(i)&&Object.keys(i).length===0,Xe=i=>Ie(i)&&!i.length;var ne=(i,e)=>Ee(i)&&(e?i.trim():i).length;var gt="video_interactive",bt="videoint";var Et=250,ie=class{constructor(e){this.handleZoomChange=ee(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?.("Chapter 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");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=rn(e),this.resizeObserver=new ResizeObserver(ee(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 nn(this.lang,gt,bt)}catch{this.onError?.("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 rn(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 re=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 h=s.startTime-e;if(h<=r&&(s.endTime&&r<=s.endTime||s.endTime===null)){n=!0;break}r<h&&(t=t===-1?h:Math.min(t,h))}return!n&&t!==-1?t:null}}};import{isSupportedManifest as Se,ContainerTypes as tr,ControlTypes as Ae,EventActionTypes as S,EventTypes as nr,migrateManifestToLatestVersion as St,compareVersions as ir}from"@interactiveplatform/movika-manifest";var It={metadata:"Object",chapters:"Array"},Tt=i=>{if(!te(i))return!1;for(let e in It)if(!i[e]||!G(i[e],It[e]))return!1;return Se(i.metadata.version)},xe=i=>i.type===Ae.Text,Ki=i=>i.type===Ae.Button,Qi=i=>i.type===Ae.Area,Xi={Choice:"Choice",TextInput:"TextInput"},Zi={Button:"Button",Area:"Area",Text:"Text"},qi={onClick:"onClick",onSuspense:"onSuspense"},xt={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 we=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)=>{vt(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 hn}from"@vkontakte/videoplayer-shared/evergreen";var ke=class{constructor(e){this.loaders={chapterLoaders:e?.chapterLoaders??[],manifestLoaders:e?.manifestLoaders??[]}}async exec(e,t){return sn(...this.loaders[e])(t)}};function sn(...i){return async function(t){let n=[...i];for(;n.length>0;)t=await n.shift()(t);return t}}function se(i,e,t){return i?{...i,[e]:i[e]?[t,...i[e]]:[t]}:{[e]:[t]}}function Ve({actions:i,errors:e,chapterId:t,...n}){if(t){let r=i.getManifest();if(r){let s=i.getChapter(r.chapters,t);if(s){let h=i.getMedia(r.media,s.videoId),a=i.getGraph(r.graph,s.id);return h?{...n,actions:i,errors:e,result:{chapter:s,media:h,graph:a}}:{...n,errors:se(e,Ve.name,"Could not find media"),actions:i}}}}return{...n,errors:se(e,Ve.name,"Could not find chapter"),actions:i}}var Ze=(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 an=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(te(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 ln(e.metadata.version)?{manifest:e}:{}}return{manifest:e,manifestURL:t}}catch{return{}}};async function At(i){let{manifest:e,manifestURL:t}=await an(i);if(!e)throw new Error("Failed on fetch");let n=St(e);return n.media=on(n.media,t),delete n.metadata.media,n}function Me(i,e){if(e)return i.find(t=>t.id===e)}function qe(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 Ye(i,e){return i.videos.find(t=>t.id===e)}function on(i,e){return{...i,videos:i.videos.map(t=>({...t,variants:t.variants.map(n=>{let r="url"in n?n.url:"",s=cn(r,e);return{...n,url:s||r}})}))}}function cn(i="",e){try{return new URL(i,e).href}catch{return""}}function ln(i){return Ze(i,"3.2.0")>=0}var Oe=i=>Ie(i)&&!Xe(i),_=i=>i.order==="end",Pe=i=>Ie(i.containers)&&!Xe(i.containers)&&_(i),wt=(i,e)=>{let t=i*1e3;return Oe(e.controls)&&t<(e.startTime??0)},Je=(i,e)=>{let t=i*1e3;return Oe(e.controls)&&t>=(e.startTime??0)&&t<=(e.endTime??1/0)};var W=(i=[])=>i.some(e=>e.action.type==="expect"),et=(i=[])=>i.find(e=>e.action.type==="expect"),pn=i=>i?.length===1,Y=i=>pn(i)&&xe(i[0]);function Rt(i,...e){return t=>typeof e[0]=="object"&&typeof t=="object"?i({...e[0],...t}):i(...e,...t)}var kt=(i,e)=>{let t=T=>e.find(({container:x})=>x.container.id===T)?.container.isRemoved,n=W(i.events)&&!t(i.id),r=(T,g=!1,x=!1)=>{let l=x?"every":"some";return T.controls[l](o=>{let d=g?T.endTime===i.endTime:!0;return o.events?.[l](u=>u.action?.type===xt.openURI)&&d})},s=T=>T.some(({container:g})=>r(g.container,!0,!1)&&!g.isRemoved),h=T=>T.every(({container:g})=>g.isRemoved?!0:r(g.container,!0,!0)),a=e.filter(({container:T})=>T.container.id!==i.id&&W(T.container.events)&&T.container.endTime===i.endTime&&!T.isRemoved).length,c=T=>T.controls.some(g=>g.events?.some(x=>x.action?.args?.shouldOpenNow)),p=n||a>0,f=s(e),y=r(i),C=h(e),v=n?!1:a>0,O=c(i);return{isExpectTime:p,hasOtherExpect:a>0,hasOpenURIEvent:f,hasOpenURIEventInCurrentContainer:y,isAllOpenURIEventsValid:C,isExpectEventForCurrentContainer:v,hasShouldOpenNowEvent:O}};var J=class extends ke{constructor(t,n){super(t);this.manifest=null;this.chapter=null;this.media=null;this.graph=null;this.prevChapter$=new hn(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:se},result:null,errors:null,source:t});return n.errors&&this.errorHandler(n.errors),this.manifest=await At(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",Ve({actions:{getManifest:()=>this.manifest,getCurrent:this.getCurrent,getGraph:qe,getChapter:Me,getMedia:Ye,getByBranches:this.getByBranches.bind(this),addErrorMessage:se},result:null,errors:null,chapterId:t}));return n.errors&&this.errorHandler(n.errors),n.result&&(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=Me(this.manifest.chapters,t);if(n){let r=Ye(this.manifest.media,n.videoId),s=qe(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=Me(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?_(this.chapter):!1}};import{Player as dn}from"@vkontakte/videoplayer-core/evergreen";import{Subscription as it,Tracer as un,ValueSubject as mn}from"@vkontakte/videoplayer-shared/evergreen";var Vt=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 tt(){let i=new Map;function e({listId:s=Math.random().toString(),itemId:h=Math.random().toString(),...a}){let c=i.get(s),p={...a};return c?c[h]=p:i.set(s,{[h]:p}),{listId:s,itemId:h,...a}}function t(s){s.player.destroy(),s.container.remove(),s.subscription.unsubscribe(),s.statistics?.oneStat.destroy(),s.statistics?.statSubscription.unsubscribe()}function n(s,h){let a=i.get(s);if(!a)throw Error("Can't remove. Not find.");if(h){let c=a[h];c&&t(c),delete a[h],Object.keys(a).length||i.delete(s)}else{for(let c of Object.values(a))t(c);i.delete(s)}}function r(){for(let s of i)n(s[0])}return{createPlayer:e,removePlayer:n,map:i,removeAll:r}}function nt(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 ae=(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 fn=2;function rt(i){let e=tt(),t=new it,n={},r=null,s=!1,h,a=new mn(null);i&&c(i);function c(g){r=g}function p(g,x,l){if(!r)throw Error("need to set interactive controller");if(!r.options)return;let d=(e.map.get(g)??{})[x];if(d){n={chapterId:l,listId:g,itemId:x,...d};let u=n.player;n.subscription.add(u.info.currentQuality$.subscribe(m=>{let b=u.info.position$.getValue(),A=u.info.isAutoQualityEnabled$.getValue();if(!(!m||!b||A))for(let k of e.map)Object.values(k[1]).forEach(({player:I})=>{ae(I,m)})})).add(u.events.started$.subscribe(()=>{f(x)})),d.container.remove(),r.setPlayer(d.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 f(g){if(!r)throw Error("need to set interactive controller");if(z(n)||g!==n.itemId)return;let x=r.getChapterBranches(),l=new Set;for(let o of x)l.has(o.media.id)||(await C({media:o.media,chapterId:o.chapter.id,setAsActive:!1,title:o.chapter.label}),l.add(o.media.id))}async function y({chapter:{id:g},manifestVideo:x}){if(z(n)||!r)return;let l=n.player.info.muted$.getValue(),o=n.player.info.currentQuality$.getValue(),d=n.player.info.isAutoQualityEnabled$.getValue(),u=n.player.info.volume$.getValue(),m=n.player.info.currentPlaybackRate$.getValue(),b=!d,A=!1;for(let k of e.map)if(k[0]===x.id&&!r.state.isReplay$.getValue()){let I=Object.keys(k[1]);for(let V of I)V===n.itemId?(I.length<fn||(A=!0),e.removePlayer(k[0],V)):(A=!0,p(k[0],V,g),b?ae(n.player,o):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(l),n.player.setPlaybackRate(m))}else e.removePlayer(k[0]);A||(await C({media:x,chapterId:g,setAsActive:!0,playbackRate:m}),b?ae(n.player,o):n.player.setAutoQuality(!0),n.player.setVolume(u),n.player.setMuted(l))}async function C({media:g,chapterId:x,prefetch:l=!0,setAsActive:o=!0,autoplay:d=!1,preferredExt:u,title:m,playbackRate:b}){let A=Math.random().toString(),k=document.createElement("div");h.append(k);let I;if(r?.options?.vkVideoLoader){let he=Vt(g);he.length&&(I=await r.options.vkVideoLoader(...he))}let V=r?.options?.coreConfig||void 0,j={...V,configName:[...V?.configName??[],"interactive"]},F={container:k,...I?.videos?.[0]||{sources:nt(g,u).sources},title:m,failoverHosts:I?.failoverHosts||[]},B=new dn(j,un.createRootTracer());B.initVideo(F);let H=null;if(I?.videos&&r?.options.createOneStat){let he=I.videos[0],Be=r.options.createOneStat(he),lt=new it;Be&&(lt.add(Be.attachTo(B)),H={oneStat:Be,statSubscription:lt})}let K=new it,tn=n?.player?.info.isAutoQualityEnabled$.getValue();K.add(B.events.canplay$.subscribe(function(){tn||ae(B,n.player.info.currentQuality$.getValue()),b&&B.setPlaybackRate(b)}));let Q=e.createPlayer({listId:g.id,itemId:A,player:B,container:k,sources:nt(g,u).sources,config:F,subscription:K,statistics:H});return o&&p(g.id,Q.itemId,x),d&&Q.player.play(),l&&!d&&Q.player.prepare(),{player:Q.player,config:Q.config,statistics:Q.statistics}}function v(){O(),r=null,h.remove()}function O(){t.unsubscribe(),e.removeAll(),n={},s=!1}async function T(){if(!r)throw Error("need to set interactive controller");O(),h=document.createElement("div");let{media:g,chapter:x}=r.getCurrentChapter();g&&x?(t.add(r.events.chapterChanged$.subscribe(y)),await C({media:g,chapterId:x.id,title:x.label})):console.error("not found")}return{...e,init:T,setInteractiveController:c,createPlayer:C,removeAll:v,getActivePlayer:function(){return n},activePlayerChanged:a}}var E={graph:"graph",interactives:"interactives",chapterChanged:"chapter-changed",playerChanged:"player-changed",manifestChanged:"manifest-changed",errors:"errors",eachTick:"eachTick",historyInited:"history-inited",historyDestroyed:"history-destroyed"},oe={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 yn}from"@vkontakte/videoplayer-shared/evergreen";var Ne=class{constructor({player:e,container:t,branches:n,selectBranches:r,interactiveEvents:s,globalEvents:h,globalEventEmitter:a,getContainerEventState:c,permanentTextControls:p,interactiveTimeOpenUri:f,disabledControls$:y,onRemove:C}){this.hide=()=>{setTimeout(()=>{this.gameState!==4&&(W(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)return;if(this.container.getElement()){let{hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState();if(this.container.show?.(),this.interactiveTimeOpenUri&&t)return;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:(r,s)=>{let{isExpectTime:h,hasOtherExpect:a,hasOpenURIEvent:c,hasOpenURIEventInCurrentContainer:p,isAllOpenURIEventsValid:f,hasShouldOpenNowEvent:y}=this.getContainerEventState(),C=this.interactiveTimeOpenUri&&!p,v=this.interactiveTimeOpenUri&&p;if((!this.interactiveTimeOpenUri||C)&&(this.isSelectedControlEvent=!0),r!==!1){if(!this.selectBranches.state.isExpect&&(!this.interactiveTimeOpenUri||C)){if(this.interactiveTimeOpenUri){let O=!a&&!f&&p;O&&this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:O})}this.removeView()}this.emitContainerVisibilityEvent(!1)}if(this.gameState===4||this.gameState===3||this.selectBranches.state.isExpect||this.interactiveTimeOpenUri&&c&&this.gameState!==5){if(v){let T=((g,x,l,o)=>!g&&!x&&l||g&&!x&&l&&!o||g&&!x&&l&&o)(h,a,f,this.isSelectedContainerEvent);this.fakeRemoveView(T)}else this.removeView(),this.emitContainerVisibilityEvent(!1);(!h||!a||!y)&&(this.selectBranches.stopExpect(),s())}},isEOV:()=>this.gameState===4},n=Rt(this.selectBranches.onControlEvent,t);this.container.createView({eventCallback:n}),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(Je(s,this.container.container))this.gameState!==2&&(this.gameState=2,this.onStartTime());else if(this.gameState!==3){let p=this.gameState;this.gameState=3,p===2&&this.onEndTime()}else{let{hasOpenURIEventInCurrentContainer:p}=this.getContainerEventState(),f=this.selectBranches.state.isExpect,y=this.interactiveTimeOpenUri&&p;if(y&&!f){let C=this.container.getElement();C&&(C.style.visibility!=="hidden"&&this.container.hide?.(),this.container.isRemoved||this.fakeRemoveView())}!this.isPermanentText&&!y&&this.removeView()}let h=Je(s,this.container.container),a=this.container.container.startTime?[this.container.container.startTime,this.container.container.endTime??1/0]:[],c={subjectId:this.container.container.id,subjectName:"container",range:a,currentTime:s,isInteractiveTime:h};this.globalEventEmitter.emit(E.eachTick,c),this.globalEvents.eachTick$.next(c)};this.container=t,this.branches=n,this.selectBranches=r,this.subscription=new yn,this.player=e,this.interactiveEvents=s,this.getContainerEventState=c,this.isPermanentText=p&&Y(t.container.controls),this.interactiveTimeOpenUri=f,this.disabledControls$=y,this.onRemove=C,this.globalEventEmitter=a,this.gameState=0,this.globalEvents=h,this.isSelectedControlEvent=!1,this.isSelectedContainerEvent=!1,this.registerEvents()}emitContainerVisibilityEvent(e,t=!1){e?(this.globalEventEmitter.emit(E.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(E.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){let{isExpectEventForCurrentContainer:t}=this.getContainerEventState();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,!t&&!this.container.isRemoved&&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{isExpectTime:e,hasOpenURIEventInCurrentContainer:t}=this.getContainerEventState(),n=this.interactiveTimeOpenUri?e||t:W(this.container.container.events)||e;(this.isSelectedControlEvent||!n)&&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(E.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?.()}fakeRemoveView(e=!1){this.container.isRemoved||this.globalEvents.interactiveContainerFakeRemoved$.next({subjectId:this.container.container.id,subjectName:"container",type:"container-fake-removed",removeAllOpenURI:e}),this.container.fakeRemove()}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 Ot=(i=[])=>i.reduce((e,t,n)=>{let r=(t?.controls??[]).filter(s=>!xe(s));if(Oe(r)){let s=[t.startTime??0,t.endTime??1/0],h={id:t.id,isRemoved:!1};if(!n)e.push({subjects:[h],range:s});else{let a=[],c=-1/0,p=1/0,f=[],y=[];for(let C=0;C<e.length;C++){let v=e[C];if(y.push(...v.subjects),v.range[0]<p&&(p=v.range[0]),v.range[1]>c&&(c=v.range[1]),s[0]>=v.range[0]&&s[1]<=v.range[1])return e[C].subjects.push(h),e;s[0]<v.range[0]&&s[1]>v.range[0]&&(a.push(C),f=f.concat(v.subjects)),s[0]>=v.range[0]&&s[0]<=v.range[1]&&(a.push(C),f=f.concat(v.subjects),s[0]=v.range[0]),s[1]>=v.range[0]&&s[1]<=v.range[1]&&(a.push(C),f=f.concat(v.subjects),s[1]=v.range[1])}if(y.push(h),s[0]<=p&&s[1]>=c)return[{subjects:y,range:s}];a.length&&a.reverse().forEach(C=>{e.splice(C,1)}),e.push({subjects:f.concat([h]),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 c={};for(let p in i)+p<=a&&(c[p]=i[p]);return c}function n(a){let c={};for(let p in i)+p>=a&&(c[p]=i[p]);return c}function r({timestamp:a,priority:c,initiator:p}){if(Qe(a)){let f=i[a]??null;if(f&&c&&ne(c,!0)){let y={},C=f[c];return C&&(y={...y,...C}),y=z(y)?null:y,y&&ne(p,!0)?y[p]??null:y}return f}return null}function s({timestamp:a,priority:c,initiator:p}){if(Qe(a))if(i[a]){if(c&&ne(c,!0))if(i[a][c]){if(p&&ne(p,!0))if(i[a][c][p]){if(delete i[a][c][p],!z(i[a][c]))return!0}else return!1;if(delete i[a][c],!z(i[a]))return!0}else return!1;return delete i[a]}else return!1;return!1}function h({timestamp:a,priority:c,initiator:p,...f}){i[a]?.[c]?.[p]?i[a][c][p].push({...f}):i[a]?.[c]?i[a][c]={...i[a][c],[p]:[{...f}]}:i[a]?i[a]={...i[a],[c]:{[p]:[{...f}]}}:i[a]={[c]:{[p]:[{...f}]}}}return{map:i,remove:s,add:h,removeAll:e,get:r,getLte:t,getGte:n}}var Cn=[S.expect,S.setNextBranch],vn=1/0;function Nt(i,e){let t=i,n,r=gn(e),s=Pt(),h,a=()=>{v(),l()},c=o=>{s.add.call(void 0,o),T()},p=(o=[])=>{for(let d of o)if(d.action(),Cn.includes(d.actionType))break},f=(o=1/0)=>{let d=$e(s.get({timestamp:o,priority:"control"})??{}),u=$e(s.get({timestamp:o,priority:"container"})??{}),m=$e(s.get({timestamp:o,priority:"chapter"})??{});return[...d,...u,...m]},y=o=>{r.isReady(o)&&p(f(o))},C=()=>{p([...$e(s.get({timestamp:1/0,priority:"chapter"})??{})])},v=()=>{n&&(h?.unsubscribe(),n=void 0)},O=o=>{},T=()=>{n||(n=()=>setTimeout(()=>{y(1/0)}),h=t.events.ended$.subscribe(n))},g=o=>{v(),t=o},x=o=>{o.priority==="container"&&r.resetCalled(o.timestamp),s.remove(o)},l=()=>{r.release(),s.removeAll()};return{setPlayer:g,add:c,remove:x,exec:y,execEndOfVideo:C,listen:T,unlisten:v,release:a,containersEventsCallState:r,getPreparedToExecActions:f}}function gn(i){let e=new Map;return{setCalled:({timestamp:a,id:c})=>{let p=e.get(a);p&&p[c]!==void 0&&(p[c]=!0)},setData:(a=[])=>{for(let c of a){let p=c.endTime??vn,f=e.get(p);e.set(p,{...f,[c.id]:!1})}},resetCalled:a=>{let c=e.get(a);if(c)for(let p in c)c[p]=!1},isReady:a=>{let c=e.get(a);if(!c)return!0;let p=Object.values(c);return i?p.some(y=>y):!p.some(y=>!y)},release:()=>e.clear()}}function $e(i){return Object.values(i).flat().sort(e=>e.actionType===S.expect?-1:1)}var $t={videoContentHeight:0,videoContentWidth:0},Lt=(i,e)=>{let{height:t,width:n}=e.info.intrinsicVideoSize$.getValue()||{};if(!(t&&n))return $t;let{clientHeight:r,clientWidth:s}=e.experimental.element$.getValue()||{};if(!(r&&s))return $t;let h=t/n,a=r/s,c,p;return a>h?(p=s,c=s*h):a<h?(p=r/h,c=r):(p=s,c=r),{videoContentWidth:p,videoContentHeight:c}};var bn=250;function jt(i){let e=()=>{},t=new ResizeObserver(a=>{s(a),e=s.bind(null,a)});function n(a){let{parentElement:c,player:p}=i();if(c&&p){let{videoContentWidth:f,videoContentHeight:y}=Lt(c,p);c.style.setProperty("--interactive-content-width",`${f}px`),c.style.setProperty("--interactive-content-height",`${y}px`),c.style.setProperty("--interactive-width",`${a[0].contentRect.width}px`),c.style.setProperty("--interactive-height",`${a[0].contentRect.height}px`)}}function r(){let{parentElement:a}=i();a.removeAttribute("style")}let s=ee(a=>{let{fns:c=[]}=i();n(a);for(let p of c)p()},bn);function h(){e=void 0,t.disconnect(),r()}return{resizeObserver:t,calc:()=>{e?.()},release:h}}var En=i=>Math.floor(Math.random()*i),Bt=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},_t=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 Ht=i=>{let e=i.length,t=En(e);return i[t]},Ft=1,Dt=i=>{let e=0;for(let n=0;n<i.length;++n)e+=i[n].weight??Ft;let t=Math.random()*e;e=0;for(let n=0;n<i.length-1;++n)if(e+=i[n].weight??Ft,e>=t)return i[n];return i[i.length-1]};var Ut={shouldOpenNow:!0,isDetachContainer:!0},Gt="after-expect";var st=(i,e=!1)=>({...i,args:e?{...i.args,...Ut}:{...Ut,...i.args}}),Kt=({globalEventEmitter:i,globalEvents:e,player:t,interactiveEvents:n})=>{let r={isExpect:!1},s=()=>{r.isExpect&&(r.isExpect=!1)},h=({action:l,controlType:o,controlId:d,containerId:u,branches:m=[],onEvent:b,isEOV:A=()=>!1,isDisabled:k=()=>!1})=>{let I=st(l,A()),V={timestamp:1/0,priority:"control",initiator:d,actionType:I.type},j=k(),F=i.emit.bind(i,E.interactives,{subjectId:d,subjectType:o,subjectName:"control",type:j?w.actionChoiceCanceled:w.actionChoice,actionType:l.type,payload:{invokeImmediately:I.args.shouldOpenNow,containerId:u,...I.args}}),B=()=>{e.interactiveActionChoice$.next({subjectId:d,subjectType:o,subjectName:"control",type:j?"action-choice-canceled":"action-choice",actionType:l.type,payload:{invokeImmediately:I.args.shouldOpenNow,containerId:u,...I.args}})};if(j){F(),B();return}switch(I.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let H=m.find(K=>K.id===I.args.branchId);if(!H)return;b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),F(),B(),I.args.shouldOpenNow?T({subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{chapterId:H.chapterId,autoSelect:!1}}):n.add({...V,action:T.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{chapterId:H.chapterId,autoSelect:!1}})});return}case S.continuePlayback.trim().toLowerCase():{b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),F(),B(),I.args.shouldOpenNow?O({subjectId:d,subjectName:"control",subjectType:o,action:l}):n.add({...V,action:O.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:l})});return}case S.openURI.trim().toLowerCase():{b(I.args.isDetachContainer,v.bind(null,{subjectId:d,subjectName:"control"})),F(),B(),I.args.shouldOpenNow?x({subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{URI:l.args.uri}}):n.add({...V,action:x.bind(null,{subjectId:d,subjectName:"control",subjectType:o,action:I,payload:{URI:l.args.uri}})});return}default:{let H="Unexpected control event",K=new M(1,1,{message:H});f(K,H);return}}},a=({action:l,container:{id:o,endTime:d},branches:u=[],isEOV:m=!1,autoSelected:b=!1})=>{let A=st(l,m),k={timestamp:!A.args.shouldOpenNow||m?1/0:d??1/0,priority:"container",initiator:o,actionType:A.type},I=i.emit.bind(i,E.interactives,{subjectId:o,subjectName:"container",type:w.actionChoice,actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}}),V=()=>{e.interactiveActionChoice$.next({subjectId:o,subjectName:"container",type:"action-choice",actionType:A.type,payload:{invokeImmediately:A.args.shouldOpenNow,...A.args}})};switch(A.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let j=u.find(F=>F.id===A.args.branchId);if(!j)return;I(),V(),n.add({...k,action:T.bind(null,{subjectId:o,subjectName:"container",action:A,payload:{chapterId:j.chapterId,autoSelect:b}})});return}case S.setMaxWeightBranch.trim().toLowerCase():return;case S.setMinWeightBranch.trim().toLowerCase():return;case S.setRandomBranch.trim().toLowerCase():return;case S.setWeightlessRandomBranch.trim().toLowerCase():return;case S.continuePlayback.trim().toLowerCase():{I(),V(),n.add({...k,action:O.bind(null,{subjectId:o,subjectName:"container",action:A})});return}case S.openURI.trim().toLowerCase():{I(),V(),n.add({...k,action:x.bind(null,{subjectId:o,subjectName:"container",action:A,payload:{URI:l.args.uri}})});return}default:{let j="Unexpected container event",F=new M(1,1,{message:j});f(F,j);return}}};function c({container:l,branches:o,isEOV:d=!1}){let u=et(l.events);if(u){let m=st(u.action,d);i.emit(E.interactives,{subjectId:l.id,subjectName:"container",type:w.actionChoice,actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"container",type:"action-choice",actionType:m.type,payload:{invokeImmediately:m.args.shouldOpenNow,...m.args}}),n.add({timestamp:d?1/0:l.endTime??1/0,priority:"container",initiator:l.id,actionType:S.expect,action:C.bind(null,{subjectId:l.id,subjectName:"container"})}),r.isExpect=!0}else for(let m of l.events??[])a({action:m.action,container:l,branches:o,isEOV:d})}let p=({chapterId:l,action:o,branches:d=[]})=>{let u=i.emit.bind(i,E.interactives,{subjectId:l,subjectName:"chapter",type:w.actionChoice,actionType:o.type,payload:o.args}),m=()=>{e.interactiveActionChoice$.next({subjectId:l,subjectName:"chapter",type:"action-choice",actionType:o.type,payload:o.args})};switch(o.type.trim().toLowerCase()){case S.setNextBranch.trim().toLowerCase():{let b=d.find(A=>A.id===o.args.branchId);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setWeightlessRandomBranch.trim().toLowerCase():{let b=Ht(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setRandomBranch.trim().toLowerCase():{let b=Dt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setMaxWeightBranch.trim().toLowerCase():{let b=_t(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.setMinWeightBranch.trim().toLowerCase():{let b=Bt(d);return b?.chapterId?(u(),m(),T.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{chapterId:b.chapterId,autoSelect:!0}})):void 0}case S.continuePlayback.trim().toLowerCase():return u(),m(),O.bind(null,{subjectId:l,subjectName:"chapter",action:o});case S.openURI.trim().toLowerCase():return u(),m(),x.bind(null,{subjectId:l,subjectName:"chapter",action:o,payload:{URI:o.args.uri}});default:{let b="Unexpected chapter event",A=new M(1,1,{message:b});f(A,b);return}}};function f(l,o){console.error(o),e.error$.next(l),i.emit(E.errors,l)}function y(l){let o=et(l.events);if(o){if(_(l))return;i.emit(E.interactives,{subjectId:l.id,subjectName:"chapter",type:w.actionChoice,actionType:o.action.type,payload:o.action.args}),e.interactiveActionChoice$.next({subjectId:l.id,subjectName:"chapter",type:"action-choice",actionType:o.action.type,payload:o.action.args}),n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:S.expect,action:C.bind(null,{subjectId:l.id,subjectName:"chapter"})})}else l.events?.forEach(d=>{let u=p({chapterId:l.id,action:d.action,branches:l.branches});u&&n.add({timestamp:1/0,priority:"chapter",initiator:l.id,actionType:d.action.type,action:u})})}let C=({subjectId:l,subjectName:o})=>{t.pause(),i.emit(E.interactives,{subjectId:l,subjectName:o,type:w.actionExecution,actionType:S.expect}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,type:"action-execution",actionType:S.expect})},v=({subjectId:l,subjectName:o})=>{t.info.isEnded$.getValue()?n.execEndOfVideo():t.play(),i.emit(E.interactives,{subjectId:l,subjectName:o,type:w.actionExecution,actionType:Gt}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,type:"action-execution",actionType:Gt})},O=({subjectId:l,subjectName:o,subjectType:d,action:u})=>{i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type})},T=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{m.behaviour="change-chapter",i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},g=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{m.behaviour="change-manifest",i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type,payload:m}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type,payload:m})},x=({subjectId:l,subjectName:o,subjectType:d,action:u,payload:m})=>{if(!m.URI)return;let b=window.open(m.URI,"_blank","noopener,noreferrer");b&&(b.opener=null),i.emit(E.interactives,{subjectId:l,subjectName:o,subjectType:d,type:w.actionExecution,actionType:u.type}),e.interactiveActionExecution$.next({subjectId:l,subjectName:o,subjectType:d,type:"action-execution",actionType:u.type})};return{onControlEvent:h,onContainerEvent:a,onChapterEvent:p,onExpectEvent:C,expectEventHandler:v,setManifestChapterEvents:y,setManifestContainerEvents:c,stopExpect:s,state:r}};import{Subscription as An,Subject as ot,ValueSubject as ce}from"@vkontakte/videoplayer-shared/evergreen";var at=(i,e)=>{let t={};return i.map(n=>{if(!t[n]){let r=e.chapters.find(h=>h.id===n);if(!r)return null;let s=e.media.videos.find(h=>r.videoId===h.id);if(!s)return null;t[n]=Qt(s)}return t[n]}).filter(Boolean)},Tn=i=>{for(let e of i.variants)if(xn(e)&&e.payload)return e.payload.id},xn=i=>!!(i.type==="custom"&&i.payload&&i.payload.type==="vk"),Qt=i=>{let e=Tn(i);if(!e)return null;let t=e.split("_").pop();return t?parseInt(t,10):null},Sn=(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}},Xt=(i,e)=>i.reduce((t,n)=>{let r=Sn(e,n);return r?[...t,r]:t},[]);var le=class{constructor({globalEventEmitter:e,videoId:t,interactiveController:n,historyApi:r,settings:s}){this.state={history$:new ce([]),hasPrevChapter$:new ce(!1),prevChapter$:new ce(null),isInitialChapter$:new ce(!1),isGoBackLimited$:new ce(!1)};this.#n=null;this.#a=!1;this.#e=null;this.#p=null;this.events={inited$:new ot,destroyed$:new ot,error$:new ot};this.#i=null;this.#r=null;this.#t=null;this.#o=new An;this.#c=!1;this.#l=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(h=>{this.state.prevChapter$.next(h.at(-2)||null),this.state.hasPrevChapter$.next(h.length>1),this.state.isInitialChapter$.next(this.getInitialChapterId()===this.#e?.metadata?.initChapterId),this.state.isGoBackLimited$.next(this.#l===this.#s.maxLength-1)}))}#n;#s;#a;#e;#p;#i;#r;#t;#o;#c;#l;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.#c?(this.#c=!1,this.#l++):this.#l=0;let n=this.#e,r=e.length-this.#s.maxLength,s=r>0?e.slice(r):e,h=at(s,n);if(this.#p=h,this.state.history$.next(s),!(!t||!this.#n||!this.#i))try{await this.#n.save(this.#i,h)}catch{let c=new M(1,5,"Unable to save interactive history");this.events.error$.next(c),this.#t?.emit(E.errors,c)}}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(E.errors,n)}this.#c=!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(E.errors,s)}let n=Xt(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 at([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(E.historyDestroyed),this.events.destroyed$.next(),this.#t=null}};var Le=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 je=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=`
|
|
7
7
|
position: absolute;
|
|
8
8
|
top: 0;
|
|
9
9
|
left: 0;
|
|
@@ -16,8 +16,45 @@ var lt="1.0.32-dev.162375f7.0";function Fe(i,e=1){let t="0",n="0",r="0";return i
|
|
|
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),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}};function
|
|
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),n={width:parseInt(t.getPropertyValue("--interactive-content-width"),10),height:parseInt(t.getPropertyValue("--interactive-content-height"),10)};try{this.lastFrameCanvas.updateCanvasDimensions(n,e)}catch(r){this._onError(r)}}draw(){(this._containerTimeFrameShouldReceived||!this._containerTimeFrameShouldReceived&&!this._endTimeFrameReceived)&&this.lastFrameCanvas.draw()}isChapterEndTime(e){return this.currentVideoDurationMs&&e>=this.currentVideoDurationMs-this.endOffsetMs}isContainerTime(e){if(this.currentChapter)return this.currentChapter.containers.some(t=>t.controls?.length&&e>=(t.startTime??0)&&e<=Math.min(t.endTime??1/0,this.currentVideoDurationMs-this.endOffsetMs))}reset(){this._endTimeFrameReceived=!1,this._containerTimeFrameShouldReceived=!1,this._shouldCallSkip=!1}_onError(e){this._callbacks?.onError?.(e)}};function Zt(i=0){return new Promise(e=>{setTimeout(()=>{e(0)},i)})}var wn=`
|
|
20
|
+
.${L.common} {
|
|
21
|
+
opacity: 1;
|
|
22
|
+
visibility: visible;
|
|
23
|
+
transition: opacity var(--interactive-transition-1);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
.${L.disabled} {
|
|
27
|
+
opacity: 0.5;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
.${L.hidden} {
|
|
31
|
+
visibility: hidden;
|
|
32
|
+
}
|
|
33
|
+
`,Rn=`
|
|
34
|
+
.interactive-chapter {
|
|
20
35
|
position: absolute;
|
|
21
36
|
top: 0;
|
|
22
37
|
left: 0;
|
|
23
|
-
`,i}var je=class{constructor(e){this.playerSubscriptions=new at;this.subscriptions=new at;this.globalEventEmitter=new we;this.animation=new Ae;this.seekToInteractiveController=new ne;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=wn();this.factories=new Map([["choice",ge]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new at;this.graph=null;this.lastFrame=null;this.appState=0;this.state={prevChapter$:new $(null),isInitialChapter$:new $(!1),isFirstChapter$:new $(!0),isEndChapter$:new $(!1),isInteractiveExpectation$:new $(!1),isReplay$:new $(!1),calledByInteractive$:new $(!1),lastChapterChangeWasInitiatedByInteractive$:new $(!1),disabledControls$:new $(!1),interactiveRanges$:new $([]),isInteractiveTime$:new $(!1),statistics$:new $(null),isSeekable$:new $(!1)};this.events={noInteraction$:new P,graphVisibilityChanged$:new P,watchAgainIsClicked$:new P,chapterChanged$:new P,playerChanged$:new P,error$:new P,eachTick$:new P,manifestChanged$:new P,interactiveRangeEnded$:new P,interactiveContainerRemoved$:new P,interactiveActionExecution$:new P,interactiveActionChoice$:new P,interactiveVisibilityChanged$:new P};this.emitErrorEvent=e=>{this.events.error$.next(e),this.globalEventEmitter.emit(y.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(y.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(p=>p!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};this._options={...Kt,...e,config:{...Kt.config,...e.config}},this._options.parentElement.append(this.rootElement),this.historyController=new oe({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 Oe({parentElement:this._options.parentElement,onError:t=>{let n=new R(1,6,t);this.emitErrorEvent(n)}})),this.subscriptions.add(Qt(this.rootElement,"mousedown").subscribe(t=>t.stopPropagation())).add(Qt(this.rootElement,"mouseup").subscribe(t=>t.stopPropagation())),this.manifestController=new q(this._options.loaders,t=>{let n=new R(1,3,t);this.emitErrorEvent(n)}),this.resizeManager=Pt(()=>({player:this.player,parentElement:this._options?.parentElement,fns:this._options?.lastFrame?[()=>{this.lastFrame?.updateCanvasDimensions(!0)}]:[]})),this._options.graph&&(this.graph=new te({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:t=>{this.setChapter({chapterId:t}),this.globalEventEmitter.emit(y.graph,{type:se.watchAgainClicked,chapterId:t}),this.events.watchAgainIsClicked$.next(t)},onError:t=>{let n=new R(1,2,{message:t});this.emitErrorEvent(n)}})),this.initSubscriptions()}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):e.actionType==="after-expect"&&this.state.isInteractiveExpectation$.next(!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:n})=>{e!=="action-choice"||t==="chapter"||"invokeImmediately"in n&&n.invokeImmediately||this.removeControllers(!1)}))}async initSeamless(){this.seamlessController=nt(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(y.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(Sn()).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(Tn({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 l=e*1e3;r=!!t.find(({range:[v,T],subjects:b})=>v<l&&l<T&&b.length)}r!==this.state.isInteractiveTime$.getValue()&&this.state.isInteractiveTime$.next(r);let s=!!this.noInteractionTimeout,a=this.player?.info.playbackState$.getValue()==="playing"||n;r&&!s&&a?this.noInteractionTimeout=window.setTimeout(()=>{this.events.noInteraction$.next()},this._options.config.noInteractionEventTimeout):s&&!a&&this.clearNoInteractionTimeout()})),this.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.filterGameControllers(e),this.interactiveEvents?.containersEventsCallState.setData(e.containers),this.seekToInteractiveController.setContainers(this.gameControllers.map(t=>t.container.container).filter(t=>!Z(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(),p=this.factories.get(r)?.(n,this.rootElement);if(p&&this.selectBranches&&this.interactiveEvents&&this.player){let a=new $e({player:this.player,container:p,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,ignoreContainerEvent:()=>xt(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)&&Pe(n))??!1,s=this.manifestController.manifest?.metadata.initChapterId===e,p=this.historyController.state.history$.getValue();if(s||r&&t){this.historyController.updateHistory([e]);return}p.at(-1)!==e&&this.historyController.updateHistory([...p,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(y.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=Rt(this.player),this.selectBranches=Dt({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:n=!1}={}){this.reset(),this.lastFrame&&this.isFirstChapterFetched&&(this.lastFrame.draw(),this.lastFrame.show()),In.isSafari&&await zt(35);let r=!n&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:s,media:p,graph:a}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!s||!p)&&(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:p}),this.globalEventEmitter.emit(y.chapterChanged,{chapter:s,media:p,graph:a}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new Wt(e=>{this.subscriptions.add(this.events.graphVisibilityChanged$.subscribe(t=>{e.next(t?le.GRAPH_SHOW:le.GRAPH_HIDE)})).add(this.events.watchAgainIsClicked$.subscribe(()=>{e.next(le.WATCH_AGAIN)})).add(this.events.interactiveActionChoice$.subscribe(({type:t,subjectName:n,subjectType:r})=>{t!=="action-choice"||n!=="control"||(r==="Button"&&e.next(le.NEXT_BUTTON),r==="Area"&&e.next(le.NEXT_AREA))}))}),nextMovie$:new Wt(e=>{this.events.playerChanged$.subscribe(({config:t})=>{t?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&e.next(t.unitedVideoId)})})}}async toggleGraphView(e=!0){this.graph&&(e?(await this.graph.show(),this.state.isSeekable$.next(!1)):(this.graph.hide(),this.checkIfSeekable()),this.globalEventEmitter.emit(y.graph,{type:se.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===g.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&&z(r.events)})}playPrevChapter(){this.historyController.goBack()}setDisabledControls(e){this.state.disabledControls$.next(e)}isSupport(e=this.manifestController.manifest){return!!e&&xe(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 At(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.playerSubscriptions.unsubscribe(),this.subscriptions.unsubscribe(),this.globalEventEmitter.reset(),this.lastFrame?.destroy(),this.rootElement.remove(),this.historyController.destroy(),this.isFirstChapterFetched=!1,this.appState=3}};var An={Container:X,createChoiceContainer:ge,createAreaControl:fe,createButtonControl:Ce,getRootEl:pe,classnamesPrefix:M};var Bs={version:lt};export{Bi as ContainerTypes,Se as ControlTypes,R as CustomError,y as EVENT_NAMES,g as EventActionTypes,Fi as EventTypes,je as Interactives,q as ManifestController,Bs as SDKInfo,rt as chapterIdsToVKVideoIds,Ke as compareVersions,Mi as containerTypes,Pi as controlTypes,Ni as eventActionTypes,$i as eventTypes,bn as getChapterIdByVkVideoId,Gt as getVKVideoIdByMedia,vn as getVideoRawIdByMedia,se as graphEventTypes,Pe as hasEndTemplate,w as interactivesEventTypes,Vi as isAreaControl,Ri as isButtonControl,F as isLastChapter,Z as isOneTextCtrlContainer,xe as isSupportedManifest,Te as isTextControl,gn as isVKVariantItem,gt as isValidManifest,bt as migrateManifestToLatestVersion,An as utils,Ut as vkVideoIdsToChapterIds};
|
|
38
|
+
font-family: inherit;
|
|
39
|
+
|
|
40
|
+
--interactive-transition-1: 100ms ease-in-out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
${wn}
|
|
44
|
+
|
|
45
|
+
.${R.common} {
|
|
46
|
+
display: flex;
|
|
47
|
+
width: 100%;
|
|
48
|
+
height: 100%;
|
|
49
|
+
font-family: inherit;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
.${R.disabled} {
|
|
53
|
+
cursor: default;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
.${R.button},
|
|
57
|
+
.${R.area} {
|
|
58
|
+
cursor: pointer;
|
|
59
|
+
}
|
|
60
|
+
`,qt=i=>{let e=document.createElement("style");e.textContent=Rn,i.prepend(e)};import{clientChecker as On}from"@vkontakte/videoplayer-core/evergreen";var en=Object.freeze({lang:Vn.RU,loaders:{},graph:!1,initSeamless:!1,lastFrame:!1,permanentTextControls:!0,interactiveTimeOpenUri:!1,config:{historyMaxLength:100,noInteractionEventTimeout:3e4}});function Pn(){let i=document.createElement("div");return i.classList.add("interactive-chapter"),i}var Fe=class{constructor(e){this.playerSubscriptions=new ct;this.subscriptions=new ct;this.globalEventEmitter=new we;this.animation=new Re;this.seekToInteractiveController=new re;this.endedRanges=new Set;this.gameControllers=[];this.rootElement=Pn();this.factories=new Map([["choice",be]]);this.isFirstChapterFetched=!1;this.player=null;this.interactiveEvents=null;this.selectBranches=null;this.seamlessController=null;this.seamlessControllerSubs=new ct;this.graph=null;this.lastFrame=null;this.appState=0;this.state={prevChapter$:new $(null),isInitialChapter$:new $(!1),isFirstChapter$:new $(!0),isEndChapter$:new $(!1),isInteractiveExpectation$:new $(!1),isReplay$:new $(!1),calledByInteractive$:new $(!1),lastChapterChangeWasInitiatedByInteractive$:new $(!1),disabledControls$:new $(!1),interactiveRanges$:new $([]),isInteractiveTime$:new $(!1),statistics$:new $(null),isSeekable$:new $(!1)};this.events={noInteraction$:new N,graphVisibilityChanged$:new N,watchAgainIsClicked$:new N,chapterChanged$:new N,playerChanged$:new N,error$:new N,eachTick$:new N,manifestChanged$:new N,interactiveRangeEnded$:new N,interactiveContainerRemoved$:new N,interactiveContainerFakeRemoved$:new N,interactiveActionExecution$:new N,interactiveActionChoice$:new N,interactiveVisibilityChanged$:new N};this.emitErrorEvent=e=>{this.events.error$.next(e),this.globalEventEmitter.emit(E.errors,e)};this.clearHistoryIfEnded=()=>{let e=this.player?.info.isEnded$.getValue(),t=this.state.isInteractiveExpectation$.getValue(),{chapter:n}=this.getCurrentChapter();e&&n&&_(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(E.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(h=>h.id!==e)}));t.next(r)};this.clearNoInteractionTimeout=()=>{this.noInteractionTimeout&&(clearTimeout(this.noInteractionTimeout),this.noInteractionTimeout=void 0)};this._options={...en,...e,config:{...en.config,...e.config}},this._options.parentElement.append(this.rootElement),this.historyController=new le({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 je({parentElement:this._options.parentElement,onError:n=>{let r=new M(1,6,n);this.emitErrorEvent(r)}})),qt(this._options.parentElement),this.subscriptions.add(Jt(this.rootElement,"mousedown").subscribe(n=>n.stopPropagation())).add(Jt(this.rootElement,"mouseup").subscribe(n=>n.stopPropagation())),this.manifestController=new J(this._options.loaders,n=>{let r=new M(1,3,n);this.emitErrorEvent(r)});let t=[];this._options.lastFrame&&t.push(()=>{this.lastFrame?.updateCanvasDimensions(!0)}),this.resizeManager=jt(()=>({player:this.player,parentElement:this._options.parentElement,fns:t})),this._options.graph&&(this.graph=new ie({root:this._options.parentElement,lang:this._options.lang,onOpenPreviewClick:n=>{this.setChapter({chapterId:n}),this.globalEventEmitter.emit(E.graph,{type:oe.watchAgainClicked,chapterId:n}),this.events.watchAgainIsClicked$.next(n)},onError:n=>{let r=new M(1,2,{message:n});this.emitErrorEvent(r)}})),this.initSubscriptions()}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.interactiveContainerFakeRemoved$.subscribe(({subjectId:e,removeAllOpenURI:t})=>{this.handleFakeRemoval(e,t)})).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)})).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:n})=>{e!=="action-choice"||t==="chapter"||"invokeImmediately"in n&&n.invokeImmediately||this.removeControllers(!1)}))}async initSeamless(){this.seamlessController=rt(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(E.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(Mn()).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(kn({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 c=e*1e3;r=!!t.find(({range:[f,y],subjects:C})=>f<c&&c<y&&C.some(v=>!v.isRemoved)&&C.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.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.filterGameControllers(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)}filterGameControllers(e){let t=[];return e.containers.forEach(n=>{let r=n.type.trim().toLowerCase(),h=this.factories.get(r)?.(n,this.rootElement);if(h&&this.selectBranches&&this.interactiveEvents&&this.player){let a=new Ne({player:this.player,container:h,branches:e.branches,selectBranches:this.selectBranches,interactiveEvents:this.interactiveEvents,globalEvents:this.events,globalEventEmitter:this.globalEventEmitter,getContainerEventState:()=>kt(n,this.gameControllers),permanentTextControls:this._options.permanentTextControls,interactiveTimeOpenUri:this._options.interactiveTimeOpenUri,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&&_(n)&&Pe(n))??!1,s=this.manifestController.manifest?.metadata.initChapterId===e,h=this.historyController.state.history$.getValue();if(s||r&&t){this.historyController.updateHistory([e]);return}h.at(-1)!==e&&this.historyController.updateHistory([...h,e])}handleFakeRemoval(e,t){let{interactiveRanges$:n}=this.state,s=n.getValue().map(h=>{let a=h.subjects.some(p=>p.id===e),c=h.subjects.map(p=>t&&a||p.id===e?{...p,isRemoved:!0}:p);return{...h,subjects:c}});n.next(s)}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(E.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=Nt(this.player,this._options.interactiveTimeOpenUri),this.selectBranches=Kt({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:n=!1}={}){this.reset(),this.lastFrame&&this.isFirstChapterFetched&&(this.lastFrame.draw(),this.lastFrame.show()),this.lastFrame&&On.browser.isSafari&&await Zt(35);let r=!n&&this.state.isEndChapter$.getValue()&&this.getCurrentManifest()?.metadata.initChapterId===e;this.state.isReplay$.next(r);let{chapter:s,media:h,graph:a}=await(e?this.manifestController.setNext(e):this.manifestController.setInitial());(!e||r)&&this.state.isFirstChapter$.next(!0),!(!s||!h)&&(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:h}),this.globalEventEmitter.emit(E.chapterChanged,{chapter:s,media:h,graph:a}),this.setGameControllers(),this.endedRanges=new Set,this.isFirstChapterFetched=!0)}getStatEvents(){return{click$:new Yt(e=>{this.subscriptions.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 Yt(e=>{this.events.playerChanged$.subscribe(({config:t})=>{t?.unitedVideoId&&!this.state.isFirstChapter$.getValue()&&e.next(t.unitedVideoId)})})}}async toggleGraphView(e=!0){this.graph&&(e?(await this.graph.show(),this.state.isSeekable$.next(!1)):(this.graph.hide(),this.checkIfSeekable()),this.globalEventEmitter.emit(E.graph,{type:oe.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===S.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&&W(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 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.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.playerSubscriptions.unsubscribe(),this.subscriptions.unsubscribe(),this.globalEventEmitter.reset(),this.lastFrame?.destroy(),this.rootElement.remove(),this.historyController.destroy(),this.isFirstChapterFetched=!1,this.appState=3}};var Nn={Container:X,createChoiceContainer:be,createAreaControl:Ce,createButtonControl:ge,classnamesPrefix:dt};var aa={version:pt};export{tr as ContainerTypes,Ae as ControlTypes,M as CustomError,E as EVENT_NAMES,S as EventActionTypes,nr as EventTypes,Fe as Interactives,J as ManifestController,aa as SDKInfo,at as chapterIdsToVKVideoIds,Ze as compareVersions,Xi as containerTypes,Zi as controlTypes,xt as eventActionTypes,qi as eventTypes,Sn as getChapterIdByVkVideoId,Qt as getVKVideoIdByMedia,Tn as getVideoRawIdByMedia,oe as graphEventTypes,Pe as hasEndTemplate,w as interactivesEventTypes,Qi as isAreaControl,Ki as isButtonControl,_ as isLastChapter,Y as isOneTextCtrlContainer,Se as isSupportedManifest,xe as isTextControl,xn as isVKVariantItem,Tt as isValidManifest,St as migrateManifestToLatestVersion,Nn as utils,Xt as vkVideoIdsToChapterIds};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vkontakte/videoplayer-interactive",
|
|
3
|
-
"version": "1.0.32-dev.
|
|
3
|
+
"version": "1.0.32-dev.ae886eaa.0",
|
|
4
4
|
"author": "vk.com",
|
|
5
5
|
"description": "Movika interactive SDK",
|
|
6
6
|
"homepage": "https://vk.com",
|
|
@@ -51,8 +51,8 @@
|
|
|
51
51
|
"dependencies": {
|
|
52
52
|
"@interactiveplatform/movika-graph-editor": "1.11.0",
|
|
53
53
|
"@interactiveplatform/movika-manifest": "^1.0.0",
|
|
54
|
-
"@vkontakte/videoplayer-core": "2.0.127-dev.
|
|
55
|
-
"@vkontakte/videoplayer-shared": "
|
|
56
|
-
"@vkontakte/videoplayer-statistics": "1.0.72-dev.
|
|
54
|
+
"@vkontakte/videoplayer-core": "2.0.127-dev.7b82b714.0",
|
|
55
|
+
"@vkontakte/videoplayer-shared": "1.0.55-dev.7f3a7134.0",
|
|
56
|
+
"@vkontakte/videoplayer-statistics": "1.0.72-dev.e742d35c.0"
|
|
57
57
|
}
|
|
58
58
|
}
|
|
@@ -67,6 +67,7 @@ export declare class Interactives {
|
|
|
67
67
|
private updateLastEventInfo;
|
|
68
68
|
private pushChapterToHistory;
|
|
69
69
|
private completeInteractiveRange;
|
|
70
|
+
private handleFakeRemoval;
|
|
70
71
|
private clearNoInteractionTimeout;
|
|
71
72
|
private reset;
|
|
72
73
|
get options(): IInteractiveOptions;
|
|
@@ -86,6 +87,16 @@ export declare class Interactives {
|
|
|
86
87
|
setVisitedChapters(chapterIds: string[]): void;
|
|
87
88
|
updateGraphVideosInfo(videosInfo: VideoInfo[]): void;
|
|
88
89
|
deadEndCheck(): boolean;
|
|
90
|
+
/**
|
|
91
|
+
* Проверяет, удалены ли все контроллы.
|
|
92
|
+
*
|
|
93
|
+
* Контрол считается удалённым, если его флаг `isRemoved` установлен в `true`.
|
|
94
|
+
* Однако, есть исключение для `openURI` — если с ним было взаимодействие, он
|
|
95
|
+
* получит `isRemoved = true`, но может оставаться в DOM до завершения эпизода (`endTime`).
|
|
96
|
+
*
|
|
97
|
+
* Из-за этого метод может вернуть `true` (что все контроллы "удалены"),
|
|
98
|
+
* хотя `openURI` всё ещё присутствует в DOM.
|
|
99
|
+
*/
|
|
89
100
|
allControlsAreRemoved(): boolean;
|
|
90
101
|
isEndedExpectation(): boolean;
|
|
91
102
|
playPrevChapter(): void;
|
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
import { Container } from './Container';
|
|
2
|
-
import { ChapterContainer } from
|
|
3
|
-
import {
|
|
4
|
-
export declare const createChoiceContainer: (container: ChapterContainer, rootElement: HTMLElement) => ChoiceContainer | undefined;
|
|
2
|
+
import { ChapterContainer } from '../../../manifest';
|
|
3
|
+
import type { ChoiceContainerOptions, ContainerCreateViewParams } from './types';
|
|
4
|
+
export declare const createChoiceContainer: (container: ChapterContainer, rootElement: HTMLElement, options?: ChoiceContainerOptions) => ChoiceContainer | undefined;
|
|
5
5
|
export declare class ChoiceContainer extends Container {
|
|
6
6
|
private rootElement;
|
|
7
|
+
private containerElement;
|
|
7
8
|
private layout;
|
|
8
9
|
isRemoved: boolean;
|
|
9
10
|
isDisabled: boolean;
|
|
10
|
-
constructor(container: ChapterContainer, rootElement: HTMLElement);
|
|
11
|
-
createView(eventCallback:
|
|
11
|
+
constructor(container: ChapterContainer, rootElement: HTMLElement, options?: ChoiceContainerOptions);
|
|
12
|
+
createView({ eventCallback }: ContainerCreateViewParams): HTMLElement;
|
|
12
13
|
hide(): void;
|
|
13
14
|
show(): void;
|
|
14
15
|
enable(): void;
|
|
15
16
|
disable(): void;
|
|
16
17
|
removeView(): void;
|
|
17
|
-
|
|
18
|
+
fakeRemove(): void;
|
|
19
|
+
getElement(): Nullable<HTMLElement>;
|
|
18
20
|
}
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import type { ChapterContainer } from '../../../manifest';
|
|
2
|
+
import { type Control, type ControlCreator, type Options } from '../../../modules/Interactives/controls';
|
|
3
|
+
import { type ChoiceContainerOptions } from './types';
|
|
4
4
|
export declare class Container {
|
|
5
5
|
container: ChapterContainer;
|
|
6
|
+
options?: Options;
|
|
6
7
|
private factories;
|
|
7
8
|
controls: Control[];
|
|
8
|
-
constructor(container: ChapterContainer);
|
|
9
|
-
|
|
9
|
+
constructor(container: ChapterContainer, options?: Options);
|
|
10
|
+
featureIsEnabled(name: keyof ChoiceContainerOptions['features']): false | undefined;
|
|
11
|
+
addControlFactory(type: string, factory: ControlCreator<any>): void;
|
|
10
12
|
removeControlFactory(type: string): void;
|
|
11
13
|
private setControls;
|
|
12
14
|
private chooseControls;
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { Options, ControlEventCallback } from '../controls';
|
|
2
|
+
import { AnimationsFeatureToggles } from '../types';
|
|
3
|
+
export type ChoiceContainerOptions = {
|
|
4
|
+
features: Pick<AnimationsFeatureToggles, never>;
|
|
5
|
+
};
|
|
6
|
+
export declare function isChoiceContainerOptions(options: Options): options is ChoiceContainerOptions;
|
|
7
|
+
export type ContainerCreateViewParams = {
|
|
8
|
+
eventCallback: ControlEventCallback;
|
|
9
|
+
};
|
|
@@ -1,2 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Control } from './Control';
|
|
2
|
+
import { type ControlCreator, type ControlCreateViewParams, type TControl, type ControlOptions } from './types';
|
|
3
|
+
export declare const createAreaControl: ControlCreator<ControlOptions, AreaControl>;
|
|
4
|
+
declare class AreaControl extends Control {
|
|
5
|
+
constructor(control: TControl, options?: ControlOptions);
|
|
6
|
+
createView({ parentElement, callbacks }: ControlCreateViewParams): void;
|
|
7
|
+
disable(): void;
|
|
8
|
+
enable(): void;
|
|
9
|
+
getElement(): Nullable<HTMLElement>;
|
|
10
|
+
}
|
|
11
|
+
export {};
|
|
@@ -1,2 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Control } from './Control';
|
|
2
|
+
import { type ControlCreator, type ControlCreateViewParams, type TControl, type ControlOptions } from './types';
|
|
3
|
+
export declare const createButtonControl: ControlCreator<ControlOptions, ButtonControl>;
|
|
4
|
+
declare class ButtonControl extends Control {
|
|
5
|
+
constructor(control: TControl, options?: ControlOptions);
|
|
6
|
+
createView({ parentElement, callbacks }: ControlCreateViewParams): void;
|
|
7
|
+
disable(): void;
|
|
8
|
+
enable(): void;
|
|
9
|
+
getElement(): Nullable<HTMLElement>;
|
|
10
|
+
}
|
|
11
|
+
export {};
|
|
@@ -1,20 +1,23 @@
|
|
|
1
|
-
import type { ControlEventCallback,
|
|
1
|
+
import type { ControlEventCallback, ControlCreateViewParams, Dimensions, Callbacks, Options, TControl, ControlOptions } from './types';
|
|
2
2
|
type ControlContainer = {
|
|
3
3
|
element: HTMLElement;
|
|
4
4
|
dimensions: Dimensions;
|
|
5
5
|
};
|
|
6
|
-
|
|
6
|
+
type ClickListener = (event: MouseEvent) => void;
|
|
7
|
+
export declare abstract class Control {
|
|
7
8
|
control: TControl;
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
9
|
+
options?: Options | undefined;
|
|
10
|
+
container: Nullable<ControlContainer>;
|
|
11
|
+
controlElement: Nullable<HTMLElement>;
|
|
12
|
+
clickListener: Nullable<ClickListener>;
|
|
13
|
+
constructor(control: TControl, options?: Options | undefined);
|
|
14
|
+
abstract createView(params: ControlCreateViewParams): void;
|
|
13
15
|
abstract getElement(): Nullable<HTMLElement>;
|
|
14
16
|
abstract disable(): void;
|
|
15
17
|
abstract enable(): void;
|
|
16
|
-
|
|
17
|
-
|
|
18
|
+
createContainerElement(callbacks: Callbacks): void;
|
|
19
|
+
createClickListener(callback: AnyFn): ClickListener;
|
|
20
|
+
featureIsEnabled(name: keyof ControlOptions['features']): false | undefined;
|
|
18
21
|
setEvents(callback: ControlEventCallback): void;
|
|
19
22
|
removeListeners(): void;
|
|
20
23
|
}
|
|
@@ -1,2 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
|
|
1
|
+
import { Control } from './Control';
|
|
2
|
+
import { type ControlCreator, type ControlCreateViewParams, type TControl, type ControlOptions } from './types';
|
|
3
|
+
export declare const createTextControl: ControlCreator<ControlOptions, TextControl>;
|
|
4
|
+
declare class TextControl extends Control {
|
|
5
|
+
constructor(control: TControl, options?: ControlOptions);
|
|
6
|
+
createView({ parentElement, callbacks }: ControlCreateViewParams): void;
|
|
7
|
+
disable(): void;
|
|
8
|
+
enable(): void;
|
|
9
|
+
getElement(): Nullable<HTMLElement>;
|
|
10
|
+
}
|
|
11
|
+
export {};
|