// @ts-check /** * Универсальный блок для списка товаров из каталога (ST340) * * tilda-catalog работает во всех блоках категории ST (store), а также на отдельных страницах товаров, подключенных к каталогу **/ import { t_cart__useRootZone } from '../src/tilda-cart/shared/rootZone/index.ts'; import { t_catalog_header__updateHeaderFromPartInfo } from '../src/tilda-catalog/block-header/index.ts'; import { t_catalog__isEditMode, t_catalog__isPublishedMode } from '../src/tilda-catalog/shared/page-mode/index.ts'; import { t_catalog__getRecUrlParam, t_catalog__getRecUrlParams, t_catalog__hasRecUrlParams, t_catalog__paramsToObj, t_catalog__updateOptionsBasedOnUrl, } from '../src/tilda-catalog/shared/url-params/index.ts'; import { t_catalog__loadCatalogSlds, t_catalog__loadHoverZoom, t_catalog__loadTildaCatalogFilters, t_catalog__loadTildaCatalogPagination, t_catalog__loadTildaCatalogTabs, t_catalog__loadTooltipster, } from '../src/tilda-catalog/shared/loadFiles/index.ts'; import { t_catalog__cleanPrice, t_catalog__getFormattedMinPrice, t_catalog__getFormattedPrice, t_catalog__getFormattedPriceRange, } from '../src/tilda-catalog/shared/price-format/index.ts'; import { t_catalog__hidePreloader } from '../src/tilda-catalog/preloader/index.ts'; import { t_catalog_stickySidebarInit } from '../src/tilda-catalog/sticky-sidebar/index.ts'; import { t_catalog_hiddenSidebarInit } from '../src/tilda-catalog/hidden-sidebar/index.ts'; import { initBreadcrumbs, updateBreadcrumbs } from '../src/tilda-catalog/breadcrumbs/index.ts'; import { initProductPopupBreadcrumbs, initProductSnippetBreadcrumbs } from '../src/tilda-catalog/breadcrumbs/popup.ts'; import { t_catalog__setGlobalDictObj } from '../src/tilda-catalog/dict/catalog.ts'; import { t_catalog__getBrowserLang } from '../src/tilda-catalog/dict/lang.ts'; import { t_catalog_filters__getVisibilityFlags } from '../src/tilda-catalog/filters/filtersVisibility.ts'; import { isNewPartsUsed } from '../src/tilda-catalog/parts/isNewPartsUsed.ts'; // TODO ST-2949_7: JSDoc and JS↔TS interop (TS2314, TS8021, TS8024, TS8032, TS1127, TS18042) // @ts-expect-error ST-2949_7 import { CatalogOptions } from '../src/tilda-catalog/types/catalog.ts'; // @ts-expect-error ST-2949_7 import { Product, ProductEdition } from '../src/tilda-catalog/types/product.ts'; import { getInitialEdition as t_catalog_product_getInitialEdition, createEditionsState as t_catalog_createEditionsState, EditionsWidget as t_catalog_EditionsWidget, createOptionsState as t_catalog_createOptionsState, OptionsWidget as t_catalog_OptionsWidget, createQuantityState as t_catalog_createQuantityState, QuantityWidget as t_catalog_QuantityWidget, mountComponent as t_catalog_mountComponent, unmountComponent as t_catalog_unmountComponent, } from '../src/tilda-catalog/components/index.module.ts'; import { t_catalog__getCardTemplateNode, t_catalog__getProductCardTemplate, t_catalog__bindBgUpOverlayOffsetListeners, t_catalog__updateBgUpOverlayOffsets, t_catalog__cardNeedsImagePlaceholder, t_catalog__emptyProductCardImageHtml, t_catalog__insertProductCardImageHtml, } from '../src/tilda-catalog/card-template/index.module.ts'; import { t_catalog__prepareCardButton } from '../src/tilda-catalog/card-template/prepare-card-button.ts'; import { t_catalog__resolveCardButtonSize } from '../src/tilda-catalog/card-template/card-button-size.ts'; import { t_catalog__addVideoIconForGallery, t_catalog__getVideoElement, t_catalog__svgVideoIcon, } from '../src/tilda-catalog/gallery-video/index.ts'; import { unescapeHtml as t_catalog_unescapeHtml } from '../src/tilda-catalog/shared/unescapeHtml/index.ts'; import { isTester } from '../src/shared/isTester/index.ts'; import { hydrateCatalogGalleries, selectCatalogGalleryImage } from '../src/tilda-catalog/card-image-gallery/index.ts'; import { t_catalog__markProductSlidesForLazyLoad } from '../src/tilda-catalog/product-gallery/lazy-slides.ts'; import { t_catalog__initTileSlider } from '../src/tilda-catalog/tile-slider/index.ts'; import { t_catalog__resolveProductsSort } from '../src/tilda-catalog/shared/sort/index.ts'; import { t_catalog_addProductQuantityEvents } from '../src/tilda-catalog/components/quantity/initializeStaticQuantityControls.ts'; import { t_catalog_editCache__getKey, t_catalog_editCache__remember, t_catalog_editCache__respond, } from '../src/tilda-catalog/shared/edit-cache/index.ts'; import { t_catalog_productTemplate__initPopup, t_catalog_productTemplate__initPopupShell } from '../src/tilda-catalog/product-template/popup.ts'; import { t_catalog_productTemplate__initSnippet } from '../src/tilda-catalog/product-template/snippet.ts'; import { t_catalog_productTemplate__updateEditionCharacteristics } from '../src/tilda-catalog/product-template/hydrate.ts'; // Expose for t_onFuncLoad from block templates (ST340 tile slider) // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.t_catalog__initTileSlider = t_catalog__initTileSlider; // ST350 (T1301) выводит контролы количества серверной разметкой и использует этот инициализатор. // @ts-expect-error ST-2949_1 window.t_catalog_addProductQuantityEvents = t_catalog_addProductQuantityEvents; // global variables declaration // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) window.tCatalogIsSearchBot = /Bot/i.test(navigator.userAgent); // @ts-expect-error ST-2949_1 window.tCatalogIsMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); // Карта флагов первой загрузки данных для каждого блока каталога {recid: boolean) // @ts-expect-error ST-2949_1 window.tCatalogFirstLoadStates = {}; // Настройки фильтров для каждого блока каталога {recid: Object} // @ts-expect-error ST-2949_1 window.tCatalogFilters = {}; // Данные о разделах каталога для каждого блока {recid: Object} window.tCatalogParts = {}; // Общий список опций каталога Object[], он одинаковый для всего проекта (может быть инициализирован в сниппете) window.tCatalogOptionsList = window.tCatalogOptionsList || null; // UID раздела, для которого загружаются фильтры и процее для каждого блока {recid: Object} window.tCatalogInitialStorepartUid = {}; // UID раздела "Все" window.tCatalogAllStorepartUid = {}; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.t_catalog_endpoint = 'store.tildaapi.com'; // UID раздела, выбранного в настройках блока для каждого блока {recid: Object} (по нему строиться навигация по разделам) // @ts-expect-error ST-2949_1 window.tCatalogInitialRootStorepartUid = {}; const t_catalog_POPUP_SHOWED_EVENT_NAME = 'catalog:popupShowed'; const t_catalog_POPUP_CLOSED_EVENT_NAME = 'catalog:popupClosed'; // Вариант, выбранный по фильтру, должен менять картинку даже при скрытых опциях /** @type {WeakSet} */ const t_catalog__filterSyncProducts = new WeakSet(); const T_CATALOG_TPRODUCT_PATTERNS = [ '#!/tproduct/', '%23!/tproduct/', '#%21%2Ftproduct%2F', '#!%2Ftproduct%2F', '%23%21%2Ftproduct%2F', ]; t_onReady(function () { t_catalog__setupEndpoint(); t_catalog__setGlobalDictObj(); // Селектор только у карточек из нового шаблона, на старой вёрстке это no-op. t_catalog__bindBgUpOverlayOffsetListeners(); }); /** * Инициализирует сниппет товара из общего шаблона на странице товара. * Вызывается init-скриптом template с настройками блока из Smarty (tpl_catalog_setup_options.tpl); * данные товара берутся из `script.js-catalog-product-init-data` в блоке. * * @param {string} recid * @param {CatalogOptions} options */ function t_catalog_productTemplateInit(recid, options) { t_onReady(function () { t_catalog_productTemplate__initSnippet(recid, options); }); } /** * Инициализация блоков с списком карточек товаров * * @param {string} recid * @param {CatalogOptions} options **/ function t_catalog_init(recid, options) { t_onReady(function () { const BLOCKS_COUNT_FOR_LAZY_INIT = 7; var rec = document.getElementById('rec' + recid); if (!rec) return; // eslint-disable-next-line no-param-reassign options = options || {}; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (!window.tCatalogInit) { // @ts-expect-error ST-2949_1 window.tCatalogInit = {}; } // @ts-expect-error ST-2949_1 window.tCatalogInit[recid] = true; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 window.tCatalogInitialStorepartUid[recid] = options.storepart; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (!window.tCatalogInitialRootStorepartUid[recid]) { // @ts-expect-error ST-2949_1 window.tCatalogInitialRootStorepartUid[recid] = options.storepart; } const allRecords = document.getElementById('allrecords'); if (allRecords) { t_catalog__setupEndpoint(); } var shouldUseLazyObserver = 'IntersectionObserver' in window && // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 Object.keys(window.tCatalogInit).length > BLOCKS_COUNT_FOR_LAZY_INIT; if (shouldUseLazyObserver) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.tCatalogInit[recid] = 'lazy'; var recordObserver = new IntersectionObserver( function (entries, observer) { entries.forEach(function (entry) { if (entry.isIntersecting) { var target = entry.target; observer.unobserve(target); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (window.tCatalogInit[recid] === 'lazy') { t_catalog_lazyInit(recid, options); // @ts-expect-error ST-2949_1 window.tCatalogInit[recid] = true; } } }); }, { rootMargin: '150px 0px', } ); recordObserver.observe(rec); } else { t_catalog_lazyInit(recid, options); } }); } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_lazyInit(recid, opt) { var options = opt || {}; var rec = document.getElementById('rec' + recid); var isSnippet = document.getElementById('allrecords') !== document.querySelector('.t-catalog__product-snippet') && // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 document.getElementById('allrecords').contains(document.querySelector('.t-catalog__product-snippet')); // ST-2522: сбрасывает внешние отступы кнопок в карточке товара. // Класс только если в блоке есть новый шаблон карточки — старые опубликованные страницы его не получают. if (t_catalog__getCardTemplateNode(rec)) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 const catalogRoot = rec.querySelector('.t-catalog'); if (catalogRoot) { catalogRoot.classList.add('t-catalog_card-template'); } } if (!isSnippet) { t_catalog_initRouting(); } if (!window.tCatalogDict) { t_catalog__setGlobalDictObj(); } // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var el_store = rec.querySelector('.js-catalog'); if (rec && !t_catalog_productTemplate__initPopupShell(rec, options)) { var prodPopup = t_catalog_get_productPopup_html(recid, options); if (el_store) { el_store.insertAdjacentHTML('beforeend', prodPopup); } } options.isPublishedPage = t_catalog__isPublishedMode(); options.needGetPartInfo = true; // draw product popup if we have it in URL if (options.isPublishedPage) { t_catalog_checkUrl(options, recid); } var recParent = document.getElementById('record' + recid); if (recParent && !options.isPublishedPage) { var off = recParent.getAttribute('off'); if (off == 'y') { return; } } // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var gridPreloader = rec.querySelector('.js-catalog-grid-cont-preloader'); if (options.storepart === '') { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 gridPreloader.style.display = 'none'; if (options.sidebar) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var tCatalogGridContainer = rec.querySelector('.t-catalog__grid-cont'); if (tCatalogGridContainer) { tCatalogGridContainer.classList.remove('t-catalog__grid-cont_hidden'); } } return; } var slice = 1; var customUrlParams = {}; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 var optsBasedOnURL; // show loader in 1s setTimeout(function () { if (gridPreloader) { gridPreloader.classList.remove('t-catalog__grid-cont-preloader_hidden'); } }, 1000); // before load Products check url for filters params customUrlParams = t_catalog__paramsToObj(recid, options); // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 if (customUrlParams[recid]) { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 optsBasedOnURL = t_catalog__updateOptionsBasedOnUrl(options, customUrlParams, recid); if (optsBasedOnURL) { options = optsBasedOnURL; } } if (options.sidebar) { // add sidebar wrapper for a positioning purpose // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var sidebar = rec.querySelector('.js-catalog-parts-select-container'); if (sidebar) { var el_sidebar = sidebar.querySelector('.t-catalog__sidebar'); if (!el_sidebar) { const wrappers = `
`; sidebar.insertAdjacentHTML('beforeend', wrappers); } if (rec && sidebar.classList.contains('t-catalog__sidebar_sticky')) { t_catalog_stickySidebarInit(rec); } if ( rec && (sidebar.classList.contains('t-catalog__sidebar_pos_hidden-left') || sidebar.classList.contains('t-catalog__sidebar_pos_hidden-right')) ) { t_catalog_hiddenSidebarInit(rec); } } } var drawAllProductsGrid = function () { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 if (customUrlParams[recid] && customUrlParams[recid].page) { // Check if page is in URLParams // Data could be stored as array :( // @ts-expect-error ST-2949_2 slice = Array.isArray(customUrlParams[recid].page) ? // @ts-expect-error ST-2949_2 customUrlParams[recid].page.join('') : // @ts-expect-error ST-2949_2 customUrlParams[recid].page; } // draw all products grid // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog_loadProducts('', recid, options, slice); t_catalog_mobileHoriz_checkBtnVisibility(recid, options); }; var onLoadFilters = function () { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 if (customUrlParams[recid] && optsBasedOnURL) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 rec.addEventListener('controlsDrawn', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog_filters_render_selected(options, recid); }); } if (options.sidebar) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 rec.addEventListener('controlsDrawn', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog_filters_opts_sort(options, recid); }); } if (options?.breadcrumbs?.hasBreadcrumbs) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 rec.addEventListener('controlsDrawn', function () { t_catalog_breadcrumbs__init(recid, options); }); } // Set proper slice if it has been set on URL slice = 1; drawAllProductsGrid(); }; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 var onDoneGetFilters = function (data) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (!window.tCatalogFilters) { // @ts-expect-error ST-2949_1 window.tCatalogFilters = {}; } if (data && ((data.filters && data.filters.length > 0) || data.search || data.sort)) { // @ts-expect-error ST-2949_1 window.tCatalogFilters[recid] = data; t_catalog__loadTildaCatalogFilters() .then(() => onLoadFilters()) .catch(() => drawAllProductsGrid()); t_catalog__loadTooltipster(); } else { drawAllProductsGrid(); } }; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_loadFilters(options, onDoneGetFilters, function (error) { t_catalog_changeEndpoint(error, function () { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog_loadFilters(options, onDoneGetFilters); }); }); if (options.isHorizOnMob && options.prodCard.listStyle === 'tile') { var handIcon = t_catalog_get_handIcon_html(recid, options.horizontalScrollHint); if (gridPreloader) { gridPreloader.insertAdjacentHTML('beforebegin', handIcon); } } if (options.tabs) { t_catalog__loadTildaCatalogTabs(); } if (options.showPagination && options.showPagination === 'on') { t_catalog__loadTildaCatalogPagination(); } t_onFuncLoad('t_throttle', function () { window.addEventListener( 'resize', t_throttle(function () { if (!rec) return; if (options.prodCard.listStyle === 'list') { t_catalog_unifyCardsWidth(recid); } t_catalog_loadMoreBtn_display(recid); if (options.sidebar || Object.keys(options.filters || {}).length > 1) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 const data = window.tCatalogFilters[recid]; const { shouldShowSearchSort } = t_catalog_filters__getVisibilityFlags(options, data); if (!shouldShowSearchSort) { t_catalog_moveSearhSort(recid, options); } } if (options.showPagination && options.showPagination === 'on') { t_catalog_onFuncLoad('t_catalog_pagination_display', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog_pagination_display(recid); }); } }) ); }); // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var tStore = rec.querySelector('.t-catalog'); if (tStore) { tStore.addEventListener('displayChanged', function () { setTimeout(function () { t_catalog_unifyCardsWidth(recid); }); }); } if (options.popup_opts.fixedButton) { t_catalog_fixedPopupButton(recid, options); } } /** * Разделяет URL на базовую часть и tproduct-хеш, если он присутствует * @param {string} url - исходный адрес * @returns {{pattern: string, baseUrl: string, hash: string}|null} */ function t_catalog__splitProductUrl(url) { if (!url) return null; const pattern = t_catalog__findBlockProductPatternInUrl(url); if (!pattern) return null; const index = url.indexOf(pattern); if (index === -1) return null; return { pattern, baseUrl: url.slice(0, index), hash: url.slice(index), }; } /** * Возвращает базовый URL без tproduct-хеша и лишнего якоря * @param {string} url - исходный адрес * @returns {string} */ function t_catalog__normalizeBaseUrl(url) { if (!url) return ''; const split = t_catalog__splitProductUrl(url); if (split) return split.baseUrl || url.split('#')[0]; return url.split('#')[0]; } /** * Сохраняет исходный адрес в глобальное состояние и заголовок страницы перед открытием попапа * @param {boolean} [force] - признак принудительного сохранения * @returns {void} */ function t_catalog__setInitialUrl(force = false) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 const hasStoredUrl = !!window.urlBeforePopupOpen; // @ts-expect-error ST-2949_1 const storedHasProductPattern = hasStoredUrl && t_catalog__findBlockProductPatternInUrl(window.urlBeforePopupOpen); if (!hasStoredUrl || storedHasProductPattern || force) { // @ts-expect-error ST-2949_1 window.urlBeforePopupOpen = t_catalog__normalizeBaseUrl(window.location.href) || window.location.href; } // @ts-expect-error ST-2949_1 if (!window.titleBeforePopupOpen) { // @ts-expect-error ST-2949_1 window.titleBeforePopupOpen = document.title; } } /** * Создает объект состояния истории для открытия товара в попапе * @param {Object} productObj - данные товара * @param {Object} options - настройки каталога * @param {boolean} isRelevantsShow - признак открытия из блока релевантов * @param {string} recid - идентификатор блока * @returns {{productData: {productObj: Object, opts: Object, isRelevantsShow: boolean, recid: string}}} */ function t_catalog__createProductHistoryState(productObj, options, isRelevantsShow, recid) { return { productData: { productObj: productObj, opts: options, isRelevantsShow: !!isRelevantsShow, recid: recid, }, }; } /** * Применяет состояние истории с учетом дополнительных опций * @param {Object} state - сохраняемое состояние * @param {string|null} title - заголовок страницы * @param {string} url - целевой адрес * @param {{replace?: boolean, syncCanonical?: boolean, updateDocumentTitle?: boolean}} [params] * @returns {void} */ function t_catalog__applyHistoryState(state, title, url, params = {}) { const method = params.replace ? 'replaceState' : 'pushState'; try { if (typeof history[method] === 'undefined') return; // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 history[method](state, title, url); if (params.syncCanonical) { var canonical = document.querySelector('head link[rel="canonical"]'); if (canonical && url) { canonical.setAttribute('href', url); } } if (params.updateDocumentTitle && typeof title === 'string') { document.title = title; } } catch (error) { console.error(error); } } /** * Initialize the product from Snippet * * @param {string} recid * @param {object} options * @param {object} product - the options of product **/ function t_catalog_productInit(recid, options, product) { t_onReady(function () { const allRecords = document.getElementById('allrecords'); if (allRecords) { t_catalog__setupEndpoint(); } t_catalog_snippet_initProduct(recid, options, product); }); } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_snippet_initProduct(recid, options, product) { var rec = document.querySelector('#rec' + recid); // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var el_product = rec.querySelector('.t-catalog__product-snippet.js-catalog-product'); // @ts-expect-error ST-2949_3 el_product.setAttribute('data-card-size', 'large'); var urlSearch = t_catalog_snippet_getJsonFromUrl(); if (options.popup_opts.popupContainer === '100') { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var productContainer = el_product.querySelector('.t-container'); // @ts-expect-error ST-2949_3 productContainer.classList.add('t-container_fluid'); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 productContainer.style.maxWidth = '100%'; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 if (productContainer.firstElementChild) { // @ts-expect-error ST-2949_3 productContainer.firstElementChild.classList.add('t-container_fluid'); } } t_catalog_snippet_copyTypographyToSnippet(recid, options); t_catalog_drawProdPopup_drawGallery(recid, el_product, product, options); // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 initProductSnippetBreadcrumbs(recid, el_product, product, options); var addOptionsAndChooseEdition = function () { // @ts-expect-error ST-2949_5 t_catalog_addProductOptions(recid, product, el_product, options, 'largecard'); t_catalog_snippet_chooseEditionFromUrl(recid, product, el_product, options); t_catalog_onFuncLoad('t_prod__init', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_prod__init(recid); }); }; if (!window.tCatalogDict) { t_catalog__setGlobalDictObj(); } // Snippet relevants title fallback (same logic as popup) // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var relevantsTitle = rec.querySelector('.t-catalog__relevants__title'); // @ts-expect-error ST-2949_3 if (relevantsTitle && !relevantsTitle.textContent.trim()) { // @ts-expect-error ST-2949_3 relevantsTitle.textContent = options.titleRelevants ? options.titleRelevants : window.tCatalogDict['seeAlso']; if (Object.prototype.hasOwnProperty.call(options.typo, 'title') && options.typo.title) { relevantsTitle.setAttribute('style', options.typo.title); } } // add SKU text // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var storeProdSKU = el_product.querySelector('.js-catalog-prod-sku'); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (storeProdSKU && storeProdSKU.style.display !== 'none') { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 storeProdSKU.insertAdjacentHTML('beforebegin', window.tCatalogDict['sku'] + ': '); } // add gen-uid (for discounts) if this product has parent product // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 el_product.setAttribute('data-product-gen-uid', product.uid); // add part-uid (for discounts) if this product has parts // @ts-expect-error ST-2949_3 el_product.setAttribute('data-product-part-uid', product.partuids ? product.partuids.join(',') : ''); if (options.tabs) { t_catalog__loadTildaCatalogTabs().then(() => { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog_tabs_initSnippet(recid, options, el_product, product); addOptionsAndChooseEdition(); }); } else { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog_initTextAndCharacteristics(el_product, product); addOptionsAndChooseEdition(); } t_catalog_triggerEvent(document.body, 'twishlist_addbtn'); if (!options.relevants_slider) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var mobileRow = rec.querySelector('.t-catalog__relevants-grid-cont.t-catalog__grid-cont_mobile-one-row'); if (mobileRow) { var handIcon = t_catalog_get_handIcon_html(recid, options.horizontalScrollHint); mobileRow.insertAdjacentHTML('beforebegin', handIcon); } } if (options.popup_opts.fixedButton) { t_catalog_fixedPopupButton(recid, options); } t_catalog_applyButtonStyles(recid, options); t_catalog_renderSnippetButtonIcon(recid, options); t_catalog_hoverZoom_init(recid); t_catalog_get_productPopup_closeIcon_color(recid, options); // отправка данных в Tilda об открытии страницы с товаром setTimeout(function () { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (!window.tCatalogIsSearchBot && window.Tilda && typeof Tilda.sendEcommerceEvent === 'function') { // @ts-expect-error ST-2949_1 if (!urlSearch.editionuid) { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 Tilda.sendEcommerceEvent('detail', [ { id: '' + (product.id ? product.id : product.uid), uid: '' + product.uid, price: '' + (product.price_min ? product.price_min : product.price), sku: product.sku ? product.sku : '', name: product.title, }, ]); } else { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 product.editions.forEach(function (cur) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (cur.uid === urlSearch.editionuid) { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 Tilda.sendEcommerceEvent('detail', [ { id: '' + cur.uid, uid: '' + cur.uid, price: '' + cur.price, sku: cur.sku ? cur.sku : '', name: product.title, }, ]); } }); } } }, 3000); } /** * This function is called when the user clicks on a product in the product list. * It stores the product data in the browser's history. * When the user clicks on the back button, the product data is retrieved from the browser's history. * This data is then used to open the product popup **/ function t_catalog_initRouting() { window.onpopstate = function () { if (window.history.state && window.history.state.productData) { var productPopupData = window.history.state.productData; var recid = productPopupData.recid, options = productPopupData.opts, productObj = productPopupData.productObj, isRelevantsShow = productPopupData.isRelevantsShow; t_catalog_openProductPopup(recid, options, productObj, isRelevantsShow); } }; } /** * Получает главную кнопку сниппета * @param {string} recid * @returns {HTMLButtonElement | null} */ function t_catalog_getSnippetMainButton(recid) { const rec = document.getElementById('rec' + recid); if (!rec) { return null; } return rec.querySelector('.t-catalog__prod-popup__btn-wrapper .t-catalog__prod-popup__btn'); } /** * Создает массив базовых CSS-правил для кнопки * @param {Record} cssPropertiesMap * @param {Record} styles * @returns {string[]} */ function t_catalog_buildBaseButtonCssRules(cssPropertiesMap, styles) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 const baseRules = []; // Основные одиночные поля по маппингу Object.keys(cssPropertiesMap).forEach(function (key) { const cssProp = cssPropertiesMap[key]; const value = styles[key]; if (value) { if (key === 'bgcolor') { if (t_catalog_isGradient(value)) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'background-image', value); // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'background-color', 'transparent'); } else { // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'background-color', value); // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'background-image', 'none'); } } else { // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, cssProp, value); } } }); const size = styles.bordersize || '0'; const color = styles.bordercolor || 'transparent'; if (styles.bordersize || styles.bordercolor) { if (/^0($|[^0-9])/i.test(size) || size === '0px') { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'border', 'none'); } else { // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'border', size + ' solid ' + color); } } // Переходы // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'transition-duration', styles.speedhover || '0.2s'); t_catalog_addRule( // @ts-expect-error ST-2949_2 baseRules, 'transition-property', 'background-color, color, border-color, box-shadow, opacity, transform' ); // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, 'transition-timing-function', 'ease-in-out'); // Добавим переменные для поддержки hover if (styles.bgcolorhover) { if (t_catalog_isGradient(styles.bgcolorhover)) { // Используем CSS переменные как и раньше // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, '--button-after-background-image-hover', styles.bgcolorhover); } else { // @ts-expect-error ST-2949_2 t_catalog_addRule(baseRules, '--button-after-background-color-hover', styles.bgcolorhover); } } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 return baseRules; } /** * Создает массив CSS-правил при наведении * @param {Record} styles * @returns {string[]} */ function t_catalog_buildHoverCssRules(styles) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 const hoverRules = []; if (styles.shadowhover) { // @ts-expect-error ST-2949_2 t_catalog_addRule(hoverRules, 'box-shadow', styles.shadowhover); } if (styles.bordersize || styles.bordercolorhover) { const sizeH = styles.bordersize || '0'; const colorH = styles.bordercolorhover || styles.bordercolor || 'transparent'; if (/^0($|[^0-9])/i.test(sizeH) || sizeH === '0px') { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(hoverRules, 'border', 'none'); } else { // @ts-expect-error ST-2949_2 t_catalog_addRule(hoverRules, 'border', sizeH + ' solid ' + colorH); } } if (styles.bgcolorhover) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(hoverRules, 'background-color', styles.bgcolorhover); } // @ts-expect-error ST-2949_2 return hoverRules; } /** * Создает массив CSS-правил для мобильных * @param {Record} cssPropertiesMap * @param {Record} styles * @returns {string[]} */ function t_catalog_buildMobileCssRules(cssPropertiesMap, styles) { const MOBILE_SUFFIX = '_res_480'; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 const mobileRules = []; Object.keys(styles).forEach(function (key) { if (!key.includes(MOBILE_SUFFIX)) return; const baseKey = key.replace(MOBILE_SUFFIX, ''); const cssProp = cssPropertiesMap[baseKey]; if (!cssProp) return; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(mobileRules, cssProp, styles[key]); }); // Доп. поля для mobile (gap_res_480 уже обработается через mап выше, т.к. gap в MAP) if (styles.padding_res_480) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addRule(mobileRules, 'padding', styles.padding_res_480); } // @ts-expect-error ST-2949_2 return mobileRules; } /** * Создает CSS для текста кнопки * @param {string} recid * @param {string} itemSelector * @param {Record} styles * @returns {string} */ function t_catalog_createButtonTextCss(recid, itemSelector, styles) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 const textBaseRules = []; // @ts-expect-error ST-2949_2 const textHoverRules = []; // @ts-expect-error ST-2949_2 const textMobileRules = []; if (styles.color) { // @ts-expect-error ST-2949_2 t_catalog_addTextColorRule(textBaseRules, styles.color); } if (styles.colorhover) { // @ts-expect-error ST-2949_2 t_catalog_addTextColorRule(textHoverRules, styles.colorhover); } if (styles.color_res_480) { // @ts-expect-error ST-2949_2 t_catalog_addTextColorRule(textMobileRules, styles.color_res_480); } // Селектор кнопки в для карточке товара и в секции Смотрите также const textBtnSelector = `${itemSelector} .t-btnflex__text, ${itemSelector} .t-catalog__card__btn-text`; const textBtnHoverSelector = `${itemSelector}:hover .t-btnflex__text, ${itemSelector}:hover .t-catalog__card__btn-text`; let css = ''; if (textBaseRules?.length) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 css += `${textBtnSelector}{${textBaseRules.join('')}}`; } if (textHoverRules?.length) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 css += `\n${textBtnHoverSelector}{${textHoverRules.join('')}}`; } if (textMobileRules?.length) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 css += `\n@media screen and (max-width:480px){${textBtnSelector}{${textMobileRules.join('')}}}`; } return css; } /** * Создает CSS для внешнего вида кнопки * @param {string} recid * @param {string} itemSelector * @param {Record} styles * @param {string[]} excludedStyles * @returns {string} */ function t_catalog_createButtonAppereanceCss(recid, itemSelector, styles, excludedStyles) { // Универсальная схема маппинга: ключ конфига -> CSS свойство const cssPropertiesMap = { bgcolor: 'background-color', radius: 'border-radius', wrap: 'white-space', shadow: 'box-shadow', fontweight: 'font-weight', uppercase: 'text-transform', fontsize: 'font-size', fontfamily: 'font-family', lineheight: 'line-height', letterspacing: 'letter-spacing', gap: 'gap', padding: 'padding', iconposition: 'flex-direction', }; if (Array.isArray(excludedStyles) && excludedStyles.length) { const excludedStylesSet = new Set(excludedStyles); for (const key in cssPropertiesMap) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 if (excludedStylesSet.has(key)) delete cssPropertiesMap[key]; } } // Построение базовых, hover и мобильных правил const baseRules = t_catalog_buildBaseButtonCssRules(cssPropertiesMap, styles); const hoverRules = t_catalog_buildHoverCssRules(styles); const mobileRules = t_catalog_buildMobileCssRules(cssPropertiesMap, styles); const selector = `#rec${recid} ${itemSelector}`; const hoverSelector = `#rec${recid} ${itemSelector}:hover`; let css = ''; if (baseRules?.length) { css += `${selector}{${baseRules.join('')}}`; } if (hoverRules?.length) { css += `\n${hoverSelector}{${hoverRules.join('')}}`; } if (mobileRules?.length) { css += `\n@media screen and (max-width:480px){${selector}{${mobileRules.join('')}}}`; } return css; } /** * Создает тег CSS-стилей * @param {string} styleId * @param {string} css */ function t_catalog_createСssStyleTag(styleId, css) { let styleEl = document.getElementById(styleId); if (!styleEl) { styleEl = document.createElement('style'); styleEl.id = styleId; (document.head || document.documentElement).appendChild(styleEl); } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (styleEl.styleSheet) { // @ts-expect-error ST-2949_1 styleEl.styleSheet.cssText = css; } else { styleEl.textContent = css; } } /** * Применяет стили к кнопке сниппета * @param {string} recid * @param {Object} options */ function t_catalog_applyButtonStyles(recid, options) { try { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (!options || !options.button_styles) return; const button = t_catalog_getSnippetMainButton(recid); if (button) { const isReplaced = button.classList.contains('t_catalog__prod-popup__btn-replaced'); button.removeAttribute('style'); // очищаем инлайновые стили с бэкенда if (isReplaced) { // кнопка не должна показываться, если она заменена на notify кнопку button.style.display = 'none'; } t_catalog_applyButtonClasses(button); } // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 let css = t_catalog_createButtonStyleCss( recid, '.t-catalog__prod-popup__btn-wrapper .t-catalog__prod-popup__btn', // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 options.button_styles ); // @ts-expect-error ST-2949_1 if (options.showRelevants) { css += t_catalog_createButtonStyleCss( recid, '.t-catalog__relevants__container .t-catalog__card__btn:not(.t-catalog__card__btn_second)', // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 options.button_styles, ['padding'] ); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options.button2_styles) { css += t_catalog_createButtonStyleCss( recid, '.t-catalog__relevants__container .t-catalog__card__btn_second', // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 options.button2_styles, ['padding'] ); } } t_catalog_createСssStyleTag('js-catalog-btn-styles-' + recid, css); if (button?.parentNode) { // Показываем кнопку, когда стили готовы // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 button.parentNode.style.opacity = 1; return; } const buttonWrapper = document.querySelector('.t-catalog__product-snippet .t-catalog__prod-popup__btn-wrapper'); if (!buttonWrapper) { return; } // скрываем блок полностью так как нет кнопки в попапе // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 buttonWrapper.style.display = 'none'; } catch (error) { console.error('Ошибка при применениии стилей к кнопке (refactored): ' + error); } } /** * Добавляет и изменяет классы кнопки сниппета * @param {HTMLButtonElement} button */ function t_catalog_applyButtonClasses(button) { button.classList.add('t-btnflex'); button.classList.add('t-btnflex_type_button'); if (button.classList.contains('t-btn_sm')) { button.classList.replace('t-btn_sm', 't-btnflex_sm'); } const td = button.querySelector('td'); // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 td.classList.add('t-btnflex__text'); } /** * Функция * @param {string} recid * @param {string} itemSelector * @param {string} stylesJSON * @param {string[]} excludedStyles // массив с названиями свойств, которые не нужно применять * @returns {string} */ function t_catalog_createButtonStyleCss(recid, itemSelector, stylesJSON, excludedStyles) { try { const styles = JSON.parse(stylesJSON); let css = t_catalog_createButtonAppereanceCss(recid, itemSelector, styles, excludedStyles); css += t_catalog_createButtonTextCss(recid, itemSelector, styles); if (styles.bgcolor && styles.bgcolorhover) { css = t_catalog_appendMainButtonBgHoverStyle(css); } if (styles.iconsize) { css += `\n .t-btnflex.t-btnflex_type_button .t-btnflex__icon { width: ${styles.iconsize}; height:${styles.iconsize}; }`; } return css; } catch (error) { console.error('Ошибка при создании css-правил для кнопки ', error); return ''; } } /** * Создает иконку для кнопки внутри сниппета * @param {string} recid * @param {Object} options */ function t_catalog_renderSnippetButtonIcon(recid, options) { try { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 const { buttonicon, buttoniconhover } = options; if (!buttonicon && !buttoniconhover) { return; } const button = t_catalog_getSnippetMainButton(recid); if (!button) { return; } const iconEl = document.createElement('span'); iconEl.className = 't-btnflex__icon'; let iconStyle = ''; if (buttonicon) { iconStyle += `--icon:url("${buttonicon.replace(/"/g, '"')}");\n`; if (buttonicon.includes('/lib/icons/button/')) { iconEl.classList.add('t-btnflex__icon_default_glyph'); } } if (buttoniconhover) { iconEl.classList.add('t-btnflex__icon_has_hover'); iconStyle += `--icon-hover:url("${buttoniconhover.replace(/"/g, '"')}");\n`; if (buttoniconhover.includes('/lib/icons/button/')) { iconEl.classList.add('t-btnflex__icon_hover_glyph'); } } if (iconStyle) { iconEl.setAttribute('style', iconStyle); } button.insertAdjacentElement('afterbegin', iconEl); } catch (error) { console.error('Ошибка при рендере иконки в кнопке: ' + error); } } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_createCssProperty(propertyName, value) { return `${propertyName}: ${value};`; } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_addRule(targetArr, prop, val) { if (val === undefined || val === null || val === '') return; targetArr.push(t_catalog_createCssProperty(prop, val)); } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_addTextColorRule(targetArr, val) { if (t_catalog_isGradient(val)) { t_catalog_addRule(targetArr, 'background-image', val); t_catalog_addRule(targetArr, '-webkit-text-fill-color', 'transparent'); t_catalog_addRule(targetArr, '-webkit-background-clip', 'text'); t_catalog_addRule(targetArr, 'background-clip', 'text'); } else { t_catalog_addRule(targetArr, 'color', val); } } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_isGradient(stylePropertyValue) { return typeof stylePropertyValue === 'string' && stylePropertyValue.indexOf('gradient') !== -1; } /** * Добавляет анимацию смены фона при наведении * @param {string} css * @returns */ function t_catalog_appendMainButtonBgHoverStyle(css) { return ( css + ` \n @media (hover: hover) { .t-catalog__prod-snippet__container .t-catalog__prod-popup__btn:hover { animation-name: t-button-hover-animation; animation-duration: 0s; animation-fill-mode: forwards; animation-delay: 1s; animation-timing-function: linear; } } ` ); } /** * Initialize the hover zoom plugin. It is called when the page is loaded * * @param {string} recid **/ function t_catalog_hoverZoom_init(recid) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (window.tCatalogIsMobile) return; var rec = document.getElementById('rec' + recid); // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 if (rec.querySelector('[data-hover-zoom]')) { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog__loadHoverZoom().then(() => t_hoverZoom_init(recid)); } } /** * Loads products from the store and shown * * @param {string} method - relevants or not * @param {string} recid * @param {CatalogOptions} options * @param {number} slice - the number of the slice to load * @param {object} relevantsOpts * @param {HTMLElement} [relevantsOpts.container] **/ function t_catalog_loadProducts(method, recid, options, slice, relevantsOpts) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.tCatalogProductsRequested = true; var showRelevants = method === 'relevants'; var c = Date.now(); var storepartuid = options.storepart; // Флаг одноразовый: сбрасываем сразу, чтобы он не остался выставленным при ошибке запроса var skipFiltersInit = Boolean(options.skipFiltersInit); options.skipFiltersInit = false; // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 var isFirstSlice = !slice || parseInt(slice, 10) === 1; var isEditMode = t_catalog__isEditMode(); var rec = document.getElementById('rec' + recid); if (!rec) return; var gridContainer = showRelevants ? (relevantsOpts && relevantsOpts.container) || rec.querySelector('.js-catalog-relevants-grid-cont') : rec.querySelector('.js-catalog-grid-cont'); // combine sending data object var dataObj; if (showRelevants) { dataObj = { storepartuid: storepartuid, // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 productuid: relevantsOpts.currentProductUid, // @ts-expect-error ST-2949_1 quantity: relevantsOpts.relevantsQuantity, // @ts-expect-error ST-2949_1 method: relevantsOpts.relevantsMethod, // @ts-expect-error ST-2949_1 sort: relevantsOpts.relevantsSort, }; gridContainer = (relevantsOpts && relevantsOpts.container) || rec.querySelector('.t-catalog__relevants-grid-cont'); if (gridContainer) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 gridContainer.style.opacity = 0; } } else { dataObj = { storepartuid: storepartuid, recid: recid, c: c, }; } var shouldFetchParts = // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 isEditMode || (!window.tCatalogFirstLoadStates[recid] && (!options.hideStoreParts || options.filters)); if (shouldFetchParts) { // @ts-expect-error ST-2949_1 var getСurrentPart = options.parts?.storePartsShowLevel === 'subs'; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 dataObj[getСurrentPart ? 'getcurrentpart' : 'getallparts'] = getСurrentPart ? // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.tCatalogInitialRootStorepartUid[recid] : true; } // Опции в edit mode всегда обновляем, // иначе после сохранения без перезагрузки не обновляются цвета. // Кэш редактора (shared/edit-cache) может отдать ответ с опциями повторно, пока не истёк его срок (EDIT_CACHE_TTL_MS), // и сбрасывается при закрытии панели настроек, undo/redo и возврате на вкладку. // Цветовые опции (ST-2585) могут отставать на этот срок — это допустимо. if (!window.tCatalogOptionsList || isEditMode) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 dataObj.getoptions = true; } if (slice) { // @ts-expect-error ST-2949_1 dataObj.slice = slice; } // @ts-expect-error ST-2949_1 if (options.filters) { // @ts-expect-error ST-2949_1 dataObj.filters = options.filters; } if (!showRelevants) { const sortValue = t_catalog__resolveProductsSort(options); if (sortValue) { dataObj.sort = sortValue; } } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options.size && options.size > 0) { // @ts-expect-error ST-2949_1 dataObj.size = options.size; } if (options && options.defaultSort && options.defaultSort.in_stock && showRelevants) { // @ts-expect-error ST-2949_1 if (!dataObj.filters) dataObj.filters = {}; // @ts-expect-error ST-2949_1 dataObj.filters['quantity'] = 'y'; } // Добавляем getpartinfo если установлен флаг needGetPartInfo // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options.hasDynamicCategoryContent && options.needGetPartInfo && !showRelevants) { // @ts-expect-error ST-2949_1 dataObj.getpartinfo = true; // Сбрасываем флаг после использования // @ts-expect-error ST-2949_1 options.needGetPartInfo = false; } // @ts-expect-error ST-2949_1 if (options?.breadcrumbs?.hasBreadcrumbs) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 dataObj['getbreadcrumbs[]'] = 'parts'; } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options?.breadcrumbs?.hasBreadcrumbs && !options?.breadcrumbs?.hideBreadcrumbsProduct) { // Увеличиваем ключ, если уже есть ключ parts // @ts-expect-error ST-2949_1 const breadcrumbsKey = options?.breadcrumbs?.hasBreadcrumbs ? '1' : ''; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 dataObj[`getbreadcrumbs[${breadcrumbsKey}]`] = 'products'; } var apiUrl = 'https://' + // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.t_catalog_endpoint + '/api' + (showRelevants ? '/getrelevantproducts/' : '/getproductslist/'); // inside tilda we get data from another url if (!options.isPublishedPage) { var domainParts = window.location.hostname.split('.'); var link = 'tilda.' + domainParts[domainParts.length - 1]; // @ts-expect-error ST-2949_1 dataObj.projectid = document.getElementById('allrecords').getAttribute('data-tilda-project-id'); apiUrl = 'https://' + link + '/projects/store' + (showRelevants ? '/getrelevantproducts/' : '/getproductslist/'); } var ts = Date.now(); if (!window.tStoreXHR) { window.tStoreXHR = {}; } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 if (window.tStoreXHR[recid]) { // @ts-expect-error ST-2949_2 window.tStoreXHR[recid].abort(); // @ts-expect-error ST-2949_2 delete window.tStoreXHR[recid]; } // В редакторе повторный рендер записи после изменения настроек берёт ответ из кэша (микрозадачей, без сети): // карточки отрисовываются до показа превью, и блок не моргает. В превью и на опубликованной странице — null. // Новый вызов для этой записи отменяет ответ из кэша так же, как xhr: через window.tStoreXHR[recid].abort(). // Ключ берём до отправки: dataObj.filters — ссылка на options.filters, и фильтры могут поменяться, пока запрос в пути. // getrelevantproducts не кэшируется: ключ null. var editCacheKey = showRelevants ? null : t_catalog_editCache__getKey('getproductslist', apiUrl, dataObj); var cachedRequest = t_catalog_editCache__respond(editCacheKey, handleProductsResponse); if (cachedRequest) { // @ts-expect-error ST-2949_2 window.tStoreXHR[recid] = cachedRequest; return; } var xhr = new XMLHttpRequest(); // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 window.tStoreXHR[recid] = xhr; xhr.onload = function () { if (xhr.readyState === xhr.DONE && xhr.status === 200) { if (t_catalog__handleRootzoneRedirect(xhr.responseText, apiUrl)) { // повтор того же запроса: флаг должен дожить до него options.skipFiltersInit = skipFiltersInit; t_catalog_loadProducts(method, recid, options, slice, relevantsOpts); return; } t_catalog_editCache__remember(editCacheKey, xhr.responseText); handleProductsResponse(xhr.responseText); } }; /** * Обрабатывает ответ getproductslist / getrelevantproducts: из сети или из кэша редактора * @param {string} data - текст ответа */ function handleProductsResponse(data) { // Отмечаем, что данные для этого блока загружены // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.tCatalogFirstLoadStates[recid] = true; t_catalog__hidePreloader(recid); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options.sidebar) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var tCatalogGridContainer = rec.querySelector('.t-catalog__grid-cont'); if (tCatalogGridContainer) { tCatalogGridContainer.classList.remove('t-catalog__grid-cont_hidden'); } } // remove cards if (isFirstSlice && gridContainer) { const chosenBar = gridContainer.querySelector('.t-catalog__filter__chosen-bar'); if (chosenBar) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 chosenBar.parentNode.removeChild(chosenBar); } gridContainer.innerHTML = ''; if (chosenBar) { gridContainer.appendChild(chosenBar); } } // check server error if ( typeof data === 'string' && data.substring(0, 1) !== '{' && (data.indexOf('ERROR:') !== -1 || data.indexOf('Wrong') !== -1) ) { var el_errorBox = t_catalog_get_errorBox(options, data); // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 gridContainer.insertAdjacentHTML('beforeend', el_errorBox); // @ts-expect-error ST-2949_3 t_catalog__fadeIn(rec.querySelector('.js-catalog-error-msg')); return; } if (data === '') { return; } // try to parse products data var obj = {}; try { obj = JSON.parse(data); // links for size chart // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (obj.partlinks) { // @ts-expect-error ST-2949_1 options.linksSizeChart = obj.partlinks; } // @ts-expect-error ST-2949_1 if (obj.breadcrumbs && Array.isArray(obj.breadcrumbs) && obj.breadcrumbs.length > 0) { // @ts-expect-error ST-2949_1 options.serverBreadcrumbs = obj.breadcrumbs; } else { // @ts-expect-error ST-2949_1 delete options.serverBreadcrumbs; } } catch (error) { console.error(error); } if (typeof obj !== 'object') { return; } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var productsArr = showRelevants ? obj.relevants : obj.products; // store option params // @ts-expect-error ST-2949_1 if (obj.options && obj.options.length >= 1) { // @ts-expect-error ST-2949_1 window.tCatalogOptionsList = obj.options; } // @ts-expect-error ST-2949_1 if (!showRelevants && options.hasDynamicCategoryContent && obj.partinfo) { // @ts-expect-error ST-2949_1 t_catalog_header__updateHeaderFromPartInfo(recid, obj.partinfo); } // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog_process(productsArr, recid, options, !!slice, showRelevants, obj, relevantsOpts); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options?.breadcrumbs?.hasBreadcrumbs && options.serverBreadcrumbs) { t_catalog_breadcrumbs__update(recid, options); } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var isAllPart = obj.parts?.find( // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 part => part.root === true && part.uid == window.tCatalogInitialStorepartUid[recid] ); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var getСurrentPart = options.parts?.storePartsShowLevel === 'subs' && !isAllPart; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 var parts; if (getСurrentPart) { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 if (/* ST-1754 для открытия на всех */ isNewPartsUsed(rec)) { // Добавляет текущий раздел в начало как root без subparts. // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var currentPart = obj.parts?.[0] ? Object.assign({}, obj.parts[0]) : null; if (currentPart) { currentPart.root = true; // Помечаем, что это не настоящий корневой раздел, а текущий раздел на его месте currentPart.isCurrentPartAsRoot = true; delete currentPart.subparts; } parts = currentPart ? // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 [currentPart].concat(obj.parts?.[0]?.subparts || []) : // @ts-expect-error ST-2949_1 obj.parts?.[0]?.subparts; } else { // @ts-expect-error ST-2949_1 parts = obj.parts?.[0]?.subparts; } } else { // @ts-expect-error ST-2949_1 parts = obj.parts; } // Добавляем проверку для отрисовки навигации по разделам: // - parts должен быть массивом и содержать хотя бы один элемент: // - - для вывода "Всех разделов" в parts имеем список разделов и мы выводим навигацию если есть хотябы 1 элемент // - - для вывода "Подразделов текущего раздела" в parts имеем список подразделов и выводим навигацию если есть хотябы 1 элемент // - навигация по разделам не должна быть уже на странице (js-catalog-parts-switcher) // - не не должна быть включенной настройка скрытия разделов (hideStoreParts) if ( Array.isArray(parts) && parts.length > 0 && // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 !rec.querySelector('.js-catalog-parts-switcher') && !options.hideStoreParts ) { // @ts-expect-error ST-2949_1 window.tCatalogParts[recid] = parts; var onLoadFilters = function () { t_catalog_onFuncLoad('t_catalog_addStoreParts', function () { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 t_catalog_addStoreParts(recid, options, parts); // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog_setActiveStorePart(recid); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options?.breadcrumbs?.hasBreadcrumbs) { t_catalog_breadcrumbs__update(recid, options); } }); }; t_catalog__loadTildaCatalogFilters().then(() => onLoadFilters()); } // Определяем UID раздела "Все" // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 const isStorePartsShowTopLevel = options.parts && options.parts.storePartsShowLevel === 'top'; // @ts-expect-error ST-2949_1 window.tCatalogAllStorepartUid[recid] = isStorePartsShowTopLevel ? window.tCatalogParts?.[recid]?.find(part => part.root)?.uid?.toString() : // @ts-expect-error ST-2949_1 window.tCatalogInitialStorepartUid[recid]; // add filters // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (!window.tCatalogFilters) { // @ts-expect-error ST-2949_1 window.tCatalogFilters = {}; } // @ts-expect-error ST-2949_1 if (obj.filters) { // @ts-expect-error ST-2949_1 window.tCatalogFilters[recid] = obj.filters; } // @ts-expect-error ST-2949_1 var data = window.tCatalogFilters[recid]; // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 const { shouldShowFilters, shouldShowSearchSort } = t_catalog_filters__getVisibilityFlags(options, data); const shouldInitFilters = // фильтры включены на стороне сервера // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 obj.filter === 'y' && // есть данные фильтров data && // показываем хотя бы фильтры или поиск/сортировку (shouldShowFilters || shouldShowSearchSort); if (shouldInitFilters) { // Перерисовываем фильтры, если не установлен skipFiltersInit if (!skipFiltersInit) { t_catalog_onFuncLoad('t_catalog_filters_init', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog_filters_init(recid, options, data); }); } // Обновляем количество товаров всегда if (!showRelevants) { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_catalog_filters_prodsNumber_update(rec, options, obj, recid); } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 } else if (options.sidebar && !showRelevants && obj.parts && obj.parts.length === 0) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var el_sidebar = rec.querySelector('.t-catalog__sidebar'); if (el_sidebar) { el_sidebar.classList.add('t-catalog__sidebar_empty'); var text = t_catalog__getBrowserLang() === 'RU' ? 'Пожалуйста, добавьте хотя бы один фильтр каталога для отображения боковой панели магазина. Справка' : 'Please add at least one catalog filter to display the store sidebar'; el_sidebar.innerHTML = '' + text + ''; } } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (t_catalog_isQueryInAddressBar('tstore') && window.t_catalog__scrollToBlock) { var hashArr = decodeURI(window.location.hash).split('/'); var storeuidIndex = hashArr.indexOf('r') + 1; var storeuid = hashArr[storeuidIndex]; if (storeuid === recid) { if ('scrollBehavior' in document.documentElement.style) { window.scrollTo({ left: 0, // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 top: rec.getBoundingClientRect().top + window.pageYOffset - 50, behavior: 'smooth', }); } else { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 window.scrollTo(0, rec.getBoundingClientRect().top + window.pageYOffset - 50); } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.t_catalog__scrollToBlock = null; } } // show more button // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var loadMoreBtn = rec.querySelector('.js-catalog-load-more-btn'); // stop loaders if (loadMoreBtn) { loadMoreBtn.classList.remove('t-btn_sending'); } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 var loadMoreScrollEvent; t_onFuncLoad('t_throttle', function () { loadMoreScrollEvent = t_throttle(function () { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (window.tCatalogProductsRequested) { return; } if (window.innerWidth < 960) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var scrollWidth = gridContainer.scrollWidth; // @ts-expect-error ST-2949_3 var scrollLeft = gridContainer.scrollLeft; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var offsetWidth = gridContainer.offsetWidth; // @ts-expect-error ST-2949_1 if (offsetWidth + scrollLeft + 20 > scrollWidth && loadMoreBtn.style.display !== 'none') { // @ts-expect-error ST-2949_1 loadMoreBtn.click(); // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 gridContainer.removeEventListener('scroll', loadMoreScrollEvent); } } }); }); var isMobileOneRow = gridContainer && gridContainer.classList.contains('t-catalog__grid-cont_mobile-one-row'); // load more // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (obj.nextslice) { // add load more button if (!loadMoreBtn) { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 loadMoreBtn = t_catalog_get_loadMoreBtn_html(rec, options); // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var pagination = rec.querySelector( '.t-catalog__cont-w-filter .t-catalog__cont-wrapper + .t-catalog__pagination' ); if (!pagination) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var gridCont = rec.querySelector('.t-catalog__cont-w-filter'); if (gridCont) { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 gridCont.insertAdjacentHTML('beforeend', loadMoreBtn); } } // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 loadMoreBtn = rec.querySelector('.js-catalog-load-more-btn'); } if (loadMoreBtn) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 loadMoreBtn.style.display = ''; var loadMoreBtnClickEvent = function () { if (t_catalog__isEditMode()) return; // @ts-expect-error ST-2949_1 if (!window.tCatalogProductsRequested) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 loadMoreBtn.classList.add('t-btn_sending'); // Фильтры при подгрузке товаров не меняются, не перерисовываем их, чтобы сохранить раскрытые списки options.skipFiltersInit = true; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 t_catalog_loadProducts('', recid, options, obj.nextslice); } }; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 loadMoreBtn.parentNode.replaceChild(loadMoreBtn.cloneNode(true), loadMoreBtn); // @ts-expect-error ST-2949_3 loadMoreBtn = rec.querySelector('.js-catalog-load-more-btn'); // @ts-expect-error ST-2949_3 loadMoreBtn.addEventListener('click', loadMoreBtnClickEvent); } if (isMobileOneRow) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 gridContainer.addEventListener('scroll', loadMoreScrollEvent); } } else if (!showRelevants) { if (loadMoreBtn) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 loadMoreBtn.style.display = 'none'; } if (gridContainer) { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 gridContainer.removeEventListener('scroll', loadMoreScrollEvent); } } // add Pagination // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options.showPagination && options.showPagination === 'on' && !showRelevants) { t_catalog_onFuncLoad('t_catalog_pagination_draw', function () { // @ts-expect-error ST-2949_1 t_catalog_pagination_draw(recid, options, slice, obj.total); }); } if (isMobileOneRow) { const isPublishedMode = t_catalog__isPublishedMode(); if (gridContainer && isPublishedMode) { if ( window.lazy === 'y' || // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 document.getElementById('allrecords').getAttribute('data-tilda-lazy') === 'yes' ) { t_catalog_onFuncLoad('t_lazyload_update', function () { t_onFuncLoad('t_throttle', function () { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 gridContainer.addEventListener( 'scroll', t_throttle(function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_lazyload_update(); }) ); }); }); } } } if (showRelevants) { if (gridContainer instanceof HTMLElement) gridContainer.style.opacity = '1'; var blocksInRowForRelevant = 4; if (options.relevants_slider && (productsArr.length > blocksInRowForRelevant || window.innerWidth <= 960)) { t_catalog_onFuncLoad('t_sldsInit', function () { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_sldsInit((relevantsOpts && relevantsOpts.container) || recid + ' .js-catalog-relevants-grid-cont'); }); } } if (options.itemsAnim && options.previewmode) { t_catalog_onFuncLoad('t_animate__startAnimation', function () { t_animate__startAnimation(); }); } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 gridContainer.style.height = ''; t_catalog_triggerEvent(document.body, 'twishlist_addbtn'); // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog_triggerEvent(gridContainer, 'tStoreRendered'); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.tCatalogProductsRequested = false; } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function onError(error) { // Сбрасываем флаг при ошибке для повторной попытки загрузки // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 delete window.tCatalogFirstLoadStates[recid]; // @ts-expect-error ST-2949_1 if (window.t_catalog_endpoint.indexOf('store.tilda') !== -1) { t_catalog_changeEndpoint(error, function () { // повтор того же запроса: флаг должен дожить до него options.skipFiltersInit = skipFiltersInit; t_catalog_loadProducts(method, recid, options, slice, relevantsOpts); }); } else { // show more button // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var loadMoreBtn = rec.querySelector('.js-catalog-load-more-btn'); if (loadMoreBtn) { loadMoreBtn.classList.remove('t-btn_sending'); } // check internet connection var ts_delta = Date.now() - ts; if (xhr.status === 0 && ts_delta < 100) { console.error('Request error (get store products). Please check internet connection...'); } // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.tCatalogProductsRequested = false; t_catalog__hidePreloader(recid); // show error var el_errorBox = t_catalog_get_errorBox( options, 'Request timeout (40s). Please check internet connection and reload the page. If the situation has not changed, please contact support team@tilda.cc.' ); // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 gridContainer.insertAdjacentHTML('beforeend', el_errorBox); // @ts-expect-error ST-2949_3 t_catalog__fadeIn(rec.querySelector('.js-catalog-error-msg')); } } xhr.ontimeout = onError; xhr.onerror = onError; // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 xhr.open('GET', apiUrl + '?' + t_catalog__serializeData(dataObj)); xhr.timeout = 20000; xhr.send(); } /** * Loads one product from the store * * @param {string} recid - the id of the product in the store * @param {object} options * @param {string} curProdUid - the product's UID that we want to load * @param {Function} onDone - callback on success * @param {Function} onFail - callback on error **/ function t_catalog_loadOneProduct(recid, options, curProdUid, onDone, onFail) { var c = Date.now(); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var storepartuid = options.storepart; var dataObj = { storepartuid: storepartuid, recid: recid, productuid: curProdUid, c: c, }; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var apiUrl = 'https://' + window.t_catalog_endpoint + '/api/getproduct/?' + t_catalog__serializeData(dataObj); var xhr = new XMLHttpRequest(); xhr.onload = function () { if (xhr.readyState === xhr.DONE && xhr.status === 200) { if (t_catalog__handleRootzoneRedirect(xhr.responseText, apiUrl)) { t_catalog_loadOneProduct(recid, options, curProdUid, onDone, onFail); return; } onDone(); } }; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function onError(error) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 console.error("Can't get product with uid = " + curProdUid + ' in storepart = ' + options.storepart); if (typeof onFail === 'function') { onFail(error); } } xhr.ontimeout = onError; xhr.onerror = onError; xhr.open('GET', apiUrl); xhr.timeout = 20000; xhr.send(); } /** * An array of product IDs and returns an array of products * * @param {Array<*>} idArr - array of product ids * @param {object} options * @param {Function} onDone - callback on success * @param {Function} onFail - callback on error **/ function t_catalog_loadProducts_byId(idArr, options, onDone, onFail) { var c = Date.now(); var dataObj = { productsuid: idArr, c: c, }; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var apiUrl = 'https://' + window.t_catalog_endpoint + '/api/getproductsbyuid/'; // inside tilda we get data from another url // @ts-expect-error ST-2949_1 if (options && !options.isPublishedPage) { // @ts-expect-error ST-2949_1 dataObj.projectid = document.getElementById('allrecords').getAttribute('data-tilda-project-id'); var domainParts = window.location.hostname.split('.'); var link = 'tilda.' + domainParts[domainParts.length - 1]; apiUrl = 'https://' + link + '/projects/store/getproductsbyuid/'; } // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 dataObj = JSON.stringify(dataObj); var xhr = new XMLHttpRequest(); xhr.onload = function () { if (xhr.readyState === xhr.DONE && xhr.status === 200) { if (typeof xhr.responseText !== 'string' || xhr.responseText.substring(0, 1) !== '{') { console.error("Can't get products array by uid list"); } if (t_catalog__handleRootzoneRedirect(xhr.responseText, apiUrl)) { t_catalog_loadProducts_byId(idArr, options, onDone, onFail); return; } onDone(JSON.parse(xhr.responseText)); } }; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function onError(error) { console.error("Can't get getproductsbyuid. Requesting idArr: " + idArr); if (typeof onFail === 'function') { onFail(error); } } xhr.ontimeout = onError; xhr.onerror = onError; xhr.open('POST', apiUrl); xhr.timeout = 20000; // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 xhr.send(dataObj); } /** * Sends a request to the server to get the filters for the store part * * @param {object} options * @param {Function} onDone - callback on success * @param {Function} onFail - callback on error **/ function t_catalog_loadFilters(options, onDone, onFail) { var c = Date.now(); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var storepartuid = options.storepart; var dataObj = { storepartuid: storepartuid, c: c, }; var allRecords = document.getElementById('allrecords'); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options && options.defaultSort && options.defaultSort.in_stock) { // @ts-expect-error ST-2949_1 if (!dataObj.filters) dataObj.filters = {}; // @ts-expect-error ST-2949_1 dataObj.filters['quantity'] = 'y'; } // @ts-expect-error ST-2949_1 var apiUrl = 'https://' + window.t_catalog_endpoint + '/api/getfilters/'; // inside tilda we get data from another url // @ts-expect-error ST-2949_1 if (!options.isPublishedPage) { if (allRecords) { // @ts-expect-error ST-2949_1 dataObj.projectid = allRecords.getAttribute('data-tilda-project-id'); } var domainParts = window.location.hostname.split('.'); var link = 'tilda.' + domainParts[domainParts.length - 1]; apiUrl = 'https://' + link + '/projects/store/getfilters/'; } /** * Обрабатывает ответ getfilters: из сети или из кэша редактора * @param {string} text - текст ответа */ function handleFiltersResponse(text) { try { onDone(JSON.parse(text)); } catch (error) { console.error(error); onDone(); } } // В редакторе повторный рендер записи берёт фильтры из кэша (микрозадачей, без сети). Ключ берём до отправки. var editCacheKey = t_catalog_editCache__getKey('getfilters', apiUrl, dataObj); if (t_catalog_editCache__respond(editCacheKey, handleFiltersResponse)) { return; } var xhr = new XMLHttpRequest(); xhr.onload = function () { if (xhr.readyState === xhr.DONE && xhr.status === 200) { if (t_catalog__handleRootzoneRedirect(xhr.responseText, apiUrl)) { t_catalog_loadFilters(options, onDone, onFail); return; } t_catalog_editCache__remember(editCacheKey, xhr.responseText); handleFiltersResponse(xhr.responseText); } }; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function onError(error) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 console.error("Can't get filters in storepart = " + options.storepart); if (typeof onFail === 'function') { onFail(error); } } xhr.ontimeout = onError; xhr.onerror = onError; // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 xhr.open('GET', apiUrl + '?' + t_catalog__serializeData(dataObj)); xhr.timeout = 20000; xhr.send(); } /** * Responsible for generating the HTML for the product cards and appending them to the DOM * * @param {Array<*>} productsArr - array of products * @param {string} recid * @param {CatalogOptions} options * @param {boolean} isNextSlice * @param {boolean} isRelevantsShow * @param {object} obj * @param {string} obj.header * @param {string} obj.footer * @param {string} obj.disablepopup * @param {object} [relevantsOpts] * @param {HTMLElement} [relevantsOpts.container] **/ function t_catalog_process(productsArr, recid, options, isNextSlice, isRelevantsShow, obj, relevantsOpts) { var rec = document.getElementById('rec' + recid); if (!rec) return; var gridContainer = rec.querySelector('.js-catalog-grid-cont'); if (!isRelevantsShow && !gridContainer) return; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var isListStyle = options.prodCard.listStyle === 'list'; // @ts-expect-error ST-2949_3 var isTileStyle = options.prodCard.listStyle === 'tile'; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var hasSeparator = options.prodCard.hasSeparator; var isSnippet = document.getElementById('allrecords') !== document.querySelector('.t-catalog__product-snippet') && // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 document.getElementById('allrecords').contains(document.querySelector('.t-catalog__product-snippet')); if (isRelevantsShow) { gridContainer = (relevantsOpts && relevantsOpts.container) || rec.querySelector('.js-catalog-relevants-grid-cont'); } if (!gridContainer) return; var separator = t_catalog_get_horizSeparator_html(); var obj_products = {}; // show empty message, if storepart is empty if (Array.isArray(productsArr) && productsArr.length === 0) { var el_emptyMsg = t_catalog_get_emptyMsg_html(options); gridContainer.insertAdjacentHTML('beforeend', el_emptyMsg); // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog__fadeIn(rec.querySelector('.js-catalog-empty-part-msg')); return; } if (isRelevantsShow && options.prodCard) { var shadowSize = options.prodCard.shadowSize; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var shadow = options.prodCard.shadow; // @ts-expect-error ST-2949_1 var shadowHover = options.prodCard.shadowHover; var shadowSizeHover = options.prodCard.shadowSizeHover; var shadowOpacityHover = options.prodCard.shadowOpacityHover; var shadowShiftyHover = options.prodCard.shadowShiftyHover; // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 var parsedShadowSize = parseInt(shadowSize, 10) || 0; parsedShadowSize = Math.min(parsedShadowSize, 10); var parsedShadowSizeHover = shadowSizeHover ? parseInt(shadowSizeHover, 10) : 20; parsedShadowSizeHover = Math.min(parsedShadowSizeHover, 40); var parsedShadowOpacityHover = shadowOpacityHover ? parseInt(shadowOpacityHover, 10) / 100 : 0.3; var maxSize = shadow || shadowHover ? 20 : Math.max(parsedShadowSizeHover, parsedShadowSize); var shadowHoverCSS = ''; if (shadowHover) { shadowHoverCSS = 'box-shadow: ' + shadowHover + ' !important;'; } else if (shadowSizeHover || shadowOpacityHover) { var offsetsMap = { sm: 10, md: 20 }; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var shadowOffset = offsetsMap[shadowShiftyHover] || 0; shadowHoverCSS = 'box-shadow: 0px ' + shadowOffset + 'px ' + parsedShadowSizeHover + 'px rgba(0,0,0,' + parsedShadowOpacityHover + ') !important;'; } // Add paddings for shadows in relevants block var paddingStyle = ''; if (shadowHoverCSS) { paddingStyle += '#rec' + recid + ' .t-catalog .t-catalog__relevants__container .t-catalog__relevants-grid-cont .t-catalog__card__wrap_all:hover {'; paddingStyle += shadowHoverCSS; paddingStyle += '}\n'; } if (parsedShadowSize || shadowSizeHover || shadow || shadowHover) { paddingStyle += '@media screen and (max-width:960px) {\n'; paddingStyle += '#rec' + recid + ' .t-catalog .t-catalog__relevants__container .t-catalog__relevants-grid-cont .t-catalog__card__wrap_all {\n'; paddingStyle += 'margin: ' + maxSize + 'px;\n'; paddingStyle += '}\n'; paddingStyle += '}\n'; paddingStyle += '@media screen and (min-width:961px) {\n'; paddingStyle += '#rec' + recid + ' .t-catalog .t-catalog__relevants__container .t-catalog__relevants-grid-cont .t-slds__items-wrapper .t-slds__item {\n'; paddingStyle += 'padding-top: ' + maxSize + 'px;\n'; paddingStyle += 'padding-bottom: ' + maxSize + 'px;\n'; paddingStyle += '}\n'; paddingStyle += '#rec' + recid + ' .t-catalog .t-catalog__relevants__container .t-catalog__relevants__title-wrapper .t-catalog__relevants__title {\n'; paddingStyle += 'margin-bottom: ' + (40 - maxSize) + 'px;\n'; paddingStyle += '}\n'; paddingStyle += '}\n'; } var relevantsSnippet = rec.querySelector('.t-catalog__product-snippet + .t-catalog__relevants__container'); var relevantsPopup = rec.querySelector('.t-popup .t-catalog__relevants__container'); if (paddingStyle) { paddingStyle = ''; if (relevantsPopup) relevantsPopup.insertAdjacentHTML('beforebegin', paddingStyle); if (isSnippet && relevantsSnippet) { relevantsSnippet.insertAdjacentHTML('beforebegin', paddingStyle); } } if (isSnippet && relevantsSnippet && options.isFlexCols) { relevantsSnippet.classList.add('t-catalog__grid-cont_col-width_stretch'); } else if (relevantsPopup && options.isFlexCols) { relevantsPopup.classList.add('t-catalog__grid-cont_col-width_stretch'); } } // generate product cards HTML var productsHtml = ''; var blocksInRowForRelevant = 4; var blocksInRow = isRelevantsShow ? blocksInRowForRelevant : options.blocksInRow; if ( isRelevantsShow && options.relevants_slider && (productsArr.length > blocksInRowForRelevant || window.innerWidth <= 960) ) { var animationduration = ''; var animationspeed = '300'; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 if (options.slider_opts.anim_speed === 'fast') { animationduration = 't-slds_animated-fast'; } // @ts-expect-error ST-2949_3 if (options.slider_opts.anim_speed === 'slow') { animationduration = 't-slds_animated-slow'; animationspeed = '500'; } productsHtml += ''; if (arrowsTpl && isRelevantsShow) { productsHtml += arrowsTpl; } } // change DOM if (cardList) { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog_process_appendAndShowProducts(rec, cardList, productsHtml); } else { // @ts-expect-error ST-2949_5 t_catalog_process_appendAndShowProducts(rec, gridContainer, productsHtml); } // prevent page from horizontal scroll, if grid container has fadeinleft animation if ( productsHtml.indexOf('data-animate-style="fadeinleft"') !== -1 && !gridContainer.classList.contains('t-catalog__grid-cont_mobile-one-row') ) { rec.style.overflowX = 'hidden'; } // init product options and edition options Array.prototype.forEach.call(productsArr, function (productData) { var productObj = productData; var el_product = isRelevantsShow ? // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 rec.querySelector( '.t-catalog__relevants__container .js-product.t-item[data-product-gen-uid="' + productObj.uid + '"]' ) : // @ts-expect-error ST-2949_3 rec.querySelector( '.t-catalog__grid-cont .js-product.t-item[data-product-gen-uid="' + productObj.uid + '"]' ); // @ts-expect-error ST-2949_3 el_product.setAttribute('data-card-size', 'small'); // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 productObj = obj_products[productObj.uid]; // create quantity input for popup var isSoldOut = parseInt(productObj.quantity, 10) <= 0; if (!isSoldOut && (options.showStoreBtnQuantity === 'both' || options.showStoreBtnQuantity === 'list')) { t_catalog_addProductQuantity(el_product, productObj, options); } // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog_addProductOptions(recid, productObj, el_product, options); t_catalog_onFuncLoad('t_prod__initProduct', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_prod__initProduct(el_product, options); }); }); t_catalog__updateBgUpOverlayOffsets(rec); // после загрузки товаров - меняем опции в соответствии с фильтрами if ( !isRelevantsShow && // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 window.tCatalogFilters && // @ts-expect-error ST-2949_1 typeof window.tCatalogFilters === 'object' && // @ts-expect-error ST-2949_1 window.tCatalogFilters[recid] && // @ts-expect-error ST-2949_1 typeof window.tCatalogFilters[recid] === 'object' && t_catalog__hasRecUrlParams(recid) ) { const recCustomUrlParams = t_catalog__getRecUrlParams(recid); Array.prototype.forEach.call(productsArr, function (productObj) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 const el_product = rec.querySelector( '.t-catalog__grid-cont .js-product.t-item[data-product-gen-uid="' + productObj.uid + '"]' ); if (!el_product) return; // ищем все опции Array.prototype.forEach.call( el_product.querySelectorAll('.js-product-edition-option'), function updateSelect(editionOption) { let select = editionOption.querySelector('select'); if (!select) return; // Картинку карточки меняем только для опций, привязанных к изображению const optionId = editionOption.getAttribute('data-edition-option-id'); // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 const optionData = (productObj.editionOptions || []).find(opt => opt.id === optionId); const isImageOption = Boolean(optionData?.params?.linkImage); const triggerOptionChangeFromFilter = () => { if (isImageOption) t_catalog__filterSyncProducts.add(el_product); t_catalog_triggerEvent(select, 'change'); t_catalog__filterSyncProducts.delete(el_product); }; let urlParams = recCustomUrlParams; if (!urlParams) return; for (const key of Object.keys(urlParams)) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 const filters = window.tCatalogFilters[recid].filters; if (!filters) return; for (const filter of [...filters]) { // если фильтр это характеристика, то нет необходимости менять значение опций if (filter.name === key && filter.name.indexOf('charact') < 0) { const values = t_catalog__getRecUrlParam(recid, key); // eslint-disable-next-line no-nested-ternary const normalizedValues = Array.isArray(values) ? values : values ? [values] : []; if (normalizedValues.length) { for (const value of [...normalizedValues].reverse()) { if (value !== select.value) { const option = select.querySelector( `[value="${t_catalog_escapeQuote(value)}"]` ); if (option && !option.disabled) { select.value = value; triggerOptionChangeFromFilter(); return; // После первого изменения выходим } } else { triggerOptionChangeFromFilter(); return; } } } } } } } ); }); } // init js events and do js updates // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 if (window.lazy === 'y' || document.getElementById('allrecords').getAttribute('data-tilda-lazy') === 'yes') { if (options.relevants_slider) { setTimeout(function () { t_catalog_onFuncLoad('t_lazyload_update', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_lazyload_update(); }); }, 100); } else { t_catalog_onFuncLoad('t_lazyload_update', function () { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 t_lazyload_update(); }); } } if (document.querySelector('.t706__cartwin') || document.querySelector('.t706__sidebar')) { // TODO ST-2949_4: cannot find name / missing jQuery types (TS2304, TS2592) // @ts-expect-error ST-2949_4 if (typeof tcart__addEvent__links === 'function') { // @ts-expect-error ST-2949_4 tcart__addEvent__links(recid); } } else { console.warn('Warning: cart block is not added to this page'); } t_catalog_initPopup(recid, obj_products, options, isRelevantsShow, obj); if (isListStyle) { setTimeout(() => { // добавляем задержку, чтобы учесть кейс, когда мы проверяем ширину колонки с базовым шрифтом // а потом подгружается реальный шрифт (который может быть больше/меньше чем базовый) t_catalog_unifyCardsWidth(recid); }, 1000); } if (!options.previewmode) { try { /* TODO: fix */ // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 window.tp__record__addEditFieldEvents(recid); } catch (e) { // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 console.error(e.message); } } } /** * Append products to the grid container and show them * * @param {HTMLElement} el_rec * @param {HTMLElement} gridContainer - the grid container where the products will be appended * @param {string} productsHtml - the HTML of the products to be appended to the grid **/ function t_catalog_process_appendAndShowProducts(el_rec, gridContainer, productsHtml) { gridContainer.insertAdjacentHTML('beforeend', productsHtml); hydrateCatalogGalleries(gridContainer); // TODO ST-2949_6: operators / arithmetic / unintentional comparison (TS2362, TS2365, TS2367) // @ts-expect-error ST-2949_6 if (el_rec.getAttribute('data-already-loaded-first-products') === true) { // products in pagination and in tabs we show with transition setTimeout(function () { Array.prototype.forEach.call(el_rec.querySelectorAll('.t-catalog__card'), function (card) { card.classList.remove('t-catalog__card_hidden'); }); t_catalog__updateBgUpOverlayOffsets(el_rec); }, 10); } else { // first products we show without transition Array.prototype.forEach.call(el_rec.querySelectorAll('.t-catalog__card'), function (card) { card.classList.remove('t-catalog__card_hidden'); }); // flag, that next loaded products wouldn't be first for this rec // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 el_rec.setAttribute('data-already-loaded-first-products', true); t_catalog__updateBgUpOverlayOffsets(el_rec); } } /** * Checks if the load button is visible and if it is, it hides it * * @param {string} recid * @param {object} options **/ function t_catalog_mobileHoriz_checkBtnVisibility(recid, options) { // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 var hideLoadBtn = function (recid, opts) { var rec = document.getElementById('rec' + recid); if (window.innerWidth < 960 && opts.hasMobileHorizScroll) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var loadMoreBtn = rec.querySelector('.js-catalog-load-more-btn'); // TODO ST-2949_5: assignability, arguments, calls, return types (TS2345, TS2322, TS2554, TS2769, TS2740, TS2739, TS2353, TS2349, TS2355, TS2366, TS2774, TS18046) // @ts-expect-error ST-2949_5 t_catalog__removeElement(loadMoreBtn); } }; hideLoadBtn(recid, options); t_onFuncLoad('t_throttle', function () { window.addEventListener( 'resize', t_throttle(function () { hideLoadBtn(recid, options); }, 500) ); }); } /** * Make popup window that appears when you click on a product * * @param {string} recid * @param {CatalogOptions} options * @returns {string} - HTML of popup **/ function t_catalog_get_productPopup_html(recid, options) { var str = ''; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var statAttr = options.popup_opts.popupStat ? 'data-track-popup="' + options.popup_opts.popupStat + '"' : ''; // @ts-expect-error ST-2949_3 var popupStyle = options.popup_opts.overlayBgColorRgba ? // @ts-expect-error ST-2949_3 'style="background-color:' + options.popup_opts.overlayBgColorRgba + '"' : ''; var containerClass = 't-popup__container t-popup__container-static '; var verticalAlignClass = options.verticalAlignButtons ? 't-catalog__valign-buttons' : ''; var showRelevants = options.showRelevants; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var titleRelevants = options.titleRelevants ? options.titleRelevants : window.tCatalogDict['seeAlso']; var mobileOneRowClass = options.relevants_slider ? '' : 't-catalog__grid-cont_mobile-one-row'; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 if (options.popup_opts.isVertical) { containerClass += 't-catalog__popup-container_8-cols '; } var containerStyle = ''; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 var sliderClass = options.popup_opts.isVertical ? '' : // @ts-expect-error ST-2949_3 't-catalog__prod-popup__col-left t-col t-col_' + options.popup_opts.columns; // @ts-expect-error ST-2949_3 var infoAlignClass = 't-align_' + (options.popup_opts.align === 'center' ? 'center' : 'left') + ' '; var infoClass = infoAlignClass + // @ts-expect-error ST-2949_3 (options.popup_opts.isVertical ? '' : // @ts-expect-error ST-2949_3 't-catalog__prod-popup__col-right t-col t-col_' + options.popup_opts.columns2); var productElClass = 'js-catalog-product js-product t-catalog__product-popup '; // @ts-expect-error ST-2949_3 if (options.popup_opts.containerBgColor) { // @ts-expect-error ST-2949_3 containerStyle += 'background-color:' + options.popup_opts.containerBgColor + ';'; } // @ts-expect-error ST-2949_3 if (options.popup_opts.popupContainer === '100') { containerStyle += 'max-width:100%;'; productElClass += 't-container_fluid '; } str += '
'; str += t_catalog_get_productPopup_closeIcon_html(options); str += t_catalog_get_productPopup_closeText_html(options); str += '
'; str += '
'; str += '
'; str += '
'; var popupContainerClasses = []; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 if (options.popup_opts.popupContainer === '100') { popupContainerClasses.push('t-container_fluid'); } str += popupContainerClasses.length ? '
' : '
'; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 if (options?.breadcrumbs?.hasBreadcrumbs && !options?.breadcrumbs?.hideBreadcrumbsProduct) { // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 str += `
`; } str += '
'; str += '
'; str += t_catalog_get_productPopup_titleText_html(); str += '
'; str += t_catalog_get_productPopup_onePrice_html(options, 'current'); str += t_catalog_get_productPopup_onePrice_html(options, 'old'); str += '
'; str += '
'; str += t_catalog_get_productPopup_linksSizeChart_html(); str += t_catalog_get_productPopup_buyBtn_html(options); str += t_catalog_get_productPopup_text_html(); str += '
'; str += '
'; str += '
'; if (showRelevants) { str += '
'; str += '
'; str += '
' + titleRelevants + '
'; str += '
'; // TODO ST-2949_3: null / undefined (TS18047, TS18048, TS2531, TS2722, TS2454, TS2538) // @ts-expect-error ST-2949_3 if (!options.relevants_slider && options.prodCard.listStyle === 'tile') { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 str += t_catalog_get_handIcon_html(recid, options.horizontalScrollHint); } str += '
'; str += '
'; } str += '
'; str += '
'; str += '
'; str += '
'; return str; } /** * Make a HTML code that will contain the product description * * @returns {string} - HTML code **/ function t_catalog_get_productPopup_text_html() { var str = ''; str += '
'; return str; } /** * Make a size chart link * * @returns {string} - HTML code **/ function t_catalog_get_productPopup_linksSizeChart_html() { var str = ''; str += ''; return str; } /** * Make 'buy' button in the popup * * @param {object} options * @returns {string} - HTML code **/ function t_catalog_get_productPopup_buyBtn_html(options) { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 const template = document.getElementById(`button_buy_${options.recid}`); // @ts-expect-error ST-2949_1 if (!template || !template.content) return t_catalog_get_productPopup_buyBtn_html_legacy(options); // @ts-expect-error ST-2949_1 const buttonTemplate = template.content.cloneNode(true); return `
${buttonTemplate.firstElementChild.outerHTML}
`; } /** * Функция оставлена для обратной совместимости * со старыми блоками, где нет нового шаблона кнопки */ // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_get_productPopup_buyBtn_html_legacy(options) { var str = ''; var btnStyle = options.btn1_style; var btnTitle = options.popup_opts.btnTitle; if (btnTitle !== '') { str += ''; } return str; } /** * Make HTML for the price of the product * * @param {object} options * @param {string} type - 'current' or 'old' * @returns {string} - HTML code **/ function t_catalog_get_productPopup_onePrice_html(options, type) { var str = ''; var priceStylingClass = type === 'current' ? 'js-catalog-prod-price t-catalog__prod-popup__price' : 'js-catalog-prod-price-old t-catalog__prod-popup__price_old'; // стили для типографики вынесены в отдельный тег ' + '' + '
'; var circleIcon = '
' + '' + '' + '' + '' + '
'; if (horizontalScrollHint === 'hand' || !horizontalScrollHint) { return handIcon; } else if (horizontalScrollHint === 'circle') { return circleIcon; } else return ''; } /** * Make a HTML code for the empty message * * @param {object} options * @returns {string} - HTML code **/ function t_catalog_get_emptyMsg_html(options) { var str = ''; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var styles = options.typo.titleColor ? // @ts-expect-error ST-2949_1 'color:' + options.typo.titleColor + ';border-color:' + options.typo.titleColor + ';' : ''; var classStr = 'js-catalog-empty-part-msg t-catalog__empty-part-msg-cont'; str += ''; return str; } /** * Make a HTML code for the error box * * @param {object} options * @param {string} errorText - the text to display in the error box * @returns {string} - HTML code **/ function t_catalog_get_errorBox(options, errorText) { var str = ''; // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 var styles = options.typo.titleColor ? // @ts-expect-error ST-2949_1 'color:' + options.typo.titleColor + ';border-color:' + options.typo.titleColor + ';' : ''; var classStr = 'js-catalog-error-msg t-catalog__error-msg-cont'; // тексты ошибок могут попадать в индексацию поисковыми роботами, поэтому игнорируем роботов и не шлём текст с ошибкой (пустую строчку str) str += ''; str += ''; str += ''; str += ''; str += ''; return str; } // Хлебные крошки // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_breadcrumbs__init(recid, options) { return initBreadcrumbs(recid, options); } // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_breadcrumbs__update(recid, options) { return updateBreadcrumbs(recid, options); } var t_catalog__cardTemplateHelpers = { get isMobile() { // TODO ST-2949_1: missing properties on Window/DOM/data objects (TS2339, TS2551) // @ts-expect-error ST-2949_1 return window.tCatalogIsMobile; }, getFirstAvailableEditionData: t_catalog_product_getFirstAvailableEditionData, getProductCardLink: t_catalog_get_productCard_link, getProductCardTargetAttr: t_catalog_get_productCard_targetAttr, getProductCardImgHtml: t_catalog_get_productCard_img_html, getProductCardPriceHtml: t_catalog_get_productCard_Price_html, getProductCardButtonsHtml: t_catalog_get_productCard_btn_html, }; // TODO ST-2949_2: implicit any on params, vars, this, and index access (TS7006, TS7005, TS7008, TS7034, TS2683, TS7053, TS7015) // @ts-expect-error ST-2949_2 function t_catalog_get_productCard_html(rec, product, options, isRelevantsShow, key, productsArr) { // Если в блоке есть шаблон-болванка карточки (