/** * @file * Только для Zero Block. Данный скрипт описывает такие типы анимаций, как * Parallax — это настройки эффекта параллакса элемента; * Fixing — это настройки эффекта фиксации. * Анимация параллакса имеет две настройки — параллакс может быть по скроллу и по движению мыши. * Для анимации фиксации можно задать старт анимации относительно * экрана пользователя Window Top / Middle / Bottom. * @module tilda-zero-animation-ext-1.0.js */ import { t396__isElementUsingCalcZoom, t396__initScaleFactorFlags } from './tilda-zero-shared.module'; /** * @typedef {Object} FixedElementProperties * @property {number} topOffset * @property {number} basicAnimationtriggerOffset * @property {number} trigger * @property {number} distance * @property {number} end * @property {HTMLElement} fixedWrapperEl */ /** * @typedef { HTMLElement | FixedElementProperties } FixedElement */ /** * @typedef {Object} ScrollParallaxElementProperties * @property {Boolean} isAboveParallax * @property {number} speed * @property {number} topPos * @property {number} bottomPos * @property {Boolean} isStarted */ /** * @typedef { HTMLElement | ScrollParallaxElementProperties } ScrollParallaxElement */ /** * @typedef {Object} ParallaxMouseElementProperties * @property {number} topOffset * @property {number} bottomOffset * @property {number} pathX * @property {number} pathY * @property {NodeList} animEl * @property {number} parentTopOffset * @property {number} parentBottomOffset */ /** * @typedef { HTMLElement | ParallaxMouseElementProperties } ParallaxMouseElement */ /** * @typedef {Object} ObjecForCreatingParallax * @property {HTMLElement} el * @property {number} elHeight * @property {number} elTopPos * @property {number} elBottomPos * @property {number} posY * @property {number} speed * @property {Boolean} isAboveParallax */ window.t_animationExt__isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || 'ontouchend' in document; t_onReady(t_animationExt__init); /** * Инициализация анимации. Если активирован режим редактирования, * выходим из функции. * * @returns {void} */ function t_animationExt__init() { var record = document.querySelector('.t-records'); var isEditMode = record ? record.getAttribute('data-tilda-mode') === 'edit' : false; if (/Bot/i.test(navigator.userAgent) || t_animateParallax__checkOldIE() || isEditMode) return; t_animationExt__isZeroBlocksRender(function () { t396__initScaleFactorFlags(); t_animationExt__wrapFixEls(); t_animationExt__wrapParallaxEls(); t_animateParallax__initScroll(); //добавляем к элементам параллакса по прокрутке ключи topOffset и bottomOffset t_animateParallax__initMouse(); //добавляем к элементам параллакса по движению мыши ключи pathX, pathY и animEl var fixedElements = t_animationExt__getAnimatedElements('fix', []); var mouseElements = t_animationExt__getAnimatedElements('prx', ['mouse']); /** * добавляем к элементам параллакса по движению мыши параметры: topOffset, bottomOffset, parentTopOffset, parentBottomOffset * и к элементам с фиксацией: topOffset, basicAnimationtriggerOffset, trigger, distance, end, fixedWrapperEl */ t_animationExt__createResizeObserver(fixedElements, mouseElements); t_animateFix__init(fixedElements); }); } /** * Инициализация анимации после отрисовки зеро-блока. * Не учитываем скрытые табами зеро-блоки. * Если у всех зеро-блоков есть класс 'rendered' - запускаем функцию обратного вызова. * Если нет - ждать события 'artBoardRendered'. * * @param {Function} callback - функция обратного вызова */ function t_animationExt__isZeroBlocksRender(callback) { var artBoards = t_animationExt__getArtboards('396', true); if (!artBoards.length) artBoards = t_animationExt__getArtboards('121', true); if (!artBoards.length) return; if ( artBoards.every(function (artboard) { return artboard.classList.contains('rendered'); }) ) { callback(); } else { // Проверяем сайты старых версий // prettier-ignore if (document.querySelector('script[src*="tilda-blocks-2.7"]')) { var time = Date.now(); t_animationExt__backwardCompatibilityWait(artBoards, time, callback); } else { var renderedList = artBoards.filter(function (artboard) { return artboard.classList.contains('rendered'); }); artBoards.forEach(function (artboard) { if (artboard.classList.contains('rendered')) return; artboard.addEventListener('artBoardRendered', function () { renderedList.push(artboard); if (renderedList.length === artBoards.length) callback(); }); }); } } } /** * * @param {'396' | '121'} recType * @param {Boolean} hasException * @returns {HTMLElement[]} - artboards */ function t_animationExt__getArtboards(recType, hasException) { const exceptionClause = hasException ? ':not(.t397__off, .t395__off, .t400__off)' : ''; const selector = `.r[data-record-type="${recType}"]${exceptionClause} .t396__artboard, .r[data-parenttplid="${recType}"]${exceptionClause} .t396__artboard`; return Array.from(document.querySelectorAll(selector)); } /** * Проверяем, отрисованы ли все артборды * * @param {HTMLElement[]} artBoards - артборды * @param {number} time * @param {Function} callback */ function t_animationExt__backwardCompatibilityWait(artBoards, time, callback) { if ( artBoards.every(function (artboard) { return artboard.classList.contains('rendered'); }) ) { callback(); } else { if (Date.now() - time > 10000) { console.warn("all zero-blocks can't be rendered"); return; } setTimeout(function () { t_animationExt__backwardCompatibilityWait(artBoards, time, callback); }, 500); } } /** * Создаем наблюдателя за изменениями размеров для элементов с параллаксом по движению мыши * и элементов с фиксацией. * Не обновляем значения, если произошло открытие попапа или высота экрана не была обновлена. * * @param {HTMLElement[]} fixedElements * @param {HTMLElement[]} mouseElements */ function t_animationExt__createResizeObserver(fixedElements, mouseElements) { if (!mouseElements.length && !fixedElements.length) return; var getClientRects = document.body.getClientRects(); if (!getClientRects.length || !('ResizeObserver' in window)) return; var initHeight = getClientRects[0].height; var animateParallaxResizeObserver = new ResizeObserver(function (entries) { entries.forEach(function (entry) { const { target } = entry; if ( target.classList.contains('t-body_popupshowed') || target.classList.contains('t-body_scroll-locked') || entry.contentRect.height === initHeight ) { return; } initHeight = getClientRects[0].height; mouseElements.forEach(function (mouseEl) { t_animateParallax__cacheOffsets(mouseEl); }); t_animateFix__cacheElsInfo(fixedElements); }); }); animateParallaxResizeObserver.observe(document.body); } /** * Эта функция оборачивает элементы с фиксацией, чтобы предотвратить смешивание стилей элемента и анимации, * удаляет атрибуты параллакса, если такие есть, чтобы предотвратить двойное оборачивание в t_animateParallax__wrapEls, * обновляет и устанавливает новые атрибуты анимации * * @return {void} */ function t_animationExt__wrapFixEls() { var animatedElements = t_animationExt__getAnimatedElements('fix', []); var artBoardsScreens = t_animationExt__getArtBoardsScreens(); animatedElements.forEach(function (animatedEl) { var isElHasParallaxAnimation = t_animationExt__getAttrByRes(animatedEl, 'prx', 'data-animate-', 0); if (isElHasParallaxAnimation) { artBoardsScreens.forEach(function (artBoardId) { var artBoard = document.querySelector('[data-artboard-recid="' + artBoardId.recid + '"]'); if (!artBoard) return; var screens = artBoardId.screens; var screenMax = artBoardId.screenMax; screens.forEach(function (screen) { var attributeName = screen === screenMax ? 'data-animate-prx' : 'data-animate-prx-res-' + screen; animatedEl.removeAttribute(attributeName); }); }); } var animCore = animatedEl.querySelector('.tn-molecule, .tn-atom'); var scaleWrapper = t_animationExt__getScaleWrapper(animCore); var sbsWrapper = animCore.closest('.tn-atom__sbs-anim-wrapper'); if (sbsWrapper && sbsWrapper.closest('.tn-elem, .tn-group') !== animatedEl) { sbsWrapper = null; } var wrapperClassList = t_animationExt__generateWrapperClassList(animCore, 'sticky'); var wrapperSelector = t_animationExt__generateWrapperSelector(animCore, 'sticky'); t_animationExt__wrapEl(animCore, wrapperClassList, wrapperSelector, scaleWrapper || sbsWrapper); var currentFixedWrapper = animCore.closest(wrapperSelector); t_animationExt__updateBasicAnimationTriggerOnFixed(currentFixedWrapper, animatedEl, artBoardsScreens); }); } /** * Получаем обертку автоскейла элемента. * Исключаем из поиска элементы-атомы, * находящиеся внутри группы, так как обернута молекула. * * @param {HTMLElement} animCore * @return {HTMLElement|null} */ function t_animationExt__getScaleWrapper(animCore) { if (!animCore) return null; var isInsideGroup = animCore.closest('.t396__group'); var isAtom = animCore.classList.contains('tn-atom'); if (isInsideGroup && isAtom) return null; return animCore.closest('.tn-atom__scale-wrapper'); } /** * В случаях, когда используется базовая анимация с анимацией фиксации, необходимо перенести * триггер и атрибуты на обёртку, из-за того, что фиксация элемента не будет работать, * если на родителе задан transform. * * @param currentFixedWrapper * @param animatedEl * @param artBoardsScreens */ function t_animationExt__updateBasicAnimationTriggerOnFixed(currentFixedWrapper, animatedEl, artBoardsScreens) { var basicAnimationClassName = 't-animate'; if (!animatedEl.classList.contains(basicAnimationClassName) || !currentFixedWrapper) return; animatedEl.classList.remove(basicAnimationClassName); currentFixedWrapper.classList.add(basicAnimationClassName); // добавляем класс, который скрывает элемент на момент его обработки animatedEl.classList.add('t-animate-for-wrapper'); var atributes = ['style', 'distance', 'duration', 'scale', 'delay']; artBoardsScreens.forEach(function (artBoardId) { var artBoard = document.querySelector('[data-artboard-recid="' + artBoardId.recid + '"]'); if (!artBoard) return; var screens = artBoardId.screens; var screenMax = artBoardId.screenMax; screens.forEach(function (screen) { atributes.forEach(function (attr) { var attributeValue = t_animationExt__getAttrByRes(animatedEl, attr, 'data-animate-', screen); if (!attributeValue) return; if (screen === screenMax) { currentFixedWrapper.setAttribute('data-animate-' + attr, attributeValue); animatedEl.removeAttribute('data-animate-' + attr); } else { currentFixedWrapper.setAttribute('data-animate-' + attr + '-res-' + screen, attributeValue); animatedEl.removeAttribute('data-animate-' + attr + '-res-' + screen); } }); }); }); } /** * Оборачиваем элементы с параллакс-анимацией * * @return {void} */ function t_animationExt__wrapParallaxEls() { var animatedElements = t_animationExt__getAnimatedElements('prx', ['scroll', 'mouse']); animatedElements.forEach(function (animatedEl) { var animCore = animatedEl.querySelector('.tn-molecule, .tn-atom'); var scaleWrapper = animCore.closest('.tn-atom__scale-wrapper, .tn-atom__sbs-anim-wrapper'); var wrapperClassList = t_animationExt__generateWrapperClassList(animCore, 'prx'); var wrapperSelector = t_animationExt__generateWrapperSelector(animCore, 'prx'); t_animationExt__wrapEl(animCore, wrapperClassList, wrapperSelector, scaleWrapper); }); } /*============= FIXED ANIMATED ELEMENTS ==============*/ /** * Анимируем элементы с фиксацией * * @param {FixedElement[]} fixedElements - элементы с фиксацией * @returns {void} */ function t_animateFix__init(fixedElements) { if (!fixedElements.length) return; t_animateFix__cacheElsInfo(fixedElements); t_animateFix__updatePositions(fixedElements, false); var allRecords = document.getElementById('allrecords'); var isLazyActive = allRecords ? allRecords.getAttribute('data-tilda-lazy') === 'yes' : false; if (window.lazy === 'y' || isLazyActive) { window.t_animationExt__isLazy = true; t_onFuncLoad('t_lazyload_update', function () { t_lazyload_update(); }); } window.addEventListener( 'resize', t_throttle(function () { t_animateFix__cacheElsInfo(fixedElements); t_animateFix__updatePositions(fixedElements, true); }, 100) ); window.addEventListener( 'scroll', t_throttle(function () { t_animateFix__updatePositions(fixedElements, false); }, 30) ); // отслеживаем события изменения высоты окна, которые могут быть вызваны табами или кнопкой "show more" var zeroBlocks = Array.from(document.querySelectorAll('.t396')); const eventList = ['displayChanged', 'zero:height-changed']; const onChangeFunction = t_throttle(function () { t_animateFix__cacheElsInfo(fixedElements); t_animateFix__updatePositions(fixedElements, true); }, 30); zeroBlocks.forEach(zeroBlock => { eventList.forEach(eventName => { zeroBlock.addEventListener(eventName, onChangeFunction); }); }); } /** * * @param {FixedElement[]} fixedEls - элементы с фиксацией * @param {boolean} isPageResized - булевое значения ресайза страницы * @returns {void} */ function t_animateFix__updatePositions(fixedEls, isPageResized) { var scrollTop = window.pageYOffset; fixedEls.forEach(function (fixedEl) { // Когда физ. находится в другой группе то у неё нет обертки // В таком случае мы не обрабатываем перемещение этой группы, т.к она будет перемещена вместе с родительской if (!fixedEl.fixedWrapperEl) return; var isScaledOnePxShape = t_animate__getScaledOnePixShape(fixedEl); if (fixedEl.distance === 0) { // фикс, когда пользователь изменяет размер экрана, а анимация уже запущена (и элемент по прежнему с фиксацией) if (isPageResized) { fixedEl.fixedWrapperEl.style.position = ''; fixedEl.fixedWrapperEl.style.top = ''; fixedEl.fixedWrapperEl.classList.remove('t-sticky_going'); fixedEl.fixedWrapperEl.classList.remove('t-sticky_ended'); } return; } var zoomValue = t_animationExt__getZoom(fixedEl); var triggerPosition = scrollTop + fixedEl.basicAnimationtriggerOffset * zoomValue; /** * определяем разницу между смещениями родительского элемента и scale-элемента для Firefox/Opera, использующих автоскейл * сохраняем эту разницу в атрибуте элемента, чтобы использовать ее позже для исправления положения элемента при автоскейле **/ var scaledWrapper = fixedEl.querySelector('.tn-atom__scale-wrapper'); if ( window.isOnlyScalable && scaledWrapper && fixedEl.fixedWrapperEl && fixedEl.fixedWrapperEl.style.position !== 'fixed' ) { var elTopPos = fixedEl.getBoundingClientRect().top; var scaleTopPos = scaledWrapper.getBoundingClientRect().top; var difference = elTopPos - scaleTopPos; fixedEl.setAttribute('data-scaled-diff', difference.toString()); } // обновить позицию триггера для Firefox/Opera, которые используют автоскейл var diff = 0; if (window.isOnlyScalable && scaledWrapper) { diff = fixedEl.getAttribute('data-scaled-diff') || '0'; diff = parseInt(diff, 10); triggerPosition = scrollTop + fixedEl.basicAnimationtriggerOffset + diff; } var isAfterStart = triggerPosition >= fixedEl.topOffset; var isBeforeStart = triggerPosition < fixedEl.topOffset; var isBeforeEnd = triggerPosition < fixedEl.end; var isAfterEnd = triggerPosition >= fixedEl.end; var isAnimationActivated = fixedEl.fixedWrapperEl.classList.contains('t-sticky_going'); var isAnimationEnded = fixedEl.fixedWrapperEl.classList.contains('t-sticky_ended'); var isGroup = fixedEl.classList.contains('tn-group'); var isHugHeight = isGroup && t_animationExt__getAttrByRes(fixedEl, 'heightmode', 'data-group-') === 'hug'; var isFillWidth = isGroup && t_animationExt__getAttrByRes(fixedEl, 'widthmode', 'data-group-') === 'fill'; var groupWidth = isFillWidth && fixedEl.offsetWidth; var isUsingCalcZoom = t396__isElementUsingCalcZoom(fixedEl); if ( (isAfterStart && isBeforeEnd && (!isAnimationActivated || isPageResized)) || (isBeforeEnd && isAnimationEnded) ) { fixedEl.style.transform = ''; fixedEl.style.willChange = 'unset'; fixedEl.fixedWrapperEl.style.position = 'fixed'; fixedEl.fixedWrapperEl.style.top = (isScaledOnePxShape || isUsingCalcZoom ? fixedEl.basicAnimationtriggerOffset * zoomValue : fixedEl.basicAnimationtriggerOffset) + diff + 'px'; fixedEl.fixedWrapperEl.classList.add('t-sticky_going'); fixedEl.fixedWrapperEl.classList.remove('t-sticky_ended'); if (isHugHeight) fixedEl.style.height = ''; if (groupWidth) fixedEl.fixedWrapperEl.style.width = groupWidth + 'px'; } if (isAfterEnd && !isAnimationEnded) { var distance = window.isOnlyScalable || isUsingCalcZoom ? fixedEl.distance : fixedEl.distance / zoomValue; fixedEl.style.transform = 'translateY(' + distance + 'px)'; fixedEl.style.willChange = ''; fixedEl.fixedWrapperEl.style.top = ''; fixedEl.fixedWrapperEl.style.position = ''; fixedEl.fixedWrapperEl.classList.remove('t-sticky_going'); fixedEl.fixedWrapperEl.classList.add('t-sticky_ended'); if (isHugHeight) fixedEl.style.height = 'initial'; if (groupWidth) fixedEl.fixedWrapperEl.style.width = 'inherit'; } /** * Здесь мы не можем использовать переменную isAnimationActive, так как при её инициализации * значение может быть false, но при этом выполнится условие выше isBeforeEnd && isAnimationEnded * и класс будет добавлен. Поэтому мы проверяем наличие класса t-sticky_going на месте. */ if (isBeforeStart && fixedEl.fixedWrapperEl.classList.contains('t-sticky_going')) { fixedEl.style.willChange = ''; fixedEl.fixedWrapperEl.style.top = ''; fixedEl.fixedWrapperEl.style.position = ''; fixedEl.fixedWrapperEl.classList.remove('t-sticky_going'); if (isHugHeight) fixedEl.style.height = 'initial'; if (groupWidth) fixedEl.fixedWrapperEl.style.width = 'inherit'; } }); } /** * Кэшируем информацию об элементах * * @param {FixedElement[]} fixedEls - элементы с фиксацией */ function t_animateFix__cacheElsInfo(fixedEls) { var winHeight = window.innerHeight; fixedEls.forEach(function (fixedEl) { var zoomValue = t_animationExt__getZoom(fixedEl); var elTopPos = parseInt(fixedEl.style.top, 10); var isUsingCalcZoom = t396__isElementUsingCalcZoom(fixedEl); if (isUsingCalcZoom && !window.isOnlyScalable) { elTopPos = fixedEl.offsetTop / zoomValue; } if (Number.isNaN(elTopPos)) elTopPos = fixedEl.offsetTop; var isScaledOnePxShape = t_animate__getScaledOnePixShape(fixedEl); if (!window.isOnlyScalable && !isScaledOnePxShape) elTopPos *= zoomValue; // добавить отступ сверху родителя к absolute top position, чтобы определить начало триггера var recTopOffset = t_animateFix__getParentTopOffset(fixedEl); var animCore = fixedEl.querySelector('.tn-molecule, .tn-atom'); var wrapperSelector = t_animationExt__generateWrapperSelector(animCore, 'sticky'); // определяем смещение группы, в которой расположен элемент с фиксацией var parentGroup = fixedEl.closest('.t396__group'); var parentGroupOffset = 0; if (parentGroup && parentGroup !== fixedEl) { parentGroupOffset = parseInt(parentGroup.style.top, 10) || 0; if (!window.isOnlyScalable) parentGroupOffset *= zoomValue; } fixedEl.topOffset = recTopOffset + elTopPos + parentGroupOffset; fixedEl.trigger = parseFloat(t_animationExt__getAttrByRes(fixedEl, 'fix', 'data-animate-', 0)) || 0; fixedEl.distance = parseInt(t_animationExt__getAttrByRes(fixedEl, 'fix-dist', 'data-animate-', 0), 10) || 0; fixedEl.distance *= zoomValue; fixedEl.end = fixedEl.topOffset + fixedEl.distance; fixedEl.fixedWrapperEl = fixedEl.querySelector(wrapperSelector); fixedEl.setAttribute('data-animate-fix-processed', 'true'); var fixedElIMG = fixedEl.querySelector('.t-img'); if (fixedElIMG) { if (fixedElIMG.complete) { t_animateFix__createOnloadImageListener(fixedEl, fixedElIMG, winHeight); } else { fixedElIMG.addEventListener('load', function () { t_animateFix__createOnloadImageListener(fixedEl, fixedElIMG, winHeight); }); } } else { t_animateFix__getElTrigger(fixedEl, winHeight); } }); } /** * Создаем обработчик события загрузки изображения * * @param {FixedElement} fixedEl - элемент с фиксацией * @param {FixedElement} fixedElIMG * @param {number} winHeight */ function t_animateFix__createOnloadImageListener(fixedEl, fixedElIMG, winHeight) { t_animateWaitForUploadImg(fixedElIMG, function () { t_animateFix__getElTrigger(fixedEl, winHeight); t_animateFix__updatePositions([fixedEl], false); }); } /** * * @param {FixedElement} fixedEl - элемент с фиксацией * @returns {number} */ function t_animateFix__getParentTopOffset(fixedEl) { var elParent = fixedEl.closest('.r'); if (!elParent) return 0; var elParentTopOffset = elParent.getBoundingClientRect().top + window.pageYOffset; var elParentTopPadding = parseInt(getComputedStyle(elParent).paddingTop, 10) || 0; return elParentTopOffset + elParentTopPadding; } /** * Проверяем является ли элемент шейпом с автоскейлом с одним пикселем * * @param {HTMLElement} element */ function t_animate__getScaledOnePixShape(element) { var isScaledOnePxShape = element.getAttribute('data-elem-type') === 'shape'; if (!isScaledOnePxShape) return false; var hasScaleOffAttr = element.getAttribute('data-scale-off') === 'yes'; if (hasScaleOffAttr) return true; var elemStyles = getComputedStyle(element); return ( (parseInt(elemStyles.height, 10) <= 2 || parseInt(elemStyles.width, 10) <= 2) && elemStyles.borderWidth === '0px' && elemStyles.backgroundImage === 'none' ); } /** * Проверяем загрузку изображения и запускаем функция обратного вызова после того, * как изображение полностью загружено * * @param {object} img - изображение * @param {Function} cb - функция обратного вызова * @returns {void} */ function t_animateWaitForUploadImg(img, cb) { if (!window.t_animationExt__isLazy) { cb(); return; } var timerID = setTimeout(function () { if (img.classList.contains('loaded') && img.clientWidth && img.src) { cb(); clearTimeout(timerID); } else { t_animateWaitForUploadImg(img, cb); } }, 300); } /** * Получаем триггер элемента * * @param {FixedElement} fixedEl - элемент с фиксацией * @param {number} winHeight - высота окна браузера */ function t_animateFix__getElTrigger(fixedEl, winHeight) { var zoomValue = t_animationExt__getZoom(fixedEl); fixedEl.basicAnimationtriggerOffset = parseInt(t_animationExt__getAttrByRes(fixedEl, 'fix-trgofst', 'data-animate-', 0), 10) || 0; if (window.isOnlyScalable) fixedEl.basicAnimationtriggerOffset *= zoomValue; if (fixedEl.trigger === 0.5 || fixedEl.trigger === 1) { var appendedHeight = winHeight * fixedEl.trigger; var removedHeight = t_animateFix__getPureElHeight(fixedEl) * fixedEl.trigger; removedHeight *= zoomValue; fixedEl.basicAnimationtriggerOffset += appendedHeight; fixedEl.basicAnimationtriggerOffset -= removedHeight; if ( fixedEl.basicAnimationtriggerOffset > fixedEl.topOffset && fixedEl.basicAnimationtriggerOffset <= appendedHeight ) { fixedEl.basicAnimationtriggerOffset = fixedEl.topOffset; } if (!window.isOnlyScalable) fixedEl.basicAnimationtriggerOffset /= zoomValue; } } /** * Если элемент в данный момент с фиксацией, он возвращает нулевую высоту. * * @param {FixedElement} fixedEl - элемент с фиксацией * @returns {number} - чистая высота элемента или его дочернего элемента. */ function t_animateFix__getPureElHeight(fixedEl) { var pureHeight = t_animationExt__getPureHeight(fixedEl); if (pureHeight) return pureHeight; var animCore = fixedEl.querySelector('.tn-molecule, .tn-atom'); return t_animationExt__getPureHeight(animCore); } /*============= MOUSEMOVE PARALLAX ==============*/ /** * init mouse parallax animation * * @returns {void} */ function t_animateParallax__initMouse() { var parallaxMouseElements = t_animationExt__getAnimatedElements('prx', ['mouse']); if (!parallaxMouseElements.length) return; function processParallaxElement(element) { element.setAttribute('data-animate-prx-processed', 'true'); element.pathX = parseInt(t_animationExt__getAttrByRes(element, 'prx-dx', 'data-animate-', 0), 10) || 0; element.pathY = parseInt(t_animationExt__getAttrByRes(element, 'prx-dy', 'data-animate-', 0), 10) || 0; element.animEl = element.querySelectorAll('.tn-atom__prx-wrapper'); t_animateParallax__cacheOffsets(element); // кешируем сохраненные координаты (оффсеты) для элементов с лейзилоадом отдельно // так как они загружаются с задержкой var isImageType = element.getAttribute('data-elem-type') === 'image'; if (isImageType) t_animateParallax__cacheOffsets__OnImgLoad(element); t_animateParallax__moveEl(element); } parallaxMouseElements.forEach(processParallaxElement); const eventList = ['displayChanged', 'zero:height-changed']; const zeroBlocks = Array.from(document.querySelectorAll('.t396')); const onChangeFunction = () => parallaxMouseElements.forEach(t_animateParallax__cacheOffsets); zeroBlocks.forEach(zeroBlock => { eventList.forEach(eventName => { zeroBlock.addEventListener(eventName, onChangeFunction); }); }); window.addEventListener('resize', t_throttle(onChangeFunction, 50)); } /** * save offset of parallax mouse element * * @param {ParallaxMouseElement} parallaxMouseEl - current element */ function t_animateParallax__cacheOffsets(parallaxMouseEl) { var zoomValue = t_animationExt__getZoom(parallaxMouseEl); parallaxMouseEl.topOffset = parallaxMouseEl.getBoundingClientRect().top; if (window.shouldUseScaleFactor) parallaxMouseEl.topOffset *= zoomValue; parallaxMouseEl.topOffset += window.pageYOffset; var elHeight = t_animationExt__getPureHeight(parallaxMouseEl); parallaxMouseEl.bottomOffset = parallaxMouseEl.topOffset + elHeight; // cache parent offset, if element is larger var parent = parallaxMouseEl.closest('.r'); var parentOffsetTop = parent ? parent.getBoundingClientRect().top + window.pageYOffset : 0; var parentHeight = parent ? t_animationExt__getPureHeight(parent) : 0; var parentOffsetBottom = parentOffsetTop + parentHeight; if (parentOffsetTop > parallaxMouseEl.topOffset) { parallaxMouseEl.parentTopOffset = parentOffsetTop; } else { delete parallaxMouseEl.parentTopOffset; } if (parentOffsetBottom < parallaxMouseEl.bottomOffset) { parallaxMouseEl.parentBottomOffset = parentOffsetBottom; } else { delete parallaxMouseEl.parentBottomOffset; } } /** * save offset of img inside parallax mouse element. * we need to catch load event for images, if lazyload is active * * @param {HTMLElement} el - current element */ function t_animateParallax__cacheOffsets__OnImgLoad(el) { if (!window.lazy) return; var image = el.querySelector('img'); if (image) image.addEventListener('load', function () { t_animateParallax__cacheOffsets(el); }); } /** * move element by mousemoving for parallax mouse elements * * @param {ParallaxMouseElement} parallaxMouseEl - current element */ function t_animateParallax__moveEl(parallaxMouseEl) { if ('ontouchend' in document && document.documentElement.clientWidth < 1200) return; var winHeight = window.innerHeight; var winWidth = window.innerWidth; var pathX = parallaxMouseEl.pathX; var pathY = parallaxMouseEl.pathY; var moveX = 0; var moveY = 0; var frameMoveX = 0; var frameMoveY = 0; var stop = false; // TODO вернуться к этой части, когда будет готово абсолютное позиционирование var fixedArtBoard = parallaxMouseEl.closest('[data-artboard-fixed="y"]'); var isInsideFixedArtBoard = Boolean(fixedArtBoard); var hasTriggerOffset = fixedArtBoard && fixedArtBoard.getAttribute('data-artboard-fixed-trigger'); t_animateParallax__preventAnimatedParentTrigger(parallaxMouseEl); document.body.addEventListener( 'mousemove', t_throttle(function (e) { var viewportTopPos = window.pageYOffset; var viewportBottomPos = viewportTopPos + window.innerHeight; var isElOutsideViewport = viewportBottomPos <= parallaxMouseEl.topOffset || parallaxMouseEl.bottomOffset <= viewportTopPos; if (fixedArtBoard && hasTriggerOffset) { isInsideFixedArtBoard = fixedArtBoard.classList.contains('t396__artboard-fixed-active'); } if (typeof e == 'undefined' || (isElOutsideViewport && !isInsideFixedArtBoard)) return; var topActiveArea = e.pageY - e.clientY - 100; var bottomActiveArea = e.pageY + winHeight + 100; if ( !isInsideFixedArtBoard && ((window.innerWidth < 1400 && (parallaxMouseEl.bottomOffset < topActiveArea || parallaxMouseEl.topOffset > bottomActiveArea)) || parallaxMouseEl.parentTopOffset > e.pageY || parallaxMouseEl.parentBottomOffset < e.pageY) ) { return; } // for large background image, which is larger than record (".r") height if (typeof pathX === 'number') { var winHalfX = winWidth / 2; var mouseCenterOffsetX = winHalfX - e.clientX; var moveIntensityX = mouseCenterOffsetX / winHalfX; moveX = Math.round(pathX * moveIntensityX); } if (typeof pathY === 'number') { var winHalfY = winHeight / 2; var mouseCenterOffsetY = winHalfY - e.clientY; var moveIntensityY = mouseCenterOffsetY / winHalfY; moveY = Math.round(pathY * moveIntensityY); } stop = false; t_animateParallax__moveEl__drawFrame(); }, 50) ); function t_animateParallax__moveEl__drawFrame() { if (stop) return; requestAnimationFrame(t_animateParallax__moveEl__drawFrame); if (moveX) frameMoveX += (moveX - frameMoveX) * 0.02; if (moveY) frameMoveY += (moveY - frameMoveY) * 0.02; if (Math.abs(frameMoveX - moveX) < 1 && Math.abs(frameMoveY - moveY) < 1) { stop = true; return; } if (parallaxMouseEl && parallaxMouseEl.animEl.length) { Array.prototype.forEach.call(parallaxMouseEl.animEl, function (animatedEl) { animatedEl.style.transform = 'translate3d(' + frameMoveX + 'px, ' + frameMoveY + 'px, 0px)'; }); } } } /** * If element has animation with transform, we can get trigger * from area from initial (cached) element position. * To prevent it - should use pointer-events. * * @param {ParallaxMouseElement} element - .t396__elem, .t396__group */ function t_animateParallax__preventAnimatedParentTrigger(element) { if (getComputedStyle(element).pointerEvents === 'none') return; var elementCore = element.querySelector('.tn-molecule, .tn-atom'); if (!elementCore) return; element.style.pointerEvents = 'none'; elementCore.style.pointerEvents = 'auto'; } /*============= SCROLL PARALLAX ==============*/ /** * init scroll for parallax animated elements * * @returns {void} */ function t_animateParallax__initScroll() { var parallaxScrollElements = t_animationExt__getAnimatedElements('prx', ['scroll']); if (!parallaxScrollElements.length) return; var hiddenEls = parallaxScrollElements.filter(function (el) { return t_animationExt__isElementHidden(el); }); parallaxScrollElements.forEach(function (parallaxScrollEl) { if (!t_animationExt__isElementHidden(parallaxScrollEl)) { parallaxScrollEl.setAttribute('data-animate-prx-processed', 'true'); var elSpeed = t_animationExt__getAttrByRes(parallaxScrollEl, 'prx-s', 'data-animate-', 0); var parallaxSpeed = Math.round((parseInt(elSpeed) - 100) / 10); var parallaxWrapper = parallaxScrollEl.querySelector('.tn-atom__prx-wrapper'); if (parallaxWrapper && parallaxSpeed) parallaxWrapper.setAttribute('data-parallax-speed', parallaxSpeed.toString()); } }); if (parallaxScrollElements.length) { t_animationExt__createScrollParallax('[data-parallax-speed]'); } if (!hiddenEls.length) return; window.addEventListener( 'scroll', t_throttle(function () { var visibleElements = hiddenEls.filter(function (el, i) { if (!t_animationExt__isElementHidden(el)) { // remove from hidden elements visible child hiddenEls.splice(i, 1); // and append this child to visible elements array return true; } return false; }); if (!visibleElements.length) return; var lastVisibleEl = visibleElements[visibleElements.length - 1]; var elSpeed = t_animationExt__getAttrByRes(lastVisibleEl, 'prx-s', 'data-animate-', 0); var curSelector = 'parallax' + Date.now(); visibleElements.forEach(function (visibleEl) { var atomWrapper = visibleEl.querySelector('.tn-atom__prx-wrapper'); var parallaxSpeed = Math.round((parseInt(elSpeed) - 100) / 10); if (atomWrapper) atomWrapper.setAttribute('data-parallax-speed', parallaxSpeed.toString()); visibleEl.classList.add(curSelector); }); t_animationExt__createScrollParallax('.' + curSelector); }, 50) ); } /** * find element by selector, get it offsets and create parallax. Update values by resize/orientation change * * @param {string} selector */ function t_animationExt__createScrollParallax(selector) { var elements = Array.prototype.slice.call(document.querySelectorAll(selector)); if ('IntersectionObserver' in window) { var parents = t_animationExt__findParallaxParents(elements); t_animationExt__updateParallax(parents, elements, selector); // update offsets in resize if (window.t_animationExt__isMobile) { window.addEventListener('orientationchange', function () { // wait to get correct viewport height setTimeout(function () { t_animationExt__updateParallax(parents, elements, selector); }, 300); }); } else { window.addEventListener( 'resize', t_throttle(function () { t_animationExt__updateParallax(parents, elements, selector); }, 50) ); } } else { //old fashion way to create parallax animation t_animationExt__createParallaxByScroll(selector); } } function t_animationExt__updateParallax(parents, elements, selector) { parents.forEach(function (parent) { t_animationExt__updateParallaxOffset(parent, selector); }); elements.forEach(function (element) { t_animationExt__updateParallaxParams(parents, element); }); } /** * update parallax element offsets, when user find its parent in viewport * * @param {HTMLElement} parent * @param {string} selector */ function t_animationExt__updateParallaxOffset(parent, selector) { var cachePositionObserver = new IntersectionObserver(function (entries, observer) { entries.forEach(function (entry) { if (!entry.isIntersecting) return; var target = entry.target; var allParallaxElements = Array.prototype.slice.call(target.querySelectorAll(selector)); t_animationExt__setParallaxOffsets(allParallaxElements); observer.unobserve(target); }); }); cachePositionObserver.observe(parent); } /** * get parallax element offset, when user scrolled to the current element * * @param {HTMLElement[]} parents * @param {HTMLElement} element */ function t_animationExt__updateParallaxParams(parents, element) { var parallaxObserver = new IntersectionObserver(function (entries, observer) { entries.forEach(function (entry) { if (!entry.isIntersecting) return; var target = entry.target; if (target.isReady) { t_animationExt__animateParallaxOnScroll(target, 'start'); } else { target.addEventListener( 'parallaxReady', function () { t_animationExt__animateParallaxOnScroll(target, 'start'); }, { once: true } ); } observer.unobserve(target); }); }); parallaxObserver.observe(element); } /** * set offsets and same options for parallax elements inside one record * * @param {HTMLElement[]} elements */ function t_animationExt__setParallaxOffsets(elements) { elements.forEach(function (scrollParallaxEl) { var speedFactor = scrollParallaxEl.getAttribute('data-parallax-speed'); var posY = window.pageYOffset; var scaledDifference = t_animationExt__calcScaledDiff(scrollParallaxEl); var blockTopPos = scrollParallaxEl.getBoundingClientRect().top + posY + scaledDifference; var blockHeight = scrollParallaxEl.clientHeight; var isAboveParallax = posY > blockTopPos; // update element top position inside zero-block, that use autoscale var zoomValue = t_animationExt__getZoom(scrollParallaxEl); if (window.shouldUseScaleFactor) blockTopPos *= zoomValue; var speedPoint = 10; var speed = speedFactor ? t_animationExt__getParallaxSpeed(speedFactor, -speedPoint, speedPoint) : 0; var event = document.createEvent('Event'); event.initEvent('parallaxReady', true, true); scrollParallaxEl.isAboveParallax = isAboveParallax; scrollParallaxEl.speed = speed; scrollParallaxEl.topPos = blockTopPos; scrollParallaxEl.bottomPos = blockTopPos + blockHeight; scrollParallaxEl.isStarted = false; scrollParallaxEl.style.transform = ''; var scrollParallaxImgEl = scrollParallaxEl.querySelector('.t-img'); if (scrollParallaxImgEl) { if ( scrollParallaxImgEl.complete && scrollParallaxImgEl.clientHeight !== 0 && scrollParallaxImgEl.src && scrollParallaxImgEl.clientWidth ) { t_animationExt__triggerParallaxInit(scrollParallaxEl, event); } else { scrollParallaxImgEl.addEventListener('load', function () { t_animationExt__triggerParallaxInit(scrollParallaxEl, event); }); } } else { t_animationExt__triggerParallaxInit(scrollParallaxEl, event); } }); } function t_animationExt__triggerParallaxInit(scrollParallaxEl, event) { scrollParallaxEl.isReady = true; scrollParallaxEl.dispatchEvent(event); } /** * * @param {ScrollParallaxElement} scrollParallaxEl * @param {'start' | 'animate'} status - start status selected, when element placed inside viewport position, * animated - when user scrolled and for element set necessary transform by axisY */ function t_animationExt__animateParallaxOnScroll(scrollParallaxEl, status) { if (status === 'animate' && !scrollParallaxEl.isStarted) return; requestAnimationFrame(function () { t_animationExt__animateParallaxOnScroll(scrollParallaxEl, 'animate'); }); var viewportHeight = document.documentElement.clientHeight; var viewportTopPos = window.pageYOffset; var viewportBottomPos = viewportTopPos + viewportHeight; var percentageY = (viewportBottomPos - scrollParallaxEl.topPos) / (scrollParallaxEl.clientHeight + viewportHeight); var updatePositionY = t_animationExt__getParallaxPosition(scrollParallaxEl.speed, percentageY); if (status === 'start') { scrollParallaxEl.posY = updatePositionY; scrollParallaxEl.isStarted = true; } else { updatePositionY -= scrollParallaxEl.posY; scrollParallaxEl.style.transform = 'translateY(' + updatePositionY + 'px)'; } } /** * get parents of parallax element * * @param {HTMLElement[]} elements * @returns {HTMLElement[]} */ function t_animationExt__findParallaxParents(elements) { var IDs = []; var parents = []; elements.forEach(function (el) { var parent = el.closest('.r'); if (!parent) return; var isUniqueID = IDs.indexOf(parent.id) === -1; if (!isUniqueID) return; IDs.push(parent.id); parents.push(parent); }); return parents; } //============== old fashion way to create parallax animation =============// /** * find element by selector, get it offsets and create parallax. Update values by resize/orientation change * * @param {string} selector */ function t_animationExt__createParallaxByScroll(selector) { var elements = Array.prototype.slice.call(document.querySelectorAll(selector)); var scrollParallaxOptions = t_animationExt__getParallaxOffests(elements); // update offsets in resize if (window.t_animationExt__isMobile) { window.addEventListener('orientationchange', function () { // wait to get correct viewport height setTimeout(function () { scrollParallaxOptions = t_animationExt__getParallaxOffests(elements); t_animationExt__animateParallaxByScroll(scrollParallaxOptions); }, 300); }); } else { window.addEventListener( 'resize', t_throttle(function () { scrollParallaxOptions = t_animationExt__getParallaxOffests(elements); t_animationExt__animateParallaxByScroll(scrollParallaxOptions); }, 50) ); } window.addEventListener('scroll', function () { t_animationExt__animateParallaxByScroll(scrollParallaxOptions); }); } /** * create object with necessary params to create and animate parallax * * @param {HTMLElement[]} elements * @returns {ObjecForCreatingParallax[]} */ function t_animationExt__getParallaxOffests(elements) { return elements.map(function (scrollParallaxEl) { var speedFactor = scrollParallaxEl.getAttribute('data-parallax-speed'); var posY = window.pageYOffset; var scaledDifference = t_animationExt__calcScaledDiff(scrollParallaxEl); var blockTopPos = scrollParallaxEl.getBoundingClientRect().top + posY + scaledDifference; var blockHeight = scrollParallaxEl.clientHeight; var isAboveParallax = posY > blockTopPos; // update element top position inside zero-block, that use autoscale var zoomValue = t_animationExt__getZoom(scrollParallaxEl); if (window.shouldUseScaleFactor) blockTopPos *= zoomValue; // apparently parallax equation everyone uses var percentageY = 0.5; var speedPoint = 10; var speed = speedFactor ? t_animationExt__getParallaxSpeed(speedFactor, -speedPoint, speedPoint) : 0; var positionY = t_animationExt__getParallaxPosition(speed, percentageY); return { el: scrollParallaxEl, elHeight: blockHeight, elTopPos: blockTopPos, elBottomPos: blockHeight + blockTopPos, posY: positionY, speed: speed, isAboveParallax: isAboveParallax, }; }); } /** * create object with necessary params to create and animate parallax * * @param {ObjecForCreatingParallax[]} scrollParallaxOptions */ function t_animationExt__animateParallaxByScroll(scrollParallaxOptions) { var viewportHeight = document.documentElement.clientHeight; var viewportTopPos = window.pageYOffset; var viewportBottomPos = viewportTopPos + viewportHeight; scrollParallaxOptions.forEach(function (opt) { var isElementInsideViewport = opt.elTopPos < viewportBottomPos && opt.elBottomPos > viewportTopPos && opt.elBottomPos <= viewportBottomPos && opt.elTopPos >= viewportTopPos; if (!opt.isAboveParallax && !isElementInsideViewport) return; var percentageY = (viewportBottomPos - opt.elTopPos) / (opt.elHeight + viewportHeight); var updatePositionY = t_animationExt__getParallaxPosition(opt.speed, percentageY); if (!opt.isAboveParallax) { opt.posY = updatePositionY; opt.isAboveParallax = true; } updatePositionY -= opt.posY; opt.el.style.transform = 'translateY(' + updatePositionY + 'px)'; }); } //============== ending of old fashion way to create parallax animation =============// /** * get correct trigger offsets in autoscale mode, in case of use Firefox/Opera * * @param {HTMLElement} el * @returns {number} - difference between top position of parent and scaled children */ function t_animationExt__calcScaledDiff(el) { var scaledWrapper = el.querySelector('.tn-atom__scale-wrapper'); if (window.isOnlyScalable && scaledWrapper && el) { var elTopPos = el.getBoundingClientRect().top; var scaleTopPos = scaledWrapper.getBoundingClientRect().top; var difference = elTopPos - scaleTopPos; el.setAttribute('data-scaled-diff', difference.toString()); } var diff = el.getAttribute('data-scaled-diff') || '0'; return parseInt(diff, 10); } function t_animationExt__getParallaxSpeed(value, min, max) { return value <= min ? min : value >= max ? max : value; } function t_animationExt__getParallaxPosition(speed, percentage) { return Math.round(speed * (100 * (1 - percentage))); } /*============= Support functions ==============*/ /** * get height without padding * * @param {HTMLElement} el - current element * @returns {number} - height without padding */ function t_animationExt__getPureHeight(el) { if (!el) return 0; var elHeight = el.clientHeight || el.offsetHeight || parseInt(window.getComputedStyle(el).height, 10); var elPaddingTop = el.style.paddingTop || 0; var elPaddingBottom = el.style.paddingBottom || 0; return elHeight - (elPaddingTop + elPaddingBottom); } function t_animationExt__isElementHidden(el) { return !el.offsetWidth && !el.offsetHeight && !el.getClientRects().length; } /** * check old IE versions * * @returns {boolean} - is old IE version */ function t_animateParallax__checkOldIE() { var iEIndex = window.navigator.userAgent.indexOf('MSIE'); if (iEIndex === -1) return false; var ieVersion = parseInt( window.navigator.userAgent.substring(iEIndex + 5, window.navigator.userAgent.indexOf('.', iEIndex)), 10 ); return ieVersion === 8 || ieVersion === 9 || ieVersion === 10; } /** * window.tn_scale_factor used for old sites * * @param {HTMLElement} el - current element * @returns {number} - zoom value */ function t_animationExt__getZoom(el) { if (typeof el.scaleFactor !== 'undefined') return el.scaleFactor; var artboard = el.closest('.t396__artboard'); if (!artboard) return 1; var abID = artboard.getAttribute('data-artboard-recid'); if ( artboard.classList.contains('t396__artboard_scale') || t_animationExt__getAttrByRes(artboard, 'data-artboard-upscale', '', 0) === 'window' ) { return abID && window.tn['ab' + abID] ? window.tn['ab' + abID].scaleFactor || window.tn_scale_factor : window.tn_scale_factor; } return 1; } /** * get value from attribute, it depends on resolution parameter, element contains mobile animation, or not * * @param {HTMLElement} el - current element * @param {string} attr - animation attribute * @param {string} preffix - animation attribute preffix (data-animate-) * @param {number} resolution - resolution, in many times use window.innerWidth * @returns {string} - attribute value (empty string - if attribute is not defined, or el is not defined */ function t_animationExt__getAttrByRes(el, attr, preffix, resolution) { if (!el?.isConnected) return ''; var isElHasMobileAnimation = el.getAttribute('data-animate-mobile') === 'y'; var foundValue; var breakpoints = []; var resolutionMax; var artBoard = el.closest('.t396__artboard'); var recid = artBoard.getAttribute('data-artboard-recid'); var artBoardId = 'ab' + recid; if (typeof window.tn[artBoardId] !== 'undefined') { if (!resolution) resolution = window.tn[artBoardId].curResolution; resolutionMax = window.tn[artBoardId].curResolution_max; breakpoints = window.tn[artBoardId].screens.slice(0, window.tn[artBoardId].screens.length - 1); } else { if (!resolution) resolution = window.tn.curResolution; resolutionMax = 1200; breakpoints = [320, 480, 640, 960]; } if (resolution === resolutionMax) { return el.getAttribute(preffix + attr); } else if (preffix && !isElHasMobileAnimation && resolution < 1200) { el.style.transition = 'none'; return ''; } else { foundValue = el.getAttribute(preffix + attr + '-res-' + resolution); } if (!foundValue) { for (var i = 0; i < breakpoints.length; i++) { var breakpoint = breakpoints[i]; if (breakpoint <= resolution) continue; if (breakpoint === resolutionMax) { foundValue = el.getAttribute(preffix + attr); } else { foundValue = el.getAttribute(preffix + attr + '-res-' + breakpoint); } if (foundValue) break; } } return foundValue ? foundValue : el.getAttribute(preffix + attr) || ''; } /** * Получает список элементов которые будут анимированы в анимации фиксации или параллакса. * Ищет элементы с заданными триггерами и идентификаторами артбордов учитывая адаптивы. * * @param {'fix' | 'prx'} attribute - тип анимации фиксированная (fix) или параллакс (prx) * @param {Array<'scroll' | 'mouse'>} triggers - триггеры анимации для поиска * @return {HTMLElement[]} - элементы на которые должна примениться анимация */ function t_animationExt__getAnimatedElements(attribute, triggers = []) { const elementsSelector = '.t396__artboard:not([data-artboard-fixed="y"]) .t396__elem, .t396__artboard:not([data-artboard-fixed="y"]) .t396__group'; const elementsList = Array.from(document.querySelectorAll(elementsSelector)); return elementsList.filter(getAnimatedElement).filter(getNotProcessedElement); /** * Совершается поиск по всем элементам зеро-блока с дата-атрибутами, соответствующие паттерну * [data-animate-(-res-)], где может быть 'fix' либо 'prx'. * -res- может либо не быть задан вовсе, либо соответствовать одному из брейкпоинтов артборда. * * @param {HTMLElement} element * @returns {boolean} */ function getAnimatedElement(element) { return Array.from(element.attributes).some(elementAttribute => { const { name, value } = elementAttribute; const expectedPrefix = `data-animate-${attribute}`; if (!name.startsWith(expectedPrefix)) return false; if (triggers.length) return triggers.includes(value); return true; }); } function getNotProcessedElement(element) { return !element.hasAttribute(`data-animate-${attribute}-processed`); } } /** * Ищет все артборды и информацию об адаптивах. * * @param {Array} artboardIds - массив идентификаторов артбордов, когда хотим получить анимируемые элементы из определенных артбордов * @returns {{recid: string, screens: Array, screenMax: number}} */ function t_animationExt__getArtBoardsScreens(artboardIds = []) { var artBoardsScreens = []; var artBoards = []; if (artboardIds && artboardIds.length) { artBoards = artboardIds.map(id => document.querySelector(`[data-artboard-recid="${id}"]`)).filter(Boolean); } else { var artBoards = t_animationExt__getArtboards('396', false); artBoards = artBoards.concat(t_animationExt__getArtboards('121', false)); } Array.prototype.forEach.call(artBoards, function (artBoard) { var recid = artBoard.getAttribute('data-artboard-recid'); var artBoardId = 'ab' + recid; var screens = []; var screenMax; if (typeof window.tn[artBoardId] !== 'undefined') { screens = window.tn[artBoardId].screens.slice().reverse(); screenMax = window.tn[artBoardId].curResolution_max; } else { screens = [1200, 960, 640, 480, 320]; screenMax = 1200; } artBoardsScreens.push({ recid: recid, screens: screens, screenMax: screenMax, }); }); return artBoardsScreens; } /** * wrappint atom element to current classname div * * @param {HTMLElement} el - atom * @param {string[]} classNameList * @param {string} wrapperSelector * @param {HTMLElement | null} scaleWrapper - for Opera/Firefox, in case of use autoscale */ function t_animationExt__wrapEl(el, classNameList, wrapperSelector, scaleWrapper) { if (el.closest(wrapperSelector)) return; var parentElement = el.closest('.tn-elem, .tn-group'); var div = document.createElement('div'); classNameList.forEach(function (name) { div.classList.add(name); }); /** * display: inherit повторяет значение родителя: у элемента это table, поэтому tn-atom * остаётся table-cell, а у autolayout-группы это block, который в отличие от таблицы * не растягивается по контенту и сохраняет скролл при overflow: auto/scroll */ div.style.display = 'inherit'; div.style.width = 'inherit'; div.style.height = 'inherit'; div.style.borderRadius = 'inherit'; scaleWrapper ? div.appendChild(scaleWrapper) : div.appendChild(el); parentElement.appendChild(div); t_animationExt__updateStylesAfterWrapping(scaleWrapper || el, div, parentElement); } /** * * @param {HTMLElement} animCore * @param {'sticky' | 'prx'} prefix * @return {string[]} */ function t_animationExt__generateWrapperClassList(animCore, prefix) { var isMolecule = animCore.classList.contains('tn-molecule'); var template = '__' + prefix + '-wrapper'; if (isMolecule) return ['tn-molecule' + template, 'tn-atom' + template]; return ['tn-atom' + template]; } /** * * @param {HTMLElement} animCore * @param {'sticky' | 'prx'} prefix * @return {string} */ function t_animationExt__generateWrapperSelector(animCore, prefix) { var isMolecule = animCore.classList.contains('tn-molecule'); var template = '__' + prefix + '-wrapper'; if (isMolecule) return '.tn-molecule' + template; return '.tn-atom' + template + ':not(.tn-molecule' + template + ')'; } function t_animationExt__updateStylesAfterWrapping(atom, wrapper, parentElement) { // add border-radius property for animation wrapper, because we set filters for parentElem // getPropertyValue returns border-radius value in px. If it cannot setted, will return '0px' var elType = parentElement ? parentElement.getAttribute('data-elem-type') : ''; var elBorderRadius = window.getComputedStyle(parentElement).getPropertyValue('border-radius'); if ((elType === 'shape' || elType === 'widget') && parseInt(elBorderRadius, 10)) { wrapper.style.borderRadius = elBorderRadius; } // find filters in parent element to set them to wrapper, and remove from current parent var filterList = ['filter', 'backdrop-filter']; filterList = filterList.map(function (filter) { var webkitFilter = '-webkit-' + filter; var parentFilterValue = window.getComputedStyle(parentElement).getPropertyValue(filter); if (parentFilterValue === 'none' || parentFilterValue === '') parentFilterValue = window.getComputedStyle(parentElement).getPropertyValue(webkitFilter); if (parentFilterValue !== 'none' && parentFilterValue !== '') { return { filter: filter, webkitFilter: webkitFilter, value: parentFilterValue }; } }); // If filter couldn't find, Array.prototype.map returns undefined. // Should use Array.prototype.filter to remove negative values (undefined) filterList = filterList.filter(function (filter) { return filter; }); filterList.forEach(function (filterOpts) { if (navigator.userAgent.search('Firefox') !== -1) wrapper.style.backfaceVisibility = 'visible'; wrapper.style[filterOpts.webkitFilter] = filterOpts.value; wrapper.style[filterOpts.filter] = filterOpts.value; parentElement.style[filterOpts.webkitFilter] = 'none'; parentElement.style[filterOpts.filter] = 'none'; if (window.getComputedStyle(atom).transform === 'none') atom.style.transform = 'translateZ(0)'; }); var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); if (isSafari && filterList.length && elType === 'image') { var backdropFilterImageEvent = document.createEvent('Event'); backdropFilterImageEvent.initEvent('backdropFilterImgWrappered', true, true); parentElement.dispatchEvent(backdropFilterImageEvent); parentElement.classList.add('t396__elem--backdrop-filter-img-wrappered'); } t_animationExt__chromeFixBackdropFilter(atom, wrapper, filterList); } function t_animationExt__chromeFixBackdropFilter(atom, wrapper, filterList) { var hasBackdropFilter = filterList.some(function (opt) { return opt.filter === 'backdrop-filter'; }); if (navigator.userAgent.indexOf('Chrome') === -1 || !hasBackdropFilter) return; var atomBG = window.getComputedStyle(atom).getPropertyValue('background-color'); var atomsOpacity = window.getComputedStyle(atom).getPropertyValue('opacity'); if (atomBG === 'rgba(0, 0, 0, 0)' || atomsOpacity === '1') return; var atomsBackgroundColorRGB = atomBG.substring(atomBG.indexOf('(') + 1, atomBG.indexOf(')')); wrapper.style.backgroundColor = 'rgba(' + atomsBackgroundColorRGB + ',' + atomsOpacity + ')'; atom.style.opacity = '1'; atom.style.backgroundColor = 'transparent'; }