-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase-ui.js
455 lines (366 loc) · 14.1 KB
/
base-ui.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
$(async function() {
// cache some selectors we'll be using quite a bit
const $navDropDown = $("#navDropDown");
const $allStoriesList = $("#all-stories-container");
const $loginButton = $("#login");
const $loginForm = $("#login-form");
const $loginModal = $("#login-modal");
const $registerButton = $("#register");
const $registerForm = $("#register-form");
const $registerModal = $("#register-modal");
const $submitStoryButton = $("#submit-story-button")
const $submitStoryModal = $("#submit-story-modal")
const $submitStoryForm = $("#submit-story-form")
const $favouriteStoryButton = $("#favourite-story-button")
const $favouriteModal = $("#favourite-modal")
const $favoritedStories = $("#favourite-stories-container")
const $ownStoryButton = $("#own-story-button")
const $ownStoryModal = $("#own-story-modal")
const $ownStories = $("#own-stories-containers")
const $profileButton = $("#profile")
const $profileModal = $("#profile-modal");
const $logoutButton = $("#logout");
// global storyList variable
let storyList = null;
// global user variable
let currentUser = null;
await checkIfLoggedIn();
/**
* Event Handler for Clicking Login
*/
$loginButton.on("click", function() {
$loginModal.modal('show');
});
/**
* Event Handler For Submitting the Login Form
*/
$loginForm.on("submit", async function(evt){
evt.preventDefault(); // no page refresh
// grab the username and password
const username = $("#login-username").val();
const password = $("#login-password").val();
// call the login static method to build a user instance
const userInstance = await User.login(username, password);
// set the global user to the user instance
currentUser = userInstance;
syncCurrentUserToLocalStorage();
checkIfLoggedIn()
//Hide Login Modal
$loginModal.modal('hide');
})
/**
* Log Out Functionality
*/
$logoutButton.on("click", function() {
// empty out local storage
localStorage.clear();
// refresh the page, clearing memory
location.reload();
});
/**
* Event Handler for Clicking Register
*/
$registerButton.on("click", function() {
$registerModal.modal('show');
})
/**
* Event Handler For Submitting the Login Form
*/
$registerForm.on("submit", async function(evt){
evt.preventDefault(); // no page refresh
// grab the required fields
const name = $("#create-account-name").val();
const username = $("#create-account-username").val();
const password = $("#create-account-password").val();
// call create method, which calls API and then builds a new user instance
const newUser = await User.create(username, password, name);
currentUser = newUser;
syncCurrentUserToLocalStorage();
checkIfLoggedIn();
//Hide Register Modal
$registerModal.modal('hide');
})
/**
* Event Handler for Clicking Submit Button
*/
$submitStoryButton.on("click", function() {
$submitStoryModal.modal('show');
});
/**
* Event Handler For Submitting the Login Form
*/
$submitStoryForm.on("submit", async function(evt){
evt.preventDefault(); // no page refresh
// grab all the info from the form
const title = $("#title").val();
const url = $("#url").val();
const hostName = getHostName(url);
const author = $("#author").val();
const username = currentUser.username
const storyObject = await storyList.addStory(currentUser, {
title,
author,
url,
username
});
$allStoriesList.prepend(`
<div class="row mb-1" id="${storyObject.storyId}">
<div class="col-sm">
<div class="card text-white bg-dark mb-1">
<div class="card-header">
<a class="article-link" href="${url}" target="a_blank">
<strong>${title}</strong>
</a>
</div>
<div class="card-footer text-muted">
Posted by <small class="article-author">by ${author}</small>
<small class="article-hostname ${hostName}">(${hostName})</small>
<small class="article-username">posted by ${username}</small>
</div>
</div>
</div>
</div>
` );
//Hide Submit Story Modal
$submitStoryModal.modal('hide');
})
$favouriteStoryButton.on("click",function(){
generateFaves();
$favouriteModal.modal("show")
})
/**
* A rendering function to build the favorites list
*/
function generateFaves() {
// empty out the list by default
$favoritedStories.empty();
// if the user has no favorites
if (currentUser.favorites.length === 0) {
$favoritedStories.append("<h5>No favorites added!</h5>");
} else {
// for all of the user's favorites
for (let story of currentUser.favorites) {
// render each story in the list
let favoriteHTML = generateStoryHTML(story,false,true);
$favoritedStories.append(favoriteHTML);
}
}
}
/**
* Event Handler for showing the profile modal
*/
$profileButton.on('click',function(){
$profileModal.modal('show')
})
/**
* Event Handler for showing the own story modal
*/
$ownStoryButton.on("click",function(){
generateMyStories();
$ownStoryModal.modal("show")
})
/**
* A rendering function to build show own stories
*/
function generateMyStories() {
$ownStories.empty();
// if the user has no stories that they have posted
if (currentUser.ownStories.length === 0) {
$ownStories.append("<h5>No stories added by user yet!</h5>");
} else {
// for all of the user's posted stories
for (let story of currentUser.ownStories) {
// render each story in the list
let ownStoryHTML = generateStoryHTML(story,true);
$ownStories.append(ownStoryHTML);
}
}
// $ownStories.show();
}
/**
* Event Handler for Deleting a Single Story
*/
$ownStories.on("click", ".trash-can", async function(evt) {
// get the Story's ID
const storyId = $(evt.target).parents().eq(3).attr('id');
// remove the story from the API
await storyList.removeStory(currentUser, storyId);
// re-generate the story list
await generateStories();
// // hide everyhing
// hideElements();
// // ...except the story list
//$allStoriesList.show();
});
/**
* On page load, checks local storage to see if the user is already logged in.
* Renders page information accordingly.
*/
async function checkIfLoggedIn() {
// let's see if we're logged in
const token = localStorage.getItem("token");
const username = localStorage.getItem("username");
// if there is a token in localStorage, call User.getLoggedInUser
// to get an instance of User with the right details
// this is designed to run once, on page load
currentUser = await User.getLoggedInUser(token, username);
await generateStories();
if (currentUser) {
generateProfile();
showNavForLoggedInUser();
}
}
function showNavForLoggedInUser() {
//Hide Login button
$loginButton.toggle();
//Hide Register Button
$registerButton.toggle();
//Show Logged In Nav items
$('#loggedinitems').toggleClass("invisible")
//Display Profile Button
$('#profile').toggle();
//Display Logout Button
$logoutButton.show();
}
/**
* A rendering function to call the StoryList.getStories static method,
* which will generate a storyListInstance. Then render it.
*/
async function generateStories() {
// get an instance of StoryList
const storyListInstance = await StoryList.getStories();
// update our global variable
storyList = storyListInstance;
// empty out that part of the page
$allStoriesList.empty();
// loop through all of our stories and generate HTML for them
for (let story of storyList.stories) {
const result = generateStoryHTML(story);
$allStoriesList.append(result);
}
}
/**
* A render method to render HTML for an individual Story instance
* - story: an instance of Story
* - isOwnStory: was the story posted by the current user
*/
function generateStoryHTML(story, isOwnStory) {
let hostName = getHostName(story.url);
let starType = isFavorite(story) ? "fas" : "far";
// render a trash can for deleting your own story
const trashCanIcon = isOwnStory
? `
<button class="btn btn-outline-primary float-right trash-can">
<svg width="1em" height="1em" viewBox="0 0 16 16" class="bi bi-trash" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>
<path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>
</svg>
</button>`: "";
// render all the rest of the story markup
const storyMarkup = $(`
<div class="row mb-1" id="${story.storyId}">
<div class="col-sm">
<div class="card text-white bg-dark mb-1">
<div class="card-header">
<span type="button" class="star"><i class="${starType} fa-star"></i></span>
<a class="article-link" href="${story.url}" target="a_blank">
<strong>${story.title}</strong>
</a>
${trashCanIcon}
</div>
<div class="card-footer text-muted">
Posted by <small class="article-author">by ${story.author}</small>
<small class="article-hostname ${hostName}">(${hostName})</small>
<small class="article-username">posted by ${story.username}</small>
</div>
</div>
</div>
</div>
`);
return storyMarkup;
}
/* simple function to pull the hostname from a URL */
function getHostName(url) {
let hostName;
if (url.indexOf("://") > -1) {
hostName = url.split("/")[2];
} else {
hostName = url.split("/")[0];
}
if (hostName.slice(0, 4) === "www.") {
hostName = hostName.slice(4);
}
return hostName;
}
/* sync current user information to localStorage */
function syncCurrentUserToLocalStorage() {
if (currentUser) {
localStorage.setItem("token", currentUser.loginToken);
localStorage.setItem("username", currentUser.username);
}
}
/**
* Build a user profile based on the global "user" instance
*/
function generateProfile() {
// show your name
$("#profile-name").append(`
<div class="col-sm-3">
<span class="badge badge-pill badge-dark">Name</span>
</div>
<div class="col-sm-9">
<p class="text-capitalize">${currentUser.name}</p>
</div>
`);
// show your username
$("#profile-username").append(`
<div class="col-sm-3">
<span class="badge badge-pill badge-dark">Username</span>
</div>
<div class="col-sm-9">
<p class="text-capitalize">${currentUser.username}</p>
</div>
`);
// format and display the account creation date
$("#profile-account-date").append(`
<div class="col-sm-3">
<span class="badge badge-pill badge-dark">Account Created</span>
</div>
<div class="col-sm-9">
<p class="text-capitalize">${currentUser.createdAt.slice(0, 10)}</p>
</div>
`);
// set the navigation to list the username
$navDropDown.text(`${currentUser.name}`)
}
/**
* Starring favorites event handler
*
*/
$(".star").on("click", async function(evt) {
if (currentUser) {
const $tgt = $(evt.target);
// get the Story's ID
const storyId = $(evt.target).parents().eq(4).attr('id');
// if the item is already favorited
if ($tgt.hasClass("fas")) {
// remove the favorite from the user's list
await currentUser.removeFavorite(storyId);
// then change the class to be an empty star
$tgt.closest("i").toggleClass("fas far");
} else {
// the item is un-favorited
await currentUser.addFavorite(storyId);
$tgt.closest("i").toggleClass("fas far");
}
}
});
/* see if a specific story is in the user's list of favorites */
function isFavorite(story) {
let favStoryIds = new Set();
if (currentUser) {
favStoryIds = new Set(currentUser.favorites.map(obj => obj.storyId));
}
return favStoryIds.has(story.storyId);
}
});