/** * tilda-animation * работает в блоках, где анимация может быть подключена к его элементам - заголовок, подзаголовок, * анимированные цифры и т.д. */ /** * tilda-animation * work with: * - basicly animated elements like: titles, subtitles, paragraphs, buttons (fadeIn, fadeInTop, fadeInBottom, fadeInLeft, fadeInRight etc.) * - numbers animation (for blocks CL19, FR402, FR403, FR501 etc) * - basic animation in Zero Block, but fixing and parallax doing tilda-animation-ext * * * how does it work by steps * 1) check the document readystate if it is not 'loading' than start init otherwise wait for DOMContentLoaded * 2) init function * - check all cases when we need to turn off animation * - wrap all text elements with custom opacity * - add no hover class to btns * - check for animation type fadeInLeft if they it exists than added overflow-x: hidden to #allrecords * - prepair all elements with number animation * - replace number part with span with 0 * - dublicate all el styles to new span * 3) start animation function after 1.5s delay * - get all animated blocks/elems into 3 Node lists * 1) grouped animation blocks * 2) chain animation blocks * 3) other animation elements * - if there is a mobile device than additionally check * and remove animation class (.t-animate) from all blocks * except elements in zero-block with mobile animtion turned on * - set state for all animated groups of blocks depends on their position on the screen * 1) grouped animation blocks * 2) chain animation blocks * 3) other animation elements * - regroup animated groups of blocks * - if the intersection observer is exist than set it, special observer for each array EXCEPT CHAIN ANIMMATION (grouped, other els) * - for chain animation we set scroll event on window * we check first element in chain array and add it class t-animate__chain_first-in-row, * to let the new row be animated as soon, as the first element in previous row is animated * */ if (document.readyState !== 'loading') { t_animate__init(); } else { document.addEventListener('DOMContentLoaded', t_animate__init); } /** * Init animation * * @returns {void} - if user stay in edit mode, animation off, etc. */ function t_animate__init() { // check if we need to turn off animation if (!t_animate__checkAnimationAvailability()) return; // generaty startes styles for custom resolutions t_animate__generateStyles(); // wrap animated text elements with custom opacity t_animate__wrapTextWithOpacity(); // adding t-animate_no-hover to animated btns t_animate__addNoHoverClassToBtns(); // check for fadeInLeft elements t_animate__preventHorizontalScroll(); if (document.documentElement.clientWidth >= 980) { t_animate__wrapTextAnimationsWords(); } // prepair number for animation if (document.documentElement.clientWidth >= 1200) { t_animate__parseNumberText(); } /** * На разрешении меньше 1200px анимация отключена, поэтому показываем элементы сразу, * не дожидаясь отложенного старта анимации */ if (window.innerWidth < 1200) { t_animate__checkMobile(Array.from(document.querySelectorAll('.t-animate'))); } // letters are wrapped after mobile check, so text of elements without mobile animation isn't split into letters t_animate__wrapAnimatedTextLetters(); // below 980px text animations are available only for ZeroBlock elements with mobile animation, which are left after mobile check if (document.documentElement.clientWidth < 980) { t_animate__wrapTextAnimationsWords('.t396'); } // start animation using setTimeout because // if don't than animation will be triggered // immediately and some styles/images may be not downloaded yet setTimeout(function () { t_animate__startAnimation(); }, 1500); } /** * Фильтруем все анимированные элементы на разрешении, меньше 1200px. * Если анимированный элемент находится внутри зеро-блока и имеет * активированный флаг мобильной анимации, пропускаем его. * В остальных случаях удаляем анимацию на элементе, * или его детях, и удаляем из перечня анимированных элементов. * * @param {HTMLElement[]} elementList - animated elements in array * @returns {HTMLElement[]} - filtered elements array (without zeroBlock child) */ function t_animate__checkMobile(elementList) { return elementList.filter(function (element) { var zeroBlockElement = element.closest('.t396__elem, .t396__group'); var hasMobileAnimation = zeroBlockElement && zeroBlockElement.getAttribute('data-animate-mobile') === 'y'; if (hasMobileAnimation) return true; var isRecordElement = element.classList.contains('r'); if (isRecordElement) { Array.prototype.forEach.call(element.querySelectorAll('.t-animate'), function (el) { t_animate__removeAnimationClass(el, ''); }); } else { t_animate__removeAnimationClass(element, ''); } return false; }); } /** * Удаляет класс .t-animate с элемента. * Второй аргумент - массив или строка модификатора, который тоже удаляется, если задан. * * @param {HTMLElement | null} element * @param {string[] | string} modifierList */ function t_animate__removeAnimationClass(element, modifierList) { if (!element) return; var baseClass = 't-animate'; element.classList.remove(baseClass); if (!modifierList) return; if (typeof modifierList === 'string') modifierList = [modifierList]; modifierList.forEach(function (modifier) { var className = baseClass + '_' + modifier; element.classList.remove(className); }); } /** * Для блоков с fadeInLeft блокируем overflow, чтобы * выходящий за пределы блока элемент не создавал горизонтальный скролл. * Обложки и зеро-блоки не обрабатываем, у них задан overflow: hidden по дефолту */ function t_animate__preventHorizontalScroll() { const fadeInLeftElements = Array.from(document.querySelectorAll('[data-animate-style="fadeinleft"]')); const elementsToHideOverflowFor = fadeInLeftElements.filter(element => { if (element.closest('.t396__artboard, .t-cover')) return false; return element.getBoundingClientRect().right > window.innerWidth; }); if (!elementsToHideOverflowFor.length || window.innerWidth < 980) return; elementsToHideOverflowFor.forEach(fadeInLeftElement => { const parentRecord = fadeInLeftElement.closest('.r'); parentRecord.classList.add('t-animate__overflow-x-hidden'); }); } /** * Check if we need to turn off animmation on the page * @returns {Boolean} */ function t_animate__checkAnimationAvailability() { var allRec = document.querySelector('.t-records'); var animationOff = allRec ? allRec.getAttribute('data-blocks-animationoff') : null; var editMode = allRec ? allRec.getAttribute('data-tilda-mode') : null; // turning off animmation if (/Bot/i.test(navigator.userAgent) || animationOff === 'yes' || t_animate__checkIE() || editMode === 'edit') { var animationList = document.querySelectorAll('.t-animate'); Array.prototype.forEach.call(animationList, function (animation) { t_animate__removeAnimationClass(animation, ''); }); return false; } return true; } /** * This function generates CSS basic animation styles for breakpoints of all ZeroBlocks on page */ function t_animate__generateStyles() { var isZeroOnPage = !!document.querySelector('.t396'); if (!isZeroOnPage) return; var breakpoints = t_animate__getBreakpointsArr(); // prettier-ignore var styleStr = '.t396 .t-animate[data-animate-style="fadein"],' + '.t396 .t-animate[data-animate-style="fadeinup"],' + '.t396 .t-animate[data-animate-style="fadeindown"],' + '.t396 .t-animate[data-animate-style="fadeinleft"],' + '.t396 .t-animate[data-animate-style="fadeinright"],' + '.t396 .t-animate[data-animate-style="zoomin"],' + '.t396 .t-animate[data-animate-style="zoomout"] {' + 'opacity: 0;' + '-webkit-transition-property: opacity, transform;' + 'transition-property: opacity, transform;' + '-webkit-transition-duration: 1s;' + 'transition-duration: 1s;' + '-webkit-transition-timing-function: cubic-bezier(0.19, 1, 0.22, 1);' + 'transition-timing-function: cubic-bezier(0.19, 1, 0.22, 1);' + '-webkit-backface-visibility: hidden;' + 'backface-visibility: hidden;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '.t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadein"],' + '.t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeinup"],' + '.t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeindown"],' + '.t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeinleft"],' + '.t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeinright"],' + '.t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="zoomin"],' + '.t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="zoomout"] {' + 'opacity: 0;' + '-webkit-transition-property: opacity, transform;' + 'transition-property: opacity, transform;' + '-webkit-transition-duration: 1s;' + 'transition-duration: 1s;' + '-webkit-transition-timing-function: cubic-bezier(0.19, 1, 0.22, 1);' + 'transition-timing-function: cubic-bezier(0.19, 1, 0.22, 1);' + '-webkit-backface-visibility: hidden;' + 'backface-visibility: hidden;' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-title.t-animate {' + '-webkit-transition-duration: 1.2s;' + 'transition-duration: 1.2s;' + '}' + '.t396 .t-descr.t-animate,' + '.t396 .t-uptitle.t-animate,' + '.t396 .t-subtitle.t-animate,' + '.t396 .t-text.t-animate {' + '-webkit-transition-duration: 0.7s;' + 'transition-duration: 0.7s;' + '}' + '.t396 .t-item.t-animate {' + '-webkit-transition-duration: 0.5s;' + 'transition-duration: 0.5s;' + '}' + '.t396 .t-animate[data-animate-style="fadein"] {' + 'opacity: 0;' + 'transform: none;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadein"] {' + 'opacity: 0;' + 'transform: none;' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-style="fadein"] {' + 'opacity: 1;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="fadein"] {' + 'opacity: 1;' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate[data-animate-style="fadeinup"] {' + '-webkit-transform: translate(0, 100px);' + 'transform: translate(0, 100px);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeinup"] {' + '-webkit-transform: translate(0, 100px);' + 'transform: translate(0, 100px);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-style="fadeinup"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="fadeinup"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate[data-animate-style="fadeindown"] {' + '-webkit-transform: translate(0, -100px);' + 'transform: translate(0, -100px);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeindown"] {' + '-webkit-transform: translate(0, -100px);' + 'transform: translate(0, -100px);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-style="fadeindown"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="fadeindown"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate[data-animate-style="fadeinleft"] {' + '-webkit-transform: translate(100px, 0);' + 'transform: translate(100px, 0);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeinleft"] {' + '-webkit-transform: translate(100px, 0);' + 'transform: translate(100px, 0);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-style="fadeinleft"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="fadeinleft"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate[data-animate-style="fadeinright"] {' + '-webkit-transform: translate(-100px, 0);' + 'transform: translate(-100px, 0);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="fadeinright"] {' + '-webkit-transform: translate(-100px, 0);' + 'transform: translate(-100px, 0);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-style="fadeinright"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="fadeinright"] {' + 'opacity: 1;' + '-webkit-transform: none;' + 'transform: none;' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate[data-animate-style="zoomin"] {' + '-webkit-transform: scale(0.9);' + 'transform: scale(0.9);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="zoomin"] {' + '-webkit-transform: scale(0.9);' + 'transform: scale(0.9);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-style="zoomin"] {' + 'opacity: 1;' + '-webkit-transform: scale(1);' + 'transform: scale(1);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="zoomin"] {' + 'opacity: 1;' + '-webkit-transform: scale(1);' + 'transform: scale(1);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate[data-animate-style="zoomout"] {' + '-webkit-transform: scale(1.2);' + 'transform: scale(1.2);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate[data-animate-style-res-' + mediaQuery.minRes + '="zoomout"] {' + '-webkit-transform: scale(1.2);' + 'transform: scale(1.2);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-style="zoomout"] {' + 'opacity: 1;' + '-webkit-transform: scale(1);' + 'transform: scale(1);' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="zoomout"] {' + 'opacity: 1;' + '-webkit-transform: scale(1);' + 'transform: scale(1);' + '}' + '}'; } // prettier-ignore styleStr += '.t396 .t-animate_started[data-animate-distance],' + '.t396 .t-animate_started[data-animate-scale]{' + '-webkit-transform: none !important;' + 'transform: none !important;' + '}'; for (var index = 0; index < breakpoints.length; index++) { var mediaQuery = t_animate__getMediaQuery(breakpoints, index); if (mediaQuery.isContinue) continue; // prettier-ignore styleStr += mediaQuery.text + '#allrecords .t396 .t-animate_started[data-animate-distance-res-' + mediaQuery.minRes + '],' + '#allrecords .t396 .t-animate_started[data-animate-style-res-' + mediaQuery.minRes + '="zoomout"] {' + '-webkit-transform: none !important;' + 'transform: none !important;' + '}' + '}'; } var style = document.createElement('style'); var head = document.head || document.querySelector('head'); style.textContent = styleStr; head.appendChild(style); } /** * find all the unique breakpoints on the page * * @returns {Array} unique breakpoints */ function t_animate__getBreakpointsArr() { var breakpoints = []; var artBoards = Array.prototype.slice.call( document.querySelectorAll( '.r[data-record-type="396"]:not(.t397__off, .t395__off, .t400__off) .t396__artboard, .r[data-parenttplid="396"]:not(.t397__off, .t395__off, .t400__off) .t396__artboard' ) ); Array.prototype.forEach.call(artBoards, function (artBoard) { if (!artBoard.classList.contains('t396__artboard')) return; var screens = artBoard.getAttribute('data-artboard-screens'); screens = screens ? screens.split(',') : [1200, 960, 640, 480, 320]; screens = screens.map(function (screen) { return parseInt(screen, 10); }); var difference = screens.filter(function (screen) { return breakpoints.indexOf(screen) === -1; }); breakpoints = breakpoints.concat(difference); }); breakpoints = t_animate__sortArr(breakpoints); return breakpoints; } /** * get correct string of CSS @media-query for generated styles of animated elements in Zero Block * * @returns {Object} */ function t_animate__getMediaQuery(breakpoints, index) { var text = ''; var isContinue = false; var minRes = breakpoints[index + 1]; var maxRes = breakpoints[index] - 1; var lastBreakpoint = index === breakpoints.length - 1; var preLastBreakpoint = index === breakpoints.length - 2; if (lastBreakpoint) { isContinue = true; } else if (preLastBreakpoint) { text += '@media screen and (max-width: ' + maxRes + 'px) {'; } else { text += '@media screen and (min-width: ' + minRes + 'px) and (max-width: ' + maxRes + 'px) {'; } return { text, isContinue, minRes }; } /** * sorting an array of breakpoints from large to small * * @param {Array} breakpoints - unsorted array of breakpoints * @returns {Array} soritized array of breakpoints */ function t_animate__sortArr(breakpoints) { return breakpoints.sort(function (a, b) { return b - a; }); } /** * Start animation * * @returns {void} - if some elements cannot find */ function t_animate__startAnimation() { var records = document.querySelectorAll('.r'); // animGroupsBlocks contains connected elements, which animation starts at the same time var animGroupsBlocks = Array.prototype.filter.call(records, function (record) { return record.querySelector('.t-animate[data-animate-group=yes]'); }); // animChainsBlocks contains elements, which are animated as a chain, row by row var animChainsBlocks = Array.prototype.filter.call(records, function (record) { return record.querySelector('.t-animate[data-animate-chain="yes"]'); }); // animElems contains independent single elements var animElems = document.querySelectorAll('.t-animate'); animElems = Array.prototype.filter.call(animElems, function (animEl) { return ( !( animEl.getAttribute('data-animate-group') === 'yes' || animEl.getAttribute('data-animate-chain') === 'yes' ) && !animEl.getAttribute('observer-ready') ); }); // upgrade list of animated blocks because of mobile resolution if (window.innerWidth < 1200) { animGroupsBlocks = t_animate__checkMobile(animGroupsBlocks); animChainsBlocks = t_animate__checkMobile(animChainsBlocks); animElems = t_animate__checkMobile(animElems); } // if there is no more blocks than quit if (!animGroupsBlocks.length && !animElems.length && !animChainsBlocks.length) { return; } // set state to all groups t_animate__setAnimationState(animGroupsBlocks, animChainsBlocks, animElems); animGroupsBlocks = t_animate__hasWaitAnimation(animGroupsBlocks); animElems = t_animate__hasWaitAnimation(animElems); animChainsBlocks = t_animate__hasWaitAnimation(animChainsBlocks); /** * Conditionally apply a workaround for the CSS transition bug in Safari 15.4 / WebKit browsers. * Remove this workaround once the WebKit bug fix is released. * https://github.com/WebKit/WebKit/commit/068a5519f0216cac2e937dcff214ae843ae69a55 */ // prettier-ignore var isWebKit154 = typeof navigator !== 'undefined' && /^((?!chrome|android).)*(safari|mobile)/i.test(navigator.userAgent) && /(os |version\/)15(.|_)[4-9]/i.test(navigator.userAgent); if ('IntersectionObserver' in window && !isWebKit154) { // groups if (animGroupsBlocks.length) { // первый элемент в группе станет триггером для анимации всех остальных элементов var firstElemInGroup = []; animGroupsBlocks.forEach(function (animGroup) { var firstElem = animGroup.querySelector('.t-animate'); var firstElemAttr = firstElem.getAttribute('data-animate-style'); if (firstElemAttr === 'fadeindown') { var firstElemParent = firstElem.closest('.t-cover'); // is overflow hiddening if (firstElemParent) { var nextElem = animGroup.querySelector('.t-animate:not(:first-child)'); if (nextElem) { firstElem = nextElem; } } } firstElemInGroup.push(firstElem); }); firstElemInGroup.forEach(function (animElem) { var options = { rootMargin: (animElem.offsetHeight / 5) * -1 + 'px 0px', }; var animGroupsObserver = new IntersectionObserver(function (entries, animGroupsObserver) { entries.forEach(function (entry) { if (entry.isIntersecting) { var target = entry.target; animGroupsObserver.unobserve(target); // code from function t_animate__animateGroups var currentBlockEls = target.closest('.r').querySelectorAll('.t-animate'); // clear array from all chaining blocks currentBlockEls = Array.prototype.filter.call(currentBlockEls, function (el) { return !( el.classList.contains('t-animate__btn-wait-chain') || el.getAttribute('data-animate-chain') === 'yes' ); }); t_animate__makeSectionButtonWait(target); t_animate__saveSectionHeaderStartTime(target); Array.prototype.forEach.call(currentBlockEls, function (el) { el.classList.remove('t-animate_wait'); t_animate__removeNoHoverClassFromBtns(el); t_animate__startElementAnimation(el, false); }); } }); }, options); animGroupsObserver.observe(animElem); }); } // elems if (animElems.length) { animElems.forEach(function (animElem) { var options = {}; var curElemTriggerOffset = t_animate__getAttrByResBase(animElem, 'trigger-offset'); if (curElemTriggerOffset) { options.rootMargin = '0px 0px ' + curElemTriggerOffset.replace('px', '') * -1 + 'px 0px'; } var animElemsObserver = new IntersectionObserver(function (entries, animElemsObserver) { entries.forEach(function (entry) { var target = entry.target; if (!target.demandTransform && target.style.transform) { target.demandTransform = target.style.transform; target.style.transform = 'unset'; } else { var computedTransform = window.getComputedStyle(target).transform; if (!target.style.transform && computedTransform !== 'none') { target.demandTransform = computedTransform; target.style.transform = 'unset'; } } if (entry.isIntersecting) { if (!target.closest('.t1093')) animElemsObserver.unobserve(target); var delay = target.style.transitionDelay || '0ms'; if (delay.indexOf('ms') !== -1) { delay = parseInt(delay) + 250; } else { delay = parseFloat(delay) * 1000 + 250; } // code from function t_animate__animateElems var animateElems = function () { target.classList.remove('t-animate_wait'); t_animate__removeNoHoverClassFromBtns(target); t_animate__startElementAnimation(target, true); if (t_animate__getAttrByResBase(target, 'style') === 'animatednumber') { t_animate__animateNumbers(target); } }; if (target.demandTransform && target.demandTransform.indexOf('matrix') !== -1) { target.style.transform = ''; } if (target.demandTransform && target.style.transform === 'unset') { target.style.transform = target.demandTransform; delete target.demandTransform; } setTimeout(function () { animateElems(); }, delay); } }); }, options); animElem.dataset.observerReady = true; animElemsObserver.observe(animElem); }); } // chains if (animChainsBlocks.length) { var getOffsets = function () { t_animate__getChainOffsets(animChainsBlocks); }; getOffsets(); window.addEventListener( 'resize', t_throttle(function () { getOffsets(); }) ); setInterval(getOffsets, 5000); window.addEventListener( 'scroll', t_throttle(function () { var viewTop = window.pageYOffset; var viewBottom = viewTop + window.innerHeight; t_animate__animateChainsBlocks(animChainsBlocks, viewBottom); }) ); } } else { // cache offsets var getOffsets = function () { t_animate__getGroupsOffsets(animGroupsBlocks); t_animate__getChainOffsets(animChainsBlocks); t_animate__getElemsOffsets(animElems); }; getOffsets(); window.addEventListener('resize', t_throttle(getOffsets)); setInterval(getOffsets, 5000); // end of cache offsets window.addEventListener( 'scroll', t_throttle(function () { var refreshedBlocks = t_animate__deleteAnimatedEls(animGroupsBlocks, animElems); animElems = refreshedBlocks[0]; animGroupsBlocks = refreshedBlocks[1]; var animBlocks = t_animate__animateOnScroll(animGroupsBlocks, animChainsBlocks, animElems); if (animBlocks && animBlocks.length) { animGroupsBlocks = animBlocks[0]; animChainsBlocks = animBlocks[1]; animElems = animBlocks[2]; } }) ); } Array.prototype.forEach.call(records, function (record) { var recordPopup = record.querySelector('.t-popup'); if (recordPopup) { recordPopup.addEventListener( 'scroll', t_throttle(function () { var viewBottom = window.pageYOffset + window.innerHeight; if ( (recordPopup.classList.contains('t-animate') && recordPopup.getAttribute('data-animate-chain') === 'yes') || recordPopup.querySelector('.t-animate[data-animate-chain=yes]') ) { var popupAnimChainsBlocks = [recordPopup]; t_animate__setAnimationStateChains(popupAnimChainsBlocks); popupAnimChainsBlocks = Array.prototype.filter.call(popupAnimChainsBlocks, function (el) { return el.querySelector('.t-animate_wait'); }); t_animate__getChainOffsets(popupAnimChainsBlocks); t_animate__animateChainsBlocks(popupAnimChainsBlocks, viewBottom); } }) ); } }); } /* ---------- functions, which do all animation work on scroll ---------- */ /** * Animate on scroll. Called if IntersectionObserver is undefined * * @param {HTMLElement[]} animGroupsBlocks - list of animated group blocks * @param {HTMLElement[]} animChainsBlocks - list of animated chain blocks * @param {HTMLElement[]} animElems - list of animated elements * @returns {void} */ function t_animate__animateOnScroll(animGroupsBlocks, animChainsBlocks, animElems) { if (!animGroupsBlocks.length && !animChainsBlocks.length && !animElems.length) return; var viewTop = window.pageYOffset; var viewBottom = viewTop + window.innerHeight; var newAnimGroupsBlocks = t_animate__animateGroups(animGroupsBlocks, viewBottom, viewTop); var newAnimChainsBlocks = t_animate__animateChainsBlocks(animChainsBlocks, viewBottom, viewTop); var newAnimElems = t_animate__animateElems(animElems, viewBottom, viewTop); return [newAnimGroupsBlocks, newAnimChainsBlocks, newAnimElems]; } /** * Animate grouped blocks. Called inside t_animate__animateOnScroll * * @param {HTMLElement[]} animGroupsBlocks - list of animated group blocks * @param {number} viewBottom - bottom position of viewport */ function t_animate__animateGroups(animGroupsBlocks, viewBottom) { animGroupsBlocks.forEach(function (currentBlock) { if (currentBlock.curTopOffset < viewBottom) { var currentBlockEls = currentBlock.querySelectorAll('.t-animate'); currentBlockEls = Array.prototype.filter.call(currentBlockEls, function (el) { return !( el.classList.contains('t-animate__btn-wait-chain') || el.getAttribute('data-animate-chain') === 'yes' ); }); t_animate__makeSectionButtonWait(currentBlock); t_animate__saveSectionHeaderStartTime(currentBlock); Array.prototype.forEach.call(currentBlockEls, function (currentBlockEl) { currentBlockEl.classList.remove('t-animate_wait'); t_animate__removeNoHoverClassFromBtns(currentBlockEl); t_animate__startElementAnimation(currentBlockEl, false); }); } }); return animGroupsBlocks; } /** * Animate chain blocks * @param {HTMLElement[]} animChainsBlocks - list of animation chain blocks * @param {number} viewBottom - bottom position of viewport */ function t_animate__animateChainsBlocks(animChainsBlocks, viewBottom) { animChainsBlocks.forEach(function (curBlock) { if (curBlock.itemsOffsets[0] < viewBottom && curBlock.querySelectorAll('.t-animate_wait').length) { t_animate__animateChainItemsOnScroll(curBlock, viewBottom); if (curBlock.itemsOffsets.length) { t_animate__checkSectionButtonAnimation__outOfTurn(curBlock); } } }); return animChainsBlocks; } /** * Animate common elements. Called inside t_animate__animateOnScroll * * @param {HTMLElement[]} animElems - list of animated elements * @param {number} viewBottom - bottom position of viewport */ function t_animate__animateElems(animElems, viewBottom, viewTop) { Array.prototype.filter.call(animElems, function (el) { var curElemTrigger = t_animate__detectElemTriggerOffset(el, viewBottom); if (el.curTopOffset < curElemTrigger) { el.classList.remove('t-animate_wait'); t_animate__removeNoHoverClassFromBtns(el); t_animate__startElementAnimation(el, false); if (t_animate__getAttrByResBase(el, 'style') === 'animatednumber') { t_animate__animateNumbers(el); } return true; } if (el.curTopOffset < viewTop) { return false; } }); return animElems; } /** * Delete animated elements. Called inside t_animate__animateOnScroll * @param {HTMLElement[]} animGroupsBlocks - list of animation chain blocks * @param {HTMLElement[]} animElems - list of animation chain blocks * @returns */ function t_animate__deleteAnimatedEls(animGroupsBlocks, animElems) { var viewTop = window.pageYOffset; var newAnimGroupsBlocks = []; var newAnimElems = []; animGroupsBlocks.forEach(function (animGroupsBlock) { if (animGroupsBlock.curTopOffset <= viewTop) { var animateElList = animGroupsBlock.querySelectorAll('.t-animate'); Array.prototype.forEach.call(animateElList, function (animateEl) { t_animate__removeAnimationClass(animateEl, ['wait', 'no-hover']); }); } else { newAnimGroupsBlocks.push(animGroupsBlock); } }); animElems.forEach(function (animElem) { if (animElem.curTopOffset <= viewTop) { t_animate__removeAnimationClass(animElem, ['wait', 'no-hover']); t_animate__startElementAnimation(animElem, false); } else { newAnimElems.push(animElem); } }); return [newAnimElems, newAnimGroupsBlocks]; } /** * Animate chain blocks. (part of t_animate__animateChainsBlocks) * @param {HTMLElement & {itemsOffsets}} curBlock - current block * @param {number} viewBottom - bottom position of viewport */ function t_animate__animateChainItemsOnScroll(curBlock, viewBottom) { var waitingChainItems = curBlock.querySelectorAll('.t-animate_wait[data-animate-chain=yes]'); waitingChainItems = Array.prototype.slice.call(waitingChainItems); var itemOrder = 0; var rowOrder = 0; var rowOffset = curBlock.itemsOffsets[0]; var chainDelay = 0.16; var delayFromPrevScroll = t_animate__getDelayFromPreviousScrollEvent(curBlock, chainDelay); var sectionHeadDelay = t_animate__getSectionHeadDealy(curBlock); // we add class t-animate__chain_first-in-row to items, to let the new row be animated as soon, as the first element in // previous row is animated if (waitingChainItems.length) waitingChainItems[0].classList.add('t-animate__chain_first-in-row'); for (var s = 0; s < waitingChainItems.length; s++) { var item = waitingChainItems[s]; var itemTopOffset = curBlock.itemsOffsets[s]; if (itemTopOffset < viewBottom) { if (itemTopOffset !== rowOffset) { // if we check next row at the same scroll event item.classList.add('t-animate__chain_first-in-row'); rowOrder++; // itemOrder = rowOrder - next row animation starts earlier, right after first item in prevoius one itemOrder = rowOrder; rowOffset = itemTopOffset; } // start item animation, set delay var curItemDelay = itemOrder * chainDelay + delayFromPrevScroll + sectionHeadDelay; item.style.transitionDelay = curItemDelay + 's'; item.classList.remove('t-animate_wait'); t_animate__startElementAnimation(item, false); item.setAttribute('data-animate-start-time', Date.now() + curItemDelay * 1000); if (item[0] === waitingChainItems[waitingChainItems.length - 1]) { t_animate__checkSectionButtonAnimation(curBlock, curItemDelay); } if (+itemTopOffset === +rowOffset) { itemOrder++; } // remove animated cached chain items and offsets waitingChainItems.splice(s, 1); curBlock.itemsOffsets.splice(s, 1); s--; } else { break; } } t_animate__catchTransitionEndEvent(curBlock); } /** * Get section head delay. Used for chain blocks only * * @param {HTMLElement} curBlock - current element * @returns {number} - section head delay */ function t_animate__getSectionHeadDealy(curBlock) { var sectionTitle = curBlock.querySelector('.t-section__title.t-animate'); var sectionDescr = curBlock.querySelector('.t-section__descr.t-animate'); var sectionHeadDelay = 0; if (sectionTitle) { var titleStartTime = sectionTitle.getAttribute('data-animate-start-time') || 0; if (Date.now() - titleStartTime <= 160) { sectionHeadDelay = 0.16; return sectionHeadDelay; } } if (sectionDescr) { var descrStartTime = sectionDescr.getAttribute('data-animate-start-time') || 0; if (Date.now() - descrStartTime <= 160) { sectionHeadDelay = 0.16; return sectionHeadDelay; } } return sectionHeadDelay; } /** * In this function we count delay, if chain items from this block on previous scroll event didn't finish its transition * * @param {HTMLElement} curBlock - current element * @param {number} chainDelay - chain delay * @returns {number} - number of delay */ function t_animate__getDelayFromPreviousScrollEvent(curBlock, chainDelay) { var isFirstRow = !curBlock.querySelectorAll('.t-animate_started').length; var notAnimated = curBlock.querySelectorAll('.t-animate__chain_first-in-row.t-animate_started'); notAnimated = Array.prototype.filter.call(notAnimated, function (notAnim) { return !notAnim.classList.contains('t-animate__chain_showed'); }); // return, if it is the first element in chain or all the items are already animated if (isFirstRow || !notAnimated.length) { return 0; } if (notAnimated.length) { var lastNotAnimated = notAnimated[notAnimated.length - 1]; var lastNotAnimatedStart = lastNotAnimated.getAttribute('data-animate-start-time') || 0; var timeGap = lastNotAnimatedStart - Date.now(); if (timeGap <= 0) { return chainDelay; } else { return timeGap / 1000 + chainDelay; } } } /** * Start element animation * @param {HTMLElement} element - current element * @param {boolean} needUpdateParent - whether to update the parent element */ function t_animate__startElementAnimation(element, needUpdateParent) { t_animate__prepareTextAnimation(element); t_animate__setStartAnimationClass(element, needUpdateParent); } /** * Set start animation class to element * @param {HTMLElement} element - current element * @param {boolean} needUpdateParent - whether to update the parent element */ function t_animate__setStartAnimationClass(element, needUpdateParent) { if (!element) return; if (needUpdateParent) { var fixedAnimationParentClassName = 't-animate-for-wrapper'; var fixedAnimationParent = element.closest('.' + fixedAnimationParentClassName); if (fixedAnimationParent) fixedAnimationParent.classList.remove(fixedAnimationParentClassName); } element.classList.add('t-animate_started'); const isFadeInLeft = element.getAttribute('data-animate-style') === 'fadeinleft'; if (isFadeInLeft) { const parentElement = element.closest('.t-animate__overflow-x-hidden'); if ( parentElement && !parentElement.querySelector('[data-animate-style="fadeinleft"]:not(.t-animate_started)') ) { parentElement.classList.remove('t-animate__overflow-x-hidden'); } } } /** * Animate chain blocks on event (transitionend) * * @param {HTMLElement} curBlock - current element */ function t_animate__catchTransitionEndEvent(curBlock) { var animateChainList = curBlock.querySelectorAll('.t-animate__chain_first-in-row.t-animate_started'); animateChainList = Array.prototype.filter.call(animateChainList, function (animChain) { return !animChain.classList.contains('t-animate__chain_showed'); }); Array.prototype.forEach.call(animateChainList, function (animateChain) { var events = ['transitionend', 'webkitTransitionEnd', 'oTransitionEnd', 'otransitionend', 'MSTransitionEnd']; events.forEach(function (event) { animateChain.addEventListener(event, function () { t_animate__addEventOnAnimateChain(animateChain); }); animateChain.removeEventListener(event, function () { t_animate__addEventOnAnimateChain(animateChain); }); }); }); } /* ---------- functions, for animated number ---------- */ /** * parse number text * for the first time define a number and replace it with span with 0 in it * also duplicate styles from main element to span * */ function t_animate__parseNumberText() { var viewTop = window.pageYOffset; var animElemsNumber = document.querySelectorAll(".t-animate[data-animate-style='animatednumber']"); Array.prototype.forEach.call(animElemsNumber, function (curElem) { var text; var style = ''; var spanList = curElem.querySelectorAll('span'); Array.prototype.forEach.call(spanList, function (span) { style += span.getAttribute('style') || ''; span.removeAttribute('style'); span.removeAttribute('data-redactor-style'); }); if (curElem.querySelectorAll('div[data-customstyle="yes"]').length) { var customStyleYes = curElem.querySelector('div[data-customstyle="yes"]'); text = customStyleYes ? customStyleYes.innerHTML : ''; var newStyle = curElem.getAttribute('style') || ''; var customStyleEl = curElem.querySelector('div[data-customstyle]'); var customStyleElStyle = customStyleEl ? customStyleEl.getAttribute('style') : ''; if (customStyleElStyle) { newStyle += customStyleElStyle; } curElem.setAttribute('style', newStyle); } else { text = curElem.innerHTML; } // remove duplicate styles style = style .split(';') .filter(function (element, index) { return style.split(';').indexOf(element) === index; }) .join(';'); // don't parse elems, who is above viewport and won't be animated if (curElem.getBoundingClientRect().top + window.pageYOffset < viewTop - 500) { return; } if (text.length) { var number = text .replace(/
/g, ' ') .replace(/[^\d., ]+/g, '') .replace(/ (\.|,)/g, '') .replace(/(\d)(?=\d) /g, '$1') .trim(); var removeNumberSpace = number; if (text.indexOf(number) === -1) { number = number.split(' ')[0]; // >2000+ м3 removeNumberSpace = number; } if (number !== '') { curElem.setAttribute('data-animate-number-count', text); t_animate__changeNumberOnZero(curElem, text.replace(removeNumberSpace, 'num')); var notAnimatedNumbers = curElem.querySelectorAll('span'); notAnimatedNumbers = Array.prototype.filter.call(notAnimatedNumbers, function (notAnimNumber) { return !notAnimNumber.classList.contains('.t-animate__number'); }); Array.prototype.forEach.call(notAnimatedNumbers, function (notAnimatedNumber) { notAnimatedNumber.setAttribute('style', style); }); } } }); } /** * Append to element span.t-animate__number * * @param {HTMLElement} el - current element * @param {string} removeNumberSpace - remove number space */ function t_animate__changeNumberOnZero(el, removeNumberSpace) { el.innerHTML = removeNumberSpace.replace(/num/g, '' + 0 + ''); } /** * Main function to animate numbers * * @param {HTMLElement} curElem - current element * @returns {false} - if current element is not defined */ function t_animate__animateNumbers(curElem) { if (!curElem) return false; var text = curElem.getAttribute('data-animate-number-count'); var style = []; var notAnimatedNumbers = curElem.querySelectorAll('span'); notAnimatedNumbers = Array.prototype.filter.call(notAnimatedNumbers, function (notAnimNumber) { return !notAnimNumber.classList.contains('.t-animate__number'); }); if (notAnimatedNumbers.length) { style = notAnimatedNumbers[0].getAttribute('style') || ''; } var number = []; var numberDotOrComma = null; if (text) { numberDotOrComma = text.match(/\d+\.\d+|\d+,\d+/g); var numberWithSpace = text.match(/\d+/g); var removeNumberSpace = text.replace(/(\d)(?= \d) /g, '$1'); var numberWithoutLetter = removeNumberSpace.split(' '); numberWithoutLetter.forEach(function (item) { if (!isNaN(parseInt(item.replace(/[^\d., ]+/g, ''), 10))) { number.push(item.replace(/[^\d., ]+/g, '')); } }); } var decimalLength = 0; var isFloat = false; var isComma = false; curElem.removeAttribute('data-animate-number-count'); if (numberDotOrComma !== null) { isComma = numberDotOrComma[0].indexOf(',') !== -1; } number.forEach(function (item, i) { if (numberDotOrComma !== null) { var itemSplitArr; if (item.indexOf(',') !== -1) { itemSplitArr = item.split(','); } if (item.indexOf('.') !== -1) { itemSplitArr = item.split('.'); } if (item.indexOf(',') !== -1 || item.indexOf('.') !== -1) { decimalLength = itemSplitArr[1].length; number[i] = +itemSplitArr.join('.'); isFloat = true; } } }); var animatedNumber = curElem.querySelector('.t-animate__number'); if (number[0]) { var maxNum = Number(number[0]) || 0; var startNum = 0; var round = Math.pow(10, decimalLength); if (isFloat) { maxNum *= round; startNum *= round; } // value in ms of one iteration which increasing the startNum var timer = 12; var animationStep = 0; var interval = setInterval(function () { // 9 - to create round value without zero as last number in value [from 1000 to 1111] startNum += maxNum / (timer * 9); if (isFloat) { animationStep = (Math.round(startNum) / round).toFixed(decimalLength) + ''; } else { animationStep = Math.floor(startNum) + ''; } if (numberWithSpace.length > 1) { animationStep = animationStep.replace(/(\d)(?=(\d{3})+([^\d]|$))/g, '$1 '); } if (isComma) { animationStep = animationStep.replace(/\./g, ','); } if (animatedNumber) animatedNumber.textContent = animationStep; if (startNum >= maxNum) { clearInterval(interval); curElem.innerHTML = text; var curElSpan = curElem.querySelectorAll('span'); Array.prototype.forEach.call(curElSpan, function (span) { span.setAttribute('style', style); }); } }, timer); } } /* ---------- functions, which set animation state after DOMContentLoaded ---------- */ /** * Set animation state * * @param {HTMLElement[]} animGroupsBlocks - animated group block list * @param {HTMLElement[]} animChainsBlocks - animated chain block list * @param {HTMLElement[]} animElems - animated elements list */ function t_animate__setAnimationState(animGroupsBlocks, animChainsBlocks, animElems) { var viewTop = window.pageYOffset; var viewBottom = viewTop + window.innerHeight; t_animate__setGroupsBlocksState(animGroupsBlocks, viewTop, viewBottom); animChainsBlocks.forEach(function (curBlock) { t_animate__assignChainDelay(curBlock, viewBottom, viewTop); t_animate__checkSectionButtonAnimation__outOfTurn(curBlock); }); t_animate__setAnimELemsState(animElems, viewTop, viewBottom); window.addEventListener('resize', t_throttle(t_animate__removeInlineAnimStyles)); } /** * Set state for animElems group * @param {HTMLElement[]} animElems - animated elements list * @param {number} viewTop * @param {number} viewBottom */ function t_animate__setAnimELemsState(animElems, viewTop, viewBottom) { animElems.forEach(function (curElem) { var curElemOffsetTop = curElem.getBoundingClientRect().top + window.pageYOffset; if (curElemOffsetTop < viewTop - 500) { t_animate__removeAnimationClass(curElem, 'no-hover'); // fix for numbers with anchor link if (t_animate__getAttrByResBase(curElem, 'style') === 'animatednumber') { t_animate__animateNumbers(curElem); } return true; } var curElemTrigger = t_animate__detectElemTriggerOffset(curElem, viewBottom); t_animate__setCustomAnimSettings(curElem, curElemOffsetTop, viewBottom); if (curElemOffsetTop < curElemTrigger && !curElem.closest('.t1093')) { t_animate__removeNoHoverClassFromBtns(curElem); t_animate__startElementAnimation(curElem, true); if (t_animate__getAttrByResBase(curElem, 'style') === 'animatednumber') { t_animate__animateNumbers(curElem); } } if (curElemOffsetTop >= curElemTrigger || curElem.closest('.t1093')) { curElem.classList.add('t-animate_wait'); } }); } /** * Set state for animGroupsBlocks group * @param {HTMLElement[]} animGroupsBlocks - animated group elements list * @param {number} viewTop * @param {number} viewBottom */ function t_animate__setGroupsBlocksState(animGroupsBlocks, viewTop, viewBottom) { animGroupsBlocks.forEach(function (curBlock) { var curBlockAnimElems = curBlock.querySelectorAll('.t-animate'); curBlockAnimElems = Array.prototype.filter.call(curBlockAnimElems, function (animEl) { return !(animEl.getAttribute('data-animate-chain') === 'yes'); }); var curBlockOffset = curBlock.getBoundingClientRect().top + window.pageYOffset; t_animate__removeAnimFromHiddenSlides(curBlock); var sectionHeadDelay = t_animate__assignSectionDelay(curBlock); t_animate__assignGroupDelay(curBlock, sectionHeadDelay); Array.prototype.forEach.call(curBlockAnimElems, function (el) { var parentIsHidden = el.closest('.t397__off') || el.closest('.t395__off') || el.closest('.t400__off'); if (el.classList.contains('t-animate_no-hover') && parentIsHidden) { el.classList.remove('t-animate_no-hover'); } if (curBlockOffset <= viewTop - 100) { t_animate__saveSectionHeaderStartTime(curBlock); t_animate__removeAnimationClass(el, 'no-hover'); el.style.transitionDelay = ''; return true; } if (curBlockOffset < viewBottom && curBlockOffset > viewTop - 100) { // if button is part of section with chain animation, it should wait till the end of chain animation t_animate__makeSectionButtonWait(curBlock); if (!el.classList.contains('.t-animate__btn-wait-chain')) { t_animate__removeNoHoverClassFromBtns(el); if (parentIsHidden) { el.classList.add('t-animate_wait'); } else { t_animate__startElementAnimation(el, false); } } } if (curBlockOffset >= viewBottom) { el.classList.add('t-animate_wait'); } }); }); } /** * Set animation state for animChainsBlocks group * * @param {HTMLElement[] | NodeList} animChainsBlocks - animated chain blocks */ function t_animate__setAnimationStateChains(animChainsBlocks) { if (!animChainsBlocks || !animChainsBlocks.length) return false; var viewTop = window.pageYOffset; var viewBottom = viewTop + window.innerHeight; Array.prototype.forEach.call(animChainsBlocks, function (curBlock) { t_animate__assignChainDelay(curBlock, viewBottom, viewTop); t_animate__checkSectionButtonAnimation__outOfTurn(curBlock); }); } /** * Return section head delay. Used for animGroupsBlocks * * @param {HTMLElement} curBlock - current element * @returns {number} - section head delay */ function t_animate__assignSectionDelay(curBlock) { var sectionHeadDelay = 0; var sectionTitle = curBlock.querySelectorAll('.t-section__title.t-animate'); var sectionDescr = curBlock.querySelectorAll('.t-section__descr.t-animate'); if (sectionTitle.length) { sectionHeadDelay = 0.16; } if (sectionDescr.length) { Array.prototype.forEach.call(sectionDescr, function (descr) { descr.style.transitionDelay = sectionHeadDelay + 's'; }); sectionHeadDelay += 0.16; } return sectionHeadDelay; } /** * Add style transition-delay for current element. * Depends on which elements are in current block * @param {HTMLElement} curBlock - current block * @param {number} sectionHeadDelay - delay */ function t_animate__assignGroupDelay(curBlock, sectionHeadDelay) { var animDelay = 0; if (curBlock.querySelectorAll('[data-animate-order]').length) { t_animate__assignOrderedElemsDelay(curBlock, sectionHeadDelay); } else { var elemImg = curBlock.querySelectorAll('.t-img.t-animate'); var elemSubtitle = curBlock.querySelectorAll('.t-uptitle.t-animate'); var elemTitle = curBlock.querySelectorAll('.t-title.t-animate'); elemTitle = Array.prototype.filter.call(elemTitle, function (title) { return !title.classList.contains('t-section__title'); }); var elemDescr = curBlock.querySelectorAll('.t-descr.t-animate'); elemDescr = Array.prototype.filter.call(elemDescr, function (descr) { return !descr.classList.contains('t-section__descr'); }); var elemBtn = curBlock.querySelectorAll('.t-btn.t-animate, .t-btnwrapper.t-animate'); elemBtn = Array.prototype.filter.call(elemBtn, function (descr) { return !descr.closest('.t-section__bottomwrapper'); }); var elemTimer = curBlock.querySelectorAll('.t-timer.t-animate'); var elemForm = curBlock.querySelectorAll('form.t-animate'); if (elemImg.length) { animDelay = 0.5; } if (elemSubtitle.length) { Array.prototype.forEach.call(elemSubtitle, function (subTitle) { subTitle.style.transitionDelay = animDelay + 's'; }); } if (elemSubtitle.length) { animDelay = animDelay + 0.3; } if (elemTitle.length) { Array.prototype.forEach.call(elemTitle, function (title) { title.style.transitionDelay = animDelay + 's'; }); } if (elemTitle.length) { animDelay = animDelay + 0.3; } if (elemDescr.length) { Array.prototype.forEach.call(elemDescr, function (descr) { descr.style.transitionDelay = animDelay + 's'; }); } if (elemDescr.length) { animDelay = animDelay + 0.3; } if (elemSubtitle.length || elemTitle.length || elemDescr.length) { animDelay = animDelay + 0.2; } if (elemTimer.length) { Array.prototype.forEach.call(elemTimer, function (timer) { timer.style.transitionDelay = animDelay + 's'; }); } if (elemTimer.length) { animDelay = animDelay + 0.5; } if (elemBtn.length) { elemBtn[0].style.transitionDelay = animDelay + 's'; } if (elemBtn.length === 2) { animDelay = animDelay + 0.4; } if (elemBtn.length === 2) { elemBtn[1].style.transitionDelay = animDelay + 's'; } if (elemForm.length !== 0) { Array.prototype.forEach.call(elemForm, function (form) { form.style.transitionDelay = animDelay + 's'; }); } } } /** * Add style transition-delay for animated el with [data-animate-order] * * @param {HTMLElement} curBlock - currentl element * @param {number} sectionHeadDelay - delay */ function t_animate__assignOrderedElemsDelay(curBlock, sectionHeadDelay) { var animDelay = 0; if (sectionHeadDelay) { animDelay = sectionHeadDelay; } var elem1 = curBlock.querySelectorAll('.t-animate[data-animate-order="1"]'); var elem2 = curBlock.querySelectorAll('.t-animate[data-animate-order="2"]'); var elem3 = curBlock.querySelectorAll('.t-animate[data-animate-order="3"]'); var elem4 = curBlock.querySelectorAll('.t-animate[data-animate-order="4"]'); var elem5 = curBlock.querySelectorAll('.t-animate[data-animate-order="5"]'); var elem6 = curBlock.querySelectorAll('.t-animate[data-animate-order="6"]'); var elem7 = curBlock.querySelectorAll('.t-animate[data-animate-order="7"]'); var elem8 = curBlock.querySelectorAll('.t-animate[data-animate-order="8"]'); var elem9 = curBlock.querySelectorAll('.t-animate[data-animate-order="9"]'); if (elem1.length) { Array.prototype.forEach.call(elem1, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if (elem1.length && elem2.length) { animDelay = animDelay + t_animate__getAttrByResBase(elem2[0], 'delay') * 1; Array.prototype.forEach.call(elem2, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if ((elem1.length || elem2.length) && elem3.length) { animDelay = animDelay + t_animate__getAttrByResBase(elem3[0], 'delay') * 1; Array.prototype.forEach.call(elem3, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if ((elem1.length || elem2.length || elem3.length) && elem4.length) { animDelay = animDelay + t_animate__getAttrByResBase(elem4[0], 'delay') * 1; Array.prototype.forEach.call(elem4, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if ((elem1.length || elem2.length || elem3.length || elem4.length) && elem5.length) { animDelay = animDelay + t_animate__getAttrByResBase(elem5[0], 'delay') * 1; Array.prototype.forEach.call(elem5, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if ((elem1.length || elem2.length || elem3.length || elem4.length || elem5.length) && elem6.length) { animDelay = animDelay + t_animate__getAttrByResBase(elem6[0], 'delay') * 1; Array.prototype.forEach.call(elem6, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if ( (elem1.length || elem2.length || elem3.length || elem4.length || elem5.length || elem6.length) && elem7.length ) { animDelay = animDelay + t_animate__getAttrByResBase(elem7[0], 'delay') * 1; Array.prototype.forEach.call(elem7, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if ( (elem1.length || elem2.length || elem3.length || elem4.length || elem5.length || elem6.length || elem7.length) && elem8.length ) { animDelay = animDelay + t_animate__getAttrByResBase(elem8[0], 'delay') * 1; Array.prototype.forEach.call(elem8, function (el) { el.style.transitionDelay = animDelay + 's'; }); } if ( (elem1.length || elem2.length || elem3.length || elem4.length || elem5.length || elem6.length || elem7.length || elem8.length) && elem9.length ) { animDelay = animDelay + t_animate__getAttrByResBase(elem9[0], 'delay') * 1; Array.prototype.forEach.call(elem9, function (el) { el.style.transitionDelay = animDelay + 's'; }); } } /** * Set the delay for chain animation * @param {HTMLElement} curBlock - current block * @param {number} viewBottom - bottom position of viewport * @param {number} viewTop - current element offset top */ function t_animate__assignChainDelay(curBlock, viewBottom, viewTop) { var chain = curBlock.querySelectorAll('.t-animate[data-animate-chain=yes]'); var itemOrder = 0; if (chain.length) { var chainEl = chain[0]; var rowOffset = chainEl.getBoundingClientRect().top + window.pageYOffset; chainEl.classList.add('t-animate__chain_first-in-row'); var sectionHeadDelay = t_animate__getCurBlockSectionHeadDelay(curBlock); Array.prototype.forEach.call(chain, function (curItem) { var curItemOffset = curItem.getBoundingClientRect().top + window.pageYOffset; if (curItemOffset < viewTop) { t_animate__removeAnimationClass(curItem, ''); return true; } if (curItemOffset < viewBottom) { if (curItemOffset !== rowOffset) { curItem.classList.add('t-animate__chain_first-in-row'); rowOffset = curItemOffset; } var curItemDelay = itemOrder * 0.16 + sectionHeadDelay; curItem.style.transitionDelay = curItemDelay + 's'; t_animate__startElementAnimation(curItem, false); curItem.setAttribute('data-animate-start-time', Date.now() + curItemDelay * 1000); if (chainEl === chain[chain.length - 1]) { t_animate__checkSectionButtonAnimation(curBlock, curItemDelay); } itemOrder++; var events = [ 'transitionend', 'webkitTransitionEnd', 'oTransitionEnd', 'otransitionend', 'MSTransitionEnd', ]; events.forEach(function (event) { curItem.addEventListener(event, function () { t_animate__addEventOnAnimateChain(curItem); }); curItem.removeEventListener(event, function () { t_animate__addEventOnAnimateChain(curItem); }); }); } else { curItem.classList.add('t-animate_wait'); } }); } } /* ---------- some helper functions ---------- */ /** * Get element, check if its parent is zeroBlock * and return animated attribute depends on * the clients device resolution * * @param {HTMLElement} el - animated el * @param {string} prop - animate param * @returns {string | null} - if element has animated param from second arg in data-attr, return string, else - null */ function t_animate__getAttrByResBase(el, prop) { var dataField; var artBoard = el.closest('.t396__artboard'); if (!artBoard) { return el.getAttribute('data-animate-' + prop); } var recid = artBoard.getAttribute('data-artboard-recid'); var artBoardId = 'ab' + recid; var curRes; var curResMax; var breakpoints; if (typeof window.tn[artBoardId] !== 'undefined') { curRes = window.tn[artBoardId].curResolution; curResMax = window.tn[artBoardId].curResolution_max; breakpoints = window.tn[artBoardId].screens.slice(); } else { curRes = window.tn.curResolution; curResMax = 1200; breakpoints = [320, 480, 640, 960, 1200]; } var elemParent = el.closest('.t396__elem, .t396__group'); var animateMob = elemParent && elemParent.getAttribute('data-animate-mobile'); if (curRes === curResMax) { dataField = el.getAttribute('data-animate-' + prop); } else if (animateMob !== 'y' && curRes < 1200) { el.style.transition = 'none'; return null; } else { dataField = el.getAttribute('data-animate-' + prop + '-res-' + curRes); } if (!dataField && dataField !== '') { for (var i = 0; i < breakpoints.length; i++) { var breakpoint = breakpoints[i]; if (breakpoint <= curRes) continue; if (breakpoint === curResMax) { dataField = el.getAttribute('data-animate-' + prop); } else { dataField = el.getAttribute('data-animate-' + prop + '-res-' + breakpoint); } if (dataField) break; } } return dataField; } /** * Filter Array of HTMLElements, if the element or its children contains .t-animate_wait * * @param {HTMLElement[]} elementsArray - list of elements * @returns {HTMLElement[]} - filtered Array */ function t_animate__hasWaitAnimation(elementsArray) { return elementsArray.filter(function (el) { return el.classList.contains('t-animate_wait') || el.querySelector('.t-animate_wait'); }); } /** * Add event on transitionend * * @param {HTMLElement} el - current element */ function t_animate__addEventOnAnimateChain(el) { el.classList.add('t-animate__chain_showed'); } /** * Add custom anim style for animElems group * @param {HTMLElement} curElem - current element * @param {number} curElemOffsetTop - current element offset top * @param {number} viewBottom - bottom position */ function t_animate__setCustomAnimSettings(curElem, curElemOffsetTop, viewBottom) { //check element custom distance var curElemStyle = t_animate__getAttrByResBase(curElem, 'style'); var curElemDistance = t_animate__getAttrByResBase(curElem, 'distance'); if (curElemDistance && curElemDistance !== '') { curElemDistance = curElemDistance.replace('px', ''); // to add new position fast, without transition duration, we need set it to 0s curElem.style.transitionDuration = '0s'; curElem.style.transitionDelay = '0s'; switch (curElemStyle) { case 'fadeinup': curElem.style.transform = 'translate3d(0,' + curElemDistance + 'px,0)'; break; case 'fadeindown': curElem.style.transform = 'translate3d(0,-' + curElemDistance + 'px,0)'; break; case 'fadeinleft': curElem.style.transform = 'translate3d(' + curElemDistance + 'px,0,0)'; break; case 'fadeinright': curElem.style.transform = 'translate3d(-' + curElemDistance + 'px,0,0)'; break; default: break; } t_animate__forceElemInViewPortRepaint(curElem, curElemOffsetTop, viewBottom); // remove 0s transition duration curElem.style.transitionDuration = ''; curElem.style.transitionDelay = ''; } // check element custom scale var curElemScale = t_animate__getAttrByResBase(curElem, 'scale'); if (curElemScale) { //to add new position fast, without transition duration, we need set it to 0s curElem.style.transitionDuration = '0s'; curElem.style.transitionDelay = '0s'; curElem.style.transform = 'scale(' + curElemScale + ')'; t_animate__forceElemInViewPortRepaint(curElem, curElemOffsetTop, viewBottom); // remove 0s transition duration curElem.style.transitionDuration = ''; curElem.style.transitionDelay = ''; } // detect element delay var curElemDelay = t_animate__getAttrByResBase(curElem, 'delay'); if (curElemDelay) { curElem.style.transitionDelay = curElemDelay + 's'; } // detect element transirtion duration var curElemDuration = t_animate__getAttrByResBase(curElem, 'duration'); if (curElemDuration) { curElem.style.transitionDuration = curElemDuration + 's'; } } /** * Remove inline animated styles for ZB elements in screen < 980px */ function t_animate__removeInlineAnimStyles() { if (window.innerWidth < 980) { var animatedElements = document.querySelectorAll('.t396__elem.t-animate:not(.t-animate_wait)'); Array.prototype.forEach.call(animatedElements, function (animatedElement) { animatedElement.style.transform = ''; animatedElement.style.transitionDuration = ''; animatedElement.style.transitionDelay = ''; }); } } /** * Force repaint element * * @param {HTMLElement} curElem - current element * @param {number} curElemOffsetTop - number of offset * @param {number} viewBottom - number of offset */ function t_animate__forceElemInViewPortRepaint(curElem, curElemOffsetTop, viewBottom) { if (curElem && curElemOffsetTop < viewBottom + 500) { curElem.offsetHeight; } } /** * Calculate trigger offset for animElems group * @param {HTMLElement} curElem - current element * @param {number} viewBottom - bottom position of viewport * @returns {number} - curElemTrigger - difference between viewBottom and current el offset top */ function t_animate__detectElemTriggerOffset(curElem, viewBottom) { var curElemTriggerOffset = t_animate__getAttrByResBase(curElem, 'trigger-offset'); var curElemTrigger = viewBottom; if (curElemTriggerOffset) { curElemTriggerOffset = curElemTriggerOffset.replace('px', ''); curElemTrigger = viewBottom - curElemTriggerOffset * 1; } return curElemTrigger; } /** * Set attributes for title and description to save * animation start time (to set right delay for chain items) * * @param {HTMLElement} curBlock - current block */ function t_animate__saveSectionHeaderStartTime(curBlock) { var sectionTitle = curBlock.querySelectorAll('.t-section__title.t-animate'); var sectionDescr = curBlock.querySelectorAll('.t-section__descr.t-animate'); if (sectionTitle.length) { Array.prototype.forEach.call(sectionTitle, function (title) { title.setAttribute('data-animate-start-time', Date.now()); }); } if (sectionDescr.length) { Array.prototype.forEach.call(sectionDescr, function (descr) { descr.setAttribute('data-animate-start-time', Date.now() + 160); }); } } /** * Add section head delay if current block has animated title or descr * * @param {HTMLElement} curBlock - current block * @returns {number} - of sectionHeadDelay */ function t_animate__getCurBlockSectionHeadDelay(curBlock) { var sectionHeadDelay = 0; if (curBlock.querySelectorAll('.t-section__title.t-animate').length) { sectionHeadDelay += 0.16; } if (curBlock.querySelectorAll('.t-section__descr.t-animate').length) { sectionHeadDelay += 0.16; } return sectionHeadDelay; } /** * Add wait class to btn if it is a part of chain animation * @param {HTMLElement} curBlock - block contains [data-animate-chain=yes] */ function t_animate__makeSectionButtonWait(curBlock) { var chainLength = curBlock.querySelectorAll('.t-animate[data-animate-chain=yes]').length; var sectionBtn = curBlock.querySelectorAll('.t-section__bottomwrapper .t-btn.t-animate'); if (chainLength.length && sectionBtn.length) { Array.prototype.forEach.call(sectionBtn, function (btn) { btn.classList.add('t-animate__btn-wait-chain'); }); } } /** * Add animation to btn if it has t-animate__btn-wait-chain * * @param {HTMLElement} curBlock - block contains animated btn * @param {number} curItemDelay - current delay */ function t_animate__checkSectionButtonAnimation(curBlock, curItemDelay) { var chainBtn = curBlock.querySelectorAll('.t-animate__btn-wait-chain'); if (chainBtn.length) { Array.prototype.forEach.call(chainBtn, function (btn) { btn.style.transitionDelay = curItemDelay + 0.16 + 's'; t_animate__removeNoHoverClassFromBtns(btn); btn.classList.remove('t-animate__btn-wait-chain'); t_animate__startElementAnimation(btn, false); }); } } /** * Add chainDelay if current block not contains chain items * * @param {HTMLElement} curBlock - current block */ function t_animate__checkSectionButtonAnimation__outOfTurn(curBlock) { var waitingChainItems = curBlock.querySelectorAll('.t-animate[data-animate-chain=yes]'); waitingChainItems = Array.prototype.filter.call(waitingChainItems, function (chain) { return !chain.classList.contains('t-animate_started'); }); if (!waitingChainItems.length) { var chainDelay = 0.16; t_animate__checkSectionButtonAnimation(curBlock, chainDelay); } } /** * Add no-hover class to btn */ function t_animate__addNoHoverClassToBtns() { var animatedBtns = document.querySelectorAll('.t-btn.t-animate'); Array.prototype.forEach.call(animatedBtns, function (btn) { btn.classList.add('t-animate_no-hover'); }); } /** * Add event to .t-btn on transitionend after which remove transition-delay&transition-duration and t-animate_no-hover class * * @param {HTMLElement} curBlockAnimElem - current el * @returns {false} - if current el is not defined */ function t_animate__removeNoHoverClassFromBtns(curBlockAnimElem) { if (!curBlockAnimElem) return false; var currentBtn = curBlockAnimElem.classList.contains('t-btn') ? curBlockAnimElem : null; if (currentBtn) { currentBtn.ontransitionend = function (e) { if (e.propertyName === 'opacity' || e.propertyName === 'transform') { currentBtn.classList.remove('t-animate_no-hover'); currentBtn.style.transitionDelay = ''; currentBtn.style.transitionDuration = ''; this.ontransitionend = null; } }; } } /** * For group animation add equal offset (curTopOffset) * * @param {HTMLElement[]} animGroupsBlocks - animated group block list */ function t_animate__getGroupsOffsets(animGroupsBlocks) { animGroupsBlocks.forEach(function (animGroupsBlock) { var animatedChild = animGroupsBlock.querySelector('.t-animate'); if (animatedChild) { animGroupsBlock.curTopOffset = animatedChild.getBoundingClientRect().top + window.pageYOffset; var zoom = t_animation__getZoom(animGroupsBlock); if (!window.isOnlyScalable) animGroupsBlock.curTopOffset *= zoom; } }); } function t_animation__getZoom(el) { if (typeof el.scaleFactor !== 'undefined') return el.scaleFactor; var artboard = el.closest('.t396__artboard'); if (!artboard) return 1; var isOldPage = document.querySelector('script[src*="tilda-blocks-2.7"]'); if ( artboard.classList.contains('t396__artboard_scale') || (!isOldPage && typeof t396_ab__getFieldValue !== 'undefined' && t396_ab__getFieldValue(artboard, 'upscale') === 'window') ) { return window.tn_scale_factor; } return 1; } /** * Add itemsOffsets param to animated elements * * @param {HTMLElement[]} animChainsBlocks animated chain block list */ function t_animate__getChainOffsets(animChainsBlocks) { animChainsBlocks.forEach(function (animChainsBlock) { var currentChain = animChainsBlock.querySelectorAll('.t-animate_wait[data-animate-chain=yes]'); animChainsBlock.itemsOffsets = []; Array.prototype.forEach.call(currentChain, function (curChain, index) { animChainsBlock.itemsOffsets[index] = curChain.getBoundingClientRect().top + window.pageYOffset; }); }); } /** * Add curTopOffset param to animated elements * * @param {HTMLElement[]} animElems - animated elements */ function t_animate__getElemsOffsets(animElems) { animElems.forEach(function (animElem) { animElem.curTopOffset = window.pageYOffset + animElem.getBoundingClientRect().top; var zoom = t_animation__getZoom(animElem); if (!window.isOnlyScalable) animElem.curTopOffset *= zoom; }); } /** * Remove animation from hidden blocks * * @param {HTMLElement} curBlock - current block */ function t_animate__removeAnimFromHiddenSlides(curBlock) { var slides = curBlock.querySelectorAll('.t-slides'); if (slides.length) { var slidesItems = curBlock.querySelectorAll('.t-slides__item'); slidesItems = Array.prototype.filter.call(slidesItems, function (slide) { return !slide.classList.contains('t-slides__item_active'); }); var hiddenSlides = []; slidesItems.forEach(function (slide) { var animateEl = slide.querySelector('.t-animate'); if (animateEl) hiddenSlides.push(animateEl); }); hiddenSlides.forEach(function (hiddenSlide) { t_animate__removeAnimationClass(hiddenSlide, 'no-hover'); }); } } /** * Move custom opacity from text element to wrapped
*/ function t_animate__wrapTextWithOpacity() { var textElements = document.querySelectorAll( '.t-title.t-animate, .t-descr.t-animate, .t-uptitle.t-animate, .t-text.t-animate' ); Array.prototype.forEach.call(textElements, function (el) { var style = el.getAttribute('style'); if (style && style.indexOf('opacity') !== -1) { var opacity = el.style.opacity; if (opacity && opacity > 0) { el.style.opacity = ''; var div = document.createElement('div'); div.style.opacity = opacity; var children = el.childNodes; Array.prototype.forEach.call(children, function (child) { var clonedChild = child.cloneNode(true); div.appendChild(clonedChild); }); el.innerHTML = ''; el.appendChild(div); } } }); } /** * Wrap words with a span for all text animations * @param {string|null} scopeSelector - optional selector of container, if set, only elements inside it are wrapped */ function t_animate__wrapTextAnimationsWords(scopeSelector = null) { t_animate__wrapAnimatedTextWords(scopeSelector); t_animate__wrapAnimatedTextWordsWithMasks(scopeSelector); } /** * Prepare text animation: * - wrap words with a line span when needed * - add delay to text animation particles * @param {HTMLElement} element - specific element to prepare */ function t_animate__prepareTextAnimation(element) { const isAnimatedElement = element?.classList.contains('t-animate') ?? false; const isAnimationStarted = element?.classList.contains('t-animate_started') ?? false; if (!isAnimatedElement || isAnimationStarted) { return; } t_animate__wrapAnimatedTextLines(element); const duration = t_animate__setTextAnimationVariables(element); t_animate__prepareWordByWordAnimationToRight(element); t_animate__prepareWordByWordAnimationToLeft(element); t_animate__prepareLinesFadeInAnimation(element); t_animate__prepareLinesFadeInWrappedAnimation(element); t_animate__prepareLetterByLetterAnimation(element, duration); } /** * Set CSS variables of ZeroBlock text animation duration and distance from data-animate-duration and data-animate-distance. * Distance is applied only to word animations without masks and gradients. * @param {HTMLElement} element - specific element to prepare * @returns {number|null} - duration in seconds, if it is set */ function t_animate__setTextAnimationVariables(element) { if (!element.closest('.t396')) { return null; } const textAnimationStyles = [ 'word-fade-in-right', 'word-fade-in-left', 'word-fade-in-down', 'word-fade-in-up', 'word-fade-in-up-masked', 'line-fade-in-up-masked', 'line-fade-in-right-gradient', 'line-fade-in-left-gradient', 'letter-bounce-in-up', ]; const distanceAnimationStyles = ['word-fade-in-right', 'word-fade-in-left', 'word-fade-in-down', 'word-fade-in-up']; const elementAnimationStyle = element.getAttribute('data-animate-style'); if (!textAnimationStyles.includes(elementAnimationStyle)) { return null; } const parsedDuration = parseFloat(t_animate__getAttrByResBase(element, 'duration')); const duration = !isNaN(parsedDuration) && parsedDuration >= 0 ? parsedDuration : null; const distance = parseFloat(t_animate__getAttrByResBase(element, 'distance')); const isDistanceAllowed = distanceAnimationStyles.includes(elementAnimationStyle); if (duration !== null) { element.style.setProperty('--t-animate-text-duration', `${duration}s`); } if (isDistanceAllowed && !isNaN(distance)) { element.style.setProperty('--t-animate-text-distance', `${distance}px`); } return duration; } /** * Check whether text animation particle is whitespace between words * @param {HTMLElement} particle - word, letter or whitespace element * @returns {boolean} */ function t_animate__isWhitespaceParticle(particle) { return particle.classList.contains('t-animate__word_whitespace'); } /** * Set animation delay to text animation particle. * Whitespace gets additional delay, so it appears after the next word or letter has started. * @param {HTMLElement} particle - word, letter or whitespace element * @param {number} delay - delay in seconds */ function t_animate__setTextParticleDelay(particle, delay) { const whitespaceAdditionalDelay = 0.2; const particleDelay = t_animate__isWhitespaceParticle(particle) ? delay + whitespaceAdditionalDelay : delay; particle.style.animationDelay = `${particleDelay}s`; } /** * Get animated text elements by animation styles or specific element. * @param {string[]} animationStyles - array of animation styles to filter elements * @param {HTMLElement|null} element - optional specific element to get, if null, gets all document elements with the specified animation styles * @returns {HTMLElement[]} - array of animated text elements */ function t_animate__getAnimatedTextElements(animationStyles, element = null) { if (!element) { const elements = document.querySelectorAll( animationStyles.map(style => `.t-animate[data-animate-style="${style}"]`).join(', ') ); return Array.from(elements); } const elementAnimationStyle = element.getAttribute('data-animate-style'); const isStyleAppropriate = animationStyles.includes(elementAnimationStyle); return isStyleAppropriate ? [element] : []; } /** * Prepare word by word animation to the right. * Add animation delay for each word by increment * @param {HTMLElement|null} element - optional specific element to prepare, if null, prepares all elements with the specified animation styles */ function t_animate__prepareWordByWordAnimationToRight(element = null) { const wordDelayIncrement = 0.06; const animatedTextElements = t_animate__getAnimatedTextElements( ['word-fade-in-right', 'word-fade-in-up', 'word-fade-in-up-masked', 'word-fade-in-down'], element ); animatedTextElements.forEach(animatedTextElement => { const wordElements = animatedTextElement.querySelectorAll('.t-animate__word'); const baseDelay = t_animate__getElementBaseDelay(animatedTextElement); let wordIndex = 0; wordElements.forEach(wordElement => { t_animate__setTextParticleDelay(wordElement, baseDelay + wordIndex * wordDelayIncrement); if (!t_animate__isWhitespaceParticle(wordElement)) { wordIndex++; } }); }); } /** * Get the root element and tree path of inline parents for a given text node. * @param {Node} node - text node to process * @param {Node[]} path - array of inline parent nodes leading to the root * @returns {{ root: Node, path: Node[] }} - root element and path of inline parents */ function t_animate__getTreePath(node, path = []) { const parent = node.parentElement; if (!parent || parent === node) { return { root: node, path, }; } const parentStyles = window.getComputedStyle(parent); const isParentInline = parentStyles.display.includes('inline'); return isParentInline ? t_animate__getTreePath(parent, [parent, ...path]) : { root: parent, path, }; } /** * Get lines of words from element. * @param {HTMLElement} element - element to get lines from * @returns {HTMLElement[][]} - array of lines, each line is an array of word elements */ function t_animate__getElementLines(element) { const wordElements = element.querySelectorAll('.t-animate__word'); const lines = Array.from(wordElements) .reduce((acc, wordElement) => { const { root } = t_animate__getTreePath(wordElement); const wordTop = Math.round(wordElement.offsetTop + (wordElement.offsetParent?.offsetTop ?? 0)); const currentLine = acc.at(-1); const isWhitespace = wordElement.classList.contains('t-animate__word_whitespace'); if (currentLine && currentLine.root === root && Math.abs(wordTop - currentLine.top) < currentLine.height) { currentLine.words.push(wordElement); if (currentLine.isTopUpdateNeeded && !isWhitespace) { currentLine.isTopUpdateNeeded = false; currentLine.top = wordTop; } } else { const lineHeight = window.getComputedStyle(wordElement).lineHeight; const lineHeightParsedValue = parseFloat(lineHeight); const lineHeightNumberValue = isNaN(lineHeightParsedValue) ? wordElement.getBoundingClientRect().height : lineHeightParsedValue; acc.push({ root, top: wordTop, height: lineHeightNumberValue, words: [wordElement], isTopUpdateNeeded: isWhitespace, }); } return acc; }, []) .map(({ words }) => words); return lines; } /** * Prepare word by word animation to the left. * Split text into lines and reverse the order of words in each line. * Add animation delay for each word by increment. * @param {HTMLElement|null} element - optional specific element to prepare, if null, prepares all elements with the specified animation styles */ function t_animate__prepareWordByWordAnimationToLeft(element = null) { const wordDelayIncrement = 0.06; const animatedTextElements = t_animate__getAnimatedTextElements(['word-fade-in-left'], element); animatedTextElements.forEach(animatedTextElement => { const lines = t_animate__getElementLines(animatedTextElement); const linesWithReversedWords = lines.map(line => line.reverse()); const baseDelay = t_animate__getElementBaseDelay(animatedTextElement); let wordIndex = 0; linesWithReversedWords.forEach(lineElement => { lineElement.forEach(wordElement => { t_animate__setTextParticleDelay(wordElement, baseDelay + wordIndex * wordDelayIncrement); if (!t_animate__isWhitespaceParticle(wordElement)) { wordIndex++; } }); }); }); } /** * Prepare line by line animation. * Add animation delay for each line by increment. * @param {HTMLElement|null} element - optional specific element to prepare, if null, prepares all elements with the specified animation styles */ function t_animate__prepareLinesFadeInAnimation(element = null) { const lineDelayIncrement = 0.12; const animatedTextElements = t_animate__getAnimatedTextElements(['line-fade-in-up-masked'], element); animatedTextElements.forEach(animatedTextElement => { const lines = t_animate__getElementLines(animatedTextElement); const baseDelay = t_animate__getElementBaseDelay(animatedTextElement); lines.forEach((words, lineIndex) => { words.forEach(word => { t_animate__setTextParticleDelay(word, baseDelay + lineIndex * lineDelayIncrement); }); }); }); } /** * Prepare line by line animation for wrapped lines (line-fade-in-right-gradient, line-fade-in-left-gradient). * Add animation delay for each line by increment. * @param {HTMLElement|null} element - optional specific element to prepare, if null, prepares all elements with the specified animation styles */ function t_animate__prepareLinesFadeInWrappedAnimation(element = null) { const lineDelayIncrement = 0.12; const animatedTextElements = t_animate__getAnimatedTextElements( ['line-fade-in-right-gradient', 'line-fade-in-left-gradient'], element ); animatedTextElements.forEach(animatedTextElement => { const lines = animatedTextElement.querySelectorAll('.t-animate__line'); const baseDelay = t_animate__getElementBaseDelay(animatedTextElement); lines.forEach((line, lineIndex) => { const lineDelay = baseDelay + lineIndex * lineDelayIncrement; line.style.animationDelay = `${lineDelay}s`; }); }); } /** * Prepare letter by letter animation (letter-bounce-in-up). * Add animation delay for each letter by increment, index is continuous through the whole element. * Increment is proportional to the letter animation duration, so the whole animation slows down with longer duration. * Strict words are not split into letters, so they are animated as a single letter. * @param {HTMLElement} element - specific element to prepare * @param {number|null} duration - letter animation duration in seconds, if null, default duration is used */ function t_animate__prepareLetterByLetterAnimation(element, duration = null) { const defaultLetterDuration = 0.36; const letterDelayRatio = 0.1; const maxLetterDelayIncrement = 0.1; const letterDuration = duration ?? defaultLetterDuration; const letterDelayIncrement = Math.min(letterDuration * letterDelayRatio, maxLetterDelayIncrement); const animatedTextElements = t_animate__getAnimatedTextElements(['letter-bounce-in-up'], element); animatedTextElements.forEach(animatedTextElement => { const particles = animatedTextElement.querySelectorAll( '.t-animate__letter, .t-animate__word_strict, .t-animate__word_whitespace' ); const baseDelay = t_animate__getElementBaseDelay(animatedTextElement); let letterIndex = 0; let lastLetter = null; particles.forEach(particle => { t_animate__setTextParticleDelay(particle, baseDelay + letterIndex * letterDelayIncrement); if (!t_animate__isWhitespaceParticle(particle)) { letterIndex++; lastLetter = particle; } }); if (!lastLetter) { return; } // letters aren't animated with zero duration, so they can be joined right away if (letterDuration === 0) { t_animate__unwrapAnimatedTextLetters(animatedTextElement); return; } // the last letter has the biggest delay, so the whole text is animated when its animation ends const onLastLetterAnimationEnd = event => { // setting delay returns paused animation to the before phase, it fires animationend with zero elapsed time if (event.elapsedTime === 0) { return; } lastLetter.removeEventListener('animationend', onLastLetterAnimationEnd); t_animate__unwrapAnimatedTextLetters(animatedTextElement); }; lastLetter.addEventListener('animationend', onLastLetterAnimationEnd); }); } /** * Wrap each word of animated text with a span for specific animation styles * @param {string|null} scopeSelector - optional selector of container, if set, only elements inside it are wrapped */ function t_animate__wrapAnimatedTextWords(scopeSelector = null) { const animatedTextElements = t_animate__getAnimatedTextElements([ 'word-fade-in-right', 'word-fade-in-left', 'word-fade-in-down', 'word-fade-in-up', 'line-fade-in-right-gradient', 'line-fade-in-left-gradient', ]).filter(animatedTextElement => !scopeSelector || animatedTextElement.closest(scopeSelector)); animatedTextElements.forEach(animatedTextElement => { t_animate__wrapAnimatedTextElementContentWords(animatedTextElement, false); }); } /** * Wrap each word of animated text with a mask wrapper for specific animation styles * @param {string|null} scopeSelector - optional selector of container, if set, only elements inside it are wrapped */ function t_animate__wrapAnimatedTextWordsWithMasks(scopeSelector = null) { const animatedTextElements = t_animate__getAnimatedTextElements([ 'word-fade-in-up-masked', 'line-fade-in-up-masked', ]).filter(animatedTextElement => !scopeSelector || animatedTextElement.closest(scopeSelector)); animatedTextElements.forEach(animatedTextElement => { t_animate__wrapAnimatedTextElementContentWords(animatedTextElement, true); }); } /** * Wrap each word and then each letter of animated text with a span for letter animation styles. * Letter animations are available only for ZeroBlock elements. */ function t_animate__wrapAnimatedTextLetters() { const animatedTextElements = t_animate__getAnimatedTextElements(['letter-bounce-in-up']).filter( animatedTextElement => animatedTextElement.closest('.t396') ); animatedTextElements.forEach(animatedTextElement => { t_animate__wrapAnimatedTextElementContentWords(animatedTextElement, false); const wordElements = animatedTextElement.querySelectorAll( '.t-animate__word:not(.t-animate__word_whitespace):not(.t-animate__word_strict)' ); wordElements.forEach(wordElement => { const letters = t_animate__splitTextIntoLetters(wordElement.textContent); wordElement.textContent = ''; wordElement.appendChild(letters); }); }); } /** * Join letters of animated text back into words after animation end. * Browser doesn't shape text across inline-block boundaries, so split letters lose kerning, ligatures * and joining of connected scripts (e.g. Arabic). * @param {HTMLElement} element - animated text element */ function t_animate__unwrapAnimatedTextLetters(element) { const wordElements = element.querySelectorAll('.t-animate__word'); wordElements.forEach(wordElement => { if (wordElement.querySelector('.t-animate__letter')) { wordElement.textContent = wordElement.textContent; } }); } /** * Unwrap each line of animated text * @param {HTMLElement|null} element - optional specific element to prepare, if null, prepares all elements with the specified animation styles */ function t_animate__unwrapAnimatedTextLines(element = null) { const animatedTextElements = t_animate__getAnimatedTextElements( ['line-fade-in-right-gradient', 'line-fade-in-left-gradient'], element ); animatedTextElements.forEach(animatedTextElement => { t_animate__unwrapAnimatedTextElementLines(animatedTextElement); }); } /** * Wrap each word of animated text with a span for specific animation styles * @param {HTMLElement|null} element - optional specific element to prepare, if null, prepares all elements with the specified animation styles */ function t_animate__wrapAnimatedTextLines(element = null) { t_animate__unwrapAnimatedTextLines(element); const animatedTextElements = t_animate__getAnimatedTextElements( ['line-fade-in-right-gradient', 'line-fade-in-left-gradient'], element ); animatedTextElements.forEach(animatedTextElement => { t_animate__wrapAnimatedTextElementLines(animatedTextElement); }); } /** * Get base delay from element's transition-delay style * @param {HTMLElement} element - element to get delay from * @returns {number} - delay in seconds */ function t_animate__getElementBaseDelay(element) { const transitionDelay = element.style.transitionDelay || window.getComputedStyle(element).transitionDelay; const parsedTransitionDelay = parseFloat(transitionDelay); if (isNaN(parsedTransitionDelay) || parsedTransitionDelay === 0) { return 0; } if (transitionDelay.includes('ms')) { return parsedTransitionDelay / 1000; } return parsedTransitionDelay; } /** * @typedef {Object} TextDecoration * @property {string[]} lines - array of text decoration lines (e.g., ['underline', 'line-through']) * @property {string} style - text decoration style (e.g., 'solid', 'dashed') * @property {string} color - text decoration color (e.g., '#000000') * @property {string} thickness - text decoration thickness (e.g., '2px') */ /** * Get text decoration properties of a node * @param {CSSStyleDeclaration} computedStyle - computed style of the node * @param {TextDecoration|null} parentTextDecoration - inherited text decoration from parent * @returns {TextDecoration|null} - object with text decoration properties or null if none */ function t_animate__getTextDecoration(computedStyle, parentTextDecoration) { const textDecorationLine = computedStyle.textDecorationLine; if (!textDecorationLine || textDecorationLine === 'none') { return parentTextDecoration; } const textDecorationStyle = computedStyle.textDecorationStyle; const textDecorationColor = computedStyle.textDecorationColor; const textDecorationThickness = computedStyle.textDecorationThickness; return { lines: [...(parentTextDecoration?.lines ?? []), textDecorationLine], style: textDecorationStyle, color: textDecorationColor, thickness: textDecorationThickness, }; } /** * Get text vertical align of a node * @param {CSSStyleDeclaration} computedStyle - computed style of the node * @param {string|null} parentVerticalAlign - inherited vertical align from parent * @returns {string|null} - vertical align value or null if none */ function t_animate__getTextVerticalAlign(computedStyle, parentVerticalAlign) { const verticalAlign = computedStyle.verticalAlign; if (!verticalAlign || verticalAlign === 'baseline' || verticalAlign === 'middle') { return parentVerticalAlign; } return verticalAlign; } /** * @typedef {Object} TextStyleOptions * @property {string|null} verticalAlign - vertical align value (e.g., 'baseline', 'middle', 'sub', 'super') or null if none * @property {TextDecoration|null} textDecoration - text decoration properties or null if none */ /** * Get text style options of a node, including vertical align and text decoration, considering inherited styles from parent. * @param {Node} node - node to get text style options from * @param {TextStyleOptions|null} parentTextStyleOptions - inherited text style options from parent * @returns {TextStyleOptions} - object with verticalAlign and textDecoration properties */ function t_animate__getTextStyleOptions(node, parentTextStyleOptions) { const { verticalAlign: parentVerticalAlign = null, textDecoration: parentTextDecoration = null } = parentTextStyleOptions ?? {}; const computedStyle = window.getComputedStyle(node); const verticalAlign = t_animate__getTextVerticalAlign(computedStyle, parentVerticalAlign); const textDecoration = t_animate__getTextDecoration(computedStyle, parentTextDecoration); return { verticalAlign, textDecoration }; } /** * Create word mask wrapper for word animation * @returns {HTMLSpanElement} */ function t_animate__createWordMaskWrapper() { const wrapper = document.createElement('span'); wrapper.className = 't-animate__word-mask-wrapper'; return wrapper; } /** * Create word span with animation * @param {string} text - text content for the span * @param {TextDecoration|null} textDecoration - inherited text decoration from parent * @param {boolean} isMasked - whether the word should be wrapped in a mask wrapper * @returns {HTMLSpanElement} */ function t_animate__createWord(text, textDecoration, isMasked = false) { const span = document.createElement('span'); span.className = 't-animate__word'; span.style.textDecorationLine = textDecoration?.lines?.join(' ') || ''; span.style.textDecorationStyle = textDecoration?.style || ''; span.style.textDecorationColor = textDecoration?.color || ''; span.style.textDecorationThickness = textDecoration?.thickness || ''; span.textContent = text; if (!isMasked) { return span; } const wrapper = t_animate__createWordMaskWrapper(); wrapper.appendChild(span); return wrapper; } /** * Create strict inline word span for complex text nodes (like superscripts with underline). * Such node will be inline and have more simple animation without transforms. * @param {string} text - text content for the span * @returns {HTMLSpanElement} */ function t_animate__createStrictWord(text) { const span = document.createElement('span'); span.className = 't-animate__word t-animate__word_strict'; span.textContent = text; return span; } /** * Create whitespace span for word animation * @param {string} text - text content for the span * @returns {HTMLSpanElement} */ function t_animate__createWhitespaceWord(text) { const span = document.createElement('span'); span.className = 't-animate__word t-animate__word_whitespace'; span.textContent = text; return span; } /** * Create letter span for letter animation * @param {string} text - text content for the span * @returns {HTMLSpanElement} */ function t_animate__createLetter(text) { const span = document.createElement('span'); span.className = 't-animate__letter'; span.textContent = text; return span; } /** * Get shared grapheme segmenter, it is created once on first call * @returns {Intl.Segmenter|null} - segmenter or null if Intl.Segmenter is not supported */ function t_animate__getGraphemeSegmenter() { if (t_animate__getGraphemeSegmenter.segmenter === undefined) { const isSegmenterSupported = typeof Intl !== 'undefined' && typeof Intl.Segmenter === 'function'; t_animate__getGraphemeSegmenter.segmenter = isSegmenterSupported ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null; } return t_animate__getGraphemeSegmenter.segmenter; } /** * Split text into letters (grapheme clusters). * Text of connected and complex shaped scripts (Arabic, Syriac, Mongolian, Indic, etc.) is not split, * because browser does not shape text across inline-block boundaries and letters lose their joining forms and ligatures. * Without Intl.Segmenter text with surrogate pairs, joiners, variation selectors or combining marks * is not split, because splitting by code points breaks emoji and accented letters. * @param {string} text - text to split * @returns {string[]} - array of letters */ function t_animate__getTextLetters(text) { const connectedScriptRegex = /[\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u07C0-\u07FF\u0840-\u085F\u08A0-\u08FF\u0900-\u0DFF\u1800-\u18AF\uFB50-\uFDFF\uFE70-\uFEFF]/; if (connectedScriptRegex.test(text)) { return [text]; } const segmenter = t_animate__getGraphemeSegmenter(); if (segmenter) { return Array.from(segmenter.segment(text), segment => segment.segment); } const complexCharRegex = /[\uD800-\uDFFF\u200C\u200D\uFE00-\uFE0F\u0300-\u036F\u1AB0-\u1AFF\u1DC0-\u1DFF\u20D0-\u20FF]/; return complexCharRegex.test(text) ? [text] : text.split(''); } /** * Split text into letters and wrap each one by span * @param {string} text - text to process * @returns {Node} - document fragment with wrapped letters */ function t_animate__splitTextIntoLetters(text) { const fragment = document.createDocumentFragment(); t_animate__getTextLetters(text).forEach(letter => { fragment.appendChild(t_animate__createLetter(letter)); }); return fragment; } /** * Create line span for line animation * @returns {HTMLSpanElement} */ function t_animate__createLine() { const line = document.createElement('span'); line.className = 't-animate__line'; return line; } /** * Split text into words and wrap each one by span, preserving whitespace and text decoration * @param {string} text - text to process * @param {TextDecoration|null} textDecoration - inherited text decoration from parent * @param {boolean} isMasked - whether the words should be wrapped in a mask wrapper * @returns {Node} - document fragment with wrapped words */ function t_animate__splitTextIntoWords(text, textDecoration, isMasked = false) { const whitespaceRegex = /(\s+)/; const fragment = document.createDocumentFragment(); const parts = text.split(whitespaceRegex).filter(Boolean); // Filter out empty strings parts.forEach(function (part) { const isWord = part.trim().length > 0; let wordSpan; if (isWord) { wordSpan = t_animate__createWord(part, textDecoration, isMasked); } else { wordSpan = t_animate__createWhitespaceWord(part); } fragment.appendChild(wordSpan); }); return fragment; } /** * Split text into strict words with trailing whitespaces and wrap each one by span. * @param {string} text - text to process * @returns {Node} - document fragment with wrapped words */ function t_animate__splitTextIntoStrictWords(text) { const whitespaceRegex = /(\s+)/; const fragment = document.createDocumentFragment(); const parts = text .split(whitespaceRegex) .reduce((acc, part) => { const isWhitespace = part.trim().length === 0; if (isWhitespace && acc.length > 0) { acc[acc.length - 1] += part; } else { acc.push(part); } return acc; }, []) // Combine trailing whitespace with the previous word .filter(Boolean); // Filter out empty strings parts.forEach(function (part) { const isWord = part.trim().length > 0; let wordSpan; if (isWord) { wordSpan = t_animate__createStrictWord(part); } else { wordSpan = t_animate__createWhitespaceWord(part); } fragment.appendChild(wordSpan); }); return fragment; } /** * Wrap inner words of an animated text element with a span, processing its child nodes recursively. * @param {Node} node - node to process * @param {boolean} isMasked - whether the words should be wrapped in a mask wrapper * @returns {Node} - document fragment with wrapped content */ function t_animate__wrapAnimatedTextElementContentWords(node, isMasked = false) { /** * Wrap inner words of a text node * @param {Text} textNode - text node to process * @param {TextStyleOptions|null} textStyleOptions - inherited text style options from parent * @returns {Node} - document fragment with wrapped words */ function wrapTextNode(textNode, textStyleOptions) { const { verticalAlign = null, textDecoration = null } = textStyleOptions ?? {}; const hasStyleConflict = Boolean(verticalAlign && textDecoration); const text = textNode.textContent; const wrappedText = hasStyleConflict ? t_animate__splitTextIntoStrictWords(text) : t_animate__splitTextIntoWords(text, textDecoration, isMasked); return wrappedText; } /** * Wrap inner words of an element node * @param {Element} elementNode - element node to process * @param {TextStyleOptions|null} textStyleOptions - inherited text style options from parent * @returns {Node} - cloned element with wrapped children */ function wrapElementNode(elementNode, textStyleOptions) { // Clone element preserving all attributes (Quill formatting, classes, etc.) const clone = elementNode.cloneNode(false); // Process children if they exist if (elementNode.childNodes.length > 0) { const wrappedChildren = wrapNode(elementNode, textStyleOptions); clone.appendChild(wrappedChildren); } return clone; } /** * Wrap inner words of a node recursively, preserving text decoration and vertical alignment. * @param {Node} node - current node to process * @param {TextStyleOptions|null} parrentTextStyleOptions - inherited text style options from parent * @returns {Node} - document fragment with wrapped content */ function wrapNode(node, parrentTextStyleOptions) { const fragment = document.createDocumentFragment(); const textStyleOptions = t_animate__getTextStyleOptions(node, parrentTextStyleOptions); Array.from(node.childNodes).forEach(function (childNode) { if (childNode.nodeType === Node.TEXT_NODE) { const wrappedTextNode = wrapTextNode(childNode, textStyleOptions); fragment.appendChild(wrappedTextNode); } else if (childNode.nodeType === Node.ELEMENT_NODE) { const wrappedElement = wrapElementNode(childNode, textStyleOptions); fragment.appendChild(wrappedElement); } }); return fragment; } const wrappedContent = wrapNode(node, null); node.innerHTML = ''; node.appendChild(wrappedContent); } /** * Unwrap each line of animated text element * @param {HTMLElement} element - specific element to unwrap */ function t_animate__unwrapAnimatedTextElementLines(element) { const lines = element.querySelectorAll('.t-animate__line'); lines.forEach(line => { line.replaceWith(...line.childNodes); }); } /** * Wrap each line of an animated text element with a span, processing its child nodes recursively. * @param {Node} node - node to process */ function t_animate__wrapAnimatedTextElementLines(node) { /** * Split an element into left and right parts based on the provided path of child nodes. * @param {Node} element - the element to split * @param {Node[]} path - array of child nodes leading to the target node to split on * @returns {{ leftPart: Node, rightPart: Node }} - object containing left and right parts */ function splitElement(element, path) { if (!path.length) { return { leftPart: document.createDocumentFragment(), rightPart: element }; } const [childToSplitOn, ...restPath] = path; const elementChildList = Array.from(element.childNodes); const childToSplitOnIndex = elementChildList.findIndex(child => child === childToSplitOn); if (childToSplitOnIndex < 0) { return { leftPart: element, rightPart: document.createDocumentFragment() }; } const leftPart = element.cloneNode(false); const rightPart = element.cloneNode(false); const leftPartChildList = childToSplitOnIndex > 0 ? elementChildList.slice(0, childToSplitOnIndex) : []; const rightPartChildList = childToSplitOnIndex < elementChildList.length - 1 ? elementChildList.slice(childToSplitOnIndex + 1) : []; const { leftPart: leftChildPart, rightPart: rightChildPart } = splitElement(childToSplitOn, restPath); leftPart.append(...leftPartChildList, leftChildPart); rightPart.append(rightChildPart, ...rightPartChildList); return { leftPart, rightPart }; } /** * Split inner elements of a node by lines. Splits two lined elements into separate elements for each line * by creating new elements and replacing the original ones in the DOM. * @param {Node} node - the parent node containing the elements * @param {Node[][]} lines - array of lines, each line is an array of nodes * @returns {{ root: Node, elements: Node[] }[]} - array of objects containing the root node and its elements for each line */ function splitNodeInnerElementsByLines(node, lines) { const elementsLineInfoList = []; for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) { const words = lines[lineIndex]; const { elements: prevElements } = elementsLineInfoList.at(-1) ?? {}; const elements = []; let root = null; for (let wordIndex = 0; wordIndex < words.length; wordIndex++) { const word = words[wordIndex]; const treePathInfo = t_animate__getTreePath(word); const path = treePathInfo.path; const [container = word, ...restPath] = path; const existedContainerIndex = prevElements?.findIndex(item => item === container); root = treePathInfo.root; if (existedContainerIndex >= 0) { const { leftPart, rightPart } = splitElement(container, [...restPath, word]); const newContainer = document.createDocumentFragment(); prevElements.splice(existedContainerIndex, 1, leftPart); elements.push(rightPart); newContainer.append(leftPart, rightPart); root.replaceChild(newContainer, container); } else if (!elements.includes(container)) { elements.push(container); } } elementsLineInfoList.push({ root, elements }); } return elementsLineInfoList; } /** * Get a slice of child nodes from a parent element between two specified child elements. * @param {Node} parentElement - the parent element containing the child nodes * @param {Node} fromElement - the starting child node of the slice * @param {Node} toElement - the ending child node of the slice * @returns {Node[]} - array of child nodes between fromElement and toElement (inclusive) */ function getElementChildrenSlice(parentElement, fromElement, toElement) { const childList = Array.from(parentElement.childNodes); const firstChildIndex = childList.findIndex(child => child === fromElement); const lastChildIndex = childList.findIndex(child => child === toElement); if (firstChildIndex < 0 || lastChildIndex < 0) { return []; } const minChildIndex = Math.min(firstChildIndex, lastChildIndex); const maxChildIndex = Math.max(firstChildIndex, lastChildIndex); return childList.slice(minChildIndex, maxChildIndex + 1); } /** * Wrap a slice of child nodes from a parent element between two specified child elements with a new wrapper element. * @param {Node} node - the parent element containing the child nodes * @param {Node} fromElement - the starting child node of the slice * @param {Node} toElement - the ending child node of the slice */ function wrapNodeInnerElementsByLine(node, fromElement, toElement) { const rootChildrenSlice = getElementChildrenSlice(node, fromElement, toElement); if (!rootChildrenSlice.length) { return; } const lineWrapper = t_animate__createLine(); rootChildrenSlice[0].before(lineWrapper); lineWrapper.append(...rootChildrenSlice); } const lines = t_animate__getElementLines(node); const elementsLineInfoList = splitNodeInnerElementsByLines(node, lines); elementsLineInfoList.forEach(({ root, elements }) => { const firstElement = elements.at(0); const lastElement = elements.at(-1); wrapNodeInnerElementsByLine(root, firstElement, lastElement); }); } /** * Check IE browser * * @returns {Boolean} - if ie browser return true */ function t_animate__checkIE() { var sAgent = window.navigator.userAgent; var Idx = sAgent.indexOf('MSIE'); var ieVersion = ''; var oldIE = false; if (Idx > 0) { ieVersion = parseInt(sAgent.substring(Idx + 5, sAgent.indexOf('.', Idx))); if (ieVersion === 8 || ieVersion === 9) { oldIE = true; } } return oldIE; }