Skip to content

Commit

Permalink
Merge pull request #13 from jap-2024-grupo2/feature/product-info
Browse files Browse the repository at this point in the history
feat: replica de diseño y funcionalidad de product-info
  • Loading branch information
ValeHernandezz authored Sep 9, 2024
2 parents ac1b334 + 928f31d commit bf9c3b8
Show file tree
Hide file tree
Showing 3 changed files with 256 additions and 116 deletions.
102 changes: 102 additions & 0 deletions js/product-info.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
// Obtenemos la ID del producto guardado previamente en el localStorage
const productID = localStorage.getItem('productID')

// Creamos un elemento para el carrusel con la imagen correspondiente
const createCarouselItem = (imgSrc, isActive, altText) => `
<div class="carousel-item ${isActive ? 'active' : ''}">
<img src="${imgSrc}" class="d-block w-100" alt="${altText}">
</div>`

// Creamos un elemento de imagen con o sin margen inferior, según si es la última imagen
const createImageElement = (imgSrc, altText, isLast) => `
<img src="${imgSrc}" class="${isLast ? '' : 'mb-3 mb-lg-4'}" alt="${altText}" style="width: 100%;">`

// Ajustamos la visibilidad del carrusel y de las imágenes verticales según el tamaño de la pantalla
const adjustCarousels = (horizontalCarousel, verticalImages) => {
if (window.innerWidth < 576) {
horizontalCarousel.style.display = 'block'
verticalImages.style.display = 'none'
} else {
horizontalCarousel.style.display = 'none'
verticalImages.style.display = 'flex'
}
}

fetch(`https://japceibal.github.io/emercado-api/products/${productID}.json`)
.then((res) => res.json())
.then(
({ id, name, description, cost, currency, soldCount, category, images, relatedProducts }) => {
// Actualizamos la información del producto
document.getElementById('product-info-img').src = images[0]
document.getElementById('product-info-category').textContent = category
document.getElementById('product-info-name').textContent = name
document.getElementById('product-info-cost').textContent = `${currency} ${cost}`
document.getElementById('product-info-description').textContent = description
document.getElementById('product-info-soldCount').textContent = `${soldCount} vendidos`

// Creamos el carrusel horizontal dinámico con las imágenes a partir del índice 1
const horizontalCarousel = document.createElement('div')
horizontalCarousel.className = 'carousel slide'
horizontalCarousel.id = 'horizontalCarousel'
horizontalCarousel.setAttribute('data-bs-ride', 'carousel')

// Generamos el contenido del carrusel horizontal
const carouselInner = images
.slice(1, 4) // Seleccionamos solo las imágenes necesarias
.map((imgSrc, index) =>
createCarouselItem(
imgSrc,
index === 0, // Marcamos la primera imagen como activa
`Imagen ${index + 1} de ${name}`
)
)
.join('')

horizontalCarousel.innerHTML = `
<div class="carousel-inner mt-5">
${carouselInner}
</div>
<button class="carousel-control-prev" type="button" data-bs-target="#horizontalCarousel" data-bs-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="visually-hidden">Previous</span>
</button>
<button class="carousel-control-next" type="button" data-bs-target="#horizontalCarousel" data-bs-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="visually-hidden">Next</span>
</button>`

// Creamos el contenedor de imágenes vertical dinámico
const verticalImages = document.createElement('div')
verticalImages.className = 'col-sm-2 d-flex flex-column align-items-center vertical-images'

// Generamos el contenido de las imágenes verticales
const verticalImagesInner = images
.slice(1, 4) // Seleccionamos las imágenes necesarias
.map((imgSrc, index, array) =>
createImageElement(
imgSrc,
`Imagen ${index + 1} de ${name}`,
index === array.length - 1 // Eliminamos margen para la última imagen
)
)
.join('')

verticalImages.innerHTML = verticalImagesInner

// Insertamos el carrusel horizontal y las imágenes verticales en sus contenedores
const solCountAddToCartContainer = document.querySelector('#product-info-soldCount-addToCart')
solCountAddToCartContainer.insertAdjacentElement('afterend', horizontalCarousel)

const contentContainer = document.querySelector('#content-container')
contentContainer.insertAdjacentElement('afterbegin', verticalImages)

// Ajustamos los carruseles según el tamaño de la pantalla al cargar la página
adjustCarousels(horizontalCarousel, verticalImages)
window.addEventListener('resize', () =>
adjustCarousels(horizontalCarousel, verticalImages) // Reajustamos carruseles al redimensionar la ventana
)
}
)
.catch((error) => {
console.error('Error fetching datos del producto:', error) // Capturamos errores en la obtención de datos
})
222 changes: 112 additions & 110 deletions js/products.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,35 @@
const catID = localStorage.getItem("catID");
let currentProductsArray = [];
let minPrice = undefined;
let maxPrice = undefined;
const catID = localStorage.getItem('catID')
let currentProductsArray = []
let minPrice = undefined
let maxPrice = undefined

fetch(`https://japceibal.github.io/emercado-api/cats_products/${catID}.json`)
.then((res) => res.json())
.then(({ products, catName }) => {
const categoryTitle = document.getElementById("categoryTitle");
categoryTitle.textContent = catName;
const categoryTitle = document.getElementById('categoryTitle')
categoryTitle.textContent = catName

currentProductsArray = products;
currentProductsArray = products

if (products.length === 0) {
showAlert("No hay productos disponibles para esta categoría");
document.getElementById("sortAndFilterContainer").style.display = "none";
return;
showAlert('No hay productos disponibles para esta categoría')
document.getElementById('sortAndFilterContainer').style.display = 'none'
return
}
document.getElementById("sortAndFilterContainer").style.display = "block";
showProductsList();
});
document.getElementById('sortAndFilterContainer').style.display = 'block'
showProductsList()
})

function setProductID(id) {
localStorage.setItem('productID', id)
window.location = 'product-info.html'
}

function showProductsList() {
const productsContainer = document.getElementById("productsContainer");
productsContainer.innerHTML = ""; // Limpiar el contenedor antes de mostrar
const productsContainer = document.getElementById('productsContainer')
productsContainer.innerHTML = '' // Limpiar el contenedor antes de mostrar

const fragment = document.createDocumentFragment();
const fragment = document.createDocumentFragment()

currentProductsArray.forEach(
({ id, image, name, description, currency, cost, soldCount }) => {
Expand All @@ -34,138 +39,135 @@ function showProductsList() {
(maxPrice == undefined ||
(maxPrice != undefined && parseFloat(cost) <= maxPrice))
) {
const column = document.createElement("div");
column.classList.add("col-12", "col-md-6", "col-lg-4", "my-3");
const column = document.createElement('div')
column.classList.add('col-12', 'col-md-6', 'col-lg-4', 'my-3')

const card = document.createElement("div");
const card = document.createElement('div')
card.classList.add(
"card",
"custom-card",
"cursor-active",
"h-100",
"w-100"
);
card.style = "width: 24rem;";

const img = document.createElement("img");
img.classList.add("card-img-top");
img.src = image;
img.alt = `Imagen de ${name}`;
img.loading = "lazy";

const cardBody = document.createElement("div");
'card',
'custom-card',
'cursor-active',
'h-100',
'w-100'
)
card.style = 'width: 24rem;'
card.onclick = () => setProductID(id)

const img = document.createElement('img')
img.classList.add('card-img-top')
img.src = image
img.alt = `Imagen de ${name}`
img.loading = 'lazy'

const cardBody = document.createElement('div')
cardBody.classList.add(
"card-body",
"d-flex",
"flex-column",
"justify-content-between"
);
'card-body',
'd-flex',
'flex-column',
'justify-content-between'
)

const cardTitle = document.createElement("h5");
cardTitle.classList.add("card-title", "card-title-h5");
cardTitle.textContent = name;
const cardTitle = document.createElement('h5')
cardTitle.classList.add('card-title', 'card-title-h5')
cardTitle.textContent = name

const cardDescription = document.createElement("p");
const cardDescription = document.createElement('p')
cardDescription.classList.add(
"card-text",
"card-description",
"flex-grow-1"
);
cardDescription.textContent = description;

const cardPrice = document.createElement("p");
cardPrice.classList.add("card-text", "card-price", "mt-auto");
cardPrice.textContent = `${currency} ${cost}`;

const cardSoldCount = document.createElement("p");
cardSoldCount.classList.add("card-text", "card-sold-count");
cardSoldCount.textContent = `${soldCount} vendidos`;

cardBody.append(cardTitle, cardDescription, cardPrice, cardSoldCount);
card.append(img, cardBody);
column.appendChild(card);
fragment.appendChild(column);
'card-text',
'card-description',
'flex-grow-1'
)
cardDescription.textContent = description

const cardPrice = document.createElement('p')
cardPrice.classList.add('card-text', 'card-price', 'mt-auto')
cardPrice.textContent = `${currency} ${cost}`

const cardSoldCount = document.createElement('p')
cardSoldCount.classList.add('card-text', 'card-sold-count')
cardSoldCount.textContent = `${soldCount} vendidos`

cardBody.append(cardTitle, cardDescription, cardPrice, cardSoldCount)
card.append(img, cardBody)
column.appendChild(card)
fragment.appendChild(column)
}
}
);
)

productsContainer.appendChild(fragment);
productsContainer.appendChild(fragment)
}

function sortProducts(criteria) {
if (criteria === "PriceAsc") {
currentProductsArray.sort(
(a, b) => parseFloat(a.cost) - parseFloat(b.cost)
);
} else if (criteria === "PriceDesc") {
currentProductsArray.sort(
(a, b) => parseFloat(b.cost) - parseFloat(a.cost)
);
} else if (criteria === "Relevance") {
if (criteria === 'PriceAsc') {
currentProductsArray.sort((a, b) => parseFloat(a.cost) - parseFloat(b.cost))
} else if (criteria === 'PriceDesc') {
currentProductsArray.sort((a, b) => parseFloat(b.cost) - parseFloat(a.cost))
} else if (criteria === 'Relevance') {
currentProductsArray.sort(
(a, b) => parseInt(b.soldCount) - parseInt(a.soldCount)
);
)
}

showProductsList();
showProductsList()
}

document.getElementById("sortAscPrice").addEventListener("click", function () {
sortProducts("PriceAsc");
});
document.getElementById('sortAscPrice').addEventListener('click', function () {
sortProducts('PriceAsc')
})

document.getElementById("sortDescPrice").addEventListener("click", function () {
sortProducts("PriceDesc");
});
document.getElementById('sortDescPrice').addEventListener('click', function () {
sortProducts('PriceDesc')
})

document
.getElementById("sortByRelevance")
.addEventListener("click", function () {
sortProducts("Relevance");
});
.getElementById('sortByRelevance')
.addEventListener('click', function () {
sortProducts('Relevance')
})

document
.getElementById("clearRangeFilter")
.addEventListener("click", function () {
document.getElementById("rangeFilterPriceMin").value = "";
document.getElementById("rangeFilterPriceMax").value = "";
.getElementById('clearRangeFilter')
.addEventListener('click', function () {
document.getElementById('rangeFilterPriceMin').value = ''
document.getElementById('rangeFilterPriceMax').value = ''

minPrice = undefined;
maxPrice = undefined;
minPrice = undefined
maxPrice = undefined

showProductsList();
});
showProductsList()
})

document
.getElementById("rangeFilterPrice")
.addEventListener("click", function () {
minPrice = document.getElementById("rangeFilterPriceMin").value;
maxPrice = document.getElementById("rangeFilterPriceMax").value;
.getElementById('rangeFilterPrice')
.addEventListener('click', function () {
minPrice = document.getElementById('rangeFilterPriceMin').value
maxPrice = document.getElementById('rangeFilterPriceMax').value

if (minPrice != undefined && minPrice != "" && parseFloat(minPrice) >= 0) {
minPrice = parseFloat(minPrice);
if (minPrice != undefined && minPrice != '' && parseFloat(minPrice) >= 0) {
minPrice = parseFloat(minPrice)
} else {
minPrice = undefined;
minPrice = undefined
}

if (maxPrice != undefined && maxPrice != "" && parseFloat(maxPrice) >= 0) {
maxPrice = parseFloat(maxPrice);
if (maxPrice != undefined && maxPrice != '' && parseFloat(maxPrice) >= 0) {
maxPrice = parseFloat(maxPrice)
} else {
maxPrice = undefined;
maxPrice = undefined
}

showProductsList();
});
showProductsList()
})

function showAlert(message) {
const alertContainer = document.createElement("div");
alertContainer.className = "alert alert-warning alert-dismissible fade show";
alertContainer.role = "alert";
const alertContainer = document.createElement('div')
alertContainer.className = 'alert alert-warning alert-dismissible fade show'
alertContainer.role = 'alert'
alertContainer.innerHTML = `
<strong>Advertencia:</strong> ${message}
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
`;
`

const categoryTitle = document.getElementById("categoryTitle");
categoryTitle.insertAdjacentElement("afterend", alertContainer);
const categoryTitle = document.getElementById('categoryTitle')
categoryTitle.insertAdjacentElement('afterend', alertContainer)
}
Loading

0 comments on commit bf9c3b8

Please sign in to comment.