/**
* tilda-video работает с блоками, где видео добавляется на страницу (AB701, VD...).
* Этот скрипт работает только с добавлением видео из YouTube или Vimeo.
* Он формирует HTML с параметрами, указанными пользователем и добавляет этот HTML на страницу.
* t-video-no-lazyload Данный класс исключает из поиска элемент, если загрузка видео происходит по событию,
* например клик по кнопке или открытие попапа
**/
import * as videoPlayer from './tilda-video-player.module';
//#region Global Functions
window.t_video__createPlayer = t_video__createPlayer;
window.t_video_lazyload__removeVideo = t_video_lazyload__removeVideo;
//#endregion Global Functions
/**
* @typedef {'mp4' | 'webm' | 'youtube' | 'rutube' | 'vimeo' | 'vkvideo' | 'kinescope' | 'boomstream' | 'iframe'} VideoType
*/
t_onReady(function () {
t_onFuncLoad('t_video_lazyload_init', function () {
var videoContainers = document.querySelectorAll('.t-video-lazyload:not(.t-video-no-lazyload)');
if (!videoContainers.length) return;
t_video_lazyload_init();
});
});
function t_video_lazyload_init() {
if ('IntersectionObserver' in window) {
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
var scrollDiffHeight = 300;
if (isMobile) scrollDiffHeight = 150;
var tVideoLazyList = document.querySelectorAll('.t-video-lazyload:not(.t-video-no-lazyload)');
var tVideoObserver = new IntersectionObserver(
function (entries, observer) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
var target = entry.target;
observer.unobserve(target);
t_video_lazyload__addVideo(target);
}
});
},
{
rootMargin: scrollDiffHeight + 'px 0px',
}
);
Array.prototype.forEach.call(tVideoLazyList, function (tVideoLazy) {
tVideoObserver.observe(tVideoLazy);
});
} else {
t_video_lazyload__addVideoWithCheckViewport();
window.addEventListener(
'scroll',
t_throttle(function () {
t_video_lazyload__addVideoWithCheckViewport();
}, 300)
);
}
}
/**
* Add video if it in viewport. Legacy method for browsers without IntersectionObserver.
*/
function t_video_lazyload__addVideoWithCheckViewport() {
var windowHeight = document.documentElement.clientHeight;
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
var scrollDiffHeight = 700;
if (isMobile) scrollDiffHeight = 350;
var tVideoLazyList;
// check IE8-
if (document.documentMode < 9) {
tVideoLazyList = Array.prototype.slice
.call(document.querySelectorAll('.t-video-lazyload:not(.t-video-no-lazyload)'))
.filter(function (el) {
var recBlock = el.closest('.r');
return (
!recBlock.classList.contains('t395__off') &&
!recBlock.classList.contains('t397__off') &&
!recBlock.classList.contains('t400__off')
);
});
} else {
tVideoLazyList = document.querySelectorAll(
'.r:not(.t395__off):not(.t397__off):not(.t400__off) .t-video-lazyload:not(.t-video-no-lazyload)'
);
}
Array.prototype.forEach.call(tVideoLazyList, function (video) {
// position of video
var blockRect = video.getBoundingClientRect();
var blockTop = blockRect.top;
var blockBottom = blockRect.bottom;
if (
(blockTop > 0 && blockTop < windowHeight + scrollDiffHeight) ||
(blockBottom > 0 && blockBottom < windowHeight + scrollDiffHeight)
) {
t_video_lazyload__addVideo(video);
}
});
}
function t_video_lazyload__addVideo(video) {
var isMobileResolution = window.matchMedia('(max-width: 640px)').matches;
var isVideoLoaded = video.getAttribute('data-videolazy-load');
var dataVideoType = video.getAttribute('data-videolazy-type');
// yotube/vimeo id
var dataVideoId = video.getAttribute('data-videolazy-id');
var videoId = dataVideoId ? dataVideoId.trim() : '';
if (dataVideoType === 'youtube' && typeof videoId === 'string') {
videoId = videoId.replace(/^v=/, '');
videoId = videoId.replace(/[&?]+$/, '');
}
// vimeo hash
var dataVideoHash = video.getAttribute('data-videolazy-hash');
var videoHash = dataVideoHash ? dataVideoHash.trim() : '';
// id for video
var dataBlockId = video.getAttribute('data-blocklazy-id');
var blockId = dataBlockId || '';
var yotubeVideoUniqId = 'youtubeiframe';
var kinescopeVideoUniqueId = 'kinescopeiframe';
var dataTwoBlockId = video.getAttribute('data-videolazy-two-id');
if (dataTwoBlockId) {
yotubeVideoUniqId += '_' + dataTwoBlockId + '_';
}
var noControls = video.getAttribute('data-videolazy-nocontrols');
// video play
var dataVideoPlay = video.getAttribute('data-videolazy-play');
// video mute
var dataVideoMute = video.getAttribute('data-videolazy-mute');
// js api enabled
var dataVideoJsApiEnabled = video.getAttribute('data-videolazy-api');
// video image
var dataVideoImage = video.getAttribute('data-videolazy-image');
// в мобильной версии видео будет воспроизводится не в фулскрин по умолчанию. актуально для mp4/webm
var dataVideoPlayInline = video.getAttribute('data-videolazy-inline');
// settings
var hashQueryStr = '';
var videoHeight = '100%';
var dataHeight = video.getAttribute('data-videolazy-height');
var dataMobHeight = video.getAttribute('data-videolazy-mob-height');
if (!isMobileResolution && dataHeight && dataHeight.indexOf('vh') === -1) {
videoHeight = dataHeight;
}
if (isMobileResolution && dataMobHeight && dataMobHeight.indexOf('vh') === -1) {
videoHeight = dataMobHeight;
}
if (isVideoLoaded === 'false' && !video.classList.contains('t-video__isload')) {
video.setAttribute('data-videolazy-load', 'true');
if (dataVideoType === 'youtube') {
var src = '';
// Добавлени интеграция видео с домена vd.tilda.cc для отдела маркетинга(не для пользователей)
if (videoId.indexOf('vd.tilda.cc') !== -1) {
src = videoId;
} else {
videoId += videoId.indexOf('?') !== -1 ? '&' : '?';
videoId = videoId.replace('https://www.youtube.com/shorts/', '');
hashQueryStr += 'rel=0&fmt=18&html5=1&showinfo=0';
hashQueryStr += dataVideoPlay ? '&autoplay=1' : '';
hashQueryStr += dataVideoMute ? '&mute=1' : '';
hashQueryStr += noControls === 'yes' ? '&controls=0' : '';
hashQueryStr += dataVideoJsApiEnabled ? '&enablejsapi=1' : '';
src = 'https://www.youtube.com/embed/' + videoId + hashQueryStr;
}
var iframeId = yotubeVideoUniqId + blockId;
video.insertAdjacentHTML(
'afterbegin',
''
);
} else if (dataVideoType === 'vimeo') {
const regExp =
/(?:https?:\/\/)?(?:www\.)?(?:vimeo\.com\/|player\.vimeo\.com\/video\/|api\.vimeo\.com\/videos\/)?(\d+)/;
const match = videoId.match(regExp);
videoId = match && match[1] ? match[1] : videoId;
hashQueryStr = videoHash ? '&h=' + videoHash : '';
hashQueryStr += dataVideoPlay ? '&autoplay=1' : '';
hashQueryStr += dataVideoMute ? '&muted=1' : '';
hashQueryStr += dataVideoJsApiEnabled ? '&api=1' : '';
video.insertAdjacentHTML(
'afterbegin',
''
);
} else if (dataVideoType === 'kinescope') {
hashQueryStr += dataVideoPlay ? '&autoplay=1' : '';
hashQueryStr += dataVideoMute ? '&muted=1' : '';
if (videoId.indexOf('?') === -1) hashQueryStr = hashQueryStr.replace('&', '?');
var iframeId = kinescopeVideoUniqueId + blockId;
video.insertAdjacentHTML(
'afterbegin',
''
);
} else if (dataVideoType === 'rutube') {
hashQueryStr += videoHash ? '&p=' + videoHash : '';
hashQueryStr += dataVideoPlay ? '&autoplay=1' : '';
hashQueryStr += dataVideoMute ? '&muted=1' : '';
hashQueryStr = hashQueryStr.replace('&', '?');
video.insertAdjacentHTML(
'afterbegin',
''
);
} else if (dataVideoType === 'vkvideo') {
var regExp =
/(?:video|video_ext\.php\?oid=|clip=?|)(-?\d+)_(\d+)|oid=(-?\d+)&id=(\d+)(?:.*?hash=([a-f0-9]+))?/;
var match = videoId.match(regExp);
var oid = '';
var id = '';
if (match) {
oid = match[1] || match[3];
id = match[2] || match[4];
if (!videoHash && match[5]) videoHash = match[5];
}
hashQueryStr += dataVideoPlay ? '&autoplay=1' : '';
hashQueryStr += dataVideoMute ? '&muted=1' : '';
hashQueryStr += videoHash ? '&hash=' + videoHash : '';
hashQueryStr += dataVideoJsApiEnabled ? '&js_api=1' : '';
video.insertAdjacentHTML(
'afterbegin',
''
);
} else if (dataVideoType === 'boomstream') {
hashQueryStr += dataVideoPlay ? '&autostart=1' : '';
hashQueryStr += dataVideoMute ? '&volume=0' : '';
hashQueryStr = hashQueryStr.replace('&', '?');
if (videoId.includes('.mp4')) {
const html = `
`;
video.insertAdjacentHTML('afterbegin', html);
} else {
video.insertAdjacentHTML(
'afterbegin',
''
);
}
} else if (dataVideoType === 'mp4') {
const html = `
`;
video.insertAdjacentHTML('afterbegin', html);
} else if (dataVideoType === 'webm') {
const html = `
`;
video.insertAdjacentHTML('afterbegin', html);
} else if (dataVideoType === 'iframe') {
video.insertAdjacentHTML(
'afterbegin',
''
);
}
}
/**
* Если значение 540px - то видео имеет стандартную высоту не заданную пользователем, рассчитываем пропорции
* Если значение отличимое, то фиксируем высоту видео
* Добавлена проверка для блока VD03, в котором добавляется высота, но используется не height, а через padding-bottom
*/
if (!video.closest('.t116, .t1148') && dataHeight === '540px') t_video_lazyload__setHeight(video);
if (dataHeight && dataMobHeight) {
window.addEventListener('resize', function () {
t_video_lazyload__setMobileHeight(video);
});
window.addEventListener('orientationchange', function () {
t_video_lazyload__setMobileHeight(video);
});
}
/**
* Autoplay для сервиса Rutube, необходимо отслеживать статус готовности плейера
* По готовности удаляем обработчик статуса и запускаем видео
*/
if (dataVideoPlay && dataVideoType === 'rutube') {
const iframe = video.querySelector('iframe');
if (!iframe) return;
/**
* Проверяет состояние готовности видео для запуска
*/
function t_video__handleRutubePlayerReady(event) {
if (event && event.data && typeof event.data === 'string') {
const message = JSON.parse(event.data);
if (message.type === 'player:ready' && message.data && message.data.videoId === videoId) {
window.removeEventListener('message', t_video__handleRutubePlayerReady);
videoPlayer.t_video__doRutubeCommand(iframe, 'play');
}
}
}
videoPlayer.t_video__doRutubeCommand(iframe, 'changeState');
window.addEventListener('message', t_video__handleRutubePlayerReady);
}
}
/**
* Для блоков popup при закрытии удаляем видео
*/
function t_video_lazyload__removeVideo(video) {
video.innerHTML = '';
video.setAttribute('data-videolazy-load', 'false');
}
function t_video_lazyload__setHeight(video) {
if (!video) return;
var videoType = video.getAttribute('data-videolazy-type');
var videoLazy = video.querySelector('iframe');
if (videoType === 'mp4' || videoType === 'webm') {
videoLazy = video.querySelector('video');
}
// 0.5625 - коэфф для пропорций видео 16:9
// откругляем до целого числа
// так, как элементы div.t-video-lazyload и iframe могут по-разному отрисовываться при дробных значениях высоты
// из-за этого могут возникать тонкие темные полосы вокруг видео
var videoHeight = Math.round(video.offsetWidth * 0.5625);
video.style.height = videoHeight + 'px';
if (videoLazy) videoLazy.style.height = videoHeight + 'px';
}
function t_video_lazyload__setMobileHeight(wrapper) {
var isMobileResolution = window.matchMedia('(max-width: 640px)').matches;
var dataHeight = wrapper.getAttribute('data-videolazy-height');
var dataMobHeight = wrapper.getAttribute('data-videolazy-mob-height');
if (!wrapper) return;
var video = wrapper.querySelector('iframe') || video.querySelector('video');
if (!video) return;
var height = isMobileResolution ? dataMobHeight : dataHeight;
video.setAttribute('height', height);
}
/**
* @typedef {import('./tilda-video-player.module').TildaVideoPlayer} TildaVideoPlayer
*/
/**
* @typedef {Object} TildaVideoPlayerCreateParams
* @property {VideoType} videoType
* @property {string} videoId
* @property {string} videoHash
* @property {string} videoBlockId
* @property {boolean} autoplay
* @property {boolean} mute
* @property {boolean} controls
* @property {boolean} playsinline
* @property {boolean} [jsApi=true] - включает возможность управлять видео через jsapi. Eсли не указан, то для некоторых ресурсов управление через плеер не будет работать
*/
/**
* Создает элемент видео нужного типа и плеер для управления этим видео.
* Если плеер уже создан, то возвращает его.
*
* @param {Element} videoWrapper - обертка, в которой находится видео .t-video-lazyload;
* @param {Partial} videoParams - параметры видео, которые перезаписывают те, что уже добавлены для t-video-lazyload.
* @returns {Promise}
*/
function t_video__createPlayer(videoWrapper, videoParams) {
const player = videoPlayer.t_video__getPlayer(videoWrapper);
if (player) {
return Promise.resolve(player);
}
const lazyloadVideo = videoWrapper.querySelector('.t-video-lazyload');
// перезаписываем параметры, если они указаны
t_video_lazyload__overwriteParams(lazyloadVideo, videoParams);
/** @type {VideoType}*/
const videoType = lazyloadVideo.getAttribute('data-videolazy-type');
// Создаем видео
t_video_lazyload__addVideo(lazyloadVideo);
return videoPlayer.t_videoPlayer__init(videoWrapper, videoType);
}
/**
* Перезаписывает параметры необходимые для инициализации видео
*
* @param {Element} lazyloadVideo
* @param {Partial} params
*/
function t_video_lazyload__overwriteParams(lazyloadVideo, params) {
const {
videoId,
videoHash,
videoType,
videoBlockId,
controls,
playsinline,
autoplay = false,
mute = false,
jsApi = true,
} = params || {};
if (videoType) {
lazyloadVideo.setAttribute('data-videolazy-type', videoType);
}
if (videoId) {
lazyloadVideo.setAttribute('data-videolazy-id', videoId);
}
if (videoHash) {
lazyloadVideo.setAttribute('data-videolazy-hash', videoHash);
}
if (videoBlockId) {
lazyloadVideo.setAttribute('data-blocklazy-id', videoBlockId);
}
if (autoplay) {
lazyloadVideo.setAttribute('data-videolazy-play', 'true');
}
if (mute) {
lazyloadVideo.setAttribute('data-videolazy-mute', 'true');
}
if (controls === true) {
lazyloadVideo.setAttribute('data-videolazy-nocontrols', 'false');
}
if (controls === false) {
lazyloadVideo.setAttribute('data-videolazy-nocontrols', 'yes');
}
if (jsApi) {
lazyloadVideo.setAttribute('data-videolazy-api', 'true');
}
if (playsinline) {
lazyloadVideo.setAttribute('data-videolazy-inline', 'true');
}
return lazyloadVideo;
}