Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
480 lines (394 loc) · 15.6 KB
/
Copy pathscript.js
File metadata and controls
480 lines (394 loc) · 15.6 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
// ===================================
// Utilities
// ===================================
function debounce(fn, delay = 250) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), delay);
};
}
// ===================================
// State Management
// ===================================
const state = {
jokes: [],
filteredJokes: [],
currentPage: 1,
jokesPerPage: 10,
searchTerm: '',
selectedGuest: '',
currentRandomJoke: null
};
// ===================================
// Load Jokes Data
// ===================================
async function loadJokes() {
try {
const response = await fetch('./jokes-data.json?v=2');
if (!response.ok) throw new Error('Failed to load jokes');
state.jokes = await response.json();
state.filteredJokes = [...state.jokes];
updateTotalCount();
populateGuestFilter();
renderJokes();
} catch (error) {
console.error('Error loading jokes:', error);
showError();
}
}
function updateTotalCount() {
document.getElementById('total-jokes').textContent = state.jokes.length;
}
function updateFilteredCount() {
document.getElementById('filtered-count').textContent = state.filteredJokes.length;
}
// ===================================
// Guest Filter Population
// ===================================
function populateGuestFilter() {
const guestFilter = document.getElementById("guest-filter");
const guestsSet = new Set();
// Single pass to collect unique non-empty guests
state.jokes.forEach(joke => {
if (joke.guest) {
guestsSet.add(joke.guest);
}
});
const guests = Array.from(guestsSet).sort();
const fragment = document.createDocumentFragment();
guests.forEach(guest => {
const option = document.createElement("option");
option.value = guest;
option.textContent = guest;
fragment.appendChild(option);
});
guestFilter.appendChild(fragment);
}
// ===================================
// Search and Filter Logic
// ===================================
function applyFilters() {
state.filteredJokes = state.jokes.filter(joke => {
const matchesSearch = joke.joke.toLowerCase().includes(state.searchTerm.toLowerCase()) ||
joke.guest?.toLowerCase().includes(state.searchTerm.toLowerCase()) ||
joke.episode?.toLowerCase().includes(state.searchTerm.toLowerCase());
const matchesGuest = !state.selectedGuest || joke.guest === state.selectedGuest;
return matchesSearch && matchesGuest;
});
state.currentPage = 1;
updateFilteredCount();
renderJokes();
renderPagination();
}
// ===================================
// Render Jokes
// ===================================
function renderJokes() {
const container = document.getElementById('jokes-container');
const emptyState = document.getElementById('empty-state');
// Clear container
container.innerHTML = '';
// Check if no jokes
if (state.filteredJokes.length === 0) {
container.style.display = 'none';
emptyState.style.display = 'block';
document.getElementById('pagination').style.display = 'none';
return;
}
container.style.display = 'grid';
emptyState.style.display = 'none';
document.getElementById('pagination').style.display = 'flex';
// Calculate pagination
const startIndex = (state.currentPage - 1) * state.jokesPerPage;
const endIndex = startIndex + state.jokesPerPage;
const jokesToShow = state.filteredJokes.slice(startIndex, endIndex);
// Render jokes
const fragment = document.createDocumentFragment();
jokesToShow.forEach(joke => {
const jokeCard = createJokeCard(joke);
fragment.appendChild(jokeCard);
});
container.appendChild(fragment);
renderPagination();
// Smooth scroll to top on page change
if (state.currentPage > 1) {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}
// Helper function to safely render joke text with paragraph breaks (XSS-safe)
function renderJokeText(element, jokeText) {
element.textContent = ''; // Clear existing content
// Split by double newlines for paragraphs
const paragraphs = jokeText.split('\n\n');
paragraphs.forEach((para, index) => {
// Split by single newlines within paragraphs
const lines = para.split('\n');
lines.forEach((line, lineIndex) => {
const textNode = document.createTextNode(line);
element.appendChild(textNode);
if (lineIndex < lines.length - 1) {
element.appendChild(document.createElement('br'));
}
});
if (index < paragraphs.length - 1) {
element.appendChild(document.createElement('br'));
element.appendChild(document.createElement('br'));
}
});
}
function createJokeCard(joke) {
const card = document.createElement('div');
card.className = 'joke-card';
const jokeText = document.createElement('p');
jokeText.className = 'joke-text';
// Safely render joke text with paragraph breaks
renderJokeText(jokeText, joke.joke);
const meta = document.createElement('div');
meta.className = 'joke-meta';
if (joke.episode) {
meta.appendChild(createBadge('episode', joke.episode));
}
if (joke.guest) {
meta.appendChild(createBadge('guest', joke.guest));
}
if (joke.time) {
meta.appendChild(createBadge('time', joke.time));
}
const actions = document.createElement('div');
actions.className = 'joke-actions';
if (joke.url) {
const timeParam = joke.time ? '&t=' + joke.time.replace(/m/g, 'm').replace(/s$/, '') : '';
const watchBtn = createActionButton('Watch', 'video', () => {
window.open(`https://youtube.com/watch?v=${joke.url}${timeParam}`, '_blank');
});
actions.appendChild(watchBtn);
}
const shareBtn = createActionButton('Share', 'share', () => {
shareJoke(joke);
});
actions.appendChild(shareBtn);
card.appendChild(jokeText);
card.appendChild(meta);
card.appendChild(actions);
return card;
}
function createBadge(type, text) {
const badge = document.createElement('span');
badge.className = 'joke-badge';
let icon = '';
if (type === 'episode') {
icon = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect><line x1="16" y1="2" x2="16" y2="6"></line><line x1="8" y1="2" x2="8" y2="6"></line><line x1="3" y1="10" x2="21" y2="10"></line></svg>';
} else if (type === 'guest') {
icon = '<svg xmlns="http://www.w3.org/2000/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="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>';
} else if (type === 'time') {
icon = '<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" 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>';
}
badge.innerHTML = `${icon} <span>${text}</span>`;
return badge;
}
function createActionButton(text, type, onClick) {
const button = document.createElement('button');
button.className = 'action-btn';
let icon = '';
if (type === 'video') {
icon = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg>';
} else if (type === 'share') {
icon = '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="18" cy="5" r="3"></circle><circle cx="6" cy="12" r="3"></circle><circle cx="18" cy="19" r="3"></circle><line x1="8.59" y1="13.51" x2="15.42" y2="17.49"></line><line x1="15.41" y1="6.51" x2="8.59" y2="10.49"></line></svg>';
}
button.innerHTML = `${icon} <span>${text}</span>`;
button.onclick = onClick;
return button;
}
// ===================================
// Pagination
// ===================================
function renderPagination() {
const pagination = document.getElementById('pagination');
pagination.innerHTML = '';
const totalPages = Math.ceil(state.filteredJokes.length / state.jokesPerPage);
if (totalPages <= 1) {
pagination.style.display = 'none';
return;
}
pagination.style.display = 'flex';
// Previous button
const prevBtn = document.createElement('button');
prevBtn.className = 'page-btn';
prevBtn.textContent = '← Prev';
prevBtn.disabled = state.currentPage === 1;
prevBtn.onclick = () => {
state.currentPage--;
renderJokes();
};
pagination.appendChild(prevBtn);
// Page numbers
const maxPagesToShow = 5;
let startPage = Math.max(1, state.currentPage - 2);
let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
if (endPage - startPage < maxPagesToShow - 1) {
startPage = Math.max(1, endPage - maxPagesToShow + 1);
}
for (let i = startPage; i <= endPage; i++) {
const pageBtn = document.createElement('button');
pageBtn.className = 'page-btn';
if (i === state.currentPage) pageBtn.classList.add('active');
pageBtn.textContent = i;
pageBtn.onclick = () => {
state.currentPage = i;
renderJokes();
};
pagination.appendChild(pageBtn);
}
// Next button
const nextBtn = document.createElement('button');
nextBtn.className = 'page-btn';
nextBtn.textContent = 'Next →';
nextBtn.disabled = state.currentPage === totalPages;
nextBtn.onclick = () => {
state.currentPage++;
renderJokes();
};
pagination.appendChild(nextBtn);
}
// ===================================
// Random Joke Modal
// ===================================
function showRandomJoke() {
if (state.jokes.length === 0) return;
const randomIndex = Math.floor(Math.random() * state.jokes.length);
const joke = state.jokes[randomIndex];
state.currentRandomJoke = joke;
const modal = document.getElementById('random-modal');
const jokeText = document.getElementById('random-joke-text');
const jokeMeta = document.getElementById('random-joke-meta');
// Safely render joke text with paragraph breaks
renderJokeText(jokeText, joke.joke);
jokeMeta.innerHTML = '';
if (joke.episode) {
jokeMeta.appendChild(createBadge('episode', joke.episode));
}
if (joke.guest) {
jokeMeta.appendChild(createBadge('guest', joke.guest));
}
if (joke.time) {
jokeMeta.appendChild(createBadge('time', joke.time));
}
modal.classList.add('active');
document.body.style.overflow = 'hidden';
}
function closeRandomJoke() {
const modal = document.getElementById('random-modal');
modal.classList.remove('active');
document.body.style.overflow = '';
}
// ===================================
// Share Functionality (uses NormShare from theme.js)
// ===================================
function shareJoke(joke) {
const shareText = `"${joke.joke}"\n\n- Norm Macdonald`;
const searchParam = joke.episode ? encodeURIComponent(joke.episode) : '';
const url = searchParam
? NormShare.SITE_URL + '/jokes.html?q=' + searchParam
: NormShare.SITE_URL + '/jokes.html';
NormShare.share({ title: 'Norm Macdonald Joke', text: shareText, url: url });
}
// ===================================
// Error State
// ===================================
function showError() {
const container = document.getElementById('jokes-container');
container.innerHTML = `
<div class="empty-state">
<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10"></circle>
<line x1="12" y1="8" x2="12" y2="12"></line>
<line x1="12" y1="16" x2="12.01" y2="16"></line>
</svg>
<h3>Failed to load jokes</h3>
<p>Please refresh the page to try again</p>
</div>
`;
}
// ===================================
// Event Listeners
// ===================================
function initEventListeners() {
// Search input
const searchInput = document.getElementById('search-input');
const clearBtn = document.getElementById('clear-search');
const debouncedFilter = debounce(() => applyFilters(), 250);
searchInput.addEventListener('input', (e) => {
state.searchTerm = e.target.value;
clearBtn.style.display = state.searchTerm ? 'block' : 'none';
debouncedFilter();
});
clearBtn.addEventListener('click', () => {
searchInput.value = '';
state.searchTerm = '';
clearBtn.style.display = 'none';
applyFilters();
});
// Guest filter
const guestFilter = document.getElementById('guest-filter');
guestFilter.addEventListener('change', (e) => {
state.selectedGuest = e.target.value;
applyFilters();
});
// Random joke button
const randomBtn = document.getElementById('random-joke-btn');
randomBtn.addEventListener('click', showRandomJoke);
// Modal controls
const modal = document.getElementById('random-modal');
const modalOverlay = modal.querySelector('.modal-overlay');
const modalClose = modal.querySelector('.modal-close');
const anotherJokeBtn = document.getElementById('another-joke-btn');
const shareJokeBtn = document.getElementById('share-joke-btn');
modalOverlay.addEventListener('click', closeRandomJoke);
modalClose.addEventListener('click', closeRandomJoke);
anotherJokeBtn.addEventListener('click', showRandomJoke);
shareJokeBtn.addEventListener('click', () => {
if (state.currentRandomJoke) {
shareJoke(state.currentRandomJoke);
}
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
closeRandomJoke();
}
if (e.key === 'r' && !e.ctrlKey && !e.metaKey && document.activeElement.tagName !== 'INPUT') {
e.preventDefault();
showRandomJoke();
}
});
}
// ===================================
// Initialize App
// ===================================
async function init() {
initTheme();
initNav();
initFooterQuote();
initEventListeners();
await loadJokes();
loadStateFromURL();
}
function loadStateFromURL() {
const params = new URLSearchParams(window.location.search);
if (params.has('q')) {
const q = params.get('q');
state.searchTerm = q;
const searchInput = document.getElementById('search-input');
if (searchInput) searchInput.value = q;
const clearBtn = document.getElementById('clear-search');
if (clearBtn) clearBtn.style.display = q ? 'block' : 'none';
applyFilters();
}
}
// Start the app when DOM is ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}