-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
366 lines (294 loc) · 11.6 KB
/
index.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
function Book(title, author, numPages, isRead = false){
this.title = title,
this.author = author,
this.numPages = numPages,
this.isRead = isRead;
this.info = () => {
let read = this.isRead ? 'read' : 'not read yet'
return `${this.title} by ${this.author}, ${this.numPages} pages, ${read} `;
}
}
//elements
const albumRow = document.getElementById('albumRow');
const submitBtn = document.getElementById('submit-btn');
// variables
let myLibrary = [];
checkLocalStorage();
const removeBtnList = Array.from(document.querySelectorAll('button[class="btn btn-sm btn-danger"]'));
//events
submitBtn.addEventListener('click', () => createNewBook());
/**
* test whether the storage object has already been populated (i.e., the page was
* previously accessed)
*/
function checkLocalStorage(){
if(!localStorage.getItem('myLibrary')) {
populateStorage();
} else {
loadBooks();
renderBooks();
}
}
/**
* Display books on cards
*/
function renderBooks(){
for (let i = 0; i < myLibrary.length; i++) {
let book = myLibrary[i];
const bookRender = renderBook(book);
albumRow.appendChild(bookRender);
}
}
/**
* Load localStorage when app is first accessed
*/
function populateStorage(){
populateLibrary();
localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
}
/**
* Retrieve books from localStorage
*/
function loadBooks(){
// Retrieve the object from storage
let retrievedLibrary = localStorage.getItem('myLibrary');
myLibrary = JSON.parse(retrievedLibrary);
}
function addBookToLibrary(newBook){
myLibrary.push(newBook);
}
/**
* When the user clicks 'Remove' Button on book card, DOM element has to be removed as well as
* the book that it relates to inside myLibrary
* @param {Object} buttonPressed Remove Button that has been presed
*/
function removeBook(buttonPressed){
const cardElementToRemove = buttonPressed.offsetParent.offsetParent;
const bookToRemoveId = cardElementToRemove.dataset.bookId;
const bookToRemoveIndex = myLibrary.findIndex( book => book.id == bookToRemoveId );
//TODO: ask for confirmation
myLibrary.splice(bookToRemoveIndex, 1);
updateLocalStorageLibrary();
cardElementToRemove.remove();
}
/**
* In order to target the apropiate card to remove from DOM when deleting a book
* I'll generate a UUID kind-of ID that will be stored in its parent element dataset
*/
function createUniqueId(){
var dateTime = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(char) {
var r = (dateTime + Math.random()*16)%16 | 0;
dateTime = Math.floor(dateTime/16);
return (char=='x' ? r :(r&0x3|0x8)).toString(16);
});
return uuid;
}
/**
* On first access to app, populate library in order to populate localStorage
*/
function populateLibrary(){
let aBook = new Book('Harry Potter', 'J.K. Rowling', 845, false);
addBookToLibrary(aBook);
aBook = new Book('Arianna Jenkins and Reverse-engineered asynchronous array ', 'Valentine Schneider', 97250, false);
addBookToLibrary(aBook);
aBook = new Book('Elyssa Kunze and Ergonomic directional alliance ', 'Clifford Beahan', 29846, true);
addBookToLibrary(aBook);
aBook = new Book('Junior Hintz and Seamless next generation implementation ', 'Keenan Mosciski', 53915, false);
addBookToLibrary(aBook);
aBook = new Book('Ernestine Krajcik and Robust client-driven hardware ', 'Luz Bradtke', 75661, false);
addBookToLibrary(aBook);
aBook = new Book('Tavares Wyman and Face to face global installation ', 'Esperanza Mraz', 33816, true);
addBookToLibrary(aBook);
aBook = new Book('Charlene Schulist and Networked local methodology ', 'Veronica Leannon', 21165, false);
addBookToLibrary(aBook);
aBook = new Book('Anahi Olson and Team-oriented multi-tasking open architecture ', 'Jordy Toy', 13603, false);
addBookToLibrary(aBook);
aBook = new Book('Jabari King and Digitized 24 hour encoding ', 'Barton Anderson', 87283, false);
addBookToLibrary(aBook);
aBook = new Book('Cecile Breitenberg and Sharable 5th generation internet solution ', 'Aimee Wunsch', 82643, false);
addBookToLibrary(aBook);
aBook = new Book('Vida Von and Persistent optimizing pricing structure ', 'Catherine Roberts', 17763, true);
addBookToLibrary(aBook);
}
function createCardElement(){
return createElementWithClass('div', ['card', 'mb-4', 'shadow-sm']);
}
/**
* adds a new div that will store the book card
*/
function createColElement(){
return createElementWithClass('div', ["col-md-4", "col-sm-12"]);
}
function createCardFooter(book){
let cardFooter = createElementWithClass('div', ['d-flex', 'justify-content-between', 'align-items-center']);
let footerBtnGroup = createElementWithClass('div', ['btn-group']);
let editBtn = createElementWithClass('button', ['btn', 'btn-sm', 'btn-outline-primary']);
editBtn.textContent = 'edit';
editBtn.setAttribute('type','button');
let markAsReadButton = createElementWithClass('button', ['btn', 'btn-sm', 'btn-outline-secondary']);
markAsReadButton.textContent = book.isRead ? '✅' : '👍' ;
markAsReadButton.setAttribute('type','button');
let btnToRemoveBook = createElementWithClass('button', ['btn','btn-sm', 'btn-danger']);
btnToRemoveBook.textContent = 'Remove';
let pagesText = createElementWithClass('small', ['text-muted', 'text-decoration-none']);
pagesText.textContent = `${book.numPages} Pages`;
let btnGroup = appendChild(footerBtnGroup, [editBtn, markAsReadButton]);
let footer = appendChild(cardFooter, [btnGroup, btnToRemoveBook]);
return footer;
}
/**
*
* @param {String} elementTag html <tag>
* @param {*} classes Array
*/
function createElementWithClass(elementTag, classes){
let newElement = document.createElement(`${elementTag}`);
for (let i = 0; i < classes.length; i++) {
newElement.classList.add(`${classes[i]}`);
}
return newElement;
}
function validateFields( bookTitle, bookAuthor, bookPages ){
let emptyString = '';
let faultyField = '';
let isValid = true;
if (emptyString===bookTitle ){
isValid = false;
faultyField = 'title';
}
if ( emptyString===bookAuthor && isValid) {
isValid = false;
faultyField = 'author';
}
if ( isValid) {
//validate page numbers field input
isValid = emptyString===bookPages ? false : validateNumbersOnlyField(bookPages) ;
faultyField = isValid ? '' : 'pages';
}
return faultyField;
}
/**
* For form fields that are type=text but meant to be for numbers (4ex: page numbers)
* checks if only valid [0-9] characters have been entered
*
* @param {String} inputValue field text value
*/
function validateNumbersOnlyField(inputValue){
const regex = /[0-9]|\./;
return regex.test(inputValue);
}
/**
* User can add new books to library by pressing the '+ add a button' Button
* and we have to create, display and localStore it properly
*/
function createNewBook(){
let bookTitle = document.getElementById('book-title').value;
let bookAuthor = document.getElementById('book-author').value;
let bookPages = document.getElementById('book-pages').value;
// read as in 'I have read this book'. !read as in 'do you like to read?' English parafernalia
let readBook = document.getElementById('read-book-check').checked;
const faultyField = validateFields(bookTitle,bookAuthor, bookPages);
let areFieldsValid = faultyField.length == 0;
if (!areFieldsValid){
alert(`Please provide a valid value for ${faultyField}`);
} else {
let aBook = new Book(bookTitle, bookAuthor, Number(bookPages), readBook);
addBookToLibrary(aBook);
// LO DE ABAJO NO ESTARÁ POR SIEMPRE AQUI ------------------------------
// Reemplazar por un metodo que renderice nuevamente la colección entera y no sólo
//este único libro
const bookCard = renderBook(aBook);
albumRow.appendChild(bookCard);
// LO DE ARRIBA NO ESTARÁ POR SIEMPRE AQUI ------------------------------
updateLocalStorageLibrary();
focusOnAddedBook(bookCard);
clearFields();
}
}
function updateLocalStorageLibrary(){
localStorage.setItem('myLibrary', JSON.stringify(myLibrary));
}
function focusOnAddedBook(newBookCard){
let bookId = newBookCard.id;
let anchor = document.querySelector(`[id='${bookId}']`);
anchor. scrollIntoView();
}
/**
* append multiple child elements to one parent element.
* @param {Object} parentElement element to append childs to
* @param {Array} childs elements to be appended
*/
function appendChild(parentElement, childs){
for (let i = 0; i < childs.length; i++) {
parentElement.innerHTML += childs[i].outerHTML;
}
return parentElement;
}
function clearFields(){
document.getElementById("new-book-form").reset();
}
/**
* creates book card and displays it
*
* @param {Object} book book to render
*/
function renderBook(book){
const bookRender = createColElement();
const cardElement = createCardElement();
const cardBody = createCard(book);
cardElement.appendChild(cardBody);
bookRender.appendChild(cardElement);
// bind book in array to book card in order to facilitate book removal
const bookId = createUniqueId();
book.id = bookId;
bookRender.dataset.bookId = `${bookId}`;
bookRender.id = (book.numPages).toString();
// provide remove-btn with functionality
// THIS IS SO CUMBERSOME AND HARD TO READ+
addFunctionalityToButtons(bookRender);
return bookRender;
}
function createCard(book){
let cardBody = createElementWithClass('div', ['card-body']);
let cardTitle = createElementWithClass('p', ['card-text', 'text-center']);
let cardAuthor = createElementWithClass('p', ['card-text', 'text-center']);
let cardPages = createElementWithClass('p', ['card-text', 'text-center', 'text-muted']);
let footer = createCardFooter(book);
cardTitle.textContent = `Title: ${book.title}`
cardAuthor.textContent = `Author: ${book.author}`
cardPages.textContent = `Pages: ${book.numPages}`
let card = appendChild(cardBody, [cardTitle, cardAuthor, cardPages, footer]);
return card;
}
/**
* When a card is created, functionality needs to be binded to each button in order to
* perform desired actions such as removing a book.
*/
function addFunctionalityToButtons(bookCard){
const cardFooter = Array.from(bookCard.lastChild.lastChild.lastElementChild.childNodes);
//remove book
let removeCardBtn = cardFooter[1];
removeCardBtn.addEventListener('click', element => removeBook(element.currentTarget))
// mark book as read
const markAsReadButton = cardFooter[0].lastElementChild;
markAsReadButton.addEventListener('click', element => markBookAsRead(element.currentTarget))
}
/**
* When user clicks on the mark-as-read button, toggle if book has been read or not
* @param {Object} cardButtonPressed HTML <button> that has been pressed
*/
function markBookAsRead(cardButtonPressed){
const cardElement = cardButtonPressed.offsetParent.offsetParent.offsetParent;
const idOfBookToMarkAsRead = cardElement.dataset.bookId;
// TODO: ask for confirmation
myLibrary = myLibrary.map( book => {
if (book.id === idOfBookToMarkAsRead) {
book.isRead = !(book.isRead)
// Switch btn to display the green tick
cardButtonPressed.textContent = book.isRead ? '✅' : '👍' ;
}
return book
} );
updateLocalStorageLibrary();
}