-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hack or snooze.js
657 lines (507 loc) · 17.6 KB
/
Hack or snooze.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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
"use strict";
// So we don't have to keep re-finding things on page, find DOM elements once:
const $body = $("body");
const $storiesLoadingMsg = $("#stories-loading-msg");
const $allStoriesList = $("#all-stories-list");
const $favoritedStories = $("#favorited-stories");
const $ownStories = $("#my-stories");
const $storiesContainer = $("#stories-container")
// selector that finds all three story lists
const $storiesLists = $(".stories-list");
const $loginForm = $("#login-form");
const $signupForm = $("#signup-form");
const $submitForm = $("#submit-form");
const $navSubmitStory = $("#nav-submit-story");
const $navLogin = $("#nav-login");
const $navUserProfile = $("#nav-user-profile");
const $navLogOut = $("#nav-logout");
const $userProfile = $("#user-profile");
/** To make it easier for individual components to show just themselves, this
* is a useful function that hides pretty much everything on the page. After
* calling this, individual components can re-show just what they want.
*/
function hidePageComponents() {
const components = [
$storiesLists,
$submitForm,
$loginForm,
$signupForm,
$userProfile
];
components.forEach(c => c.hide());
}
/** Overall function to kick off the app. */
async function start() {
console.debug("start");
// "Remember logged-in user" and log in, if credentials in localStorage
await checkForRememberedUser();
await getAndShowStoriesOnStart();
// if we got a logged-in user
if (currentUser) updateUIOnUserLogin();
}
// Once the DOM is entirely loaded, begin the app
console.warn("HEY STUDENT: This program sends many debug messages to" +
" the console. If you don't see the message 'start' below this, you're not" +
" seeing those helpful debug messages. In your browser console, click on" +
" menu 'Default Levels' and add Verbose");
$(start);
"use strict";
const BASE_URL = "https://hack-or-snooze-v3.herokuapp.com";
/******************************************************************************
* Story: a single story in the system
*/
class Story {
/** Make instance of Story from data object about story:
* - {storyId, title, author, url, username, createdAt}
*/
constructor({ storyId, title, author, url, username, createdAt }) {
this.storyId = storyId;
this.title = title;
this.author = author;
this.url = url;
this.username = username;
this.createdAt = createdAt;
}
/** Parses hostname out of URL and returns it. */
getHostName() {
return new URL(this.url).host;
}
}
/******************************************************************************
* List of Story instances: used by UI to show story lists in DOM.
*/
class StoryList {
constructor(stories) {
this.stories = stories;
}
/** Generate a new StoryList. It:
*
* - calls the API
* - builds an array of Story instances
* - makes a single StoryList instance out of that
* - returns the StoryList instance.
*/
static async getStories() {
// Note presence of `static` keyword: this indicates that getStories is
// **not** an instance method. Rather, it is a method that is called on the
// class directly. Why doesn't it make sense for getStories to be an
// instance method?
// query the /stories endpoint (no auth required)
const response = await axios({
url: `${BASE_URL}/stories`,
method: "GET",
});
// turn plain old story objects from API into instances of Story class
const stories = response.data.stories.map(story => new Story(story));
// build an instance of our own class using the new array of stories
return new StoryList(stories);
}
/** Adds story data to API, makes a Story instance, adds it to story list.
* - user - the current instance of User who will post the story
* - obj of {title, author, url}
*
* Returns the new Story instance
*/
async addStory(user, { title, author, url }) {
const token = user.loginToken;
const response = await axios({
method: "POST",
url: `${BASE_URL}/stories`,
data: { token, story: { title, author, url } },
});
const story = new Story(response.data.story);
this.stories.unshift(story);
user.ownStories.unshift(story);
return story;
}
/** Delete story from API and remove from the story lists.
*
* - user: the current User instance
* - storyId: the ID of the story you want to remove
*/
async removeStory(user, storyId) {
const token = user.loginToken;
await axios({
url: `${BASE_URL}/stories/${storyId}`,
method: "DELETE",
data: { token: user.loginToken }
});
// filter out the story whose ID we are removing
this.stories = this.stories.filter(story => story.storyId !== storyId);
// do the same thing for the user's list of stories & their favorites
user.ownStories = user.ownStories.filter(s => s.storyId !== storyId);
user.favorites = user.favorites.filter(s => s.storyId !== storyId);
}
}
/******************************************************************************
* User: a user in the system (only used to represent the current user)
*/
class User {
/** Make user instance from obj of user data and a token:
* - {username, name, createdAt, favorites[], ownStories[]}
* - token
*/
constructor({
username,
name,
createdAt,
favorites = [],
ownStories = []
},
token) {
this.username = username;
this.name = name;
this.createdAt = createdAt;
// instantiate Story instances for the user's favorites and ownStories
this.favorites = favorites.map(s => new Story(s));
this.ownStories = ownStories.map(s => new Story(s));
// store the login token on the user so it's easy to find for API calls.
this.loginToken = token;
}
/** Register new user in API, make User instance & return it.
*
* - username: a new username
* - password: a new password
* - name: the user's full name
*/
static async signup(username, password, name) {
const response = await axios({
url: `${BASE_URL}/signup`,
method: "POST",
data: { user: { username, password, name } },
});
let { user } = response.data;
return new User(
{
username: user.username,
name: user.name,
createdAt: user.createdAt,
favorites: user.favorites,
ownStories: user.stories
},
response.data.token
);
}
/** Login in user with API, make User instance & return it.
* - username: an existing user's username
* - password: an existing user's password
*/
static async login(username, password) {
const response = await axios({
url: `${BASE_URL}/login`,
method: "POST",
data: { user: { username, password } },
});
let { user } = response.data;
return new User(
{
username: user.username,
name: user.name,
createdAt: user.createdAt,
favorites: user.favorites,
ownStories: user.stories
},
response.data.token
);
}
/** When we already have credentials (token & username) for a user,
* we can log them in automatically. This function does that.
*/
static async loginViaStoredCredentials(token, username) {
try {
const response = await axios({
url: `${BASE_URL}/users/${username}`,
method: "GET",
params: { token },
});
let { user } = response.data;
return new User(
{
username: user.username,
name: user.name,
createdAt: user.createdAt,
favorites: user.favorites,
ownStories: user.stories
},
token
);
} catch (err) {
console.error("loginViaStoredCredentials failed", err);
return null;
}
}
/** Add a story to the list of user favorites and update the API
* - story: a Story instance to add to favorites
*/
async addFavorite(story) {
this.favorites.push(story);
await this._addOrRemoveFavorite("add", story)
}
/** Remove a story to the list of user favorites and update the API
* - story: the Story instance to remove from favorites
*/
async removeFavorite(story) {
this.favorites = this.favorites.filter(s => s.storyId !== story.storyId);
await this._addOrRemoveFavorite("remove", story);
}
/** Update API with favorite/not-favorite.
* - newState: "add" or "remove"
* - story: Story instance to make favorite / not favorite
* */
async _addOrRemoveFavorite(newState, story) {
const method = newState === "add" ? "POST" : "DELETE";
const token = this.loginToken;
await axios({
url: `${BASE_URL}/users/${this.username}/favorites/${story.storyId}`,
method: method,
data: { token },
});
}
/** Return true/false if given Story instance is a favorite of this user. */
isFavorite(story) {
return this.favorites.some(s => (s.storyId === story.storyId));
}
}
"use strict";
// This is the global list of the stories, an instance of StoryList
let storyList;
/** Get and show stories when site first loads. */
async function getAndShowStoriesOnStart() {
storyList = await StoryList.getStories();
$storiesLoadingMsg.remove();
putStoriesOnPage();
}
/**
* A render method to render HTML for an individual Story instance
* - story: an instance of Story
* - showDeleteBtn: show delete button?
*
* Returns the markup for the story.
*/
function generateStoryMarkup(story, showDeleteBtn = false) {
// console.debug("generateStoryMarkup", story);
const hostName = story.getHostName();
// if a user is logged in, show favorite/not-favorite star
const showStar = Boolean(currentUser);
return $(`
<li id="${story.storyId}">
<div>
${showDeleteBtn ? getDeleteBtnHTML() : ""}
${showStar ? getStarHTML(story, currentUser) : ""}
<a href="${story.url}" target="a_blank" class="story-link">
${story.title}
</a>
<small class="story-hostname">(${hostName})</small>
<div class="story-author">by ${story.author}</div>
<div class="story-user">posted by ${story.username}</div>
</div>
</li>
`);
}
/** Make delete button HTML for story */
function getDeleteBtnHTML() {
return `
<span class="trash-can">
<i class="fas fa-trash-alt"></i>
</span>`;
}
/** Make favorite/not-favorite star for story */
function getStarHTML(story, user) {
const isFavorite = user.isFavorite(story);
const starType = isFavorite ? "fas" : "far";
return `
<span class="star">
<i class="${starType} fa-star"></i>
</span>`;
}
/** Gets list of stories from server, generates their HTML, and puts on page. */
function putStoriesOnPage() {
console.debug("putStoriesOnPage");
$allStoriesList.empty();
// loop through all of our stories and generate HTML for them
for (let story of storyList.stories) {
const $story = generateStoryMarkup(story);
$allStoriesList.append($story);
}
$allStoriesList.show();
}
/** Handle deleting a story. */
async function deleteStory(evt) {
console.debug("deleteStory");
const $closestLi = $(evt.target).closest("li");
const storyId = $closestLi.attr("id");
await storyList.removeStory(currentUser, storyId);
// re-generate story list
await putUserStoriesOnPage();
}
$ownStories.on("click", ".trash-can", deleteStory);
/** Handle submitting new story form. */
async function submitNewStory(evt) {
console.debug("submitNewStory");
evt.preventDefault();
// grab all info from form
const title = $("#create-title").val();
const url = $("#create-url").val();
const author = $("#create-author").val();
const username = currentUser.username
const storyData = { title, url, author, username };
const story = await storyList.addStory(currentUser, storyData);
const $story = generateStoryMarkup(story);
$allStoriesList.prepend($story);
// hide the form and reset it
$submitForm.slideUp("slow");
$submitForm.trigger("reset");
}
$submitForm.on("submit", submitNewStory);
/******************************************************************************
* Functionality for list of user's own stories
*/
function putUserStoriesOnPage() {
console.debug("putUserStoriesOnPage");
$ownStories.empty();
if (currentUser.ownStories.length === 0) {
$ownStories.append("<h5>No stories added by user yet!</h5>");
} else {
// loop through all of users stories and generate HTML for them
for (let story of currentUser.ownStories) {
let $story = generateStoryMarkup(story, true);
$ownStories.append($story);
}
}
$ownStories.show();
}
/******************************************************************************
* Functionality for favorites list and starr/un-starr a story
*/
/** Put favorites list on page. */
function putFavoritesListOnPage() {
console.debug("putFavoritesListOnPage");
$favoritedStories.empty();
if (currentUser.favorites.length === 0) {
$favoritedStories.append("<h5>No favorites added!</h5>");
} else {
// loop through all of users favorites and generate HTML for them
for (let story of currentUser.favorites) {
const $story = generateStoryMarkup(story);
$favoritedStories.append($story);
}
}
$favoritedStories.show();
}
/** Handle favorite/un-favorite a story */
async function toggleStoryFavorite(evt) {
console.debug("toggleStoryFavorite");
const $tgt = $(evt.target);
const $closestLi = $tgt.closest("li");
const storyId = $closestLi.attr("id");
const story = storyList.stories.find(s => s.storyId === storyId);
// see if the item is already favorited (checking by presence of star)
if ($tgt.hasClass("fas")) {
// currently a favorite: remove from user's fav list and change star
await currentUser.removeFavorite(story);
$tgt.closest("i").toggleClass("fas far");
} else {
// currently not a favorite: do the opposite
await currentUser.addFavorite(story);
$tgt.closest("i").toggleClass("fas far");
}
}
$storiesLists.on("click", ".star", toggleStoryFavorite);
"use strict";
// global to hold the User instance of the currently-logged-in user
let currentUser;
/******************************************************************************
* User login/signup/login
*/
/** Handle login form submission. If login ok, sets up the user instance */
async function login(evt) {
console.debug("login", evt);
evt.preventDefault();
// grab the username and password
const username = $("#login-username").val();
const password = $("#login-password").val();
// User.login retrieves user info from API and returns User instance
// which we'll make the globally-available, logged-in user.
currentUser = await User.login(username, password);
$loginForm.trigger("reset");
saveUserCredentialsInLocalStorage();
updateUIOnUserLogin();
}
$loginForm.on("submit", login);
/** Handle signup form submission. */
async function signup(evt) {
console.debug("signup", evt);
evt.preventDefault();
const name = $("#signup-name").val();
const username = $("#signup-username").val();
const password = $("#signup-password").val();
// User.signup retrieves user info from API and returns User instance
// which we'll make the globally-available, logged-in user.
currentUser = await User.signup(username, password, name);
saveUserCredentialsInLocalStorage();
updateUIOnUserLogin();
$signupForm.trigger("reset");
}
$signupForm.on("submit", signup);
/** Handle click of logout button
*
* Remove their credentials from localStorage and refresh page
*/
function logout(evt) {
console.debug("logout", evt);
localStorage.clear();
location.reload();
}
$navLogOut.on("click", logout);
/******************************************************************************
* Storing/recalling previously-logged-in-user with localStorage
*/
/** If there are user credentials in local storage, use those to log in
* that user. This is meant to be called on page load, just once.
*/
async function checkForRememberedUser() {
console.debug("checkForRememberedUser");
const token = localStorage.getItem("token");
const username = localStorage.getItem("username");
if (!token || !username) return false;
// try to log in with these credentials (will be null if login failed)
currentUser = await User.loginViaStoredCredentials(token, username);
}
/** Sync current user information to localStorage.
*
* We store the username/token in localStorage so when the page is refreshed
* (or the user revisits the site later), they will still be logged in.
*/
function saveUserCredentialsInLocalStorage() {
console.debug("saveUserCredentialsInLocalStorage");
if (currentUser) {
localStorage.setItem("token", currentUser.loginToken);
localStorage.setItem("username", currentUser.username);
}
}
/******************************************************************************
* General UI stuff about users & profiles
*/
/** When a user signs up or registers, we want to set up the UI for them:
*
* - show the stories list
* - update nav bar options for logged-in user
* - generate the user profile part of the page
*/
async function updateUIOnUserLogin() {
console.debug("updateUIOnUserLogin");
hidePageComponents();
// re-display stories (so that "favorite" stars can appear)
putStoriesOnPage();
$allStoriesList.show();
updateNavOnLogin();
generateUserProfile();
$storiesContainer.show()
}
/** Show a "user profile" part of page built from the current user's info. */
function generateUserProfile() {
console.debug("generateUserProfile");
$("#profile-name").text(currentUser.name);
$("#profile-username").text(currentUser.username);
$("#profile-account-date").text(currentUser.createdAt.slice(0, 10));
}