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
|
// OnClick attaches a listener to the elements that match the selector.
function onClick(selector, callback, noPreventDefault) {
document.querySelectorAll(selector).forEach((element) => {
element.onclick = (event) => {
if (!noPreventDefault) {
event.preventDefault();
}
callback(event);
};
});
}
function onAuxClick(selector, callback, noPreventDefault) {
document.querySelectorAll(selector).forEach((element) => {
element.onauxclick = (event) => {
if (!noPreventDefault) {
event.preventDefault();
}
callback(event);
};
});
}
// make logo element as button on mobile layout
function checkMenuToggleModeByLayout() {
const logoElement = document.querySelector(".logo");
if (!logoElement) return;
const homePageLinkElement = document.querySelector(".logo > a");
if (document.documentElement.clientWidth < 620) {
const navMenuElement = document.getElementById("header-menu");
const navMenuElementIsExpanded = navMenuElement.classList.contains("js-menu-show");
const logoToggleButtonLabel = logoElement.getAttribute("data-toggle-button-label");
logoElement.setAttribute("role", "button");
logoElement.setAttribute("tabindex", "0");
logoElement.setAttribute("aria-label", logoToggleButtonLabel);
logoElement.setAttribute("aria-expanded", navMenuElementIsExpanded?"true":"false");
homePageLinkElement.setAttribute("tabindex", "-1");
} else {
logoElement.removeAttribute("role");
logoElement.removeAttribute("tabindex");
logoElement.removeAttribute("aria-expanded");
logoElement.removeAttribute("aria-label");
homePageLinkElement.removeAttribute("tabindex");
}
}
function fixVoiceOverDetailsSummaryBug() {
document.querySelectorAll("details").forEach((details) => {
const summaryElement = details.querySelector("summary");
summaryElement.setAttribute("role", "button");
summaryElement.setAttribute("aria-expanded", details.open? "true": "false");
details.addEventListener("toggle", () => {
summaryElement.setAttribute("aria-expanded", details.open? "true": "false");
});
});
}
// Show and hide the main menu on mobile devices.
function toggleMainMenu(event) {
if (event.type === "keydown" && !(event.key === "Enter" || event.key === " ")) {
return;
}
if (event.currentTarget.getAttribute("role")) {
event.preventDefault();
}
const menu = document.querySelector(".header nav ul");
const menuToggleButton = document.querySelector(".logo");
if (menu.classList.contains("js-menu-show")) {
menu.classList.remove("js-menu-show");
menuToggleButton.setAttribute("aria-expanded", false);
} else {
menu.classList.add("js-menu-show");
menuToggleButton.setAttribute("aria-expanded", true);
}
}
// Handle click events for the main menu (<li> and <a>).
function onClickMainMenuListItem(event) {
const element = event.target;
if (element.tagName === "A") {
window.location.href = element.getAttribute("href");
} else {
window.location.href = element.querySelector("a").getAttribute("href");
}
}
// Change the button label when the page is loading.
function handleSubmitButtons() {
document.querySelectorAll("form").forEach((element) => {
element.onsubmit = () => {
const button = element.querySelector("button");
if (button) {
button.textContent = button.dataset.labelLoading;
button.disabled = true;
}
};
});
}
// Show modal dialog with the list of keyboard shortcuts.
function showKeyboardShortcuts() {
const template = document.getElementById("keyboard-shortcuts");
if (template !== null) {
ModalHandler.open(template.content, "dialog-title");
}
}
// Mark as read visible items of the current page.
function markPageAsRead() {
const items = DomHelper.getVisibleElements(".items .item");
const entryIDs = [];
items.forEach((element) => {
element.classList.add("item-status-read");
entryIDs.push(parseInt(element.dataset.id, 10));
});
if (entryIDs.length > 0) {
updateEntriesStatus(entryIDs, "read", () => {
// Make sure the Ajax request reach the server before we reload the page.
const element = document.querySelector(":is(a, button)[data-action=markPageAsRead]");
let showOnlyUnread = false;
if (element) {
showOnlyUnread = element.dataset.showOnlyUnread || false;
}
if (showOnlyUnread) {
window.location.href = window.location.href;
} else {
goToPage("next", true);
}
});
}
}
/**
* Handle entry status changes from the list view and entry view.
* Focus the next or the previous entry if it exists.
* @param {string} item Item to focus: "previous" or "next".
* @param {Element} element
* @param {boolean} setToRead
*/
function handleEntryStatus(item, element, setToRead) {
const toasting = !element;
const currentEntry = findEntry(element);
if (currentEntry) {
if (!setToRead || currentEntry.querySelector(":is(a, button)[data-toggle-status]").dataset.value == "unread") {
toggleEntryStatus(currentEntry, toasting);
}
if (isListView() && currentEntry.classList.contains('current-item')) {
switch (item) {
case "previous":
goToListItem(-1);
break;
case "next":
goToListItem(1);
break;
}
}
}
}
// Add an icon-label span element.
function appendIconLabel(element, labelTextContent) {
const span = document.createElement('span');
span.classList.add('icon-label');
span.textContent = labelTextContent;
element.appendChild(span);
}
// Change the entry status to the opposite value.
function toggleEntryStatus(element, toasting) {
const entryID = parseInt(element.dataset.id, 10);
const link = element.querySelector(":is(a, button)[data-toggle-status]");
const currentStatus = link.dataset.value;
const newStatus = currentStatus === "read" ? "unread" : "read";
link.querySelector("span").textContent = link.dataset.labelLoading;
updateEntriesStatus([entryID], newStatus, () => {
let iconElement, label;
if (currentStatus === "read") {
iconElement = document.querySelector("template#icon-read");
label = link.dataset.labelRead;
if (toasting) {
showToast(link.dataset.toastUnread, iconElement);
}
} else {
iconElement = document.querySelector("template#icon-unread");
label = link.dataset.labelUnread;
if (toasting) {
showToast(link.dataset.toastRead, iconElement);
}
}
link.replaceChildren(iconElement.content.cloneNode(true));
appendIconLabel(link, label);
link.dataset.value = newStatus;
if (element.classList.contains("item-status-" + currentStatus)) {
element.classList.remove("item-status-" + currentStatus);
element.classList.add("item-status-" + newStatus);
}
});
}
// Mark a single entry as read.
function markEntryAsRead(element) {
if (element.classList.contains("item-status-unread")) {
element.classList.remove("item-status-unread");
element.classList.add("item-status-read");
const entryID = parseInt(element.dataset.id, 10);
updateEntriesStatus([entryID], "read");
}
}
// Send the Ajax request to refresh all feeds in the background
function handleRefreshAllFeeds() {
const url = document.body.dataset.refreshAllFeedsUrl;
if (url) {
window.location.href = url;
}
}
// Send the Ajax request to change entries statuses.
function updateEntriesStatus(entryIDs, status, callback) {
const url = document.body.dataset.entriesStatusUrl;
const request = new RequestBuilder(url);
request.withBody({ entry_ids: entryIDs, status: status });
request.withCallback((resp) => {
resp.json().then(count => {
if (callback) {
callback(resp);
}
if (status === "read") {
decrementUnreadCounter(count);
} else {
incrementUnreadCounter(count);
}
});
});
request.execute();
}
// Handle save entry from list view and entry view.
function handleSaveEntry(element) {
const toasting = !element;
const currentEntry = findEntry(element);
if (currentEntry) {
saveEntry(currentEntry.querySelector(":is(a, button)[data-save-entry]"), toasting);
}
}
// Send the Ajax request to save an entry.
function saveEntry(element, toasting) {
if (!element || element.dataset.completed) {
return;
}
element.textContent = "";
appendIconLabel(element, element.dataset.labelLoading);
const request = new RequestBuilder(element.dataset.saveUrl);
request.withCallback(() => {
element.textContent = "";
appendIconLabel(element, element.dataset.labelDone);
element.dataset.completed = true;
if (toasting) {
const iconElement = document.querySelector("template#icon-save");
showToast(element.dataset.toastDone, iconElement);
}
});
request.execute();
}
// Handle bookmark from the list view and entry view.
function handleBookmark(element) {
const toasting = !element;
const currentEntry = findEntry(element);
if (currentEntry) {
toggleBookmark(currentEntry, toasting);
}
}
// Send the Ajax request and change the icon when bookmarking an entry.
function toggleBookmark(parentElement, toasting) {
const buttonElement = parentElement.querySelector(":is(a, button)[data-toggle-bookmark]");
if (!buttonElement) {
return;
}
buttonElement.textContent = "";
appendIconLabel(buttonElement, buttonElement.dataset.labelLoading);
const request = new RequestBuilder(buttonElement.dataset.bookmarkUrl);
request.withCallback(() => {
const currentStarStatus = buttonElement.dataset.value;
const newStarStatus = currentStarStatus === "star" ? "unstar" : "star";
let iconElement, label;
if (currentStarStatus === "star") {
iconElement = document.querySelector("template#icon-star");
label = buttonElement.dataset.labelStar;
if (toasting) {
showToast(buttonElement.dataset.toastUnstar, iconElement);
}
} else {
iconElement = document.querySelector("template#icon-unstar");
label = buttonElement.dataset.labelUnstar;
if (toasting) {
showToast(buttonElement.dataset.toastStar, iconElement);
}
}
buttonElement.replaceChildren(iconElement.content.cloneNode(true));
appendIconLabel(buttonElement, label);
buttonElement.dataset.value = newStarStatus;
});
request.execute();
}
// Send the Ajax request to download the original web page.
function handleFetchOriginalContent() {
if (isListView()) {
return;
}
const buttonElement = document.querySelector(":is(a, button)[data-fetch-content-entry]");
if (!buttonElement) {
return;
}
const previousElement = buttonElement.cloneNode(true);
buttonElement.textContent = "";
appendIconLabel(buttonElement, buttonElement.dataset.labelLoading);
const request = new RequestBuilder(buttonElement.dataset.fetchContentUrl);
request.withCallback((response) => {
buttonElement.textContent = '';
buttonElement.appendChild(previousElement);
response.json().then((data) => {
if (data.hasOwnProperty("content") && data.hasOwnProperty("reading_time")) {
document.querySelector(".entry-content").innerHTML = ttpolicy.createHTML(data.content);
const entryReadingtimeElement = document.querySelector(".entry-reading-time");
if (entryReadingtimeElement) {
entryReadingtimeElement.textContent = data.reading_time;
}
}
});
});
request.execute();
}
function openOriginalLink(openLinkInCurrentTab) {
const entryLink = document.querySelector(".entry h1 a");
if (entryLink !== null) {
if (openLinkInCurrentTab) {
window.location.href = entryLink.getAttribute("href");
} else {
DomHelper.openNewTab(entryLink.getAttribute("href"));
}
return;
}
const currentItemOriginalLink = document.querySelector(".current-item :is(a, button)[data-original-link]");
if (currentItemOriginalLink !== null) {
DomHelper.openNewTab(currentItemOriginalLink.getAttribute("href"));
const currentItem = document.querySelector(".current-item");
// If we are not on the list of starred items, move to the next item
if (document.location.href != document.querySelector(':is(a, button)[data-page=starred]').href) {
goToListItem(1);
}
markEntryAsRead(currentItem);
}
}
function openCommentLink(openLinkInCurrentTab) {
if (!isListView()) {
const entryLink = document.querySelector(":is(a, button)[data-comments-link]");
if (entryLink !== null) {
if (openLinkInCurrentTab) {
window.location.href = entryLink.getAttribute("href");
} else {
DomHelper.openNewTab(entryLink.getAttribute("href"));
}
return;
}
} else {
const currentItemCommentsLink = document.querySelector(".current-item :is(a, button)[data-comments-link]");
if (currentItemCommentsLink !== null) {
DomHelper.openNewTab(currentItemCommentsLink.getAttribute("href"));
}
}
}
function openSelectedItem() {
const currentItemLink = document.querySelector(".current-item .item-title a");
if (currentItemLink !== null) {
window.location.href = currentItemLink.getAttribute("href");
}
}
function unsubscribeFromFeed() {
const unsubscribeLinks = document.querySelectorAll("[data-action=remove-feed]");
if (unsubscribeLinks.length === 1) {
const unsubscribeLink = unsubscribeLinks[0];
const request = new RequestBuilder(unsubscribeLink.dataset.url);
request.withCallback(() => {
if (unsubscribeLink.dataset.redirectUrl) {
window.location.href = unsubscribeLink.dataset.redirectUrl;
} else {
window.location.reload();
}
});
request.execute();
}
}
/**
* @param {string} page Page to redirect to.
* @param {boolean} fallbackSelf Refresh actual page if the page is not found.
*/
function goToPage(page, fallbackSelf) {
const element = document.querySelector(":is(a, button)[data-page=" + page + "]");
if (element) {
document.location.href = element.href;
} else if (fallbackSelf) {
window.location.reload();
}
}
/**
*
* @param {(number|event)} offset - many items to jump for focus.
*/
function goToPrevious(offset) {
if (offset instanceof KeyboardEvent) {
offset = -1;
}
if (isListView()) {
goToListItem(offset);
} else {
goToPage("previous");
}
}
/**
*
* @param {(number|event)} offset - How many items to jump for focus.
*/
function goToNext(offset) {
if (offset instanceof KeyboardEvent) {
offset = 1;
}
if (isListView()) {
goToListItem(offset);
} else {
goToPage("next");
}
}
function goToFeedOrFeeds() {
if (isEntry()) {
goToFeed();
} else {
goToPage('feeds');
}
}
function goToFeed() {
if (isEntry()) {
const feedAnchor = document.querySelector("span.entry-website a");
if (feedAnchor !== null) {
window.location.href = feedAnchor.href;
}
} else {
const currentItemFeed = document.querySelector(".current-item :is(a, button)[data-feed-link]");
if (currentItemFeed !== null) {
window.location.href = currentItemFeed.getAttribute("href");
}
}
}
// Sentinel values for specific list navigation
const TOP = 9999;
const BOTTOM = -9999;
/**
* @param {number} offset How many items to jump for focus.
*/
function goToListItem(offset) {
const items = DomHelper.getVisibleElements(".items .item");
if (items.length === 0) {
return;
}
if (document.querySelector(".current-item") === null) {
items[0].classList.add("current-item");
items[0].focus();
return;
}
for (let i = 0; i < items.length; i++) {
if (items[i].classList.contains("current-item")) {
items[i].classList.remove("current-item");
// By default adjust selection by offset
let itemOffset = (i + offset + items.length) % items.length;
// Allow jumping to top or bottom
if (offset == TOP) {
itemOffset = 0;
} else if (offset == BOTTOM) {
itemOffset = items.length - 1;
}
const item = items[itemOffset];
item.classList.add("current-item");
DomHelper.scrollPageTo(item);
item.focus();
break;
}
}
}
function scrollToCurrentItem() {
const currentItem = document.querySelector(".current-item");
if (currentItem !== null) {
DomHelper.scrollPageTo(currentItem, true);
}
}
function decrementUnreadCounter(n) {
updateUnreadCounterValue((current) => {
return current - n;
});
}
function incrementUnreadCounter(n) {
updateUnreadCounterValue((current) => {
return current + n;
});
}
function updateUnreadCounterValue(callback) {
document.querySelectorAll("span.unread-counter").forEach((element) => {
const oldValue = parseInt(element.textContent, 10);
element.textContent = callback(oldValue);
});
if (window.location.href.endsWith('/unread')) {
const oldValue = parseInt(document.title.split('(')[1], 10);
const newValue = callback(oldValue);
document.title = document.title.replace(
/(.*?)\(\d+\)(.*?)/,
function (match, prefix, suffix, offset, string) {
return prefix + '(' + newValue + ')' + suffix;
}
);
}
}
function isEntry() {
return document.querySelector("section.entry") !== null;
}
function isListView() {
return document.querySelector(".items") !== null;
}
function findEntry(element) {
if (isListView()) {
if (element) {
return element.closest(".item");
}
return document.querySelector(".current-item");
}
return document.querySelector(".entry");
}
function handleConfirmationMessage(linkElement, callback) {
if (linkElement.tagName != 'A' && linkElement.tagName != "BUTTON") {
linkElement = linkElement.parentNode;
}
linkElement.style.display = "none";
const containerElement = linkElement.parentNode;
const questionElement = document.createElement("span");
function createLoadingElement() {
const loadingElement = document.createElement("span");
loadingElement.className = "loading";
loadingElement.appendChild(document.createTextNode(linkElement.dataset.labelLoading));
questionElement.remove();
containerElement.appendChild(loadingElement);
}
const yesElement = document.createElement("button");
yesElement.appendChild(document.createTextNode(linkElement.dataset.labelYes));
yesElement.onclick = (event) => {
event.preventDefault();
createLoadingElement();
callback(linkElement.dataset.url, linkElement.dataset.redirectUrl);
};
const noElement = document.createElement("button");
noElement.appendChild(document.createTextNode(linkElement.dataset.labelNo));
noElement.onclick = (event) => {
event.preventDefault();
const noActionUrl = linkElement.dataset.noActionUrl;
if (noActionUrl) {
createLoadingElement();
callback(noActionUrl, linkElement.dataset.redirectUrl);
} else {
linkElement.style.display = "inline";
questionElement.remove();
}
};
questionElement.className = "confirm";
questionElement.appendChild(document.createTextNode(linkElement.dataset.labelQuestion + " "));
questionElement.appendChild(yesElement);
questionElement.appendChild(document.createTextNode(", "));
questionElement.appendChild(noElement);
containerElement.appendChild(questionElement);
}
function showToast(label, iconElement) {
if (!label || !iconElement) {
return;
}
const toastMsgElement = document.getElementById("toast-msg");
if (toastMsgElement) {
toastMsgElement.replaceChildren(iconElement.content.cloneNode(true));
appendIconLabel(toastMsgElement, label);
const toastElementWrapper = document.getElementById("toast-wrapper");
if (toastElementWrapper) {
toastElementWrapper.classList.remove('toast-animate');
setTimeout(function () {
toastElementWrapper.classList.add('toast-animate');
}, 100);
}
}
}
/** Navigate to the new subscription page. */
function goToAddSubscription() {
window.location.href = document.body.dataset.addSubscriptionUrl;
}
/**
* save player position to allow to resume playback later
* @param {Element} playerElement
*/
function handlePlayerProgressionSave(playerElement) {
const currentPositionInSeconds = Math.floor(playerElement.currentTime); // we do not need a precise value
const lastKnownPositionInSeconds = parseInt(playerElement.dataset.lastPosition, 10);
const recordInterval = 10;
// we limit the number of update to only one by interval. Otherwise, we would have multiple update per seconds
if (currentPositionInSeconds >= (lastKnownPositionInSeconds + recordInterval) ||
currentPositionInSeconds <= (lastKnownPositionInSeconds - recordInterval)
) {
playerElement.dataset.lastPosition = currentPositionInSeconds.toString();
const request = new RequestBuilder(playerElement.dataset.saveUrl);
request.withBody({ progression: currentPositionInSeconds });
request.execute();
}
}
/**
* handle new share entires and already shared entries
*/
function handleShare() {
const link = document.querySelector(':is(a, button)[data-share-status]');
const title = document.querySelector("body > main > section > header > h1 > a");
if (link.dataset.shareStatus === "shared") {
checkShareAPI(title, link.href);
}
if (link.dataset.shareStatus === "share") {
const request = new RequestBuilder(link.href);
request.withCallback((r) => {
checkShareAPI(title, r.url);
});
request.withHttpMethod("GET");
request.execute();
}
}
/**
* wrapper for Web Share API
*/
function checkShareAPI(title, url) {
if (!navigator.canShare) {
console.error("Your browser doesn't support the Web Share API.");
window.location = url;
return;
}
try {
navigator.share({
title: title,
url: url
});
window.location.reload();
} catch (err) {
console.error(err);
window.location.reload();
}
}
function getCsrfToken() {
const element = document.querySelector("body[data-csrf-token]");
if (element !== null) {
return element.dataset.csrfToken;
}
return "";
}
|