-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscripts.js
315 lines (279 loc) · 9.89 KB
/
scripts.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
let myLibrary = {}; // Stores book objs - supposed to use array (but how could we look for duplicates?)
let storage = false;
// ES6 class
class Book {
constructor(id, title, author, pages, read){
this.id = id;
this.title = title;
this.author = author;
this.pages = pages;
this.read = read;
}
info() {
let readStatus = this.read === true? 'read' : 'not read';
return `${this.title} by ${this.author}, ${this.pages} pages, ${readStatus}`;
}
changeReadStatus() {
if(this.read === true || this.read === 'Read') this.read = 'Not read';
else if(this.read === false || this.read === 'Not read') this.read = 'Read';
}
}
const addBookToLibrary = (title, author, pages, read) => {
const id = `Bk-T${title.length}A${author.length}`;
let newBook = new Book(id,title, author, pages, read);
if(myLibrary[id] === undefined) {
myLibrary[id] = newBook;
if(storage) {
storeBookLocally(newBook);
}
displayNewBook(newBook);
toggleEmptyMessage();
}
}
const displayNewBook = (book) => {
let booksContainer = document.querySelector('#library');
const bookElem = document.createElement('article');
bookElem.classList.add('library__bookCard');
bookElem.setAttribute('data-index',book.id);
bookElem.innerHTML=`<button class="button remove-btn"><i aria-hidden="true" class="fas fa-minus-circle" title="Remove from library"></i></button><h3 class="title is-3">${book.title}</h3> <p>${book.author}</p>`;
if(book.pages !== undefined){
let pagesText = document.createElement("p");
pagesText.innerHTML = `${book.pages} pages`;
bookElem.appendChild(pagesText);
}
if(book.read !== undefined){
let readStatus = book.read === true? 'read' : 'not read';
let readBtn = document.createElement("button");
readBtn.classList.add('button');
readBtn.classList.add('read-btn');
readBtn.innerHTML = readStatus;
bookElem.appendChild(readBtn);
}
booksContainer.appendChild(bookElem);
activateListeners();
}
const displayBooksFromLibrary = () => {
let booksContainer = document.querySelector('#library');
Object.keys(myLibrary).forEach((key) => {
const bookElem = document.createElement("article");
bookElem.classList.add('library__bookCard');
bookElem.innerHTML=`<h3 class="title is-3">${myLibrary[key].title}</h3> <p><strong>By:</strong> ${myLibrary[key].author}</p>`;
if(myLibrary[key].pages !== undefined){
let pagesText = document.createElement("p");
pagesText.innerHTML = `${myLibrary[key].pages} pages`;
bookElem.appendChild(pagesText);
}
booksContainer.appendChild(bookElem);
});
}
const removeBook = (book) => {
let bookElem = book.parentElement;
let bookIndex = bookElem.dataset.index;
localStorage.removeItem(bookIndex);
delete myLibrary[bookIndex];
bookElem.remove();
toggleEmptyMessage();
}
const changeBookStatus = (book) => { // TODO: Fix bug - function running multiple times when book is already in library at load time
let bookElem = book.parentElement;
let bookIndex = bookElem.dataset.index;
myLibrary[bookIndex].changeReadStatus();
let readStatus = myLibrary[bookIndex].read;
bookElem.querySelector('.read-btn').innerHTML = readStatus;
}
const openModal = (btn) => {
let targetModal = btn.dataset.target;
let targetElem = document.querySelector(`.${targetModal}`);
let htmlBody = document.querySelector('html');
let addBtn = document.getElementById('add-book-btn');
targetElem.classList.add("is-active");
htmlBody.classList.add("is-clipped");
closeModal(targetElem);
addBtn.addEventListener('click', (e) => {
e.preventDefault();
getUserInput(targetElem, function(){
let form = document.getElementById('new-book-form');
form.reset();
closingModalProps(targetElem, htmlBody);
});
});
}
const closeModal = (modal) => {
let html = document.querySelector('html');
let closeBtn = modal.querySelector("button.modal-close");
closeBtn.addEventListener('click', () => { // close modal if 'close' button is clicked
closingModalProps(modal, html);
});
document.addEventListener('click', e => {
if(e.target.classList.contains('modal-background')){ // close modal if user clicks on the background
closingModalProps(modal, html);
}
});
}
const closingModalProps = (modal, html) => {
modal.classList.remove("is-active");
html.classList.remove("is-clipped");
}
/*
* TODO: Add 'live' validation so 'Add btn' becomes enabled
* Listener activated when modal is open. The button will be disabled to begin with.
* Listener on required fields will check for input, if the text is >= 2 the button will be enabled. If < 2, the button will be disabled.
*/
// function liveValidation(field) {
// if (field.classList.contains('is-danger'))
// field.classList.remove('is-danger');
// // title.addEventListener('input',countChars); // Using () will execute the fn and return its value. without it will fetch the function (reference it)
// // author.addEventListener('input',countChars);
// // if(title.dataset.valid === 'true' && author.dataset.valid === 'true') {
// // console.log('req fields are valid now')
// // }
// }
/* Helper Fn for liveValidation */
// const countChars = (e) => {
// let field = e.currentTarget;
// let currentInput = e.currentTarget.value;
// if(currentInput.length >= 2) {
// field.dataset.valid = 'true';
// } else {
// field.dataset.valid = 'false';
// }
// return;
// }
const validateFormInput = () => {
let requiredFields = document.querySelectorAll('input[required]');
let flag = true;
requiredFields.forEach( field => {
if(field.value.length <= 0) {
flag = false;
field.classList.add('is-danger');
}
});
return flag;
}
getUserInput = (form, callback) => {
let validForm = validateFormInput();
if(validForm){
const inputFields = form.querySelectorAll('input[type="text"], input[type="number"], input[type="radio"]');
let savedInputs = {};
inputFields.forEach(field => { // Grabs users input from form and saves it in obj
let input = '';
let id = field.id;
if(field.value !== "" && field.type !=='radio' ){
input = field.value;
} else if(field.type === 'radio' && field.checked) {
input = field.checked;
} else {
return;
}
savedInputs[id] = input;
});
if(Object.keys(savedInputs).length > 0){ // goes through obj and assigns to vars to add to library
let title = savedInputs['titleInput'];
let author = savedInputs['authorInput'];
let pages = savedInputs['pagesInput'] === null? '' : savedInputs['pagesInput'];
let read = savedInputs['readYesInput']? true : false;
addBookToLibrary(title,author,pages, read);
}
} else { return; }
callback();
}
toggleEmptyMessage = () => {
let msg = document.getElementById('empty-msg');
if(Object.keys(myLibrary).length <= 0) {
msg.style.display = 'block';
} else {
msg.style.display = 'none';
}
}
const activateListeners = () => {
let addNewBtn = document.querySelector('button.modal-button');
let removeBtns = document.querySelectorAll('button.remove-btn');
let readBtns = document.querySelectorAll('button.read-btn');
let requiredFields = document.querySelectorAll('input[required]');
addNewBtn.addEventListener('click', function(e){
e.preventDefault();
openModal(this);
});
removeBtns.forEach( btn => btn.addEventListener('click', function(e){
e.preventDefault();
removeBook(this);
}));
readBtns.forEach( btn => {
btn.addEventListener('click', function(e){
e.preventDefault();
changeBookStatus(this);
});
});
requiredFields.forEach(field => field.addEventListener('input', () => liveValidation(field)));
}
// Main functions
const init = () => {
toggleEmptyMessage();
activateListeners();
checkforStorage();
}
window.addEventListener("load", () => {
init();
});
// Web Storage
const storageAvailable = function(type) {
let storage;
try {
storage = window[type];
let x = '__storage_test__';
storage.setItem(x, x);
storage.removeItem(x);
return true;
}
catch(e) {
return e instanceof DOMException && (
// everything except Firefox
e.code === 22 ||
// Firefox
e.code === 1014 ||
// test name field too, because code might not be present
// everything except Firefox
e.name === 'QuotaExceededError' ||
// Firefox
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') &&
// acknowledge QuotaExceededError only if there's something already stored
(storage && storage.length !== 0);
}
}
const checkforStorage = function() {
if(storageAvailable('localStorage')) {
storage = true;
if(localStorage.length > 0) {
getBooksFromStorage();
}
}
}
const storeBookLocally = function(book){
let book_serialized = JSON.stringify(book);
if(localStorage.getItem(book.id) === null){
localStorage.setItem(book.id, book_serialized);
}
//console.log(localStorage.getItem(book.id)); // get book in string format
}
const getBooksFromStorage = function(){
let bookObj;
for(let [key,value] of Object.entries(localStorage)){
bookObj = JSON.parse(localStorage.getItem(key));
addBookToLibrary(bookObj.title, bookObj.author, bookObj.pages, bookObj.read);
}
}
// Following OP format (ES5)
// function Book(title, author, pages, read) {
// this.title = title;
// this.author = author;
// this.pages = pages;
// this.read = read;
// }
// // By defining functions on the protoype of the object, we ensure a single instance will be shared between all obj created and not duplicated every time
// Book.prototype.info = function () {
// let readStatus = this.read === true ? "read" : "not read yet";
// return `${this.title} by ${this.author}, ${this.pages} pages, ${this.readStatus}`;
// };
// // Takes user's input and stores the new book object into the myLibrary array
// function addBookToLibrary() {
// }