const t396__parsedCssVarRegex = /var\((--uc-([^-]+)-([^-]+)-([^,]+)),\s?(.*)\)/; /** * Проверяет, является ли значение CSS-переменной глобального стиля. * @param {string} value CSS-переменная с глобальным стилем */ export function t396__isGlobalStyleCSSVar(value) { if (typeof value !== 'string') return false; const parsedVar = t396__parsedCssVarRegex.exec(value); if (!parsedVar) return false; const [, , type, field, id, fallback] = parsedVar; return Boolean(type && field && id && fallback); } /** * Если переданная переменная соответствует переменной глобального стиля, возвращает всю возможную информацию про нее. * @param value CSS-переменная с глобальным стилем */ export function t396__parseGlobalStyleCSSVar(value) { try { const parsedVar = t396__parsedCssVarRegex.exec(value); if (!parsedVar) return undefined; const [fullMatch, varName, type, field, id, fallback] = parsedVar; if (!fullMatch || !type || !field || !id || !fallback) return undefined; let actualFallback = fallback; // Ищем актуальное значение из CSS стилей, кроме случаев, когда находимся в редакторе zero if (window.tildamode !== 'zero') { const bodyStyle = window.getComputedStyle(document.body); actualFallback = bodyStyle.getPropertyValue(varName) || fallback; } return { parent: { id, type }, fallback: actualFallback, field }; } catch (e) { console.error('Error trying to parse CSS Variable'); } } /** * Конвертирует значение цвета из формата hex в формат RGBA * * @param {string} hexStr - цвет в формате hex * @param {string} opacity - коэффициент прозрачности * * @returns {Array} - массив RGBA */ export function t396__hex2rgba(hexStr, opacity) { if (!hexStr) return false; const cssVarData = t396__parseGlobalStyleCSSVar(hexStr); if (cssVarData) { hexStr = cssVarData.fallback; } const cleanHex = hexStr.replace(/#/, ''); if (cleanHex.length === 3) { const [r, g, b] = cleanHex; hexStr = '#' + r + r + g + g + b + b; } const hex = parseInt(hexStr.substring(1), 16); const r = (hex & 0xff0000) >> 16; const g = (hex & 0x00ff00) >> 8; const b = hex & 0x0000ff; return [r, g, b, parseFloat(opacity)]; } /** * @param {HTMLElement} element * @returns {boolean} */ export function t396__isElementUsingCalcZoom(element) { const availableElementTypes = ['gallery', 'map']; const elementType = element.getAttribute('data-elem-type'); return availableElementTypes.includes(elementType); } export function t396__isFlex(element) { const isArtboardFlex = element.classList.contains('t396__artboard-flex'); const isGroupFlex = element.classList.contains('t396__group-flex'); return isArtboardFlex || isGroupFlex; } /** * Если артборду задано значение overflow: visible, то необходимо общему блоку * задать overflow: hidden, чтобы не появлялся горизонтальный скролл всей страницы. * Если на странице присутствует элементы со sticky-позицией, задаём overflow: clip, * чтобы фиксация этих элементов работала корректно. */ export function t396__setOverflowToAllRecords() { const allRecords = document.getElementById('allrecords'); if (!allRecords) return; const stickyElementsSelectors = [ '.t951__sidebar_sticky', '.t1206__content_sticky', '.t754__col_fixed', '.t776__col_fixed', '.t786__col_fixed', '.t-store__prod-popup__col_fixed', '.t-catalog__sidebar_sticky', ]; t396__generateOverflowStyle(); const hasStickyElement = Boolean(document.querySelector(stickyElementsSelectors.join(', '))); allRecords.classList.remove('t-records__overflow-clip', 't-records__overflow-hidden'); allRecords.classList.add(hasStickyElement ? 't-records__overflow-clip' : 't-records__overflow-hidden'); } function t396__generateOverflowStyle() { if (document.getElementById('t396__overflow-styles')) return; const styles = document.createElement('style'); styles.id = 't396__overflow-styles'; styles.innerHTML = `.t-records__overflow-clip { overflow: clip; } .t-records__overflow-hidden { overflow: hidden; }`; document.head.appendChild(styles); } function t396__getArtboards(recType) { var allRecords = document.getElementById('allrecords'); var isEditMode = allRecords && allRecords.getAttribute('data-tilda-mode') === 'edit'; var selector = isEditMode ? `.record[data-record-type="${recType}"] .r:not(.t397__off, .t395__off, .t400__off) .t396__artboard, .record[data-parenttplid="${recType}"] .r:not(.t397__off, .t395__off, .t400__off) .t396__artboard` : `.r[data-record-type="${recType}"]:not(.t397__off, .t395__off, .t400__off) .t396__artboard, .r[data-parenttplid="${recType}"]:not(.t397__off, .t395__off, .t400__off) .t396__artboard`; return Array.from(document.querySelectorAll(selector)); } export function t396__getZeroBlocks() { var artboards = [...t396__getArtboards('396'), ...t396__getArtboards('121')]; if (!artboards.length) return []; var zeroBlockList = artboards.map(function (artboard) { return { record: artboard.closest('.r:not(.t397__off):not(.t395__off):not(.t400__off)'), artboard: artboard, }; }); return zeroBlockList.filter(function (zeroBlockObject) { return zeroBlockObject.record; }); } export function t396__isInsideGroupWithZoom(element) { let current = element.closest('.t396__group'); while (current) { if (current.style.zoom) { return true; } current = current.parentElement?.closest('.t396__group'); } return false; } /** * Генератор объявляется отдельно, чтобы была возможность подменять его в тестах. * * @returns {() => string} Функция генератор уникальных идентификаторов */ const t396__uniqueId__generator = () => { let idCounter = 0; return () => { idCounter += 1; const paddedCounter = String(idCounter).padStart(6, '0'); return `${Date.now()}${paddedCounter}`; }; }; /** * @returns {string} Уникальный идентификатор, состоящий из текущего времени и случайного числа */ export const t396__getUniqueId = t396__uniqueId__generator(); export function t396_isBlockVisible(rec) { var windowWidth = window.innerWidth; var screenMin = rec.getAttribute('data-screen-min'); var screenMax = rec.getAttribute('data-screen-max'); if (screenMin && windowWidth < parseInt(screenMin, 10)) return false; return !(screenMax && windowWidth > parseInt(screenMax, 10)); } /** * Собственная реализация для поддержки вызовы внутри редактора зеро. * @param {Function} callback */ export const t396__onReady = callback => { document.readyState !== 'loading' ? callback() : document.addEventListener('DOMContentLoaded', callback); }; let t396__htmlTextDecoder; /** * Декодирует HTML-сущности в чистый текст. * @param {string | undefined} html * @returns {string} */ export function t396__decodeHtmlText(html) { if (!html) return ''; if (!t396__htmlTextDecoder) t396__htmlTextDecoder = document.createElement('textarea'); t396__htmlTextDecoder.innerHTML = html; return t396__htmlTextDecoder.value; } /** * Возвращает данные для элемента формы * @param {HTMLElement} element * @returns */ export function t396_elem__getFormInputsValue(element) { const valueContainer = element.querySelector('.tn-atom__inputs-data'); if (valueContainer) { const data = valueContainer.getAttribute('data-value'); if (data) { try { return JSON.parse(data); } catch (error) { console.error('Error parsing form inputs data:', error, data); return []; } } } // fallback на старый метод передачи данных через textarea const textarea = element.querySelector('.tn-atom__inputs-textarea'); if (textarea) { const data = textarea.value; if (data) { try { return JSON.parse(data); } catch (error) { console.error('Error parsing form inputs textarea value:', error, data); return []; } } } return []; } export function t396_getEl(el) { if (window.jQuery && el instanceof jQuery) { return el.length ? el.get(0) : null; } else { return el; } } /** * В Safari 26.4 getBoundingClientRect/getClientRects начали возвращать координаты * с учётом CSS zoom (раньше zoom в них не учитывался). * Autoscale масштабирует элементы именно через zoom. * После этого изменения умножение задваивает масштаб, поэтому некоторые костыли больше не нужны. * * true — окружение, в котором zoom уже учтён в getBoundingClientRect. * * https://webkit.org/blog/17862/webkit-features-for-safari-26-4/ * https://bugs.webkit.org/show_bug.cgi?id=77998 */ function t396__doesClientRectIncludeZoom() { try { const ZOOM = 2; const SIZE = 50; const zoomed = document.createElement('div'); zoomed.style.cssText = `position:absolute;left:0;top:0;visibility:hidden;pointer-events:none;width:${SIZE}px;height:${SIZE}px;zoom:${ZOOM};`; document.body.appendChild(zoomed); const { width } = zoomed.getBoundingClientRect(); document.body.removeChild(zoomed); // В WebKit 26.4+ boundingClientRect возвращает значения с учетом zoom, до этой версии zoom не учитывался return width === SIZE * ZOOM; } catch (error) { return undefined; } } /** * Инициализирует глобальные флаги масштабирования для autoscale-артбордов: * - window.isOnlyScalable — браузер умеет только scalable-режим (старый Firefox < 126). * - window.shouldUseScaleFactor — getBoundingClientRect в этом браузере НЕ учитывает CSS zoom, * поэтому полученные из него значения нужно вручную домножать на scale factor. * * shouldUseScaleFactor становится false в браузерах, которые уже учитывают zoom в rect: * Chrome 128+ (стандартизация CSS zoom) и Safari 26.4+ (window.t396__clientRectIncludesZoom). */ export function t396__initScaleFactorFlags() { if (typeof window.shouldUseScaleFactor !== 'undefined') { return; } if (typeof window.t396__clientRectIncludesZoom === 'undefined') { window.t396__clientRectIncludesZoom = t396__doesClientRectIncludeZoom(); } const isFirefox = window.navigator.userAgent.match(/Firefox\/([0-9]+)\./); const firefoxVersion = isFirefox ? parseInt(isFirefox[1], 10) : 126; const chromeMatch = window.navigator.userAgent.match(/Chrome\/([0-9]+)\./); const chromeVersion = (chromeMatch && parseInt(chromeMatch[1], 10)) || 0; const clientRectIncludesZoom = chromeVersion > 127 || window.t396__clientRectIncludesZoom; window.isOnlyScalable = firefoxVersion < 126; window.shouldUseScaleFactor = !window.isOnlyScalable && !isFirefox && !clientRectIncludesZoom; }