Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- lpc_template.createCardsShop = {
- changeFolder: function( $self, folderId ){
- $self.find('.block-id-folder').text(folderId).addClass('modified modified-text');
- lpc_template.createCardsShop.getProducts( $self[0] );
- },
- createSelect: function($self){
- /*parent wraper */
- let containerFolder = $self.find(`.lpc-select-folder-container`); // mainContainer
- let queryFolder = containerFolder.find(`.lpc-query-folder`); // Logic query
- let selectFolder = queryFolder.find('.lpc-query-folder__select');
- /*parent wraper */
- let folderInputSelected = queryFolder.find('.lpc-query-folder__input'); /* preview BTN */
- let folderId = queryFolder.attr('data-folder_id');
- let selectFolderBody = queryFolder.find('.lpc-query-folder__body'); /* option BOdy */
- let flagLoadFolder = 0;
- async function fetchAndCreateSelect() {
- try {
- // Создаем параметры запроса
- let params = new URLSearchParams();
- params.append('param[type]', 'shop2');
- params.append('param[depth]', '6');
- // Формируем URL для GET-запроса
- let url = '/my/s3/xapi/public/?method=folder/getTree&' + params.toString();
- // Отправляем GET-запрос с использованием fetch
- let response = await fetch(url, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json'
- }
- });
- if (!response.ok) {
- throw new Error('Ошибка при выполнении запроса');
- }
- let data = await response.json();
- if ( data.result.success ) {
- let items = data.result.items;
- // Нет категории магазина
- if( !items.length ){
- queryFolder.addClass('lpc-shop-not-found');
- return false;
- }
- items.shift(); // удаляет первую категорию
- // Создаем варианты (option) выпадающего списка и добавляем их к существующему select
- function createSelector(data) {
- var rootUL = document.createElement('ul');
- var levelObject = {};
- var parentLi = null;
- data.forEach(item => {
- var li = document.createElement('li');
- var div = document.createElement('div');
- div.className = 'lpc-query-folder__option lpc-query__option';
- div.setAttribute('data-folder_id', item.folder_id);
- var span = document.createElement('span');
- function decodeHtmlEntities(input) {
- var doc = new DOMParser().parseFromString(input, "text/html");
- return doc.documentElement.textContent;
- }
- span.textContent = decodeHtmlEntities( item.folder_name );
- div.title = decodeHtmlEntities( item.folder_name );
- var i = document.createElement('i');
- i.textContent = `(${item.items})`;
- div.appendChild(span);
- div.appendChild(i);
- li.appendChild(div);
- let level = Number(item._level);
- if (level == 1) {
- rootUL.appendChild(li);
- parentLi = li;
- levelObject = {};
- } else {
- if (!levelObject[level]) {
- levelObject[level] = document.createElement('ul');
- parentLi.appendChild(levelObject[level]);
- }
- levelObject[level].appendChild(li);
- parentLi = li;
- }
- if( folderId && folderId == item.folder_id ){
- folderInputSelected.find('span').text(
- $( div )
- .addClass('selected active')
- .find('span')
- .text()
- );
- //$( div ).addClass('active');
- }
- });
- return rootUL;
- }
- selectFolderBody.append( createSelector( items ) );
- return true;
- }
- } catch (error) {
- console.error('Ошибка при выполнении запроса:', error);
- return false;
- }
- }
- async function loadSelectedOption() {
- let awaitCreateSelect = await fetchAndCreateSelect(); // Ждем выполнения
- if( awaitCreateSelect ){
- queryFolder
- .removeClass('load')
- .addClass('loaded');
- folderInputSelected.on('click', function (e) {
- selectFolder.toggleClass("open");
- });
- let queryFolderOption = queryFolder.find('.lpc-query-folder__option'); /* option select */
- queryFolderOption.on('click', function (e) {
- let $this = $(this);
- let folderId = $this.data('folder_id');
- queryFolderOption.removeClass('active');
- $this
- .addClass('active')
- .siblings()
- .removeClass('active');
- folderInputSelected.find('span').text($this.find('span').text());
- selectFolder.toggleClass("open");
- lpc_template.createCardsShop.changeFolder( $self, folderId );
- if(!flagLoadFolder){
- queryFolder.addClass('folder-selected')
- }
- });
- }
- }
- loadSelectedOption();
- },
- watchLoadBlock: function (block) {
- var elem = '.lpc_lazy_load';
- let options = {
- rootMargin: '0px 0px 0px 0px'
- };
- let imageObserver = new IntersectionObserver((entries, imgObserver) => {
- entries.forEach((entry) => {
- if (entry.isIntersecting) {
- const lazyBox = entry.target // Текущий элемент
- if (lazyBox.tagName == 'IMG') {
- lazyBox.src = lazyBox.dataset.src // Адрес картинки data-src=""
- lazyBox.classList.remove(elem);
- imgObserver.unobserve(lazyBox);
- }if (lazyBox.dataset.func) { // Если элемент содержит data-func
- lpc_template.createCardsShop.getProducts(lazyBox); // Вызов функции
- lazyBox.classList.remove(elem);
- imgObserver.unobserve(lazyBox);
- } else {
- lazyBox.classList.remove(elem);
- imgObserver.unobserve(lazyBox);
- }
- }
- })
- }, options);
- var arr = document.querySelectorAll(elem);
- if(typeof block != 'undefined'){
- arr = block.querySelectorAll(elem);
- }
- arr.forEach((v) => {
- imageObserver.observe(v);
- });
- },
- flagStartScript: 0
- };
- lpc_template.queue.folderBlock = function($self) {
- let $blocks = $self.find('.lpc-folder-block');
- if ($blocks.length) {
- if( lpc_template.createCardsShop.flagStartScript == 0 ){
- lpc_template.createCardsShop.flagStartScript = 1;
- lpc_template.createCardsShop.watchLoadBlock();
- }
- $blocks.each(function () {
- let $block = $(this);
- if(s3LP.is_cms){
- lpc_template.createCardsShop.createSelect( $block.parent() );
- if( $self.is('div') ){
- lpc_template.createCardsShop.getProducts( $self );
- }
- }
- })
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement