-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
550 lines (439 loc) · 17 KB
/
script.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
// get the root element of the document
const app = document.getElementById('root');
// create the container element
const container = document.createElement('div');
container.setAttribute('class', 'container');
// add container to the document
app.appendChild(container);
// endpoints for the different stories
const BASEURL = 'https://hacker-news.firebaseio.com/v0/';
const TOPSTORIES = 'topstories.json';
const NEWSTORIES = 'newstories.json';
const BESTSTORIES = 'beststories.json';
const ASKSTORIES = 'askstories.json';
const SHOWSTORIES = 'showstories.json';
const JOBSTORIES = 'jobstories.json';
// top nav elements
const topNav = document.getElementById('top');
const newNav = document.getElementById('new');
const bestNav = document.getElementById('best');
const askNav = document.getElementById('ask');
const showNav = document.getElementById('show');
const jobNav = document.getElementById('jobs');
const savedNav = document.getElementById('saved');
var navItems = document.getElementsByClassName('nav-item');
for (var item of navItems){
item.addEventListener('click', changeNav);
}
// array for stories
var stories = [];
// function for getting the friendly time elapsed since a date. timestamp is the time in milliseconds
// adapted from https://stackoverflow.com/a/53138036
const getElapsedTime = (timestamp) => {
if (typeof timestamp !== 'number') return 'NaN';
// timestamp is in milliseconds
const SECOND = 1000;
const MINUTE = 1000 * 60;
const HOUR = 1000 * 60 * 60;
const DAY = 1000 * 60 * 60 * 24;
const MONTH = 1000 * 60 * 60 * 24 * 30;
const YEAR = 1000 * 60 * 60 * 24 * 30 * 12;
const elapsed = (new Date()).valueOf() - timestamp;
if(elapsed < 0) return 'Date is in the future';
if (elapsed <= MINUTE) return `${Math.round(elapsed / SECOND)} second${Math.round(elapsed / SECOND) == 1 ? "": "s"} ago`;
if (elapsed <= HOUR) return `${Math.round(elapsed / MINUTE)} minute${Math.round(elapsed / MINUTE) == 1 ? "": "s"} ago`;
if (elapsed <= DAY) return `${Math.round(elapsed / HOUR)} hour${Math.round(elapsed / HOUR) == 1 ? "": "s"} ago`;
if (elapsed <= MONTH) return `${Math.round(elapsed / DAY)} day${Math.round(elapsed / DAY) == 1 ? "": "s"} ago`;
if (elapsed <= YEAR) return `${Math.round(elapsed / MONTH)} month${Math.round(elapsed / MONTH) == 1 ? "": "s"} ago`;
return `${Math.round(elapsed / YEAR)} year${Math.round(elapsed / YEAR) == 1 ? "": "s"}`;
}
// get a nicely formatted time
const getNiceTime = (timestamp) => {
var a = new Date(timestamp * 1000);
var lang;
if(window.navigator.languages){
lang = window.navigator.languages[0];
} else{
lang = window.navigator.userLanguage || window.navigator.language;
}
var time = a.toLocaleString(lang, {weekday: 'short', year:'numeric', month:'short', day:'numeric', hour:'numeric', minute:'numeric', hour12:true});
return time;
}
function updateLastUpdate() {
var updatedTimeDiv;
if(container.querySelector('.update-time')){
updatedTimeDiv = container.querySelector('.update-time');
} else{
updatedTime = document.createElement('div');
updatedTime.classList.add('update-time');
}
var now = new Date();
updatedTime.innerText = `Last updated: ${getNiceTime(now.getTime() / 1000)}`;
container.appendChild(updatedTime);
}
// get saved stories
function getSavedStories(){
// get records out of storage
var records = localStorage.getItem('records') ? JSON.parse(localStorage.getItem('records')) : [];
// create a containing div
var recordsDiv = document.createElement('div');
recordsDiv.classList.add('records');
// create a heading div
var recordsDivHeader = document.createElement('h2');
container.appendChild(recordsDivHeader);
container.appendChild(recordsDiv);
// check if there are any saved stories
if(records.length > 0){
recordsDivHeader.innerText = `${records.length} saved stor${records.length === 1 ? 'y' : 'ies' }`;
for(record of records){
var recordCard = createdSavedStoryCard(record);
recordsDiv.appendChild(recordCard);
}
} else {
recordsDivHeader.innerText = 'No saved stories';
}
}
// create a saved story card and return it
function createdSavedStoryCard(record){
var recordCard = document.createElement('div');
recordCard.classList.add('record');
var recordHeadline = document.createElement('div');
//recordHeadline.classList.add('headline');
// check if there is an associated url
var recordTitle = document.createElement('a');
//recordTitle.classList = ('title');
recordTitle.innerText = record.story.title;
var url = record.story.url ? record.story.url : `https://news.ycombinator.com/item?id=${record.story.id}`;
recordTitle.setAttribute('href', url);
recordTitle.setAttribute('target', '_blank');
var domain = document.createElement('span');
//domain.classList.add('domain');
domain.innerText = `(${getDomain(url)})`;
// date saved
var savedDiv = document.createElement('div');
var savedDate = new Date(record.date);
savedDiv.innerText = `Saved: ${getElapsedTime(savedDate.getTime())}`;
//append nodes to headline
recordHeadline.appendChild(recordTitle);
var recordSubtext = document.createElement('div');
//recordSubtext.classList = ('subtext');
//append nodes to subtext
recordSubtext.appendChild(domain);
recordSubtext.appendChild(savedDiv);
// append nodes to record card
recordCard.appendChild(recordHeadline);
recordCard.appendChild(recordSubtext);
return recordCard;
}
// get the top HN stories
function getStories(feed){
fetch(BASEURL + feed)
.then(response => {
return response.json();
})
.then(data => {
console.log(`Num stories: ${data.length}`);
updateLastUpdate();
//limit for now
for(let i = 0; i < data.length && i < 50 ; i++){
getStoryDetails(data[i]);
}
})
.catch(err => {
console.log('error fetching ' + err);
});
}
// get top-level details about a story
function getStoryDetails(itemId){
let storyURL = `https://hacker-news.firebaseio.com/v0/item/${itemId}.json`
fetch(storyURL)
.then(respose => {
return respose.json();
})
.then(data => {
createStoryCard(data);
stories.push(data);
})
.catch(err => {
console.log(`error fetching story ${itemId} with ${err}`);
});
}
function getComment(commentId, commentCard){
let url = `https://hacker-news.firebaseio.com/v0/item/${commentId}.json`
fetch(url)
.then(response => {
return response.json();
})
.then(data => {
createComment(data, commentCard);
})
.catch(err => {
console.log(`error fetching comment ${commentId} with ${err}`);
})
}
function createComment(commentData, parentCard){
if(!commentData.deleted){
let commentDiv = document.createElement('div');
commentDiv.setAttribute('class', 'comment');
commentDiv.classList.add('is-visible');
commentDiv.innerHTML = commentData.text;
let authorDiv = document.createElement('div');
authorDiv.classList.add('subtext');
let timeElapse = document.createElement('span');
timeElapse.innerText = `${getElapsedTime(commentData.time * 1000)}`;
timeElapse.title = `${getNiceTime(commentData.time)}`;
let commentToggle = document.createElement('span');
commentToggle.setAttribute('class', 'comment-toggle');
let commentsDiv = document.createElement('div');
commentsDiv.classList.add('comments');
commentsDiv.classList.add('is-visible');
if(commentData.kids){
commentToggle.innerText = `Hide ${commentData.kids.length > 1 ? `${commentData.kids.length} comments` : `${commentData.kids.length} comment`}`;
commentToggle.classList.add('has-comments');
commentToggle.addEventListener('click', function(){
var self = this;
var storyDiv = this.parentNode.parentNode;
var children = storyDiv.querySelectorAll('.comment');
children.forEach(element => {
if(element.classList.contains('is-visible')){
self.innerText = `View ${commentData.kids.length > 1 ? `${commentData.kids.length} comments` : `${commentData.kids.length} comment`}`;
hide(element);
} else{
self.innerText = `Hide ${commentData.kids.length > 1 ? `${commentData.kids.length} comments` : `${commentData.kids.length} comment`}`;
show(element);
}
});
});
for(var item of commentData.kids){
getComment(item, commentsDiv);
}
} else{
commentToggle.innerText = 'No comments';
}
let authorSpan = document.createElement('span');
let author = document.createElement('a');
author.setAttribute('href', `https://news.ycombinator.com/user?id=${commentData.by}`);
author.setAttribute('target', '_blank');
author.textContent = `${commentData.by}`;
authorSpan.append(author);
authorDiv.append('By ', authorSpan, ' ', timeElapse, ' | ', commentToggle);
commentDiv.appendChild(authorDiv);
commentDiv.appendChild(commentsDiv);
parentCard.appendChild(commentDiv);
}
}
function clearStoryContainer(){
// empty global stories
stories.length = 0;
// remove all nodes in container
while(container.hasChildNodes()){
container.removeChild(container.lastChild);
}
}
//
function selectStory(storyid, storyDiv){
var selectedStory = stories.find(x => x.id === storyid);
var commentsCard;
//check if commentscard is already created
if(!storyDiv.querySelector('.comments')){
commentsCard = createCommentsCard(selectedStory);
storyDiv.appendChild(commentsCard);
} else{
commentsCard = storyDiv.querySelector('.comments');
toggle(commentsCard);
}
}
// creates a saved story record to add to storage
function saveStory(storyid){
// get the story from the array of stories
var selectedStory = stories.find(x => x.id === storyid);
console.log(selectedStory);
if(selectedStory){
let savedStoryRecord = {
date: new Date(),
story: selectedStory
}
pushRecord(savedStoryRecord);
}
}
// saves a record to localstorage
function pushRecord(record){
// get the records out of storage
var records = localStorage.getItem('records') ? JSON.parse(localStorage.getItem('records')) : [];
records.push(record);
localStorage.setItem('records', JSON.stringify(records));
console.log(localStorage);
}
// creates HTML markup for a story
function createStoryCard(story){
// story div
let storyCard = document.createElement('div');
storyCard.setAttribute('class', 'story');
storyCard.setAttribute('storyid', story.id);
// headline div
let headline = document.createElement('div');
headline.setAttribute('class', 'headline');
// story title and domain
let storyTitle = document.createElement('a');
storyTitle.setAttribute('class', 'title')
storyTitle.setAttribute('target', '_blank');
storyTitle.innerHTML = story.title;
let domain = document.createElement('span');
domain.setAttribute('class', 'domain');
// check if there is a associated url
if(story.hasOwnProperty('url')){
domain.textContent = `(${getDomain(story.url)})`;
storyTitle.setAttribute('href', story.url);
} else {
// set the url to the story itself
var url = `https://news.ycombinator.com/item?id=${story.id}`
domain.textContent = `(${getDomain(url)})`;
storyTitle.setAttribute('href', url);
storyCard.classList.add('self-story');
}
// subtext links
let subtext = document.createElement('div');
subtext.setAttribute('class', 'subtext');
// get the score of the story
let score = document.createElement('span');
score.setAttribute('class', 'score');
score.textContent = `${story.score} points `;
if (story.score >= 300){
score.className += ' hot';
}
// get the user who posted the story
let authorSpan = document.createElement('span');
let author = document.createElement('a');
author.setAttribute('href', `https://news.ycombinator.com/user?id=${story.by}`);
author.setAttribute('target', '_blank');
author.textContent = `${story.by}`;
authorSpan.append(author);
// set time elapsed
let timeElapse = document.createElement('span');
timeElapse.innerText = `${getElapsedTime(story.time * 1000)}`;
timeElapse.title = `${getNiceTime(story.time)}`
// link to the story
let commentToggle = document.createElement('span');
commentToggle.setAttribute('storyid', story.id);
commentToggle.setAttribute('class', 'comment-toggle');
// check if the story has any comments
if(story.descendants){
commentToggle.innerText = `View ${story.descendants > 1 ? `${story.descendants} comments` : `${story.descendants} comment`}`;
if(story.descendants >= 100) commentToggle.classList.add('hot');
commentToggle.classList.add('has-comments');
commentToggle.addEventListener('click', function(){
var self = this;
var storyDiv = this.parentNode.parentNode;
selectStory(story.id, storyDiv);
var commentDiv = storyDiv.querySelector('.comments');
if(commentDiv.classList.contains('is-visible')){
self.innerText = `Hide ${story.descendants > 1 ? `${story.descendants} comments` : `${story.descendants} comment`}`;
show(commentDiv);
} else {
self.innerText = `View ${story.descendants > 1 ? `${story.descendants} comments` : `${story.descendants} comment`}`;
hide(commentDiv);
}
});
} else{
commentToggle.innerText = 'No comments';
}
// create the save "button"
let saveButton = document.createElement('span');
saveButton.classList.add('save');
saveButton.innerText = "Save";
saveButton.addEventListener('click', function(){
var storyId = story.id;
saveStory(storyId);
});
//add the story element
container.appendChild(storyCard);
//add story elements
storyCard.appendChild(headline);
storyCard.appendChild(subtext);
//add headline elements
headline.appendChild(storyTitle);
headline.appendChild(domain);
//add links element
subtext.append(score, ' by ', authorSpan, ' ', timeElapse, ' | ', saveButton, ' | ', commentToggle);
}
function createCommentsCard(story){
let commentsCard = document.createElement('div');
commentsCard.setAttribute('class', 'comments');
commentsCard.classList.add('is-visible');
if(story.text){
let selfText = document.createElement('div');
selfText.classList.add('self-text');
selfText.innerHTML = story.text;
commentsCard.append(selfText);
}
for(var item of story.kids){
getComment(item, commentsCard);
}
return commentsCard;
}
// get the domain from a full url
function getDomain(url){
let domain = "", page = "";
//remove http://
if(url.indexOf('http://') == 0){
url = url.substr(7);
}
//remove https://
if(url.indexOf('https://') == 0){
url = url.substr(8);
}
//remove www.
if(url.indexOf('www.') == 0 ){
url = url.substr(4);
}
//get everything up to the first '/'
domain = url.split('/')[0];
return domain;
}
// change navigation between the different feeds
function changeNav(){
for(var item of navItems){
item.classList.remove('selected');
}
clearStoryContainer();
this.className += ' selected';
console.log(this.id);
switch (this.id) {
case 'top':
getStories(TOPSTORIES);
break;
case 'new':
getStories(NEWSTORIES);
break;
case 'best':
getStories(BESTSTORIES);
break;
case 'ask':
getStories(ASKSTORIES);
break;
case 'show':
getStories(SHOWSTORIES);
break;
case 'jobs':
getStories(JOBSTORIES);
break;
case 'saved':
getSavedStories();
break;
default:
getStories(TOPSTORIES);
}
}
var show = function(elem) {
elem.classList.add('is-visible');
elem.classList.remove('is-hidden');
};
var hide = function(elem) {
elem.classList.add('is-hidden');
elem.classList.remove('is-visible');
};
var toggle = function(elem) {
elem.classList.toggle('is-visible');
}
// load something on first load
window.onload = getStories(TOPSTORIES);