-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
777 lines (688 loc) · 28.3 KB
/
app.js
File metadata and controls
777 lines (688 loc) · 28.3 KB
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
// ── Theme Toggle ────────────────────────────────────────
function getPreferredTheme() {
const stored = localStorage.getItem('hn_theme');
if (stored) return stored;
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
}
function applyTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('hn_theme', theme);
// Update meta theme-color for mobile browsers
const meta = document.querySelector('meta[name="theme-color"]');
if (meta) meta.content = theme === 'dark' ? '#080808' : '#2e8b57';
}
function toggleTheme() {
const current = document.documentElement.getAttribute('data-theme') || 'light';
applyTheme(current === 'dark' ? 'light' : 'dark');
}
applyTheme(getPreferredTheme());
// ── API Configuration ───────────────────────────────────
const HN_API = 'https://hacker-news.firebaseio.com/v0';
const ALGOLIA_API = 'https://hn.algolia.com/api/v1';
const STORIES_PER_PAGE = 20;
// ── State ───────────────────────────────────────────────
let state = {
currentFeed: 'top',
storyIds: [],
loadedCount: 0,
currentStory: null,
searchTimeout: null,
isSearching: false,
lastSearchQuery: '',
scrollY: 0,
};
// ── DOM Elements ────────────────────────────────────────
const storyList = document.getElementById('storyList');
const storyDetail = document.getElementById('storyDetail');
const searchResults = document.getElementById('searchResults');
const loader = document.getElementById('loader');
const loadMore = document.getElementById('loadMore');
const searchInput = document.getElementById('searchInput');
// ── Feed Mapping ────────────────────────────────────────
const FEED_MAP = {
top: 'topstories',
new: 'newstories',
best: 'beststories',
ask: 'askstories',
show: 'showstories',
jobs: 'jobstories',
};
// ── Icons ───────────────────────────────────────────────
const icons = {
arrow: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>',
points: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon></svg>',
comment: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path></svg>',
clock: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><polyline points="12 6 12 12 16 14"></polyline></svg>',
user: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>',
link: '<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path><polyline points="15 3 21 3 21 9"></polyline><line x1="10" y1="14" x2="21" y2="3"></line></svg>',
bookmark: '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path></svg>',
bookmarkFilled: '<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21l-7-5-7 5V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2z"></path></svg>',
};
// ── Bookmarks (localStorage) ────────────────────────────
function getBookmarks() {
try {
return JSON.parse(localStorage.getItem('hn_bookmarks') || '{}');
} catch { return {}; }
}
function saveBookmarks(bookmarks) {
localStorage.setItem('hn_bookmarks', JSON.stringify(bookmarks));
}
function isBookmarked(id) {
return !!getBookmarks()[id];
}
function toggleBookmark(storyData) {
const bookmarks = getBookmarks();
if (bookmarks[storyData.id]) {
delete bookmarks[storyData.id];
} else {
bookmarks[storyData.id] = {
id: storyData.id,
title: storyData.title,
url: storyData.url || null,
by: storyData.by,
score: storyData.score,
time: storyData.time,
descendants: storyData.descendants || 0,
savedAt: Date.now(),
};
}
saveBookmarks(bookmarks);
return !!bookmarks[storyData.id];
}
// ── Cache ───────────────────────────────────────────────
const cache = {
items: new Map(), // id -> { data, ts }
feeds: new Map(), // feed -> { data, ts }
ITEM_TTL: 5 * 60000, // 5 min for stories/comments
FEED_TTL: 2 * 60000, // 2 min for feed lists
};
function getCached(map, key, ttl) {
const entry = map.get(key);
if (entry && (Date.now() - entry.ts) < ttl) return entry.data;
return null;
}
function setCache(map, key, data) {
map.set(key, { data, ts: Date.now() });
// Keep cache from growing forever — cap at 500 items
if (map.size > 500) {
const oldest = map.keys().next().value;
map.delete(oldest);
}
}
// ── API Helpers ─────────────────────────────────────────
async function fetchItem(id) {
const cached = getCached(cache.items, id, cache.ITEM_TTL);
if (cached) return cached;
const res = await fetch(`${HN_API}/item/${id}.json`);
const data = await res.json();
if (data) setCache(cache.items, id, data);
return data;
}
async function fetchFeedIds(feed) {
const cached = getCached(cache.feeds, feed, cache.FEED_TTL);
if (cached) return cached;
const res = await fetch(`${HN_API}/${FEED_MAP[feed]}.json`);
const data = await res.json();
if (data) setCache(cache.feeds, feed, data);
return data;
}
async function searchStories(query) {
const res = await fetch(`${ALGOLIA_API}/search?query=${encodeURIComponent(query)}&tags=story&hitsPerPage=30`);
return res.json();
}
// ── Time Formatting ─────────────────────────────────────
function timeAgo(timestamp) {
const seconds = Math.floor(Date.now() / 1000) - timestamp;
if (seconds < 60) return 'just now';
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
if (days < 30) return `${days}d ago`;
const months = Math.floor(days / 30);
return `${months}mo ago`;
}
function extractDomain(url) {
if (!url) return null;
try {
const hostname = new URL(url).hostname;
return hostname.replace(/^www\./, '');
} catch {
return null;
}
}
// ── Render: Story Item ──────────────────────────────────
function renderStoryItem(story, rank) {
const domain = extractDomain(story.url);
const saved = isBookmarked(story.id);
const el = document.createElement('div');
el.className = 'story-item';
el.innerHTML = `
<span class="story-rank">${rank}</span>
<div class="story-content">
<div>
<span class="story-title">${escapeHtml(story.title)}</span>
${domain ? `<span class="story-domain">(${domain})</span>` : ''}
</div>
<div class="story-meta">
<span class="story-meta-item">
${icons.points}
<span class="story-score">${story.score || 0}</span>
</span>
<span class="story-meta-item">
${icons.user}
<span>${story.by || 'unknown'}</span>
</span>
<span class="story-meta-item">
${icons.clock}
<span>${timeAgo(story.time)}</span>
</span>
<button class="story-comments-btn" onclick="event.stopPropagation(); openStory(${story.id})">
${icons.comment}
<span>${story.descendants || 0} comments</span>
</button>
</div>
</div>
<button class="bookmark-btn ${saved ? 'bookmarked' : ''}" onclick="event.stopPropagation(); handleBookmark(this, ${story.id})" title="${saved ? 'Remove bookmark' : 'Bookmark'}">
${saved ? icons.bookmarkFilled : icons.bookmark}
</button>
`;
// Store story data on the button for toggling
const btn = el.querySelector('.bookmark-btn');
btn._storyData = story;
el.addEventListener('click', () => {
if (story.url) {
window.open(story.url, '_blank', 'noopener');
} else {
openStory(story.id);
}
});
return el;
}
// ── Render: Search Result ───────────────────────────────
function renderSearchItem(hit, rank) {
const domain = extractDomain(hit.url);
const storyData = {
id: Number(hit.objectID),
title: hit.title || 'Untitled',
url: hit.url || null,
by: hit.author,
score: hit.points || 0,
time: Math.floor(new Date(hit.created_at).getTime() / 1000),
descendants: hit.num_comments || 0,
};
const saved = isBookmarked(storyData.id);
const el = document.createElement('div');
el.className = 'story-item';
el.innerHTML = `
<span class="story-rank">${rank}</span>
<div class="story-content">
<div>
<span class="story-title">${escapeHtml(hit.title || 'Untitled')}</span>
${domain ? `<span class="story-domain">(${domain})</span>` : ''}
</div>
<div class="story-meta">
<span class="story-meta-item">
${icons.points}
<span class="story-score">${hit.points || 0}</span>
</span>
<span class="story-meta-item">
${icons.user}
<span>${hit.author || 'unknown'}</span>
</span>
<span class="story-meta-item">
${icons.clock}
<span>${timeAgo(storyData.time)}</span>
</span>
<button class="story-comments-btn" onclick="event.stopPropagation(); openStory(${hit.objectID})">
${icons.comment}
<span>${hit.num_comments || 0} comments</span>
</button>
</div>
</div>
<button class="bookmark-btn ${saved ? 'bookmarked' : ''}" onclick="event.stopPropagation(); handleBookmark(this, ${storyData.id})" title="${saved ? 'Remove bookmark' : 'Bookmark'}">
${saved ? icons.bookmarkFilled : icons.bookmark}
</button>
`;
const btn = el.querySelector('.bookmark-btn');
btn._storyData = storyData;
el.addEventListener('click', () => {
if (hit.url) {
window.open(hit.url, '_blank', 'noopener');
} else {
openStory(hit.objectID);
}
});
return el;
}
// ── Render: Comment ─────────────────────────────────────
function renderComment(comment, opUser) {
if (!comment || comment.deleted || comment.dead) return '';
const isOp = comment.by === opUser;
const childrenHtml = (comment.kids || []).length > 0
? `<div class="comment-children" id="children-${comment.id}"></div>`
: '';
return `
<div class="comment" id="comment-${comment.id}">
<div class="comment-inner">
<div class="comment-meta">
<span class="comment-author ${isOp ? 'op' : ''}">${comment.by || 'unknown'}${isOp ? ' (OP)' : ''}</span>
<span class="comment-time">${timeAgo(comment.time)}</span>
${(comment.kids || []).length > 0 ? `<button class="comment-toggle" onclick="toggleComment(${comment.id})">[−]</button>` : ''}
</div>
<div class="comment-body">${comment.text || ''}</div>
</div>
${childrenHtml}
</div>
`;
}
// ── Toggle Comment ──────────────────────────────────────
function toggleComment(id) {
const comment = document.getElementById(`comment-${id}`);
const toggle = comment.querySelector('.comment-toggle');
comment.classList.toggle('comment-collapsed');
toggle.textContent = comment.classList.contains('comment-collapsed') ? '[+]' : '[−]';
}
// ── Skeleton Loader ─────────────────────────────────────
function showSkeletons(container, count = 8) {
container.innerHTML = '';
for (let i = 0; i < count; i++) {
const el = document.createElement('div');
el.className = 'story-item skeleton-item';
el.innerHTML = `
<div class="skeleton skeleton-rank"></div>
<div class="story-content">
<div class="skeleton skeleton-title"></div>
<div class="skeleton skeleton-meta"></div>
</div>
`;
container.appendChild(el);
}
}
// ── Load Story Feed ─────────────────────────────────────
async function loadFeed(feed) {
state.currentFeed = feed;
state.loadedCount = 0;
state.currentStory = null;
// Update active nav
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.feed === feed);
});
// Show skeletons
storyList.classList.remove('hidden');
storyDetail.classList.add('hidden');
searchResults.classList.add('hidden');
loadMore.classList.add('hidden');
loader.classList.add('hidden');
showSkeletons(storyList);
try {
state.storyIds = await fetchFeedIds(feed);
storyList.innerHTML = '';
await loadMoreStories();
} catch (err) {
storyList.innerHTML = `
<div class="empty-state">
<div class="empty-state-text">Failed to load stories.</div>
<button class="retry-btn" onclick="loadFeed('${feed}')">Retry</button>
</div>
`;
}
}
// ── Load More Stories ───────────────────────────────────
async function loadMoreStories() {
const start = state.loadedCount;
const end = start + STORIES_PER_PAGE;
const ids = state.storyIds.slice(start, end);
if (ids.length === 0) return;
loadMore.classList.add('hidden');
loader.classList.remove('hidden');
try {
const stories = await Promise.all(ids.map(fetchItem));
stories.forEach((story, i) => {
if (story) {
storyList.appendChild(renderStoryItem(story, start + i + 1));
}
});
state.loadedCount = end;
if (end < state.storyIds.length) {
loadMore.classList.remove('hidden');
}
} catch (err) {
console.error('Failed to load stories:', err);
}
loader.classList.add('hidden');
}
// ── Open Story (via hash) ───────────────────────────────
function openStory(id) {
state.scrollY = window.scrollY;
navigate(`#/story/${id}`);
}
// ── Open Story Detail View ──────────────────────────────
async function openStoryView(id) {
storyList.classList.add('hidden');
searchResults.classList.add('hidden');
loadMore.classList.add('hidden');
storyDetail.classList.remove('hidden');
storyDetail.innerHTML = '';
loader.classList.remove('hidden');
window.scrollTo(0, 0);
try {
const story = await fetchItem(id);
state.currentStory = story;
const domain = extractDomain(story.url);
storyDetail.innerHTML = `
<button class="back-btn" onclick="goBack()">
${icons.arrow}
<span>Back</span>
</button>
<div class="detail-card">
<h1 class="detail-title">
${story.url
? `<a href="${escapeAttr(story.url)}" target="_blank" rel="noopener">${escapeHtml(story.title)} ${icons.link}</a>`
: escapeHtml(story.title)
}
</h1>
${domain ? `<div class="detail-domain">${domain}</div>` : ''}
<div class="detail-meta">
<span class="story-meta-item">${icons.points} <span class="story-score">${story.score} points</span></span>
<span class="story-meta-item">${icons.user} ${story.by}</span>
<span class="story-meta-item">${icons.clock} ${timeAgo(story.time)}</span>
<button class="detail-bookmark-btn ${isBookmarked(story.id) ? 'bookmarked' : ''}" onclick="handleDetailBookmark(this, ${story.id})" title="${isBookmarked(story.id) ? 'Remove bookmark' : 'Bookmark'}">
${isBookmarked(story.id) ? icons.bookmarkFilled : icons.bookmark}
<span>${isBookmarked(story.id) ? 'Saved' : 'Save'}</span>
</button>
</div>
${story.text ? `<div class="detail-text">${story.text}</div>` : ''}
</div>
<div class="comments-section" id="commentsSection">
<div class="comments-header">
Comments
<span class="comments-count">${story.descendants || 0}</span>
</div>
<div id="commentsList"></div>
</div>
`;
loader.classList.add('hidden');
// Make all links in detail card open in new tab
storyDetail.querySelectorAll('.detail-text a, .comment-body a').forEach(fixExternalLink);
// Load comments
if (story.kids && story.kids.length > 0) {
await loadComments(story.kids, document.getElementById('commentsList'), story.by);
}
} catch (err) {
loader.classList.add('hidden');
storyDetail.innerHTML = `
<button class="back-btn" onclick="goBack()">
${icons.arrow}
<span>Back</span>
</button>
<div class="empty-state">
<div class="empty-state-text">Failed to load story.</div>
<button class="retry-btn" onclick="openStoryView(${id})">Retry</button>
</div>
`;
}
}
// ── Fix External Links ──────────────────────────────────
function fixExternalLink(a) {
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'noopener noreferrer');
}
// ── Load Comments Recursively ───────────────────────────
const MAX_COMMENT_DEPTH = 5;
async function loadComments(ids, container, opUser, depth = 0) {
const BATCH_SIZE = 5;
for (let i = 0; i < ids.length; i += BATCH_SIZE) {
const batch = ids.slice(i, i + BATCH_SIZE);
const comments = await Promise.all(batch.map(fetchItem));
for (const comment of comments) {
if (!comment || comment.deleted) continue;
const html = renderComment(comment, opUser);
container.insertAdjacentHTML('beforeend', html);
// Fix links in this comment to open in new tab
const commentEl = document.getElementById(`comment-${comment.id}`);
if (commentEl) {
commentEl.querySelectorAll('.comment-body a').forEach(fixExternalLink);
}
// Load children (with depth limit)
if (comment.kids && comment.kids.length > 0) {
const childContainer = document.getElementById(`children-${comment.id}`);
if (childContainer) {
if (depth >= MAX_COMMENT_DEPTH) {
// Show "load more" button instead of auto-loading
const count = comment.kids.length;
childContainer.innerHTML = `
<button class="load-replies-btn" onclick="loadDeepReplies(this, [${comment.kids.join(',')}], '${opUser}', ${depth + 1})">
Load ${count} more ${count === 1 ? 'reply' : 'replies'}
</button>
`;
} else {
await loadComments(comment.kids, childContainer, opUser, depth + 1);
}
}
}
}
}
}
async function loadDeepReplies(btn, ids, opUser, depth) {
const container = btn.parentElement;
btn.textContent = 'Loading...';
btn.disabled = true;
container.innerHTML = '';
await loadComments(ids, container, opUser, depth);
}
// ── Bookmark Handler ────────────────────────────────────
function handleBookmark(btn, id) {
const storyData = btn._storyData;
const nowSaved = toggleBookmark(storyData);
btn.classList.toggle('bookmarked', nowSaved);
btn.title = nowSaved ? 'Remove bookmark' : 'Bookmark';
btn.innerHTML = nowSaved ? icons.bookmarkFilled : icons.bookmark;
// If we're on the Saved feed and unbookmarked, remove the item
if (state.currentFeed === 'saved' && !nowSaved) {
const item = btn.closest('.story-item');
if (item) {
item.style.transition = 'opacity 200ms ease, transform 200ms ease';
item.style.opacity = '0';
item.style.transform = 'translateX(20px)';
setTimeout(() => {
item.remove();
// Check if list is now empty
const remaining = storyList.querySelectorAll('.story-item');
if (remaining.length === 0) {
storyList.innerHTML = `
<div class="empty-state">
<div class="empty-state-text">No saved stories yet. Bookmark stories to read them later.</div>
</div>
`;
}
}, 200);
}
}
}
// ── Load Saved Stories ──────────────────────────────────
function loadSavedStories() {
state.currentFeed = 'saved';
state.currentStory = null;
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.classList.toggle('active', btn.dataset.feed === 'saved');
});
storyList.innerHTML = '';
storyList.classList.remove('hidden');
storyDetail.classList.add('hidden');
searchResults.classList.add('hidden');
loadMore.classList.add('hidden');
loader.classList.add('hidden');
const bookmarks = getBookmarks();
const stories = Object.values(bookmarks).sort((a, b) => b.savedAt - a.savedAt);
if (stories.length === 0) {
storyList.innerHTML = `
<div class="empty-state">
<div class="empty-state-text">No saved stories yet. Bookmark stories to read them later.</div>
</div>
`;
return;
}
stories.forEach((story, i) => {
storyList.appendChild(renderStoryItem(story, i + 1));
});
}
// ── Bookmark in Detail View ─────────────────────────────
function handleDetailBookmark(btn, id) {
const story = state.currentStory;
if (!story) return;
btn._storyData = story;
const nowSaved = toggleBookmark(story);
btn.classList.toggle('bookmarked', nowSaved);
btn.title = nowSaved ? 'Remove bookmark' : 'Bookmark';
btn.innerHTML = `${nowSaved ? icons.bookmarkFilled : icons.bookmark} <span>${nowSaved ? 'Saved' : 'Save'}</span>`;
}
// ── Navigation / Router ─────────────────────────────────
function navigate(hash) {
if (location.hash === hash) {
// Same hash — force route anyway (e.g. clicking same nav tab)
handleRoute(hash);
} else {
location.hash = hash;
}
}
function goBack() {
if (state.isSearching && state.lastSearchQuery) {
navigate(`#/search/${encodeURIComponent(state.lastSearchQuery)}`);
} else {
navigate(`#/${state.currentFeed}`);
}
// Restore scroll after DOM updates
requestAnimationFrame(() => window.scrollTo(0, state.scrollY));
}
function navigateHome(event) {
event.preventDefault();
searchInput.value = '';
state.isSearching = false;
navigate('#/top');
}
function handleRoute(hash) {
const route = (hash || '#/top').replace(/^#\/?/, '');
const parts = route.split('/');
const page = parts[0] || 'top';
searchInput.value = '';
state.isSearching = false;
if (page === 'story' && parts[1]) {
openStoryView(Number(parts[1]));
} else if (page === 'search' && parts.slice(1).join('/')) {
const query = decodeURIComponent(parts.slice(1).join('/'));
searchInput.value = query;
performSearch(query);
} else if (page === 'saved') {
loadSavedStories();
} else if (FEED_MAP[page]) {
loadFeed(page);
} else {
loadFeed('top');
}
}
// ── Search ──────────────────────────────────────────────
searchInput.addEventListener('input', (e) => {
clearTimeout(state.searchTimeout);
const query = e.target.value.trim();
if (!query) {
state.isSearching = false;
state.lastSearchQuery = '';
searchResults.classList.add('hidden');
storyList.classList.remove('hidden');
if (state.loadedCount < state.storyIds.length) {
loadMore.classList.remove('hidden');
}
// Go back to current feed hash
history.replaceState(null, '', `#/${state.currentFeed}`);
return;
}
state.searchTimeout = setTimeout(() => {
// Update hash without triggering router (use replaceState)
history.replaceState(null, '', `#/search/${encodeURIComponent(query)}`);
performSearch(query);
}, 300);
});
searchInput.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
searchInput.value = '';
searchInput.blur();
state.isSearching = false;
state.lastSearchQuery = '';
searchResults.classList.add('hidden');
storyList.classList.remove('hidden');
if (state.loadedCount < state.storyIds.length) {
loadMore.classList.remove('hidden');
}
history.replaceState(null, '', `#/${state.currentFeed}`);
}
});
async function performSearch(query) {
state.isSearching = true;
state.lastSearchQuery = query;
storyList.classList.add('hidden');
storyDetail.classList.add('hidden');
loadMore.classList.add('hidden');
searchResults.innerHTML = '';
searchResults.classList.remove('hidden');
loader.classList.remove('hidden');
try {
const data = await searchStories(query);
loader.classList.add('hidden');
if (data.hits.length === 0) {
searchResults.innerHTML = `
<div class="empty-state">
<div class="empty-state-icon">🔍</div>
<div class="empty-state-text">No results for "${escapeHtml(query)}"</div>
</div>
`;
return;
}
const header = document.createElement('div');
header.className = 'search-header';
header.innerHTML = `Found <strong>${data.nbHits.toLocaleString()}</strong> results for "<strong>${escapeHtml(query)}</strong>"`;
searchResults.appendChild(header);
data.hits.forEach((hit, i) => {
searchResults.appendChild(renderSearchItem(hit, i + 1));
});
} catch (err) {
loader.classList.add('hidden');
searchResults.innerHTML = `
<div class="empty-state">
<div class="empty-state-text">Search failed.</div>
<button class="retry-btn" onclick="performSearch('${escapeAttr(query)}')">Retry</button>
</div>
`;
}
}
// ── Keyboard Shortcut ───────────────────────────────────
document.addEventListener('keydown', (e) => {
if (e.key === '/' && document.activeElement !== searchInput) {
e.preventDefault();
searchInput.focus();
}
});
// ── Nav Buttons ─────────────────────────────────────────
document.querySelectorAll('.nav-btn').forEach(btn => {
btn.addEventListener('click', () => {
searchInput.value = '';
state.isSearching = false;
navigate(`#/${btn.dataset.feed}`);
});
});
// ── HTML Escaping ───────────────────────────────────────
function escapeHtml(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function escapeAttr(str) {
if (!str) return '';
return str.replace(/&/g, '&').replace(/"/g, '"').replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>');
}
// ── Router Init ─────────────────────────────────────────
window.addEventListener('hashchange', () => handleRoute(location.hash));
// Initial route
handleRoute(location.hash || '#/top');