/** * tilda-video-processor необходим для блоков, где в качестве фоновой обложки зачастую используюся видео - * (CR...). Однако иногда это могут быть остальные блоки: видео VD01; последовательность слайдов GL06. * Видео загружается ссылкой и может воспроизводиться либо как в формате .mp4 и .webm для HTML5-проигрывателя, * либо это будет ссылка на YouTube видео и соответственно YouTube-плеер. Для первого случая - основная функция в скрипте * t_videoprocessor__processHTML5Video, для второго - processYoutubeVideo. В них происходят по сути идентичные сценарии: * получаем параметры, переданные через tilda-cover, эти параметры применяем на видео, которое будет создавать, вешаем * обработчики по ресайзу или скроллу: * например, постановку на паузу, если видео не в зоне видимости; переопределение высоты контейнера и видео; и тд. * * В tilda-cover можно установить эффект при скролле: паралакс или фиксацию. Фиксация в видео не * работает. * * В setWidthAndHeightVideo обложка для YouTube увеличена по высоте, чтобы пользователь не видел * рекламный блок снизу, это вынесено в переменной isAdCutted. * * Фоновые видео не работают в мобильных и планшетных версиях. * * Функция processYoutubeVideo() помимо видео-обложек используется в блоках GL06 и VD01. * Функция setWidthAndHeightVideo() кроме обложек может использоваться в блоках CR32N и CR26AN */ /** * append to head YouTube api script, wait after load YT (YouTube object) * to create iframe and set properties. * Naming without prefix because this function used in GL06 and VD01. * * @param {HTMLElement} el * @param {string} height */ function processYoutubeVideo(el, height) { // append YouTube API script if (!document.getElementById('youtube-api')) { var script = document.createElement('script'); script.id = 'youtube-api'; script.src = 'https://www.youtube.com/iframe_api'; document.head.insertAdjacentElement('beforeend', script); } t_videoprocessor__onFuncLoad('YT', function () { // create object with YouTube video params, which will be found by data-attributes in current element var videoObject = { 'url-youtube': '', nomute: '', noloop: '', nocover: '', }; // iterating keys from created object and append to it current values for (var key in videoObject) { var value = el.getAttribute('data-content-video-' + key); if (value) videoObject[key] = value; } // force disable sound from video inside covers if (videoObject['nocover'] !== 'yes') videoObject['nomute'] = ''; // append new values to simplified using in t_videoprocessor__setYoutubePlayer videoObject['mute'] = videoObject['nomute'] !== 'yes'; videoObject['loop'] = videoObject['noloop'] !== 'yes'; videoObject['cover'] = videoObject['nocover'] !== 'yes'; t_videoprocessor__setYoutubePlayer(el, videoObject); t_onReady(function () { t_videoprocessor__updateVideoHeight(el, height, 'youtube'); }); if ( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || 'ontouchend' in document ) { return; } // update params of maxHeight in resize window.addEventListener('resize', function () { if (!videoObject['cover']) return; t_videoprocessor__updateVideoHeight(el, height, 'youtube'); }); el.addEventListener( 'coverHeightUpdated', function () { t_videoprocessor__updateVideoHeight(el, height, 'youtube'); }, { once: true } ); }); } /** * update height of video-element * * @param {HTMLElement} el - .t-cover__carrier * @param {string} height * @param {'youtube' | 'html5'} type */ function t_videoprocessor__updateVideoHeight(el, height, type) { var currentHeight = height; if (type === 'youtube') { var customHeight = t_videoprocessor__getHeightFromAttr(height); var calculatedHeight = parseInt(el.getAttribute('data-content-cover-updated-height'), 10) || 0; currentHeight = calculatedHeight > customHeight ? el.getAttribute('data-content-cover-updated-height') : height; } setWidthAndHeightVideo(el, currentHeight, type); } function t_videoprocessor__setYoutubePlayer(el, videoObject) { // create YouTube iframe var iframe = document.createElement('iframe'); iframe.src = t_videoprocessor__generateYoutubeURL(videoObject); iframe.frameBorder = '0'; iframe.allow = 'fullscreen'; iframe.style.opacity = '0'; // prevent white background while processing video el.appendChild(iframe); var playtimer; const player = new YT.Player(iframe, { events: { onReady: function (e) { // update src and reinit iframe, if player cannot play video at first time if (e.target.getPlayerState() === -1 && iframe.getAttribute('programmly-updated') !== 'y') { iframe.src = t_videoprocessor__generateYoutubeURL(videoObject); iframe.setAttribute('programmly-updated', 'y'); } iframe.style.opacity = ''; t_videoprocessor__pauseAndPlayYouTubeVideo(el, e.target, videoObject['mute']); t_videoprocessor__muteYouTubeVideo(e, videoObject); e.target.setLoop(true); }, onStateChange: function (e) { t_videoprocessor__muteYouTubeVideo(e, videoObject); if (e.data === YT.PlayerState.PLAYING) { playtimer = t_videoprocessor__updateLoopedVideo(e.target, videoObject); } else { window.clearInterval(playtimer); } }, }, }); } /** * mute created video * * @param {Event} e * @param {Object} videoObject */ function t_videoprocessor__muteYouTubeVideo(e, videoObject) { if (e.target.setVolume && videoObject['mute']) { e.target.setVolume(0); } } /** * remove black window between stop and play again video * * @param {Object} el - player * @param {Object} videoObject * @return {number} - an interval, that checks ending of the video */ function t_videoprocessor__updateLoopedVideo(el, videoObject) { return setInterval(function () { // time in sec var currentTime = el.getCurrentTime(); var endVideoTime = el.getDuration(); if (endVideoTime && currentTime + 1 > endVideoTime) { el.seekTo(0); // return to the beginning (0sec) if (videoObject['noloop']) { el.stopVideo(); el.clearVideo(); } } }, 1000); } /** * function to generate mp4 or .webm video * * @param {HTMLElement} el * @param {Object} options */ function t_videoprocessor__processHTML5Video(el, options) { if (!el) return; var computedStyle = window.getComputedStyle(el); // container to be at least relative if (computedStyle.position === 'static' || !el.style.position) { el.style.position = 'relative'; } //set height options.height = el.offsetHeight; var initialHeight = parseInt(computedStyle.height.replace('px', ''), 10); var initialWidth = parseInt(computedStyle.width.replace('px', ''), 10); if ((window.t_cover__isMobile || 'ontouchend' in document) && initialWidth < initialHeight) { el.setAttribute('data-content-video-ratio', initialHeight / initialWidth); } var videoWrapper = t_videoprocessor__createHTML5Video(options); el.insertAdjacentElement('beforeend', videoWrapper); t_onReady(function () { t_videoprocessor__updateVideoHeight(videoWrapper, window.getComputedStyle(el).height, 'html5'); }); el.addEventListener( 'coverHeightUpdated', function () { t_videoprocessor__updateVideoHeight(videoWrapper, window.getComputedStyle(el).height, 'html5'); }, { once: true } ); window.addEventListener('resize', function () { t_videoprocessor__updateVideoHeight(videoWrapper, window.getComputedStyle(el).height, 'html5'); }); if ('IntersectionObserver' in window) { var htmlVideoObserver = new IntersectionObserver(function (entries) { entries.forEach(function (entry) { var target = entry.target; var video = target.querySelector('video'); if (video) { if (entry.isIntersecting) { if (video.readyState >= 2) video.play(); } else { video.pause(); } } }); }); htmlVideoObserver.observe(videoWrapper); } else { window.addEventListener( 'scroll', t_throttle(function () { t_videoprocessor__pauseAndPlayHTMLVideo(videoWrapper); }, 100) ); } return videoWrapper.querySelector('video'); } function t_videoprocessor__pauseAndPlayHTMLVideo(videoWrapper) { var video = videoWrapper.querySelector('video'); if (!video) return; var viewportTopPos = window.pageYOffset; var viewportBottomPos = viewportTopPos + document.documentElement.clientHeight; var videoWrapperTopPos = videoWrapper.getBoundingClientRect().top + viewportTopPos; var videoWrapperHeight = videoWrapper.offsetHeight; var videoWrapperBottomPos = videoWrapperTopPos + videoWrapperHeight; var padding = 500; var currentPosition; if (viewportBottomPos > videoWrapperTopPos && viewportTopPos <= videoWrapperBottomPos) { currentPosition = 'inside'; } else if ( (viewportBottomPos < videoWrapperTopPos && viewportBottomPos > videoWrapperTopPos - padding) || (viewportTopPos > videoWrapperBottomPos && viewportTopPos < videoWrapperBottomPos + padding) ) { currentPosition = 'near'; } else { currentPosition = 'near'; } switch (currentPosition) { case 'inside': if (video.readyState >= 2) video.play(); break; case 'near': video.pause(); break; } } /** * create video wrapper with video with current options * * @param {Object} options * @return {HTMLDivElement} */ function t_videoprocessor__createHTML5Video(options) { var videoWrapper = document.createElement('div'); videoWrapper.style.position = options.position; videoWrapper.style.zIndex = options.zIndex; videoWrapper.style.top = '0'; videoWrapper.style.left = '0'; videoWrapper.style.height = options.height + 'px'; videoWrapper.style.width = options.width + 'px'; videoWrapper.style.opacity = options.opacity; videoWrapper.style.overflow = 'hidden'; var video = document.createElement('video'); video.style.position = 'relative'; video.style.zIndex = options.zIndex; video.style.poster = options.poster; video.style.top = '0'; video.style.left = '0'; video.style.minHeight = '100%'; video.style.minWidth = '100%'; video.style.height = options.height + 'px'; video.style.width = options.width + 'px'; video.style.objectFit = 'cover'; video.autoplay = options.autoplay; video.loop = options.loop; video.muted = options.muted; video.volume = options.volume; video.setAttribute('playsinline', ''); video.addEventListener('canplay', function () { if (options.autoplay) { video.muted = true; video.play(); } }); var codec = options.mp4 ? 'video/mp4; codecs="avc1.42E01E, mp4a.40.2"' : 'video/webm; codecs="vp8, vorbis"'; var emptyVideo = document.createElement('video'); var isVideoSupported = emptyVideo.canPlayType(codec); if (isVideoSupported) { video.src = options.webm || options.mp4; videoWrapper.insertAdjacentElement('beforeend', video); } else if (!videoWrapper.querySelector('.no-video-loader')) { // image for those that don't support the video var img = document.createElement('img'); img.setAttribute('src', options.poster); img.style.position = 'absolute'; img.style.zIndex = options.zIndex; img.style.top = '0'; img.style.left = '0'; img.style.minHeight = '100%'; img.style.minWidth = '100%'; img.classList.add('no-video-loader'); videoWrapper.insertAdjacentElement('beforeend', img); } return videoWrapper; } /** * set width and height to current video. * Naming without prefix, because used in blocks. * * @param {HTMLElement} el - current el * @param {string} height - height with px or vh * @param {string} type - YouTube or HTML5 video */ function setWidthAndHeightVideo(el, height, type) { var iframe = el.querySelector('iframe'); var coverCarrier = el.closest('.t-cover__carrier'); if (type === 'html5') { var video = el; el = el.closest('.t-cover__carrier'); iframe = el.querySelector('video'); } var isHasCover = el.getAttribute('data-content-video-nocover') !== 'yes'; var isAdCutted = el.getAttribute('data-content-video-noadcut-youtube') !== 'yes'; var isAdCuttedInType = type === 'youtube' || type === 'rutube' || type === 'vk'; var customRatio = el.getAttribute('data-content-video-ratio'); var adCuttedPadding = isAdCutted && isAdCuttedInType ? 220 : 0; var videoRatio = 0.5625; if (customRatio && parseFloat(customRatio) > 0) videoRatio = parseFloat(customRatio); if (isHasCover) { var coverHeight = t_videoprocessor__getHeight(height, isHasCover, el, videoRatio); var videoWidth = coverCarrier?.clientWidth || window.innerWidth; var videoHeight = videoWidth * videoRatio; var deltaRatio = 1; // recalculate deltaRatio if video height less than div height if (videoHeight - adCuttedPadding < coverHeight) { deltaRatio = videoHeight < coverHeight ? coverHeight / videoHeight : videoHeight / coverHeight; deltaRatio += 0.02; } var zoomedWidth = Math.floor(videoWidth * deltaRatio); var zoomedHeight = Math.floor((videoHeight + adCuttedPadding) * deltaRatio); var heightDelta = zoomedHeight - coverHeight; var widthDelta = zoomedWidth - videoWidth; if (iframe) iframe.style.height = zoomedHeight + 'px'; if (iframe) iframe.style.width = zoomedWidth + 'px'; if (type === 'html5' && video) { video.style.height = coverHeight + 'px'; video.style.width = videoWidth + 'px'; } if (iframe) iframe.style.marginTop = heightDelta > 0 ? -Math.floor(heightDelta / 2) + 'px' : '0'; if (iframe) iframe.style.marginLeft = widthDelta > 0 ? -Math.floor(widthDelta / 2) + 'px' : '0'; } else { var noCoverHeight = t_videoprocessor__getHeight(height, isHasCover, el, videoRatio); if (type === 'html5' && video) { video.style.width = '100%'; video.style.height = noCoverHeight + 'px'; } if (iframe) iframe.style.width = '100%'; if (iframe) iframe.style.height = noCoverHeight + 'px'; } } /** * calculate and get height for video element * * @param {string} height * @param {Boolean} isHasCover * @param {HTMLElement} el * @param {number} videoRatio * @return {number} - height */ function t_videoprocessor__getHeight(height, isHasCover, el, videoRatio) { var calculatedHeight; if (!height) { if (isHasCover) { height = '100vh'; } else { calculatedHeight = Math.floor(el.offsetWidth * videoRatio); } } if (height.indexOf('vh') !== -1) { var parsedHeight = parseInt(height, 10) || 0; calculatedHeight = Math.floor(document.documentElement.clientHeight * (parsedHeight / 100)); } else if (height) { calculatedHeight = parseInt(height, 10) || 0; } return calculatedHeight || 0; } function t_videoprocessor__getHeightFromAttr(height) { if (!height) return 0; if (height.indexOf('vh') !== -1) { return (parseInt(height, 10) * document.documentElement.clientHeight) / 100; } else { return parseInt(height, 10); } } /** * @param {Object} videoObject - link to video * @returns {string} - transformed src */ function t_videoprocessor__generateYoutubeURL(videoObject) { var src = videoObject['url-youtube']; var protocolAndDomain = 'https://www.youtube.com/embed'; var hasCover = videoObject['cover']; var isMute = videoObject['mute']; // if contains only videoID if (src.indexOf(protocolAndDomain) === -1) { if (src.indexOf('/') === -1) src = '/' + src; // append to protocol and domain video ID, it will look like: https://www.youtube.com/embed/{URL} src = protocolAndDomain.concat(src); } // adding separator for parameters in URL src += src.indexOf('?') === -1 ? '?' : '&'; var currentLocation = location.protocol + '//' + location.host; var videoID = src.replace(protocolAndDomain + '/', ''); var firstSeparator = videoID.indexOf('?'); if (firstSeparator !== -1) videoID = videoID.slice(0, firstSeparator); if (hasCover) { src += 'autoplay=1'; src += '&loop=1'; src += '&enablejsapi=1'; src += '&playerapiid=featuredytplayer'; src += '&controls=0'; src += '&modestbranding=1'; src += '&rel=0'; src += '&showinfo=0'; src += '&color=white'; src += '&iv_load_policy=3'; src += '&theme=light'; src += '&wmode=transparent'; src += '&origin=' + currentLocation; src += '&playlist=' + videoID; } else { src += 'autoplay=0'; src += '&loop=0'; src += '&enablejsapi=1'; src += '&playerapiid=featuredytplayer'; src += '&controls=1'; src += '&modestbranding=1'; src += '&rel=0'; src += '&showinfo=0'; src += '&color=black'; src += '&iv_load_policy=3'; src += '&theme=dark'; src += '&wmode=transparent'; src += '&origin=' + currentLocation; } if (isMute) src += '&mute=1'; return src; } /** * which user scroll the page, background video can be pausing; * and smooth muting its volume (not for bg cover) * * @param {HTMLElement} el - current element, which include YouTube iframe * @param {Object} player * @param {Boolean} isMute */ function t_videoprocessor__pauseAndPlayYouTubeVideo(el, player, isMute) { if ('IntersectionObserver' in window) { var youtubeVideo = new IntersectionObserver(function (entries) { entries.forEach(function (entry) { var target = entry.target; var playerState = player.getPlayerState(); var isInvisible = el.getAttribute('data-video-invisible') === 'y'; // playerState: //-1 – воспроизведение видео не началось // 0 – воспроизведение видео завершено // 1 – воспроизведение // 2 – пауза // 3 – буферизация // 5 – видео находится в очереди if (entry.isIntersecting) { if ( playerState === -1 || playerState === 3 || playerState === 5 || (playerState === 2 && isInvisible) ) { player.playVideo(); target.removeAttribute('data-video-invisible'); } } else { t_videoprocessor__pauseVideo(player, playerState, target); } }); }); youtubeVideo.observe(el); } else { window.addEventListener( 'scroll', t_throttle(function () { var viewportTopPos = window.pageYOffset; var viewportHeight = document.documentElement.clientHeight; var viewportBottomPos = viewportTopPos + viewportHeight; var videoTopPos = el.getBoundingClientRect().top + viewportTopPos; var videoHeight = el.offsetHeight; var videoBottomPos = videoTopPos + videoHeight; var isInvisible = el.getAttribute('data-video-invisible') === 'y'; var playerState = player.getPlayerState(); var padding = 500; var currentPosition; if (viewportBottomPos > videoTopPos && viewportTopPos <= videoBottomPos) { currentPosition = 'inside'; } else if ( (viewportBottomPos < videoTopPos && viewportBottomPos > videoTopPos - padding) || (viewportTopPos > videoBottomPos && viewportTopPos < videoBottomPos + padding) ) { currentPosition = 'near'; } else { currentPosition = 'far'; } switch (currentPosition) { case 'inside': if ( playerState === -1 || playerState === 3 || playerState === 5 || (playerState === 2 && isInvisible) ) { player.playVideo(); el.removeAttribute('data-video-invisible'); } break; case 'near': t_videoprocessor__pauseVideo(player, playerState, el); break; case 'far': t_videoprocessor__pauseVideo(player, playerState, el); break; } }, 100) ); } if (isMute) return; // dynamical volume muting, depend on pageYOffset (only for VD01 block) window.addEventListener( 'scroll', t_throttle(function () { var viewportTopPos = window.pageYOffset; var videoTopPos = el.getBoundingClientRect().top + viewportTopPos; var videoHeight = el.clientHeight; var videoBottomPos = videoTopPos + videoHeight; var viewportBottomPos = viewportTopPos + document.documentElement.clientHeight; if (viewportTopPos > videoBottomPos || viewportBottomPos < videoTopPos) { return; } var volumeValue = 0; if (videoBottomPos > viewportBottomPos && viewportBottomPos > viewportTopPos) { volumeValue = Math.floor(100 * ((videoBottomPos - viewportBottomPos) / videoHeight)); } else if (viewportTopPos > videoTopPos && viewportTopPos < videoBottomPos) { volumeValue = Math.floor(100 * ((viewportTopPos - videoTopPos) / videoHeight)); } player.setVolume(100 - volumeValue); }, 100) ); } /** * @param {Object} player * @param {number} playerState * @param {HTMLElement} el */ function t_videoprocessor__pauseVideo(player, playerState, el) { el.setAttribute('data-video-invisible', 'y'); if (playerState !== 2) { player.pauseVideo(); } } /** * Processing video added with iframe * @param {HTMLElement} el - current el * @param {Object} params - cover params */ function t_videoprocessor__processIframeVideo(el, params) { if (el.hasAttribute('data-content-video-url-vimeo')) { t_videoprocessor__processVimeoVideo(el, params); } else if (el.hasAttribute('data-content-video-url-vkvideo')) { t_videoprocessor__processVkVideo(el, params); } else if (el.hasAttribute('data-content-video-url-kinescope')) { t_videoprocessor__processKinescopeVideo(el, params); } else if (el.hasAttribute('data-content-video-url-rutube')) { t_videoprocessor__processRutubeVideo(el, params); } } /** * Generates URL for iframe video * @param {('rutube'|'kinescope')} videoType - type of video * @param {string} id - id for video * @param {string} hash - hash for video * @param {boolean} noloop - if video should not be looped * @return {string} - url for iframe */ function t_videoprocessor__getIframeVideoUrl(videoType, id, hash, noloop) { var startUrlByType = { vimeo: 'https://player.vimeo.com/video/', rutube: 'https://rutube.ru/play/embed/', kinescope: 'https://kinescope.io/embed/', }; var startUrl = startUrlByType[videoType]; if (!startUrl) return; var idParts = id.split('?t='); var id = idParts[0]; var start = idParts[1] || 0; var url = startUrl + id; var params = 'autoplay=true&muted=true&controls=false' + (noloop ? '' : '&loop=true') + (start ? '&t=' + start : ''); if (videoType === 'vimeo') { url += '/?' + (hash ? 'h=' + hash + '&' : '') + params; } else if (videoType === 'rutube') { url += '/?p=' + hash + '&' + params; } else if (videoType === 'kinescope') { url += '/?' + params + '&autopause=false'; } return url; } /** * Generates HTML for iframe * @param {string} url - url of video * @param {string} height - height of cover * @return {HTMLElement} - iframe */ function t_videoprocessor__getIframeHtml(url, height) { var iframe = document.createElement('iframe'); iframe.src = url; iframe.frameBorder = '0'; iframe.setAttribute( 'allow', 'autoplay; fullscreen; picture-in-picture; encrypted-media; gyroscope; accelerometer; clipboard-write;' ); iframe.style.width = '100%'; iframe.style.height = height || '100%'; iframe.setAttribute('webkitAllowFullScreen', ''); iframe.setAttribute('mozallowfullscreen', ''); iframe.setAttribute('allowFullScreen', ''); iframe.innerHTML = "

Your browser don't support videos.

"; return iframe; } function t_videoprocessor__processVimeoVideo(el, params) { var id = el.getAttribute('data-content-video-url-vimeo'); if (!id) { el.style.backgroundImage = null; return; } var noloop = params['video-noloop']; var hash = el.getAttribute('data-content-video-hash-vimeo') || ''; var url = t_videoprocessor__getIframeVideoUrl('vimeo', id, hash, noloop); var iframe = t_videoprocessor__getIframeHtml(url, params['cover-height']); if (!url) { el.style.backgroundImage = null; return; } el.style.backgroundImage = null; el.insertAdjacentElement('beforeend', iframe); t_onReady(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'vimeo'); }); el.addEventListener( 'coverHeightUpdated', function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'vimeo'); }, { once: true } ); window.addEventListener( 'resize', t_throttle(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'vimeo'); }, 100) ); } /** * Process Rutube video * @param {HTMLElement} el - Element containing Rutube video * @param {Object} params - Options for video processing * @param {string} params ['cover-height'] - Video height * @param {boolean} params['video-noloop'] - Flag indicating whether to loop the video */ function t_videoprocessor__processRutubeVideo(el, params) { var id = el.getAttribute('data-content-video-url-rutube'); if (!id) { el.style.backgroundImage = null; return; } var noloop = params['video-noloop']; var hash = el.getAttribute('data-content-video-hash-rutube') || ''; var url = t_videoprocessor__getIframeVideoUrl('rutube', id, hash, noloop); if (!url) { el.style.backgroundImage = null; return; } var iframe = t_videoprocessor__getIframeHtml(url, params['cover-height']); var autoplayInitiated = false; window.addEventListener('message', function (event) { if (!event) return; var message = ''; try { // event.data is not always json message = typeof event.data === 'string' ? JSON.parse(event.data) : event.data; } catch (error) { console.error(error); } if (!message.data) return; // Событие message также возвращает player:ready для других инициализирующихся видео, // добавляем проверку, что это конкретное видео, а не из другого блока if (message.type === 'player:ready' && iframe.src.indexOf(message.data.videoId) !== -1) { t_videoprocessor__doRutubeCommand(iframe, 'stop'); t_videoprocessor__doRutubeCommand(iframe, 'mute'); } else if (message.type === 'player:changeState' && message.data.state === 'buffering' && !autoplayInitiated) { autoplayInitiated = true; t_videoprocessor__doRutubeCommand(iframe, 'play'); } else if ( !noloop && message.type === 'player:changeState' && ['stopped', 'completed'].includes(message.data.state) ) { t_videoprocessor__doRutubeCommand(iframe, 'play'); } }); el.style.backgroundImage = null; el.insertAdjacentElement('beforeend', iframe); t_onReady(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'rutube'); }); el.addEventListener( 'coverHeightUpdated', function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'rutube'); }, { once: true } ); window.addEventListener( 'resize', t_throttle(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'rutube'); }, 100) ); if ('IntersectionObserver' in window) { var iframeVideoObserver = new IntersectionObserver(function (entries) { entries.forEach(function (entry) { var target = entry.target; if (target === iframe) { var command = entry.isIntersecting ? 'play' : 'pause'; t_videoprocessor__doRutubeCommand(iframe, command); } }); }); iframeVideoObserver.observe(iframe); } } function t_videoprocessor__doRutubeCommand(iframe, command) { iframe.contentWindow.postMessage(JSON.stringify({ type: 'player:' + command, data: {} }), '*'); } /** * Process Kinescope video * @param {HTMLElement} el - Element containing Kinescope video * @param {Object} params - Options for video processing * @param {string} params ['cover-height'] - Video height * @param {boolean} params['video-noloop'] - Flag indicating whether to loop the video */ function t_videoprocessor__processKinescopeVideo(el, params) { var id = el.getAttribute('data-content-video-url-kinescope'); if (!id) { el.style.backgroundImage = null; return; } var noloop = params['video-noloop']; var url = t_videoprocessor__getIframeVideoUrl('kinescope', id, null, noloop); if (!url) { el.style.backgroundImage = null; return; } var videoWrapper = document.createElement('div'); videoWrapper.classList.add('t-cover__video__wrapper'); videoWrapper.style.height = params['cover-height']; var iframe = t_videoprocessor__getIframeHtml(url); videoWrapper.insertAdjacentElement('beforeend', iframe); el.insertAdjacentElement('beforeend', videoWrapper); t_onReady(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(videoWrapper, elHeight, 'kinescope'); }); el.addEventListener( 'coverHeightUpdated', function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(videoWrapper, elHeight, 'kinescope'); }, { once: true } ); window.addEventListener( 'resize', t_throttle(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(videoWrapper, elHeight, 'kinescope'); }, 100) ); el.style.backgroundImage = null; } /** * Process VK video * @param {HTMLElement} el - Element containing VK video * @param {Object} params - Options for video processing * @param {string} params ['cover-height'] - Video height * @param {boolean} params ['video-noloop'] - Flag indicating whether to loop the video */ function t_videoprocessor__processVkVideo(el, params) { var url = el.getAttribute('data-content-video-url-vkvideo'); var noloop = params['video-noloop']; if (!url) { el.style.backgroundImage = null; return; } url = url.replace(/https:\/\/(vk\.com|vk\.ru|vkvideo\.ru)\/video/, ''); var urlParts = url.split('_'); var hash = el.getAttribute('data-content-video-hash-vkvideo') || ''; var elHeight = 0; var embedUrl = 'https://vkvideo.ru/video_ext.php?oid=' + urlParts[0] + '&id=' + urlParts[1] + '&hd=2' + (hash ? '&hash=' + hash : '') + '&js_api=1' + (!noloop ? '&loop=1' : ''); var iframe = t_videoprocessor__getIframeHtml(embedUrl); el.insertAdjacentElement('beforeend', iframe); t_onFuncLoad('t_loadJsFile', () => { t_loadJsFile('https://vkvideo.ru/js/api/videoplayer.js', () => { t_onFuncLoad('VK', () => { const player = VK.VideoPlayer(iframe); player.on('inited', function () { player.mute(); player.play(); elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'vk'); }); if ('IntersectionObserver' in window) { var iframeVideoObserver = new IntersectionObserver(function (entries) { entries.forEach(function (entry) { if (!player) return; var target = entry.target; if (target === iframe) { var doCommand = entry.isIntersecting ? player.play : player.pause; doCommand(); } }); }); iframeVideoObserver.observe(iframe); } }); }); }); t_onReady(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'vk'); }); el.addEventListener( 'coverHeightUpdated', function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'vk'); }, { once: true } ); window.addEventListener( 'resize', t_throttle(function () { var elHeight = window.getComputedStyle(el).height || 0; t_videoprocessor__updateVideoHeight(el, elHeight, 'vk'); }, 100) ); el.style.backgroundImage = null; } /** * some analog of promise * we cannot use here t_onFuncLoad, because after getting YT object, we need check is YT.Player is ready to use * * @param {String} obj - if obj is object * @param {Function} okFunc - do okFunc */ function t_videoprocessor__onFuncLoad(obj, okFunc) { var timer; if (typeof window[obj] === 'object' && typeof window[obj].Player === 'function') { okFunc(); } else { timer = setInterval(function () { if (typeof window[obj] === 'object' && typeof window[obj].Player === 'function') { okFunc(); clearInterval(timer); timer = 0; } }, 100); } window.addEventListener('load', function () { setTimeout(function () { if (timer) { if (typeof window[obj] === 'object' && typeof window[obj].Player === 'function') { okFunc(); clearInterval(timer); } else { clearInterval(timer); throw new Error(obj + ' is undefined'); } } }, 5000); }); } if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.msMatchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.webkitMatchesSelector || Element.prototype.oMatchesSelector; } // Polyfill: Element.closest if (!Element.prototype.closest) { Element.prototype.closest = function (s) { var el = this; while (el && el.nodeType === 1) { if (Element.prototype.matches.call(el, s)) { return el; } el = el.parentElement || el.parentNode; } return null; }; }