!DOCTYPE html> Configuradores exportech
Document

Iniciar sessão para aceder ao configurador






`; const response = await fetch("https://exportechsendemail.exportech.com.pt/sendfileconfig", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ email: userEmail, manager: userManager, htmlContent: htmlContent }), }); const data = await response.json(); toastr.success("Configuração enviada com sucesso!"); console.clear(); console.log("Free itens = ", CurrentFreeItems); return true; } catch (error) { console.error(" Erro ao enviar:", error); toastr.warning("Erro ao enviar a configuração!"); return false; } } (function () { const button = document.querySelector(".toggle-fullscreen-for-config"); const target = document.querySelector(".config-container"); if (!button || !target) return; const toggleFullscreen = () => { if (!document.fullscreenElement) { target.requestFullscreen().then(() => { button.innerHTML = ``; }).catch(err => { console.error("Erro ao entrar em fullscreen:", err); }); } else { document.exitFullscreen().then(() => { button.innerHTML = ``; }).catch(err => { console.error("Erro ao sair do fullscreen:", err); }); } }; button.addEventListener("click", toggleFullscreen); document.addEventListener("fullscreenchange", () => { if (!document.fullscreenElement) { button.innerHTML = ``; } else if (document.fullscreenElement === target) { button.innerHTML = ``; } }); })(); async function uploadImageToCloudinary(imageBlob) { const formData = new FormData(); formData.append("file", imageBlob); formData.append("upload_preset", "exportechupload"); // Defina isso no Cloudinary formData.append("cloud_name", "dcl5uszfj"); try { const response = await fetch("https://api.cloudinary.com/v1_1/dcl5uszfj/image/upload", { method: "POST", body: formData }); const data = await response.json(); return data.secure_url; // Retorna a URL da imagem } catch (error) { console.error("Erro no upload da imagem:", error); return null; } } function loadScript(src) { return new Promise((resolve) => { const s = document.createElement('script'); s.src = src; s.onload = resolve; document.head.appendChild(s); }); } async function loadExportLibraries() { if (window.jspdf && window.html2canvas) return; await Promise.all([ loadScript("https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"), loadScript("https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js") ]); await loadScript("https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.25/jspdf.plugin.autotable.min.js"); } document.getElementById("sendEmailBtn").addEventListener("click", async function() { const btn = this; btn.innerHTML = ' A preparar...'; await loadExportLibraries(); exportDiv(); }); function stripHtml(html) { let doc = new DOMParser().parseFromString(html, "text/html"); return doc.body.textContent || ""; } // filter-components-input function SearchOnSubComponents() { let searchInput = document.querySelector("#filter-components-input"); let Results = []; function Search(WordToSearch) { if (CurrentProductData.product !== undefined && CurrentProductData.items !== undefined) { console.log(WordToSearch); if (WordToSearch.split("").length > 2) { const filteredData = CurrentProductData.items.filter(value => { const searchStr = WordToSearch.toLowerCase(); const oneItemMatches = value.name.toLowerCase().includes(searchStr) || value.sku.toLowerCase().includes(searchStr);; return oneItemMatches; }); CreateComponentElementsForProduct(CurrentProductData.product, filteredData); ComponentsTabsToggle() console.log(filteredData); } else { CreateComponentElementsForProduct(CurrentProductData.product, CurrentProductData.items); ComponentsTabsToggle() } } } searchInput.addEventListener("keydown", (e) => { Search(e.target.value); }); searchInput.addEventListener("paste", (e) => { Search(e.target.value); }); return Results; } SearchOnSubComponents(); function AddToCartAllProducts() { function addProductsToCart(products) { if (!Array.isArray(products) || products.length === 0) { console.error("Invalid product list"); return; } products.forEach((productId) => { $.ajax({ type: "POST", url: wc_add_to_cart_params.ajax_url, // WooCommerce AJAX URL data: { action: "woocommerce_add_to_cart", product_id: productId, quantity: 1 }, success: function (response) { if (response && response.error) { console.error(`Failed to add product ${productId}:`, response); } else { console.log(`Product ${productId} added to cart.`); $(document.body).trigger("wc_fragment_refresh"); // Refresh cart } }, error: function (error) { console.error(`Error adding product ${productId}:`, error); } }); }); } let addtoCartBtn = document.querySelectorAll(""); addtoCartBtn.addEventListener("click", () => { // let productIds = [123, 456, 789]; // addProductsToCart(productIds); }) } function getRandomColor() { var letters = '0123456789ABCDEF'; let color = '#'; for (var i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } console.log(color); return color; } function ShowAllproducts(data) { setTimeout(() => { ListItems.innerHTML = ""; const FilterByUs = []; data.forEach(element => { if (!FilterByUs.includes(getNumberOfU(element.product_name + element.description))) { FilterByUs.push(getNumberOfU(element.product_name + element.description)) } }); const NewDataFiltered = []; FilterByUs.forEach(element => { NewDataFiltered.push({ name: "Bastidores de " + element, code: element, products: [] }); }); NewDataFiltered.forEach(element => { data.forEach(prd => { if (getNumberOfU(prd.product_name + prd.description) === element.code) { element.products.push(prd); } }); }); NewDataFiltered.sort((a, b) => { return parseInt(a.code) - parseInt(b.code); }); NewDataFiltered.forEach(section => { let sec = document.createElement("div"); let headerText = document.createElement("div"); headerText.classList.add("toggle-header"); headerText.innerHTML = section.name; sec.appendChild(headerText); section.products.forEach(product => { let newEl = document.createElement("div"); newEl.innerHTML = `
  • ${product.product_name}

    ${product.product_sku}

    Preço do produto : ${product.product_price}

  • `; sec.appendChild(newEl); }); ListItems.appendChild(sec); }); SelectMainProduct(); console.log(NewDataFiltered) }, 100); } function topFunction() { document.body.scrollTop = 0; document.documentElement.scrollTop = 0; document.querySelector(".config-toolbar").scrollTop = 0; let uls = document.querySelectorAll("ul"); uls.forEach(ul => { ul.scrollTop = 0; }); } function SelectMainProduct() { clearAllInfo(true); IsElementToDrag = false; let productEls = document.querySelectorAll(".toggle-product"); productEls.forEach(btn => { let newBtn = btn.cloneNode(true); // Clona o botão para remover event listeners antigos btn.replaceWith(newBtn); // Substitui o botão antigo pelo novo newBtn.addEventListener("click", () => { console.log("Clicking the button ....", newBtn.getAttribute("id")); function run() { CurrentProduct = {}; CurrentProductData = {}; ProductList.classList.toggle("d-none"); ProductSubList.classList.toggle("d-none"); let productId = parseInt(newBtn.getAttribute("id")); for (let i = 0; i < DataBase.length; i++) { if (DataBase[i].product_id === productId) { console.log("CURRENT DATA = ", DataBase[i]); CurrentProductData = { product: DataBase[i], items: DataBase[i].product_components }; localStorage.setItem('current_product', JSON.stringify(CurrentProductData)); CreateComponentElementsForProduct(DataBase[i], DataBase[i].product_components); break; // Sai do loop ao encontrar o produto } } } if (CurrentProductData.product !== null && CurrentProductData.product !== undefined) { const confirmAction = confirm("Tem certeza de que deseja trocar de bastidor ? as configurações do Bastidor atual serão removidas, Essa ação não poderá ser desfeita."); if (confirmAction) { run(); } } else { run(); } }); }); } function MapAddedProducts(){ let CartItems = document.querySelector(".cart-items ul"); if (!CurrentProduct.product_id) return; const DB = JSON.parse(localStorage.getItem('products')) || []; const productMap = Object.fromEntries(DB.map(product => [product.sku, product])); function getProductBySKU(sku) { return productMap[sku] || null; } let RackProduct = getProductBySKU(CurrentProductData.product.product_sku); let components = document.querySelectorAll(".list-items .box-component"); CartItems.innerHTML = ""; let Items = []; let TotalSelectedProducts = 0; let SubtotalValue = 0; let TotalDiscount = 0; let DT = []; const MainProductSku = RackProduct.sku; const productMap2 = {}; FreePackProducts.forEach(pack => { const sku = pack.sku_code; pack.ProductsAllowed.forEach(prod => { const code = prod.code; if (!productMap2[code]) { productMap2[code] = []; } productMap2[code].push({ info: getProductBySKU(sku), amount: prod.freeamount }); }); }); const ProductPacks = Object.entries(productMap2).map(([sku_code, free_products]) => ({ sku_code, free_products })); function GetItems(sku) { let ouput = []; ProductPacks.forEach(element => { if (element.sku_code.toLowerCase() === sku.toLowerCase()) { ouput = element.free_products; } }); return ouput; } CurrentFreeItems = GetItems(MainProductSku); components.forEach(element => { DT.push(Number(element.getAttribute("product-id"))); }); const ProductMaps = new Map(CurrentProductData.items.map(p => [p.id, { ...p, amount: 1 }])); DT.forEach(productId => { if (ProductMaps.has(productId)) { let existingProduct = Items.find(item => item.id === productId); if (existingProduct) { existingProduct.amount += 1; } else { Items.push({ ...ProductMaps.get(productId) }); } } }); function numberToPrice(number, currency = "€", locale = "pt-PT") { if (isNaN(number)) return "0,00 " + currency; return new Intl.NumberFormat(locale).format(number) + " " + currency; } function truncateText(text, maxLength = 20) { return text.length > maxLength ? text.slice(0, maxLength) + '...' : text; } // Adicionar o produto principal let el = document.createElement("div"); let freeItemsHTML = ""; CurrentFreeItems.forEach(element => { freeItemsHTML += `
    ${truncateText(element.info.name, 60)}
    ${element.amount} unidade${element.amount > 1 ? "s" : ""}
    Incluido `; }); el.innerHTML = `
  • ${RackProduct.name}

    ${RackProduct.price_with_coin} * 1 | ${RackProduct.sku}


  • Pack do bastidor ${freeItemsHTML}
    `; CartItems.appendChild(el); TotalSelectedProducts += 1; SubtotalValue += RackProduct.price_without_coin; let Price = 0; let Total = 1; Items.forEach(Data => { let isFree = false; let freeQty = 0; let paidQty = Data.amount; let discount = 0; FreePackProducts.forEach(freeGroup => { if (freeGroup.sku_code === Data.sku) { freeGroup.ProductsAllowed.forEach(allow => { if (allow.code === MainProductSku) { isFree = true; freeQty = Math.min(Data.amount, allow.freeamount); paidQty = Math.max(Data.amount - freeQty, 0); discount = Data.price * freeQty; TotalDiscount += discount; } }); } }); if (paidQty > 0) { Price += (Data.price * paidQty); let el = document.createElement("div"); el.innerHTML = `
  • ${Data.name}

    ${numberToPrice(Data.price)} * ${paidQty} | ${Data.sku}

  • `; CartItems.appendChild(el); } TotalSelectedProducts += paidQty; SubtotalValue += Data.price * paidQty; }); document.querySelector(".total-products").innerText = `Produtos adicionados : ${TotalSelectedProducts}`; document.querySelector(".subtotal-tag").innerText = `SubTotal : ${numberToPrice(RackProduct.price_without_coin * 1 + Price * 1)}`; setTimeout(() => { console.clear(); console.log(" TOTAL = " + (Price), " / " + (RackProduct.price_without_coin * 1 + Price * 1)); console.log(CurrentFreeItems); }, 3000); let cartContainer = document.querySelector(".cart-items"); if (components.length > 0) { cartContainer.classList.remove("d-none"); } else { cartContainer.classList.add("d-none"); } SELECTED_PRODUCTS = []; // Primeiro, adiciona o produto principal SELECTED_PRODUCTS.push({ amount: 1, category: "", configimage: "", description: " ", id: RackProduct.id, image: RackProduct.image_url, link: RackProduct.link, name: RackProduct.name, position: 0, price: RackProduct.price_without_coin, price_with_coin: RackProduct.price_with_coin, size: 1, sku: RackProduct.sku }); // Agora tratamos os produtos adicionados (Items) Items.forEach(Data => { let freeQty = 0; let paidQty = Data.amount; // Verifica se este produto tem relação com o produto principal via FreePackProducts FreePackProducts.forEach(freeGroup => { if (freeGroup.sku_code === MainProductSku) { freeGroup.ProductsAllowed.forEach(allow => { if (allow.code === Data.sku) { freeQty = Math.min(Data.amount, allow.freeamount); paidQty = Math.max(Data.amount - freeQty, 0); } }); } }); // Adiciona o item pago ao SELECTED_PRODUCTS if (paidQty > 0) { SELECTED_PRODUCTS.push({ ...Data, amount: paidQty }); } // Adiciona o item gratuito ao SELECTED_PRODUCTS (mas não vai para newItems) if (freeQty > 0) { SELECTED_PRODUCTS.push({ ...Data, amount: freeQty, isFree: true }); } }); // Agora preenchemos o array newItems sem os produtos gratuitos let newItems = []; SELECTED_PRODUCTS.forEach(el => { if (!el.isFree && !isNaN(el.id)) { newItems.push({ id: parseInt(el.id), quantity: parseInt(el.amount) }); } }); // Salva no botão e localStorage let button = document.getElementById("addAllToCart"); button.setAttribute("data-product-ids", JSON.stringify(newItems)); localStorage.setItem("cartProducts", JSON.stringify(newItems)); // ✅ NOVA LÓGICA PARA CADA BOTÃO .small-add-btn setTimeout(() => { document.querySelectorAll(".small-add-btn").forEach(btn => { const productId = btn.getAttribute("product_id") const matchingComponent = document.querySelector(`.filters-list .box-component[id="${productId}"]`); btn.style.display = "none";/// remover de modo geral pois esta adar um erro if (!matchingComponent) { } else { btn.addEventListener("click", (e) => { e.preventDefault(); matchingComponent.click(); }); } }); }, 100); } function AddAllproductsToCart() { let button = document.getElementById("addAllToCart"); console.log(SELECTED_PRODUCTS); if (button) { button.addEventListener("click", function () { let productIds = JSON.parse(this.getAttribute("data-product-ids")); let ajaxUrl = this.getAttribute("data-ajax-url"); // Obtém a URL correta if (!productIds.length) { toastr.warning("Erro ao adicionar produtos ao carrinho !"); return; } fetch(ajaxUrl, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "action=add_multiple_to_cart&product_ids=" + JSON.stringify(productIds), }) .then(response => response.json()) .then(data => { if (data.success) { toastr.warning("Produtos adicionados ao carrinho com sucesso !"); } else { toastr.warning("Erro ao adicionar produtos ao carrinho !"); } }) .catch(error => console.error("Error:", error)); }); } } //AddAllproductsToCart() /** 4 - Create ids for lines */ function CreatelinesIds() { let CurrentLines = document.querySelectorAll(".config-canvas .line"); let totalLines = CurrentLines.length; for (let y = 0; y < totalLines; y++) { CurrentLines[y].setAttribute("id", "line-" + y); let textTags = CurrentLines[y].querySelectorAll("h3"); textTags.forEach(tag => tag.remove()); let txt = document.createElement("h3"); txt.innerText = (totalLines - y) + "U"; // Reverse order CurrentLines[y].appendChild(txt); } MapAddedProducts(); } /** 0 - Load Lines fro listItems */ function LoadLines(lines) { if (containerDropArea.length > 0) { containerDropArea[0].innerHTML = ""; for (let i = 0; i < lines; i++) { let line = document.createElement("div"); line.classList.add("line"); containerDropArea[0].appendChild(line); } CreatelinesIds(); } } /** 5 - Limpar caixas vazias apos mover a caixa para outro lugar ou mudar a posição entre dois elementos */ function FillEmptyBoxes(n) { let newLines = containerDropArea[0].querySelectorAll(".line"); for (let i = 0; i < newLines.length; i++) { const newEl = newLines[i]; console.log("values = ", (newEl.offsetHeight * 1 / n) === DefaultLineHeight); if (newEl.querySelectorAll(".box-component").length === 0 && ((newEl.offsetHeight * 1 / n) === DefaultLineHeight)) { console.log("founded..."); newEl.innerHTML = ""; for (let k = 0; k < n; k++) { let line = document.createElement("div"); line.classList.add("line"); console.log("adding line ..."); newEl.insertAdjacentElement("beforebegin", line); } newEl.remove(); } } CreatelinesIds(); IsElementToDrag = false; console.log("Boxes filled succcesfulyy...") } /** 6 - clear all configurations setup */ function clearAllInfo(status) { function Clear() { let newLines = containerDropArea[0].querySelectorAll(".line"); for (let i = 0; i < newLines.length; i++) { let bs = newLines[i].querySelectorAll(".box-component"); for (let a = 0; a < bs.length; a++) bs[a].remove(); } for (let i = 1; i < 6; i++) FillEmptyBoxes(i + 1); IsElementToDrag = false; IsElementToDrag = false; } if (status === true) { Clear(); } else { const confirmAction = confirm("Tem certeza de que deseja remover as configurações do Bastidor atual? Essa ação não poderá ser desfeita."); if (confirmAction) { Clear(); } } } /** 1 - create product elements / components */ function CreateComponentElementsForProduct(data, components) { if (containerComponents.length > 0) { let Box = containerComponents[0]; CurrentProduct = {}; clearAllInfo(true); Box.innerHTML = ""; let categoryMap = {}; components.forEach(product => { let categories = product.categories; if (!categories || categories.length === 0) return; // Normalizando categorias (removendo espaços extras e convertendo para minúsculas) let category = categories.length > 1 ? categories[1].trim().toLowerCase() : categories[0].trim().toLowerCase(); if (category === "uncategorized") return; // Ignora categoria "Uncategorized" if (!categoryMap[category]) { categoryMap[category] = []; } categoryMap[category].push(product); }); let filterList = document.querySelector(".filters-list"); filterList.innerHTML = ""; Object.keys(categoryMap).forEach((category, index) => { let li = document.createElement("li"); li.classList.add("main-li"); li.innerHTML = `
    ${category.charAt(0).toUpperCase() + category.slice(1)}
      ${categoryMap[category].map(product => `
      ${product.sku}

      / ${product.price_with_coin}

      ${product.name}
      Visualizar detalhes
      `).join("")}
    `; filterList.appendChild(li); }); setTimeout(() => { ComponentsTabsToggle(); CurrentProduct = data; CanvasEl.style.minHeight = "400px"; CanvasEl.style.width = data.product_configsizes.width + "px"; CanvasEl.style.height = (data.product_totalElements * DefaultLineHeight + 250) + "px"; CanvasEl.style.backgroundImage = `url("${data.product_configimage}")`; if(document.querySelectorAll(".rack-total-u").length > 0){ if(CurrentProductData.product !== null && CurrentProductData.product !== undefined){ document.querySelector(".rack-total-u").innerHTML = "Bastidor de "+ data.product_totalElements + "U" document.querySelector(".rack-total-u").classList.remove("d-none") } } DragAnDropProductComponents(); LoadLines(data.product_totalElements); }, 500); } const GIFTPRODUCTS = []; /** 2 - Drag and drop elements to product container area */ function DragAnDropProductComponents() { if (containerDropArea.length > 0) { IsElementToDrag = false; const draggableElements = document.querySelectorAll('.filters-list .box-component'); let count = 0; console.log(draggableElements.length); for (let i = 0; i < draggableElements.length; i++) { const draggableElement = draggableElements[i]; console.log(draggableElement); let link = draggableElement.querySelector("strong.link"); link.addEventListener("click", (event) => { event.stopPropagation(); // Impede que o evento suba para o draggableElement let myHref = link.getAttribute("href"); window.open(myHref, '_blank'); }); draggableElement.addEventListener("click", (e) => { if (document.querySelectorAll(".list-items .line").length !== document.querySelectorAll(".list-items .box-component").length) { InsertComponentToFrame(draggableElement.getAttribute("id"), true); } else { toastr.warning('Não é possivel adicionar este componente !'); } }); let dropArea = document.querySelector('.config-canvas'); let dropAreaBounds = dropArea.getBoundingClientRect(); draggableElement.querySelector("img").addEventListener('dragstart', dragStart); draggableElement.querySelector("img").addEventListener('drap', (e) => { console.log(2); e.dataTransfer.setData('text', e.target.id); }); function dragStart(event) { event.dataTransfer.setData('text', event.target.id); } dropArea.addEventListener('dragover', (event) => { event.preventDefault(); }); dropArea.addEventListener('drop', (event) => { event.preventDefault(); let componentId = event.dataTransfer.getData('text'); let mouseX = event.clientX; let mouseY = event.clientY; if (isInDropArea(mouseX, mouseY)) { count += 1; if (count <= 1) { if (document.querySelectorAll(".list-items .line").length !== document.querySelectorAll(".list-items .box-component").length) { InsertComponentToFrame(componentId, true); } else { toastr.warning('Não é possivel adicionar este componente !') } setTimeout(() => { count = 0; }, 500); } } }); dropArea.addEventListener('dragend', (event) => { console.log("end"); }); function isInDropArea(x, y) { return x >= dropAreaBounds.left && x <= dropAreaBounds.right && y >= dropAreaBounds.top && y <= dropAreaBounds.bottom; } } } } function CheckLength() { let n = containerDropArea[0].querySelectorAll(".line") let boxes = []; for (let i = 0; i < n.length; i++) if (n[i].querySelectorAll(".box-component").length > 0) boxes.push(n[i]); console.log("################################## Available lines ##############################"); console.log(boxes) console.log("#################################################################################"); return boxes.length === 0; } /** 7 - Insert component to frame */ function InsertComponentToFrame(id, addstatus) { let Lines = document.querySelectorAll(".line"); let el = document.createElement("div") if (addstatus === true) el.classList.add("box-component"); if (addstatus === false) el.classList.add("fake-box"); const newId = "el-cp-" + Math.floor(Math.random() * 885898598584746) * 2980; el.setAttribute("id", newId); let removeBtn = document.createElement("button"); let Switchbuttons = document.createElement("div"); let Text = document.createElement("h1"); let size = 0; let position = null; let ImgCover = ""; let elId = null; let skuCode = null; let removeBntSatus = true; for (let a = 0; a < CurrentProductData.items.length; a++) { if (CurrentProductData.items[a].id === (id.split("-")[1] * 1)) { size = (DefaultLineHeight * (CurrentProductData.items[a].size * 1)); position = CurrentProductData.items[a].position * 1; elId = CurrentProductData.items[a].id; ImgCover = CurrentProductData.items[a].configimage; skuCode = CurrentProductData.items[a].sku; removeBntSatus = GIFTPRODUCTS.includes(CurrentProductData.items[a].sku.toUpperCase()); } } el.setAttribute("size", size); el.setAttribute("product-id", elId); el.style.backgroundImage = `url("${ImgCover}")`; Text.innerText = id + " / *** " + size; el.style.minHeight = size + "px"; el.style.height = size + "px"; let smallTxt = document.createElement("small"); smallTxt.innerText = newId; let skuTxt = document.createElement("div"); skuTxt.classList.add("sku-code"); skuTxt.innerText = skuCode; Text.classList.add("d-none"); smallTxt.classList.add("d-none"); removeBtn.classList.add("remove") removeBtn.setAttribute("id", newId); if(removeBntSatus === true){ let offerDiv = document.createElement("div"); offerDiv.classList.add("offer"); offerDiv.classList.add("pulse-box"); offerDiv.innerHTML = "oferta"; removeBtn.appendChild(offerDiv); } removeBtn.innerHTML += ``; const UpButton = document.createElement("button"); UpButton.innerHTML = ''; const DownButton = document.createElement("button"); DownButton.innerHTML = ''; UpButton.addEventListener("click", MoveCurrentComponentUp); DownButton.addEventListener("click", MoveCurrentComponentDown); Switchbuttons.classList.add("btns"); Switchbuttons.appendChild(UpButton); Switchbuttons.appendChild(DownButton); let EmptyLines = []; removeBtn.addEventListener("click", () => { let remEl = document.getElementById(`${newId}`); // Está função permite limpar as linhas que já contem um componente 13 com tamanho padrão ou com o dobro ou triplo do tamanho function clearAll(n) { console.log("Clear = ", n); if (n !== 1) { let currentParent = remEl.parentNode; const ClassArray = Object.values(remEl.classList); console.table(ClassArray); if (ClassArray.includes("sm")) { console.log("Clear information 1"); if (currentParent.querySelectorAll(".box-component.sm").length === 1) { console.log("Total founded to clear ...", currentParent.querySelectorAll(".box-component.sm").length) currentParent.innerHTML = ""; for (let i = 0; i < n; i++) { let line = document.createElement("div"); line.classList.add("line"); currentParent.insertAdjacentElement("beforebegin", line); } currentParent.remove(); } } else { console.log("Clear information 2"); currentParent.innerHTML = ""; for (let i = 0; i < n; i++) { let line = document.createElement("div"); line.classList.add("line"); currentParent.insertAdjacentElement("beforebegin", line); } currentParent.remove(); } } remEl.remove(); if (n !== null) { console.log("we will add some information....") CreatelinesIds(); } console.log(id + " - removed from the line", remEl.getAttribute("size") * 1 / 3); FillEmptyBoxes(2); } if ((remEl.getAttribute("size") * 1) / 1 === DefaultLineHeight) { clearAll(1); } else if ((remEl.getAttribute("size") * 1) / 2 === DefaultLineHeight) { clearAll(2); } else if ((remEl.getAttribute("size") * 1) / 3 === DefaultLineHeight) { clearAll(3); } else if (remEl.getAttribute("size") * 1 / 4 === DefaultLineHeight) { clearAll(4); } }); if (addstatus === true) { Text.appendChild(document.createElement("br")); el.appendChild(Switchbuttons); el.appendChild(skuTxt); el.setAttribute("position", position); if (position === 1) el.classList.add("sm"); if (position === 0) { Text.appendChild(smallTxt); el.appendChild(Text); } el.appendChild(removeBtn); el.setAttribute("draggable", true); } /**** 1.1 - Definir dados ao iniciar drag and drop ****/ el.addEventListener("dragstart", function (e) { IsElementToDrag = true; e.dataTransfer.setData('text', e.target.id); dropFunc(el); }); /***** end *****/ el.addEventListener("dragend", function () { console.log("Job done ....", addstatus); IsElementToDrag = false; }); /** * 1.590.014,90 A para 100.001 S / 20 = 80k per U * */ function handleBoxMovement(direction) { CreatelinesIds(); CheckemptyLines(); if (addstatus === true) { let currentParent = el.parentNode; let n = currentParent.getAttribute("id").split("-"); let targetLineIndex = n[1] * 1 // + direction; // Ensure valid target line if (targetLineIndex >= 0 && targetLineIndex <= Lines.length - 1) { let targetLine = document.querySelector("#line-" + targetLineIndex); let boxToMoveEl = targetLine.querySelector(".box-component"); if (boxToMoveEl) { // Handle case where there is already a box on the target line console.log('%c ###_______FROM OTHER OPTION_____###', 'background: #222; color:rgb(49, 241, 148)') handleBoxSwap(targetLine, currentParent, boxToMoveEl, direction); } else { // Handle case where target line is empty console.log("*?===??=?*?=*?=?*==?*?=?=?=?=?==???*=?*=?*=?*=?*=*?=") console.log("TARGET = ", targetLineIndex); console.log("LINE = ", targetLine); console.log("BOX COMPONENT = ", boxToMoveEl) console.log(`Move ${direction > 0 ? 'down' : 'up'} 4`, true); console.log("*?===??=?*?=*?=?*==?*?=?=?=?=?==???*=?*=?*=?*=?*=*?=") CheckBoxesAndClosestBoxesHeigth(targetLine, el, true, null, false); } } } setTimeout(() => { CreatelinesIds(); }, 100); } function handleBoxSwap(targetLine, currentParent, boxToMoveEl, direction) { console.log(`00#Move ${direction > 0 ? 'down' : 'up'}`, true); console.log('%c ###_______ GETTING STARTED _____###', 'background: #222; color:rgb(241, 49, 49)') let newBoxElSize = boxToMoveEl.getAttribute("size") * 1; let targetBoxParentEl = boxToMoveEl.parentNode; let currentBoxSize = targetBoxParentEl.getAttribute("id").split("-")[1] * 1; let Places = [currentBoxSize, currentBoxSize + 1]; console.log({ currentPlace: currentBoxSize, storeIndexes: Places, down: direction > 0 }); if (newBoxElSize > el.getAttribute("size") * 1) { if (newBoxElSize === DefaultLineHeight * 2) { // Case when target box size is 140 (DefaultLineHeight * 2) console.log(`Show off ${direction > 0 ? 1 : 'up'}`); CheckBoxesAndClosestBoxesHeigth( currentParent, boxToMoveEl, true, { currentPlace: currentBoxSize, storeIndexes: Places, down: direction > 0, Elements: { e1: el, e2: boxToMoveEl } }, null, false ); } else { ShowAlert() } } else if (newBoxElSize === el.getAttribute("size") * 1) { // Case when both boxes have the same size console.log(`01#Move ${direction > 0 ? 2 : 3}`, true); CheckBoxesAndClosestBoxesHeigth(currentParent, boxToMoveEl, true, null, { currentPlace: currentBoxSize, storeIndexes: Places, down: direction > 0, Elements: { e1: el, e2: boxToMoveEl } }, false); // CheckBoxesAndClosestBoxesHeigth(targetLine, el, true, null); } else { // Case when the current box is larger than the target box console.log(`02#Move ${direction > 0 ? 3 : 4}`, true); CheckBoxesAndClosestBoxesHeigth(currentParent, boxToMoveEl, true, { currentPlace: currentBoxSize, storeIndexes: Places, down: direction > 0, doubble: true, elr: el, Elements: { e1: el, e2: boxToMoveEl } }, null, false); } } // Function to move the component up function MoveCurrentComponentUp() { handleBoxMovement(-1); // -1 for up direction } // Function to move the component down function MoveCurrentComponentDown() { handleBoxMovement(1); // 1 for down direction } function MoveItemWhenDrop(area, item) { console.log("Just in case sun ..."); let newArea = area; IsElementToDrag = true; setTimeout(() => { const El = item //document.getElementById(item); console.log(area, item); if (area !== null) { const originalString = area; const result = originalString.substring(0, 5); if (result === "el-cp") { newArea = document.querySelector("#" + area).parentElement.getAttribute("id"); } if (document.querySelectorAll("#" + newArea).length > 0) { if (document.getElementById(newArea).querySelectorAll(".box-component").length > 0) { ShowAlert(); } else { console.log('%c ****ADD 2 ***************', 'background: #222; color:rgb(49, 142, 241)'); CheckBoxesAndClosestBoxesHeigth(document.getElementById(newArea), El, true, null, null, true); } } else { ShowAlert(); } } else { console.log('%c **** COMPONENT START = 2 ***************', 'background: #222; color:rgb(49, 241, 123)'); ShowAlert(); } }, 10); } function ShowAlert() { toastr.warning("Lamentamos mas não é possivel adicionar este componente !"); return; } function CheckemptyLines() { EmptyLines = []; let p = containerDropArea[0].querySelectorAll(".line"); for (let i = 0; i < p.length; i++) { if (p[i].querySelectorAll(".box-component.sm").length === 0) { if (p[i].querySelectorAll(".box-component").length <= 0) { EmptyLines.push({ n: i, status: true }); } } } } // for full horizontal products function CheckBoxesAndClosestBoxesHeigth(area, l, move, moveData, ExtraMove, toDragDrop) { console.log("############################# MY CODE #################################"); let ele = l; console.log(l, ele); var STATUSINFO = ExtraMove === null ? moveData : ExtraMove; let StoreEl = ele; const OtherValues = [2, 3, 4, 5, 6, 7, 8, 9]; let Sz = ele.getAttribute("size") * 1; let areaId = area.getAttribute("id").split("-")[1] * 1; FillEmptyBoxes(Sz / DefaultLineHeight); let StoredIndexes = []; let Status = CheckLength(); let DOWNMOVE = null; if (ExtraMove !== null) { DOWNMOVE = ExtraMove.down; } else { if (moveData !== null) { DOWNMOVE = moveData.down; } } if (toDragDrop === true && ((ele.getAttribute("size") * 1) / DefaultLineHeight) > 1) { console.log("DO YOUR THING"); let currentPosition = ele.parentElement.getAttribute("id").split("-")[1]; console.clear(); console.log("CURRENT ELEMENT = " + currentPosition, " AREA TO MOVE = " + areaId); MoveWhenDropRandomly(ele, areaId); return; } function MoveWhenDropRandomly(curreEl, positionMove) { let totalNeededLines = Math.floor(curreEl.getAttribute("size") * 1 / DefaultLineHeight); let ValidLines = []; const DownLines = []; for (var i = 0; i < totalNeededLines; i++) { if (document.querySelectorAll("#line-" + (positionMove + 1)).length === 1) { DownLines.push(positionMove + i); } } const UPLines = []; for (var i = 0; i < totalNeededLines; i++) { if (positionMove - 1 >= 0) { if (document.querySelectorAll("#line-" + (positionMove - i)).length > 0) { UPLines.push(positionMove - i); } } } let useDownLines = true; for (var i = 0; i < DownLines.length; i++) { if (document.querySelector("#line-" + DownLines[i]).querySelectorAll(".box-component").length > 0) { useDownLines = false; } } let useUpLines = true; for (var i = 0; i < UPLines.length; i++) { if (document.querySelector("#line-" + UPLines[i]).querySelectorAll(".box-component").length > 0) { useUpLines = false; } } if (useDownLines === true && DownLines.length === totalNeededLines) { ValidLines = DownLines; console.log("YOU CAN USE DOWN LINES !"); } if (useUpLines === true && UPLines.length === totalNeededLines) { if (ValidLines.length === 0) { ValidLines = UPLines; console.log("YOU CAN USE UP LINES !"); } } if (ValidLines.length === 0 && useDownLines === true) { DownLines.forEach(n => { ValidLines.push(n) }); } if (ValidLines.length === 0 && useUpLines === true) { UPLines.forEach(n => { ValidLines.push(n) }); } console.log("DOWNLINES , USE " + useDownLines, DownLines); console.log("UPLINES , USE " + useUpLines, UPLines); console.log("LINES I WILL USE = ", ValidLines); console.log("ELEMENT SIZE = ", Math.floor(curreEl.getAttribute("size") * 1 / DefaultLineHeight)); if (ValidLines.length === totalNeededLines) { ValidLines.sort(function (a, b) { return a - b; }); const CurrentEl_copy = curreEl; curreEl.remove(); for (let r = 1; r < ValidLines.length; r++) { document.querySelector("#line-" + ValidLines[r])?.remove(); } if (ValidLines.length > 0) { document.querySelector("#line-" + ValidLines[0]).style.minHeight = (DefaultLineHeight * totalNeededLines) + "px"; document.querySelector("#line-" + ValidLines[0]).style.height = (DefaultLineHeight * totalNeededLines) + "px"; document.querySelector("#line-" + ValidLines[0]).appendChild(CurrentEl_copy); } FillEmptyBoxes(totalNeededLines); } else { ShowAlert(); } } // function to switch position between components; function SwitchElementsPosition(curreEl, positionMove) { let curreEl_parent = curreEl.parentNode; let currEl_Position = curreEl_parent.getAttribute("id").split("-")[1] * 1; let curreEl_size = Math.floor(Math.floor(curreEl.getAttribute("size") * 1) / DefaultLineHeight); console.log("POSITION TO MOVE = ", positionMove); if (document.querySelectorAll("#line-" + positionMove).length > 0) { if (document.querySelector("#line-" + positionMove).querySelectorAll(".box-component").length > 0) { let positionMove_component = document.querySelector("#line-" + positionMove).querySelector(".box-component"); let positionMove_component_size = Math.floor(Math.floor(positionMove_component.getAttribute("size") * 1) / DefaultLineHeight); let WhereToMove = currEl_Position > position; console.log("WHERE TO MOVE = ", WhereToMove); console.log("THE CURRENT DATA = ", DOWNMOVE) function MoveItemsUP() { const positionMove_OcupiedPositions = []; positionMove_OcupiedPositions.push(positionMove) for (let i = 1; i < positionMove_component_size; i++) { positionMove_OcupiedPositions.push((positionMove + i)); console.log("MATH => " + `${positionMove} + ${i} => `, Math.floor((positionMove + i))); } const Currentele_OcupiedPositions = []; Currentele_OcupiedPositions.push(currEl_Position * 1); for (let i = 1; i < curreEl_size; i++) { Currentele_OcupiedPositions.push((currEl_Position * 1) + i); } let CurreElNewPositions = []; let MoveElementPositions = []; const CurrentEl_copy = curreEl; const MovedEl_Copy = positionMove_component; /** apply down and up statement from here */ if (positionMove_component_size === 1) { const Currentele_OcupiedPositions = []; Currentele_OcupiedPositions.push(currEl_Position * 1); for (let i = 1; i < curreEl_size; i++) { Currentele_OcupiedPositions.push((currEl_Position * 1) + i); } let MV_ARRAY = Currentele_OcupiedPositions; let LastPosition = Currentele_OcupiedPositions.slice(-1); MV_ARRAY.pop(); MV_ARRAY.push(positionMove); MV_ARRAY.sort(function (a, b) { return a - b; }); curreEl.remove(); positionMove_component.remove(); FillEmptyBoxes(curreEl_size); for (let r = 1; r < MV_ARRAY.length; r++) { document.querySelector("#line-" + MV_ARRAY[r])?.remove(); } if (MV_ARRAY.length > 0) { document.querySelector("#line-" + MV_ARRAY[0]).style.minHeight = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).style.height = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).appendChild(CurrentEl_copy); } document.querySelector("#line-" + LastPosition).style.minHeight = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + LastPosition).style.height = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + LastPosition).appendChild(MovedEl_Copy); setTimeout(() => { CreatelinesIds(); Lines = containerDropArea[0].querySelectorAll(".line"); }, 1); console.clear(); console.log("MOVE ELEMENT = 1.1"); console.log("NEW OCUPIED POSITIONS = ", MV_ARRAY); console.log("NEW ELEMENT TO MOVE POSITIONS = ", LastPosition); console.log(positionMove_component); } else { if (positionMove_component_size !== curreEl_size) { if (Currentele_OcupiedPositions.length < positionMove_OcupiedPositions.length) { // alert("here you area - 2 !"); let MV_ARRAY = positionMove_OcupiedPositions; for (let i = 0; i < curreEl_size; i++) { CurreElNewPositions.push(positionMove_OcupiedPositions[i]); } for (let i = 0; i < curreEl_size; i++) { MV_ARRAY.splice(0, 1); } MV_ARRAY.sort(function (a, b) { return a - b; }); let LastItem = MV_ARRAY.slice(-1); for (let i = 1; i <= curreEl_size; i++) { MV_ARRAY.push((LastItem * 1) + i); } MoveElementPositions = MV_ARRAY; CurreElNewPositions.sort(function (a, b) { return a - b; }); MoveElementPositions.sort(function (a, b) { return a - b; }); console.log("CURRENT NEW POSITIONS = ", CurreElNewPositions); console.log("MOVED NEW POSITIONS = ", MoveElementPositions); function PopElements() { curreEl.remove(); positionMove_component.remove(); FillEmptyBoxes(curreEl_size); FillEmptyBoxes(positionMove_component_size); for (let r = 1; r < CurreElNewPositions.length; r++) { document.querySelector("#line-" + CurreElNewPositions[r])?.remove(); } if (CurreElNewPositions.length > 0) { document.querySelector("#line-" + CurreElNewPositions[0]).style.minHeight = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + CurreElNewPositions[0]).style.height = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + CurreElNewPositions[0]).appendChild(CurrentEl_copy); } for (let r = 1; r < MoveElementPositions.length; r++) { document.querySelector("#line-" + MoveElementPositions[r])?.remove(); } if (MoveElementPositions.length > 0) { document.querySelector("#line-" + MoveElementPositions[0]).style.minHeight = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + MoveElementPositions[0]).style.height = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + MoveElementPositions[0]).appendChild(MovedEl_Copy); setTimeout(() => { CreatelinesIds(); Lines = containerDropArea[0].querySelectorAll(".line"); }, 1); } } PopElements(); } else { // alert("here you area - 3 !"); let rpt_val = null; for (let i = 0; i < Currentele_OcupiedPositions.length; i++) { const rpt = Currentele_OcupiedPositions[i]; if (positionMove_OcupiedPositions.includes(rpt)) { rpt_val = Currentele_OcupiedPositions.indexOf(rpt); } } console.clear(); let CurrentElementPositions = []; let lastItemFromMoved = positionMove_OcupiedPositions.slice(-1) * 1; for (var i = 1; i <= curreEl_size; i++) { CurrentElementPositions.push(lastItemFromMoved + i); } console.log(" CURRENT ELEMENT POSITION (BIG) = ", CurrentElementPositions); console.log(" MOVED ELEMENT POSITION (SMALL) = ", positionMove_OcupiedPositions); let MV_ARRAY = []; let SmallElementArray = []; for (var i = 0; i < positionMove_OcupiedPositions.length; i++) { MV_ARRAY.push(positionMove_OcupiedPositions[i]); } let totalNeeded = curreEl_size * 1 - MV_ARRAY.length; if (totalNeeded > 0) { for (var i = 0; i < totalNeeded; i++) { MV_ARRAY.push(CurrentElementPositions[i]); } } let LastCurrentNewItem = MV_ARRAY.slice(-1) * 1; for (var i = 1; i < positionMove_component_size + 1; i++) { SmallElementArray.push(LastCurrentNewItem + i); } MV_ARRAY.sort(function (a, b) { return a - b; }); SmallElementArray.sort(function (a, b) { return a - b; }); console.log("NEW CURRENT ELEMENT POSITION (BIG) = ", MV_ARRAY); console.log("NEW MOVED ELEMENT POSITION (SMALL) = ", SmallElementArray); function PopElements() { curreEl.remove(); positionMove_component.remove(); FillEmptyBoxes(curreEl_size); FillEmptyBoxes(positionMove_component_size); for (let r = 1; r < MV_ARRAY.length; r++) { document.querySelector("#line-" + MV_ARRAY[r])?.remove(); } if (MV_ARRAY.length > 0) { document.querySelector("#line-" + MV_ARRAY[0]).style.minHeight = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).style.height = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).appendChild(CurrentEl_copy); } for (let r = 1; r < SmallElementArray.length; r++) { document.querySelector("#line-" + SmallElementArray[r])?.remove(); } if (SmallElementArray.length > 0) { document.querySelector("#line-" + SmallElementArray[0]).style.minHeight = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + SmallElementArray[0]).style.height = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + SmallElementArray[0]).appendChild(MovedEl_Copy); setTimeout(() => { CreatelinesIds(); Lines = containerDropArea[0].querySelectorAll(".line"); }, 1); } } PopElements(); } } else { //alert("here you area - 4 !"); CurreElNewPositions = positionMove; MoveElementPositions = currEl_Position; console.log("MOVE EQUAL WHEN UP ...",); console.log("CURRENT NEW POSITIONS = ", CurreElNewPositions); console.log("MOVED NEW POSITIONS = ", MoveElementPositions); curreEl.remove(); positionMove_component.remove(); document.querySelector("#line-" + CurreElNewPositions).append(CurrentEl_copy); document.querySelector("#line-" + MoveElementPositions).append(MovedEl_Copy); } } } function MoveItemsDown() { const positionMove_OcupiedPositions = []; positionMove_OcupiedPositions.push(positionMove) for (let i = 1; i < positionMove_component_size; i++) { positionMove_OcupiedPositions.push((positionMove + i)); console.log("MATH => " + `${positionMove} + ${i} => `, Math.floor((positionMove + i))); } const Currentele_OcupiedPositions = []; Currentele_OcupiedPositions.push(currEl_Position * 1); for (let i = 1; i < curreEl_size; i++) { Currentele_OcupiedPositions.push((currEl_Position * 1) + i); } let CurreElNewPositions = []; let MoveElementPositions = []; const CurrentEl_copy = curreEl; const MovedEl_Copy = positionMove_component; if (positionMove_component_size === 1) { const Currentele_OcupiedPositions = []; Currentele_OcupiedPositions.push(currEl_Position * 1); for (let i = 1; i < curreEl_size; i++) { Currentele_OcupiedPositions.push((currEl_Position * 1) + i); } let newPositionMove = Math.floor((Currentele_OcupiedPositions.slice(-1) * 1) + 1); let newMovePosition = Currentele_OcupiedPositions[0]; //Currentele_OcupiedPositions.shift(); let MV_ARRAY = Currentele_OcupiedPositions.slice(); MV_ARRAY.push(newPositionMove); MV_ARRAY.sort(function (a, b) { return a - b; }); MV_ARRAY.shift(); curreEl.remove(); positionMove_component.remove(); FillEmptyBoxes(curreEl_size); for (let r = 1; r < MV_ARRAY.length; r++) { document.querySelector("#line-" + MV_ARRAY[r])?.remove(); } if (MV_ARRAY.length > 0) { document.querySelector("#line-" + MV_ARRAY[0]).style.minHeight = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).style.height = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).appendChild(CurrentEl_copy); } document.querySelector("#line-" + newMovePosition).style.minHeight = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + newMovePosition).style.height = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + newMovePosition).appendChild(MovedEl_Copy); setTimeout(() => { CreatelinesIds(); Lines = containerDropArea[0].querySelectorAll(".line"); }, 1); console.clear(); console.log("MOVE ELEMENT = 1.2"); console.log(" OCUPIED POSITIONS = ", Currentele_OcupiedPositions); console.log(" ELEMENT TO MOVE POSITIONS = ", newPositionMove); console.log("NEW OCUPIED POSITIONS = ", MV_ARRAY); console.log("NEW ELEMENT TO MOVE POSITIONS = ", newMovePosition); } else { if (positionMove_component_size !== curreEl_size) { function PopElements() { curreEl.remove(); positionMove_component.remove(); FillEmptyBoxes(curreEl_size); FillEmptyBoxes(positionMove_component_size); for (let r = 1; r < CurreElNewPositions.length; r++) { document.querySelector("#line-" + CurreElNewPositions[r])?.remove(); } if (CurreElNewPositions.length > 0) { document.querySelector("#line-" + CurreElNewPositions[0]).style.minHeight = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + CurreElNewPositions[0]).style.height = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + CurreElNewPositions[0]).appendChild(CurrentEl_copy); } for (let r = 1; r < MoveElementPositions.length; r++) { document.querySelector("#line-" + MoveElementPositions[r])?.remove(); } if (MoveElementPositions.length > 0) { document.querySelector("#line-" + MoveElementPositions[0]).style.minHeight = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + MoveElementPositions[0]).style.height = (DefaultLineHeight * positionMove_component_size) + "px"; document.querySelector("#line-" + MoveElementPositions[0]).appendChild(MovedEl_Copy); setTimeout(() => { CreatelinesIds(); Lines = containerDropArea[0].querySelectorAll(".line"); }, 1); } } if (Currentele_OcupiedPositions.length > positionMove_OcupiedPositions.length) { let MOVED_ARRAY = []; let MV_ARRAY = Currentele_OcupiedPositions.slice(); for (var i = 1; i <= positionMove_component_size; i++) { MOVED_ARRAY.push((Currentele_OcupiedPositions.slice(-1) * 1) + i); } for (var i = 0; i < positionMove_component_size; i++) { MoveElementPositions.push(Currentele_OcupiedPositions[i]); } for (var i = 0; i < positionMove_component_size; i++) { MV_ARRAY.splice(0, 1); } for (var i = 0; i < positionMove_component_size; i++) { MV_ARRAY.push(MOVED_ARRAY[i]); } console.clear(); console.log("CURRENT ELEMENT (OLD) = ", Currentele_OcupiedPositions); console.log("MOVED ELEMENTS (OLD) = ", MOVED_ARRAY); console.log(""); console.log("CURRENT ELEMENT (NEW) = ", MV_ARRAY); console.log("MOVED ELEMENTS (NEW) = ", MoveElementPositions); CurreElNewPositions = MV_ARRAY; PopElements(); } else { let MOVED_ARRAY = []; let MV_ARRAY = []; for (var i = 1; i <= positionMove_component_size; i++) { MOVED_ARRAY.push((Currentele_OcupiedPositions.slice(-1) * 1) + i); } for (var i = 0; i < curreEl_size; i++) { MoveElementPositions.push(Currentele_OcupiedPositions[i]); } MOVED_ARRAY.sort(function (a, b) { return b - a; }); for (var i = 0; i < curreEl_size; i++) { MV_ARRAY.push(MOVED_ARRAY[i]); } MV_ARRAY.sort(function (a, b) { return a - b; }); let MovedCopy = MOVED_ARRAY.slice(); for (var i = 0; i < curreEl_size; i++) { MovedCopy.splice(0, 1); } for (var i = 0; i < MovedCopy.length; i++) { MoveElementPositions.push(MovedCopy[i]); } console.clear(); console.log("CURRENT ELEMENT (OLD) = ", Currentele_OcupiedPositions); console.log("MOVED ELEMENTS (OLD) = ", MOVED_ARRAY); console.log(""); console.log("CURRENT ELEMENT (NEW) = ", MV_ARRAY); console.log("MOVED ELEMENTS (NEW) = ", MoveElementPositions); CurreElNewPositions = MV_ARRAY; PopElements(); } } else { CurreElNewPositions = positionMove; MoveElementPositions = currEl_Position; console.log("MOVE EQUAL WHEN DOWN ...",); console.log("CURRENT NEW POSITIONS = ", CurreElNewPositions); console.log("MOVED NEW POSITIONS = ", MoveElementPositions); curreEl.remove(); positionMove_component.remove(); document.querySelector("#line-" + CurreElNewPositions).append(CurrentEl_copy); document.querySelector("#line-" + MoveElementPositions).append(MovedEl_Copy); } } } if (DOWNMOVE === false) { console.log("NOW YOU WANNA MOVE UP ....") MoveItemsUP(); } else { console.log("NOW YOU WANNA MOVE DOWN ....") MoveItemsDown(); } } else { let positionMove_line = document.querySelector("#line-" + positionMove); const Currentele_OcupiedPositions = []; Currentele_OcupiedPositions.push(currEl_Position * 1); for (let i = 1; i < curreEl_size; i++) { Currentele_OcupiedPositions.push((currEl_Position * 1) + i); } let MV_ARRAY = Currentele_OcupiedPositions; if (curreEl_size * 1 * DefaultLineHeight === DefaultLineHeight) { positionMove_line.append(curreEl); } else { Currentele_OcupiedPositions.pop(); MV_ARRAY.push(positionMove); MV_ARRAY.sort(function (a, b) { return a - b; }); const CurrentEl_copy = curreEl; curreEl.remove(); FillEmptyBoxes(curreEl_size); for (let r = 1; r < MV_ARRAY.length; r++) { document.querySelector("#line-" + MV_ARRAY[r])?.remove(); } if (MV_ARRAY.length > 0) { document.querySelector("#line-" + MV_ARRAY[0]).style.minHeight = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).style.height = (DefaultLineHeight * curreEl_size) + "px"; document.querySelector("#line-" + MV_ARRAY[0]).appendChild(CurrentEl_copy); } } console.clear(); console.log("WHERE I WANT TO JOIN = ", positionMove); console.log("ELEMENT TO JOIN = ", document.querySelectorAll("#line-" + positionMove)); console.log("OCUPIED POSITIONS BY CURRENT COMPONENT = ", Currentele_OcupiedPositions); console.log("CURRENT POSITION = ", currEl_Position); console.log("CURRENT SIZE = ", curreEl_size); console.log("NEW POSITIONS = ", MV_ARRAY); } } else { const Currentele_OcupiedPositions = []; Currentele_OcupiedPositions.push(currEl_Position * 1); for (let i = 1; i < curreEl_size; i++) { Currentele_OcupiedPositions.push((currEl_Position * 1) + i); } if (currEl_Position > positionMove) { // moving up } else { // moving down } console.clear(); console.log("ELEMENT NOT FOUNDED ....", document.querySelectorAll("#line-" + positionMove)); console.log("OCUPIED POSITIONS BY CURRENT COMPONENT = ", Currentele_OcupiedPositions); console.log("CURRENT POSITION = ", currEl_Position); console.log("CURRENT SIZE = ", curreEl_size); console.log('%c **** COMPONENT START = 3 ***************', 'background: #222; color:rgb(49, 241, 123)'); ShowAlert(); } return; } if (Object.values(l.classList).includes("sm")) { console.log(":::::::::::::::::::::::::::::::::::::::::::::::::"); console.log("SHOW ME SOMETHING NICE SUN ..."); console.log(":::::::::::::::::::::::::::::::::::::::::::::::::"); console.log("ST---", CheckForSmallElementsInLine(l)) CheckForSmallElementsInLine(l); } if (Sz === DefaultLineHeight) { console.log("HELLO MY DEAR -----") setTimeout(() => { if (STATUSINFO === null) { document.getElementById(area.getAttribute("id")).appendChild(ele) } else { console.log('%c ###____ MAKING SWITCH ____###', 'background: #222; color:rgb(228, 87, 27)'); console.log("YOU NEED TO APLY THE SWITCH FUNCTION ", STATUSINFO); if (STATUSINFO.down === false) { console.log("Moving Up - ", Math.floor(STATUSINFO.currentPlace - 1)); SwitchElementsPosition(ele, Math.floor(STATUSINFO.currentPlace - 1)); } else { console.log("Moving Down - ", Math.floor(STATUSINFO.currentPlace + 1)); SwitchElementsPosition(ele, Math.floor(STATUSINFO.currentPlace + 1)); } } setTimeout(() => { CreatelinesIds(); }, 20); }, 100); return; } CheckemptyLines(); if (moveData !== null) { if (moveData.storeIndexes.length === 2) { let lineToDrop = moveData.storeIndexes[0]; let EleBox = null; for (let p = 0; p < moveData.storeIndexes.length; p++) { let element = document.querySelectorAll(`#line-${moveData.storeIndexes[p]}`); console.log("HERE YOU ARE SUN ...", element.length); for (let j = 0; j < element.length; j++) { console.log(element[j], "|||||||||||"); if (element[j].querySelectorAll(".box-component").length > 0) { if (element[j].offsetHeight * 1 / DefaultLineHeight === 2) { if (moveData.elr !== null && moveData.elr !== undefined) { lineToDrop = moveData.currentPlace; document.querySelector("#line-" + moveData.currentPlace).querySelector(".box-component").remove(); document.querySelector("#line-" + moveData.storeIndexes[0]).style.minHeight = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + moveData.storeIndexes[0]).style.height = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + moveData.storeIndexes[0]).appendChild(moveData.elr) FillEmptyBoxes(2); document.querySelector("#line-" + moveData.storeIndexes[1]).remove(); CreatelinesIds(); setTimeout(() => { document.querySelector("#line-" + lineToDrop).appendChild(l); }, 10); return true; } else { EleBox = element[j].querySelectorAll(".box-component")[0]; setTimeout(() => { if (element[j].querySelectorAll(".box-component").length > 0) { if (moveData.down === false) { StoredIndexes = [moveData.storeIndexes[1], moveData.currentPlace * 1 + 1]; element[j].querySelectorAll(".box-component")[0].remove(); FillEmptyBoxes(2); //append small element document.querySelector("#line-" + lineToDrop).appendChild(ele); // add large element document.querySelector("#line-" + StoredIndexes[1]).remove(); document.querySelector("#line-" + StoredIndexes[0]).style.minHeight = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + StoredIndexes[0]).style.height = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + StoredIndexes[0]).appendChild(EleBox); } else { if (moveData.Elements !== undefined && moveData.Elements !== null) { if (moveData.Elements.e1.getAttribute("size") * 1 === DefaultLineHeight) { StoredIndexes = [moveData.storeIndexes[0], moveData.storeIndexes[1]]; let e1_copy = moveData.Elements.e1; let e2_copy = moveData.Elements.e2; moveData.Elements.e1.parentNode.querySelector(".box-component").remove(); moveData.Elements.e2.parentNode.querySelector(".box-component").remove(); FillEmptyBoxes(2); setTimeout(() => { document.querySelector("#line-" + moveData.currentPlace * 1).style.minHeight = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + moveData.currentPlace * 1).style.height = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + StoredIndexes[0]).appendChild(e1_copy); document.querySelector("#line-" + moveData.currentPlace * 1).appendChild(e2_copy); document.querySelector("#line-" + StoredIndexes[1]).remove(); console.log("1_____________ line - comp ________________") console.log(document.querySelector("#line-" + StoredIndexes[0])); console.log(e1_copy); console.log("2_____________ line - comp ________________") console.log(document.querySelector("#line-" + moveData.currentPlace * 1)); console.log(e2_copy); CreatelinesIds(); }, 50); } else { console.log("NO NO NO..."); } } else { console.log("YOU DO NOT GOT MULTIPLE ELEMENTS"); } } } }, 100); } } else if (element[j].offsetHeight * 1 / DefaultLineHeight === 1) { console.log("IT'S NOT MY MAN..."); if (moveData.Elements.e1.getAttribute("size") * 1 === DefaultLineHeight * 2) { if (moveData.down === true) { StoredIndexes = [moveData.storeIndexes[0], moveData.storeIndexes[1]]; let e1_copy = moveData.Elements.e1; let e2_copy = moveData.Elements.e2; moveData.Elements.e1.parentNode.querySelector(".box-component").remove(); moveData.Elements.e2.parentNode.querySelector(".box-component").remove(); FillEmptyBoxes(2); setTimeout(() => { let text1 = document.createElement("h4"); text1.innerText = "GRANDE"; let text2 = document.createElement("h4"); text2.innerText = "PEQUENO"; document.querySelector("#line-" + StoredIndexes[0]).style.minHeight = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + StoredIndexes[0]).style.height = (DefaultLineHeight * 2) + "px"; document.querySelector("#line-" + moveData.currentPlace * 1).appendChild(e2_copy); document.querySelector("#line-" + StoredIndexes[0]).appendChild(e1_copy); document.querySelector("#line-" + StoredIndexes[1]).remove(); console.log("1_____________ line - comp ________________"); console.log(document.querySelector("#line-" + StoredIndexes[0])); console.log(e1_copy, text1); console.log("2_____________ line - comp ________________"); console.log(document.querySelector("#line-" + moveData.currentPlace * 1)); console.log(e2_copy, text2); console.log("Lines_____________________________###"); console.log(StoredIndexes); CreatelinesIds(); }, 50); } else { console.log("NICE JOB ........") console.log(moveData); } } else { console.log("GOOD ..."); console.log(moveData); } } } } } return; } } else { if (ExtraMove !== null && ExtraMove !== undefined) { let CRP = ele.parentNode.getAttribute("id").split("-")[1] * 1; if (DOWNMOVE === true) { console.log(document.querySelector("#line-" + (CRP + 1)), document.querySelector("#line-" + (CRP))) if (document.querySelectorAll("#line-" + (CRP + 1)).length > 0) { let up = document.querySelector("#line-" + (CRP + 1)).querySelectorAll(".box-component").length; if (up > 0) { SwitchElementsPosition(ele, Math.floor((CRP * 1) + 1)); } } else { ShowAlert(); } } else if (DOWNMOVE === false) { console.log(document.querySelector("#line-" + (CRP + 1)), document.querySelector("#line-" + (CRP))) if (document.querySelectorAll("#line-" + (CRP - 1)).length > 0) { let down = document.querySelector("#line-" + (CRP - 1)).querySelectorAll(".box-component").length; if (down > 0) { SwitchElementsPosition(ele, Math.floor((CRP * 1) - 1)); } } else { ShowAlert(); } } } } function TryUnorderedSolution(comp, n) { let NewEmptyLines = []; let LNT = containerDropArea[0].querySelectorAll(".line"); function checkEmptyLn() { NewEmptyLines = []; let p = containerDropArea[0].querySelectorAll(".line"); for (let i = 0; i < p.length; i++) { if (p[i].querySelectorAll(".box-component.sm").length === 0) { if (p[i].querySelectorAll(".box-component").length <= 0) { NewEmptyLines.push(i); // Push empty lines } } } } checkEmptyLn(); // Function to find the first z consecutive lines function getCorrectLines(array, z) { for (let i = 0; i < array.length; i++) { if (i + z <= array.length) { let NewAreas = array.slice(i, i + z); // Check if the lines are consecutive (difference between adjacent lines is 1) if (NewAreas.every((num, idx) => idx === 0 || num - NewAreas[idx - 1] === 1)) { return NewAreas; // Return the first valid consecutive lines } } } return []; // Return empty array if no valid space found } // Function to handle placing the component in the available space function PopMultipleU(v) { let z = v / DefaultLineHeight; checkEmptyLn(); NewEmptyLines.sort(function (a, b) { return a - b; }); // Sort empty lines in ascending order console.clear(); console.log("All empty lines ****", "NEEDED LINES = " + z); console.log(LNT); let NewAreas = getCorrectLines(NewEmptyLines, z); // Check if valid space was found if (NewAreas.length > 0 && NewAreas.length === z) { const StoredIndexes = NewAreas; // Stores the found empty spaces const ElementCopy = comp; for (let r = 1; r < StoredIndexes.length; r++) { if (document.querySelectorAll("#line-" + StoredIndexes[r]).length > 0) { document.querySelector("#line-" + StoredIndexes[r]).remove(); } } console.log('%c **** COMPONENT ADDED ***************', 'background: #222; color:rgb(241, 49, 215)'); console.log("places", StoredIndexes); console.log('%c *****************************************', 'background: #222; color:rgb(241, 49, 215)'); // Set the height of the first line to fit the component document.querySelector("#line-" + StoredIndexes[0]).style.minHeight = (DefaultLineHeight * z) + "px"; document.querySelector("#line-" + StoredIndexes[0]).style.height = (DefaultLineHeight * z) + "px"; //document.querySelector("#line-" + StoredIndexes[0]).style.backgroundColor = "red"; console.log('%c ###___________ CHEKING _________###', 'background:gold; color:rgb(54, 41, 110)') setTimeout(() => { Lines = document.querySelectorAll(".config-canvas .line"); let totalLines = Lines.length; for (let j = 0; j < Lines.length; j++) { Lines[j].removeAttribute("id"); Lines[j].setAttribute("id", "line-" + j); Lines[j].querySelector("h3").innerText = (totalLines - j) + "U"; } Lines = document.querySelectorAll(".config-canvas .line"); MapAddedProducts(); setTimeout(() => { CreatelinesIds(); }, 100); document.querySelector("#line-" + StoredIndexes[0]).append(comp) }, 100); console.log('%c ###____________ END ___________###', 'background:green; color:rgb(54, 41, 110)'); } else { console.log('%c **** COMPONENT START = 4 ***************', 'background: #222; color:rgb(49, 241, 123)'); ShowAlert(); // Show alert if there is no valid space } } PopMultipleU(ele.getAttribute("size") * 1); } OtherValues.forEach(element => { if (Sz / DefaultLineHeight === element) { if (move === false) { TryUnorderedSolution(ele, 2); } else { PopOther(ele.getAttribute("size") * 1); } } }); /****** START MOving */ function PopOther(V) { // Ensure the helper functions are defined before usage function getCorrectLinesCrescente(array, z) { for (let i = 0; i < array.length; i++) { if (i + z <= array.length) { let NewAreas = array.slice(i, i + z); if (NewAreas.every((num, idx) => idx === 0 || num - NewAreas[idx - 1] === 1)) { return NewAreas; // Return if in consecutive sequence } } } return []; } function getCorrectLinesDecrescente(array, z) { for (let i = array.length - 1; i >= 0; i--) { if (i - z + 1 >= 0) { let NewAreas = array.slice(i - z + 1, i + 1); if (NewAreas.every((num, idx) => idx === 0 || NewAreas[idx] - NewAreas[idx - 1] === 1)) { return NewAreas; // Return if in consecutive sequence } } } return []; } if (EmptyLines.length > 0) { CheckemptyLines(); let z = V / DefaultLineHeight; let NewEmptyLines = []; function checkEmptyLn(area) { NewEmptyLines = []; let p = containerDropArea[0].querySelectorAll(".line"); for (let i = 0; i < p.length; i++) { if (p[i].querySelectorAll(".box-component").length <= 0) { if (i >= area) { NewEmptyLines.push(i); } } } } checkEmptyLn(areaId); // Update indexes before new check StoredIndexes = []; let validDown = getCorrectLinesCrescente(NewEmptyLines, z); let validUp = getCorrectLinesDecrescente(NewEmptyLines, z); if (validDown.length < z) { if (!validDown.includes(ExtraMove.currentPlace)) { validDown.push(ExtraMove.currentPlace); } } if (validDown.length > 0) { validDown.sort(function (a, b) { return a - b; }); StoredIndexes = validDown; } else if (validUp.length > 0) { StoredIndexes = validUp; } else { console.log('%c **** COMPONENT START = 5 ***************', 'background: #222; color:rgb(49, 241, 123)'); ShowAlert(); } console.clear(); console.log("All empty lines *********************"); console.log(moveData); console.log("All available lines *****************"); console.log(StoredIndexes); console.log("NEW EMPTY LINES = ", NewEmptyLines); if (DOWNMOVE === false) { console.log('%c **** SEEMS LIKE YOU WANNA MOVE UP ***************', 'background: #222; color:rgb(241, 238, 49)'); let UpCurrentPlace = Math.floor(STATUSINFO.currentPlace); // 1 - GETTING EMPTY LINES var MyLines = []; let p = containerDropArea[0].querySelectorAll(".line"); for (let i = 0; i < p.length; i++) { if (p[i].querySelectorAll(".box-component").length <= 0) { if (i <= UpCurrentPlace) { MyLines.push(i); } } } // 2 - GETTING NEXT LINES TO DROP; var SpotsWeNeedToMove = []; var b = UpCurrentPlace - 1; for (let x = 0; x < z; x++) { var d = b + x; if (d >= 0) { SpotsWeNeedToMove.push(d); } } // 3 - REMOVE ELEMENT AND CHECK IF WE CAN DROP AT SELECTED LINES const ElementCopy = ele; var IT = []; console.clear(); console.log("AVAILABLE SPOTS", SpotsWeNeedToMove); console.log("EMPTY LINES WHEN GOING UP", MyLines); console.log("CURRENT PLACE = ", UpCurrentPlace); if (SpotsWeNeedToMove.length === z) { var occupiedSpace = false; for (let i = 0; i < SpotsWeNeedToMove.length; i++) { if (document.querySelectorAll("#line-" + SpotsWeNeedToMove[i]).length > 0) { if(document.querySelector("#line-" + SpotsWeNeedToMove[i]).querySelectorAll(".box-component").length > 0 === true && SpotsWeNeedToMove[i] !== STATUSINFO.currentPlace) { occupiedSpace = true; console.clear(); console.log(document.querySelector("#line-" + SpotsWeNeedToMove[i])) console.log("CURRENT PLACE = ", STATUSINFO.currentPlace); } } } if (occupiedSpace === true) { console.log(SpotsWeNeedToMove); console.log("YOU NEED TO APLY THE SWITCH FUNCTION ", areaId); SwitchElementsPosition(ele, SpotsWeNeedToMove[0]); } else { setTimeout(() => { ele.remove(); FillEmptyBoxes(z); CreatelinesIds(); for (let i = 0; i < SpotsWeNeedToMove.length; i++) { var ln = document.querySelector("#line-" + SpotsWeNeedToMove[i]); if (ln.querySelectorAll(".box-component").length === 0) { IT.push(i); } } console.log("PUSHED SPOTS = ", IT); console.log("NEEDED LINES = ", z); if (IT.length * 1 === z * 1) { console.log("MOving on ....") for (let r = 1; r < SpotsWeNeedToMove.length; r++) { document.querySelector("#line-" + SpotsWeNeedToMove[r])?.remove(); } document.querySelector("#line-" + SpotsWeNeedToMove[0]).style.minHeight = (DefaultLineHeight * z) + "px"; document.querySelector("#line-" + SpotsWeNeedToMove[0]).style.height = (DefaultLineHeight * z) + "px"; document.querySelector("#line-" + SpotsWeNeedToMove[0]).appendChild(ElementCopy); setTimeout(() => { CreatelinesIds(); Lines = containerDropArea[0].querySelectorAll(".line"); }, 10); } else { console.log("ERROR 1"); console.log('%c **** COMPONENT START = 6 ***************', 'background: #222; color:rgb(49, 241, 123)'); ShowAlert(); } }, 100); } } else { console.log("ERROR 2"); console.log('%c **** COMPONENT START = 7 ***************', 'background: #222; color:rgb(49, 241, 123)'); ShowAlert(); return; } } else { if (StoredIndexes.length === z) { const ElementCopy = ele; let CRP = ele.parentNode.getAttribute("id").split("-")[1]; console.log("Current position = " + Math.floor(CRP), " Next position = " + Math.floor((CRP * 1) + 1)); setTimeout(() => { var occupiedSpace = false; if (document.querySelectorAll("#line-" + Math.floor((CRP * 1) + 1)).length > 0) { if (document.querySelector("#line-" + Math.floor((CRP * 1) + 1)).querySelectorAll(".box-component").length > 0) occupiedSpace = true; } if (occupiedSpace === true) { console.log(SpotsWeNeedToMove); console.log("YOU NEED TO APLY THE SWITCH FUNCTION ", areaId); SwitchElementsPosition(ele, Math.floor((CRP * 1) + 1)); } else { setTimeout(() => { ele.remove(); FillEmptyBoxes(z); function addComponent(array) { for (let r = 1; r < array.length; r++) { document.querySelector("#line-" + array[r])?.remove(); } document.querySelector("#line-" + array[0]).style.minHeight = (DefaultLineHeight * z) + "px"; document.querySelector("#line-" + array[0]).style.height = (DefaultLineHeight * z) + "px"; document.querySelector("#line-" + array[0]).appendChild(ElementCopy); setTimeout(() => { CreatelinesIds(); }, 2); Lines = document.querySelectorAll(".line"); console.log('%c **** ALL UPDATED LINES ***************', 'background:red; color:rgb(18, 119, 57)'); console.log(Lines); setTimeout(() => { CreatelinesIds(); }, 1); } if (StoredIndexes[0] - STATUSINFO.currentPlace !== 1) { let alternativeSpaces = []; for (let i = 1; i < z + 1; i++) { if (document.querySelector("#line-" + (STATUSINFO.currentPlace + i)).querySelectorAll(".box-component").length === 0) { alternativeSpaces.push(STATUSINFO.currentPlace + i); } } console.log('%c **** ALERT ***************', 'background:pink; color:rgb(18, 119, 57)'); console.log("CURRENT POS = ", STATUSINFO.currentPlace); console.log("SLECTED AREAS - ", validDown); console.log("STORE = ", StoredIndexes); console.log("ALTERNATIVE SPACES = ", alternativeSpaces); if (alternativeSpaces.length === z) { addComponent(alternativeSpaces); } return false; } console.log('%c **** COMPONENT ADDED ***************', 'background: #222; color:rgb(49, 241, 123)'); console.log("places", StoredIndexes); console.log('%c *****************************************', 'background: #222; color:rgb(241, 174, 49)'); addComponent(StoredIndexes) }, 1); } }, 1); } else { if (NewEmptyLines.length > 0) { let CurrentPosition = ExtraMove.currentPlace; let nextPosition = CurrentPosition + 1; const ElementCopy = ele; let CRP = ele.parentNode.getAttribute("id").split("-")[1]; if (document.querySelectorAll("#line-" + Math.floor((CRP * 1) + 1)).length > 0) { if (document.querySelector("#line-" + Math.floor((CRP * 1) + 1)).querySelectorAll(".box-component").length > 0) { SwitchElementsPosition(ele, Math.floor((CRP * 1) + 1)); } } function CleanForAwhile() { ele.remove(); FillEmptyBoxes(z); CreatelinesIds(); } CleanForAwhile(); document.querySelector("#line-" + CurrentPosition).style.backgroundColor = getRandomColor(); let oldLines = NewEmptyLines checkEmptyLn(nextPosition); console.log("OLD LINES = ", oldLines); checkEmptyLn(nextPosition); let LeftLines = getCorrectLinesCrescente(NewEmptyLines, z); console.log("ALL EMPTY SPACES = ", NewEmptyLines); console.log("LINES I CAN USE = ", LeftLines); let Status = false; for (let i = 0; i < LeftLines.length; i++) { if (LeftLines[i] > nextPosition) { Status = true; } } if (LeftLines.length === z) { setTimeout(() => { for (let r = 1; r < LeftLines.length; r++) { document.querySelector("#line-" + LeftLines[r])?.remove(); } if (LeftLines.length > 0) { document.querySelector("#line-" + LeftLines[0]).style.minHeight = (DefaultLineHeight * z) + "px"; document.querySelector("#line-" + LeftLines[0]).style.height = (DefaultLineHeight * z) + "px"; document.querySelector("#line-" + LeftLines[0]).appendChild(ElementCopy); setTimeout(() => { CreatelinesIds(); // Re-create line IDs after the component has been added Lines = containerDropArea[0].querySelectorAll(".line"); }, 1); } }, 1); } } else { let CRP = ele.parentNode.getAttribute("id").split("-")[1]; SwitchElementsPosition(ele, Math.floor((CRP * 1) + 1)); } } } } else { console.log('%c **** COMPONENT START = 8 ***************', 'background: #222; color:rgb(49, 241, 123)'); //ShowAlert(); } } } // for small horizontal products function CheckForSmallElementsInLine(elem) { let boxesMultiple = []; let NewLines = document.querySelectorAll(".line"); for (let i = 0; i < NewLines.length; i++) { if (NewLines[i].querySelectorAll(".box-component.sm").length > 0) { boxesMultiple.push(NewLines[i]); } } let text = document.createElement("h5"); text.innerText = "POP"; for (let i = 0; i < boxesMultiple.length; i++) { if (boxesMultiple[i].querySelectorAll(".box-component.sm").length <= 3) { boxesMultiple[i].appendChild(elem); return true; console.log("adding at line - ", i); }; console.log(boxesMultiple[i]); console.log(elem); } console.log("TOTAL BOXES = " + document.querySelectorAll(".box-component.sm").length); console.log("Boxes = ", boxesMultiple.length); } function dropFunc(EL) { /* let dropAreas = document.querySelectorAll(".config-container .line"); IsElementToDrag = true; console.log("ELENENT STAT = ", IsElementToDrag); dropAreas.forEach(dropArea => { dropArea.addEventListener('dragover', (event) => { event.preventDefault(); // Allow the drop }); dropArea.addEventListener('drop', (event) => { event.preventDefault(); // Get the ID or class of the area where the item was dropped const droppedAreaId = event.target.id; // Get the ID of the drop area const droppedAreaClass = event.target.className; // Get the class of the drop area let areaCode = droppedAreaId.split("-")[0]; IsElementToDrag = true; MoveItemWhenDrop(droppedAreaId, EL); console.log(`Dropped on area with ID: ${droppedAreaId}`); console.log(`Dropped on area with class: ${droppedAreaClass}`); }); }); return; */ } let AvailableLines = []; for (var x = 0; x < Lines.length; x++) { if (Lines[x].querySelectorAll(".box-component").length === 0) { AvailableLines.push(Lines[x].getAttribute("id").split("-")[1] * 1) } } AvailableLines.sort(function (a, b) { return a - b; }); for (let i = 0; i < Lines.length; i++) { let txt = document.createElement("h3"); txt.innerText = (Lines.length - i) + "U"; Lines[i].appendChild(txt); Lines[i].setAttribute("id", "line-" + i); console.log("IS DRAGING = ", IsElementToDrag); if (IsElementToDrag === false) { if (Lines[i].querySelectorAll(".box-component").length === 0) { console.log(" PAI DO ELEMENTO = ", el.parentElement); console.log('%c ****ADD 1 ***************', 'background: #222; color:rgb(49, 142, 241)'); CheckBoxesAndClosestBoxesHeigth(document.querySelector("#line-" + Math.min(...AvailableLines)), el, false, null, null, false, true); } else { // CheckForSmallElementsInLine(el); console.log("Line container " + i + " is not empty try other !"); } Lines[i].addEventListener("dragenter", function (e) { e.preventDefault(); console.log("Total empty lines = ", EmptyLines.length); console.log(EmptyLines); const droppedAreaId = e.target.id; const droppedAreaClass = e.target.className; console.log(`Dropped on area with ID: ${droppedAreaId}`); console.log(`Dropped on area with class: ${droppedAreaClass}`); console.log(document.querySelector("#" + e.target.id)); }); Lines[i].addEventListener("dragover", function (e) { e.preventDefault(); console.log("Total empty lines = ", EmptyLines.length); console.log(EmptyLines); const droppedAreaId = e.target.id; const droppedAreaClass = e.target.className; console.log(`Dropped on area with ID: ${droppedAreaId}`); console.log(`Dropped on area with class: ${droppedAreaClass}`); console.log(document.querySelector("#" + e.target.id)); }); Lines[i].addEventListener("drop", function (e) { console.log(e.target); console.log("Start new dropping ..."); e.preventDefault() const draggedElementId = e.target.id; const droppedAreaId = e.target.id; const droppedAreaClass = e.target.className; console.log(`Dropped on area with ID: ${droppedAreaId}`); console.log(`Dropped on area with class: ${droppedAreaClass}`); console.log(document.querySelector("#" + e.target.id)); if (IsElementToDrag === false) { const draggedElementClass = Object.values(e.target.classList); let DropItem = e.dataTransfer.getData("plain"); if (draggedElementClass.length <= 0) { console.log("Not available choose another spot...", 1); } else { if (draggedElementId !== undefined && draggedElementClass[0] === "line") { console.log("we are about to drop the itemm ####"); MoveItemWhenDrop(draggedElementId, DropItem); console.log("Lines got updated !"); setTimeout(() => { Lines = containerDropArea[0].querySelectorAll(".line"); }, 500); } else { console.log("Not available choose another spot...", 2); } } } }); } } } function getRandomColor() { var color = ''; return color; } } document.addEventListener('DOMContentLoaded', () => { setupTabs(); filterAndShowProducts(); SearchProducts(); }); let selectedCategory = "pavimento"; function setupTabs() { const tabs = document.querySelectorAll('.tab-item'); tabs.forEach(tab => { tab.addEventListener('click', function () { tabs.forEach(item => item.classList.remove('active')); this.classList.add('active'); selectedCategory = this.textContent.trim().toLowerCase(); filterAndShowProducts(); }); }); const pavimentoTab = [...tabs].find(tab => tab.textContent.trim().toLowerCase() === "pavimento"); if (pavimentoTab) pavimentoTab.classList.add("active"); } function SearchProducts() { let searchInput = document.querySelector("#search-products"); searchInput.addEventListener("input", () => { filterAndShowProducts(); }); } function filterAndShowProducts() { let searchInput = document.querySelector("#search-products").value.toLowerCase(); const filteredData = DataBase.filter(product => { // 🔹 Criar regras para separar Pavimento e Mural const isPavimento = product.product_name.toLowerCase().includes("pavimento") || product.product_sku.toLowerCase().startsWith("pav"); const isMural = product.product_name.toLowerCase().includes("mural") || product.product_sku.toLowerCase().startsWith("mur"); // Definir se o produto pertence à aba ativa let matchesCategory = false; if (selectedCategory === "pavimento") matchesCategory = isPavimento; if (selectedCategory === "mural") matchesCategory = isMural; // 🔹 Aplicar filtro de busca junto com a categoria const matchesSearch = product.product_name.toLowerCase().includes(searchInput) || product.product_sku.toLowerCase().includes(searchInput); return matchesCategory && matchesSearch; }); ShowAllproducts(filteredData); } function GoBack() { function back() { console.clear(); console.log("sub-list : ", document.querySelector(".sub-components-section")); console.log("Main list : ", ProductList); if (document.querySelector(".sub-components-section").classList.contains("d-none")) { document.querySelector(".sub-components-section").classList.remove("d-none"); } else { document.querySelector(".sub-components-section").classList.add("d-none"); } if (ProductList.classList.contains("d-none")) { ProductList.classList.remove("d-none"); } else { ProductList.classList.add("d-none"); } } document.querySelector(".go-back-btn").addEventListener("click", () => { back(); }); document.querySelector(".back-to-configs").addEventListener("click", () => { back(); }); } GoBack(); setInterval(() => { if (CurrentProductData.product !== undefined && CurrentProductData.product !== null) { document.querySelector(".back-to-configs").classList.remove("d-none"); document.querySelector(".back-to-configs").classList.add("d-flex"); } else { document.querySelector(".back-to-configs").classList.add("d-none"); document.querySelector(".back-to-configs").classList.remove("d-flex"); } }, 3000); }
    Meu carrinho
    Favoritos
    Visualizado recentemente
    Ativar Alerta Iremos notificá-lo quando o produto voltar a estar disponível.
    You need to Login for joining waitlist.