/** * @typedef {Object} BasicAutoscaleSettings * @property {'.t-record_scaled'} scaledRecordSelector - CSS-селектор масштабируемых записей * @property {'data-height-in-vh'} dynamicHeightAttribute - data-атрибут для динамической высоты в vh * @property {HTMLElement|null} allRecords - контейнер всех записей * @property {[1200, 960, 640, 480, 360]} breakpoints - контрольные точки сетки в px (по убыванию) * @property {'--t-zoom'} variableName - CSS-переменная для значения зума * @property {boolean} isWindowsOS - флаг ОС Windows (для корректной обработки дробных значений зума) */ t_onReady(t_autoscale__init); function t_autoscale__init() { const { scaledRecordSelector, allRecords } = t_autoscale__getAutoscaleData(); if (!document.querySelector(scaledRecordSelector)) return; t_autoscale__appendTextStylesForSafari(); t_autoscale__setGeneralStyles(); t_autoscale__setZoomValue(); /** * Для Safari значения с vh рассчитываются без учёта заданного zoom-значения, * поэтому для этих браузеров не нужно переназначать значение динамической высоты. */ const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); if (!isSafari) t_autoscale__processDynamicHeight(); t_autoscale__processMapsAndVideos(); t_autoscale__updateCoverHeight(); t_autoscale__triggerSliderUpdate(); // обновление зум-значения после инициализации бокового отступа для обертки блоков по событию allRecPaddingInit allRecords?.addEventListener('allRecPaddingInit', t_autoscale__setZoomValue); window.addEventListener('load', t_autoscale__setZoomValue); t_autoscale__updateOnResize(); } function t_autoscale__appendTextStylesForSafari() { const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); const styleId = 'tilda-autoscale-text-style'; if (!isSafari || document.getElementById(styleId)) return; const { scaledRecordSelector } = t_autoscale__getAutoscaleData(); const style = document.createElement('style'); style.id = styleId; style.textContent = ` ${scaledRecordSelector} .t-card__descr, ${scaledRecordSelector} .t-card__title, ${scaledRecordSelector} .t-title, ${scaledRecordSelector} .t-descr, ${scaledRecordSelector} .t-uptitle, ${scaledRecordSelector} .t-btntext { -webkit-text-size-adjust: auto; } `; document.head.appendChild(style); } function t_autoscale__updateOnResize() { let lastWidth = document.documentElement.clientWidth; const observer = new ResizeObserver(() => { const currentWidth = document.documentElement.clientWidth; if (currentWidth === lastWidth) return; lastWidth = currentWidth; requestAnimationFrame(() => t_autoscale__setZoomValue()); }); observer.observe(document.documentElement); } /** * @returns {BasicAutoscaleSettings} */ function t_autoscale__getAutoscaleData() { return { scaledRecordSelector: '.t-record_scaled', dynamicHeightAttribute: 'data-height-in-vh', allRecords: document.getElementById('allrecords'), breakpoints: [1200, 960, 640, 480, 360], variableName: '--t-zoom', isWindowsOS: navigator.userAgent.toLowerCase().includes('win'), }; } function t_autoscale__setZoomValue() { const styleId = 'tilda-autoscale-style'; const alreadyExistedStyle = document.getElementById(styleId); const { scaledRecordSelector, variableName, breakpoints, allRecords, isWindowsOS } = t_autoscale__getAutoscaleData(); const style = alreadyExistedStyle || document.createElement('style'); if (!alreadyExistedStyle) style.id = styleId; style.textContent = ` ${scaledRecordSelector} { ${variableName}: ${getZoomValue(isWindowsOS)}; }`; if (!alreadyExistedStyle) document.head.appendChild(style); /** * При наличии скроллбара, возможен кейс при котором gridWidth может быть * больше фактической ширины экрана с вычетом ширины скроллбара. * Поэтому при расчете брейкпоинта, ориентируемся на window.innerWidth. * Так же зум-значение может быть меньше 1 при наличии вертикального скроллбара, * когда фактическая ширина экрана равна, например, 1190, а брейкпоинт 1200. * * @param {boolean} isWindowsOS * @returns {number} */ function getZoomValue(isWindowsOS) { const leftOffset = (allRecords && parseInt(getComputedStyle(allRecords).paddingLeft, 10)) || 0; const rightOffset = getRightOffset(); const offsetX = leftOffset + rightOffset; const hasScrollbar = Math.abs(window.innerWidth - document.documentElement.clientWidth) > 1 || rightOffset > 0; const windowFullWidth = window.innerWidth - offsetX; const windowWidth = document.documentElement.clientWidth - offsetX; const gridWidth = breakpoints.find(breakpoint => windowFullWidth > breakpoint); if (!gridWidth) return 1; const zoomValue = Math.round((windowWidth / gridWidth) * 100000) / 100000; const processedZoomValue = (hasScrollbar ? zoomValue : Math.max(zoomValue, 1)) || 1; const decimal = isWindowsOS ? 2 : 5; return getTruncatedValue(processedZoomValue, decimal); } /** * При открытии попапа нужно учесть отступ, который задаётся для body справа * @returns {number} */ function getRightOffset() { if (!document.body.classList.contains('t-body_popupshowed')) return 0; return parseInt(getComputedStyle(document.body).paddingRight, 10) || 0; } /** * Для Windows обрезаем значение до 2-х знаков после запятой, чтобы избежать проблем с рендерингом * @param {number} value * @param {number} decimal * @returns {number} */ function getTruncatedValue(value, decimal) { if (!value) return 1; return Math.floor(value * Math.pow(10, decimal)) / Math.pow(10, decimal); } } function t_autoscale__setGeneralStyles() { const styleId = 'tilda-autoscale-main-style'; if (document.getElementById(styleId)) return; const { scaledRecordSelector, variableName, breakpoints } = t_autoscale__getAutoscaleData(); const style = document.createElement('style'); style.textContent = breakpoints .slice() .reverse() .map(gridWidth => { return `@media (min-width: ${gridWidth}px) { ${scaledRecordSelector} { max-width: ${gridWidth}px; } }`; }) .join(' '); style.textContent += `@media (min-width: ${Math.min(...breakpoints)}px) { ${scaledRecordSelector} { zoom: var(${variableName}, 1); } }`; style.id = styleId; document.head.appendChild(style); } /** * Для динамической высоты, заданной в vh, необходимо сохранять значение, которое задаёт пользователь, * поэтому уменьшаем его на зум-значение, чтобы 100vh соответствовали 100% высоты экрана. */ function t_autoscale__processDynamicHeight() { const { scaledRecordSelector, dynamicHeightAttribute, variableName } = t_autoscale__getAutoscaleData(); const allDynamicHeightElements = document.querySelectorAll(`${scaledRecordSelector} [${dynamicHeightAttribute}]`); allDynamicHeightElements.forEach(element => { if (element.classList.contains('t-map')) return; const currentHeight = element.getAttribute(dynamicHeightAttribute); if (!currentHeight) return; const currentProperty = getCurrentProperty(element); element.style.setProperty(currentProperty, `calc(${currentHeight}vh / var(${variableName}, 1))`); }); function getCurrentProperty(element) { if (element.style.getPropertyValue('--height') && element.style.getPropertyValue('--height').includes('vh')) { return '--height'; } if (element.style.minHeight && element.style.minHeight.includes('vh')) return 'min-height'; if (element.style.maxHeight && element.style.maxHeight.includes('vh')) return 'max-height'; return 'height'; } } /** * Некоторые элементы при наличии свойства zoom некорректно масштабируются, поэтому для них зум будет сброшен */ function t_autoscale__processMapsAndVideos() { const { scaledRecordSelector, variableName } = t_autoscale__getAutoscaleData(); const selector = `${scaledRecordSelector} .t-video-lazyload, ${scaledRecordSelector} .t-map`; const toProcessScaleElements = document.querySelectorAll(selector); toProcessScaleElements.forEach(element => { element.style.zoom = `calc(1 / var(${variableName}, 1))`; t_autoscale__setElementHeight(element, variableName); }); } function t_autoscale__setElementHeight(element, variableName) { const height = t_autoscale__getElementHeight(element, variableName); if (height) element.style.height = height; } /** * 1) Если высота не задана инлайн - значит преобразование не было задано из скрипта или TPL - ничего не делаем * 2) Если высота содержит vh без лишних преобразований - ничего не делаем (ориентируемся на фактическую высоту экрана) * 3) Если высота содержит calc с vh - значит на стороне TPL или скрипта блока было преобразование, * которое нужно отключить - в этом случае забираем vh и применяем его, он и будет истинным значением. * * @param {HTMLElement} element * @param {'--t-zoom'} variableName * @returns {string} */ function t_autoscale__getElementHeight(element, variableName) { const height = element.style.height; if (!height) return ''; const isVH = height.includes('vh'); const isContainsScale = height.includes('calc(') && height.includes(`var(${variableName}, 1)`); if (isVH && !isContainsScale) return ''; if (isContainsScale && isVH) { const regex = /\d+(?=px|vh)/; const match = height.match(regex); if (match && match[0]) return `${match[0]}vh`; return ''; } return !isVH && parseFloat(height) ? `calc(${parseFloat(height)}px * var(${variableName}, 1))` : ''; } /** * Если у обложек задалось свойство высоты с учётом зума до того, как зум был определён, * необходимо триггернуть пересчет высоты обложки. */ function t_autoscale__updateCoverHeight() { const { scaledRecordSelector } = t_autoscale__getAutoscaleData(); const scaledCoverElements = document.querySelectorAll(`${scaledRecordSelector} .t-cover__carrier`); scaledCoverElements.forEach(element => { element.dispatchEvent(new Event('displayChanged')); }); } /** * Некоторые галереи, расположенные на всю ширину экрана, могут вычислить размеры и положение слайдов * до применения итогового zoom-значения. После автоскейла это может приводить к некорректной ширине * контейнера или смещению элементов, поэтому для .t-slds__container вручную диспатчится событие * displayChanged, чтобы галерея пересчитала отображение с учётом актуального масштаба. */ function t_autoscale__triggerSliderUpdate() { const { scaledRecordSelector } = t_autoscale__getAutoscaleData(); const scaledSlideWrappers = document.querySelectorAll(`${scaledRecordSelector} .t-slds__container`); scaledSlideWrappers.forEach(element => { element.dispatchEvent(new Event('displayChanged', { bubbles: true })); }); }