-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
983 lines (847 loc) · 34.8 KB
/
content.js
File metadata and controls
983 lines (847 loc) · 34.8 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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
// ==UserScript==
// @name Cornucopia Enhancement Suite
// @namespace github.com/lundgren
// @version 0.0.15
// @description Various enhancements to Cornucopia.se
// @author You
// @match https://cornucopia.se/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=cornucopia.se
// @grant GM.setValue
// @grant GM.getValue
// ==/UserScript==
const DEFAULT_PREFERENCES = {
commentsReadOnPageLoad: true,
hideFirstVisit: true,
highlightParagraphs: true,
highlightAdmin: true,
favoriteMe: true,
autoHideByDefault: false,
jumpToFirstUnread: false,
rewriteTwitterLinks: false,
rewriteTwitterDomain: "nitter.net",
forceOpenInNewTab: false,
colorParagraphs: "#84dc23",
colorComments: "#dc2328",
colorFavorites: "#23dcd7",
colorNavigation: "#7b23dc",
favoriteWords: [],
favoriteAuthors: [],
hiddenAuthors: [],
};
const TWITTER_DOMAINS = ["https://twitter.com/", "https://www.twitter.com/", "https://mobile.twitter.com/", "https://x.com", "https://www.x.com", "https://mobile.x.com"];
const SETTINGS_ICN_BASE64 = `data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgaGVpZ2h0PSIyMHB4IiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCAyMCAyMCIgd2lkdGg9IjIwcHgiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6c2tldGNoPSJodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gvbnMiIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIj48dGl0bGUvPjxkZXNjLz48ZGVmcy8+PGcgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSI+PGcgZmlsbD0iIzAwMDAwMCIgaWQ9IkNvcmUiIHRyYW5zZm9ybT0idHJhbnNsYXRlK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jc1N2EyLjEyOSwyLjEyOSwwLDAsMSwuNjEzLDEuODg3TDQuNDIsMjAuNUEyLjEzMSwyLjEzMSwwLDAsMCw3LjUxMiwyMi43NWwzLjUtMS44MzhBMi4xMzUsMi4xMzUsMCwwLDEsMTIuOTkyLDIwLjkxMloiLz48L3N2Zz4=";
const ADMIN_COLOR = "#d3d3d3";
let settingsIcnSrc;
let hideCommentsIcnSrc;
let emptyStarIcnSrc;
let filledStarIcnSrc;
const StateFlags = {
Read: 1 << 0,
Hidden: 1 << 1,
Favorite: 1 << 2,
};
(async () => {
const pageId = window.location.pathname;
if (pageId === "/") {
// We only enhance the article page for now
return;
}
settingsIcnSrc = await loadImage(SETTINGS_ICN_BASE64);
hideCommentsIcnSrc = await loadImage(HIDE_COMMENTS_ICN_BASE64);
emptyStarIcnSrc = await loadImage(EMPTY_STAR_ICN_BASE64);
filledStarIcnSrc = await loadImage(FILLED_STAR_ICN_BASE64);
// Fetch info about previous visits
const pageState = await readStorage(pageId, { readBefore: false });
const preferences = { ...DEFAULT_PREFERENCES, ...(await readStorage("preferences", {})) };
preferences.colorCommentsDark = darkenColor(preferences.colorComments, 0.2);
preferences.colorFavoritesDark = darkenColor(preferences.colorFavorites, 0.2);
const articleReadBefore = pageState.readBefore;
// Setup a state object to simplify working with flags
const state = {
isUnread: (id) => pageState[id] === undefined,
isHidden: (id) => pageState[id] & StateFlags.Hidden,
isFavorite: (id) => pageState[id] & StateFlags.Favorite,
setAsRead: (id) => (pageState[id] |= StateFlags.Read),
setHidden: (id, hidden) => {
if (hidden) {
pageState[id] |= StateFlags.Hidden;
} else {
pageState[id] &= ~StateFlags.Hidden;
}
},
setFavorite: (id, favorite) => {
if (favorite) {
pageState[id] |= StateFlags.Favorite;
} else {
pageState[id] &= ~StateFlags.Favorite;
}
},
isHideReadThreads: () => pageState.hideReadThreads,
setHideReadThreads: (hide) => (pageState.hideReadThreads = hide),
};
// Try to find the logged in user so we can automatically favorite their comments
const loggedInUser = findLoggedInUser();
// Setup a canvas to draw the minimap on
const $canvas = document.createElement("canvas");
document.body.appendChild($canvas);
// Get a list of all comments and paragraphs
const comments = getComments();
const paragraphs = getParagraphs();
const allItems = [...paragraphs, ...comments];
const redrawHighlightsAndMinimap = () => {
drawHighlights(allItems);
drawMinimap($canvas, allItems);
};
// Add state to all comments and make them clickable
const positionTitle = ["1st", "2nd", "3rd", "Nylander"];
let position = -1;
const articleTs = getArticleTimestamp();
let firstCommentTs;
for (const comment of comments) {
comment.unread = state.isUnread(comment.id);
comment.hasFavoriteWords = containsAny(comment.$el, preferences.favoriteWords);
if (preferences.commentsReadOnPageLoad) {
state.setAsRead(comment.id);
}
// Set up time popup and add position to the first 4 comments
const commentsDate = new Date(comment.$dateEl.getAttribute("datetime"));
comment.$dateEl.title = commentsDate.toLocaleString();
if (!comment.parent) {
if (!firstCommentTs) {
firstCommentTs = commentsDate.getTime();
const after = parseInt((commentsDate - articleTs) / 1000);
if (after < 180) {
position++;
const date = comment.$dateEl.innerText.substr(0, 16);
const seconds = commentsDate.getSeconds() < 10 ? `0${commentsDate.getSeconds()}` : commentsDate.getSeconds();
comment.$dateEl.innerText = `${date}:${seconds} (1st - ${after}s after posting)`;
}
} else {
const after = parseInt((commentsDate.getTime() - firstCommentTs) / 1000);
if (position > -1 && (position < 4 || after < 200)) {
position++;
const date = comment.$dateEl.innerText.substr(0, 16);
const seconds = commentsDate.getSeconds() < 10 ? `0${commentsDate.getSeconds()}` : commentsDate.getSeconds();
if (position < 4) {
comment.$dateEl.innerText = `${date}:${seconds} (${positionTitle[position]} - ${after}s after 1st)`;
} else {
comment.$dateEl.innerText = `${date}:${seconds} (${after}s after 1st)`;
}
}
}
}
const shouldAutoHideAuthor = preferences.hiddenAuthors.includes(comment.author);
if (comment.unread && shouldAutoHideAuthor) {
state.setHidden(comment.id, true);
comment.hidden = true;
}
if (comment.unread && comment.author === loggedInUser && preferences.favoriteMe) {
state.setFavorite(comment.id, true);
}
if (comment.unread && comment.hasFavoriteWords) {
highlightWords(comment.$el, preferences.favoriteWords, preferences.colorFavorites);
}
comment.isHidden = () => state.isHidden(comment.id);
comment.isFavorite = () => state.isFavorite(comment.id);
comment.isParentFavorite = () => {
let node = comment;
while (node) {
if (node.isFavorite()) {
return true;
}
node = node.parent;
}
return false;
};
// Return how the comment should be highlighted, undefined if not at all
comment.highlightColor = () => {
let color;
if (comment.fromAdmin && preferences.highlightAdmin) {
color = ADMIN_COLOR;
}
if (comment.unread) {
if (articleReadBefore || !preferences.hideFirstVisit) {
color = preferences.colorComments;
if (!preferences.commentsReadOnPageLoad && comment.viewed) {
color = preferences.colorCommentsDark;
}
}
const isFavoriteAuthor = preferences.favoriteAuthors.includes(comment.author);
if (isFavoriteAuthor || comment.isParentFavorite() || comment.hasFavoriteWords) {
color = preferences.colorFavorites;
if (!preferences.commentsReadOnPageLoad && comment.viewed) {
color = preferences.colorFavoritesDark;
}
}
}
return color;
};
comment.setHidden = (hidden) => {
state.setHidden(comment.id, hidden);
writeStorage(pageId, pageState);
};
comment.setFavorite = (favorite) => {
state.setFavorite(comment.id, favorite);
writeStorage(pageId, pageState);
redrawHighlightsAndMinimap();
};
}
// We cant count unread children until all comments have been processed
let totalUnread = 0;
for (const comment of comments) {
totalUnread += comment.unread ? 1 : 0;
comment.count = getCommentCount(comment);
makeCommentClickable(comment);
}
// Add unread count to the comment count header
updateCommentCount(totalUnread);
// Add state to all paragraphs
for (const paragraph of paragraphs) {
paragraph.unread = state.isUnread(paragraph.id);
state.setAsRead(paragraph.id);
paragraph.highlightColor = () => {
const hightlight =
preferences.highlightParagraphs && paragraph.unread && (articleReadBefore || !preferences.hideFirstVisit);
return hightlight ? preferences.colorParagraphs : undefined;
};
}
// Rewrite twitter links to use nitter instead
if (preferences.rewriteTwitterLinks) {
rewriteTwitterLinks(preferences.rewriteTwitterDomain || "nitter.net");
}
// Rewrite all links to open in a new tab
if (preferences.forceOpenInNewTab) {
rewriteLinksToOpenInNewTab(allItems);
}
// Highlight all new content and comments
drawHighlights(allItems);
// Setup comments options
const toggleReadThreads = (hide) => {
state.setHideReadThreads(hide);
writeStorage(pageId, pageState);
for (const comment of comments) {
const topCommentWithoutUnread = !comment.parent && comment.count.unread == 0;
if (topCommentWithoutUnread) {
if (hide) {
comment.$el.temporarilyHideIt();
} else {
comment.$el.temporarilyShowIt();
}
}
}
};
const hideReadComments = state.isHideReadThreads() || (preferences.autoHideByDefault && !articleReadBefore);
if (hideReadComments) {
toggleReadThreads(true);
}
addOptionsControls(state.isHideReadThreads(), toggleReadThreads);
// Add hotkeys to navigate between paragraphs and comments
const jumpToFirstUnread = preferences.jumpToFirstUnread && articleReadBefore;
enableHotkeyNavigationFor(allItems, preferences.colorNavigation, jumpToFirstUnread);
// Make sure the minimap is redrawn when the window is resized
const redrawMinimap = () => drawMinimap($canvas, allItems);
new ResizeObserver(redrawMinimap).observe(document.body);
addEventListener("resize", redrawMinimap);
// Save the info about this visit
pageState.lastReadTs = Date.now();
pageState.readBefore = true;
writeStorage(pageId, pageState);
// Setup listener to figure out when the user reads specific comments
if (!preferences.commentsReadOnPageLoad) {
let viewedCommentsChanged = false;
const commentsMap = new WeakMap();
const observer = new IntersectionObserver(
(entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const comment = commentsMap.get(entry.target);
if (comment && !comment.viewed) {
comment.viewed = true;
viewedCommentsChanged = true;
state.setAsRead(comment.id);
redrawHighlightsAndMinimap();
}
}
});
},
{
threshold: 1,
}
);
for (let comment of comments) {
const endOfComment = document.createElement("div");
comment.$el.appendChild(endOfComment);
commentsMap.set(endOfComment, comment);
observer.observe(endOfComment);
}
// Save when the user leaves the page or moves to another tab
window.addEventListener("beforeunload", () => {
if (viewedCommentsChanged) {
writeStorage(pageId, pageState);
viewedCommentsChanged = false;
}
});
document.addEventListener("visibilitychange", () => {
if (document.hidden && viewedCommentsChanged) {
writeStorage(pageId, pageState);
viewedCommentsChanged = false;
}
});
}
})();
async function readStorage(key, defaultVal) {
// Firefox
if (typeof browser !== "undefined") {
return (await browser.storage.local.get(key))[key] || defaultVal;
}
// Chromium based browsers
if (typeof chrome !== "undefined") {
return (await chrome.storage.local.get(key))[key] || defaultVal;
}
// Userscripts
if (typeof GM !== "undefined") {
return await GM.getValue(key, defaultVal);
}
throw new Error("No storage available");
}
async function writeStorage(key, value) {
// Firefox
if (typeof browser !== "undefined") {
return await browser.storage.local.set({ [key]: value });
}
// Chromium based browsers
if (typeof chrome !== "undefined") {
return await chrome.storage.local.set({ [key]: value });
}
// Userscripts
if (typeof GM !== "undefined") {
return await GM.setValue(key, value);
}
throw new Error("No storage available");
}
function findLoggedInUser() {
const $wpAdmin = document.getElementById("wp-admin-bar-my-account");
if ($wpAdmin) {
return ($wpAdmin.getElementsByClassName("display-name")[0]?.innerText || "").trim().toLowerCase();
}
return null;
}
function getDepth(element) {
for (const className of element.classList) {
if (className.startsWith("depth-")) {
return parseInt(className.split("-")[1], 10);
}
}
return 0;
}
function getCommentsChildren($el) {
const $children = $el.getElementsByClassName(`comment depth-${getDepth($el) + 1}`);
const children = [];
for (let $child of $children) {
children.push({
$el: $child,
children: getCommentsChildren($child),
});
}
return children;
}
// getComments will return a list of all comments on the page
function getComments() {
const comments = [];
const traverseAndSave = ($el, parent) => {
const id = $el.id;
const author = ($el.getElementsByClassName("author")[0]?.textContent || "").trim().toLowerCase();
const $commentText = $el.getElementsByClassName("comment-text")[0];
const $dateText = $el.getElementsByClassName("date")[0];
$commentText.style.transition = "color 500ms";
const comment = {
id: id,
$el: $commentText,
$dateEl: $dateText,
type: "comment",
author: author,
fromAdmin: $el.classList.contains("bypostauthor") || $el.classList.contains("comment-author-admin"),
children: [],
parent: parent,
};
comments.push(comment);
const $children = $el.getElementsByClassName(`comment depth-${getDepth($el) + 1}`);
for (let $child of $children) {
comment.children.push(traverseAndSave($child, comment));
}
return comment;
};
const $commentsContainer = document.getElementById("comments");
if ($commentsContainer) {
const $children = $commentsContainer.getElementsByClassName(`comment depth-1`);
for (let $child of $children) {
traverseAndSave($child, undefined);
}
}
return comments;
}
// getParagraphs will return a list of all paragraphs
function getParagraphs() {
const paragraphs = [];
const $post = document.getElementById("penci-post-entry-inner");
for (let $paragraph of $post.children) {
if ($paragraph.nodeName === "P" || $paragraph.nodeName === "BLOCKQUOTE") {
if ($paragraph.nodeName === "BLOCKQUOTE") {
// Blockquotes uses the left border to indicate quotes, so we wrap it in a div we can style
const $wrapper = document.createElement("div");
$paragraph.replaceWith($wrapper);
$wrapper.append($paragraph);
$paragraph = $wrapper;
}
paragraphs.push({
id: hashCode($paragraph.innerText),
type: "paragraph",
$el: $paragraph,
});
}
}
// Add next post link as a paragraph
const $nextPost = document.getElementsByClassName("post-pagination")[0];
if ($nextPost) {
paragraphs.push({
id: hashCode($nextPost.innerText),
type: "nextpost",
$el: $nextPost,
});
}
return paragraphs;
}
function drawHighlights(items) {
for (let item of items) {
const color = item.highlightColor();
if (color) {
item.$el.style.borderLeft = `3px solid ${color}`;
item.$el.style.paddingLeft = "6px";
} else if (item.$el.style.borderLeft != "") {
// Remove possible highlights
item.$el.style.borderLeft = "";
item.$el.style.paddingLeft = "";
}
}
}
function containsAny($el, words = []) {
const $commentText = $el.getElementsByClassName("comment-content")[0];
if ($commentText) {
const lowerText = $commentText.textContent.toLowerCase();
return words.some((word) => lowerText.includes(word));
}
return false;
}
function highlightWords($el, words = [], color) {
const $commentText = $el.getElementsByClassName("comment-content")[0];
function walkAndHighlight(node) {
if (node) {
let children = Array.from(node.childNodes);
for(let i = 0; i < children.length; i++) {
walkAndHighlight(children[i]);
}
// Node.TEXT_NODE
if (node.nodeType === 3) {
let newText = node.textContent;
for (let word of words) {
const regex = new RegExp(`(${word})`, "ig");
const replacement = `<span style="border-bottom: 2px solid ${color};">$1</span>`;
newText = newText.replace(regex, replacement);
}
const temp = document.createElement("div");
temp.innerHTML = newText;
const parent = node.parentNode;
if (parent) {
while (temp.firstChild) {
parent.insertBefore(temp.firstChild, node);
}
parent.removeChild(node);
}
}
}
}
walkAndHighlight($commentText);
}
function updateCommentCount(count) {
const $comments = document.getElementById("comments");
if ($comments) {
const $commentCount = $comments.getElementsByClassName("post-box-title")[0];
if ($commentCount) {
$commentCount.textContent = `${$commentCount.textContent} (${count} olästa)`;
}
}
}
function addOptionsControls(isChecked, onHideThreadsChanged) {
const $comments = document.getElementById("comments");
var $commentList = $comments.getElementsByClassName("comments")[0];
if ($commentList) {
// Settings button to open the options page
const $settingsBtn = imageButton(settingsIcnSrc, "Settings");
$settingsBtn.href = chrome.runtime.getURL("options.html");
$settingsBtn.addEventListener("click", () => {
chrome.runtime.sendMessage({ action: "openOptionsPage" });
});
const $spacing = document.createElement("span");
$spacing.style.padding = "0 10px";
$spacing.appendChild(document.createTextNode(" | "));
// Checkbox to hide read threads
const $checkbox = document.createElement("input");
$checkbox.type = "checkbox";
$checkbox.checked = isChecked;
$checkbox.id = "hide-read-threads";
$checkbox.addEventListener("change", (e) => onHideThreadsChanged(e.target.checked));
const $label = document.createElement("label");
$label.htmlFor = "hide-read-threads";
$label.title =
"This will hide all top level comments that have no unread replies to minimize distractions.\nIf a thread gets a reply in your next visit it will show up again.";
$label.appendChild(document.createTextNode(" Hide threads without unread replies"));
// Add the options to the DOM
const $container = document.createElement("div");
$container.style.padding = "10px";
$container.appendChild($settingsBtn);
$container.appendChild($spacing);
$container.appendChild($checkbox);
$container.appendChild($label);
$comments.insertBefore($container, $commentList);
}
}
// enableHotkeyNavigationFor will
// - allow the user to navigate new comments and paragraphs using the J and K keys
// - allow the user to navigate to the first new comment or paragraph using the I key
// - allow the user to minimize navigated comments by pressing the M key
function enableHotkeyNavigationFor(allItems, navigationColor, jumpToFirstUnread) {
const entries = allItems.filter((item) => item.unread);
let navigatedEntry;
let styleBefore;
addEventListener("scroll", (e) => {
if (navigatedEntry) {
navigatedEntry.$el.style.borderLeft = styleBefore;
navigatedEntry = null;
}
});
// Scroll to center of element or top of element if it's too tall
// Also highlight the element for a short time
const scrollTo = (entry) => {
const rect = entry.$el.getBoundingClientRect();
if (rect.height > window.innerHeight) {
window.scrollTo(0, rect.top + window.scrollY - 50);
} else {
entry.$el.scrollIntoView({ block: "center" });
}
setTimeout(() => {
navigatedEntry = entry;
styleBefore = entry.$el.style.borderLeft;
entry.$el.style.borderLeft = `3px solid ${navigationColor}`;
}, 50);
};
const jumpToFirst = () => {
for (let i = 0; i < entries.length; i++) {
const isMinimized = entries[i].$el.getBoundingClientRect().height === 0;
if (!isMinimized) {
scrollTo(entries[i]);
return;
}
}
// If no unread, jump to comment section
const $comments = document.getElementById("comments");
if ($comments) {
let position = $comments.getBoundingClientRect();
window.scrollTo(0, position.top + window.scrollY - 50);
}
};
addEventListener("keydown", (e) => {
const focused = document.activeElement && document.activeElement.nodeName;
if (focused === "INPUT" || focused === "TEXTAREA") {
return;
}
const center = window.innerHeight / 2;
if (e.code === "KeyJ") {
for (let i = 0; i < entries.length; i++) {
const rect = entries[i].$el.getBoundingClientRect();
const isMinimized = rect.height === 0;
const isBelowCenter = rect.top + rect.height / 2 - 50 > center;
const isAlreadyNavigated = entries[i] === navigatedEntry;
if (isBelowCenter && !isMinimized && !isAlreadyNavigated) {
scrollTo(entries[i]);
return;
}
}
} else if (e.code === "KeyK") {
for (let i = entries.length - 1; i >= 0; i--) {
const rect = entries[i].$el.getBoundingClientRect();
const isMinimized = rect.height === 0;
const isAboveCenter = rect.top + rect.height / 2 + 50 < center;
const isAlreadyNavigated = entries[i] === navigatedEntry;
if (isAboveCenter && !isMinimized && !isAlreadyNavigated) {
scrollTo(entries[i]);
return;
}
}
} else if (e.code === "KeyI") {
jumpToFirst();
} else if (e.code === "KeyM") {
if (navigatedEntry && navigatedEntry.type === "comment") {
navigatedEntry.$el.hideIt();
}
} else if (e.code === "KeyN") {
if (navigatedEntry && navigatedEntry.type === "comment") {
navigatedEntry.$el.favoriteIt();
}
}
});
if (jumpToFirstUnread) {
if ("scrollRestoration" in history) {
history.scrollRestoration = "manual";
}
jumpToFirst();
}
}
// drawMinimap will
// - draw a minimap on the right side of the screen
function drawMinimap($canvas, entries) {
const scrollOffset = window.innerWidth - document.documentElement.clientWidth;
$canvas.style = `position:fixed; left: ${
document.body.clientWidth - 5
}px; top: ${scrollOffset}px; width: 5px; height: ${window.innerHeight - scrollOffset * 2}px; z-index: 9999;`;
$canvas.width = 5;
$canvas.height = window.innerHeight;
const q = window.innerHeight / document.documentElement.scrollHeight;
var ctx = $canvas.getContext("2d");
ctx.clearRect(0, 0, $canvas.width, $canvas.height);
for (const item of entries) {
const color = item.highlightColor();
if (color) {
const rect = item.$el.getBoundingClientRect();
let elementTop = item.$el.offsetTop;
ctx.fillStyle = color;
ctx.fillRect(0, elementTop * q, 5, rect.height * q);
}
}
}
function makeCommentClickable(comment) {
const $container = comment.$el.parentElement.parentElement;
const $hiddenContainer = createHiddenThreadContainer($container, comment);
$container.parentNode.insertBefore($hiddenContainer, $container);
const hideComments = (e) => {
e?.preventDefault();
$container.style.display = "none";
$hiddenContainer.style.display = "";
comment.setHidden(true);
};
const temporarilyHideComments = (e) => {
e?.preventDefault();
$container.style.display = "none";
$hiddenContainer.style.display = "";
};
const showComments = (e) => {
e?.preventDefault();
$container.style.display = "";
$hiddenContainer.style.display = "none";
comment.setHidden(false);
};
const temporarilyShowComments = (e) => {
e?.preventDefault();
$container.style.display = "";
$hiddenContainer.style.display = "none";
comment.setHidden(false);
};
if (comment.isHidden()) {
$container.style.display = "none";
} else {
$hiddenContainer.style.display = "none";
}
// Find author element and hide comments when it's clicked
const $author = comment.$el.getElementsByClassName("author")[0];
$author.title = "Hide comments";
$author.style.cursor = "pointer";
$author.prepend(imageButton(hideCommentsIcnSrc, "Hide comments"));
$author.addEventListener("click", hideComments);
comment.$el.hideIt = hideComments;
comment.$el.temporarilyHideIt = temporarilyHideComments;
// Show comments again when hidden container is clicked
$hiddenContainer.addEventListener("click", showComments);
comment.$el.showIt = showComments;
comment.$el.temporarilyShowIt = temporarilyShowComments;
// Add favorite button
const $favoriteBtn = imageButton(comment.isFavorite() ? filledStarIcnSrc : emptyStarIcnSrc, "Favorite comments");
$author.prepend($favoriteBtn);
const toggleFavorite = (e) => {
e?.stopImmediatePropagation();
if (comment.isFavorite()) {
$favoriteBtn.src = emptyStarIcnSrc;
comment.setFavorite(false);
} else {
$favoriteBtn.src = filledStarIcnSrc;
comment.setFavorite(true);
}
};
$favoriteBtn.addEventListener("click", toggleFavorite);
comment.$el.favoriteIt = toggleFavorite;
first = false;
}
function createHiddenThreadContainer($container, comment) {
const $hiddenContainer = document.createElement("div");
const $text = document.createElement("p");
$hiddenContainer.appendChild($text);
const $authorContent = comment.$el.getElementsByClassName("author")[0];
const $commentContent = comment.$el.getElementsByClassName("comment-content")[0];
const summary = getSummary($authorContent, $commentContent);
if (comment.count.unread > 0) {
$text.innerText = `[${comment.count.total} comments, ${comment.count.unread} unread] - ${summary} (${comment.count.unread} unread)`;
} else {
$text.innerText = `[${comment.count.total} comments] - ${summary}`;
}
$hiddenContainer.className = $container.className;
$hiddenContainer.title = "Show comments";
$hiddenContainer.style.cursor = "pointer";
$hiddenContainer.style.height = "30px";
$hiddenContainer.style.borderTop = "1px solid #dedede";
if ($container.className.includes("depth-1")) {
$hiddenContainer.style.backgroundColor = "#fff9ec";
}
return $hiddenContainer;
}
function getSummary($author, $comment) {
const author = $author.textContent || "";
const comment = $comment.textContent || "";
return `${author}: ${comment}`.replace(/(\r\n|\n|\r)/gm, " ").substring(0, 75) + "...";
}
function getCommentCount(comment) {
let total = 1;
let unread = comment.unread ? 1 : 0;
for (const child of comment.children) {
const count = getCommentCount(child);
total += count.total;
unread += count.unread;
}
return { total, unread };
}
function imageButton(imgSrc, title) {
// <img style="width: 16px; height: 16px; margin-right: 8px;" />
const $imgBtn = document.createElement("img");
$imgBtn.style.width = "16px";
$imgBtn.style.height = "16px";
$imgBtn.style.marginRight = "8px";
$imgBtn.style.cursor = "pointer";
$imgBtn.title = title;
$imgBtn.src = imgSrc;
return $imgBtn;
}
async function loadImage(src) {
const image = new Image();
image.src = src;
await image.decode();
return image.src;
}
function getArticleTimestamp() {
const $timestamp = document.querySelector("time.entry-date.published");
const timestamp = $timestamp.getAttribute("datetime");
return new Date(timestamp).getTime();
}
function rewriteTwitterLinks(replaceDomain) {
const $twitterLinks = document.querySelectorAll("a[href*='twitter.com'], a[href*='x.com']");
const fullReplaceDomain = `https://${replaceDomain}/`;
for (const $link of $twitterLinks) {
let url = $link.href;
for (const domain of TWITTER_DOMAINS) {
if (url.indexOf(domain) !== -1) {
let rewrittenUrl = url.replace(domain, fullReplaceDomain);
$link.href = rewrittenUrl;
if ($link.textContent.indexOf(domain) !== -1) {
let rewrittenLinkText = $link.textContent.replace(domain, fullReplaceDomain);
$link.textContent = rewrittenLinkText;
}
break;
}
}
}
}
function rewriteLinksToOpenInNewTab(elements) {
elements.forEach(item => {
const links = item.$el.querySelectorAll('a');
links.forEach(link => {
link.target = '_blank';
});
});
}
// https://stackoverflow.com/a/52171480
function hashCode(str) {
let h1 = 0xdeadbeef ^ 0,
h2 = 0x41c6ce57 ^ 0;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
}
function darkenColor(color, amount) {
// Convert the hex color to RGB
let r = parseInt(color.slice(1, 3), 16);
let g = parseInt(color.slice(3, 5), 16);
let b = parseInt(color.slice(5, 7), 16);
// Convert RGB to HSL
(r /= 255), (g /= 255), (b /= 255);
let max = Math.max(r, g, b),
min = Math.min(r, g, b);
let h,
s,
l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
let d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r:
h = (g - b) / d + (g < b ? 6 : 0);
break;
case g:
h = (b - r) / d + 2;
break;
case b:
h = (r - g) / d + 4;
break;
}
h /= 6;
}
// Reduce the lightness by the specified amount (0 to 1)
l = Math.max(0, l - amount);
// Convert HSL back to RGB
let r1, g1, b1;
if (s === 0) {
r1 = g1 = b1 = l;
} else {
function hue2rgb(p, q, t) {
if (t < 0) t += 1;
if (t > 1) t -= 1;
if (t < 1 / 6) return p + (q - p) * 6 * t;
if (t < 1 / 2) return q;
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
return p;
}
let q = l < 0.5 ? l * (1 + s) : l + s - l * s;
let p = 2 * l - q;
r1 = hue2rgb(p, q, h + 1 / 3);
g1 = hue2rgb(p, q, h);
b1 = hue2rgb(p, q, h - 1 / 3);
}
// Convert RGB back to hex
r = Math.round(r1 * 255)
.toString(16)
.padStart(2, "0");
g = Math.round(g1 * 255)
.toString(16)
.padStart(2, "0");
b = Math.round(b1 * 255)
.toString(16)
.padStart(2, "0");
return "#" + r + g + b;
}