-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
493 lines (432 loc) · 15 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
var defaultLocation = "";
var foundCurrent = false;
function titleCase(str) {
return str
?.toLowerCase()
?.split(" ")
?.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
?.join(" ");
}
function dashCase(str) {
return str
?.trim()
?.toLowerCase()
?.split(" ")
?.map((word) => word.charAt(0).toLowerCase() + word.slice(1))
?.join("-");
}
function sanitizeTag(str) {
let result = str.split(/[,&]/);
if (str.match(/nyt:.*=/g)) {
return "";
}
return result;
}
const newEl = (tag, prop) => Object.assign(document.createElement(tag), prop);
let startY = 0;
let containerScrollTop = 0;
let isPulling = false;
// const content = document.getElementById("content");
document.body.addEventListener("touchstart", (e) => {
startY = e.touches[0].clientY; // Record the initial touch position
containerScrollTop = document.querySelector(".container").scrollTop;
isPulling = false; // Reset the pulling state
// console.log("touch start");
});
document.body.addEventListener("touchmove", (e) => {
const currentY = e.touches[0].clientY;
// console.log(document.querySelector(".container").scrollTop);
// Check if the user is pulling down, the scroll position is at the top, and they've pulled far enough
isPulling = currentY > startY + 50 && containerScrollTop <= 10; // Set the pulling state
// console.log("touch move");
});
document.body.addEventListener("touchend", () => {
if (isPulling) {
// Reload the entire page when the gesture is completed
location.reload();
}
// console.log("touch end");
});
function openPlayer(link) {
const player = document.querySelector(".player");
player.src = link;
const playerWrapper = document.querySelector(".wrapper.hidden");
playerWrapper?.classList.remove("hidden");
}
function hidePlayer() {
const playerWrapper = document.querySelector(".wrapper");
playerWrapper?.classList.add("hidden");
}
function createEventHeader(event) {
var otherClass = "";
const today = new Date();
const eventDateTime = new Date(event.details.date);
if (
(today.getFullYear() <= eventDateTime.getFullYear() &&
today.getMonth() == eventDateTime.getMonth() &&
today.getDate() <= eventDateTime.getDate()) ||
(today.getFullYear() <= eventDateTime.getFullYear() &&
today.getMonth() < eventDateTime.getMonth() &&
!foundCurrent)
) {
otherClass = "current";
foundCurrent = true;
} else if (
today.getFullYear() > eventDateTime.getFullYear() ||
today.getMonth() > eventDateTime.getMonth() ||
(today.getMonth() == eventDateTime.getMonth() &&
today.getDate() > eventDateTime.getDate())
) {
otherClass = "past";
}
const formattedDate = new Intl.DateTimeFormat("en-US", {
year: "numeric",
month: "long",
day: "numeric",
timeZone: "America/New_York",
}).format(eventDateTime);
const formattedTime = new Intl.DateTimeFormat("en-US", {
hour: "numeric",
minute: "numeric",
hour12: true,
timeZone: "America/New_York",
}).format(eventDateTime);
const audiobookshelfLink = `https://audiobooks.milot.family/library/7ccd944b-d1d4-406d-8859-5e3db53e621e/search?q=${encodeURIComponent(
event.book.title
)}`;
return `<div class="event-card${
otherClass ? " " + otherClass : ""
}" json="${encodeURIComponent(JSON.stringify(event))}">
<div class="event-card__header">
<div>
<h2 class="event-card__title">${
event?.book?.title?.length > 0
? `<a href="${audiobookshelfLink}" target="_blank" >${event.book.title}</a>`
: "TBD"
}</h2>
<div class="event-card__host">Hosted by ${event.details.host}</div>
<div class="event-card__links">
<a class="link discord" href="${
event.details.links.discord
}" target="_blank"><i class="fa-brands fa-discord"></i></a>
<a class="link storygraph" href="${
event.details.links.storygraph
}" target="_blank"><img class="storygraph-logo" src="/images/story-graph-logo.png"></a>
<a class="link audiobookshelf" href="${audiobookshelfLink}" target="_blank"><img class="audiobookshelf-logo" src="/images/audiobookshelf-logo.svg"></a>
</div>
</div>
<div class="event-card__date">
<i class="fas fa-calendar-days"></i>
<div>
<div class="event-card__accent">${formattedDate}</div>
<div class="event-card__accent">${formattedTime}</div>
</div>
</div>
</div>
`;
}
function createBookElement(event) {
const book = event?.book;
if (book?.isbn) {
const coverLink = `https://covers.openlibrary.org/b/isbn/${book?.isbn}-L.jpg`;
const el = newEl("link", {
rel: "preload",
href: coverLink,
as: "image",
});
document.head.appendChild(el);
const audiobookshelfLink = `https://audiobooks.milot.family/library/7ccd944b-d1d4-406d-8859-5e3db53e621e/search?q=${encodeURIComponent(
event.book.title
)}`;
return getOpenLibraryData(book.isbn).then((data) => {
// Construct book elements
const bookCover = newEl("img", {
className: "book-cover",
src: coverLink,
});
const bookCoverWrapper = newEl("div", {
className: "book-cover-wrapper",
});
const playButton = newEl("button", {
classList: "play-button",
});
playButton.setAttribute(
"onclick",
`openPlayer('${
event?.details?.links?.audiobookshelf ?? audiobookshelfLink
}')`
);
bookCover.onload = function () {
covers = Array.from(document.querySelectorAll(".book-cover"));
covers.forEach((cover) => {
if (cover.src == coverLink) {
cover.previousElementSibling.classList.remove("hidden");
}
});
};
const playIcon = newEl("i", { className: "fas fa-circle-play" });
playButton.appendChild(playIcon);
bookCoverWrapper.appendChild(playButton);
bookCoverWrapper.appendChild(bookCover);
const bookEl = newEl("div", {
className: "event-card__book",
});
bookEl.setAttribute("isbn", book.isbn);
const bookItems = newEl("div", { className: "event-card__book-items" });
const bookDetails = newEl("div", { className: "book-details" });
const bookTags = newEl("div", { className: "book-tags" });
const bookAuthor = newEl("a", {
className: "book-item author",
href: `${
data?.authors[0]?.author?.key
? `https://openlibrary.org${data.authors[0].author.key}`
: `https://www.google.com/search?q=${book?.author}`
}`,
target: "_blank",
innerText: titleCase(book?.author),
});
const desc = data?.description?.value;
var converter = new showdown.Converter();
var markHtml = converter.makeHtml(desc);
const bookDesc = newEl("div", {
className: "book-item",
innerHTML: markHtml,
});
data?.subjects &&
Object.entries(data?.subjects)?.forEach((val) => {
const sanitized = Array.from(sanitizeTag(val[1]));
sanitized.forEach((tag) => {
bookTags.appendChild(
newEl("div", {
className: "book-item",
innerText: `#${dashCase(tag)}`,
})
);
});
});
// Build book element structure
book?.author.length > 0 && bookDetails.appendChild(bookAuthor);
if (desc?.length > 0) bookDetails.appendChild(bookDesc);
bookDetails.appendChild(bookTags);
bookItems.appendChild(bookCoverWrapper);
bookItems.appendChild(bookDetails);
bookEl.appendChild(bookItems);
return bookEl;
});
}
return `<div class="event-card__book">
<div class="event-card__book-items">
${
book?.title?.length > 0
? `<span class="book-details">${
book?.author?.length > 0
? `<a href="https://www.google.com/search?q=${
book.author
}" target="_blank" class="book-item">${titleCase(
book.author
)}</a>`
: ``
}${
book?.description?.length > 0
? `<span class="book-item">${titleCase(
book.description
)}</span></span>`
: ``
}`
: `<span class="book-item">TBD</span>`
}
</div >
</div >
</div >`;
}
async function createEventCard(event) {
const eventHeader = createEventHeader(event);
const bookElement = await createBookElement(event);
return `${eventHeader}${bookElement?.outerHTML || bookElement}`;
}
const systemPrefersDark = () =>
window?.matchMedia?.("(prefers-color-scheme:dark)")?.matches ?? false;
// Set initial theme based on system preference
const icon = document.getElementById("toggle-icon");
if (systemPrefersDark()) {
document.body.classList.remove("light-mode");
icon.classList.add("fa-sun");
} else {
document.body.classList.add("light-mode");
icon.classList.add("fa-moon");
}
const setToggleButton = () => {
const icon = document.getElementById("toggle-icon");
if (document.body.classList.contains("light-mode")) {
icon.classList.remove("fa-sun");
icon.classList.add("fa-moon");
} else {
icon.classList.remove("fa-moon");
icon.classList.add("fa-sun");
}
};
// Function to toggle the mode
const toggleMode = () => {
document.body.classList.toggle("light-mode");
setToggleButton();
};
window
.matchMedia("(prefers-color-scheme: dark)")
.addEventListener("change", () => {
if (
(systemPrefersDark() &&
(document.getElementById("toggle-icon").classList.contains("fa-sun") ||
document.body.classList.contains("light-mode"))) ||
(!systemPrefersDark() &&
(!document
.getElementById("toggle-icon")
.classList.contains("fa-moon") ||
!document.body.classList.contains("light-mode")))
) {
toggleMode();
}
});
// Path to the dynamically created secrets file
const secretsPath = "./secrets.json";
async function getOpenLibraryData(isbn) {
const url = `https://openlibrary.org/search.json?q=isbn:${isbn}&limit=1.json`;
return fetch(url)
.then((response) => response.json())
.then((data) => {
const workId = data?.docs[0]?.key;
if (workId) {
return fetch(`https://openlibrary.org${workId}.json`)
.then((response) => response.json())
.then((data) => {
return data;
})
.catch((error) => console.error("Failed to get book data:", error));
} else {
console.error(`Failed to find open library works for isbn ${isbn}`);
}
})
.catch((error) => {
console.error("Failed to look up book information:", error);
});
}
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("./sw.js").then(() => {
navigator.serviceWorker.addEventListener("message", (event) => {
if (event.data.type === "CACHE_UPDATED") {
refreshEvents();
}
});
});
}
function eventCardToJson(eventCard) {
if (!eventCard) return null;
return JSON.parse(decodeURIComponent(eventCard.getAttribute("json")));
}
function refreshEvents() {
setToggleButton();
fetch("./data/events.json")
.then((response) => response.json())
.then(async (data) => {
const eventsList = document.getElementById("events-list");
const existingEventCards = Array.from(
document.querySelectorAll(".event-card")
);
for (const event of data.events) {
let foundCard = false;
const newCard = await createEventCard(event);
for (const oldCard of existingEventCards) {
const oldEvent = eventCardToJson(oldCard);
if (
(oldEvent?.book?.title ?? "TBD") ===
(event?.book?.title ?? "TBD") &&
((oldEvent?.details?.date == event?.details?.date &&
oldEvent?.details?.host == event?.details?.host) ||
oldEvent?.details?.links?.storygraph ==
event?.details?.links?.storygraph)
) {
foundCard = true;
// Compare JSON objects for changes
if (JSON.stringify(oldEvent) !== JSON.stringify(event)) {
const parentLi = oldCard.closest("li");
if (parentLi) {
newCard.className = oldCard.className;
parentLi.innerHTML = newCard;
}
}
break;
}
}
if (!foundCard) {
// Add new card
const li = newEl("li", { className: "raised" });
li.innerHTML = newCard;
eventsList.appendChild(li);
}
}
})
.catch((error) => console.error("Error loading JSON:", error));
}
// Load events initially
// refreshEvents();
function createEventList(events) {
const eventsList = document.getElementById("events-list");
const loadingSpinner = document.getElementById("loading-spinner");
// Show the spinner
loadingSpinner.classList.remove("hidden");
const promises = events.map(async (event, index) => {
const li = newEl("li", { className: "raised hidden" }); // Start as hidden
li.innerHTML = await createEventCard(event);
// Wait for all images in the <li> to load
const images = li.querySelectorAll("img");
const imageLoadPromises = Array.from(images).map(
(img) =>
new Promise((resolve) => {
if (img.complete) {
resolve(); // Image already loaded
} else {
img.addEventListener("load", resolve);
img.addEventListener("error", resolve);
}
})
);
// Wait for all image load promises to resolve
await Promise.all(imageLoadPromises);
return { li, index };
});
// Wait for all promises to resolve
Promise.all(promises)
.then((resolvedItems) => {
// Sort resolved items based on the original index
resolvedItems.sort((a, b) => a.index - b.index);
// Append each `li` to the event list
resolvedItems.forEach(({ li }) => {
eventsList.appendChild(li);
li.classList.remove("hidden"); // Show each <li> after its content is ready
});
// Remove the hidden class from the entire list
eventsList.classList.remove("hidden");
// Hide the spinner after everything is loaded
loadingSpinner.classList.add("hidden");
})
.catch((error) => {
console.error("Error creating event list:", error);
// Hide spinner in case of an error
loadingSpinner.classList.add("hidden");
});
}
async function setup() {
try {
const response = await fetch("./data/events.json");
const data = await response.json();
if (data?.events?.length) {
createEventList(data.events);
} else {
console.warn("No events found in the JSON data.");
document.getElementById("events-list").classList.remove("hidden");
}
} catch (error) {
console.error("Failed to initialize events list:", error);
document.getElementById("events-list").classList.remove("hidden");
}
}
setup();