/** * @file Содержит глобальные функции (IE8+). * @module tilda-scripts-3.0.js */ /** * Вызывает функцию, когда DOM прогрузится/прогрузился для IE8+ * * @param {function} func */ function t_onReady(func) { if (document.readyState != 'loading') { func(); } else { document.addEventListener('DOMContentLoaded', func); } } /** * Метод для добавления класса к элементу для IE8+. * * @param {Node} el - Элемент, к которому добавляется класс. * @param {string} className - Имя класса. */ function t_addClass(el, className) { // HTML 5 compliant browsers if (document.body.classList) { el.classList.add(className); return; } // legacy browsers (IE<10) support el.className += (el.className ? ' ' : '') + className; } /** * Метод для удаления класса у элемента для IE8+. * * @param {Node} el - Элемент, из которого удаляется класс. * @param {string} className - Имя класса. */ function t_removeClass(el, className) { // HTML 5 compliant browsers if (document.body.classList) { el.classList.remove(className); return; } // legacy browsers (IE<10) support el.className = el.className .replace(new RegExp('(^|\\s+)' + className + '(\\s+|$)'), ' ') .replace(/^\s+/, '') .replace(/\s+$/, ''); } /** * Метод для удаления элемента для IE8+. * * @param {Node} el - Элемент, который нужно удалить. */ function t_removeEl(el) { if (el && el.parentNode) { el.parentNode.removeChild(el); } } /** * Получает внешнюю ширину элемента с учётом отступов. * Если ширина или отступы не установлены или имеют значение `'auto'`, они заменяются на `0`. * * @param {Node} el - Элемент, для которого нужно получить внешнюю ширину. * @returns {number} Внешняя ширина элемента в пикселях, включая отступы. */ function t_outerWidth(el) { var style = getComputedStyle(el); var width = style.width; var marginLeft = style.marginLeft; var marginRight = style.marginRight; if (width === 'auto') width = 0; if (marginLeft === 'auto') marginLeft = 0; if (marginRight === 'auto') marginRight = 0; width = parseInt(width) + parseInt(marginLeft) + parseInt(marginRight); return width; } // Глобальные переменные /** * Определяет, является ли пользовательский агент поисковым ботом. * @type {boolean} */ window.isSearchBot = false; if (/Bot/i.test(navigator.userAgent)) { window.isSearchBot = true; } /** * Определяет, используется ли мобильное устройство. * @type {boolean} */ window.isMobile = false; window.$isMobile = false; if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { window.isMobile = true; window.$isMobile = true; } /** * Определяет, используется ли планшетное устройство. * @type {boolean} */ window.isTablet = /(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/i.test( navigator.userAgent ); /** * Определяет, используется ли iOS устройство. * @type {boolean} */ window.isiOS = false; if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) { window.isiOS = true; } /** * Определяет, используется ли браузер Chrome на iOS. * @type {boolean} */ window.isiOSChrome = !!navigator.userAgent.match('CriOS'); /** * Определяет, используется ли браузер Firefox. * @type {boolean} */ window.isFirefox = /firefox/i.test(navigator.userAgent); /** * Определяет, используется ли браузер Opera. * @type {boolean} */ window.isOpera = (!!window.opr && !!window.opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0; /** * Хранит версию iOS, если используется устройство на iOS. * @type {Array} */ window.isiOSVersion = ''; if (window.isiOS) { var version = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); if (version !== null) { window.isiOSVersion = [parseInt(version[1], 10), parseInt(version[2], 10), parseInt(version[3] || 0, 10)]; } } /** * Определяет, используется ли браузер Safari. * @type {boolean} */ window.isSafari = false; if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) { window.isSafari = true; } /** * Определяет, используется ли Internet Explorer. * @type {boolean} */ window.isIE = !!document.documentMode; /** * Хранит версию Safari, если используется браузер Safari. * @type {Array} */ window.isSafariVersion = ''; // TODO: возможно упростить до safariVersion? if (window.isSafari) { var version = navigator.appVersion.match(/Version\/(\d+)\.(\d+)\.?(\d+)? Safari/); if (version !== null) { window.isSafariVersion = [parseInt(version[1], 10), parseInt(version[2], 10), parseInt(version[3] || 0, 10)]; } } /** * Хранит язык браузера, преобразованный в верхний регистр. * @type {string} */ window.browserLang = (window.navigator.userLanguage || window.navigator.language).toUpperCase().slice(0, 2); /** * Устаревшее название для `browserLang`. * @type {string} */ window.tildaBrowserLang = window.browserLang; // устаревшее /** Language override based on attribute */ t_onReady(function () { var allrecords = document.getElementById('allrecords'); if (allrecords) { var projectLang = allrecords.getAttribute('data-tilda-project-lang'); } if (projectLang) { window.browserLang = projectLang; } }); /** * Создаёт функцию, которая вызывает `fn` через заданный таймаут и с указанным контекстом. * * @template {unknown[]} T * @param {(...args: T) => void} fn - Функция для вызова. * @param {number} threshhold - Таймаут в миллисекундах. * @param {Node} [scope] - Контекст вызова. * @returns {(...args: T) => void} Функция, которая планирует вызов `fn`. */ function t_throttle(fn, threshhold, scope) { var last; var deferTimer; threshhold || (threshhold = 250); return function () { var context = scope || this; var now = +new Date(); var args = arguments; if (last && now < last + threshhold) { clearTimeout(deferTimer); deferTimer = setTimeout(function () { last = now; fn.apply(context, args); }, threshhold); } else { last = now; fn.apply(context, args); } }; } /** * Создаёт функцию, которая откладывает вызов `fn` до тех пор, пока не пройдёт заданное время после последнего вызова. * * @template {unknown[]} T * @param {(...args: T) => void} fn - Функция для вызова * @param {number} delay - Задержка в миллисекундах. * @param {Node} [scope] - Контекст вызова. * @returns {(...args: T) => void} Функция, которая откладывает вызов `fn`. */ function t_debounce(fn, delay, scope) { var timer; delay || (delay = 250); return function () { var context = scope || this; var args = arguments; clearTimeout(timer); timer = setTimeout(function () { fn.apply(context, args); }, delay); }; } /** * Проверяет, загружена ли функция, и выполняет указанную функцию, если функция готова. * Для редактора блоков проверяет готовность редактора для выполнения функций. * * @param {string} funcName - Имя функции для проверки. * @param {Function} okFunc - Функция, которую нужно выполнить, если проверка успешна. * @param {number} time - Время в миллисекундах для проверки. */ function t_onFuncLoad(funcName, okFunc, time) { var TIMEOUT = 15 * 1000; var isEditMode = t_checkIsEditMode(); var isEditorReady = function () { return !isEditMode || (isEditMode && t_checkEditorIsReady()); }; var isFuncExist = function (_funcName) { return typeof window[_funcName] === 'function' || typeof window[_funcName] === 'object'; }; if (isFuncExist(funcName) && isEditorReady()) { okFunc(); } else { var startTime = Date.now(); var error = new Error(funcName + ' is undefined'); var callbackError = function () { throw error; }; setTimeout(function checkFuncExist() { var currentTime = Date.now(); if (isFuncExist(funcName) && isEditorReady()) { okFunc(); return; } if (document.readyState === 'complete' && currentTime - startTime > TIMEOUT && !isFuncExist(funcName)) { callbackError(); } setTimeout(checkFuncExist, time || 100); }); } } /** * Проверяет, находится ли редактор в режиме редактирования. * * @returns {boolean} `true`, если редактор находится в режиме редактирования, иначе `false`. */ function t_checkIsEditMode() { var isEditMode = false; var allRecords = document.getElementById('allrecords'); if (!allRecords) return false; var tildaMode = allRecords.getAttribute('data-tilda-mode'); isEditMode = tildaMode && tildaMode === 'edit'; return !!isEditMode; } /** * Проверяет, готов ли редактор к выполнению функций. * * @returns {boolean} `true`, если редактор готов, иначе `false`. */ function t_checkEditorIsReady() { var isEditorReady = false; if (!t_checkIsEditMode()) return false; var editorReadyStatus = document.body.getAttribute('data-ready-status'); isEditorReady = editorReadyStatus && editorReadyStatus === 'ready'; return !!isEditorReady; } /** Turn off font boosting */ t_onReady(function () { var userAgent = window.navigator.userAgent; var isInstagram = userAgent.indexOf('Instagram') !== -1; var isFacebook = userAgent.indexOf('FBAV') !== -1; var isYandex = userAgent.indexOf('YaSearchBrowser') !== -1; var isSamsung = userAgent.indexOf('SamsungBrowser') !== -1; var isDuckDuckGo = userAgent.indexOf('DuckDuckGo') !== -1; var isAndroid = userAgent.indexOf('Android') !== -1; if (isAndroid && (isFacebook || isInstagram || isYandex || isSamsung || isDuckDuckGo)) { var textElement = document.createElement('p'); textElement.style.lineHeight = '100px'; textElement.style.padding = '0'; textElement.style.margin = '0'; textElement.style.height = 'auto'; textElement.style.position = 'absolute'; textElement.style.opacity = '0.001'; textElement.innerText = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; document.body.appendChild(textElement); var factor = 100 / textElement.getBoundingClientRect().height; textElement.parentNode.removeChild(textElement); if (factor < 0.98) { document.body.insertAdjacentHTML( 'beforeend', '' ); } } /* Зум текста под экран на альбомной ориентации в iOS */ if (window.isiOS && !window.MSStream) { document.body.style.setProperty('-webkit-text-size-adjust', '100%'); document.body.style.setProperty('text-size-adjust', '100%'); } }); /** Tilda label */ t_onReady(function () { setTimeout(function () { var html = document.querySelector('html'); var tildaLabel = document.querySelector('.t-tildalabel'); var bodyScrollHeight = html.offsetHeight; if (document.body) { bodyScrollHeight = Math.max( document.body.scrollHeight, document.body.offsetHeight, document.body.clientHeight, html.offsetHeight ); } if ((!document.getElementById('tildacopy') && !tildaLabel) || !tildaLabel.querySelectorAll('div')) { var childs = document.body.childNodes; var arrChilds = []; for (var i = 0; i < childs.length; i++) { var element = childs[i]; if (element.nodeType === 8) { arrChilds.push(element); } } for (var i = 0; i < arrChilds.length; i++) { if (arrChilds[i].nodeValue.indexOf("'t remove this l") !== -1) { document .getElementById('allrecords') .insertAdjacentHTML( 'afterend', '' ); } } } else if (bodyScrollHeight + 70 > window.innerHeight) { if (tildaLabel) { tildaLabel.setAttribute( 'style', 'display: block !important; visibility: visible !important; position: relative !important; width: 100% !important; pointer-events: all !important; opacity: 1 !important; margin: 0 !important; z-index: 1 !important' ); } } }, 500); }); /** Appearance animation */ t_onReady(function () { var allRecords = document.getElementById('allrecords'); if ( !window.isMobile && allRecords && allRecords.getAttribute('data-blocks-animationoff') !== 'yes' && window.isSearchBot === false ) { var recBlocks = document.querySelectorAll('.r'); for (var i = 0; i < recBlocks.length; i++) { var rec = recBlocks[i]; var style = rec.getAttribute('style'); if (style && style.indexOf('background') !== -1) { rec.setAttribute('data-animationappear', 'off'); } } // add animation var recBlocksNot = Array.prototype.slice.call(recBlocks).filter(function (el) { return ( !el.getAttribute('data-animationappear') && !el.getAttribute('data-screen-min') && !el.getAttribute('data-screen-max') ); }); for (var i = 0; i < recBlocksNot.length; i++) { var rec = recBlocksNot[i]; var recTop = rec.getBoundingClientRect().top + window.pageYOffset; var position = window.pageYOffset + window.innerHeight + 300; if (recTop > 1000 && recTop > position) { t_addClass(rec, 'r_hidden'); } else { t_addClass(rec, 'r_showed'); } t_addClass(rec, 'r_anim'); } if (recBlocksNot.length) { function t_blocksFade() { for (var i = recBlocksNot.length - 1; i >= 0; i--) { var rec = recBlocksNot[i]; var recTop = rec.getBoundingClientRect().top + window.pageYOffset; var position = 0; if (rec.offsetHeight <= 100) { position = window.pageYOffset + window.innerHeight; } else { position = window.pageYOffset + window.innerHeight - 100; } if (recTop < position) { t_removeClass(rec, 'r_hidden'); t_addClass(rec, 'r_showed'); recBlocksNot = Array.prototype.slice.call(recBlocksNot); recBlocksNot.splice(i, 1); } } } var recBlocksT400 = document.querySelectorAll('[data-record-type="400"], [data-parenttplid="400"]'); if (recBlocksT400.length > 0) { var countCompleted = 0; var count = 0; var timer = setInterval(function () { count += 1; // 300 - время через которое остановить интервал если условие не выполнится // 300 * 100 = 30000 мс -> 30 сек if (300 === count) clearInterval(timer); for (var i = 0; i < recBlocksT400.length; i++) { var rec = recBlocksT400[i]; if (rec.getAttribute('data-hiding-completed') === 'yes') countCompleted += 1; } if (countCompleted === recBlocksT400.length) { t_blocksFade(); clearInterval(timer); } }, 100); } window.addEventListener( 'scroll', t_throttle(function () { t_blocksFade(); }, 200) ); window.addEventListener( 'tildatab:change', t_throttle(function () { t_blocksFade(); }, 200) ); setTimeout(function () { t_blocksFade(); }); } } var html = document.querySelector('html'); var body = document.body; if (html.style.display === 'none') { html.style.display = 'block'; } var tildaLabel = document.querySelector('.t-tildalabel'); var bodyScrollHeight; if (body) { bodyScrollHeight = Math.max(body.scrollHeight, body.offsetHeight, body.clientHeight, html.offsetHeight); } else { bodyScrollHeight = html.offsetHeight; } // Исторически сложилось, что скрываем Tilda Label, // если страница короче окна, чтобы он не «висел» в пустоте. if (bodyScrollHeight + 70 < window.innerHeight) { if (tildaLabel) { tildaLabel.style.display = 'none'; } } else { if (tildaLabel) { tildaLabel.setAttribute('style', 'display: block !important'); } } }); /** * window.winWidth and window.winHeight used in tilda-stat, to create fingerprint statistics. * The blocks are hidden via css. It seems to work the same without this function. */ (function () { /** Set window width and height */ function t_setWindowVars() { window.winWidth = window.innerWidth; window.winHeight = window.innerHeight; } /** Show and hide blocks */ function t_blocksdisplay() { var windowWidth = window.isMobile ? document.documentElement.clientWidth : window.innerWidth; var recBlocks = document.querySelectorAll('.r[data-screen-max], .r[data-screen-min]'); var max; var min; var display; if (navigator.userAgent.indexOf('Instagram') !== -1) windowWidth = screen.width; for (var i = 0; i < recBlocks.length; i++) { var rec = recBlocks[i]; var recId = rec.id.replace('rec', ''); const zeroPopupSelector = `[data-popup-rec-ids*="${recId}"]`; if (rec.getAttribute('data-connect-with-tab') === 'yes' || document.querySelector(zeroPopupSelector)) { return; } display = getComputedStyle(rec).display; max = rec.getAttribute('data-screen-max'); min = rec.getAttribute('data-screen-min'); if (!max) max = 10000; if (!min) min = 0; max = parseInt(max); min = parseInt(min); if (min <= max) { if (windowWidth <= max && windowWidth > min) { if (display !== 'block') { rec.style.display = 'block'; } } else if (display !== 'none') { rec.style.display = 'none'; } } } } t_onReady(function () { t_setWindowVars(); t_blocksdisplay(); window.addEventListener( 'resize', t_throttle(function () { t_setWindowVars(); }, 200) ); window.addEventListener( 'resize', t_throttle(function () { t_blocksdisplay(); }, 200) ); }); })(); /** * Defining heights for covers and other blocks in the mobile version, * reducing fonts and tracking blocks that are not optimized for the mobile version */ (function () { var isInstagram = navigator.userAgent.indexOf('Instagram') !== -1; function t_correctHeight() { var coverCarries = document.querySelectorAll('.t-cover__carrier'); var factor = 0; for (var i = 0; i < coverCarries.length; i++) { var element = coverCarries[i]; var elementStyle = element.style; if (elementStyle.height.indexOf('vh') > -1) { factor = parseInt(elementStyle.height, 10) / 100; var div = document.createElement('div'); div.id = 'tempDiv'; div.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100vh;visibility:hidden;'; document.body.appendChild(div); var tempDiv = document.getElementById('tempDiv'); var tempDivHeight = parseInt(getComputedStyle(tempDiv).height.replace('px', '')); t_removeEl(tempDiv); var newHeight = Math.round(tempDivHeight * factor) + 'px'; var cover = element.closest('.t-cover'); if (cover) { var coverFilter = cover.querySelector('.t-cover__filter'); var textBox = cover.querySelector('.t-cover__wrapper'); cover.style.height = newHeight; if (coverFilter) coverFilter.style.height = newHeight; if (textBox) textBox.style.height = newHeight; } elementStyle.height = newHeight; } } // others var elCarries = document.querySelectorAll('[data-height-correct-vh]'); var windowHeight = window.innerHeight; factor = 0; for (var i = 0; i < elCarries.length; i++) { var element = elCarries[i]; var elementStyle = element.style; if (elementStyle.height.indexOf('vh') > -1) { factor = parseInt(elementStyle.height) / 100; newHeight = windowHeight * (isNaN(factor) ? 1 : factor) + 'px'; elementStyle.height = newHeight; } } } if (window.isMobile || window.parent.isPagePreview) { t_onReady(function () { setTimeout(t_correctHeight, 400); }); window.addEventListener('load', function () { setTimeout(t_correctHeight, 400); }); if ( window.innerWidth < 480 || (window.isMobile && document.documentElement.clientWidth < 480) || (isInstagram && screen.width < 480) ) { t_onReady(function () { var customStyleElements = document.querySelectorAll('[data-customstyle="yes"]'); var fieldElements = document.querySelectorAll('[field] span, [field] strong, [field] em, [field] a'); for (var i = 0; i < customStyleElements.length; i++) { var element = customStyleElements[i]; if (parseInt(getComputedStyle(element).fontSize.replace('px', '')) > 26) { element.style.fontSize = null; element.style.lineHeight = null; } } for (var i = 0; i < fieldElements.length; i++) { var element = fieldElements[i]; if (parseInt(getComputedStyle(element).fontSize.replace('px', '')) > 26) { element.style.fontSize = null; } } updateFontSize(480); window.addEventListener('orientationchange', function () { setTimeout(function () { updateFontSize(480); }, 500); }); }); window.addEventListener('load', setBreakWords); window.addEventListener('orientationchange', function () { setTimeout(function () { setBreakWords(); }, 500); }); } else if ( window.innerWidth < 900 || (window.isMobile && document.documentElement.clientWidth < 900) || (isInstagram && screen.width < 900) ) { t_onReady(function () { var customStyleElements = document.querySelectorAll('[data-customstyle="yes"]'); var fieldElements = document.querySelectorAll('[field] span, [field] strong, [field] em, [field] a'); for (var i = 0; i < customStyleElements.length; i++) { var element = customStyleElements[i]; if (parseInt(getComputedStyle(element).fontSize.replace('px', '')) > 30) { element.style.fontSize = null; element.style.lineHeight = null; } } for (var i = 0; i < fieldElements.length; i++) { var element = fieldElements[i]; if (parseInt(getComputedStyle(element).fontSize.replace('px', '')) > 30) { element.style.fontSize = null; } } var elements = document.querySelectorAll( '' + '.t-text:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-name:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-title:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-descr:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-heading:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-text-impact:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-subtitle:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-uptitle:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"])' ); for (var i = 0; i < elements.length; i++) { var element = elements[i]; var elementStyle = element.getAttribute('style'); if (elementStyle && elementStyle.indexOf('font-size') > -1) { if (parseInt(getComputedStyle(element).fontSize.replace('px', '')) > 30) { if (element.getAttribute('data-auto-correct-font-size') === 'rem') { // set adaptive font size for mobile devices var newStyle = elementStyle .replace(/font-size.*px;/gi, 'font-size: 1.6rem;') .replace('line-height', 'lineheight'); element.setAttribute('style', newStyle); } else { // reset font-size for all other elements var newStyle = elementStyle .replace('font-size', 'fontsize') .replace('line-height', 'lineheight'); element.setAttribute('style', newStyle); } } } } }); } } function setBreakWords() { var windowWidth = isInstagram ? screen.width : window.innerWidth; if (window.isMobile && !isInstagram) { windowWidth = document.documentElement.clientWidth; } var recBlocks = document.querySelectorAll( '.r:not([data-record-type="396"], [data-record-type="1003"], [data-parenttplid="396"], [data-parenttplid="1003"])' ); var visibleRecBlocks = []; for (var k = 0; k < recBlocks.length; k++) { var record = recBlocks[k]; var recStyles = getComputedStyle(record); if (recStyles.display !== 'none' && recStyles.visibility !== 'hidden' && recStyles.opacity !== '0') { visibleRecBlocks.push(record); } } for (var i = 0; i < visibleRecBlocks.length; i++) { var rec = visibleRecBlocks[i]; var blocks = rec.querySelectorAll( '' + 'div:not([data-auto-correct-mobile-width="false"]):not(.tn-elem):not(.tn-atom):not(.tn-atom__sbs-anim-wrapper)' + ':not(.tn-atom__prx-wrapper):not(.tn-atom__videoiframe):not(.tn-atom__sticky-wrapper)' + ':not(.t-catalog__relevants__container):not(.t-slds__items-wrapper):not(.js-product-controls-wrapper)' + ':not(.t-store__relevants__container):not(.t-slds__items-wrapper):not(.js-product-controls-wrapper)' + ':not(.js-product-edition-option):not(.t-product__option-variants)' ); for (var j = 0; j < blocks.length; j++) { var block = blocks[j]; rec.style.wordBreak = ''; var blockWidth = t_outerWidth(block); if (blockWidth > windowWidth) { if (block.getAttribute('[data-customstyle]') === 'yes') { if (block.parentNode.getAttribute('[data-auto-correct-mobile-width]') === 'false') { return; } } console.log( 'Block not optimized for mobile width. Block width:' + blockWidth + ' Block id:' + rec.getAttribute('id') ); console.log(block); rec.style.overflow = 'auto'; rec.style.wordBreak = blockWidth - 3 > windowWidth ? 'break-word' : ''; } } } } function updateFontSize(breakpoint) { var elements = document.querySelectorAll( '' + '.t-text:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-name:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-title:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-descr:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-heading:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-text-impact:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-subtitle:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"]), ' + '.t-uptitle:not(.tn-elem):not(.tn-atom):not([data-auto-correct-line-height="false"])' ); for (var i = 0; i < elements.length; i++) { var element = elements[i]; var elementStyle = element.getAttribute('style'); if (!elementStyle) continue; var isREMValue = element.getAttribute('data-auto-correct-font-size') === 'rem'; var newStyle; if (document.documentElement.clientWidth > breakpoint) { newStyle = elementStyle.replace('lineheight', 'line-height'); newStyle = newStyle.replace('fontsize', 'font-size'); element.setAttribute('style', newStyle); } else { if (elementStyle.indexOf('font-size') === -1) continue; if (parseInt(getComputedStyle(element).fontSize.replace('px', '')) < 26) continue; newStyle = elementStyle.replace('line-height', 'lineheight'); newStyle = isREMValue ? newStyle.replace(/font-size.*px;/gi, 'font-size: 1.6rem;') : newStyle.replace('font-size', 'fontsize'); element.setAttribute('style', newStyle); } } } })(); /** * Adding rel=noopener for all links on the page * https://mathiasbynens.github.io/rel-noopener/ * UPD: Browsers now implicitly set rel=noopener for any target=_blank link */ (function () { t_onReady(function () { setTimeout(function () { var links = document.querySelectorAll('a[href^="http"][target="_blank"]'); for (var i = 0; i < links.length; i++) { var link = links[i]; var attrRel = link.getAttribute('rel') || ''; if (attrRel === '') { link.setAttribute('rel', 'noopener'); } else if (attrRel.indexOf('noopener') === -1) { link.setAttribute('rel', attrRel + ' noopener'); } } }, 2500); }); })(); /** Capture JS errors */ (function (window, Math) { /* window.t_captureJsErrors = function (message, filename, lineno, colno, error){ var has_code=''; var el_all=$('#allrecords'); if($('.t123').length || $('.tn-atom__html').length || el_all.attr('data-tilda-project-headcode')==='yes' || el_all.attr('data-tilda-page-headcode')==='yes'){ var has_code='y'; } if(has_code!=='y'){ var xhr = new XMLHttpRequest(); xhr.open("POST", 'https://sysstat.tildacdn.com/api/js/error/', true); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.send(JSON.stringify({ event_id: Date.now() + '-' + Math.floor(Math.random() * 100000), request: { url: window.location.href, }, exception: { values: [ { type: (typeof error!=='undefined' && error!=null && typeof error.name!=='undefined' ? error.name: ''), value: message, stacktrace: { frames: [ { filename: filename, colno: colno, lineno: lineno } ] } } ] }, stacktrace: (typeof error!=='undefined' && error!==null && typeof error.stack!=='undefined' ? error.stack : '') })); } } window.onerror = function(message, filename, lineno, colno, error) { if(typeof window.t_jserr_i!='number')window.t_jserr_i=0; window.t_jserr_i++; setTimeout(function() { window.t_captureJsErrors(message, filename, lineno, colno, error); }, 500*window.t_jserr_i); }; */ window.onerror = function (message, filename, lineno, colno, error) { if (typeof window.t_jserrors !== 'object') window.t_jserrors = []; window.t_jserrors.push({ message: message, filename: filename, lineno: lineno, colno: colno, error: error, }); }; })(window, Math); t_onReady(function () { document.body.addEventListener('popupShowed', t_scrollBarWidthCompensator__init); document.body.addEventListener('popupHidden', function () { var obj = window.scrollBarWidthCompensator; if (!obj) return; if (obj.cancelTimeout) { window.clearTimeout(obj.cancelTimeout); obj.cancelTimeout = null; } obj.cancelTimeout = window.setTimeout( function () { obj.cancelTimeout = null; t_scrollBarWidthCompensator__cancel(); }, Math.min(300, obj.delay) ); }); }); /** * Глобальный объект для компенсации ширины полосы прокрутки. * * @type {Object} * @property {boolean} isInited - Флаг, указывающий, инициализирован ли объект. * @property {number} scrollBarWidth - Ширина полосы прокрутки. * @property {number} delay - Таймаут для задержки. * @property {number} [cancelTimeout] - Идентификатор таймера для отмены. * @property {Array} fixedElements - Список элементов с фиксированным позиционированием. */ window.scrollBarWidthCompensator; /** * Инициализирует объект для компенсации ширины полосы прокрутки. * Создаёт список фиксированных элементов, ширина которых может измениться из-за полосы прокрутки. */ function t_scrollBarWidthCompensator__setObject() { window.scrollBarWidthCompensator = {}; var obj = window.scrollBarWidthCompensator; obj.isInited = false; obj.scrollBarWidth = Math.abs(window.innerWidth - document.documentElement.clientWidth); obj.delay = 0; obj.cancelTimeout = null; var excludedElements = [ 't450', 't282__container', 't282__container__bg_opened', 't282__menu__container', 't830m', 't830__panel', 't451m', 't204__menu', 'tn-atom__sbs-anim-wrapper', 't-menu-popover__burgermenu__sidebar_right', 't-menu-popover_fullscreen', ]; var allElements = document.querySelectorAll('*'); allElements = Array.prototype.filter.call(allElements, function (el) { if (el.closest('.t1093')) return false; // не обрабатываем все элементы внутри зеро-попапа return !excludedElements.some(function (className) { return el.classList.contains(className); }); }); obj.fixedElements = []; Array.prototype.forEach.call(allElements, function (el) { if (el.classList.contains('t975')) return; var computedStyle = window.getComputedStyle(el); var computedPosition = computedStyle.getPropertyValue('position'); var { isFullscreenWidth, isFullscreenHeight } = t_scrollBarWidthCompensator__checkSize( computedStyle, obj.scrollBarWidth ); if ( computedPosition === 'fixed' || (computedPosition === 'absolute' && isFullscreenWidth && !isFullscreenHeight) ) { obj.fixedElements.push({ el: el, computedStyle: computedStyle, }); } }); } /** * Инициализирует компенсацию ширины полосы прокрутки, устанавливает отступы и высоту для `body`, * а также регулирует ширину и правый отступ фиксированных элементов. */ function t_scrollBarWidthCompensator__init() { if (window.isMobile || t_checkIsEditMode()) return; if (!window.scrollBarWidthCompensator) t_scrollBarWidthCompensator__setObject(); var obj = window.scrollBarWidthCompensator; obj.scrollBarWidth = Math.abs(window.innerWidth - document.documentElement.clientWidth); if (obj.cancelTimeout) { window.clearTimeout(obj.cancelTimeout); obj.cancelTimeout = null; } if (obj.isInited || !obj.scrollBarWidth) return; obj.isInited = true; var bodyComputedPadding = window.getComputedStyle(document.body).getPropertyValue('padding-right'); bodyComputedPadding = parseInt(bodyComputedPadding.replace('px', ''), 10); var bodyInlinePadding = document.body.style.paddingRight; if (bodyInlinePadding) { document.body.setAttribute('data-tilda-initial-padding-right', bodyInlinePadding); } document.body.style.paddingRight = obj.scrollBarWidth + bodyComputedPadding + 'px'; document.body.style.height = '100vh'; document.body.style.minHeight = '100vh'; document.body.style.overflow = 'hidden'; var transitionDurations = []; Array.prototype.forEach.call(obj.fixedElements, function (entry) { var el = entry.el; if (!document.body.contains(el) || el.classList.contains('t975') || el.classList.contains('t975')) return; var elParent = el.closest('.r'); var computedStyle = entry.computedStyle; var position = computedStyle.getPropertyValue('position'); if (position !== 'fixed' && position !== 'absolute') return; var duration = computedStyle.getPropertyValue('transition-duration'); if (duration.indexOf('ms') + 1) { duration = parseInt(duration.replace('ms', ''), 10); transitionDurations.push(duration); } else if (duration.indexOf('s') + 1) { duration = parseFloat(duration.replace('s', '')) * 1000; transitionDurations.push(duration); } var computedRight = computedStyle.getPropertyValue('right'); computedRight = parseInt(computedRight.replace('px', ''), 10); var elementInlineRight = el.style.right; if (elementInlineRight) { el.setAttribute('data-tilda-initial-right', elementInlineRight); } var inlineWidth = el.style.width; if (inlineWidth) { el.setAttribute('data-tilda-initial-width', inlineWidth); } var elZoom = (elParent && parseFloat(getComputedStyle(elParent).getPropertyValue('zoom'))) || 1; var scrollBarValue = obj.scrollBarWidth / elZoom; var { isFullscreenWidth, isFullscreenHeight, computedMarginNum } = t_scrollBarWidthCompensator__checkSize( computedStyle, obj.scrollBarWidth ); isFullscreenWidth = isFullscreenWidth || el.classList.contains('t-menu-popover_fullwidth') || (el.classList.contains('t-menu-popover') && elZoom > 1); if ( (computedRight || computedRight === 0) && el.style.right !== 'auto' && position !== 'absolute' && !isFullscreenWidth ) { el.style.right = scrollBarValue + computedRight + 'px'; } else if (isFullscreenWidth && !isFullscreenHeight) { el.style.width = `calc(100vw / ${window.isSafari ? 1 : elZoom} - ${computedMarginNum}px - ${scrollBarValue}px)`; } }); if (transitionDurations.length) { obj.delay = Math.max.apply(null, transitionDurations); } } /** * Проверяет полноэкранный ли элемент * * @param {CSSStyleDeclaration} computedStyle * @param {number} scrollBarWidth * @returns {{isFullscreenWidth: boolean, isFullscreenHeight: boolean, computedMarginNum: number}} */ function t_scrollBarWidthCompensator__checkSize(computedStyle, scrollBarWidth) { var { innerWidth, innerHeight } = window; var computedWidth = computedStyle.getPropertyValue('width'); var computedWidthNum = parseFloat(computedWidth) || 0; var computedHeight = computedStyle.getPropertyValue('height'); var computedHeightNum = parseFloat(computedHeight) || 0; var computedMarginLeft = computedStyle.getPropertyValue('margin-left'); var computedMarginLeftNum = parseFloat(computedMarginLeft) || 0; var computedMarginRight = computedStyle.getPropertyValue('margin-right'); var computedMarginRightNum = parseFloat(computedMarginRight) || 0; var computedMarginNum = computedMarginLeftNum + computedMarginRightNum; var isFullscreenWidth = computedWidth === '100%' || computedWidth === '100vw' || computedWidthNum === innerWidth || computedWidthNum === innerWidth - scrollBarWidth || computedWidthNum === innerWidth - computedMarginNum || computedWidthNum === innerWidth - computedMarginNum - scrollBarWidth; var isFullscreenHeight = computedHeight === '100%' || computedHeight === '100vh' || computedHeight === 'auto' || computedHeightNum === innerHeight || computedHeightNum === innerHeight - scrollBarWidth; return { isFullscreenWidth, isFullscreenHeight, computedMarginNum }; } /** * Отменяет компенсацию ширины полосы прокрутки, восстанавливает исходные стили `body` и фиксированных элементов. */ function t_scrollBarWidthCompensator__cancel() { var obj = window.scrollBarWidthCompensator; if (!obj || !obj.isInited) return; obj.isInited = false; obj.delay = 0; if (document.body.hasAttribute('data-tilda-initial-padding-right')) { document.body.style.paddingRight = document.body.getAttribute('data-tilda-initial-padding-right'); document.body.removeAttribute('data-tilda-initial-padding-right'); } else { document.body.style.removeProperty('padding-right'); } document.body.style.removeProperty('height'); document.body.style.removeProperty('min-height'); document.body.style.removeProperty('overflow'); Array.prototype.forEach.call(obj.fixedElements, function (entry) { var el = entry.el; var isAnimationWrapper = el.classList.contains('tn-atom__sticky-wrapper') || el.classList.contains('tn-atom__sbs-anim-wrapper'); if (el.hasAttribute('data-tilda-initial-right')) { el.style.right = el.getAttribute('data-tilda-initial-right'); el.removeAttribute('data-tilda-initial-right'); } else { el.style.removeProperty('right'); } if (el.hasAttribute('data-tilda-initial-width')) { el.style.width = el.getAttribute('data-tilda-initial-width'); el.removeAttribute('data-tilda-initial-width'); } else { el.style.removeProperty('width'); if (isAnimationWrapper) el.style.width = 'inherit'; } }); } /** * Запускает событие для элементов, совместимо с IE8+. * * @param {Node} el - Элемент, на котором инициируется событие. * @param {string} eventName - Имя события для запуска. */ function t_triggerEvent(el, eventName) { var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); } else if (document.createEventObject) { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; if (el.dispatchEvent) { el.dispatchEvent(event); } else if (el.fireEvent) { el.fireEvent('on' + event.eventType, event); } else if (el[eventName]) { el[eventName](); } else if (el['on' + eventName]) { el['on' + eventName](); } } function t_getRootZone() { const allrecords = document.getElementById('allrecords'); const rootZone = allrecords && allrecords.getAttribute('data-tilda-root-zone'); return rootZone || 'com'; } /** * Заменяет фиксированную rootzone в ссылке на динамическую. * @param {string} src */ function t_modifyRootZone(src) { if (!src || !src.includes('static.tildacdn.com')) { return src; } return src.replace('static.tildacdn.com', `static.tildacdn.${t_getRootZone()}`); } /** * Добавляет в head тэг script с указанной ссылкой. * @param {string} originalSrc * @param {function=} callback * @param {number=} retry номер текущей попытки повторной загрузки. Не нужно передавать снаружи, так как это технический параметр для контроля состояния. */ function t_loadJsFile(originalSrc, callback, retry = 0) { const MAX_RETRIES = 3; const RETRY_TIMEOUT_MULTIPLIER = 1000; const src = t_modifyRootZone(originalSrc); if (document.querySelector('script[src^="' + src + '"]')) { if (callback) { callback(); } return; } const script = document.createElement('script'); script.type = 'text/javascript'; script.src = src; if (callback) { script.addEventListener('load', () => { callback(); }); } script.addEventListener('error', errorEvent => { if (retry <= MAX_RETRIES) { setTimeout(() => { script.remove(); t_loadJsFile(src, callback, retry + 1); console.warn(`Retrying to load ${src}. Retry: ${retry + 1}`); }, retry * RETRY_TIMEOUT_MULTIPLIER); } else { const msg = errorEvent.message || ''; throw new Error(`Failed to load ${src} script: ${msg}`, { cause: errorEvent }); } }); document.head.appendChild(script); } /** * * Добавляет в head тэг link с указанной ссылкой. * @param {string} originalHref * @param {function=} callback * @param {number=} retry номер текущей попытки повторной загрузки. Не нужно передавать снаружи, так как это технический параметр для контроля состояния. */ function t_loadCSSFile(originalHref, callback, retry = 0) { const MAX_RETRIES = 3; const RETRY_TIMEOUT_MULTIPLIER = 1000; const href = t_modifyRootZone(originalHref); if (document.querySelector('link[href^="' + href + '"]')) { if (callback) { callback(); } return; } const link = document.createElement('link'); link.rel = 'stylesheet'; link.type = 'text/css'; link.media = 'all'; link.href = href; // Нужен, чтобы стили корректно отображались в мобильной версии редактора link.crossOrigin = 'anonymous'; if (callback) { link.addEventListener('load', callback); } link.addEventListener('error', errorEvent => { if (retry <= MAX_RETRIES) { setTimeout(() => { link.remove(); t_loadCSSFile(href, callback, retry + 1); console.warn(`Retrying to load ${href}. Retry: ${retry + 1}`); }, retry * RETRY_TIMEOUT_MULTIPLIER); } else { const msg = errorEvent.message || ''; throw new Error(`Failed to load ${href} style: ${msg}`, { cause: errorEvent }); } }); document.head.appendChild(link); } /** * @typedef TScrollToOptions * @prop {boolean} [useNativeScrollTo] * @prop {number} [duration] * @prop {'smooth' | 'instant'} [behavior] * @prop {number} [offset] */ /** * @param {Element} targetElem * @param {TScrollToOptions} options */ function t_scrollTo(targetElem, options) { if (!targetElem) return; const { useNativeScrollTo, duration, behavior = 'instant', offset = 0 } = options || {}; const targetYPos = Math.max(parseInt(targetElem.getBoundingClientRect().top + window.scrollY - offset, 10), 0); if (useNativeScrollTo || behavior === 'instant') { window.scrollTo({ left: 0, top: targetYPos, behavior, }); return; } t_smoothScrollTo(targetYPos, duration); } /** * Кастоманая реализация функции плавного скролла. * Нативная реализация через behavior: smooth работает не стабильно и вызывает недовольство пользователей. * @param {Number} targetY * @param {Number} duration */ function t_smoothScrollTo(targetY, duration = 500) { var body = document.body; var startY = window.scrollY || window.pageYOffset; var deltaY = targetY - startY; var startTime = performance.now(); function easeInOutQuad(t) { return Math.pow(t, 2); } function scroll() { var currentTime = performance.now(); var elapsedTime = Math.min((currentTime - startTime) / duration, 1); var ease = easeInOutQuad(elapsedTime); window.scrollTo(0, startY + deltaY * ease); if (elapsedTime < 1) { requestAnimationFrame(scroll); } else { body.removeAttribute('data-scroll'); body.removeAttribute('data-scrollable'); window.scrollTo(0, targetY); } } body.setAttribute('data-scroll', 'true'); body.setAttribute('data-scrollable', 'true'); requestAnimationFrame(scroll); }