-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
194 lines (172 loc) · 6.24 KB
/
script.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
const firstSectionItem = document.querySelectorAll('.items')[0];
const cartItems = document.querySelectorAll('.cart__items')[0];
const emptyBtn = document.querySelector('.empty-cart');
const totalPrice = document.querySelector('.total-price');
const loaderContainer = document.getElementById('loader-container');
const loaderElement = document.getElementsByClassName('loader-wrapper')[0];
const searchButton = document.getElementById('search-btn');
const selectCategories = document.getElementById('search-items');
const searchNewCategory = () => {
const category = selectCategories.selectedOptions[0].value;
firstSectionItem.innerHTML = '';
localStorage.setItem('initialCategory', category);
appendProduct(category, firstSectionItem);
}
const findInitialCategoryIndex = (initialCategory) => {
const test = [...selectCategories.options];
const actualOptionIndex = test.findIndex((el) => el.value === initialCategory);
return actualOptionIndex;
}
searchButton.addEventListener('click', searchNewCategory);
const stringifyContent = () => {
const cartItemsContent = cartItems.innerHTML;
const stringifiedCartItems = JSON.stringify(cartItemsContent);
saveCartItems(stringifiedCartItems);
};
const loadMaker = () => {
const testParagraph = document.getElementsByClassName('loading')[0];
if (!testParagraph) {
const createdParagraph = document.createElement('p');
createdParagraph.className = 'loading';
createdParagraph.innerText = 'Carregando...';
loaderContainer.appendChild(createdParagraph);
loaderElement.style.display = 'inline-block';
}
};
const loadDestroyer = () => {
const destroyingParagraph = document.getElementsByClassName('loading')[0];
if (destroyingParagraph) {
loaderElement.style.display = 'none';
loaderContainer.removeChild(destroyingParagraph);
}
};
function cartItemClickListener(event) {
const cartElement = event.target;
const cartElementPrice = cartElement.parentNode.innerText.split('PRICE: $')[1].trim();
const finalPrice = parseFloat(totalPrice.innerText - cartElementPrice);
totalPrice.innerText = (finalPrice > 0.5) ? finalPrice.toFixed(2) : '0.00';
cartItems.removeChild(cartElement.parentNode);
stringifyContent();
};
function getSkuFromProductItem(item) {
return item.querySelector('span.item__sku').innerText;
};
function createProductImageElement(imageSource) {
const img = document.createElement('img');
img.className = 'item__image';
img.src = imageSource;
return img;
};
function createCartItemElement({ sku, name, salePrice, thumbnail }) {
const section = document.createElement('section');
const li = document.createElement('li');
const img = document.createElement('img');
img.src = thumbnail;
img.className = 'cart__item-img'
li.className = 'cart__item';
li.innerText = `SKU: ${sku} | NAME: ${name} | PRICE: $${salePrice}`;
section.appendChild(img);
section.appendChild(li)
return section;
};
const sumSubTotal = async (obj) => {
const checkObj = await fetchItem(obj.id);
const floatPrice = parseFloat(totalPrice.innerText);
const newItemPrice = parseFloat(checkObj.price);
const newText = (floatPrice + newItemPrice).toFixed(2);
totalPrice.innerText = newText;
stringifyContent();
return totalPrice;
};
const prepareToAppend = async (itemId) => {
loadMaker();
const getItem = await fetchItem(itemId);
loadDestroyer();
const cardObj = {
sku: getItem.id,
name: getItem.title,
salePrice: getItem.price,
thumbnail: getItem.thumbnail,
};
const cardItem = createCartItemElement(cardObj);
cardItem.classList.add('chosenItem');
const closeBtn = document.createElement('div');
closeBtn.classList.add('cartItemDiv');
closeBtn.addEventListener('click', cartItemClickListener);
cartItems.appendChild(cardItem);
cardItem.appendChild(closeBtn);
sumSubTotal(getItem);
};
const appendCart = async (event) => {
const cardBtn = event.target;
const cardId = getSkuFromProductItem(cardBtn.parentNode);
prepareToAppend(cardId);
};
function createCustomElement(element, className, innerText) {
const e = document.createElement(element);
e.className = className;
e.innerText = innerText;
if (className === 'item__add') {
e.addEventListener('click', appendCart);
}
return e;
};
function createProductItemElement({ sku, name, image, price }) {
const section = document.createElement('section');
section.className = 'item';
const displayPrice = `R$ ${price.toFixed(2)}`
section.appendChild(createProductImageElement(image));
section.appendChild(createCustomElement('span', 'item__sku', sku));
section.appendChild(createCustomElement('span', 'item__title', name));
section.appendChild(createCustomElement('span', 'item__price', displayPrice))
section.appendChild(createCustomElement('button', 'item__add', 'Adicionar ao carrinho!'));
return section;
};
const emptyCart = () => {
const allCartItems = [...cartItems.childNodes];
allCartItems.forEach((element) => cartItems.removeChild(element));
totalPrice.innerText = '0.00';
localStorage.clear();
};
emptyBtn.addEventListener('click', emptyCart);
const appendProduct = async (query, parentNode) => {
loadMaker();
const data = await fetchProducts(query);
const productsList = data.results;
productsList.forEach((product) => {
const productObj = {
sku: product.id,
name: product.title,
image: product.thumbnail,
price: product.price,
};
const item = createProductItemElement(productObj);
parentNode.appendChild(item);
});
setTimeout(() => {
loadDestroyer();
}, 700); // somente por critério estético
};
const appendSavedItems = async () => {
const cartItemsValue = getSavedCartItems();
const parsedCartItems = JSON.parse(cartItemsValue);
const splitedParsedCartItems = parsedCartItems.split(' ');
const savedIds = splitedParsedCartItems.filter((element) => element.startsWith('ML'));
savedIds.forEach((element) => {
prepareToAppend(element);
});
};
window.onload = () => {
const initialCategory = localStorage.getItem('initialCategory') || 'Computador';
appendProduct(initialCategory, firstSectionItem);
if (JSON.parse(localStorage.getItem('cartItems'))) {
appendSavedItems();
}
createCategoriesOptions();
};
if (typeof module !== 'undefined') {
module.exports = {
appendProduct,
prepareToAppend,
};
};