-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathui.js
475 lines (370 loc) · 12.7 KB
/
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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
$(async function() {
// cache some selectors we'll be using quite a bit
const $allStoriesList = $("#all-articles-list");
const $filteredArticles = $("#filtered-articles");
const $loginForm = $("#login-form");
const $createAccountForm = $("#create-account-form");
const $ownStories = $("#my-articles");
const $navLogin = $("#nav-login");
const $navLogOut = $("#nav-logout");
const $navPost = $("#nav-post")
const $submitForm = $("#submit-form");
const $navFav = $("#nav-fav")
const $favoriteArticles = $("#favorited-articles");
const $articleForm = $("#articles-container")
const $navProfile = $("#nav-profile")
const $userProfile = $("#user-profile")
const $navMyStories = $("#nav-myStories")
const $myStories = $("#my-articles")
// global storyList variable
let storyList = null;
// global currentUser variable
let currentUser = null;
let publishedStory = null;
await checkIfLoggedIn();
/**
* Event listener for logging in.
* If successfully we will setup the user instance
*/
$loginForm.on("submit", async function (evt) {
evt.preventDefault(); // no page-refresh on submit
// 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();
loginAndSubmitForm();
await generateStories();
click()
});
/**
* Event listener for signing up.
* If successfully we will setup a new user instance
*/
$createAccountForm.on("submit", async function(evt) {
evt.preventDefault(); // no page refresh
// grab the required fields
let name = $("#create-account-name").val();
let username = $("#create-account-username").val();
let password = $("#create-account-password").val();
// call the create method, which calls the API and then builds a new user instance
const newUser = await User.create(username, password, name);
currentUser = newUser;
syncCurrentUserToLocalStorage();
loginAndSubmitForm();
});
$navPost.on("click", function (e) {
$submitForm.slideToggle();
$favoriteArticles.hide();
$myStories.hide()
})
//Post a story
$submitForm.on("submit", async function (e) {
e.preventDefault()
const author = $("#author").val()
const title = $("#title").val()
const url = $("#url").val()
$("#url").val('')
$("#author").val('')
$("#title").val('')
let token = currentUser.loginToken;
let newStory = new StoryList({ author, title, url})
let postStory = await newStory.addStory(token, { author, title, url });
location.reload();
return postStory;
})
//append own stories to #myStories
function ownStories() {
for (let myStory of currentUser.ownStories) {
const ownStory = generateMyStoryHTML(myStory)
$myStories.append(ownStory)
}
}
function generateMyStoryHTML(story) {
let hostName = getHostName(story.url);
// render story markup
const storyMarkup = $(`
<li id="${story.storyId}">
<i class="fas fa-trash"></i>
<a class="article-link" href="${story.url}" target="a_blank">
<strong> ${story.title}</strong>
</a>
<small class="article-author">by ${story.author}</small>
<small class="article-hostname ${hostName}">(${hostName})</small>
<small class="article-username">posted by ${story.username}</small>
</li>
`);
return storyMarkup;
}
//generate favStories
async function generateFavStories() {
$('#favorited-articles li').remove()
const res = await axios.get(`https://hack-or-snooze-v3.herokuapp.com/users/${currentUser.username}/?token=${currentUser.loginToken}`)
//get story info from user favorites and append to favorites seciton
const { favorites } = res.data.user
for (let favStory of favorites) {
const indivFav = favStoryHTML(favStory)
$favoriteArticles.append(indivFav)
}
}
//function to render favorite stories
function favStoryHTML(favStory) {
let hostName = getHostName(favStory.url);
// render story markup
const favStoryMarkup = $(`
<li id="${favStory.storyId}">
<span class="star"><i class="fas fa-star"></i></span>
<a class="article-link" href="${favStory.url}" target="a_blank">
<strong> ${favStory.title}</strong>
</a>
<small class="article-author">by ${favStory.author}</small>
<small class="article-hostname ${hostName}">(${hostName})</small>
<small class="article-username">posted by ${favStory.username}</small>
</li>
`);
return favStoryMarkup;
}
//place click events in function to continue flow of code
function click() {
let username = null;
let userToken = null;
if (currentUser) {
username = currentUser.username
userToken = currentUser.loginToken
} else {
return;
}
//favorite a story, send to api
$(".star").on("click", ".far", async function (e) {
//make star solid upon clicking
e.target.className = "fas fa-star";
//save userToken,username, and storyId for API
const userToken = currentUser.loginToken
const username = currentUser.username
const storyId = e.target.parentElement.parentElement.id;
//add favorited story to user API
const post = await axios.post(`https://hack-or-snooze-v3.herokuapp.com/users/${username}/favorites/${storyId}`, { "token": userToken })
//generate favorite stories
await generateFavStories()
})
//remove favorite from user api when unfavorited
$(".star").on("click", ".fas", async function (e) {
//make star reg upon clicking
e.target.className = "far fa-star";
//get storyId to delete from API
const storyId = e.target.parentElement.parentElement.id;
//delete story from user API
const del = await axios.delete(`https://hack-or-snooze-v3.herokuapp.com/users/${username}/favorites/${storyId}`, { data: { "token": userToken } })
//update favorite article
await generateFavStories()
click()
})
//remove own article when trash can is clicked
$(".fa-trash").on("click", async function (e) {
const targetLI = e.target.parentElement;
//remove the article associated with the trashcan icon that was clicked
$('#my-articles').find(targetLI).remove()
//delete story from userfav in the API
const storyId = e.target.parentElement.id
let del = await axios.delete(`https://hack-or-snooze-v3.herokuapp.com/stories/${storyId}`, { data: { "token": userToken } })
})
}
/*Log Out Functionality*/
$navLogOut.on("click", function() {
// empty out local storage
localStorage.clear();
// refresh the page, clearing memory
location.reload();
});
/*Event Handler for Clicking Login*/
$navLogin.on("click", function() {
// Show the Login and Create Account Forms
$loginForm.slideToggle();
$createAccountForm.slideToggle();
$allStoriesList.toggle();
});
/*on click of fav articles, show article*/
$navFav.on("click", async function () {
$favoriteArticles.show();
$allStoriesList.hide();
$userProfile.hide();
$submitForm.hide();
$myStories.hide()
await generateFavStories()
click()
})
/* Event handler for Navigation to Homepage*/
$("body").on("click", "#nav-all", async function() {
await generateStories();
hideElements();
$allStoriesList.show();
$articleForm.hide();
$submitForm.hide();
$userProfile.hide();
$myStories.hide()
$favoriteArticles.hide();
location.reload()
click()
});
//Profile from navigation
$navProfile.on("click", function() {
$userProfile.show();
$submitForm.hide();
$allStoriesList.hide();
$submitForm.hide();
$favoriteArticles.hide();
$myStories.hide()
userProfileInfo()
})
//Show articles published by own user
$navMyStories.on("click", function () {
$myStories.show()
$userProfile.hide();
$submitForm.hide();
$allStoriesList.hide();
$submitForm.hide();
$favoriteArticles.hide();
click()
})
//update user profile with info
function userProfileInfo() {
const username = currentUser.username;
$('#profile-username').append(username)
const name = currentUser.name;
$('#profile-name').append(name)
const creationDay = new Date(currentUser.createdAt).toString()
const mm = creationDay.slice(4, 7)
const dd = creationDay.slice(8,10)
const yyyy = creationDay.slice(11, 15)
$('#profile-account-date').append(`${mm} ${dd}, ${yyyy}`)
}
/**
* 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) {
showNavForLoggedInUser();
await generateFavStories();
}
}
/**
* A rendering function to run to reset the forms and hide the login info
*/
function loginAndSubmitForm() {
// hide the forms for logging in and signing up
$loginForm.hide();
$createAccountForm.hide();
// reset those forms
$loginForm.trigger("reset");
$createAccountForm.trigger("reset");
// show the stories
$allStoriesList.show();
// update the navigation bar
showNavForLoggedInUser();
}
/**
* 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) {
// console.log(story)
const result = generateStoryHTML(story);
$allStoriesList.append(result);
}
}
/**
* A function to render HTML for an individual Story instance
*/
function generateStoryHTML(story) {
let star = "far"
if (currentUser) {
star = solidStars(story) ? "fas" : "far"
}
let hostName = getHostName(story.url);
// render story markup
const storyMarkup = $(`
<li id="${story.storyId}">
<span class="star"><i class="${star} fa-star"></i></span>
<a class="article-link" href="${story.url}" target="a_blank">
<strong> ${story.title}</strong>
</a>
<small class="article-author">by ${story.author}</small>
<small class="article-hostname ${hostName}">(${hostName})</small>
<small class="article-username">posted by ${story.username}</small>
</li>
`);
return storyMarkup;
}
function solidStars(story) {
let favStoryId = new Set()
for (let myStory of currentUser.favorites) {
favStoryId.add(myStory.storyId)
}
return favStoryId.has(story.storyId)
}
/* hide all elements in elementsArr */
function hideElements() {
const elementsArr = [
$submitForm,
$allStoriesList,
$filteredArticles,
$ownStories,
$loginForm,
$createAccountForm
];
elementsArr.forEach($elem => $elem.hide());
}
function showNavForLoggedInUser() {
$navLogin.hide();
$navLogOut.show();
$navPost.show();
$navFav.show();
$articleForm.show();
$navProfile.show();
$userProfile.hide();
$navMyStories.show();
ownStories()
click()
}
/* 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);
}
}
click()
});